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": "implementation from SICP section 2.1\"\n {:author \"Vasily Kolesnikov\"}\n (:refer-clojure :exclude [cons]))\n\n(defn car ", "end": 98, "score": 0.9997861981391907, "start": 81, "tag": "NAME", "value": "Vasily Kolesnikov" } ]
src/sicp/common/pairs.clj
justCxx/SICP
90
(ns sicp.common.pairs "Pairs implementation from SICP section 2.1" {:author "Vasily Kolesnikov"} (:refer-clojure :exclude [cons])) (defn car [[x _]] x) (defn cdr [[_ y]] y) (defn cons [x y] (list x y)) (defn pair? [data] (and (list? data) (= (count data) 2))) (defn inspect [pair] (if-not (pair? pair) pair (let [head (car pair) tail (cdr pair)] (format "(%s, %s)" (inspect head) (inspect tail)))))
6139
(ns sicp.common.pairs "Pairs implementation from SICP section 2.1" {:author "<NAME>"} (:refer-clojure :exclude [cons])) (defn car [[x _]] x) (defn cdr [[_ y]] y) (defn cons [x y] (list x y)) (defn pair? [data] (and (list? data) (= (count data) 2))) (defn inspect [pair] (if-not (pair? pair) pair (let [head (car pair) tail (cdr pair)] (format "(%s, %s)" (inspect head) (inspect tail)))))
true
(ns sicp.common.pairs "Pairs implementation from SICP section 2.1" {:author "PI:NAME:<NAME>END_PI"} (:refer-clojure :exclude [cons])) (defn car [[x _]] x) (defn cdr [[_ y]] y) (defn cons [x y] (list x y)) (defn pair? [data] (and (list? data) (= (count data) 2))) (defn inspect [pair] (if-not (pair? pair) pair (let [head (car pair) tail (cdr pair)] (format "(%s, %s)" (inspect head) (inspect tail)))))
[ { "context": ";; Copyright 2015 Ben Ashford\n;;\n;; Licensed under the Apache License, Version ", "end": 29, "score": 0.999870777130127, "start": 18, "tag": "NAME", "value": "Ben Ashford" } ]
src/redis_async/client.clj
benashford/redis-async
19
;; Copyright 2015 Ben Ashford ;; ;; 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 redis-async.client (:refer-clojure :exclude [time sync keys sort type get set eval send]) (:require [clojure.java.io :as io] [clojure.string :as s] [clojure.core.async :as a] [cheshire.core :as json] [redis-async.core :refer :all] [redis-async.protocol :as protocol]) (:import [jresp Connection] [jresp.pool PubSubConnection])) ;; Internal utilities (defn- is-str? [v] (or (= (class v) jresp.protocol.SimpleStr) (= (class v) jresp.protocol.BulkStr))) (defn- coerce-to-string [val] (cond (or (string? val) (is-str? val)) val (keyword? val) (-> val name s/upper-case) :else (str val))) ;; Useful to enforce conventions (defn read-value [msg] (if-not (nil? msg) (let [value (protocol/->clj msg)] (if (isa? (class value) clojure.lang.ExceptionInfo) (throw value) value)) nil)) (defmacro <! [expr] `(read-value (a/<! ~expr))) (defmacro <!! [expr] `(read-value (a/<!! ~expr))) (defn faf "Fire-and-forget. Warning: if no error-callback is defined, all errors are ignored." ([ch] (faf ch (fn [_] nil))) ([ch error-callback] (a/go-loop [v (a/<! ch)] (when v (if (is-error? v) (error-callback v)) (recur (a/<! ch)))))) (defn check-wait-for-errors [results] (let [errs (->> results (filter #(is-error? %)) (map protocol/->clj))] (when-not (empty? errs) (throw (ex-info (str "Error(s) from Redis:" (pr-str errs)) {:type :redis :msgs errs}))))) (defmacro wait! [expr] `(check-wait-for-errors (a/<! (a/into [] ~expr)))) (defmacro wait!! [expr] `(check-wait-for-errors (a/<!! (a/into [] ~expr)))) ;; Prepare custom commands (defn- command->resp [command args] (->> args (map coerce-to-string) (cons (protocol/cmd->resp command)) protocol/->resp)) ;; Specific commands, the others are auto-generated later (defn monitor [pool] (let [^Connection con (get-connection pool :dedicated) close-c (a/chan) r-r-c (a/chan) ret-c (a/chan)] (.start con (make-stream-response-handler ret-c)) (.write con (protocol/->resp [(protocol/cmd->resp "MONITOR")])) (a/go (let [ok (a/<! ret-c)] (if (= (protocol/->clj ok) "OK") (do (a/go-loop [[v _] (a/alts! [ret-c close-c])] (if-not v (do (a/close! r-r-c) (.write ^Connection con (protocol/->resp [(protocol/cmd->resp "QUIT")]))) (do (a/>! r-r-c v) (recur (a/alts! [ret-c close-c]))))) [r-r-c close-c]) (do (a/close! r-r-c) (close-connection con) nil)))))) ;; Blocking commands (defn- blocking-command [cmd pool & params] (let [con (get-connection pool :borrowed) ret-c (->> params (command->resp cmd) (send con))] (a/go (let [res (a/<! ret-c)] (finish-connection pool con) res)))) (def blpop (partial blocking-command "BLPOP")) (def brpop (partial blocking-command "BRPOP")) (def brpoplpush (partial blocking-command "BRPOPLPUSH")) ;; Pub-sub (def ^:private pub-sub-channel-size 16) (defn subscribe [pool channel] (let [^PubSubConnection con (get-connection pool :pub-sub) ch (a/chan pub-sub-channel-size (drop 1))] (.subscribe con channel (make-stream-response-handler ch)) ch)) (defn unsubscribe [pool channel] (let [^PubSubConnection con (get-connection pool :pub-sub)] (.unsubscribe con channel))) (defn psubscribe [pool pattern] (let [^PubSubConnection con (get-connection pool :pub-sub) ch (a/chan pub-sub-channel-size (drop 1))] (.psubscribe con pattern (make-stream-response-handler ch)) ch)) (defn punsubscribe [pool pattern] (let [^PubSubConnection con (get-connection pool :pub-sub)] (.punsubscribe con pattern))) ;; All other commands (def ^:private overriden-clients #{"monitor" ;; needs a dedicated connection listing all traffic "blpop" "brpop" "brpoplpush" ;; blocking commands "subscribe" "unsubscribe" "psubscribe" "punsubscribe" ;; pub-sub "multi" "exec" "discard" ;; transactions }) (defn- load-commands-meta [] (->> "commands.json" io/resource slurp json/decode)) (defn- emit-client-fn [fn-n summary] (let [cmd (as-> fn-n x (s/split x #"-") (mapv s/upper-case x)) fn-s (symbol fn-n)] `(defn ~fn-s ~summary [& ~'params] (let [redis# (first ~'params) params# (->> (drop 1 ~'params) (map coerce-to-string))] (send-cmd redis# ~cmd params#))))) (defn- generate-commands [commands-meta] (for [[command-name command-data] commands-meta :let [fn-name (-> command-name s/lower-case (s/replace " " "-"))] :when (not (overriden-clients fn-name))] (let [command-data (clojure.walk/keywordize-keys command-data) summary (command-data :summary) args (command-data :arguments)] (emit-client-fn fn-name summary)))) (let [cmd-meta (load-commands-meta) fn-defs (generate-commands cmd-meta)] (doseq [fn-def fn-defs] (clojure.core/eval fn-def))) ;; DELETE ME - temporary functions for ad-hoc benchmarking (defn count-1000 [p] (let [last-c (last (map #(echo p (str %)) (range 1000)))] (a/<!! last-c))) (defn ping-1000 [p] (let [last-c (last (map (fn [_] (ping p)) (range 1000)))] (a/<!! last-c))) (defn count-and-ping [p] (let [cc (a/thread (count-1000 p)) pc (a/thread (ping-1000 p))] (<!! cc) (<!! pc)))
109783
;; 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 redis-async.client (:refer-clojure :exclude [time sync keys sort type get set eval send]) (:require [clojure.java.io :as io] [clojure.string :as s] [clojure.core.async :as a] [cheshire.core :as json] [redis-async.core :refer :all] [redis-async.protocol :as protocol]) (:import [jresp Connection] [jresp.pool PubSubConnection])) ;; Internal utilities (defn- is-str? [v] (or (= (class v) jresp.protocol.SimpleStr) (= (class v) jresp.protocol.BulkStr))) (defn- coerce-to-string [val] (cond (or (string? val) (is-str? val)) val (keyword? val) (-> val name s/upper-case) :else (str val))) ;; Useful to enforce conventions (defn read-value [msg] (if-not (nil? msg) (let [value (protocol/->clj msg)] (if (isa? (class value) clojure.lang.ExceptionInfo) (throw value) value)) nil)) (defmacro <! [expr] `(read-value (a/<! ~expr))) (defmacro <!! [expr] `(read-value (a/<!! ~expr))) (defn faf "Fire-and-forget. Warning: if no error-callback is defined, all errors are ignored." ([ch] (faf ch (fn [_] nil))) ([ch error-callback] (a/go-loop [v (a/<! ch)] (when v (if (is-error? v) (error-callback v)) (recur (a/<! ch)))))) (defn check-wait-for-errors [results] (let [errs (->> results (filter #(is-error? %)) (map protocol/->clj))] (when-not (empty? errs) (throw (ex-info (str "Error(s) from Redis:" (pr-str errs)) {:type :redis :msgs errs}))))) (defmacro wait! [expr] `(check-wait-for-errors (a/<! (a/into [] ~expr)))) (defmacro wait!! [expr] `(check-wait-for-errors (a/<!! (a/into [] ~expr)))) ;; Prepare custom commands (defn- command->resp [command args] (->> args (map coerce-to-string) (cons (protocol/cmd->resp command)) protocol/->resp)) ;; Specific commands, the others are auto-generated later (defn monitor [pool] (let [^Connection con (get-connection pool :dedicated) close-c (a/chan) r-r-c (a/chan) ret-c (a/chan)] (.start con (make-stream-response-handler ret-c)) (.write con (protocol/->resp [(protocol/cmd->resp "MONITOR")])) (a/go (let [ok (a/<! ret-c)] (if (= (protocol/->clj ok) "OK") (do (a/go-loop [[v _] (a/alts! [ret-c close-c])] (if-not v (do (a/close! r-r-c) (.write ^Connection con (protocol/->resp [(protocol/cmd->resp "QUIT")]))) (do (a/>! r-r-c v) (recur (a/alts! [ret-c close-c]))))) [r-r-c close-c]) (do (a/close! r-r-c) (close-connection con) nil)))))) ;; Blocking commands (defn- blocking-command [cmd pool & params] (let [con (get-connection pool :borrowed) ret-c (->> params (command->resp cmd) (send con))] (a/go (let [res (a/<! ret-c)] (finish-connection pool con) res)))) (def blpop (partial blocking-command "BLPOP")) (def brpop (partial blocking-command "BRPOP")) (def brpoplpush (partial blocking-command "BRPOPLPUSH")) ;; Pub-sub (def ^:private pub-sub-channel-size 16) (defn subscribe [pool channel] (let [^PubSubConnection con (get-connection pool :pub-sub) ch (a/chan pub-sub-channel-size (drop 1))] (.subscribe con channel (make-stream-response-handler ch)) ch)) (defn unsubscribe [pool channel] (let [^PubSubConnection con (get-connection pool :pub-sub)] (.unsubscribe con channel))) (defn psubscribe [pool pattern] (let [^PubSubConnection con (get-connection pool :pub-sub) ch (a/chan pub-sub-channel-size (drop 1))] (.psubscribe con pattern (make-stream-response-handler ch)) ch)) (defn punsubscribe [pool pattern] (let [^PubSubConnection con (get-connection pool :pub-sub)] (.punsubscribe con pattern))) ;; All other commands (def ^:private overriden-clients #{"monitor" ;; needs a dedicated connection listing all traffic "blpop" "brpop" "brpoplpush" ;; blocking commands "subscribe" "unsubscribe" "psubscribe" "punsubscribe" ;; pub-sub "multi" "exec" "discard" ;; transactions }) (defn- load-commands-meta [] (->> "commands.json" io/resource slurp json/decode)) (defn- emit-client-fn [fn-n summary] (let [cmd (as-> fn-n x (s/split x #"-") (mapv s/upper-case x)) fn-s (symbol fn-n)] `(defn ~fn-s ~summary [& ~'params] (let [redis# (first ~'params) params# (->> (drop 1 ~'params) (map coerce-to-string))] (send-cmd redis# ~cmd params#))))) (defn- generate-commands [commands-meta] (for [[command-name command-data] commands-meta :let [fn-name (-> command-name s/lower-case (s/replace " " "-"))] :when (not (overriden-clients fn-name))] (let [command-data (clojure.walk/keywordize-keys command-data) summary (command-data :summary) args (command-data :arguments)] (emit-client-fn fn-name summary)))) (let [cmd-meta (load-commands-meta) fn-defs (generate-commands cmd-meta)] (doseq [fn-def fn-defs] (clojure.core/eval fn-def))) ;; DELETE ME - temporary functions for ad-hoc benchmarking (defn count-1000 [p] (let [last-c (last (map #(echo p (str %)) (range 1000)))] (a/<!! last-c))) (defn ping-1000 [p] (let [last-c (last (map (fn [_] (ping p)) (range 1000)))] (a/<!! last-c))) (defn count-and-ping [p] (let [cc (a/thread (count-1000 p)) pc (a/thread (ping-1000 p))] (<!! cc) (<!! pc)))
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 redis-async.client (:refer-clojure :exclude [time sync keys sort type get set eval send]) (:require [clojure.java.io :as io] [clojure.string :as s] [clojure.core.async :as a] [cheshire.core :as json] [redis-async.core :refer :all] [redis-async.protocol :as protocol]) (:import [jresp Connection] [jresp.pool PubSubConnection])) ;; Internal utilities (defn- is-str? [v] (or (= (class v) jresp.protocol.SimpleStr) (= (class v) jresp.protocol.BulkStr))) (defn- coerce-to-string [val] (cond (or (string? val) (is-str? val)) val (keyword? val) (-> val name s/upper-case) :else (str val))) ;; Useful to enforce conventions (defn read-value [msg] (if-not (nil? msg) (let [value (protocol/->clj msg)] (if (isa? (class value) clojure.lang.ExceptionInfo) (throw value) value)) nil)) (defmacro <! [expr] `(read-value (a/<! ~expr))) (defmacro <!! [expr] `(read-value (a/<!! ~expr))) (defn faf "Fire-and-forget. Warning: if no error-callback is defined, all errors are ignored." ([ch] (faf ch (fn [_] nil))) ([ch error-callback] (a/go-loop [v (a/<! ch)] (when v (if (is-error? v) (error-callback v)) (recur (a/<! ch)))))) (defn check-wait-for-errors [results] (let [errs (->> results (filter #(is-error? %)) (map protocol/->clj))] (when-not (empty? errs) (throw (ex-info (str "Error(s) from Redis:" (pr-str errs)) {:type :redis :msgs errs}))))) (defmacro wait! [expr] `(check-wait-for-errors (a/<! (a/into [] ~expr)))) (defmacro wait!! [expr] `(check-wait-for-errors (a/<!! (a/into [] ~expr)))) ;; Prepare custom commands (defn- command->resp [command args] (->> args (map coerce-to-string) (cons (protocol/cmd->resp command)) protocol/->resp)) ;; Specific commands, the others are auto-generated later (defn monitor [pool] (let [^Connection con (get-connection pool :dedicated) close-c (a/chan) r-r-c (a/chan) ret-c (a/chan)] (.start con (make-stream-response-handler ret-c)) (.write con (protocol/->resp [(protocol/cmd->resp "MONITOR")])) (a/go (let [ok (a/<! ret-c)] (if (= (protocol/->clj ok) "OK") (do (a/go-loop [[v _] (a/alts! [ret-c close-c])] (if-not v (do (a/close! r-r-c) (.write ^Connection con (protocol/->resp [(protocol/cmd->resp "QUIT")]))) (do (a/>! r-r-c v) (recur (a/alts! [ret-c close-c]))))) [r-r-c close-c]) (do (a/close! r-r-c) (close-connection con) nil)))))) ;; Blocking commands (defn- blocking-command [cmd pool & params] (let [con (get-connection pool :borrowed) ret-c (->> params (command->resp cmd) (send con))] (a/go (let [res (a/<! ret-c)] (finish-connection pool con) res)))) (def blpop (partial blocking-command "BLPOP")) (def brpop (partial blocking-command "BRPOP")) (def brpoplpush (partial blocking-command "BRPOPLPUSH")) ;; Pub-sub (def ^:private pub-sub-channel-size 16) (defn subscribe [pool channel] (let [^PubSubConnection con (get-connection pool :pub-sub) ch (a/chan pub-sub-channel-size (drop 1))] (.subscribe con channel (make-stream-response-handler ch)) ch)) (defn unsubscribe [pool channel] (let [^PubSubConnection con (get-connection pool :pub-sub)] (.unsubscribe con channel))) (defn psubscribe [pool pattern] (let [^PubSubConnection con (get-connection pool :pub-sub) ch (a/chan pub-sub-channel-size (drop 1))] (.psubscribe con pattern (make-stream-response-handler ch)) ch)) (defn punsubscribe [pool pattern] (let [^PubSubConnection con (get-connection pool :pub-sub)] (.punsubscribe con pattern))) ;; All other commands (def ^:private overriden-clients #{"monitor" ;; needs a dedicated connection listing all traffic "blpop" "brpop" "brpoplpush" ;; blocking commands "subscribe" "unsubscribe" "psubscribe" "punsubscribe" ;; pub-sub "multi" "exec" "discard" ;; transactions }) (defn- load-commands-meta [] (->> "commands.json" io/resource slurp json/decode)) (defn- emit-client-fn [fn-n summary] (let [cmd (as-> fn-n x (s/split x #"-") (mapv s/upper-case x)) fn-s (symbol fn-n)] `(defn ~fn-s ~summary [& ~'params] (let [redis# (first ~'params) params# (->> (drop 1 ~'params) (map coerce-to-string))] (send-cmd redis# ~cmd params#))))) (defn- generate-commands [commands-meta] (for [[command-name command-data] commands-meta :let [fn-name (-> command-name s/lower-case (s/replace " " "-"))] :when (not (overriden-clients fn-name))] (let [command-data (clojure.walk/keywordize-keys command-data) summary (command-data :summary) args (command-data :arguments)] (emit-client-fn fn-name summary)))) (let [cmd-meta (load-commands-meta) fn-defs (generate-commands cmd-meta)] (doseq [fn-def fn-defs] (clojure.core/eval fn-def))) ;; DELETE ME - temporary functions for ad-hoc benchmarking (defn count-1000 [p] (let [last-c (last (map #(echo p (str %)) (range 1000)))] (a/<!! last-c))) (defn ping-1000 [p] (let [last-c (last (map (fn [_] (ping p)) (range 1000)))] (a/<!! last-c))) (defn count-and-ping [p] (let [cc (a/thread (count-1000 p)) pc (a/thread (ping-1000 p))] (<!! cc) (<!! pc)))
[ { "context": "as u]))\n\n\n(def battles-table-state-keys\n [:battle-password :filter-battles :now])\n\n(def battles-tabl", "end": 385, "score": 0.6134061813354492, "start": 385, "tag": "KEY", "value": "" }, { "context": "ttle battle\n :battle-password battle-password\n :client-data clien", "end": 2300, "score": 0.5983644723892212, "start": 2294, "tag": "PASSWORD", "value": "battle" } ]
src/clj/skylobby/fx/battles_table.clj
MasterBel2/skylobby
0
(ns skylobby.fx.battles-table (:require [clojure.string :as string] [cljfx.ext.table-view :as fx.ext.table-view] java-time [skylobby.fx.ext :refer [ext-recreate-on-key-changed ext-table-column-auto-size]] [skylobby.fx.flag-icon :as flag-icon] [spring-lobby.fx.font-icon :as font-icon] [spring-lobby.util :as u])) (def battles-table-state-keys [:battle-password :filter-battles :now]) (def battles-table-keys (concat battles-table-state-keys [:battle :battles :client-data :selected-battle :server-key :users])) (defn battles-table [{:keys [battle battle-password battles client-data filter-battles now selected-battle server-key users]}] (let [filter-lc (when-not (string/blank? filter-battles) (string/lower-case filter-battles)) now (or now (u/curr-millis))] {:fx/type fx.ext.table-view/with-selection-props :props {:selection-mode :single :on-selected-item-changed {:event/type :spring-lobby/select-battle :server-key server-key}} :desc {:fx/type ext-table-column-auto-size :items (->> battles vals (filter :battle-title) (filter (fn [{:keys [battle-map battle-modname battle-title]}] (if filter-lc (or (and battle-map (string/includes? (string/lower-case battle-map) filter-lc)) (and battle-modname (string/includes? (string/lower-case battle-modname) filter-lc)) (string/includes? (string/lower-case battle-title) filter-lc)) true))) (sort-by (juxt (comp count :users) :battle-spectators)) reverse) :desc {:fx/type :table-view :style {:-fx-font-size 15} :column-resize-policy :constrained ; TODO auto resize :row-factory {:fx/cell-type :table-row :describe (fn [{:keys [battle-engine battle-id battle-map battle-modname battle-title battle-version users]}] {:on-mouse-clicked {:event/type :spring-lobby/on-mouse-clicked-battles-row :battle battle :battle-password battle-password :client-data client-data :selected-battle selected-battle :battle-passworded (= "1" (-> battles (get selected-battle) :battle-passworded))} :tooltip {:fx/type :tooltip :style {:-fx-font-size 16} :show-delay [10 :ms] :text (str battle-title "\n\n" "Map: " battle-map "\n" "Game: " battle-modname "\n" "Engine: " battle-engine " " battle-version "\n\n" (->> users keys (sort String/CASE_INSENSITIVE_ORDER) (string/join "\n") (str "Players:\n\n")))} :context-menu {:fx/type :context-menu :items [{:fx/type :menu-item :text "Join Battle" :on-action {:event/type :spring-lobby/join-battle :battle battle :client-data client-data :selected-battle battle-id}}]}})} :columns [ {:fx/type :table-column :text "Game" :pref-width 240 :cell-value-factory :battle-modname :cell-factory {:fx/cell-type :table-cell :describe (fn [battle-modname] {:text (str battle-modname)})}} {:fx/type :table-column :text "Status" :resizable false :pref-width 112 :cell-value-factory identity :cell-factory {:fx/cell-type :table-cell :describe (fn [status] (let [{:keys [game-start-time] :as user-data} (->> status :host-username (get users)) ingame (-> user-data :client-status :ingame)] {:text "" :graphic {:fx/type :h-box :children (concat (if (or (= "1" (:battle-passworded status)) (= "1" (:battle-locked status))) [{:fx/type font-icon/lifecycle :icon-literal "mdi-lock:16:yellow"}] [{:fx/type :pane :style {:-fx-pref-width 16}}]) [(if ingame {:fx/type font-icon/lifecycle :icon-literal "mdi-sword:16:red"} {:fx/type font-icon/lifecycle :icon-literal "mdi-checkbox-blank-circle-outline:16:green"})] (when (and ingame game-start-time) [{:fx/type ext-recreate-on-key-changed :key (str now) :desc {:fx/type :label :text (str " " (u/format-duration (java-time/duration (- now game-start-time) :millis)))}}]))}}))}} {:fx/type :table-column :text "Map" :pref-width 200 :cell-value-factory :battle-map :cell-factory {:fx/cell-type :table-cell :describe (fn [battle-map] {:text (str battle-map)})}} {:fx/type :table-column :text "Play (Spec)" :resizable false :pref-width 100 :cell-value-factory (juxt (comp count :users) #(or (u/to-number (:battle-spectators %)) 0)) :cell-factory {:fx/cell-type :table-cell :describe (fn [[total-user-count spec-count]] {:text (str (if (and (number? total-user-count) (number? spec-count)) (- total-user-count spec-count) total-user-count) " (" spec-count ")")})}} {:fx/type :table-column :text "Battle Name" :pref-width 200 :cell-value-factory :battle-title :cell-factory {:fx/cell-type :table-cell :describe (fn [battle-title] {:text (str battle-title)})}} {:fx/type :table-column :text "Country" :resizable false :pref-width 64 :cell-value-factory #(:country (get users (:host-username %))) :cell-factory {:fx/cell-type :table-cell :describe (fn [country] {:text "" :graphic {:fx/type flag-icon/flag-icon :country-code country}})}} {:fx/type :table-column :text "Host" :pref-width 100 :cell-value-factory :host-username :cell-factory {:fx/cell-type :table-cell :describe (fn [host-username] {:text (str host-username)})}} #_ {:fx/type :table-column :text "Engine" :cell-value-factory #(str (:battle-engine %) " " (:battle-version %)) :cell-factory {:fx/cell-type :table-cell :describe (fn [engine] {:text (str engine)})}}]}}}))
122996
(ns skylobby.fx.battles-table (:require [clojure.string :as string] [cljfx.ext.table-view :as fx.ext.table-view] java-time [skylobby.fx.ext :refer [ext-recreate-on-key-changed ext-table-column-auto-size]] [skylobby.fx.flag-icon :as flag-icon] [spring-lobby.fx.font-icon :as font-icon] [spring-lobby.util :as u])) (def battles-table-state-keys [:battle<KEY>-password :filter-battles :now]) (def battles-table-keys (concat battles-table-state-keys [:battle :battles :client-data :selected-battle :server-key :users])) (defn battles-table [{:keys [battle battle-password battles client-data filter-battles now selected-battle server-key users]}] (let [filter-lc (when-not (string/blank? filter-battles) (string/lower-case filter-battles)) now (or now (u/curr-millis))] {:fx/type fx.ext.table-view/with-selection-props :props {:selection-mode :single :on-selected-item-changed {:event/type :spring-lobby/select-battle :server-key server-key}} :desc {:fx/type ext-table-column-auto-size :items (->> battles vals (filter :battle-title) (filter (fn [{:keys [battle-map battle-modname battle-title]}] (if filter-lc (or (and battle-map (string/includes? (string/lower-case battle-map) filter-lc)) (and battle-modname (string/includes? (string/lower-case battle-modname) filter-lc)) (string/includes? (string/lower-case battle-title) filter-lc)) true))) (sort-by (juxt (comp count :users) :battle-spectators)) reverse) :desc {:fx/type :table-view :style {:-fx-font-size 15} :column-resize-policy :constrained ; TODO auto resize :row-factory {:fx/cell-type :table-row :describe (fn [{:keys [battle-engine battle-id battle-map battle-modname battle-title battle-version users]}] {:on-mouse-clicked {:event/type :spring-lobby/on-mouse-clicked-battles-row :battle battle :battle-password <PASSWORD>-password :client-data client-data :selected-battle selected-battle :battle-passworded (= "1" (-> battles (get selected-battle) :battle-passworded))} :tooltip {:fx/type :tooltip :style {:-fx-font-size 16} :show-delay [10 :ms] :text (str battle-title "\n\n" "Map: " battle-map "\n" "Game: " battle-modname "\n" "Engine: " battle-engine " " battle-version "\n\n" (->> users keys (sort String/CASE_INSENSITIVE_ORDER) (string/join "\n") (str "Players:\n\n")))} :context-menu {:fx/type :context-menu :items [{:fx/type :menu-item :text "Join Battle" :on-action {:event/type :spring-lobby/join-battle :battle battle :client-data client-data :selected-battle battle-id}}]}})} :columns [ {:fx/type :table-column :text "Game" :pref-width 240 :cell-value-factory :battle-modname :cell-factory {:fx/cell-type :table-cell :describe (fn [battle-modname] {:text (str battle-modname)})}} {:fx/type :table-column :text "Status" :resizable false :pref-width 112 :cell-value-factory identity :cell-factory {:fx/cell-type :table-cell :describe (fn [status] (let [{:keys [game-start-time] :as user-data} (->> status :host-username (get users)) ingame (-> user-data :client-status :ingame)] {:text "" :graphic {:fx/type :h-box :children (concat (if (or (= "1" (:battle-passworded status)) (= "1" (:battle-locked status))) [{:fx/type font-icon/lifecycle :icon-literal "mdi-lock:16:yellow"}] [{:fx/type :pane :style {:-fx-pref-width 16}}]) [(if ingame {:fx/type font-icon/lifecycle :icon-literal "mdi-sword:16:red"} {:fx/type font-icon/lifecycle :icon-literal "mdi-checkbox-blank-circle-outline:16:green"})] (when (and ingame game-start-time) [{:fx/type ext-recreate-on-key-changed :key (str now) :desc {:fx/type :label :text (str " " (u/format-duration (java-time/duration (- now game-start-time) :millis)))}}]))}}))}} {:fx/type :table-column :text "Map" :pref-width 200 :cell-value-factory :battle-map :cell-factory {:fx/cell-type :table-cell :describe (fn [battle-map] {:text (str battle-map)})}} {:fx/type :table-column :text "Play (Spec)" :resizable false :pref-width 100 :cell-value-factory (juxt (comp count :users) #(or (u/to-number (:battle-spectators %)) 0)) :cell-factory {:fx/cell-type :table-cell :describe (fn [[total-user-count spec-count]] {:text (str (if (and (number? total-user-count) (number? spec-count)) (- total-user-count spec-count) total-user-count) " (" spec-count ")")})}} {:fx/type :table-column :text "Battle Name" :pref-width 200 :cell-value-factory :battle-title :cell-factory {:fx/cell-type :table-cell :describe (fn [battle-title] {:text (str battle-title)})}} {:fx/type :table-column :text "Country" :resizable false :pref-width 64 :cell-value-factory #(:country (get users (:host-username %))) :cell-factory {:fx/cell-type :table-cell :describe (fn [country] {:text "" :graphic {:fx/type flag-icon/flag-icon :country-code country}})}} {:fx/type :table-column :text "Host" :pref-width 100 :cell-value-factory :host-username :cell-factory {:fx/cell-type :table-cell :describe (fn [host-username] {:text (str host-username)})}} #_ {:fx/type :table-column :text "Engine" :cell-value-factory #(str (:battle-engine %) " " (:battle-version %)) :cell-factory {:fx/cell-type :table-cell :describe (fn [engine] {:text (str engine)})}}]}}}))
true
(ns skylobby.fx.battles-table (:require [clojure.string :as string] [cljfx.ext.table-view :as fx.ext.table-view] java-time [skylobby.fx.ext :refer [ext-recreate-on-key-changed ext-table-column-auto-size]] [skylobby.fx.flag-icon :as flag-icon] [spring-lobby.fx.font-icon :as font-icon] [spring-lobby.util :as u])) (def battles-table-state-keys [:battlePI:KEY:<KEY>END_PI-password :filter-battles :now]) (def battles-table-keys (concat battles-table-state-keys [:battle :battles :client-data :selected-battle :server-key :users])) (defn battles-table [{:keys [battle battle-password battles client-data filter-battles now selected-battle server-key users]}] (let [filter-lc (when-not (string/blank? filter-battles) (string/lower-case filter-battles)) now (or now (u/curr-millis))] {:fx/type fx.ext.table-view/with-selection-props :props {:selection-mode :single :on-selected-item-changed {:event/type :spring-lobby/select-battle :server-key server-key}} :desc {:fx/type ext-table-column-auto-size :items (->> battles vals (filter :battle-title) (filter (fn [{:keys [battle-map battle-modname battle-title]}] (if filter-lc (or (and battle-map (string/includes? (string/lower-case battle-map) filter-lc)) (and battle-modname (string/includes? (string/lower-case battle-modname) filter-lc)) (string/includes? (string/lower-case battle-title) filter-lc)) true))) (sort-by (juxt (comp count :users) :battle-spectators)) reverse) :desc {:fx/type :table-view :style {:-fx-font-size 15} :column-resize-policy :constrained ; TODO auto resize :row-factory {:fx/cell-type :table-row :describe (fn [{:keys [battle-engine battle-id battle-map battle-modname battle-title battle-version users]}] {:on-mouse-clicked {:event/type :spring-lobby/on-mouse-clicked-battles-row :battle battle :battle-password PI:PASSWORD:<PASSWORD>END_PI-password :client-data client-data :selected-battle selected-battle :battle-passworded (= "1" (-> battles (get selected-battle) :battle-passworded))} :tooltip {:fx/type :tooltip :style {:-fx-font-size 16} :show-delay [10 :ms] :text (str battle-title "\n\n" "Map: " battle-map "\n" "Game: " battle-modname "\n" "Engine: " battle-engine " " battle-version "\n\n" (->> users keys (sort String/CASE_INSENSITIVE_ORDER) (string/join "\n") (str "Players:\n\n")))} :context-menu {:fx/type :context-menu :items [{:fx/type :menu-item :text "Join Battle" :on-action {:event/type :spring-lobby/join-battle :battle battle :client-data client-data :selected-battle battle-id}}]}})} :columns [ {:fx/type :table-column :text "Game" :pref-width 240 :cell-value-factory :battle-modname :cell-factory {:fx/cell-type :table-cell :describe (fn [battle-modname] {:text (str battle-modname)})}} {:fx/type :table-column :text "Status" :resizable false :pref-width 112 :cell-value-factory identity :cell-factory {:fx/cell-type :table-cell :describe (fn [status] (let [{:keys [game-start-time] :as user-data} (->> status :host-username (get users)) ingame (-> user-data :client-status :ingame)] {:text "" :graphic {:fx/type :h-box :children (concat (if (or (= "1" (:battle-passworded status)) (= "1" (:battle-locked status))) [{:fx/type font-icon/lifecycle :icon-literal "mdi-lock:16:yellow"}] [{:fx/type :pane :style {:-fx-pref-width 16}}]) [(if ingame {:fx/type font-icon/lifecycle :icon-literal "mdi-sword:16:red"} {:fx/type font-icon/lifecycle :icon-literal "mdi-checkbox-blank-circle-outline:16:green"})] (when (and ingame game-start-time) [{:fx/type ext-recreate-on-key-changed :key (str now) :desc {:fx/type :label :text (str " " (u/format-duration (java-time/duration (- now game-start-time) :millis)))}}]))}}))}} {:fx/type :table-column :text "Map" :pref-width 200 :cell-value-factory :battle-map :cell-factory {:fx/cell-type :table-cell :describe (fn [battle-map] {:text (str battle-map)})}} {:fx/type :table-column :text "Play (Spec)" :resizable false :pref-width 100 :cell-value-factory (juxt (comp count :users) #(or (u/to-number (:battle-spectators %)) 0)) :cell-factory {:fx/cell-type :table-cell :describe (fn [[total-user-count spec-count]] {:text (str (if (and (number? total-user-count) (number? spec-count)) (- total-user-count spec-count) total-user-count) " (" spec-count ")")})}} {:fx/type :table-column :text "Battle Name" :pref-width 200 :cell-value-factory :battle-title :cell-factory {:fx/cell-type :table-cell :describe (fn [battle-title] {:text (str battle-title)})}} {:fx/type :table-column :text "Country" :resizable false :pref-width 64 :cell-value-factory #(:country (get users (:host-username %))) :cell-factory {:fx/cell-type :table-cell :describe (fn [country] {:text "" :graphic {:fx/type flag-icon/flag-icon :country-code country}})}} {:fx/type :table-column :text "Host" :pref-width 100 :cell-value-factory :host-username :cell-factory {:fx/cell-type :table-cell :describe (fn [host-username] {:text (str host-username)})}} #_ {:fx/type :table-column :text "Engine" :cell-value-factory #(str (:battle-engine %) " " (:battle-version %)) :cell-factory {:fx/cell-type :table-cell :describe (fn [engine] {:text (str engine)})}}]}}}))
[ { "context": "g)\n user (core/get-user db \"import@lipas.fi\")\n task-ks (or (not-empty (map", "end": 689, "score": 0.9993603825569153, "start": 674, "tag": "EMAIL", "value": "import@lipas.fi" } ]
webapp/src/clj/lipas/integrator.clj
lipas-liikuntapaikat/lipas
49
(ns lipas.integrator "See also `lipas.worker` namespace." (:require [lipas.backend.config :as config] [lipas.backend.core :as core] [lipas.backend.system :as backend] [lipas.integration.old-lipas.tasks :as integration] [taoensso.timbre :as log] [tea-time.core :as tt])) (defonce tasks (atom {})) (def all-tasks [:new->old ;;:old->new ]) (defn -main "Runs all integrations if no task names are given in args. Else runs only integrations defined in args." [& args] (let [config (select-keys config/default-config [:db :search]) {:keys [db search]} (backend/start-system! config) user (core/get-user db "import@lipas.fi") task-ks (or (not-empty (mapv keyword args)) all-tasks)] (log/info "Starting to run integrations:" task-ks) (tt/with-threadpool (when (some #{:new->old} task-ks) (let [task (tt/every! 60 (fn [] (integration/new->old db)))] (swap! tasks assoc :new->old task))) (when (some #{:old->new} task-ks) (let [task (tt/every! 60 30 (fn [] (integration/old->new db search user)))] (swap! tasks assoc :old->new task))) ;; Keep running forever (while true (Thread/sleep 1000))))) (comment (-main "new->old") (:new->old @tasks) (tt/cancel! (-> @tasks :old->new)) (tt/cancel! (-> @tasks :new->old)) (tt/stop!))
8736
(ns lipas.integrator "See also `lipas.worker` namespace." (:require [lipas.backend.config :as config] [lipas.backend.core :as core] [lipas.backend.system :as backend] [lipas.integration.old-lipas.tasks :as integration] [taoensso.timbre :as log] [tea-time.core :as tt])) (defonce tasks (atom {})) (def all-tasks [:new->old ;;:old->new ]) (defn -main "Runs all integrations if no task names are given in args. Else runs only integrations defined in args." [& args] (let [config (select-keys config/default-config [:db :search]) {:keys [db search]} (backend/start-system! config) user (core/get-user db "<EMAIL>") task-ks (or (not-empty (mapv keyword args)) all-tasks)] (log/info "Starting to run integrations:" task-ks) (tt/with-threadpool (when (some #{:new->old} task-ks) (let [task (tt/every! 60 (fn [] (integration/new->old db)))] (swap! tasks assoc :new->old task))) (when (some #{:old->new} task-ks) (let [task (tt/every! 60 30 (fn [] (integration/old->new db search user)))] (swap! tasks assoc :old->new task))) ;; Keep running forever (while true (Thread/sleep 1000))))) (comment (-main "new->old") (:new->old @tasks) (tt/cancel! (-> @tasks :old->new)) (tt/cancel! (-> @tasks :new->old)) (tt/stop!))
true
(ns lipas.integrator "See also `lipas.worker` namespace." (:require [lipas.backend.config :as config] [lipas.backend.core :as core] [lipas.backend.system :as backend] [lipas.integration.old-lipas.tasks :as integration] [taoensso.timbre :as log] [tea-time.core :as tt])) (defonce tasks (atom {})) (def all-tasks [:new->old ;;:old->new ]) (defn -main "Runs all integrations if no task names are given in args. Else runs only integrations defined in args." [& args] (let [config (select-keys config/default-config [:db :search]) {:keys [db search]} (backend/start-system! config) user (core/get-user db "PI:EMAIL:<EMAIL>END_PI") task-ks (or (not-empty (mapv keyword args)) all-tasks)] (log/info "Starting to run integrations:" task-ks) (tt/with-threadpool (when (some #{:new->old} task-ks) (let [task (tt/every! 60 (fn [] (integration/new->old db)))] (swap! tasks assoc :new->old task))) (when (some #{:old->new} task-ks) (let [task (tt/every! 60 30 (fn [] (integration/old->new db search user)))] (swap! tasks assoc :old->new task))) ;; Keep running forever (while true (Thread/sleep 1000))))) (comment (-main "new->old") (:new->old @tasks) (tt/cancel! (-> @tasks :old->new)) (tt/cancel! (-> @tasks :new->old)) (tt/stop!))
[ { "context": ".iota :refer [given]])\n (:import\n [com.github.benmanes.caffeine.cache Caffeine]\n [java.util.function ", "end": 386, "score": 0.9843387603759766, "start": 378, "tag": "USERNAME", "value": "benmanes" }, { "context": "{:blaze.db/cache-collector nil})\n :key := :blaze.db/cache-collector\n :reason := ::ig/build-faile", "end": 839, "score": 0.5888240337371826, "start": 833, "tag": "KEY", "value": "aze.db" }, { "context": "laze.db/cache-collector {}})\n :key := :blaze.db/cache-collector\n :reason := ::ig/build-faile", "end": 1056, "score": 0.5460032224655151, "start": 1054, "tag": "KEY", "value": "db" } ]
modules/db/test/blaze/db/cache_collector_test.clj
samply/blaze
50
(ns blaze.db.cache-collector-test (:require [blaze.db.cache-collector] [blaze.metrics.core :as metrics] [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]]) (:import [com.github.benmanes.caffeine.cache Caffeine] [java.util.function Function])) (st/instrument) (defn- fixture [f] (st/instrument) (f) (st/unstrument)) (test/use-fixtures :each fixture) (def cache (-> (Caffeine/newBuilder) (.recordStats) (.build))) (def system {:blaze.db/cache-collector {:caches {"name-135224" cache}}}) (deftest init-test (testing "nil config" (given-thrown (ig/init {:blaze.db/cache-collector nil}) :key := :blaze.db/cache-collector :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `map?)) (testing "missing config" (given-thrown (ig/init {:blaze.db/cache-collector {}}) :key := :blaze.db/cache-collector :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `(fn ~'[%] (contains? ~'% :caches)))) (testing "invalid caches" (given-thrown (ig/init {:blaze.db/cache-collector {:caches ::invalid}}) :key := :blaze.db/cache-collector :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `map? [:explain ::s/problems 0 :val] := ::invalid))) (deftest cache-collector-test (with-system [{collector :blaze.db/cache-collector} system] (testing "all zero on fresh cache" (given (metrics/collect collector) [0 :name] := "blaze_db_cache_hits" [0 :type] := :counter [0 :samples 0 :value] := 0.0 [1 :name] := "blaze_db_cache_loads" [1 :type] := :counter [1 :samples 0 :value] := 0.0 [2 :name] := "blaze_db_cache_load_failures" [2 :type] := :counter [2 :samples 0 :value] := 0.0 [3 :name] := "blaze_db_cache_load_seconds" [3 :type] := :counter [3 :samples 0 :value] := 0.0 [4 :name] := "blaze_db_cache_evictions" [4 :samples 0 :value] := 0.0 [4 :type] := :counter)) (testing "one load" (.get cache 1 (reify Function (apply [_ key] key))) (Thread/sleep 100) (given (metrics/collect collector) [0 :name] := "blaze_db_cache_hits" [0 :samples 0 :value] := 0.0 [1 :name] := "blaze_db_cache_loads" [1 :samples 0 :value] := 1.0)) (testing "one loads and one hit" (.get cache 1 (reify Function (apply [_ key] key))) (Thread/sleep 100) (given (metrics/collect collector) [0 :name] := "blaze_db_cache_hits" [0 :samples 0 :value] := 1.0 [1 :name] := "blaze_db_cache_loads" [1 :samples 0 :value] := 1.0))))
55690
(ns blaze.db.cache-collector-test (:require [blaze.db.cache-collector] [blaze.metrics.core :as metrics] [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]]) (:import [com.github.benmanes.caffeine.cache Caffeine] [java.util.function Function])) (st/instrument) (defn- fixture [f] (st/instrument) (f) (st/unstrument)) (test/use-fixtures :each fixture) (def cache (-> (Caffeine/newBuilder) (.recordStats) (.build))) (def system {:blaze.db/cache-collector {:caches {"name-135224" cache}}}) (deftest init-test (testing "nil config" (given-thrown (ig/init {:blaze.db/cache-collector nil}) :key := :bl<KEY>/cache-collector :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `map?)) (testing "missing config" (given-thrown (ig/init {:blaze.db/cache-collector {}}) :key := :blaze.<KEY>/cache-collector :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `(fn ~'[%] (contains? ~'% :caches)))) (testing "invalid caches" (given-thrown (ig/init {:blaze.db/cache-collector {:caches ::invalid}}) :key := :blaze.db/cache-collector :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `map? [:explain ::s/problems 0 :val] := ::invalid))) (deftest cache-collector-test (with-system [{collector :blaze.db/cache-collector} system] (testing "all zero on fresh cache" (given (metrics/collect collector) [0 :name] := "blaze_db_cache_hits" [0 :type] := :counter [0 :samples 0 :value] := 0.0 [1 :name] := "blaze_db_cache_loads" [1 :type] := :counter [1 :samples 0 :value] := 0.0 [2 :name] := "blaze_db_cache_load_failures" [2 :type] := :counter [2 :samples 0 :value] := 0.0 [3 :name] := "blaze_db_cache_load_seconds" [3 :type] := :counter [3 :samples 0 :value] := 0.0 [4 :name] := "blaze_db_cache_evictions" [4 :samples 0 :value] := 0.0 [4 :type] := :counter)) (testing "one load" (.get cache 1 (reify Function (apply [_ key] key))) (Thread/sleep 100) (given (metrics/collect collector) [0 :name] := "blaze_db_cache_hits" [0 :samples 0 :value] := 0.0 [1 :name] := "blaze_db_cache_loads" [1 :samples 0 :value] := 1.0)) (testing "one loads and one hit" (.get cache 1 (reify Function (apply [_ key] key))) (Thread/sleep 100) (given (metrics/collect collector) [0 :name] := "blaze_db_cache_hits" [0 :samples 0 :value] := 1.0 [1 :name] := "blaze_db_cache_loads" [1 :samples 0 :value] := 1.0))))
true
(ns blaze.db.cache-collector-test (:require [blaze.db.cache-collector] [blaze.metrics.core :as metrics] [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]]) (:import [com.github.benmanes.caffeine.cache Caffeine] [java.util.function Function])) (st/instrument) (defn- fixture [f] (st/instrument) (f) (st/unstrument)) (test/use-fixtures :each fixture) (def cache (-> (Caffeine/newBuilder) (.recordStats) (.build))) (def system {:blaze.db/cache-collector {:caches {"name-135224" cache}}}) (deftest init-test (testing "nil config" (given-thrown (ig/init {:blaze.db/cache-collector nil}) :key := :blPI:KEY:<KEY>END_PI/cache-collector :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `map?)) (testing "missing config" (given-thrown (ig/init {:blaze.db/cache-collector {}}) :key := :blaze.PI:KEY:<KEY>END_PI/cache-collector :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `(fn ~'[%] (contains? ~'% :caches)))) (testing "invalid caches" (given-thrown (ig/init {:blaze.db/cache-collector {:caches ::invalid}}) :key := :blaze.db/cache-collector :reason := ::ig/build-failed-spec [:explain ::s/problems 0 :pred] := `map? [:explain ::s/problems 0 :val] := ::invalid))) (deftest cache-collector-test (with-system [{collector :blaze.db/cache-collector} system] (testing "all zero on fresh cache" (given (metrics/collect collector) [0 :name] := "blaze_db_cache_hits" [0 :type] := :counter [0 :samples 0 :value] := 0.0 [1 :name] := "blaze_db_cache_loads" [1 :type] := :counter [1 :samples 0 :value] := 0.0 [2 :name] := "blaze_db_cache_load_failures" [2 :type] := :counter [2 :samples 0 :value] := 0.0 [3 :name] := "blaze_db_cache_load_seconds" [3 :type] := :counter [3 :samples 0 :value] := 0.0 [4 :name] := "blaze_db_cache_evictions" [4 :samples 0 :value] := 0.0 [4 :type] := :counter)) (testing "one load" (.get cache 1 (reify Function (apply [_ key] key))) (Thread/sleep 100) (given (metrics/collect collector) [0 :name] := "blaze_db_cache_hits" [0 :samples 0 :value] := 0.0 [1 :name] := "blaze_db_cache_loads" [1 :samples 0 :value] := 1.0)) (testing "one loads and one hit" (.get cache 1 (reify Function (apply [_ key] key))) (Thread/sleep 100) (given (metrics/collect collector) [0 :name] := "blaze_db_cache_hits" [0 :samples 0 :value] := 1.0 [1 :name] := "blaze_db_cache_loads" [1 :samples 0 :value] := 1.0))))
[ { "context": ";; Copyright (c) 2020-2021 Saidone\n\n(ns clj-ssh-keygen.core\n (:import [java.securit", "end": 34, "score": 0.9974021911621094, "start": 27, "tag": "NAME", "value": "Saidone" } ]
src/clj_ssh_keygen/core.clj
saidone75/clj-ssh-keygen
17
;; Copyright (c) 2020-2021 Saidone (ns clj-ssh-keygen.core (:import [java.security SecureRandom]) (:gen-class)) (require '[clj-ssh-keygen.utils :as utils] '[clj-ssh-keygen.oid :as oid]) ;; (minimum) key length (def key-length 2048) ;; public exponent (def e (biginteger 65537)) ;; generate a prime number of (key length / 2) bits (defn- genprime [kl] (loop [n (BigInteger/probablePrime (quot kl 2) (SecureRandom.))] (if-not (= 1 (.mod n e)) n (recur (BigInteger/probablePrime (quot kl 2) (SecureRandom.)))))) ;; key as a quintuplet (e, p, q, n, d) ;; see https://www.di-mgt.com.au/rsa_alg.html#keygen for algorithm insights (defn generate-key [& [kl]] (let [kl (if (< (or kl key-length) key-length) key-length (or kl key-length)) ;; public exponent e e ;; secret prime 1 p (genprime kl) ;; secret prime 2 ;; making sure that p x q (modulus) is exactly "kl" bit long q (loop [q (genprime kl)] (if (= kl (.bitLength (.multiply p q))) q (recur (genprime (if (odd? kl) (inc kl) kl))))) ;; modulus n (.multiply p q) ;; private exponent d (.modInverse e (.multiply (.subtract p (biginteger 1)) (.subtract q (biginteger 1))))] {:e e :p p :q q :n n :d d})) ;; ASN.1 encoding stuff ;; ;; the bare minimum for working with PKCS #1 keys ;; http://luca.ntop.org/Teaching/Appunti/asn1.html ;; ;; compute length of ASN.1 content (defn- asn1-length [c] (let [c (count c)] (cond (< c 128) [(unchecked-byte c)] (and (> c 127) (< c 256)) (concat [(unchecked-byte 0x81)] [(unchecked-byte c)]) :else (concat [(unchecked-byte 0x82)] (.toByteArray (biginteger c)))))) ;; ASN.1 generic encoding (defn- asn1-enc [tag content] (byte-array (concat [(unchecked-byte tag)] (asn1-length content) content))) ;; ASN.1 encoding for INTEGER (defn- asn1-int [n] (asn1-enc 0x02 (.toByteArray n))) ;; ASN.1 encoding for SEQUENCE (defn- asn1-seq [n] (asn1-enc 0x30 n)) ;; ASN.1 encoding for OBJECT (defn- asn1-obj [n] (asn1-enc 0x06 n)) ;; ASN.1 encoding for NULL (defn- asn1-null [] (concat [(unchecked-byte 0x05) (unchecked-byte 0x00)])) ;; ASN.1 encoding for BIT STRING (defn- asn1-bit-str [n] (asn1-enc 0x03 (concat ;; unused bits for padding [(unchecked-byte 0x00)] n))) ;; ASN.1 encoding for OCTET STRING (defn- asn1-oct-str [n] (asn1-enc 0x04 n)) ;; PKCS-1 OID value for RSA encryption ;; see https://www.alvestrand.no/objectid/1.2.840.113549.1.1.1.html (def pkcs1-oid "1.2.840.113549.1.1.1") ;; RSA public key (only modulus (p x q) and public exponent) ;; https://tools.ietf.org/html/rfc3447#appendix-A.1.1 (defn public-key [key] (asn1-seq (concat (asn1-seq (concat (asn1-obj (map #(unchecked-byte %) (oid/oid-string-to-bytes pkcs1-oid))) (asn1-null))) (asn1-bit-str (asn1-seq (concat ;; modulus (asn1-int (:n key)) ;; public exponent (asn1-int (:e key)))))))) ;; OpenSSH public key (id_rsa.pub) more familiar for ssh users ;; ;; compute item length as required from OpenSSH ;; 4 bytes format (defn- openssh-length [c] (loop [c (.toByteArray (biginteger (count c)))] (if (= 4 (count c)) c (recur (concat [(unchecked-byte 0x00)] c))))) ;; concat item length with item represented as byte array (defn- openssh-item [i] (let [ba (cond (string? i) (.getBytes i) :else (.toByteArray i))] (concat (openssh-length ba) ba))) ;; same informations of pem in a sligthly different format (defn openssh-public-key [key] (byte-array (concat ;; string prefix (openssh-item "ssh-rsa") ;; public exponent (openssh-item (:e key)) ;; modulus (openssh-item (:n key))))) ;; RSA private key ;; https://tools.ietf.org/html/rfc3447#appendix-A.1.2 (defn private-key [key] (asn1-seq (concat (asn1-int (biginteger 0)) (asn1-seq (concat (asn1-obj (map #(unchecked-byte %) (oid/oid-string-to-bytes pkcs1-oid))) (asn1-null))) (asn1-oct-str (asn1-seq (concat ;; version (asn1-int (biginteger 0)) ;; modulus (asn1-int (:n key)) ;; public exponent (asn1-int (:e key)) ;; private exponent (asn1-int (:d key)) ;; prime1 (asn1-int (:p key)) ;; prime2 (asn1-int (:q key)) ;; exponent1 (asn1-int (.mod (:d key) (.subtract (:p key) (biginteger 1)))) ;; exponent2 (asn1-int (.mod (:d key) (.subtract (:q key) (biginteger 1)))) ;; coefficient (asn1-int (.modInverse (:q key) (:p key))))))))) (defn write-private-key! [k f] (utils/write-private-key! (private-key k) f)) (defn write-public-key! [k f] (utils/write-public-key! (public-key k) f)) (defn write-openssh-public-key! [k f] (utils/write-openssh-public-key! (openssh-public-key k) f))
25056
;; Copyright (c) 2020-2021 <NAME> (ns clj-ssh-keygen.core (:import [java.security SecureRandom]) (:gen-class)) (require '[clj-ssh-keygen.utils :as utils] '[clj-ssh-keygen.oid :as oid]) ;; (minimum) key length (def key-length 2048) ;; public exponent (def e (biginteger 65537)) ;; generate a prime number of (key length / 2) bits (defn- genprime [kl] (loop [n (BigInteger/probablePrime (quot kl 2) (SecureRandom.))] (if-not (= 1 (.mod n e)) n (recur (BigInteger/probablePrime (quot kl 2) (SecureRandom.)))))) ;; key as a quintuplet (e, p, q, n, d) ;; see https://www.di-mgt.com.au/rsa_alg.html#keygen for algorithm insights (defn generate-key [& [kl]] (let [kl (if (< (or kl key-length) key-length) key-length (or kl key-length)) ;; public exponent e e ;; secret prime 1 p (genprime kl) ;; secret prime 2 ;; making sure that p x q (modulus) is exactly "kl" bit long q (loop [q (genprime kl)] (if (= kl (.bitLength (.multiply p q))) q (recur (genprime (if (odd? kl) (inc kl) kl))))) ;; modulus n (.multiply p q) ;; private exponent d (.modInverse e (.multiply (.subtract p (biginteger 1)) (.subtract q (biginteger 1))))] {:e e :p p :q q :n n :d d})) ;; ASN.1 encoding stuff ;; ;; the bare minimum for working with PKCS #1 keys ;; http://luca.ntop.org/Teaching/Appunti/asn1.html ;; ;; compute length of ASN.1 content (defn- asn1-length [c] (let [c (count c)] (cond (< c 128) [(unchecked-byte c)] (and (> c 127) (< c 256)) (concat [(unchecked-byte 0x81)] [(unchecked-byte c)]) :else (concat [(unchecked-byte 0x82)] (.toByteArray (biginteger c)))))) ;; ASN.1 generic encoding (defn- asn1-enc [tag content] (byte-array (concat [(unchecked-byte tag)] (asn1-length content) content))) ;; ASN.1 encoding for INTEGER (defn- asn1-int [n] (asn1-enc 0x02 (.toByteArray n))) ;; ASN.1 encoding for SEQUENCE (defn- asn1-seq [n] (asn1-enc 0x30 n)) ;; ASN.1 encoding for OBJECT (defn- asn1-obj [n] (asn1-enc 0x06 n)) ;; ASN.1 encoding for NULL (defn- asn1-null [] (concat [(unchecked-byte 0x05) (unchecked-byte 0x00)])) ;; ASN.1 encoding for BIT STRING (defn- asn1-bit-str [n] (asn1-enc 0x03 (concat ;; unused bits for padding [(unchecked-byte 0x00)] n))) ;; ASN.1 encoding for OCTET STRING (defn- asn1-oct-str [n] (asn1-enc 0x04 n)) ;; PKCS-1 OID value for RSA encryption ;; see https://www.alvestrand.no/objectid/1.2.840.113549.1.1.1.html (def pkcs1-oid "1.2.840.113549.1.1.1") ;; RSA public key (only modulus (p x q) and public exponent) ;; https://tools.ietf.org/html/rfc3447#appendix-A.1.1 (defn public-key [key] (asn1-seq (concat (asn1-seq (concat (asn1-obj (map #(unchecked-byte %) (oid/oid-string-to-bytes pkcs1-oid))) (asn1-null))) (asn1-bit-str (asn1-seq (concat ;; modulus (asn1-int (:n key)) ;; public exponent (asn1-int (:e key)))))))) ;; OpenSSH public key (id_rsa.pub) more familiar for ssh users ;; ;; compute item length as required from OpenSSH ;; 4 bytes format (defn- openssh-length [c] (loop [c (.toByteArray (biginteger (count c)))] (if (= 4 (count c)) c (recur (concat [(unchecked-byte 0x00)] c))))) ;; concat item length with item represented as byte array (defn- openssh-item [i] (let [ba (cond (string? i) (.getBytes i) :else (.toByteArray i))] (concat (openssh-length ba) ba))) ;; same informations of pem in a sligthly different format (defn openssh-public-key [key] (byte-array (concat ;; string prefix (openssh-item "ssh-rsa") ;; public exponent (openssh-item (:e key)) ;; modulus (openssh-item (:n key))))) ;; RSA private key ;; https://tools.ietf.org/html/rfc3447#appendix-A.1.2 (defn private-key [key] (asn1-seq (concat (asn1-int (biginteger 0)) (asn1-seq (concat (asn1-obj (map #(unchecked-byte %) (oid/oid-string-to-bytes pkcs1-oid))) (asn1-null))) (asn1-oct-str (asn1-seq (concat ;; version (asn1-int (biginteger 0)) ;; modulus (asn1-int (:n key)) ;; public exponent (asn1-int (:e key)) ;; private exponent (asn1-int (:d key)) ;; prime1 (asn1-int (:p key)) ;; prime2 (asn1-int (:q key)) ;; exponent1 (asn1-int (.mod (:d key) (.subtract (:p key) (biginteger 1)))) ;; exponent2 (asn1-int (.mod (:d key) (.subtract (:q key) (biginteger 1)))) ;; coefficient (asn1-int (.modInverse (:q key) (:p key))))))))) (defn write-private-key! [k f] (utils/write-private-key! (private-key k) f)) (defn write-public-key! [k f] (utils/write-public-key! (public-key k) f)) (defn write-openssh-public-key! [k f] (utils/write-openssh-public-key! (openssh-public-key k) f))
true
;; Copyright (c) 2020-2021 PI:NAME:<NAME>END_PI (ns clj-ssh-keygen.core (:import [java.security SecureRandom]) (:gen-class)) (require '[clj-ssh-keygen.utils :as utils] '[clj-ssh-keygen.oid :as oid]) ;; (minimum) key length (def key-length 2048) ;; public exponent (def e (biginteger 65537)) ;; generate a prime number of (key length / 2) bits (defn- genprime [kl] (loop [n (BigInteger/probablePrime (quot kl 2) (SecureRandom.))] (if-not (= 1 (.mod n e)) n (recur (BigInteger/probablePrime (quot kl 2) (SecureRandom.)))))) ;; key as a quintuplet (e, p, q, n, d) ;; see https://www.di-mgt.com.au/rsa_alg.html#keygen for algorithm insights (defn generate-key [& [kl]] (let [kl (if (< (or kl key-length) key-length) key-length (or kl key-length)) ;; public exponent e e ;; secret prime 1 p (genprime kl) ;; secret prime 2 ;; making sure that p x q (modulus) is exactly "kl" bit long q (loop [q (genprime kl)] (if (= kl (.bitLength (.multiply p q))) q (recur (genprime (if (odd? kl) (inc kl) kl))))) ;; modulus n (.multiply p q) ;; private exponent d (.modInverse e (.multiply (.subtract p (biginteger 1)) (.subtract q (biginteger 1))))] {:e e :p p :q q :n n :d d})) ;; ASN.1 encoding stuff ;; ;; the bare minimum for working with PKCS #1 keys ;; http://luca.ntop.org/Teaching/Appunti/asn1.html ;; ;; compute length of ASN.1 content (defn- asn1-length [c] (let [c (count c)] (cond (< c 128) [(unchecked-byte c)] (and (> c 127) (< c 256)) (concat [(unchecked-byte 0x81)] [(unchecked-byte c)]) :else (concat [(unchecked-byte 0x82)] (.toByteArray (biginteger c)))))) ;; ASN.1 generic encoding (defn- asn1-enc [tag content] (byte-array (concat [(unchecked-byte tag)] (asn1-length content) content))) ;; ASN.1 encoding for INTEGER (defn- asn1-int [n] (asn1-enc 0x02 (.toByteArray n))) ;; ASN.1 encoding for SEQUENCE (defn- asn1-seq [n] (asn1-enc 0x30 n)) ;; ASN.1 encoding for OBJECT (defn- asn1-obj [n] (asn1-enc 0x06 n)) ;; ASN.1 encoding for NULL (defn- asn1-null [] (concat [(unchecked-byte 0x05) (unchecked-byte 0x00)])) ;; ASN.1 encoding for BIT STRING (defn- asn1-bit-str [n] (asn1-enc 0x03 (concat ;; unused bits for padding [(unchecked-byte 0x00)] n))) ;; ASN.1 encoding for OCTET STRING (defn- asn1-oct-str [n] (asn1-enc 0x04 n)) ;; PKCS-1 OID value for RSA encryption ;; see https://www.alvestrand.no/objectid/1.2.840.113549.1.1.1.html (def pkcs1-oid "1.2.840.113549.1.1.1") ;; RSA public key (only modulus (p x q) and public exponent) ;; https://tools.ietf.org/html/rfc3447#appendix-A.1.1 (defn public-key [key] (asn1-seq (concat (asn1-seq (concat (asn1-obj (map #(unchecked-byte %) (oid/oid-string-to-bytes pkcs1-oid))) (asn1-null))) (asn1-bit-str (asn1-seq (concat ;; modulus (asn1-int (:n key)) ;; public exponent (asn1-int (:e key)))))))) ;; OpenSSH public key (id_rsa.pub) more familiar for ssh users ;; ;; compute item length as required from OpenSSH ;; 4 bytes format (defn- openssh-length [c] (loop [c (.toByteArray (biginteger (count c)))] (if (= 4 (count c)) c (recur (concat [(unchecked-byte 0x00)] c))))) ;; concat item length with item represented as byte array (defn- openssh-item [i] (let [ba (cond (string? i) (.getBytes i) :else (.toByteArray i))] (concat (openssh-length ba) ba))) ;; same informations of pem in a sligthly different format (defn openssh-public-key [key] (byte-array (concat ;; string prefix (openssh-item "ssh-rsa") ;; public exponent (openssh-item (:e key)) ;; modulus (openssh-item (:n key))))) ;; RSA private key ;; https://tools.ietf.org/html/rfc3447#appendix-A.1.2 (defn private-key [key] (asn1-seq (concat (asn1-int (biginteger 0)) (asn1-seq (concat (asn1-obj (map #(unchecked-byte %) (oid/oid-string-to-bytes pkcs1-oid))) (asn1-null))) (asn1-oct-str (asn1-seq (concat ;; version (asn1-int (biginteger 0)) ;; modulus (asn1-int (:n key)) ;; public exponent (asn1-int (:e key)) ;; private exponent (asn1-int (:d key)) ;; prime1 (asn1-int (:p key)) ;; prime2 (asn1-int (:q key)) ;; exponent1 (asn1-int (.mod (:d key) (.subtract (:p key) (biginteger 1)))) ;; exponent2 (asn1-int (.mod (:d key) (.subtract (:q key) (biginteger 1)))) ;; coefficient (asn1-int (.modInverse (:q key) (:p key))))))))) (defn write-private-key! [k f] (utils/write-private-key! (private-key k) f)) (defn write-public-key! [k f] (utils/write-public-key! (public-key k) f)) (defn write-openssh-public-key! [k f] (utils/write-openssh-public-key! (openssh-public-key k) f))
[ { "context": ";; Copyright © 2015-2019 Esko Luontola\n;; This software is released under the Apache Lic", "end": 38, "score": 0.9998800158500671, "start": 25, "tag": "NAME", "value": "Esko Luontola" } ]
src/territory_bro/congregation.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.congregation (:require [clojure.string :as str] [clojure.tools.logging :as log] [territory-bro.commands :as commands] [territory-bro.config :as config] [territory-bro.db :as db] [territory-bro.event-store :as event-store] [territory-bro.events :as events] [territory-bro.permissions :as permissions] [territory-bro.user :as user]) (:import (java.util UUID) (territory_bro ValidationException))) ;;; Read model (defmulti ^:private update-congregation (fn [_congregation event] (:event/type event))) (defmethod update-congregation :default [congregation _event] congregation) (defmethod update-congregation :congregation.event/congregation-created [congregation event] (-> congregation (assoc :congregation/id (:congregation/id event)) (assoc :congregation/name (:congregation/name event)) (assoc :congregation/schema-name (:congregation/schema-name event)))) (defmethod update-congregation :congregation.event/congregation-renamed [congregation event] (-> congregation (assoc :congregation/name (:congregation/name event)))) (defmethod update-congregation :congregation.event/permission-granted [congregation event] (-> congregation (update-in [:congregation/user-permissions (:user/id event)] (fnil conj #{}) (:permission/id event)))) (defmethod update-congregation :congregation.event/permission-revoked [congregation event] (-> congregation ;; TODO: remove user when no more permissions remain (update-in [:congregation/user-permissions (:user/id event)] disj (:permission/id event)))) (defmulti ^:private update-permissions (fn [_state event] (:event/type event))) (defmethod update-permissions :default [state _event] state) (defmethod update-permissions :congregation.event/permission-granted [state event] (-> state (permissions/grant (:user/id event) [(:permission/id event) (:congregation/id event)]))) (defmethod update-permissions :congregation.event/permission-revoked [state event] (-> state (permissions/revoke (:user/id event) [(:permission/id event) (:congregation/id event)]))) (defn congregations-view [state event] (-> state (update-in [::congregations (:congregation/id event)] update-congregation event) (update-permissions event))) (defn get-unrestricted-congregations [state] (vals (::congregations state))) (defn get-unrestricted-congregation [state cong-id] (get (::congregations state) cong-id)) (defn- apply-user-permissions [cong user-id] (let [permissions (get-in cong [:congregation/user-permissions user-id])] (when (contains? permissions :view-congregation) cong))) (defn get-my-congregations [state user-id] ;; TODO: avoid the linear search (->> (get-unrestricted-congregations state) (map #(apply-user-permissions % user-id)) (remove nil?))) (defn get-my-congregation [state cong-id user-id] (-> (get-unrestricted-congregation state cong-id) (apply-user-permissions user-id))) (defn use-schema [conn state cong-id] ; TODO: create a better helper? (let [cong (get-unrestricted-congregation state cong-id) schema (:congregation/schema-name cong)] (db/use-tenant-schema conn schema))) (defn create-congregation! [conn name] (let [id (UUID/randomUUID) master-schema (:database-schema config/env) tenant-schema (str master-schema "_" (str/replace (str id) "-" ""))] (assert (not (contains? (set (db/get-schemas conn)) tenant-schema)) {:schema-name tenant-schema}) (event-store/save! conn id 0 [(assoc (events/defaults) :event/type :congregation.event/congregation-created :congregation/id id :congregation/name name :congregation/schema-name tenant-schema)]) (-> (db/tenant-schema tenant-schema master-schema) (.migrate)) (log/info "Congregation created:" id) id)) ;;;; Write model (defmulti ^:private write-model (fn [_congregation event] (:event/type event))) (defmethod write-model :default [congregation _event] congregation) (defmethod write-model :congregation.event/congregation-created [congregation event] (-> congregation (assoc :congregation/id (:congregation/id event)) (assoc :congregation/name (:congregation/name event)))) (defmethod write-model :congregation.event/congregation-renamed [congregation event] (-> congregation (assoc :congregation/name (:congregation/name event)))) (defmethod write-model :congregation.event/permission-granted [congregation event] (if (= :view-congregation (:permission/id event)) (update congregation ::users (fnil conj #{}) (:user/id event)) congregation)) (defmethod write-model :congregation.event/permission-revoked [congregation event] (if (= :view-congregation (:permission/id event)) (update congregation ::users disj (:user/id event)) congregation)) (defmulti ^:private command-handler (fn [command _congregation _injections] (:command/type command))) (defmethod command-handler :congregation.command/add-user [command congregation {:keys [user-exists? check-permit]}] (let [cong-id (:congregation/id congregation) user-id (:user/id command)] (check-permit [:configure-congregation cong-id]) (when-not (user-exists? user-id) (throw (ValidationException. [[:no-such-user user-id]]))) (when-not (contains? (::users congregation) user-id) [{:event/type :congregation.event/permission-granted :event/version 1 :congregation/id cong-id :user/id user-id :permission/id :view-congregation}]))) (defmethod command-handler :congregation.command/rename-congregation [command congregation {:keys [check-permit]}] (check-permit [:configure-congregation (:congregation/id congregation)]) (when-not (= (:congregation/name congregation) (:congregation/name command)) [{:event/type :congregation.event/congregation-renamed :event/version 1 :congregation/id (:congregation/id congregation) :congregation/name (:congregation/name command)}])) (defn- enrich-event [event command] (-> event (assoc :event/time (:command/time command)) (assoc :event/user (:command/user command)))) (defn handle-command [command events injections] (let [command (commands/validate-command command) congregation (reduce write-model nil events) injections (merge {:check-permit (fn [permit] (permissions/check (:state injections) (:command/user command) permit)) :user-exists? (fn [user-id] (db/with-db [conn {:read-only? true}] (some? (user/get-by-id conn user-id))))} injections)] (->> (command-handler command congregation injections) (map #(enrich-event % command))))) (defn command! [conn state command] (let [stream-id (:congregation/id command) old-events (event-store/read-stream conn stream-id) new-events (handle-command command old-events {:state state})] (event-store/save! conn stream-id (count old-events) new-events))) ;;;; User access (defn get-users [state cong-id] (let [cong (get-unrestricted-congregation state cong-id)] (->> (:congregation/user-permissions cong) ;; TODO: remove old users already in the projection (filter (fn [[_user-id permissions]] (not (empty? permissions)))) (keys)))) (defn grant! [conn cong-id user-id permission] ;; TODO: refactor to event sourcing commands (event-store/save! conn cong-id nil [(assoc (events/defaults) :event/type :congregation.event/permission-granted :congregation/id cong-id :user/id user-id :permission/id permission)]) nil) (defn revoke! [conn cong-id user-id permission] ;; TODO: refactor to event sourcing commands (event-store/save! conn cong-id nil [(assoc (events/defaults) :event/type :congregation.event/permission-revoked :congregation/id cong-id :user/id user-id :permission/id permission)]) nil)
106091
;; 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.congregation (:require [clojure.string :as str] [clojure.tools.logging :as log] [territory-bro.commands :as commands] [territory-bro.config :as config] [territory-bro.db :as db] [territory-bro.event-store :as event-store] [territory-bro.events :as events] [territory-bro.permissions :as permissions] [territory-bro.user :as user]) (:import (java.util UUID) (territory_bro ValidationException))) ;;; Read model (defmulti ^:private update-congregation (fn [_congregation event] (:event/type event))) (defmethod update-congregation :default [congregation _event] congregation) (defmethod update-congregation :congregation.event/congregation-created [congregation event] (-> congregation (assoc :congregation/id (:congregation/id event)) (assoc :congregation/name (:congregation/name event)) (assoc :congregation/schema-name (:congregation/schema-name event)))) (defmethod update-congregation :congregation.event/congregation-renamed [congregation event] (-> congregation (assoc :congregation/name (:congregation/name event)))) (defmethod update-congregation :congregation.event/permission-granted [congregation event] (-> congregation (update-in [:congregation/user-permissions (:user/id event)] (fnil conj #{}) (:permission/id event)))) (defmethod update-congregation :congregation.event/permission-revoked [congregation event] (-> congregation ;; TODO: remove user when no more permissions remain (update-in [:congregation/user-permissions (:user/id event)] disj (:permission/id event)))) (defmulti ^:private update-permissions (fn [_state event] (:event/type event))) (defmethod update-permissions :default [state _event] state) (defmethod update-permissions :congregation.event/permission-granted [state event] (-> state (permissions/grant (:user/id event) [(:permission/id event) (:congregation/id event)]))) (defmethod update-permissions :congregation.event/permission-revoked [state event] (-> state (permissions/revoke (:user/id event) [(:permission/id event) (:congregation/id event)]))) (defn congregations-view [state event] (-> state (update-in [::congregations (:congregation/id event)] update-congregation event) (update-permissions event))) (defn get-unrestricted-congregations [state] (vals (::congregations state))) (defn get-unrestricted-congregation [state cong-id] (get (::congregations state) cong-id)) (defn- apply-user-permissions [cong user-id] (let [permissions (get-in cong [:congregation/user-permissions user-id])] (when (contains? permissions :view-congregation) cong))) (defn get-my-congregations [state user-id] ;; TODO: avoid the linear search (->> (get-unrestricted-congregations state) (map #(apply-user-permissions % user-id)) (remove nil?))) (defn get-my-congregation [state cong-id user-id] (-> (get-unrestricted-congregation state cong-id) (apply-user-permissions user-id))) (defn use-schema [conn state cong-id] ; TODO: create a better helper? (let [cong (get-unrestricted-congregation state cong-id) schema (:congregation/schema-name cong)] (db/use-tenant-schema conn schema))) (defn create-congregation! [conn name] (let [id (UUID/randomUUID) master-schema (:database-schema config/env) tenant-schema (str master-schema "_" (str/replace (str id) "-" ""))] (assert (not (contains? (set (db/get-schemas conn)) tenant-schema)) {:schema-name tenant-schema}) (event-store/save! conn id 0 [(assoc (events/defaults) :event/type :congregation.event/congregation-created :congregation/id id :congregation/name name :congregation/schema-name tenant-schema)]) (-> (db/tenant-schema tenant-schema master-schema) (.migrate)) (log/info "Congregation created:" id) id)) ;;;; Write model (defmulti ^:private write-model (fn [_congregation event] (:event/type event))) (defmethod write-model :default [congregation _event] congregation) (defmethod write-model :congregation.event/congregation-created [congregation event] (-> congregation (assoc :congregation/id (:congregation/id event)) (assoc :congregation/name (:congregation/name event)))) (defmethod write-model :congregation.event/congregation-renamed [congregation event] (-> congregation (assoc :congregation/name (:congregation/name event)))) (defmethod write-model :congregation.event/permission-granted [congregation event] (if (= :view-congregation (:permission/id event)) (update congregation ::users (fnil conj #{}) (:user/id event)) congregation)) (defmethod write-model :congregation.event/permission-revoked [congregation event] (if (= :view-congregation (:permission/id event)) (update congregation ::users disj (:user/id event)) congregation)) (defmulti ^:private command-handler (fn [command _congregation _injections] (:command/type command))) (defmethod command-handler :congregation.command/add-user [command congregation {:keys [user-exists? check-permit]}] (let [cong-id (:congregation/id congregation) user-id (:user/id command)] (check-permit [:configure-congregation cong-id]) (when-not (user-exists? user-id) (throw (ValidationException. [[:no-such-user user-id]]))) (when-not (contains? (::users congregation) user-id) [{:event/type :congregation.event/permission-granted :event/version 1 :congregation/id cong-id :user/id user-id :permission/id :view-congregation}]))) (defmethod command-handler :congregation.command/rename-congregation [command congregation {:keys [check-permit]}] (check-permit [:configure-congregation (:congregation/id congregation)]) (when-not (= (:congregation/name congregation) (:congregation/name command)) [{:event/type :congregation.event/congregation-renamed :event/version 1 :congregation/id (:congregation/id congregation) :congregation/name (:congregation/name command)}])) (defn- enrich-event [event command] (-> event (assoc :event/time (:command/time command)) (assoc :event/user (:command/user command)))) (defn handle-command [command events injections] (let [command (commands/validate-command command) congregation (reduce write-model nil events) injections (merge {:check-permit (fn [permit] (permissions/check (:state injections) (:command/user command) permit)) :user-exists? (fn [user-id] (db/with-db [conn {:read-only? true}] (some? (user/get-by-id conn user-id))))} injections)] (->> (command-handler command congregation injections) (map #(enrich-event % command))))) (defn command! [conn state command] (let [stream-id (:congregation/id command) old-events (event-store/read-stream conn stream-id) new-events (handle-command command old-events {:state state})] (event-store/save! conn stream-id (count old-events) new-events))) ;;;; User access (defn get-users [state cong-id] (let [cong (get-unrestricted-congregation state cong-id)] (->> (:congregation/user-permissions cong) ;; TODO: remove old users already in the projection (filter (fn [[_user-id permissions]] (not (empty? permissions)))) (keys)))) (defn grant! [conn cong-id user-id permission] ;; TODO: refactor to event sourcing commands (event-store/save! conn cong-id nil [(assoc (events/defaults) :event/type :congregation.event/permission-granted :congregation/id cong-id :user/id user-id :permission/id permission)]) nil) (defn revoke! [conn cong-id user-id permission] ;; TODO: refactor to event sourcing commands (event-store/save! conn cong-id nil [(assoc (events/defaults) :event/type :congregation.event/permission-revoked :congregation/id cong-id :user/id user-id :permission/id permission)]) nil)
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.congregation (:require [clojure.string :as str] [clojure.tools.logging :as log] [territory-bro.commands :as commands] [territory-bro.config :as config] [territory-bro.db :as db] [territory-bro.event-store :as event-store] [territory-bro.events :as events] [territory-bro.permissions :as permissions] [territory-bro.user :as user]) (:import (java.util UUID) (territory_bro ValidationException))) ;;; Read model (defmulti ^:private update-congregation (fn [_congregation event] (:event/type event))) (defmethod update-congregation :default [congregation _event] congregation) (defmethod update-congregation :congregation.event/congregation-created [congregation event] (-> congregation (assoc :congregation/id (:congregation/id event)) (assoc :congregation/name (:congregation/name event)) (assoc :congregation/schema-name (:congregation/schema-name event)))) (defmethod update-congregation :congregation.event/congregation-renamed [congregation event] (-> congregation (assoc :congregation/name (:congregation/name event)))) (defmethod update-congregation :congregation.event/permission-granted [congregation event] (-> congregation (update-in [:congregation/user-permissions (:user/id event)] (fnil conj #{}) (:permission/id event)))) (defmethod update-congregation :congregation.event/permission-revoked [congregation event] (-> congregation ;; TODO: remove user when no more permissions remain (update-in [:congregation/user-permissions (:user/id event)] disj (:permission/id event)))) (defmulti ^:private update-permissions (fn [_state event] (:event/type event))) (defmethod update-permissions :default [state _event] state) (defmethod update-permissions :congregation.event/permission-granted [state event] (-> state (permissions/grant (:user/id event) [(:permission/id event) (:congregation/id event)]))) (defmethod update-permissions :congregation.event/permission-revoked [state event] (-> state (permissions/revoke (:user/id event) [(:permission/id event) (:congregation/id event)]))) (defn congregations-view [state event] (-> state (update-in [::congregations (:congregation/id event)] update-congregation event) (update-permissions event))) (defn get-unrestricted-congregations [state] (vals (::congregations state))) (defn get-unrestricted-congregation [state cong-id] (get (::congregations state) cong-id)) (defn- apply-user-permissions [cong user-id] (let [permissions (get-in cong [:congregation/user-permissions user-id])] (when (contains? permissions :view-congregation) cong))) (defn get-my-congregations [state user-id] ;; TODO: avoid the linear search (->> (get-unrestricted-congregations state) (map #(apply-user-permissions % user-id)) (remove nil?))) (defn get-my-congregation [state cong-id user-id] (-> (get-unrestricted-congregation state cong-id) (apply-user-permissions user-id))) (defn use-schema [conn state cong-id] ; TODO: create a better helper? (let [cong (get-unrestricted-congregation state cong-id) schema (:congregation/schema-name cong)] (db/use-tenant-schema conn schema))) (defn create-congregation! [conn name] (let [id (UUID/randomUUID) master-schema (:database-schema config/env) tenant-schema (str master-schema "_" (str/replace (str id) "-" ""))] (assert (not (contains? (set (db/get-schemas conn)) tenant-schema)) {:schema-name tenant-schema}) (event-store/save! conn id 0 [(assoc (events/defaults) :event/type :congregation.event/congregation-created :congregation/id id :congregation/name name :congregation/schema-name tenant-schema)]) (-> (db/tenant-schema tenant-schema master-schema) (.migrate)) (log/info "Congregation created:" id) id)) ;;;; Write model (defmulti ^:private write-model (fn [_congregation event] (:event/type event))) (defmethod write-model :default [congregation _event] congregation) (defmethod write-model :congregation.event/congregation-created [congregation event] (-> congregation (assoc :congregation/id (:congregation/id event)) (assoc :congregation/name (:congregation/name event)))) (defmethod write-model :congregation.event/congregation-renamed [congregation event] (-> congregation (assoc :congregation/name (:congregation/name event)))) (defmethod write-model :congregation.event/permission-granted [congregation event] (if (= :view-congregation (:permission/id event)) (update congregation ::users (fnil conj #{}) (:user/id event)) congregation)) (defmethod write-model :congregation.event/permission-revoked [congregation event] (if (= :view-congregation (:permission/id event)) (update congregation ::users disj (:user/id event)) congregation)) (defmulti ^:private command-handler (fn [command _congregation _injections] (:command/type command))) (defmethod command-handler :congregation.command/add-user [command congregation {:keys [user-exists? check-permit]}] (let [cong-id (:congregation/id congregation) user-id (:user/id command)] (check-permit [:configure-congregation cong-id]) (when-not (user-exists? user-id) (throw (ValidationException. [[:no-such-user user-id]]))) (when-not (contains? (::users congregation) user-id) [{:event/type :congregation.event/permission-granted :event/version 1 :congregation/id cong-id :user/id user-id :permission/id :view-congregation}]))) (defmethod command-handler :congregation.command/rename-congregation [command congregation {:keys [check-permit]}] (check-permit [:configure-congregation (:congregation/id congregation)]) (when-not (= (:congregation/name congregation) (:congregation/name command)) [{:event/type :congregation.event/congregation-renamed :event/version 1 :congregation/id (:congregation/id congregation) :congregation/name (:congregation/name command)}])) (defn- enrich-event [event command] (-> event (assoc :event/time (:command/time command)) (assoc :event/user (:command/user command)))) (defn handle-command [command events injections] (let [command (commands/validate-command command) congregation (reduce write-model nil events) injections (merge {:check-permit (fn [permit] (permissions/check (:state injections) (:command/user command) permit)) :user-exists? (fn [user-id] (db/with-db [conn {:read-only? true}] (some? (user/get-by-id conn user-id))))} injections)] (->> (command-handler command congregation injections) (map #(enrich-event % command))))) (defn command! [conn state command] (let [stream-id (:congregation/id command) old-events (event-store/read-stream conn stream-id) new-events (handle-command command old-events {:state state})] (event-store/save! conn stream-id (count old-events) new-events))) ;;;; User access (defn get-users [state cong-id] (let [cong (get-unrestricted-congregation state cong-id)] (->> (:congregation/user-permissions cong) ;; TODO: remove old users already in the projection (filter (fn [[_user-id permissions]] (not (empty? permissions)))) (keys)))) (defn grant! [conn cong-id user-id permission] ;; TODO: refactor to event sourcing commands (event-store/save! conn cong-id nil [(assoc (events/defaults) :event/type :congregation.event/permission-granted :congregation/id cong-id :user/id user-id :permission/id permission)]) nil) (defn revoke! [conn cong-id user-id permission] ;; TODO: refactor to event sourcing commands (event-store/save! conn cong-id nil [(assoc (events/defaults) :event/type :congregation.event/permission-revoked :congregation/id cong-id :user/id user-id :permission/id permission)]) nil)
[ { "context": "-resources/client-keystore\")\n(def client-ks-pass \"keykey\")\n(def secure-request {:request-method :get :uri ", "end": 502, "score": 0.7132206559181213, "start": 496, "tag": "PASSWORD", "value": "keykey" } ]
test/clj_http/test/conn_mgr_test.clj
Deraen/clj-http
1,240
(ns clj-http.test.conn-mgr-test (:require [clj-http.conn-mgr :as conn-mgr] [clj-http.core :as core] [clj-http.test.core-test :refer [run-server]] [clojure.test :refer :all] [ring.adapter.jetty :as ring]) (:import java.security.KeyStore [javax.net.ssl KeyManagerFactory TrustManagerFactory] org.apache.http.impl.conn.BasicHttpClientConnectionManager)) (def client-ks "test-resources/client-keystore") (def client-ks-pass "keykey") (def secure-request {:request-method :get :uri "/" :server-port 18084 :scheme :https :keystore client-ks :keystore-pass client-ks-pass :trust-store client-ks :trust-store-pass client-ks-pass :server-name "localhost" :insecure? true}) (defn secure-handler [req] (if (nil? (:ssl-client-cert req)) {:status 403} {:status 200})) (deftest load-keystore (let [ks (conn-mgr/get-keystore "test-resources/keystore" nil "keykey")] (is (instance? KeyStore ks)) (is (> (.size ks) 0)))) (deftest use-existing-keystore (let [ks (conn-mgr/get-keystore "test-resources/keystore" nil "keykey") ks (conn-mgr/get-keystore ks)] (is (instance? KeyStore ks)) (is (> (.size ks) 0)))) (deftest load-keystore-with-nil-pass (let [ks (conn-mgr/get-keystore "test-resources/keystore" nil nil)] (is (instance? KeyStore ks)))) (def array-of-trust-manager (let [ks (conn-mgr/get-keystore "test-resources/keystore" nil "keykey") tmf (doto (TrustManagerFactory/getInstance (TrustManagerFactory/getDefaultAlgorithm)) (.init ks))] (.getTrustManagers tmf))) (def array-of-key-manager (let [ks (conn-mgr/get-keystore "test-resources/keystore" nil "keykey") tmf (doto (KeyManagerFactory/getInstance (KeyManagerFactory/getDefaultAlgorithm)) (.init ks (.toCharArray "keykey")))] (.getKeyManagers tmf))) (deftest ^:integration ssl-client-cert-get (let [server (ring/run-jetty secure-handler {:port 18083 :ssl-port 18084 :ssl? true :join? false :keystore "test-resources/keystore" :key-password "keykey" :client-auth :want})] (try (let [resp (core/request {:request-method :get :uri "/get" :server-port 18084 :scheme :https :insecure? true :server-name "localhost"})] (is (= 403 (:status resp)))) (let [resp (core/request secure-request)] (is (= 200 (:status resp)))) (finally (.stop server))))) (deftest ^:integration ssl-client-cert-get-async (let [server (ring/run-jetty secure-handler {:port 18083 :ssl-port 18084 :ssl? true :join? false :keystore "test-resources/keystore" :key-password "keykey" :client-auth :want})] (try (let [resp (promise) exception (promise) _ (core/request {:request-method :get :uri "/get" :server-port 18084 :scheme :https :insecure? true :server-name "localhost" :async? true} resp exception)] (is (= 403 (:status (deref resp 1000 {:status :timeout}))))) (let [resp (promise) exception (promise) _ (core/request (assoc secure-request :async? true) resp exception)] (is (= 200 (:status (deref resp 1000 {:status :timeout}))))) (testing "with reusable connection pool" (let [pool (conn-mgr/make-reusable-async-conn-manager {:timeout 10000 :keystore client-ks :keystore-pass client-ks-pass :trust-store client-ks :trust-store-pass client-ks-pass :insecure? true})] (try (let [resp (promise) exception (promise) _ (core/request {:request-method :get :uri "/get" :server-port 18084 :scheme :https :server-name "localhost" :connection-manager pool :async? true} resp exception)] (is (= 200 (:status (deref resp 1000 {:status :timeout})))) (is (:body @resp)) (is (not (realized? exception)))) (finally (conn-mgr/shutdown-manager pool))))) (finally (.stop server))))) (deftest ^:integration t-closed-conn-mgr-for-as-stream (run-server) (let [shutdown? (atom false) cm (proxy [BasicHttpClientConnectionManager] [] (shutdown [] (reset! shutdown? true)))] (try (core/request {:request-method :get :uri "/timeout" :server-port 18080 :scheme :http :server-name "localhost" ;; timeouts forces an exception being thrown :socket-timeout 1 :connection-timeout 1 :connection-manager cm :as :stream}) (is false "request should have thrown an exception") (catch Exception e)) (is @shutdown? "Connection manager has been shutdown"))) (deftest ^:integration t-closed-conn-mgr-for-empty-body (run-server) (let [shutdown? (atom false) cm (proxy [BasicHttpClientConnectionManager] [] (shutdown [] (reset! shutdown? true))) response (core/request {:request-method :get :uri "/unmodified-resource" :server-port 18080 :scheme :http :server-name "localhost" :connection-manager cm})] (is (nil? (:body response)) "response shouldn't have body") (is (= 304 (:status response))) (is @shutdown? "connection manager should be shutdown"))) (deftest t-reusable-conn-mgrs (let [regular (conn-mgr/make-regular-conn-manager {}) regular-reusable (conn-mgr/make-reusable-conn-manager {}) async (conn-mgr/make-regular-async-conn-manager {}) async-reusable (conn-mgr/make-reusable-async-conn-manager {}) async-reuseable (conn-mgr/make-reuseable-async-conn-manager {})] (is (false? (conn-mgr/reusable? regular))) (is (true? (conn-mgr/reusable? regular-reusable))) (is (false? (conn-mgr/reusable? async))) (is (true? (conn-mgr/reusable? async-reusable))) (is (true? (conn-mgr/reusable? async-reuseable)))))
7435
(ns clj-http.test.conn-mgr-test (:require [clj-http.conn-mgr :as conn-mgr] [clj-http.core :as core] [clj-http.test.core-test :refer [run-server]] [clojure.test :refer :all] [ring.adapter.jetty :as ring]) (:import java.security.KeyStore [javax.net.ssl KeyManagerFactory TrustManagerFactory] org.apache.http.impl.conn.BasicHttpClientConnectionManager)) (def client-ks "test-resources/client-keystore") (def client-ks-pass "<PASSWORD>") (def secure-request {:request-method :get :uri "/" :server-port 18084 :scheme :https :keystore client-ks :keystore-pass client-ks-pass :trust-store client-ks :trust-store-pass client-ks-pass :server-name "localhost" :insecure? true}) (defn secure-handler [req] (if (nil? (:ssl-client-cert req)) {:status 403} {:status 200})) (deftest load-keystore (let [ks (conn-mgr/get-keystore "test-resources/keystore" nil "keykey")] (is (instance? KeyStore ks)) (is (> (.size ks) 0)))) (deftest use-existing-keystore (let [ks (conn-mgr/get-keystore "test-resources/keystore" nil "keykey") ks (conn-mgr/get-keystore ks)] (is (instance? KeyStore ks)) (is (> (.size ks) 0)))) (deftest load-keystore-with-nil-pass (let [ks (conn-mgr/get-keystore "test-resources/keystore" nil nil)] (is (instance? KeyStore ks)))) (def array-of-trust-manager (let [ks (conn-mgr/get-keystore "test-resources/keystore" nil "keykey") tmf (doto (TrustManagerFactory/getInstance (TrustManagerFactory/getDefaultAlgorithm)) (.init ks))] (.getTrustManagers tmf))) (def array-of-key-manager (let [ks (conn-mgr/get-keystore "test-resources/keystore" nil "keykey") tmf (doto (KeyManagerFactory/getInstance (KeyManagerFactory/getDefaultAlgorithm)) (.init ks (.toCharArray "keykey")))] (.getKeyManagers tmf))) (deftest ^:integration ssl-client-cert-get (let [server (ring/run-jetty secure-handler {:port 18083 :ssl-port 18084 :ssl? true :join? false :keystore "test-resources/keystore" :key-password "keykey" :client-auth :want})] (try (let [resp (core/request {:request-method :get :uri "/get" :server-port 18084 :scheme :https :insecure? true :server-name "localhost"})] (is (= 403 (:status resp)))) (let [resp (core/request secure-request)] (is (= 200 (:status resp)))) (finally (.stop server))))) (deftest ^:integration ssl-client-cert-get-async (let [server (ring/run-jetty secure-handler {:port 18083 :ssl-port 18084 :ssl? true :join? false :keystore "test-resources/keystore" :key-password "keykey" :client-auth :want})] (try (let [resp (promise) exception (promise) _ (core/request {:request-method :get :uri "/get" :server-port 18084 :scheme :https :insecure? true :server-name "localhost" :async? true} resp exception)] (is (= 403 (:status (deref resp 1000 {:status :timeout}))))) (let [resp (promise) exception (promise) _ (core/request (assoc secure-request :async? true) resp exception)] (is (= 200 (:status (deref resp 1000 {:status :timeout}))))) (testing "with reusable connection pool" (let [pool (conn-mgr/make-reusable-async-conn-manager {:timeout 10000 :keystore client-ks :keystore-pass client-ks-pass :trust-store client-ks :trust-store-pass client-ks-pass :insecure? true})] (try (let [resp (promise) exception (promise) _ (core/request {:request-method :get :uri "/get" :server-port 18084 :scheme :https :server-name "localhost" :connection-manager pool :async? true} resp exception)] (is (= 200 (:status (deref resp 1000 {:status :timeout})))) (is (:body @resp)) (is (not (realized? exception)))) (finally (conn-mgr/shutdown-manager pool))))) (finally (.stop server))))) (deftest ^:integration t-closed-conn-mgr-for-as-stream (run-server) (let [shutdown? (atom false) cm (proxy [BasicHttpClientConnectionManager] [] (shutdown [] (reset! shutdown? true)))] (try (core/request {:request-method :get :uri "/timeout" :server-port 18080 :scheme :http :server-name "localhost" ;; timeouts forces an exception being thrown :socket-timeout 1 :connection-timeout 1 :connection-manager cm :as :stream}) (is false "request should have thrown an exception") (catch Exception e)) (is @shutdown? "Connection manager has been shutdown"))) (deftest ^:integration t-closed-conn-mgr-for-empty-body (run-server) (let [shutdown? (atom false) cm (proxy [BasicHttpClientConnectionManager] [] (shutdown [] (reset! shutdown? true))) response (core/request {:request-method :get :uri "/unmodified-resource" :server-port 18080 :scheme :http :server-name "localhost" :connection-manager cm})] (is (nil? (:body response)) "response shouldn't have body") (is (= 304 (:status response))) (is @shutdown? "connection manager should be shutdown"))) (deftest t-reusable-conn-mgrs (let [regular (conn-mgr/make-regular-conn-manager {}) regular-reusable (conn-mgr/make-reusable-conn-manager {}) async (conn-mgr/make-regular-async-conn-manager {}) async-reusable (conn-mgr/make-reusable-async-conn-manager {}) async-reuseable (conn-mgr/make-reuseable-async-conn-manager {})] (is (false? (conn-mgr/reusable? regular))) (is (true? (conn-mgr/reusable? regular-reusable))) (is (false? (conn-mgr/reusable? async))) (is (true? (conn-mgr/reusable? async-reusable))) (is (true? (conn-mgr/reusable? async-reuseable)))))
true
(ns clj-http.test.conn-mgr-test (:require [clj-http.conn-mgr :as conn-mgr] [clj-http.core :as core] [clj-http.test.core-test :refer [run-server]] [clojure.test :refer :all] [ring.adapter.jetty :as ring]) (:import java.security.KeyStore [javax.net.ssl KeyManagerFactory TrustManagerFactory] org.apache.http.impl.conn.BasicHttpClientConnectionManager)) (def client-ks "test-resources/client-keystore") (def client-ks-pass "PI:PASSWORD:<PASSWORD>END_PI") (def secure-request {:request-method :get :uri "/" :server-port 18084 :scheme :https :keystore client-ks :keystore-pass client-ks-pass :trust-store client-ks :trust-store-pass client-ks-pass :server-name "localhost" :insecure? true}) (defn secure-handler [req] (if (nil? (:ssl-client-cert req)) {:status 403} {:status 200})) (deftest load-keystore (let [ks (conn-mgr/get-keystore "test-resources/keystore" nil "keykey")] (is (instance? KeyStore ks)) (is (> (.size ks) 0)))) (deftest use-existing-keystore (let [ks (conn-mgr/get-keystore "test-resources/keystore" nil "keykey") ks (conn-mgr/get-keystore ks)] (is (instance? KeyStore ks)) (is (> (.size ks) 0)))) (deftest load-keystore-with-nil-pass (let [ks (conn-mgr/get-keystore "test-resources/keystore" nil nil)] (is (instance? KeyStore ks)))) (def array-of-trust-manager (let [ks (conn-mgr/get-keystore "test-resources/keystore" nil "keykey") tmf (doto (TrustManagerFactory/getInstance (TrustManagerFactory/getDefaultAlgorithm)) (.init ks))] (.getTrustManagers tmf))) (def array-of-key-manager (let [ks (conn-mgr/get-keystore "test-resources/keystore" nil "keykey") tmf (doto (KeyManagerFactory/getInstance (KeyManagerFactory/getDefaultAlgorithm)) (.init ks (.toCharArray "keykey")))] (.getKeyManagers tmf))) (deftest ^:integration ssl-client-cert-get (let [server (ring/run-jetty secure-handler {:port 18083 :ssl-port 18084 :ssl? true :join? false :keystore "test-resources/keystore" :key-password "keykey" :client-auth :want})] (try (let [resp (core/request {:request-method :get :uri "/get" :server-port 18084 :scheme :https :insecure? true :server-name "localhost"})] (is (= 403 (:status resp)))) (let [resp (core/request secure-request)] (is (= 200 (:status resp)))) (finally (.stop server))))) (deftest ^:integration ssl-client-cert-get-async (let [server (ring/run-jetty secure-handler {:port 18083 :ssl-port 18084 :ssl? true :join? false :keystore "test-resources/keystore" :key-password "keykey" :client-auth :want})] (try (let [resp (promise) exception (promise) _ (core/request {:request-method :get :uri "/get" :server-port 18084 :scheme :https :insecure? true :server-name "localhost" :async? true} resp exception)] (is (= 403 (:status (deref resp 1000 {:status :timeout}))))) (let [resp (promise) exception (promise) _ (core/request (assoc secure-request :async? true) resp exception)] (is (= 200 (:status (deref resp 1000 {:status :timeout}))))) (testing "with reusable connection pool" (let [pool (conn-mgr/make-reusable-async-conn-manager {:timeout 10000 :keystore client-ks :keystore-pass client-ks-pass :trust-store client-ks :trust-store-pass client-ks-pass :insecure? true})] (try (let [resp (promise) exception (promise) _ (core/request {:request-method :get :uri "/get" :server-port 18084 :scheme :https :server-name "localhost" :connection-manager pool :async? true} resp exception)] (is (= 200 (:status (deref resp 1000 {:status :timeout})))) (is (:body @resp)) (is (not (realized? exception)))) (finally (conn-mgr/shutdown-manager pool))))) (finally (.stop server))))) (deftest ^:integration t-closed-conn-mgr-for-as-stream (run-server) (let [shutdown? (atom false) cm (proxy [BasicHttpClientConnectionManager] [] (shutdown [] (reset! shutdown? true)))] (try (core/request {:request-method :get :uri "/timeout" :server-port 18080 :scheme :http :server-name "localhost" ;; timeouts forces an exception being thrown :socket-timeout 1 :connection-timeout 1 :connection-manager cm :as :stream}) (is false "request should have thrown an exception") (catch Exception e)) (is @shutdown? "Connection manager has been shutdown"))) (deftest ^:integration t-closed-conn-mgr-for-empty-body (run-server) (let [shutdown? (atom false) cm (proxy [BasicHttpClientConnectionManager] [] (shutdown [] (reset! shutdown? true))) response (core/request {:request-method :get :uri "/unmodified-resource" :server-port 18080 :scheme :http :server-name "localhost" :connection-manager cm})] (is (nil? (:body response)) "response shouldn't have body") (is (= 304 (:status response))) (is @shutdown? "connection manager should be shutdown"))) (deftest t-reusable-conn-mgrs (let [regular (conn-mgr/make-regular-conn-manager {}) regular-reusable (conn-mgr/make-reusable-conn-manager {}) async (conn-mgr/make-regular-async-conn-manager {}) async-reusable (conn-mgr/make-reusable-async-conn-manager {}) async-reuseable (conn-mgr/make-reuseable-async-conn-manager {})] (is (false? (conn-mgr/reusable? regular))) (is (true? (conn-mgr/reusable? regular-reusable))) (is (false? (conn-mgr/reusable? async))) (is (true? (conn-mgr/reusable? async-reusable))) (is (true? (conn-mgr/reusable? async-reuseable)))))
[ { "context": "entiment words).\n; Copied from https://github.com/redmonk/bluebird\n;\n; This file and the papers can all be ", "end": 1858, "score": 0.9986345171928406, "start": 1851, "tag": "USERNAME", "value": "redmonk" }, { "context": ", please cite one of the following two papers:\n;\n; Minqing Hu and Bing Liu. \"Mining and Summarizing Customer Re", "end": 2067, "score": 0.999727189540863, "start": 2057, "tag": "NAME", "value": "Minqing Hu" }, { "context": "ne of the following two papers:\n;\n; Minqing Hu and Bing Liu. \"Mining and Summarizing Customer Reviews.\"\n; Pro", "end": 2080, "score": 0.9997903108596802, "start": 2072, "tag": "NAME", "value": "Bing Liu" }, { "context": "4), Aug 22-25, 2004, Seattle,\n; Washington, USA,\n; Bing Liu, Minqing Hu and Junsheng Cheng. \"Opinion Observer", "end": 2290, "score": 0.9996277093887329, "start": 2282, "tag": "NAME", "value": "Bing Liu" }, { "context": "-25, 2004, Seattle,\n; Washington, USA,\n; Bing Liu, Minqing Hu and Junsheng Cheng. \"Opinion Observer: Analyzing\n", "end": 2302, "score": 0.9997646808624268, "start": 2292, "tag": "NAME", "value": "Minqing Hu" }, { "context": "tle,\n; Washington, USA,\n; Bing Liu, Minqing Hu and Junsheng Cheng. \"Opinion Observer: Analyzing\n; and Comparing Opi", "end": 2321, "score": 0.9998133778572083, "start": 2307, "tag": "NAME", "value": "Junsheng Cheng" }, { "context": "ve or negative opinion.\n; See the paper below:\n;\n; Bing Liu. \"Sentiment Analysis and Subjectivity.\" An chapte", "end": 2688, "score": 0.9988099336624146, "start": 2680, "tag": "NAME", "value": "Bing Liu" }, { "context": "l Language Processing, Second Edition,\n; (editors: N. Indurkhya and F. J. Damerau), 2010.\n;\n; 2. You will notice ", "end": 2826, "score": 0.9998621344566345, "start": 2814, "tag": "NAME", "value": "N. Indurkhya" }, { "context": "sing, Second Edition,\n; (editors: N. Indurkhya and F. J. Damerau), 2010.\n;\n; 2. You will notice many misspelled wo", "end": 2844, "score": 0.9998720288276672, "start": 2831, "tag": "NAME", "value": "F. J. Damerau" }, { "context": "ombardment\"\n \"bombastic\"\n \"bondage\"\n \"bonkers\"\n \"bore\"\n \"bored\"\n \"boredom\"\n \"bores\"", "end": 9155, "score": 0.5777161121368408, "start": 9151, "tag": "NAME", "value": "kers" }, { "context": "bothersome\"\n \"bowdlerize\"\n \"boycott\"\n \"braggart\"\n \"bragger\"\n \"brainless\"\n \"brainwash\"\n ", "end": 9350, "score": 0.6133207678794861, "start": 9344, "tag": "NAME", "value": "aggart" }, { "context": "\n \"mashed\"\n \"massacre\"\n \"massacres\"\n \"matte\"\n \"mawkish\"\n \"mawkishly\"\n \"mawkishness", "end": 46896, "score": 0.6264897584915161, "start": 46893, "tag": "NAME", "value": "mat" } ]
src/plugh/util/sent_analysis.clj
projectplugh/plugh
2
(ns plugh.util.sent-analysis (:require [clojure.string :as str] [clojure.core.async :as async])) (declare pos neg) (defn calc-sentiment [line] (let [splits (str/split (str/lower-case (str/replace (str/replace line #"\p{Punct}" " ") #"\p{Cntrl}" " ")) #" +")] {:pos (count (filter pos splits)) :neg (* -1 (count (filter neg splits)))} )) (defn xform [the-func the-chan] (async/map< (fn [z] (do ;; (println "Xform from " z " to " (the-func z)) (the-func z))) the-chan)) (defn xfilter [the-func the-chan] (async/filter< (fn [z] (do ;; (println "Filtering incoming value " z) (the-func z))) the-chan)) (defn flow [the-func seed the-chan] (let [cur-val (atom seed)] (async/map< (fn [mv] (let [new-val (the-func @cur-val mv)] (reset! cur-val new-val) new-val)) the-chan))) (defn arrow-update-func [the-var func-map] (reduce (fn [cur v] (let [[the-key the-func] v] (assoc cur the-key (the-func (the-key cur))))) the-var (into [] func-map))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; Opinion Lexicon: Negative & Positive ; ; This file contains a list of NEGATIVE and POSITIVE opinion words (or sentiment words). ; Copied from https://github.com/redmonk/bluebird ; ; This file and the papers can all be downloaded from ; http://www.cs.uic.edu/~liub/FBS/sentiment-analysis.html ; ; If you use this list, please cite one of the following two papers: ; ; Minqing Hu and Bing Liu. "Mining and Summarizing Customer Reviews." ; Proceedings of the ACM SIGKDD International Conference on Knowledge ; Discovery and Data Mining (KDD-2004), Aug 22-25, 2004, Seattle, ; Washington, USA, ; Bing Liu, Minqing Hu and Junsheng Cheng. "Opinion Observer: Analyzing ; and Comparing Opinions on the Web." Proceedings of the 14th ; International World Wide Web conference (WWW-2005), May 10-14, ; 2005, Chiba, Japan. ; ; Notes: ; 1. The appearance of an opinion word in a sentence does not necessarily ; mean that the sentence expresses a positive or negative opinion. ; See the paper below: ; ; Bing Liu. "Sentiment Analysis and Subjectivity." An chapter in ; Handbook of Natural Language Processing, Second Edition, ; (editors: N. Indurkhya and F. J. Damerau), 2010. ; ; 2. You will notice many misspelled words in the list. They are not ; mistakes. They are included as these misspelled words appear ; frequently in social media content. ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def neg #{"2-faced" "2-faces" "abnormal" "abolish" "abominable" "abominably" "abominate" "abomination" "abort" "aborted" "aborts" "abrade" "abrasive" "abrupt" "abruptly" "abscond" "absence" "absent-minded" "absentee" "absurd" "absurdity" "absurdly" "absurdness" "abuse" "abused" "abuses" "abusive" "abysmal" "abysmally" "abyss" "accidental" "accost" "accursed" "accusation" "accusations" "accuse" "accuses" "accusing" "accusingly" "acerbate" "acerbic" "acerbically" "ache" "ached" "aches" "achey" "aching" "acrid" "acridly" "acridness" "acrimonious" "acrimoniously" "acrimony" "adamant" "adamantly" "addict" "addicted" "addicting" "addicts" "admonish" "admonisher" "admonishingly" "admonishment" "admonition" "adulterate" "adulterated" "adulteration" "adulterier" "adversarial" "adversary" "adverse" "adversity" "afflict" "affliction" "afflictive" "affront" "afraid" "aggravate" "aggravating" "aggravation" "aggression" "aggressive" "aggressiveness" "aggressor" "aggrieve" "aggrieved" "aggrivation" "aghast" "agonies" "agonize" "agonizing" "agonizingly" "agony" "aground" "ail" "ailing" "ailment" "aimless" "alarm" "alarmed" "alarming" "alarmingly" "alienate" "alienated" "alienation" "allegation" "allegations" "allege" "allergic" "allergies" "allergy" "aloof" "altercation" "ambiguity" "ambiguous" "ambivalence" "ambivalent" "ambush" "amiss" "amputate" "anarchism" "anarchist" "anarchistic" "anarchy" "anemic" "anger" "angrily" "angriness" "angry" "anguish" "animosity" "annihilate" "annihilation" "annoy" "annoyance" "annoyances" "annoyed" "annoying" "annoyingly" "annoys" "anomalous" "anomaly" "antagonism" "antagonist" "antagonistic" "antagonize" "anti-" "anti-american" "anti-israeli" "anti-occupation" "anti-proliferation" "anti-semites" "anti-social" "anti-us" "anti-white" "antipathy" "antiquated" "antithetical" "anxieties" "anxiety" "anxious" "anxiously" "anxiousness" "apathetic" "apathetically" "apathy" "apocalypse" "apocalyptic" "apologist" "apologists" "appal" "appall" "appalled" "appalling" "appallingly" "apprehension" "apprehensions" "apprehensive" "apprehensively" "arbitrary" "arcane" "archaic" "arduous" "arduously" "argumentative" "arrogance" "arrogant" "arrogantly" "ashamed" "asinine" "asininely" "asinininity" "askance" "asperse" "aspersion" "aspersions" "assail" "assassin" "assassinate" "assault" "assult" "astray" "asunder" "atrocious" "atrocities" "atrocity" "atrophy" "attack" "attacks" "audacious" "audaciously" "audaciousness" "audacity" "audiciously" "austere" "authoritarian" "autocrat" "autocratic" "avalanche" "avarice" "avaricious" "avariciously" "avenge" "averse" "aversion" "aweful" "awful" "awfully" "awfulness" "awkward" "awkwardness" "ax" "babble" "back-logged" "back-wood" "back-woods" "backache" "backaches" "backaching" "backbite" "backbiting" "backward" "backwardness" "backwood" "backwoods" "bad" "badly" "baffle" "baffled" "bafflement" "baffling" "bait" "balk" "banal" "banalize" "bane" "banish" "banishment" "bankrupt" "barbarian" "barbaric" "barbarically" "barbarity" "barbarous" "barbarously" "barren" "baseless" "bash" "bashed" "bashful" "bashing" "bastard" "bastards" "battered" "battering" "batty" "bearish" "beastly" "bedlam" "bedlamite" "befoul" "beg" "beggar" "beggarly" "begging" "beguile" "belabor" "belated" "beleaguer" "belie" "belittle" "belittled" "belittling" "bellicose" "belligerence" "belligerent" "belligerently" "bemoan" "bemoaning" "bemused" "bent" "berate" "bereave" "bereavement" "bereft" "berserk" "beseech" "beset" "besiege" "besmirch" "bestial" "betray" "betrayal" "betrayals" "betrayer" "betraying" "betrays" "bewail" "beware" "bewilder" "bewildered" "bewildering" "bewilderingly" "bewilderment" "bewitch" "bias" "biased" "biases" "bicker" "bickering" "bid-rigging" "bigotries" "bigotry" "bitch" "bitchy" "biting" "bitingly" "bitter" "bitterly" "bitterness" "bizarre" "blab" "blabber" "blackmail" "blah" "blame" "blameworthy" "bland" "blandish" "blaspheme" "blasphemous" "blasphemy" "blasted" "blatant" "blatantly" "blather" "bleak" "bleakly" "bleakness" "bleed" "bleeding" "bleeds" "blemish" "blind" "blinding" "blindingly" "blindside" "blister" "blistering" "bloated" "blockage" "blockhead" "bloodshed" "bloodthirsty" "bloody" "blotchy" "blow" "blunder" "blundering" "blunders" "blunt" "blur" "bluring" "blurred" "blurring" "blurry" "blurs" "blurt" "boastful" "boggle" "bogus" "boil" "boiling" "boisterous" "bomb" "bombard" "bombardment" "bombastic" "bondage" "bonkers" "bore" "bored" "boredom" "bores" "boring" "botch" "bother" "bothered" "bothering" "bothers" "bothersome" "bowdlerize" "boycott" "braggart" "bragger" "brainless" "brainwash" "brash" "brashly" "brashness" "brat" "bravado" "brazen" "brazenly" "brazenness" "breach" "break" "break-up" "break-ups" "breakdown" "breaking" "breaks" "breakup" "breakups" "bribery" "brimstone" "bristle" "brittle" "broke" "broken" "broken-hearted" "brood" "browbeat" "bruise" "bruised" "bruises" "bruising" "brusque" "brutal" "brutalising" "brutalities" "brutality" "brutalize" "brutalizing" "brutally" "brute" "brutish" "bs" "buckle" "bug" "bugging" "buggy" "bugs" "bulkier" "bulkiness" "bulky" "bulkyness" "bull****" "bull----" "bullies" "bullshit" "bullshyt" "bully" "bullying" "bullyingly" "bum" "bump" "bumped" "bumping" "bumpping" "bumps" "bumpy" "bungle" "bungler" "bungling" "bunk" "burden" "burdensome" "burdensomely" "burn" "burned" "burning" "burns" "bust" "busts" "busybody" "butcher" "butchery" "buzzing" "byzantine" "cackle" "calamities" "calamitous" "calamitously" "calamity" "callous" "calumniate" "calumniation" "calumnies" "calumnious" "calumniously" "calumny" "cancer" "cancerous" "cannibal" "cannibalize" "capitulate" "capricious" "capriciously" "capriciousness" "capsize" "careless" "carelessness" "caricature" "carnage" "carp" "cartoonish" "cash-strapped" "castigate" "castrated" "casualty" "cataclysm" "cataclysmal" "cataclysmic" "cataclysmically" "catastrophe" "catastrophes" "catastrophic" "catastrophically" "catastrophies" "caustic" "caustically" "cautionary" "cave" "censure" "chafe" "chaff" "chagrin" "challenging" "chaos" "chaotic" "chasten" "chastise" "chastisement" "chatter" "chatterbox" "cheap" "cheapen" "cheaply" "cheat" "cheated" "cheater" "cheating" "cheats" "checkered" "cheerless" "cheesy" "chide" "childish" "chill" "chilly" "chintzy" "choke" "choleric" "choppy" "chore" "chronic" "chunky" "clamor" "clamorous" "clash" "cliche" "cliched" "clique" "clog" "clogged" "clogs" "cloud" "clouding" "cloudy" "clueless" "clumsy" "clunky" "coarse" "cocky" "coerce" "coercion" "coercive" "cold" "coldly" "collapse" "collude" "collusion" "combative" "combust" "comical" "commiserate" "commonplace" "commotion" "commotions" "complacent" "complain" "complained" "complaining" "complains" "complaint" "complaints" "complex" "complicated" "complication" "complicit" "compulsion" "compulsive" "concede" "conceded" "conceit" "conceited" "concen" "concens" "concern" "concerned" "concerns" "concession" "concessions" "condemn" "condemnable" "condemnation" "condemned" "condemns" "condescend" "condescending" "condescendingly" "condescension" "confess" "confession" "confessions" "confined" "conflict" "conflicted" "conflicting" "conflicts" "confound" "confounded" "confounding" "confront" "confrontation" "confrontational" "confuse" "confused" "confuses" "confusing" "confusion" "confusions" "congested" "congestion" "cons" "conscons" "conservative" "conspicuous" "conspicuously" "conspiracies" "conspiracy" "conspirator" "conspiratorial" "conspire" "consternation" "contagious" "contaminate" "contaminated" "contaminates" "contaminating" "contamination" "contempt" "contemptible" "contemptuous" "contemptuously" "contend" "contention" "contentious" "contort" "contortions" "contradict" "contradiction" "contradictory" "contrariness" "contravene" "contrive" "contrived" "controversial" "controversy" "convoluted" "corrode" "corrosion" "corrosions" "corrosive" "corrupt" "corrupted" "corrupting" "corruption" "corrupts" "corruptted" "costlier" "costly" "counter-productive" "counterproductive" "coupists" "covetous" "coward" "cowardly" "crabby" "crack" "cracked" "cracks" "craftily" "craftly" "crafty" "cramp" "cramped" "cramping" "cranky" "crap" "crappy" "craps" "crash" "crashed" "crashes" "crashing" "crass" "craven" "cravenly" "craze" "crazily" "craziness" "crazy" "creak" "creaking" "creaks" "credulous" "creep" "creeping" "creeps" "creepy" "crept" "crime" "criminal" "cringe" "cringed" "cringes" "cripple" "crippled" "cripples" "crippling" "crisis" "critic" "critical" "criticism" "criticisms" "criticize" "criticized" "criticizing" "critics" "cronyism" "crook" "crooked" "crooks" "crowded" "crowdedness" "crude" "cruel" "crueler" "cruelest" "cruelly" "cruelness" "cruelties" "cruelty" "crumble" "crumbling" "crummy" "crumple" "crumpled" "crumples" "crush" "crushed" "crushing" "cry" "culpable" "culprit" "cumbersome" "cunt" "cunts" "cuplrit" "curse" "cursed" "curses" "curt" "cuss" "cussed" "cutthroat" "cynical" "cynicism" "d*mn" "damage" "damaged" "damages" "damaging" "damn" "damnable" "damnably" "damnation" "damned" "damning" "damper" "danger" "dangerous" "dangerousness" "dark" "darken" "darkened" "darker" "darkness" "dastard" "dastardly" "daunt" "daunting" "dauntingly" "dawdle" "daze" "dazed" "dead" "deadbeat" "deadlock" "deadly" "deadweight" "deaf" "dearth" "death" "debacle" "debase" "debasement" "debaser" "debatable" "debauch" "debaucher" "debauchery" "debilitate" "debilitating" "debility" "debt" "debts" "decadence" "decadent" "decay" "decayed" "deceit" "deceitful" "deceitfully" "deceitfulness" "deceive" "deceiver" "deceivers" "deceiving" "deception" "deceptive" "deceptively" "declaim" "decline" "declines" "declining" "decrement" "decrepit" "decrepitude" "decry" "defamation" "defamations" "defamatory" "defame" "defect" "defective" "defects" "defensive" "defiance" "defiant" "defiantly" "deficiencies" "deficiency" "deficient" "defile" "defiler" "deform" "deformed" "defrauding" "defunct" "defy" "degenerate" "degenerately" "degeneration" "degradation" "degrade" "degrading" "degradingly" "dehumanization" "dehumanize" "deign" "deject" "dejected" "dejectedly" "dejection" "delay" "delayed" "delaying" "delays" "delinquency" "delinquent" "delirious" "delirium" "delude" "deluded" "deluge" "delusion" "delusional" "delusions" "demean" "demeaning" "demise" "demolish" "demolisher" "demon" "demonic" "demonize" "demonized" "demonizes" "demonizing" "demoralize" "demoralizing" "demoralizingly" "denial" "denied" "denies" "denigrate" "denounce" "dense" "dent" "dented" "dents" "denunciate" "denunciation" "denunciations" "deny" "denying" "deplete" "deplorable" "deplorably" "deplore" "deploring" "deploringly" "deprave" "depraved" "depravedly" "deprecate" "depress" "depressed" "depressing" "depressingly" "depression" "depressions" "deprive" "deprived" "deride" "derision" "derisive" "derisively" "derisiveness" "derogatory" "desecrate" "desert" "desertion" "desiccate" "desiccated" "desititute" "desolate" "desolately" "desolation" "despair" "despairing" "despairingly" "desperate" "desperately" "desperation" "despicable" "despicably" "despise" "despised" "despoil" "despoiler" "despondence" "despondency" "despondent" "despondently" "despot" "despotic" "despotism" "destabilisation" "destains" "destitute" "destitution" "destroy" "destroyer" "destruction" "destructive" "desultory" "deter" "deteriorate" "deteriorating" "deterioration" "deterrent" "detest" "detestable" "detestably" "detested" "detesting" "detests" "detract" "detracted" "detracting" "detraction" "detracts" "detriment" "detrimental" "devastate" "devastated" "devastates" "devastating" "devastatingly" "devastation" "deviate" "deviation" "devil" "devilish" "devilishly" "devilment" "devilry" "devious" "deviously" "deviousness" "devoid" "diabolic" "diabolical" "diabolically" "diametrically" "diappointed" "diatribe" "diatribes" "dick" "dictator" "dictatorial" "die" "die-hard" "died" "dies" "difficult" "difficulties" "difficulty" "diffidence" "dilapidated" "dilemma" "dilly-dally" "dim" "dimmer" "din" "ding" "dings" "dinky" "dire" "direly" "direness" "dirt" "dirtbag" "dirtbags" "dirts" "dirty" "disable" "disabled" "disaccord" "disadvantage" "disadvantaged" "disadvantageous" "disadvantages" "disaffect" "disaffected" "disaffirm" "disagree" "disagreeable" "disagreeably" "disagreed" "disagreeing" "disagreement" "disagrees" "disallow" "disapointed" "disapointing" "disapointment" "disappoint" "disappointed" "disappointing" "disappointingly" "disappointment" "disappointments" "disappoints" "disapprobation" "disapproval" "disapprove" "disapproving" "disarm" "disarray" "disaster" "disasterous" "disastrous" "disastrously" "disavow" "disavowal" "disbelief" "disbelieve" "disbeliever" "disclaim" "discombobulate" "discomfit" "discomfititure" "discomfort" "discompose" "disconcert" "disconcerted" "disconcerting" "disconcertingly" "disconsolate" "disconsolately" "disconsolation" "discontent" "discontented" "discontentedly" "discontinued" "discontinuity" "discontinuous" "discord" "discordance" "discordant" "discountenance" "discourage" "discouragement" "discouraging" "discouragingly" "discourteous" "discourteously" "discoutinous" "discredit" "discrepant" "discriminate" "discrimination" "discriminatory" "disdain" "disdained" "disdainful" "disdainfully" "disfavor" "disgrace" "disgraced" "disgraceful" "disgracefully" "disgruntle" "disgruntled" "disgust" "disgusted" "disgustedly" "disgustful" "disgustfully" "disgusting" "disgustingly" "dishearten" "disheartening" "dishearteningly" "dishonest" "dishonestly" "dishonesty" "dishonor" "dishonorable" "dishonorablely" "disillusion" "disillusioned" "disillusionment" "disillusions" "disinclination" "disinclined" "disingenuous" "disingenuously" "disintegrate" "disintegrated" "disintegrates" "disintegration" "disinterest" "disinterested" "dislike" "disliked" "dislikes" "disliking" "dislocated" "disloyal" "disloyalty" "dismal" "dismally" "dismalness" "dismay" "dismayed" "dismaying" "dismayingly" "dismissive" "dismissively" "disobedience" "disobedient" "disobey" "disoobedient" "disorder" "disordered" "disorderly" "disorganized" "disorient" "disoriented" "disown" "disparage" "disparaging" "disparagingly" "dispensable" "dispirit" "dispirited" "dispiritedly" "dispiriting" "displace" "displaced" "displease" "displeased" "displeasing" "displeasure" "disproportionate" "disprove" "disputable" "dispute" "disputed" "disquiet" "disquieting" "disquietingly" "disquietude" "disregard" "disregardful" "disreputable" "disrepute" "disrespect" "disrespectable" "disrespectablity" "disrespectful" "disrespectfully" "disrespectfulness" "disrespecting" "disrupt" "disruption" "disruptive" "diss" "dissapointed" "dissappointed" "dissappointing" "dissatisfaction" "dissatisfactory" "dissatisfied" "dissatisfies" "dissatisfy" "dissatisfying" "dissed" "dissemble" "dissembler" "dissension" "dissent" "dissenter" "dissention" "disservice" "disses" "dissidence" "dissident" "dissidents" "dissing" "dissocial" "dissolute" "dissolution" "dissonance" "dissonant" "dissonantly" "dissuade" "dissuasive" "distains" "distaste" "distasteful" "distastefully" "distort" "distorted" "distortion" "distorts" "distract" "distracting" "distraction" "distraught" "distraughtly" "distraughtness" "distress" "distressed" "distressing" "distressingly" "distrust" "distrustful" "distrusting" "disturb" "disturbance" "disturbed" "disturbing" "disturbingly" "disunity" "disvalue" "divergent" "divisive" "divisively" "divisiveness" "dizzing" "dizzingly" "dizzy" "doddering" "dodgey" "dogged" "doggedly" "dogmatic" "doldrums" "domineer" "domineering" "donside" "doom" "doomed" "doomsday" "dope" "doubt" "doubtful" "doubtfully" "doubts" "douchbag" "douchebag" "douchebags" "downbeat" "downcast" "downer" "downfall" "downfallen" "downgrade" "downhearted" "downheartedly" "downhill" "downside" "downsides" "downturn" "downturns" "drab" "draconian" "draconic" "drag" "dragged" "dragging" "dragoon" "drags" "drain" "drained" "draining" "drains" "drastic" "drastically" "drawback" "drawbacks" "dread" "dreadful" "dreadfully" "dreadfulness" "dreary" "dripped" "dripping" "drippy" "drips" "drones" "droop" "droops" "drop-out" "drop-outs" "dropout" "dropouts" "drought" "drowning" "drunk" "drunkard" "drunken" "dubious" "dubiously" "dubitable" "dud" "dull" "dullard" "dumb" "dumbfound" "dump" "dumped" "dumping" "dumps" "dunce" "dungeon" "dungeons" "dupe" "dust" "dusty" "dwindling" "dying" "earsplitting" "eccentric" "eccentricity" "effigy" "effrontery" "egocentric" "egomania" "egotism" "egotistical" "egotistically" "egregious" "egregiously" "election-rigger" "elimination" "emaciated" "emasculate" "embarrass" "embarrassing" "embarrassingly" "embarrassment" "embattled" "embroil" "embroiled" "embroilment" "emergency" "emphatic" "emphatically" "emptiness" "encroach" "encroachment" "endanger" "enemies" "enemy" "enervate" "enfeeble" "enflame" "engulf" "enjoin" "enmity" "enrage" "enraged" "enraging" "enslave" "entangle" "entanglement" "entrap" "entrapment" "envious" "enviously" "enviousness" "epidemic" "equivocal" "erase" "erode" "erodes" "erosion" "err" "errant" "erratic" "erratically" "erroneous" "erroneously" "error" "errors" "eruptions" "escapade" "eschew" "estranged" "evade" "evasion" "evasive" "evil" "evildoer" "evils" "eviscerate" "exacerbate" "exagerate" "exagerated" "exagerates" "exaggerate" "exaggeration" "exasperate" "exasperated" "exasperating" "exasperatingly" "exasperation" "excessive" "excessively" "exclusion" "excoriate" "excruciating" "excruciatingly" "excuse" "excuses" "execrate" "exhaust" "exhausted" "exhaustion" "exhausts" "exhorbitant" "exhort" "exile" "exorbitant" "exorbitantance" "exorbitantly" "expel" "expensive" "expire" "expired" "explode" "exploit" "exploitation" "explosive" "expropriate" "expropriation" "expulse" "expunge" "exterminate" "extermination" "extinguish" "extort" "extortion" "extraneous" "extravagance" "extravagant" "extravagantly" "extremism" "extremist" "extremists" "eyesore" "f**k" "fabricate" "fabrication" "facetious" "facetiously" "fail" "failed" "failing" "fails" "failure" "failures" "faint" "fainthearted" "faithless" "fake" "fall" "fallacies" "fallacious" "fallaciously" "fallaciousness" "fallacy" "fallen" "falling" "fallout" "falls" "false" "falsehood" "falsely" "falsify" "falter" "faltered" "famine" "famished" "fanatic" "fanatical" "fanatically" "fanaticism" "fanatics" "fanciful" "far-fetched" "farce" "farcical" "farcical-yet-provocative" "farcically" "farfetched" "fascism" "fascist" "fastidious" "fastidiously" "fastuous" "fat" "fat-cat" "fat-cats" "fatal" "fatalistic" "fatalistically" "fatally" "fatcat" "fatcats" "fateful" "fatefully" "fathomless" "fatigue" "fatigued" "fatique" "fatty" "fatuity" "fatuous" "fatuously" "fault" "faults" "faulty" "fawningly" "faze" "fear" "fearful" "fearfully" "fears" "fearsome" "feckless" "feeble" "feeblely" "feebleminded" "feign" "feint" "fell" "felon" "felonious" "ferociously" "ferocity" "fetid" "fever" "feverish" "fevers" "fiasco" "fib" "fibber" "fickle" "fiction" "fictional" "fictitious" "fidget" "fidgety" "fiend" "fiendish" "fierce" "figurehead" "filth" "filthy" "finagle" "finicky" "fissures" "fist" "flabbergast" "flabbergasted" "flagging" "flagrant" "flagrantly" "flair" "flairs" "flak" "flake" "flakey" "flakieness" "flaking" "flaky" "flare" "flares" "flareup" "flareups" "flat-out" "flaunt" "flaw" "flawed" "flaws" "flee" "fleed" "fleeing" "fleer" "flees" "fleeting" "flicering" "flicker" "flickering" "flickers" "flighty" "flimflam" "flimsy" "flirt" "flirty" "floored" "flounder" "floundering" "flout" "fluster" "foe" "fool" "fooled" "foolhardy" "foolish" "foolishly" "foolishness" "forbid" "forbidden" "forbidding" "forceful" "foreboding" "forebodingly" "forfeit" "forged" "forgetful" "forgetfully" "forgetfulness" "forlorn" "forlornly" "forsake" "forsaken" "forswear" "foul" "foully" "foulness" "fractious" "fractiously" "fracture" "fragile" "fragmented" "frail" "frantic" "frantically" "franticly" "fraud" "fraudulent" "fraught" "frazzle" "frazzled" "freak" "freaking" "freakish" "freakishly" "freaks" "freeze" "freezes" "freezing" "frenetic" "frenetically" "frenzied" "frenzy" "fret" "fretful" "frets" "friction" "frictions" "fried" "friggin" "frigging" "fright" "frighten" "frightening" "frighteningly" "frightful" "frightfully" "frigid" "frost" "frown" "froze" "frozen" "fruitless" "fruitlessly" "frustrate" "frustrated" "frustrates" "frustrating" "frustratingly" "frustration" "frustrations" "fuck" "fucking" "fudge" "fugitive" "full-blown" "fulminate" "fumble" "fume" "fumes" "fundamentalism" "funky" "funnily" "funny" "furious" "furiously" "furor" "fury" "fuss" "fussy" "fustigate" "fusty" "futile" "futilely" "futility" "fuzzy" "gabble" "gaff" "gaffe" "gainsay" "gainsayer" "gall" "galling" "gallingly" "galls" "gangster" "gape" "garbage" "garish" "gasp" "gauche" "gaudy" "gawk" "gawky" "geezer" "genocide" "get-rich" "ghastly" "ghetto" "ghosting" "gibber" "gibberish" "gibe" "giddy" "gimmick" "gimmicked" "gimmicking" "gimmicks" "gimmicky" "glare" "glaringly" "glib" "glibly" "glitch" "glitches" "gloatingly" "gloom" "gloomy" "glower" "glum" "glut" "gnawing" "goad" "goading" "god-awful" "goof" "goofy" "goon" "gossip" "graceless" "gracelessly" "graft" "grainy" "grapple" "grate" "grating" "gravely" "greasy" "greed" "greedy" "grief" "grievance" "grievances" "grieve" "grieving" "grievous" "grievously" "grim" "grimace" "grind" "gripe" "gripes" "grisly" "gritty" "gross" "grossly" "grotesque" "grouch" "grouchy" "groundless" "grouse" "growl" "grudge" "grudges" "grudging" "grudgingly" "gruesome" "gruesomely" "gruff" "grumble" "grumpier" "grumpiest" "grumpily" "grumpish" "grumpy" "guile" "guilt" "guiltily" "guilty" "gullible" "gutless" "gutter" "hack" "hacks" "haggard" "haggle" "hairloss" "halfhearted" "halfheartedly" "hallucinate" "hallucination" "hamper" "hampered" "handicapped" "hang" "hangs" "haphazard" "hapless" "harangue" "harass" "harassed" "harasses" "harassment" "harboring" "harbors" "hard" "hard-hit" "hard-line" "hard-liner" "hardball" "harden" "hardened" "hardheaded" "hardhearted" "hardliner" "hardliners" "hardship" "hardships" "harm" "harmed" "harmful" "harms" "harpy" "harridan" "harried" "harrow" "harsh" "harshly" "hasseling" "hassle" "hassled" "hassles" "haste" "hastily" "hasty" "hate" "hated" "hateful" "hatefully" "hatefulness" "hater" "haters" "hates" "hating" "hatred" "haughtily" "haughty" "haunt" "haunting" "havoc" "hawkish" "haywire" "hazard" "hazardous" "haze" "hazy" "head-aches" "headache" "headaches" "heartbreaker" "heartbreaking" "heartbreakingly" "heartless" "heathen" "heavy-handed" "heavyhearted" "heck" "heckle" "heckled" "heckles" "hectic" "hedge" "hedonistic" "heedless" "hefty" "hegemonism" "hegemonistic" "hegemony" "heinous" "hell" "hell-bent" "hellion" "hells" "helpless" "helplessly" "helplessness" "heresy" "heretic" "heretical" "hesitant" "hestitant" "hideous" "hideously" "hideousness" "high-priced" "hiliarious" "hinder" "hindrance" "hiss" "hissed" "hissing" "ho-hum" "hoard" "hoax" "hobble" "hogs" "hollow" "hoodium" "hoodwink" "hooligan" "hopeless" "hopelessly" "hopelessness" "horde" "horrendous" "horrendously" "horrible" "horrid" "horrific" "horrified" "horrifies" "horrify" "horrifying" "horrifys" "hostage" "hostile" "hostilities" "hostility" "hotbeds" "hothead" "hotheaded" "hothouse" "hubris" "huckster" "hum" "humid" "humiliate" "humiliating" "humiliation" "humming" "hung" "hurt" "hurted" "hurtful" "hurting" "hurts" "hustler" "hype" "hypocricy" "hypocrisy" "hypocrite" "hypocrites" "hypocritical" "hypocritically" "hysteria" "hysteric" "hysterical" "hysterically" "hysterics" "idiocies" "idiocy" "idiot" "idiotic" "idiotically" "idiots" "idle" "ignoble" "ignominious" "ignominiously" "ignominy" "ignorance" "ignorant" "ignore" "ill-advised" "ill-conceived" "ill-defined" "ill-designed" "ill-fated" "ill-favored" "ill-formed" "ill-mannered" "ill-natured" "ill-sorted" "ill-tempered" "ill-treated" "ill-treatment" "ill-usage" "ill-used" "illegal" "illegally" "illegitimate" "illicit" "illiterate" "illness" "illogic" "illogical" "illogically" "illusion" "illusions" "illusory" "imaginary" "imbalance" "imbecile" "imbroglio" "immaterial" "immature" "imminence" "imminently" "immobilized" "immoderate" "immoderately" "immodest" "immoral" "immorality" "immorally" "immovable" "impair" "impaired" "impasse" "impatience" "impatient" "impatiently" "impeach" "impedance" "impede" "impediment" "impending" "impenitent" "imperfect" "imperfection" "imperfections" "imperfectly" "imperialist" "imperil" "imperious" "imperiously" "impermissible" "impersonal" "impertinent" "impetuous" "impetuously" "impiety" "impinge" "impious" "implacable" "implausible" "implausibly" "implicate" "implication" "implode" "impolite" "impolitely" "impolitic" "importunate" "importune" "impose" "imposers" "imposing" "imposition" "impossible" "impossiblity" "impossibly" "impotent" "impoverish" "impoverished" "impractical" "imprecate" "imprecise" "imprecisely" "imprecision" "imprison" "imprisonment" "improbability" "improbable" "improbably" "improper" "improperly" "impropriety" "imprudence" "imprudent" "impudence" "impudent" "impudently" "impugn" "impulsive" "impulsively" "impunity" "impure" "impurity" "inability" "inaccuracies" "inaccuracy" "inaccurate" "inaccurately" "inaction" "inactive" "inadequacy" "inadequate" "inadequately" "inadverent" "inadverently" "inadvisable" "inadvisably" "inane" "inanely" "inappropriate" "inappropriately" "inapt" "inaptitude" "inarticulate" "inattentive" "inaudible" "incapable" "incapably" "incautious" "incendiary" "incense" "incessant" "incessantly" "incite" "incitement" "incivility" "inclement" "incognizant" "incoherence" "incoherent" "incoherently" "incommensurate" "incomparable" "incomparably" "incompatability" "incompatibility" "incompatible" "incompetence" "incompetent" "incompetently" "incomplete" "incompliant" "incomprehensible" "incomprehension" "inconceivable" "inconceivably" "incongruous" "incongruously" "inconsequent" "inconsequential" "inconsequentially" "inconsequently" "inconsiderate" "inconsiderately" "inconsistence" "inconsistencies" "inconsistency" "inconsistent" "inconsolable" "inconsolably" "inconstant" "inconvenience" "inconveniently" "incorrect" "incorrectly" "incorrigible" "incorrigibly" "incredulous" "incredulously" "inculcate" "indecency" "indecent" "indecently" "indecision" "indecisive" "indecisively" "indecorum" "indefensible" "indelicate" "indeterminable" "indeterminably" "indeterminate" "indifference" "indifferent" "indigent" "indignant" "indignantly" "indignation" "indignity" "indiscernible" "indiscreet" "indiscreetly" "indiscretion" "indiscriminate" "indiscriminately" "indiscriminating" "indistinguishable" "indoctrinate" "indoctrination" "indolent" "indulge" "ineffective" "ineffectively" "ineffectiveness" "ineffectual" "ineffectually" "ineffectualness" "inefficacious" "inefficacy" "inefficiency" "inefficient" "inefficiently" "inelegance" "inelegant" "ineligible" "ineloquent" "ineloquently" "inept" "ineptitude" "ineptly" "inequalities" "inequality" "inequitable" "inequitably" "inequities" "inescapable" "inescapably" "inessential" "inevitable" "inevitably" "inexcusable" "inexcusably" "inexorable" "inexorably" "inexperience" "inexperienced" "inexpert" "inexpertly" "inexpiable" "inexplainable" "inextricable" "inextricably" "infamous" "infamously" "infamy" "infected" "infection" "infections" "inferior" "inferiority" "infernal" "infest" "infested" "infidel" "infidels" "infiltrator" "infiltrators" "infirm" "inflame" "inflammation" "inflammatory" "inflammed" "inflated" "inflationary" "inflexible" "inflict" "infraction" "infringe" "infringement" "infringements" "infuriate" "infuriated" "infuriating" "infuriatingly" "inglorious" "ingrate" "ingratitude" "inhibit" "inhibition" "inhospitable" "inhospitality" "inhuman" "inhumane" "inhumanity" "inimical" "inimically" "iniquitous" "iniquity" "injudicious" "injure" "injurious" "injury" "injustice" "injustices" "innuendo" "inoperable" "inopportune" "inordinate" "inordinately" "insane" "insanely" "insanity" "insatiable" "insecure" "insecurity" "insensible" "insensitive" "insensitively" "insensitivity" "insidious" "insidiously" "insignificance" "insignificant" "insignificantly" "insincere" "insincerely" "insincerity" "insinuate" "insinuating" "insinuation" "insociable" "insolence" "insolent" "insolently" "insolvent" "insouciance" "instability" "instable" "instigate" "instigator" "instigators" "insubordinate" "insubstantial" "insubstantially" "insufferable" "insufferably" "insufficiency" "insufficient" "insufficiently" "insular" "insult" "insulted" "insulting" "insultingly" "insults" "insupportable" "insupportably" "insurmountable" "insurmountably" "insurrection" "intefere" "inteferes" "intense" "interfere" "interference" "interferes" "intermittent" "interrupt" "interruption" "interruptions" "intimidate" "intimidating" "intimidatingly" "intimidation" "intolerable" "intolerablely" "intolerance" "intoxicate" "intractable" "intransigence" "intransigent" "intrude" "intrusion" "intrusive" "inundate" "inundated" "invader" "invalid" "invalidate" "invalidity" "invasive" "invective" "inveigle" "invidious" "invidiously" "invidiousness" "invisible" "involuntarily" "involuntary" "irascible" "irate" "irately" "ire" "irk" "irked" "irking" "irks" "irksome" "irksomely" "irksomeness" "irksomenesses" "ironic" "ironical" "ironically" "ironies" "irony" "irragularity" "irrational" "irrationalities" "irrationality" "irrationally" "irrationals" "irreconcilable" "irrecoverable" "irrecoverableness" "irrecoverablenesses" "irrecoverably" "irredeemable" "irredeemably" "irreformable" "irregular" "irregularity" "irrelevance" "irrelevant" "irreparable" "irreplacible" "irrepressible" "irresolute" "irresolvable" "irresponsible" "irresponsibly" "irretating" "irretrievable" "irreversible" "irritable" "irritably" "irritant" "irritate" "irritated" "irritating" "irritation" "irritations" "isolate" "isolated" "isolation" "issue" "issues" "itch" "itching" "itchy" "jabber" "jaded" "jagged" "jam" "jarring" "jaundiced" "jealous" "jealously" "jealousness" "jealousy" "jeer" "jeering" "jeeringly" "jeers" "jeopardize" "jeopardy" "jerk" "jerky" "jitter" "jitters" "jittery" "job-killing" "jobless" "joke" "joker" "jolt" "judder" "juddering" "judders" "jumpy" "junk" "junky" "junkyard" "jutter" "jutters" "kaput" "kill" "killed" "killer" "killing" "killjoy" "kills" "knave" "knife" "knock" "knotted" "kook" "kooky" "lack" "lackadaisical" "lacked" "lackey" "lackeys" "lacking" "lackluster" "lacks" "laconic" "lag" "lagged" "lagging" "laggy" "lags" "laid-off" "lambast" "lambaste" "lame" "lame-duck" "lament" "lamentable" "lamentably" "languid" "languish" "languor" "languorous" "languorously" "lanky" "lapse" "lapsed" "lapses" "lascivious" "last-ditch" "latency" "laughable" "laughably" "laughingstock" "lawbreaker" "lawbreaking" "lawless" "lawlessness" "layoff" "layoff-happy" "lazy" "leak" "leakage" "leakages" "leaking" "leaks" "leaky" "lech" "lecher" "lecherous" "lechery" "leech" "leer" "leery" "left-leaning" "lemon" "lengthy" "less-developed" "lesser-known" "letch" "lethal" "lethargic" "lethargy" "lewd" "lewdly" "lewdness" "liability" "liable" "liar" "liars" "licentious" "licentiously" "licentiousness" "lie" "lied" "lier" "lies" "life-threatening" "lifeless" "limit" "limitation" "limitations" "limited" "limits" "limp" "listless" "litigious" "little-known" "livid" "lividly" "loath" "loathe" "loathing" "loathly" "loathsome" "loathsomely" "lone" "loneliness" "lonely" "loner" "lonesome" "long-time" "long-winded" "longing" "longingly" "loophole" "loopholes" "loose" "loot" "lorn" "lose" "loser" "losers" "loses" "losing" "loss" "losses" "lost" "loud" "louder" "lousy" "loveless" "lovelorn" "low-rated" "lowly" "ludicrous" "ludicrously" "lugubrious" "lukewarm" "lull" "lumpy" "lunatic" "lunaticism" "lurch" "lure" "lurid" "lurk" "lurking" "lying" "macabre" "mad" "madden" "maddening" "maddeningly" "madder" "madly" "madman" "madness" "maladjusted" "maladjustment" "malady" "malaise" "malcontent" "malcontented" "maledict" "malevolence" "malevolent" "malevolently" "malice" "malicious" "maliciously" "maliciousness" "malign" "malignant" "malodorous" "maltreatment" "mangle" "mangled" "mangles" "mangling" "mania" "maniac" "maniacal" "manic" "manipulate" "manipulation" "manipulative" "manipulators" "mar" "marginal" "marginally" "martyrdom" "martyrdom-seeking" "mashed" "massacre" "massacres" "matte" "mawkish" "mawkishly" "mawkishness" "meager" "meaningless" "meanness" "measly" "meddle" "meddlesome" "mediocre" "mediocrity" "melancholy" "melodramatic" "melodramatically" "meltdown" "menace" "menacing" "menacingly" "mendacious" "mendacity" "menial" "merciless" "mercilessly" "mess" "messed" "messes" "messing" "messy" "midget" "miff" "militancy" "mindless" "mindlessly" "mirage" "mire" "misalign" "misaligned" "misaligns" "misapprehend" "misbecome" "misbecoming" "misbegotten" "misbehave" "misbehavior" "miscalculate" "miscalculation" "miscellaneous" "mischief" "mischievous" "mischievously" "misconception" "misconceptions" "miscreant" "miscreants" "misdirection" "miser" "miserable" "miserableness" "miserably" "miseries" "miserly" "misery" "misfit" "misfortune" "misgiving" "misgivings" "misguidance" "misguide" "misguided" "mishandle" "mishap" "misinform" "misinformed" "misinterpret" "misjudge" "misjudgment" "mislead" "misleading" "misleadingly" "mislike" "mismanage" "mispronounce" "mispronounced" "mispronounces" "misread" "misreading" "misrepresent" "misrepresentation" "miss" "missed" "misses" "misstatement" "mist" "mistake" "mistaken" "mistakenly" "mistakes" "mistified" "mistress" "mistrust" "mistrustful" "mistrustfully" "mists" "misunderstand" "misunderstanding" "misunderstandings" "misunderstood" "misuse" "moan" "mobster" "mock" "mocked" "mockeries" "mockery" "mocking" "mockingly" "mocks" "molest" "molestation" "monotonous" "monotony" "monster" "monstrosities" "monstrosity" "monstrous" "monstrously" "moody" "moot" "mope" "morbid" "morbidly" "mordant" "mordantly" "moribund" "moron" "moronic" "morons" "mortification" "mortified" "mortify" "mortifying" "motionless" "motley" "mourn" "mourner" "mournful" "mournfully" "muddle" "muddy" "mudslinger" "mudslinging" "mulish" "multi-polarization" "mundane" "murder" "murderer" "murderous" "murderously" "murky" "muscle-flexing" "mushy" "musty" "mysterious" "mysteriously" "mystery" "mystify" "myth" "nag" "nagging" "naive" "naively" "narrower" "nastily" "nastiness" "nasty" "naughty" "nauseate" "nauseates" "nauseating" "nauseatingly" "na�ve" "nebulous" "nebulously" "needless" "needlessly" "needy" "nefarious" "nefariously" "negate" "negation" "negative" "negatives" "negativity" "neglect" "neglected" "negligence" "negligent" "nemesis" "nepotism" "nervous" "nervously" "nervousness" "nettle" "nettlesome" "neurotic" "neurotically" "niggle" "niggles" "nightmare" "nightmarish" "nightmarishly" "nitpick" "nitpicking" "noise" "noises" "noisier" "noisy" "non-confidence" "nonexistent" "nonresponsive" "nonsense" "nosey" "notoriety" "notorious" "notoriously" "noxious" "nuisance" "numb" "obese" "object" "objection" "objectionable" "objections" "oblique" "obliterate" "obliterated" "oblivious" "obnoxious" "obnoxiously" "obscene" "obscenely" "obscenity" "obscure" "obscured" "obscures" "obscurity" "obsess" "obsessive" "obsessively" "obsessiveness" "obsolete" "obstacle" "obstinate" "obstinately" "obstruct" "obstructed" "obstructing" "obstruction" "obstructs" "obtrusive" "obtuse" "occlude" "occluded" "occludes" "occluding" "odd" "odder" "oddest" "oddities" "oddity" "oddly" "odor" "offence" "offend" "offender" "offending" "offenses" "offensive" "offensively" "offensiveness" "officious" "ominous" "ominously" "omission" "omit" "one-sided" "onerous" "onerously" "onslaught" "opinionated" "opponent" "opportunistic" "oppose" "opposition" "oppositions" "oppress" "oppression" "oppressive" "oppressively" "oppressiveness" "oppressors" "ordeal" "orphan" "ostracize" "outbreak" "outburst" "outbursts" "outcast" "outcry" "outlaw" "outmoded" "outrage" "outraged" "outrageous" "outrageously" "outrageousness" "outrages" "outsider" "over-acted" "over-awe" "over-balanced" "over-hyped" "over-priced" "over-valuation" "overact" "overacted" "overawe" "overbalance" "overbalanced" "overbearing" "overbearingly" "overblown" "overdo" "overdone" "overdue" "overemphasize" "overheat" "overkill" "overloaded" "overlook" "overpaid" "overpayed" "overplay" "overpower" "overpriced" "overrated" "overreach" "overrun" "overshadow" "oversight" "oversights" "oversimplification" "oversimplified" "oversimplify" "oversize" "overstate" "overstated" "overstatement" "overstatements" "overstates" "overtaxed" "overthrow" "overthrows" "overturn" "overweight" "overwhelm" "overwhelmed" "overwhelming" "overwhelmingly" "overwhelms" "overzealous" "overzealously" "overzelous" "pain" "painful" "painfull" "painfully" "pains" "pale" "pales" "paltry" "pan" "pandemonium" "pander" "pandering" "panders" "panic" "panick" "panicked" "panicking" "panicky" "paradoxical" "paradoxically" "paralize" "paralyzed" "paranoia" "paranoid" "parasite" "pariah" "parody" "partiality" "partisan" "partisans" "passe" "passive" "passiveness" "pathetic" "pathetically" "patronize" "paucity" "pauper" "paupers" "payback" "peculiar" "peculiarly" "pedantic" "peeled" "peeve" "peeved" "peevish" "peevishly" "penalize" "penalty" "perfidious" "perfidity" "perfunctory" "peril" "perilous" "perilously" "perish" "pernicious" "perplex" "perplexed" "perplexing" "perplexity" "persecute" "persecution" "pertinacious" "pertinaciously" "pertinacity" "perturb" "perturbed" "pervasive" "perverse" "perversely" "perversion" "perversity" "pervert" "perverted" "perverts" "pessimism" "pessimistic" "pessimistically" "pest" "pestilent" "petrified" "petrify" "pettifog" "petty" "phobia" "phobic" "phony" "picket" "picketed" "picketing" "pickets" "picky" "pig" "pigs" "pillage" "pillory" "pimple" "pinch" "pique" "pitiable" "pitiful" "pitifully" "pitiless" "pitilessly" "pittance" "pity" "plagiarize" "plague" "plasticky" "plaything" "plea" "pleas" "plebeian" "plight" "plot" "plotters" "ploy" "plunder" "plunderer" "pointless" "pointlessly" "poison" "poisonous" "poisonously" "pokey" "poky" "polarisation" "polemize" "pollute" "polluter" "polluters" "polution" "pompous" "poor" "poorer" "poorest" "poorly" "posturing" "pout" "poverty" "powerless" "prate" "pratfall" "prattle" "precarious" "precariously" "precipitate" "precipitous" "predatory" "predicament" "prejudge" "prejudice" "prejudices" "prejudicial" "premeditated" "preoccupy" "preposterous" "preposterously" "presumptuous" "presumptuously" "pretence" "pretend" "pretense" "pretentious" "pretentiously" "prevaricate" "pricey" "pricier" "prick" "prickle" "prickles" "prideful" "prik" "primitive" "prison" "prisoner" "problem" "problematic" "problems" "procrastinate" "procrastinates" "procrastination" "profane" "profanity" "prohibit" "prohibitive" "prohibitively" "propaganda" "propagandize" "proprietary" "prosecute" "protest" "protested" "protesting" "protests" "protracted" "provocation" "provocative" "provoke" "pry" "pugnacious" "pugnaciously" "pugnacity" "punch" "punish" "punishable" "punitive" "punk" "puny" "puppet" "puppets" "puzzled" "puzzlement" "puzzling" "quack" "qualm" "qualms" "quandary" "quarrel" "quarrellous" "quarrellously" "quarrels" "quarrelsome" "quash" "queer" "questionable" "quibble" "quibbles" "quitter" "rabid" "racism" "racist" "racists" "racy" "radical" "radicalization" "radically" "radicals" "rage" "ragged" "raging" "rail" "raked" "rampage" "rampant" "ramshackle" "rancor" "randomly" "rankle" "rant" "ranted" "ranting" "rantingly" "rants" "rape" "raped" "raping" "rascal" "rascals" "rash" "rattle" "rattled" "rattles" "ravage" "raving" "reactionary" "rebellious" "rebuff" "rebuke" "recalcitrant" "recant" "recession" "recessionary" "reckless" "recklessly" "recklessness" "recoil" "recourses" "redundancy" "redundant" "refusal" "refuse" "refused" "refuses" "refusing" "refutation" "refute" "refuted" "refutes" "refuting" "regress" "regression" "regressive" "regret" "regreted" "regretful" "regretfully" "regrets" "regrettable" "regrettably" "regretted" "reject" "rejected" "rejecting" "rejection" "rejects" "relapse" "relentless" "relentlessly" "relentlessness" "reluctance" "reluctant" "reluctantly" "remorse" "remorseful" "remorsefully" "remorseless" "remorselessly" "remorselessness" "renounce" "renunciation" "repel" "repetitive" "reprehensible" "reprehensibly" "reprehension" "reprehensive" "repress" "repression" "repressive" "reprimand" "reproach" "reproachful" "reprove" "reprovingly" "repudiate" "repudiation" "repugn" "repugnance" "repugnant" "repugnantly" "repulse" "repulsed" "repulsing" "repulsive" "repulsively" "repulsiveness" "resent" "resentful" "resentment" "resignation" "resigned" "resistance" "restless" "restlessness" "restrict" "restricted" "restriction" "restrictive" "resurgent" "retaliate" "retaliatory" "retard" "retarded" "retardedness" "retards" "reticent" "retract" "retreat" "retreated" "revenge" "revengeful" "revengefully" "revert" "revile" "reviled" "revoke" "revolt" "revolting" "revoltingly" "revulsion" "revulsive" "rhapsodize" "rhetoric" "rhetorical" "ricer" "ridicule" "ridicules" "ridiculous" "ridiculously" "rife" "rift" "rifts" "rigid" "rigidity" "rigidness" "rile" "riled" "rip" "rip-off" "ripoff" "ripped" "risk" "risks" "risky" "rival" "rivalry" "roadblocks" "rocky" "rogue" "rollercoaster" "rot" "rotten" "rough" "rremediable" "rubbish" "rude" "rue" "ruffian" "ruffle" "ruin" "ruined" "ruining" "ruinous" "ruins" "rumbling" "rumor" "rumors" "rumours" "rumple" "run-down" "runaway" "rupture" "rust" "rusts" "rusty" "rut" "ruthless" "ruthlessly" "ruthlessness" "ruts" "sabotage" "sack" "sacrificed" "sad" "sadden" "sadly" "sadness" "sag" "sagged" "sagging" "saggy" "sags" "salacious" "sanctimonious" "sap" "sarcasm" "sarcastic" "sarcastically" "sardonic" "sardonically" "sass" "satirical" "satirize" "savage" "savaged" "savagery" "savages" "scaly" "scam" "scams" "scandal" "scandalize" "scandalized" "scandalous" "scandalously" "scandals" "scandel" "scandels" "scant" "scapegoat" "scar" "scarce" "scarcely" "scarcity" "scare" "scared" "scarier" "scariest" "scarily" "scarred" "scars" "scary" "scathing" "scathingly" "sceptical" "scoff" "scoffingly" "scold" "scolded" "scolding" "scoldingly" "scorching" "scorchingly" "scorn" "scornful" "scornfully" "scoundrel" "scourge" "scowl" "scramble" "scrambled" "scrambles" "scrambling" "scrap" "scratch" "scratched" "scratches" "scratchy" "scream" "screech" "screw-up" "screwed" "screwed-up" "screwy" "scuff" "scuffs" "scum" "scummy" "second-class" "second-tier" "secretive" "sedentary" "seedy" "seethe" "seething" "self-coup" "self-criticism" "self-defeating" "self-destructive" "self-humiliation" "self-interest" "self-interested" "self-serving" "selfinterested" "selfish" "selfishly" "selfishness" "semi-retarded" "senile" "sensationalize" "senseless" "senselessly" "seriousness" "sermonize" "servitude" "set-up" "setback" "setbacks" "sever" "severe" "severity" "sh*t" "shabby" "shadowy" "shady" "shake" "shaky" "shallow" "sham" "shambles" "shame" "shameful" "shamefully" "shamefulness" "shameless" "shamelessly" "shamelessness" "shark" "sharply" "shatter" "shemale" "shimmer" "shimmy" "shipwreck" "shirk" "shirker" "shit" "shiver" "shock" "shocked" "shocking" "shockingly" "shoddy" "short-lived" "shortage" "shortchange" "shortcoming" "shortcomings" "shortness" "shortsighted" "shortsightedness" "showdown" "shrew" "shriek" "shrill" "shrilly" "shrivel" "shroud" "shrouded" "shrug" "shun" "shunned" "sick" "sicken" "sickening" "sickeningly" "sickly" "sickness" "sidetrack" "sidetracked" "siege" "sillily" "silly" "simplistic" "simplistically" "sin" "sinful" "sinfully" "sinister" "sinisterly" "sink" "sinking" "skeletons" "skeptic" "skeptical" "skeptically" "skepticism" "sketchy" "skimpy" "skinny" "skittish" "skittishly" "skulk" "slack" "slander" "slanderer" "slanderous" "slanderously" "slanders" "slap" "slashing" "slaughter" "slaughtered" "slave" "slaves" "sleazy" "slime" "slog" "slogged" "slogging" "slogs" "sloooooooooooooow" "sloooow" "slooow" "sloow" "sloppily" "sloppy" "sloth" "slothful" "slow" "slow-moving" "slowed" "slower" "slowest" "slowly" "sloww" "slowww" "slowwww" "slug" "sluggish" "slump" "slumping" "slumpping" "slur" "slut" "sluts" "sly" "smack" "smallish" "smash" "smear" "smell" "smelled" "smelling" "smells" "smelly" "smelt" "smoke" "smokescreen" "smolder" "smoldering" "smother" "smoulder" "smouldering" "smudge" "smudged" "smudges" "smudging" "smug" "smugly" "smut" "smuttier" "smuttiest" "smutty" "snag" "snagged" "snagging" "snags" "snappish" "snappishly" "snare" "snarky" "snarl" "sneak" "sneakily" "sneaky" "sneer" "sneering" "sneeringly" "snob" "snobbish" "snobby" "snobish" "snobs" "snub" "so-cal" "soapy" "sob" "sober" "sobering" "solemn" "solicitude" "somber" "sore" "sorely" "soreness" "sorrow" "sorrowful" "sorrowfully" "sorry" "sour" "sourly" "spade" "spank" "spendy" "spew" "spewed" "spewing" "spews" "spilling" "spinster" "spiritless" "spite" "spiteful" "spitefully" "spitefulness" "splatter" "split" "splitting" "spoil" "spoilage" "spoilages" "spoiled" "spoilled" "spoils" "spook" "spookier" "spookiest" "spookily" "spooky" "spoon-fed" "spoon-feed" "spoonfed" "sporadic" "spotty" "spurious" "spurn" "sputter" "squabble" "squabbling" "squander" "squash" "squeak" "squeaks" "squeaky" "squeal" "squealing" "squeals" "squirm" "stab" "stagnant" "stagnate" "stagnation" "staid" "stain" "stains" "stale" "stalemate" "stall" "stalls" "stammer" "stampede" "standstill" "stark" "starkly" "startle" "startling" "startlingly" "starvation" "starve" "static" "steal" "stealing" "steals" "steep" "steeply" "stench" "stereotype" "stereotypical" "stereotypically" "stern" "stew" "sticky" "stiff" "stiffness" "stifle" "stifling" "stiflingly" "stigma" "stigmatize" "sting" "stinging" "stingingly" "stingy" "stink" "stinks" "stodgy" "stole" "stolen" "stooge" "stooges" "stormy" "straggle" "straggler" "strain" "strained" "straining" "strange" "strangely" "stranger" "strangest" "strangle" "streaky" "strenuous" "stress" "stresses" "stressful" "stressfully" "stricken" "strict" "strictly" "strident" "stridently" "strife" "strike" "stringent" "stringently" "struck" "struggle" "struggled" "struggles" "struggling" "strut" "stubborn" "stubbornly" "stubbornness" "stuck" "stuffy" "stumble" "stumbled" "stumbles" "stump" "stumped" "stumps" "stun" "stunt" "stunted" "stupid" "stupidest" "stupidity" "stupidly" "stupified" "stupify" "stupor" "stutter" "stuttered" "stuttering" "stutters" "sty" "stymied" "sub-par" "subdued" "subjected" "subjection" "subjugate" "subjugation" "submissive" "subordinate" "subpoena" "subpoenas" "subservience" "subservient" "substandard" "subtract" "subversion" "subversive" "subversively" "subvert" "succumb" "suck" "sucked" "sucker" "sucks" "sucky" "sue" "sued" "sueing" "sues" "suffer" "suffered" "sufferer" "sufferers" "suffering" "suffers" "suffocate" "sugar-coat" "sugar-coated" "sugarcoated" "suicidal" "suicide" "sulk" "sullen" "sully" "sunder" "sunk" "sunken" "superficial" "superficiality" "superficially" "superfluous" "superstition" "superstitious" "suppress" "suppression" "surrender" "susceptible" "suspect" "suspicion" "suspicions" "suspicious" "suspiciously" "swagger" "swamped" "sweaty" "swelled" "swelling" "swindle" "swipe" "swollen" "symptom" "symptoms" "syndrome" "taboo" "tacky" "taint" "tainted" "tamper" "tangle" "tangled" "tangles" "tank" "tanked" "tanks" "tantrum" "tardy" "tarnish" "tarnished" "tarnishes" "tarnishing" "tattered" "taunt" "taunting" "tauntingly" "taunts" "taut" "tawdry" "taxing" "tease" "teasingly" "tedious" "tediously" "temerity" "temper" "tempest" "temptation" "tenderness" "tense" "tension" "tentative" "tentatively" "tenuous" "tenuously" "tepid" "terrible" "terribleness" "terribly" "terror" "terror-genic" "terrorism" "terrorize" "testily" "testy" "tetchily" "tetchy" "thankless" "thicker" "thirst" "thorny" "thoughtless" "thoughtlessly" "thoughtlessness" "thrash" "threat" "threaten" "threatening" "threats" "threesome" "throb" "throbbed" "throbbing" "throbs" "throttle" "thug" "thumb-down" "thumbs-down" "thwart" "time-consuming" "timid" "timidity" "timidly" "timidness" "tin-y" "tingled" "tingling" "tired" "tiresome" "tiring" "tiringly" "toil" "toll" "top-heavy" "topple" "torment" "tormented" "torrent" "tortuous" "torture" "tortured" "tortures" "torturing" "torturous" "torturously" "totalitarian" "touchy" "toughness" "tout" "touted" "touts" "toxic" "traduce" "tragedy" "tragic" "tragically" "traitor" "traitorous" "traitorously" "tramp" "trample" "transgress" "transgression" "trap" "traped" "trapped" "trash" "trashed" "trashy" "trauma" "traumatic" "traumatically" "traumatize" "traumatized" "travesties" "travesty" "treacherous" "treacherously" "treachery" "treason" "treasonous" "trick" "tricked" "trickery" "tricky" "trivial" "trivialize" "trouble" "troubled" "troublemaker" "troubles" "troublesome" "troublesomely" "troubling" "troublingly" "truant" "tumble" "tumbled" "tumbles" "tumultuous" "turbulent" "turmoil" "twist" "twisted" "twists" "two-faced" "two-faces" "tyrannical" "tyrannically" "tyranny" "tyrant" "ugh" "uglier" "ugliest" "ugliness" "ugly" "ulterior" "ultimatum" "ultimatums" "ultra-hardline" "un-viewable" "unable" "unacceptable" "unacceptablely" "unacceptably" "unaccessible" "unaccustomed" "unachievable" "unaffordable" "unappealing" "unattractive" "unauthentic" "unavailable" "unavoidably" "unbearable" "unbearablely" "unbelievable" "unbelievably" "uncaring" "uncertain" "uncivil" "uncivilized" "unclean" "unclear" "uncollectible" "uncomfortable" "uncomfortably" "uncomfy" "uncompetitive" "uncompromising" "uncompromisingly" "unconfirmed" "unconstitutional" "uncontrolled" "unconvincing" "unconvincingly" "uncooperative" "uncouth" "uncreative" "undecided" "undefined" "undependability" "undependable" "undercut" "undercuts" "undercutting" "underdog" "underestimate" "underlings" "undermine" "undermined" "undermines" "undermining" "underpaid" "underpowered" "undersized" "undesirable" "undetermined" "undid" "undignified" "undissolved" "undocumented" "undone" "undue" "unease" "uneasily" "uneasiness" "uneasy" "uneconomical" "unemployed" "unequal" "unethical" "uneven" "uneventful" "unexpected" "unexpectedly" "unexplained" "unfairly" "unfaithful" "unfaithfully" "unfamiliar" "unfavorable" "unfeeling" "unfinished" "unfit" "unforeseen" "unforgiving" "unfortunate" "unfortunately" "unfounded" "unfriendly" "unfulfilled" "unfunded" "ungovernable" "ungrateful" "unhappily" "unhappiness" "unhappy" "unhealthy" "unhelpful" "unilateralism" "unimaginable" "unimaginably" "unimportant" "uninformed" "uninsured" "unintelligible" "unintelligile" "unipolar" "unjust" "unjustifiable" "unjustifiably" "unjustified" "unjustly" "unkind" "unkindly" "unknown" "unlamentable" "unlamentably" "unlawful" "unlawfully" "unlawfulness" "unleash" "unlicensed" "unlikely" "unlucky" "unmoved" "unnatural" "unnaturally" "unnecessary" "unneeded" "unnerve" "unnerved" "unnerving" "unnervingly" "unnoticed" "unobserved" "unorthodox" "unorthodoxy" "unpleasant" "unpleasantries" "unpopular" "unpredictable" "unprepared" "unproductive" "unprofitable" "unprove" "unproved" "unproven" "unproves" "unproving" "unqualified" "unravel" "unraveled" "unreachable" "unreadable" "unrealistic" "unreasonable" "unreasonably" "unrelenting" "unrelentingly" "unreliability" "unreliable" "unresolved" "unresponsive" "unrest" "unruly" "unsafe" "unsatisfactory" "unsavory" "unscrupulous" "unscrupulously" "unsecure" "unseemly" "unsettle" "unsettled" "unsettling" "unsettlingly" "unskilled" "unsophisticated" "unsound" "unspeakable" "unspeakablely" "unspecified" "unstable" "unsteadily" "unsteadiness" "unsteady" "unsuccessful" "unsuccessfully" "unsupported" "unsupportive" "unsure" "unsuspecting" "unsustainable" "untenable" "untested" "unthinkable" "unthinkably" "untimely" "untouched" "untrue" "untrustworthy" "untruthful" "unusable" "unusably" "unuseable" "unuseably" "unusual" "unusually" "unviewable" "unwanted" "unwarranted" "unwatchable" "unwelcome" "unwell" "unwieldy" "unwilling" "unwillingly" "unwillingness" "unwise" "unwisely" "unworkable" "unworthy" "unyielding" "upbraid" "upheaval" "uprising" "uproar" "uproarious" "uproariously" "uproarous" "uproarously" "uproot" "upset" "upseting" "upsets" "upsetting" "upsettingly" "urgent" "useless" "usurp" "usurper" "utterly" "vagrant" "vague" "vagueness" "vain" "vainly" "vanity" "vehement" "vehemently" "vengeance" "vengeful" "vengefully" "vengefulness" "venom" "venomous" "venomously" "vent" "vestiges" "vex" "vexation" "vexing" "vexingly" "vibrate" "vibrated" "vibrates" "vibrating" "vibration" "vice" "vicious" "viciously" "viciousness" "victimize" "vile" "vileness" "vilify" "villainous" "villainously" "villains" "villian" "villianous" "villianously" "villify" "vindictive" "vindictively" "vindictiveness" "violate" "violation" "violator" "violators" "violent" "violently" "viper" "virulence" "virulent" "virulently" "virus" "vociferous" "vociferously" "volatile" "volatility" "vomit" "vomited" "vomiting" "vomits" "vulgar" "vulnerable" "wack" "wail" "wallow" "wane" "waning" "wanton" "war-like" "warily" "wariness" "warlike" "warned" "warning" "warp" "warped" "wary" "washed-out" "waste" "wasted" "wasteful" "wastefulness" "wasting" "water-down" "watered-down" "wayward" "weak" "weaken" "weakening" "weaker" "weakness" "weaknesses" "weariness" "wearisome" "weary" "wedge" "weed" "weep" "weird" "weirdly" "wheedle" "whimper" "whine" "whining" "whiny" "whips" "whore" "whores" "wicked" "wickedly" "wickedness" "wild" "wildly" "wiles" "wilt" "wily" "wimpy" "wince" "wobble" "wobbled" "wobbles" "woe" "woebegone" "woeful" "woefully" "womanizer" "womanizing" "worn" "worried" "worriedly" "worrier" "worries" "worrisome" "worry" "worrying" "worryingly" "worse" "worsen" "worsening" "worst" "worthless" "worthlessly" "worthlessness" "wound" "wounds" "wrangle" "wrath" "wreak" "wreaked" "wreaks" "wreck" "wrest" "wrestle" "wretch" "wretched" "wretchedly" "wretchedness" "wrinkle" "wrinkled" "wrinkles" "wrip" "wripped" "wripping" "writhe" "wrong" "wrongful" "wrongly" "wrought" "yawn" "zap" "zapped" "zaps" "zealot" "zealous" "zealously" "zombie"}) (def pos #{"a+" "abound" "abounds" "abundance" "abundant" "accessable" "accessible" "acclaim" "acclaimed" "acclamation" "accolade" "accolades" "accommodative" "accomodative" "accomplish" "accomplished" "accomplishment" "accomplishments" "accurate" "accurately" "achievable" "achievement" "achievements" "achievible" "acumen" "adaptable" "adaptive" "adequate" "adjustable" "admirable" "admirably" "admiration" "admire" "admirer" "admiring" "admiringly" "adorable" "adore" "adored" "adorer" "adoring" "adoringly" "adroit" "adroitly" "adulate" "adulation" "adulatory" "advanced" "advantage" "advantageous" "advantageously" "advantages" "adventuresome" "adventurous" "advocate" "advocated" "advocates" "affability" "affable" "affably" "affectation" "affection" "affectionate" "affinity" "affirm" "affirmation" "affirmative" "affluence" "affluent" "afford" "affordable" "affordably" "afordable" "agile" "agilely" "agility" "agreeable" "agreeableness" "agreeably" "all-around" "alluring" "alluringly" "altruistic" "altruistically" "amaze" "amazed" "amazement" "amazes" "amazing" "amazingly" "ambitious" "ambitiously" "ameliorate" "amenable" "amenity" "amiability" "amiabily" "amiable" "amicability" "amicable" "amicably" "amity" "ample" "amply" "amuse" "amusing" "amusingly" "angel" "angelic" "apotheosis" "appeal" "appealing" "applaud" "appreciable" "appreciate" "appreciated" "appreciates" "appreciative" "appreciatively" "appropriate" "approval" "approve" "ardent" "ardently" "ardor" "articulate" "aspiration" "aspirations" "aspire" "assurance" "assurances" "assure" "assuredly" "assuring" "astonish" "astonished" "astonishing" "astonishingly" "astonishment" "astound" "astounded" "astounding" "astoundingly" "astutely" "attentive" "attraction" "attractive" "attractively" "attune" "audible" "audibly" "auspicious" "authentic" "authoritative" "autonomous" "available" "aver" "avid" "avidly" "award" "awarded" "awards" "awe" "awed" "awesome" "awesomely" "awesomeness" "awestruck" "awsome" "backbone" "balanced" "bargain" "beauteous" "beautiful" "beautifullly" "beautifully" "beautify" "beauty" "beckon" "beckoned" "beckoning" "beckons" "believable" "believeable" "beloved" "benefactor" "beneficent" "beneficial" "beneficially" "beneficiary" "benefit" "benefits" "benevolence" "benevolent" "benifits" "best" "best-known" "best-performing" "best-selling" "better" "better-known" "better-than-expected" "beutifully" "blameless" "bless" "blessing" "bliss" "blissful" "blissfully" "blithe" "blockbuster" "bloom" "blossom" "bolster" "bonny" "bonus" "bonuses" "boom" "booming" "boost" "boundless" "bountiful" "brainiest" "brainy" "brand-new" "brave" "bravery" "bravo" "breakthrough" "breakthroughs" "breathlessness" "breathtaking" "breathtakingly" "breeze" "bright" "brighten" "brighter" "brightest" "brilliance" "brilliances" "brilliant" "brilliantly" "brisk" "brotherly" "bullish" "buoyant" "cajole" "calm" "calming" "calmness" "capability" "capable" "capably" "captivate" "captivating" "carefree" "cashback" "cashbacks" "catchy" "celebrate" "celebrated" "celebration" "celebratory" "champ" "champion" "charisma" "charismatic" "charitable" "charm" "charming" "charmingly" "chaste" "cheaper" "cheapest" "cheer" "cheerful" "cheery" "cherish" "cherished" "cherub" "chic" "chivalrous" "chivalry" "civility" "civilize" "clarity" "classic" "classy" "clean" "cleaner" "cleanest" "cleanliness" "cleanly" "clear" "clear-cut" "cleared" "clearer" "clearly" "clears" "clever" "cleverly" "cohere" "coherence" "coherent" "cohesive" "colorful" "comely" "comfort" "comfortable" "comfortably" "comforting" "comfy" "commend" "commendable" "commendably" "commitment" "commodious" "compact" "compactly" "compassion" "compassionate" "compatible" "competitive" "complement" "complementary" "complemented" "complements" "compliant" "compliment" "complimentary" "comprehensive" "conciliate" "conciliatory" "concise" "confidence" "confident" "congenial" "congratulate" "congratulation" "congratulations" "congratulatory" "conscientious" "considerate" "consistent" "consistently" "constructive" "consummate" "contentment" "continuity" "contrasty" "contribution" "convenience" "convenient" "conveniently" "convience" "convienient" "convient" "convincing" "convincingly" "cool" "coolest" "cooperative" "cooperatively" "cornerstone" "correct" "correctly" "cost-effective" "cost-saving" "counter-attack" "counter-attacks" "courage" "courageous" "courageously" "courageousness" "courteous" "courtly" "covenant" "cozy" "creative" "credence" "credible" "crisp" "crisper" "cure" "cure-all" "cushy" "cute" "cuteness" "danke" "danken" "daring" "daringly" "darling" "dashing" "dauntless" "dawn" "dazzle" "dazzled" "dazzling" "dead-cheap" "dead-on" "decency" "decent" "decisive" "decisiveness" "dedicated" "defeat" "defeated" "defeating" "defeats" "defender" "deference" "deft" "deginified" "delectable" "delicacy" "delicate" "delicious" "delight" "delighted" "delightful" "delightfully" "delightfulness" "dependable" "dependably" "deservedly" "deserving" "desirable" "desiring" "desirous" "destiny" "detachable" "devout" "dexterous" "dexterously" "dextrous" "dignified" "dignify" "dignity" "diligence" "diligent" "diligently" "diplomatic" "dirt-cheap" "distinction" "distinctive" "distinguished" "diversified" "divine" "divinely" "dominate" "dominated" "dominates" "dote" "dotingly" "doubtless" "dreamland" "dumbfounded" "dumbfounding" "dummy-proof" "durable" "dynamic" "eager" "eagerly" "eagerness" "earnest" "earnestly" "earnestness" "ease" "eased" "eases" "easier" "easiest" "easiness" "easing" "easy" "easy-to-use" "easygoing" "ebullience" "ebullient" "ebulliently" "ecenomical" "economical" "ecstasies" "ecstasy" "ecstatic" "ecstatically" "edify" "educated" "effective" "effectively" "effectiveness" "effectual" "efficacious" "efficient" "efficiently" "effortless" "effortlessly" "effusion" "effusive" "effusively" "effusiveness" "elan" "elate" "elated" "elatedly" "elation" "electrify" "elegance" "elegant" "elegantly" "elevate" "elite" "eloquence" "eloquent" "eloquently" "embolden" "eminence" "eminent" "empathize" "empathy" "empower" "empowerment" "enchant" "enchanted" "enchanting" "enchantingly" "encourage" "encouragement" "encouraging" "encouragingly" "endear" "endearing" "endorse" "endorsed" "endorsement" "endorses" "endorsing" "energetic" "energize" "energy-efficient" "energy-saving" "engaging" "engrossing" "enhance" "enhanced" "enhancement" "enhances" "enjoy" "enjoyable" "enjoyably" "enjoyed" "enjoying" "enjoyment" "enjoys" "enlighten" "enlightenment" "enliven" "ennoble" "enough" "enrapt" "enrapture" "enraptured" "enrich" "enrichment" "enterprising" "entertain" "entertaining" "entertains" "enthral" "enthrall" "enthralled" "enthuse" "enthusiasm" "enthusiast" "enthusiastic" "enthusiastically" "entice" "enticed" "enticing" "enticingly" "entranced" "entrancing" "entrust" "enviable" "enviably" "envious" "enviously" "enviousness" "envy" "equitable" "ergonomical" "err-free" "erudite" "ethical" "eulogize" "euphoria" "euphoric" "euphorically" "evaluative" "evenly" "eventful" "everlasting" "evocative" "exalt" "exaltation" "exalted" "exaltedly" "exalting" "exaltingly" "examplar" "examplary" "excallent" "exceed" "exceeded" "exceeding" "exceedingly" "exceeds" "excel" "exceled" "excelent" "excellant" "excelled" "excellence" "excellency" "excellent" "excellently" "excels" "exceptional" "exceptionally" "excite" "excited" "excitedly" "excitedness" "excitement" "excites" "exciting" "excitingly" "exellent" "exemplar" "exemplary" "exhilarate" "exhilarating" "exhilaratingly" "exhilaration" "exonerate" "expansive" "expeditiously" "expertly" "exquisite" "exquisitely" "extol" "extoll" "extraordinarily" "extraordinary" "exuberance" "exuberant" "exuberantly" "exult" "exultant" "exultation" "exultingly" "eye-catch" "eye-catching" "eyecatch" "eyecatching" "fabulous" "fabulously" "facilitate" "fair" "fairly" "fairness" "faith" "faithful" "faithfully" "faithfulness" "fame" "famed" "famous" "famously" "fancier" "fancinating" "fancy" "fanfare" "fans" "fantastic" "fantastically" "fascinate" "fascinating" "fascinatingly" "fascination" "fashionable" "fashionably" "fast" "fast-growing" "fast-paced" "faster" "fastest" "fastest-growing" "faultless" "fav" "fave" "favor" "favorable" "favored" "favorite" "favorited" "favour" "fearless" "fearlessly" "feasible" "feasibly" "feat" "feature-rich" "fecilitous" "feisty" "felicitate" "felicitous" "felicity" "fertile" "fervent" "fervently" "fervid" "fervidly" "fervor" "festive" "fidelity" "fiery" "fine" "fine-looking" "finely" "finer" "finest" "firmer" "first-class" "first-in-class" "first-rate" "flashy" "flatter" "flattering" "flatteringly" "flawless" "flawlessly" "flexibility" "flexible" "flourish" "flourishing" "fluent" "flutter" "fond" "fondly" "fondness" "foolproof" "foremost" "foresight" "formidable" "fortitude" "fortuitous" "fortuitously" "fortunate" "fortunately" "fortune" "fragrant" "free" "freed" "freedom" "freedoms" "fresh" "fresher" "freshest" "friendliness" "friendly" "frolic" "frugal" "fruitful" "ftw" "fulfillment" "fun" "futurestic" "futuristic" "gaiety" "gaily" "gain" "gained" "gainful" "gainfully" "gaining" "gains" "gallant" "gallantly" "galore" "geekier" "geeky" "gem" "gems" "generosity" "generous" "generously" "genial" "genius" "gentle" "gentlest" "genuine" "gifted" "glad" "gladden" "gladly" "gladness" "glamorous" "glee" "gleeful" "gleefully" "glimmer" "glimmering" "glisten" "glistening" "glitter" "glitz" "glorify" "glorious" "gloriously" "glory" "glow" "glowing" "glowingly" "god-given" "god-send" "godlike" "godsend" "gold" "golden" "good" "goodly" "goodness" "goodwill" "goood" "gooood" "gorgeous" "gorgeously" "grace" "graceful" "gracefully" "gracious" "graciously" "graciousness" "grand" "grandeur" "grateful" "gratefully" "gratification" "gratified" "gratifies" "gratify" "gratifying" "gratifyingly" "gratitude" "great" "greatest" "greatness" "grin" "groundbreaking" "guarantee" "guidance" "guiltless" "gumption" "gush" "gusto" "gutsy" "hail" "halcyon" "hale" "hallmark" "hallmarks" "hallowed" "handier" "handily" "hands-down" "handsome" "handsomely" "handy" "happier" "happily" "happiness" "happy" "hard-working" "hardier" "hardy" "harmless" "harmonious" "harmoniously" "harmonize" "harmony" "headway" "heal" "healthful" "healthy" "hearten" "heartening" "heartfelt" "heartily" "heartwarming" "heaven" "heavenly" "helped" "helpful" "helping" "hero" "heroic" "heroically" "heroine" "heroize" "heros" "high-quality" "high-spirited" "hilarious" "holy" "homage" "honest" "honesty" "honor" "honorable" "honored" "honoring" "hooray" "hopeful" "hospitable" "hot" "hotcake" "hotcakes" "hottest" "hug" "humane" "humble" "humility" "humor" "humorous" "humorously" "humour" "humourous" "ideal" "idealize" "ideally" "idol" "idolize" "idolized" "idyllic" "illuminate" "illuminati" "illuminating" "illumine" "illustrious" "ilu" "imaculate" "imaginative" "immaculate" "immaculately" "immense" "impartial" "impartiality" "impartially" "impassioned" "impeccable" "impeccably" "important" "impress" "impressed" "impresses" "impressive" "impressively" "impressiveness" "improve" "improved" "improvement" "improvements" "improves" "improving" "incredible" "incredibly" "indebted" "individualized" "indulgence" "indulgent" "industrious" "inestimable" "inestimably" "inexpensive" "infallibility" "infallible" "infallibly" "influential" "ingenious" "ingeniously" "ingenuity" "ingenuous" "ingenuously" "innocuous" "innovation" "innovative" "inpressed" "insightful" "insightfully" "inspiration" "inspirational" "inspire" "inspiring" "instantly" "instructive" "instrumental" "integral" "integrated" "intelligence" "intelligent" "intelligible" "interesting" "interests" "intimacy" "intimate" "intricate" "intrigue" "intriguing" "intriguingly" "intuitive" "invaluable" "invaluablely" "inventive" "invigorate" "invigorating" "invincibility" "invincible" "inviolable" "inviolate" "invulnerable" "irreplaceable" "irreproachable" "irresistible" "irresistibly" "issue-free" "jaw-droping" "jaw-dropping" "jollify" "jolly" "jovial" "joy" "joyful" "joyfully" "joyous" "joyously" "jubilant" "jubilantly" "jubilate" "jubilation" "jubiliant" "judicious" "justly" "keen" "keenly" "keenness" "kid-friendly" "kindliness" "kindly" "kindness" "knowledgeable" "kudos" "large-capacity" "laud" "laudable" "laudably" "lavish" "lavishly" "law-abiding" "lawful" "lawfully" "lead" "leading" "leads" "lean" "led" "legendary" "leverage" "levity" "liberate" "liberation" "liberty" "lifesaver" "light-hearted" "lighter" "likable" "like" "liked" "likes" "liking" "lionhearted" "lively" "logical" "long-lasting" "lovable" "lovably" "love" "loved" "loveliness" "lovely" "lover" "loves" "loving" "low-cost" "low-price" "low-priced" "low-risk" "lower-priced" "loyal" "loyalty" "lucid" "lucidly" "luck" "luckier" "luckiest" "luckiness" "lucky" "lucrative" "luminous" "lush" "luster" "lustrous" "luxuriant" "luxuriate" "luxurious" "luxuriously" "luxury" "lyrical" "magic" "magical" "magnanimous" "magnanimously" "magnificence" "magnificent" "magnificently" "majestic" "majesty" "manageable" "maneuverable" "marvel" "marveled" "marvelled" "marvellous" "marvelous" "marvelously" "marvelousness" "marvels" "master" "masterful" "masterfully" "masterpiece" "masterpieces" "masters" "mastery" "matchless" "mature" "maturely" "maturity" "meaningful" "memorable" "merciful" "mercifully" "mercy" "merit" "meritorious" "merrily" "merriment" "merriness" "merry" "mesmerize" "mesmerized" "mesmerizes" "mesmerizing" "mesmerizingly" "meticulous" "meticulously" "mightily" "mighty" "mind-blowing" "miracle" "miracles" "miraculous" "miraculously" "miraculousness" "modern" "modest" "modesty" "momentous" "monumental" "monumentally" "morality" "motivated" "multi-purpose" "navigable" "neat" "neatest" "neatly" "nice" "nicely" "nicer" "nicest" "nifty" "nimble" "noble" "nobly" "noiseless" "non-violence" "non-violent" "notably" "noteworthy" "nourish" "nourishing" "nourishment" "novelty" "nurturing" "oasis" "obsession" "obsessions" "obtainable" "openly" "openness" "optimal" "optimism" "optimistic" "opulent" "orderly" "originality" "outdo" "outdone" "outperform" "outperformed" "outperforming" "outperforms" "outshine" "outshone" "outsmart" "outstanding" "outstandingly" "outstrip" "outwit" "ovation" "overjoyed" "overtake" "overtaken" "overtakes" "overtaking" "overtook" "overture" "pain-free" "painless" "painlessly" "palatial" "pamper" "pampered" "pamperedly" "pamperedness" "pampers" "panoramic" "paradise" "paramount" "pardon" "passion" "passionate" "passionately" "patience" "patient" "patiently" "patriot" "patriotic" "peace" "peaceable" "peaceful" "peacefully" "peacekeepers" "peach" "peerless" "pep" "pepped" "pepping" "peppy" "peps" "perfect" "perfection" "perfectly" "permissible" "perseverance" "persevere" "personages" "personalized" "phenomenal" "phenomenally" "picturesque" "piety" "pinnacle" "playful" "playfully" "pleasant" "pleasantly" "pleased" "pleases" "pleasing" "pleasingly" "pleasurable" "pleasurably" "pleasure" "plentiful" "pluses" "plush" "plusses" "poetic" "poeticize" "poignant" "poise" "poised" "polished" "polite" "politeness" "popular" "portable" "posh" "positive" "positively" "positives" "powerful" "powerfully" "praise" "praiseworthy" "praising" "pre-eminent" "precious" "precise" "precisely" "preeminent" "prefer" "preferable" "preferably" "prefered" "preferes" "preferring" "prefers" "premier" "prestige" "prestigious" "prettily" "pretty" "priceless" "pride" "principled" "privilege" "privileged" "prize" "proactive" "problem-free" "problem-solver" "prodigious" "prodigiously" "prodigy" "productive" "productively" "proficient" "proficiently" "profound" "profoundly" "profuse" "profusion" "progress" "progressive" "prolific" "prominence" "prominent" "promise" "promised" "promises" "promising" "promoter" "prompt" "promptly" "proper" "properly" "propitious" "propitiously" "pros" "prosper" "prosperity" "prosperous" "prospros" "protect" "protection" "protective" "proud" "proven" "proves" "providence" "proving" "prowess" "prudence" "prudent" "prudently" "punctual" "pure" "purify" "purposeful" "quaint" "qualified" "qualify" "quicker" "quiet" "quieter" "radiance" "radiant" "rapid" "rapport" "rapt" "rapture" "raptureous" "raptureously" "rapturous" "rapturously" "rational" "razor-sharp" "reachable" "readable" "readily" "ready" "reaffirm" "reaffirmation" "realistic" "realizable" "reasonable" "reasonably" "reasoned" "reassurance" "reassure" "receptive" "reclaim" "recomend" "recommend" "recommendation" "recommendations" "recommended" "reconcile" "reconciliation" "record-setting" "recover" "recovery" "rectification" "rectify" "rectifying" "redeem" "redeeming" "redemption" "refine" "refined" "refinement" "reform" "reformed" "reforming" "reforms" "refresh" "refreshed" "refreshing" "refund" "refunded" "regal" "regally" "regard" "rejoice" "rejoicing" "rejoicingly" "rejuvenate" "rejuvenated" "rejuvenating" "relaxed" "relent" "reliable" "reliably" "relief" "relish" "remarkable" "remarkably" "remedy" "remission" "remunerate" "renaissance" "renewed" "renown" "renowned" "replaceable" "reputable" "reputation" "resilient" "resolute" "resound" "resounding" "resourceful" "resourcefulness" "respect" "respectable" "respectful" "respectfully" "respite" "resplendent" "responsibly" "responsive" "restful" "restored" "restructure" "restructured" "restructuring" "retractable" "revel" "revelation" "revere" "reverence" "reverent" "reverently" "revitalize" "revival" "revive" "revives" "revolutionary" "revolutionize" "revolutionized" "revolutionizes" "reward" "rewarding" "rewardingly" "rich" "richer" "richly" "richness" "right" "righten" "righteous" "righteously" "righteousness" "rightful" "rightfully" "rightly" "rightness" "risk-free" "robust" "rock-star" "rock-stars" "rockstar" "rockstars" "romantic" "romantically" "romanticize" "roomier" "roomy" "rosy" "safe" "safely" "sagacity" "sagely" "saint" "saintliness" "saintly" "salutary" "salute" "sane" "satisfactorily" "satisfactory" "satisfied" "satisfies" "satisfy" "satisfying" "satisified" "saver" "savings" "savior" "savvy" "scenic" "seamless" "seasoned" "secure" "securely" "selective" "self-determination" "self-respect" "self-satisfaction" "self-sufficiency" "self-sufficient" "sensation" "sensational" "sensationally" "sensations" "sensible" "sensibly" "sensitive" "serene" "serenity" "sexy" "sharp" "sharper" "sharpest" "shimmering" "shimmeringly" "shine" "shiny" "significant" "silent" "simpler" "simplest" "simplified" "simplifies" "simplify" "simplifying" "sincere" "sincerely" "sincerity" "skill" "skilled" "skillful" "skillfully" "slammin" "sleek" "slick" "smart" "smarter" "smartest" "smartly" "smile" "smiles" "smiling" "smilingly" "smitten" "smooth" "smoother" "smoothes" "smoothest" "smoothly" "snappy" "snazzy" "sociable" "soft" "softer" "solace" "solicitous" "solicitously" "solid" "solidarity" "soothe" "soothingly" "sophisticated" "soulful" "soundly" "soundness" "spacious" "sparkle" "sparkling" "spectacular" "spectacularly" "speedily" "speedy" "spellbind" "spellbinding" "spellbindingly" "spellbound" "spirited" "spiritual" "splendid" "splendidly" "splendor" "spontaneous" "sporty" "spotless" "sprightly" "stability" "stabilize" "stable" "stainless" "standout" "state-of-the-art" "stately" "statuesque" "staunch" "staunchly" "staunchness" "steadfast" "steadfastly" "steadfastness" "steadiest" "steadiness" "steady" "stellar" "stellarly" "stimulate" "stimulates" "stimulating" "stimulative" "stirringly" "straighten" "straightforward" "streamlined" "striking" "strikingly" "striving" "strong" "stronger" "strongest" "stunned" "stunning" "stunningly" "stupendous" "stupendously" "sturdier" "sturdy" "stylish" "stylishly" "stylized" "suave" "suavely" "sublime" "subsidize" "subsidized" "subsidizes" "subsidizing" "substantive" "succeed" "succeeded" "succeeding" "succeeds" "succes" "success" "successes" "successful" "successfully" "suffice" "sufficed" "suffices" "sufficient" "sufficiently" "suitable" "sumptuous" "sumptuously" "sumptuousness" "super" "superb" "superbly" "superior" "superiority" "supple" "support" "supported" "supporter" "supporting" "supportive" "supports" "supremacy" "supreme" "supremely" "supurb" "supurbly" "surmount" "surpass" "surreal" "survival" "survivor" "sustainability" "sustainable" "swank" "swankier" "swankiest" "swanky" "sweeping" "sweet" "sweeten" "sweetheart" "sweetly" "sweetness" "swift" "swiftness" "talent" "talented" "talents" "tantalize" "tantalizing" "tantalizingly" "tempt" "tempting" "temptingly" "tenacious" "tenaciously" "tenacity" "tender" "tenderly" "terrific" "terrifically" "thank" "thankful" "thinner" "thoughtful" "thoughtfully" "thoughtfulness" "thrift" "thrifty" "thrill" "thrilled" "thrilling" "thrillingly" "thrills" "thrive" "thriving" "thumb-up" "thumbs-up" "tickle" "tidy" "time-honored" "timely" "tingle" "titillate" "titillating" "titillatingly" "togetherness" "tolerable" "toll-free" "top" "top-notch" "top-quality" "topnotch" "tops" "tough" "tougher" "toughest" "traction" "tranquil" "tranquility" "transparent" "treasure" "tremendously" "trendy" "triumph" "triumphal" "triumphant" "triumphantly" "trivially" "trophy" "trouble-free" "trump" "trumpet" "trust" "trusted" "trusting" "trustingly" "trustworthiness" "trustworthy" "trusty" "truthful" "truthfully" "truthfulness" "twinkly" "ultra-crisp" "unabashed" "unabashedly" "unaffected" "unassailable" "unbeatable" "unbiased" "unbound" "uncomplicated" "unconditional" "undamaged" "undaunted" "understandable" "undisputable" "undisputably" "undisputed" "unencumbered" "unequivocal" "unequivocally" "unfazed" "unfettered" "unforgettable" "unity" "unlimited" "unmatched" "unparalleled" "unquestionable" "unquestionably" "unreal" "unrestricted" "unrivaled" "unselfish" "unwavering" "upbeat" "upgradable" "upgradeable" "upgraded" "upheld" "uphold" "uplift" "uplifting" "upliftingly" "upliftment" "upscale" "usable" "useable" "useful" "user-friendly" "user-replaceable" "valiant" "valiantly" "valor" "valuable" "variety" "venerate" "verifiable" "veritable" "versatile" "versatility" "vibrant" "vibrantly" "victorious" "victory" "viewable" "vigilance" "vigilant" "virtue" "virtuous" "virtuously" "visionary" "vivacious" "vivid" "vouch" "vouchsafe" "warm" "warmer" "warmhearted" "warmly" "warmth" "wealthy" "welcome" "well" "well-backlit" "well-balanced" "well-behaved" "well-being" "well-bred" "well-connected" "well-educated" "well-established" "well-informed" "well-intentioned" "well-known" "well-made" "well-managed" "well-mannered" "well-positioned" "well-received" "well-regarded" "well-rounded" "well-run" "well-wishers" "wellbeing" "whoa" "wholeheartedly" "wholesome" "whooa" "whoooa" "wieldy" "willing" "willingly" "willingness" "win" "windfall" "winnable" "winner" "winners" "winning" "wins" "wisdom" "wise" "wisely" "witty" "won" "wonder" "wonderful" "wonderfully" "wonderous" "wonderously" "wonders" "wondrous" "woo" "work" "workable" "worked" "works" "world-famous" "worth" "worth-while" "worthiness" "worthwhile" "worthy" "wow" "wowed" "wowing" "wows" "yay" "youthful" "zeal" "zenith" "zest" "zippy"})
46595
(ns plugh.util.sent-analysis (:require [clojure.string :as str] [clojure.core.async :as async])) (declare pos neg) (defn calc-sentiment [line] (let [splits (str/split (str/lower-case (str/replace (str/replace line #"\p{Punct}" " ") #"\p{Cntrl}" " ")) #" +")] {:pos (count (filter pos splits)) :neg (* -1 (count (filter neg splits)))} )) (defn xform [the-func the-chan] (async/map< (fn [z] (do ;; (println "Xform from " z " to " (the-func z)) (the-func z))) the-chan)) (defn xfilter [the-func the-chan] (async/filter< (fn [z] (do ;; (println "Filtering incoming value " z) (the-func z))) the-chan)) (defn flow [the-func seed the-chan] (let [cur-val (atom seed)] (async/map< (fn [mv] (let [new-val (the-func @cur-val mv)] (reset! cur-val new-val) new-val)) the-chan))) (defn arrow-update-func [the-var func-map] (reduce (fn [cur v] (let [[the-key the-func] v] (assoc cur the-key (the-func (the-key cur))))) the-var (into [] func-map))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; Opinion Lexicon: Negative & Positive ; ; This file contains a list of NEGATIVE and POSITIVE opinion words (or sentiment words). ; Copied from https://github.com/redmonk/bluebird ; ; This file and the papers can all be downloaded from ; http://www.cs.uic.edu/~liub/FBS/sentiment-analysis.html ; ; If you use this list, please cite one of the following two papers: ; ; <NAME> and <NAME>. "Mining and Summarizing Customer Reviews." ; Proceedings of the ACM SIGKDD International Conference on Knowledge ; Discovery and Data Mining (KDD-2004), Aug 22-25, 2004, Seattle, ; Washington, USA, ; <NAME>, <NAME> and <NAME>. "Opinion Observer: Analyzing ; and Comparing Opinions on the Web." Proceedings of the 14th ; International World Wide Web conference (WWW-2005), May 10-14, ; 2005, Chiba, Japan. ; ; Notes: ; 1. The appearance of an opinion word in a sentence does not necessarily ; mean that the sentence expresses a positive or negative opinion. ; See the paper below: ; ; <NAME>. "Sentiment Analysis and Subjectivity." An chapter in ; Handbook of Natural Language Processing, Second Edition, ; (editors: <NAME> and <NAME>), 2010. ; ; 2. You will notice many misspelled words in the list. They are not ; mistakes. They are included as these misspelled words appear ; frequently in social media content. ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def neg #{"2-faced" "2-faces" "abnormal" "abolish" "abominable" "abominably" "abominate" "abomination" "abort" "aborted" "aborts" "abrade" "abrasive" "abrupt" "abruptly" "abscond" "absence" "absent-minded" "absentee" "absurd" "absurdity" "absurdly" "absurdness" "abuse" "abused" "abuses" "abusive" "abysmal" "abysmally" "abyss" "accidental" "accost" "accursed" "accusation" "accusations" "accuse" "accuses" "accusing" "accusingly" "acerbate" "acerbic" "acerbically" "ache" "ached" "aches" "achey" "aching" "acrid" "acridly" "acridness" "acrimonious" "acrimoniously" "acrimony" "adamant" "adamantly" "addict" "addicted" "addicting" "addicts" "admonish" "admonisher" "admonishingly" "admonishment" "admonition" "adulterate" "adulterated" "adulteration" "adulterier" "adversarial" "adversary" "adverse" "adversity" "afflict" "affliction" "afflictive" "affront" "afraid" "aggravate" "aggravating" "aggravation" "aggression" "aggressive" "aggressiveness" "aggressor" "aggrieve" "aggrieved" "aggrivation" "aghast" "agonies" "agonize" "agonizing" "agonizingly" "agony" "aground" "ail" "ailing" "ailment" "aimless" "alarm" "alarmed" "alarming" "alarmingly" "alienate" "alienated" "alienation" "allegation" "allegations" "allege" "allergic" "allergies" "allergy" "aloof" "altercation" "ambiguity" "ambiguous" "ambivalence" "ambivalent" "ambush" "amiss" "amputate" "anarchism" "anarchist" "anarchistic" "anarchy" "anemic" "anger" "angrily" "angriness" "angry" "anguish" "animosity" "annihilate" "annihilation" "annoy" "annoyance" "annoyances" "annoyed" "annoying" "annoyingly" "annoys" "anomalous" "anomaly" "antagonism" "antagonist" "antagonistic" "antagonize" "anti-" "anti-american" "anti-israeli" "anti-occupation" "anti-proliferation" "anti-semites" "anti-social" "anti-us" "anti-white" "antipathy" "antiquated" "antithetical" "anxieties" "anxiety" "anxious" "anxiously" "anxiousness" "apathetic" "apathetically" "apathy" "apocalypse" "apocalyptic" "apologist" "apologists" "appal" "appall" "appalled" "appalling" "appallingly" "apprehension" "apprehensions" "apprehensive" "apprehensively" "arbitrary" "arcane" "archaic" "arduous" "arduously" "argumentative" "arrogance" "arrogant" "arrogantly" "ashamed" "asinine" "asininely" "asinininity" "askance" "asperse" "aspersion" "aspersions" "assail" "assassin" "assassinate" "assault" "assult" "astray" "asunder" "atrocious" "atrocities" "atrocity" "atrophy" "attack" "attacks" "audacious" "audaciously" "audaciousness" "audacity" "audiciously" "austere" "authoritarian" "autocrat" "autocratic" "avalanche" "avarice" "avaricious" "avariciously" "avenge" "averse" "aversion" "aweful" "awful" "awfully" "awfulness" "awkward" "awkwardness" "ax" "babble" "back-logged" "back-wood" "back-woods" "backache" "backaches" "backaching" "backbite" "backbiting" "backward" "backwardness" "backwood" "backwoods" "bad" "badly" "baffle" "baffled" "bafflement" "baffling" "bait" "balk" "banal" "banalize" "bane" "banish" "banishment" "bankrupt" "barbarian" "barbaric" "barbarically" "barbarity" "barbarous" "barbarously" "barren" "baseless" "bash" "bashed" "bashful" "bashing" "bastard" "bastards" "battered" "battering" "batty" "bearish" "beastly" "bedlam" "bedlamite" "befoul" "beg" "beggar" "beggarly" "begging" "beguile" "belabor" "belated" "beleaguer" "belie" "belittle" "belittled" "belittling" "bellicose" "belligerence" "belligerent" "belligerently" "bemoan" "bemoaning" "bemused" "bent" "berate" "bereave" "bereavement" "bereft" "berserk" "beseech" "beset" "besiege" "besmirch" "bestial" "betray" "betrayal" "betrayals" "betrayer" "betraying" "betrays" "bewail" "beware" "bewilder" "bewildered" "bewildering" "bewilderingly" "bewilderment" "bewitch" "bias" "biased" "biases" "bicker" "bickering" "bid-rigging" "bigotries" "bigotry" "bitch" "bitchy" "biting" "bitingly" "bitter" "bitterly" "bitterness" "bizarre" "blab" "blabber" "blackmail" "blah" "blame" "blameworthy" "bland" "blandish" "blaspheme" "blasphemous" "blasphemy" "blasted" "blatant" "blatantly" "blather" "bleak" "bleakly" "bleakness" "bleed" "bleeding" "bleeds" "blemish" "blind" "blinding" "blindingly" "blindside" "blister" "blistering" "bloated" "blockage" "blockhead" "bloodshed" "bloodthirsty" "bloody" "blotchy" "blow" "blunder" "blundering" "blunders" "blunt" "blur" "bluring" "blurred" "blurring" "blurry" "blurs" "blurt" "boastful" "boggle" "bogus" "boil" "boiling" "boisterous" "bomb" "bombard" "bombardment" "bombastic" "bondage" "bon<NAME>" "bore" "bored" "boredom" "bores" "boring" "botch" "bother" "bothered" "bothering" "bothers" "bothersome" "bowdlerize" "boycott" "br<NAME>" "bragger" "brainless" "brainwash" "brash" "brashly" "brashness" "brat" "bravado" "brazen" "brazenly" "brazenness" "breach" "break" "break-up" "break-ups" "breakdown" "breaking" "breaks" "breakup" "breakups" "bribery" "brimstone" "bristle" "brittle" "broke" "broken" "broken-hearted" "brood" "browbeat" "bruise" "bruised" "bruises" "bruising" "brusque" "brutal" "brutalising" "brutalities" "brutality" "brutalize" "brutalizing" "brutally" "brute" "brutish" "bs" "buckle" "bug" "bugging" "buggy" "bugs" "bulkier" "bulkiness" "bulky" "bulkyness" "bull****" "bull----" "bullies" "bullshit" "bullshyt" "bully" "bullying" "bullyingly" "bum" "bump" "bumped" "bumping" "bumpping" "bumps" "bumpy" "bungle" "bungler" "bungling" "bunk" "burden" "burdensome" "burdensomely" "burn" "burned" "burning" "burns" "bust" "busts" "busybody" "butcher" "butchery" "buzzing" "byzantine" "cackle" "calamities" "calamitous" "calamitously" "calamity" "callous" "calumniate" "calumniation" "calumnies" "calumnious" "calumniously" "calumny" "cancer" "cancerous" "cannibal" "cannibalize" "capitulate" "capricious" "capriciously" "capriciousness" "capsize" "careless" "carelessness" "caricature" "carnage" "carp" "cartoonish" "cash-strapped" "castigate" "castrated" "casualty" "cataclysm" "cataclysmal" "cataclysmic" "cataclysmically" "catastrophe" "catastrophes" "catastrophic" "catastrophically" "catastrophies" "caustic" "caustically" "cautionary" "cave" "censure" "chafe" "chaff" "chagrin" "challenging" "chaos" "chaotic" "chasten" "chastise" "chastisement" "chatter" "chatterbox" "cheap" "cheapen" "cheaply" "cheat" "cheated" "cheater" "cheating" "cheats" "checkered" "cheerless" "cheesy" "chide" "childish" "chill" "chilly" "chintzy" "choke" "choleric" "choppy" "chore" "chronic" "chunky" "clamor" "clamorous" "clash" "cliche" "cliched" "clique" "clog" "clogged" "clogs" "cloud" "clouding" "cloudy" "clueless" "clumsy" "clunky" "coarse" "cocky" "coerce" "coercion" "coercive" "cold" "coldly" "collapse" "collude" "collusion" "combative" "combust" "comical" "commiserate" "commonplace" "commotion" "commotions" "complacent" "complain" "complained" "complaining" "complains" "complaint" "complaints" "complex" "complicated" "complication" "complicit" "compulsion" "compulsive" "concede" "conceded" "conceit" "conceited" "concen" "concens" "concern" "concerned" "concerns" "concession" "concessions" "condemn" "condemnable" "condemnation" "condemned" "condemns" "condescend" "condescending" "condescendingly" "condescension" "confess" "confession" "confessions" "confined" "conflict" "conflicted" "conflicting" "conflicts" "confound" "confounded" "confounding" "confront" "confrontation" "confrontational" "confuse" "confused" "confuses" "confusing" "confusion" "confusions" "congested" "congestion" "cons" "conscons" "conservative" "conspicuous" "conspicuously" "conspiracies" "conspiracy" "conspirator" "conspiratorial" "conspire" "consternation" "contagious" "contaminate" "contaminated" "contaminates" "contaminating" "contamination" "contempt" "contemptible" "contemptuous" "contemptuously" "contend" "contention" "contentious" "contort" "contortions" "contradict" "contradiction" "contradictory" "contrariness" "contravene" "contrive" "contrived" "controversial" "controversy" "convoluted" "corrode" "corrosion" "corrosions" "corrosive" "corrupt" "corrupted" "corrupting" "corruption" "corrupts" "corruptted" "costlier" "costly" "counter-productive" "counterproductive" "coupists" "covetous" "coward" "cowardly" "crabby" "crack" "cracked" "cracks" "craftily" "craftly" "crafty" "cramp" "cramped" "cramping" "cranky" "crap" "crappy" "craps" "crash" "crashed" "crashes" "crashing" "crass" "craven" "cravenly" "craze" "crazily" "craziness" "crazy" "creak" "creaking" "creaks" "credulous" "creep" "creeping" "creeps" "creepy" "crept" "crime" "criminal" "cringe" "cringed" "cringes" "cripple" "crippled" "cripples" "crippling" "crisis" "critic" "critical" "criticism" "criticisms" "criticize" "criticized" "criticizing" "critics" "cronyism" "crook" "crooked" "crooks" "crowded" "crowdedness" "crude" "cruel" "crueler" "cruelest" "cruelly" "cruelness" "cruelties" "cruelty" "crumble" "crumbling" "crummy" "crumple" "crumpled" "crumples" "crush" "crushed" "crushing" "cry" "culpable" "culprit" "cumbersome" "cunt" "cunts" "cuplrit" "curse" "cursed" "curses" "curt" "cuss" "cussed" "cutthroat" "cynical" "cynicism" "d*mn" "damage" "damaged" "damages" "damaging" "damn" "damnable" "damnably" "damnation" "damned" "damning" "damper" "danger" "dangerous" "dangerousness" "dark" "darken" "darkened" "darker" "darkness" "dastard" "dastardly" "daunt" "daunting" "dauntingly" "dawdle" "daze" "dazed" "dead" "deadbeat" "deadlock" "deadly" "deadweight" "deaf" "dearth" "death" "debacle" "debase" "debasement" "debaser" "debatable" "debauch" "debaucher" "debauchery" "debilitate" "debilitating" "debility" "debt" "debts" "decadence" "decadent" "decay" "decayed" "deceit" "deceitful" "deceitfully" "deceitfulness" "deceive" "deceiver" "deceivers" "deceiving" "deception" "deceptive" "deceptively" "declaim" "decline" "declines" "declining" "decrement" "decrepit" "decrepitude" "decry" "defamation" "defamations" "defamatory" "defame" "defect" "defective" "defects" "defensive" "defiance" "defiant" "defiantly" "deficiencies" "deficiency" "deficient" "defile" "defiler" "deform" "deformed" "defrauding" "defunct" "defy" "degenerate" "degenerately" "degeneration" "degradation" "degrade" "degrading" "degradingly" "dehumanization" "dehumanize" "deign" "deject" "dejected" "dejectedly" "dejection" "delay" "delayed" "delaying" "delays" "delinquency" "delinquent" "delirious" "delirium" "delude" "deluded" "deluge" "delusion" "delusional" "delusions" "demean" "demeaning" "demise" "demolish" "demolisher" "demon" "demonic" "demonize" "demonized" "demonizes" "demonizing" "demoralize" "demoralizing" "demoralizingly" "denial" "denied" "denies" "denigrate" "denounce" "dense" "dent" "dented" "dents" "denunciate" "denunciation" "denunciations" "deny" "denying" "deplete" "deplorable" "deplorably" "deplore" "deploring" "deploringly" "deprave" "depraved" "depravedly" "deprecate" "depress" "depressed" "depressing" "depressingly" "depression" "depressions" "deprive" "deprived" "deride" "derision" "derisive" "derisively" "derisiveness" "derogatory" "desecrate" "desert" "desertion" "desiccate" "desiccated" "desititute" "desolate" "desolately" "desolation" "despair" "despairing" "despairingly" "desperate" "desperately" "desperation" "despicable" "despicably" "despise" "despised" "despoil" "despoiler" "despondence" "despondency" "despondent" "despondently" "despot" "despotic" "despotism" "destabilisation" "destains" "destitute" "destitution" "destroy" "destroyer" "destruction" "destructive" "desultory" "deter" "deteriorate" "deteriorating" "deterioration" "deterrent" "detest" "detestable" "detestably" "detested" "detesting" "detests" "detract" "detracted" "detracting" "detraction" "detracts" "detriment" "detrimental" "devastate" "devastated" "devastates" "devastating" "devastatingly" "devastation" "deviate" "deviation" "devil" "devilish" "devilishly" "devilment" "devilry" "devious" "deviously" "deviousness" "devoid" "diabolic" "diabolical" "diabolically" "diametrically" "diappointed" "diatribe" "diatribes" "dick" "dictator" "dictatorial" "die" "die-hard" "died" "dies" "difficult" "difficulties" "difficulty" "diffidence" "dilapidated" "dilemma" "dilly-dally" "dim" "dimmer" "din" "ding" "dings" "dinky" "dire" "direly" "direness" "dirt" "dirtbag" "dirtbags" "dirts" "dirty" "disable" "disabled" "disaccord" "disadvantage" "disadvantaged" "disadvantageous" "disadvantages" "disaffect" "disaffected" "disaffirm" "disagree" "disagreeable" "disagreeably" "disagreed" "disagreeing" "disagreement" "disagrees" "disallow" "disapointed" "disapointing" "disapointment" "disappoint" "disappointed" "disappointing" "disappointingly" "disappointment" "disappointments" "disappoints" "disapprobation" "disapproval" "disapprove" "disapproving" "disarm" "disarray" "disaster" "disasterous" "disastrous" "disastrously" "disavow" "disavowal" "disbelief" "disbelieve" "disbeliever" "disclaim" "discombobulate" "discomfit" "discomfititure" "discomfort" "discompose" "disconcert" "disconcerted" "disconcerting" "disconcertingly" "disconsolate" "disconsolately" "disconsolation" "discontent" "discontented" "discontentedly" "discontinued" "discontinuity" "discontinuous" "discord" "discordance" "discordant" "discountenance" "discourage" "discouragement" "discouraging" "discouragingly" "discourteous" "discourteously" "discoutinous" "discredit" "discrepant" "discriminate" "discrimination" "discriminatory" "disdain" "disdained" "disdainful" "disdainfully" "disfavor" "disgrace" "disgraced" "disgraceful" "disgracefully" "disgruntle" "disgruntled" "disgust" "disgusted" "disgustedly" "disgustful" "disgustfully" "disgusting" "disgustingly" "dishearten" "disheartening" "dishearteningly" "dishonest" "dishonestly" "dishonesty" "dishonor" "dishonorable" "dishonorablely" "disillusion" "disillusioned" "disillusionment" "disillusions" "disinclination" "disinclined" "disingenuous" "disingenuously" "disintegrate" "disintegrated" "disintegrates" "disintegration" "disinterest" "disinterested" "dislike" "disliked" "dislikes" "disliking" "dislocated" "disloyal" "disloyalty" "dismal" "dismally" "dismalness" "dismay" "dismayed" "dismaying" "dismayingly" "dismissive" "dismissively" "disobedience" "disobedient" "disobey" "disoobedient" "disorder" "disordered" "disorderly" "disorganized" "disorient" "disoriented" "disown" "disparage" "disparaging" "disparagingly" "dispensable" "dispirit" "dispirited" "dispiritedly" "dispiriting" "displace" "displaced" "displease" "displeased" "displeasing" "displeasure" "disproportionate" "disprove" "disputable" "dispute" "disputed" "disquiet" "disquieting" "disquietingly" "disquietude" "disregard" "disregardful" "disreputable" "disrepute" "disrespect" "disrespectable" "disrespectablity" "disrespectful" "disrespectfully" "disrespectfulness" "disrespecting" "disrupt" "disruption" "disruptive" "diss" "dissapointed" "dissappointed" "dissappointing" "dissatisfaction" "dissatisfactory" "dissatisfied" "dissatisfies" "dissatisfy" "dissatisfying" "dissed" "dissemble" "dissembler" "dissension" "dissent" "dissenter" "dissention" "disservice" "disses" "dissidence" "dissident" "dissidents" "dissing" "dissocial" "dissolute" "dissolution" "dissonance" "dissonant" "dissonantly" "dissuade" "dissuasive" "distains" "distaste" "distasteful" "distastefully" "distort" "distorted" "distortion" "distorts" "distract" "distracting" "distraction" "distraught" "distraughtly" "distraughtness" "distress" "distressed" "distressing" "distressingly" "distrust" "distrustful" "distrusting" "disturb" "disturbance" "disturbed" "disturbing" "disturbingly" "disunity" "disvalue" "divergent" "divisive" "divisively" "divisiveness" "dizzing" "dizzingly" "dizzy" "doddering" "dodgey" "dogged" "doggedly" "dogmatic" "doldrums" "domineer" "domineering" "donside" "doom" "doomed" "doomsday" "dope" "doubt" "doubtful" "doubtfully" "doubts" "douchbag" "douchebag" "douchebags" "downbeat" "downcast" "downer" "downfall" "downfallen" "downgrade" "downhearted" "downheartedly" "downhill" "downside" "downsides" "downturn" "downturns" "drab" "draconian" "draconic" "drag" "dragged" "dragging" "dragoon" "drags" "drain" "drained" "draining" "drains" "drastic" "drastically" "drawback" "drawbacks" "dread" "dreadful" "dreadfully" "dreadfulness" "dreary" "dripped" "dripping" "drippy" "drips" "drones" "droop" "droops" "drop-out" "drop-outs" "dropout" "dropouts" "drought" "drowning" "drunk" "drunkard" "drunken" "dubious" "dubiously" "dubitable" "dud" "dull" "dullard" "dumb" "dumbfound" "dump" "dumped" "dumping" "dumps" "dunce" "dungeon" "dungeons" "dupe" "dust" "dusty" "dwindling" "dying" "earsplitting" "eccentric" "eccentricity" "effigy" "effrontery" "egocentric" "egomania" "egotism" "egotistical" "egotistically" "egregious" "egregiously" "election-rigger" "elimination" "emaciated" "emasculate" "embarrass" "embarrassing" "embarrassingly" "embarrassment" "embattled" "embroil" "embroiled" "embroilment" "emergency" "emphatic" "emphatically" "emptiness" "encroach" "encroachment" "endanger" "enemies" "enemy" "enervate" "enfeeble" "enflame" "engulf" "enjoin" "enmity" "enrage" "enraged" "enraging" "enslave" "entangle" "entanglement" "entrap" "entrapment" "envious" "enviously" "enviousness" "epidemic" "equivocal" "erase" "erode" "erodes" "erosion" "err" "errant" "erratic" "erratically" "erroneous" "erroneously" "error" "errors" "eruptions" "escapade" "eschew" "estranged" "evade" "evasion" "evasive" "evil" "evildoer" "evils" "eviscerate" "exacerbate" "exagerate" "exagerated" "exagerates" "exaggerate" "exaggeration" "exasperate" "exasperated" "exasperating" "exasperatingly" "exasperation" "excessive" "excessively" "exclusion" "excoriate" "excruciating" "excruciatingly" "excuse" "excuses" "execrate" "exhaust" "exhausted" "exhaustion" "exhausts" "exhorbitant" "exhort" "exile" "exorbitant" "exorbitantance" "exorbitantly" "expel" "expensive" "expire" "expired" "explode" "exploit" "exploitation" "explosive" "expropriate" "expropriation" "expulse" "expunge" "exterminate" "extermination" "extinguish" "extort" "extortion" "extraneous" "extravagance" "extravagant" "extravagantly" "extremism" "extremist" "extremists" "eyesore" "f**k" "fabricate" "fabrication" "facetious" "facetiously" "fail" "failed" "failing" "fails" "failure" "failures" "faint" "fainthearted" "faithless" "fake" "fall" "fallacies" "fallacious" "fallaciously" "fallaciousness" "fallacy" "fallen" "falling" "fallout" "falls" "false" "falsehood" "falsely" "falsify" "falter" "faltered" "famine" "famished" "fanatic" "fanatical" "fanatically" "fanaticism" "fanatics" "fanciful" "far-fetched" "farce" "farcical" "farcical-yet-provocative" "farcically" "farfetched" "fascism" "fascist" "fastidious" "fastidiously" "fastuous" "fat" "fat-cat" "fat-cats" "fatal" "fatalistic" "fatalistically" "fatally" "fatcat" "fatcats" "fateful" "fatefully" "fathomless" "fatigue" "fatigued" "fatique" "fatty" "fatuity" "fatuous" "fatuously" "fault" "faults" "faulty" "fawningly" "faze" "fear" "fearful" "fearfully" "fears" "fearsome" "feckless" "feeble" "feeblely" "feebleminded" "feign" "feint" "fell" "felon" "felonious" "ferociously" "ferocity" "fetid" "fever" "feverish" "fevers" "fiasco" "fib" "fibber" "fickle" "fiction" "fictional" "fictitious" "fidget" "fidgety" "fiend" "fiendish" "fierce" "figurehead" "filth" "filthy" "finagle" "finicky" "fissures" "fist" "flabbergast" "flabbergasted" "flagging" "flagrant" "flagrantly" "flair" "flairs" "flak" "flake" "flakey" "flakieness" "flaking" "flaky" "flare" "flares" "flareup" "flareups" "flat-out" "flaunt" "flaw" "flawed" "flaws" "flee" "fleed" "fleeing" "fleer" "flees" "fleeting" "flicering" "flicker" "flickering" "flickers" "flighty" "flimflam" "flimsy" "flirt" "flirty" "floored" "flounder" "floundering" "flout" "fluster" "foe" "fool" "fooled" "foolhardy" "foolish" "foolishly" "foolishness" "forbid" "forbidden" "forbidding" "forceful" "foreboding" "forebodingly" "forfeit" "forged" "forgetful" "forgetfully" "forgetfulness" "forlorn" "forlornly" "forsake" "forsaken" "forswear" "foul" "foully" "foulness" "fractious" "fractiously" "fracture" "fragile" "fragmented" "frail" "frantic" "frantically" "franticly" "fraud" "fraudulent" "fraught" "frazzle" "frazzled" "freak" "freaking" "freakish" "freakishly" "freaks" "freeze" "freezes" "freezing" "frenetic" "frenetically" "frenzied" "frenzy" "fret" "fretful" "frets" "friction" "frictions" "fried" "friggin" "frigging" "fright" "frighten" "frightening" "frighteningly" "frightful" "frightfully" "frigid" "frost" "frown" "froze" "frozen" "fruitless" "fruitlessly" "frustrate" "frustrated" "frustrates" "frustrating" "frustratingly" "frustration" "frustrations" "fuck" "fucking" "fudge" "fugitive" "full-blown" "fulminate" "fumble" "fume" "fumes" "fundamentalism" "funky" "funnily" "funny" "furious" "furiously" "furor" "fury" "fuss" "fussy" "fustigate" "fusty" "futile" "futilely" "futility" "fuzzy" "gabble" "gaff" "gaffe" "gainsay" "gainsayer" "gall" "galling" "gallingly" "galls" "gangster" "gape" "garbage" "garish" "gasp" "gauche" "gaudy" "gawk" "gawky" "geezer" "genocide" "get-rich" "ghastly" "ghetto" "ghosting" "gibber" "gibberish" "gibe" "giddy" "gimmick" "gimmicked" "gimmicking" "gimmicks" "gimmicky" "glare" "glaringly" "glib" "glibly" "glitch" "glitches" "gloatingly" "gloom" "gloomy" "glower" "glum" "glut" "gnawing" "goad" "goading" "god-awful" "goof" "goofy" "goon" "gossip" "graceless" "gracelessly" "graft" "grainy" "grapple" "grate" "grating" "gravely" "greasy" "greed" "greedy" "grief" "grievance" "grievances" "grieve" "grieving" "grievous" "grievously" "grim" "grimace" "grind" "gripe" "gripes" "grisly" "gritty" "gross" "grossly" "grotesque" "grouch" "grouchy" "groundless" "grouse" "growl" "grudge" "grudges" "grudging" "grudgingly" "gruesome" "gruesomely" "gruff" "grumble" "grumpier" "grumpiest" "grumpily" "grumpish" "grumpy" "guile" "guilt" "guiltily" "guilty" "gullible" "gutless" "gutter" "hack" "hacks" "haggard" "haggle" "hairloss" "halfhearted" "halfheartedly" "hallucinate" "hallucination" "hamper" "hampered" "handicapped" "hang" "hangs" "haphazard" "hapless" "harangue" "harass" "harassed" "harasses" "harassment" "harboring" "harbors" "hard" "hard-hit" "hard-line" "hard-liner" "hardball" "harden" "hardened" "hardheaded" "hardhearted" "hardliner" "hardliners" "hardship" "hardships" "harm" "harmed" "harmful" "harms" "harpy" "harridan" "harried" "harrow" "harsh" "harshly" "hasseling" "hassle" "hassled" "hassles" "haste" "hastily" "hasty" "hate" "hated" "hateful" "hatefully" "hatefulness" "hater" "haters" "hates" "hating" "hatred" "haughtily" "haughty" "haunt" "haunting" "havoc" "hawkish" "haywire" "hazard" "hazardous" "haze" "hazy" "head-aches" "headache" "headaches" "heartbreaker" "heartbreaking" "heartbreakingly" "heartless" "heathen" "heavy-handed" "heavyhearted" "heck" "heckle" "heckled" "heckles" "hectic" "hedge" "hedonistic" "heedless" "hefty" "hegemonism" "hegemonistic" "hegemony" "heinous" "hell" "hell-bent" "hellion" "hells" "helpless" "helplessly" "helplessness" "heresy" "heretic" "heretical" "hesitant" "hestitant" "hideous" "hideously" "hideousness" "high-priced" "hiliarious" "hinder" "hindrance" "hiss" "hissed" "hissing" "ho-hum" "hoard" "hoax" "hobble" "hogs" "hollow" "hoodium" "hoodwink" "hooligan" "hopeless" "hopelessly" "hopelessness" "horde" "horrendous" "horrendously" "horrible" "horrid" "horrific" "horrified" "horrifies" "horrify" "horrifying" "horrifys" "hostage" "hostile" "hostilities" "hostility" "hotbeds" "hothead" "hotheaded" "hothouse" "hubris" "huckster" "hum" "humid" "humiliate" "humiliating" "humiliation" "humming" "hung" "hurt" "hurted" "hurtful" "hurting" "hurts" "hustler" "hype" "hypocricy" "hypocrisy" "hypocrite" "hypocrites" "hypocritical" "hypocritically" "hysteria" "hysteric" "hysterical" "hysterically" "hysterics" "idiocies" "idiocy" "idiot" "idiotic" "idiotically" "idiots" "idle" "ignoble" "ignominious" "ignominiously" "ignominy" "ignorance" "ignorant" "ignore" "ill-advised" "ill-conceived" "ill-defined" "ill-designed" "ill-fated" "ill-favored" "ill-formed" "ill-mannered" "ill-natured" "ill-sorted" "ill-tempered" "ill-treated" "ill-treatment" "ill-usage" "ill-used" "illegal" "illegally" "illegitimate" "illicit" "illiterate" "illness" "illogic" "illogical" "illogically" "illusion" "illusions" "illusory" "imaginary" "imbalance" "imbecile" "imbroglio" "immaterial" "immature" "imminence" "imminently" "immobilized" "immoderate" "immoderately" "immodest" "immoral" "immorality" "immorally" "immovable" "impair" "impaired" "impasse" "impatience" "impatient" "impatiently" "impeach" "impedance" "impede" "impediment" "impending" "impenitent" "imperfect" "imperfection" "imperfections" "imperfectly" "imperialist" "imperil" "imperious" "imperiously" "impermissible" "impersonal" "impertinent" "impetuous" "impetuously" "impiety" "impinge" "impious" "implacable" "implausible" "implausibly" "implicate" "implication" "implode" "impolite" "impolitely" "impolitic" "importunate" "importune" "impose" "imposers" "imposing" "imposition" "impossible" "impossiblity" "impossibly" "impotent" "impoverish" "impoverished" "impractical" "imprecate" "imprecise" "imprecisely" "imprecision" "imprison" "imprisonment" "improbability" "improbable" "improbably" "improper" "improperly" "impropriety" "imprudence" "imprudent" "impudence" "impudent" "impudently" "impugn" "impulsive" "impulsively" "impunity" "impure" "impurity" "inability" "inaccuracies" "inaccuracy" "inaccurate" "inaccurately" "inaction" "inactive" "inadequacy" "inadequate" "inadequately" "inadverent" "inadverently" "inadvisable" "inadvisably" "inane" "inanely" "inappropriate" "inappropriately" "inapt" "inaptitude" "inarticulate" "inattentive" "inaudible" "incapable" "incapably" "incautious" "incendiary" "incense" "incessant" "incessantly" "incite" "incitement" "incivility" "inclement" "incognizant" "incoherence" "incoherent" "incoherently" "incommensurate" "incomparable" "incomparably" "incompatability" "incompatibility" "incompatible" "incompetence" "incompetent" "incompetently" "incomplete" "incompliant" "incomprehensible" "incomprehension" "inconceivable" "inconceivably" "incongruous" "incongruously" "inconsequent" "inconsequential" "inconsequentially" "inconsequently" "inconsiderate" "inconsiderately" "inconsistence" "inconsistencies" "inconsistency" "inconsistent" "inconsolable" "inconsolably" "inconstant" "inconvenience" "inconveniently" "incorrect" "incorrectly" "incorrigible" "incorrigibly" "incredulous" "incredulously" "inculcate" "indecency" "indecent" "indecently" "indecision" "indecisive" "indecisively" "indecorum" "indefensible" "indelicate" "indeterminable" "indeterminably" "indeterminate" "indifference" "indifferent" "indigent" "indignant" "indignantly" "indignation" "indignity" "indiscernible" "indiscreet" "indiscreetly" "indiscretion" "indiscriminate" "indiscriminately" "indiscriminating" "indistinguishable" "indoctrinate" "indoctrination" "indolent" "indulge" "ineffective" "ineffectively" "ineffectiveness" "ineffectual" "ineffectually" "ineffectualness" "inefficacious" "inefficacy" "inefficiency" "inefficient" "inefficiently" "inelegance" "inelegant" "ineligible" "ineloquent" "ineloquently" "inept" "ineptitude" "ineptly" "inequalities" "inequality" "inequitable" "inequitably" "inequities" "inescapable" "inescapably" "inessential" "inevitable" "inevitably" "inexcusable" "inexcusably" "inexorable" "inexorably" "inexperience" "inexperienced" "inexpert" "inexpertly" "inexpiable" "inexplainable" "inextricable" "inextricably" "infamous" "infamously" "infamy" "infected" "infection" "infections" "inferior" "inferiority" "infernal" "infest" "infested" "infidel" "infidels" "infiltrator" "infiltrators" "infirm" "inflame" "inflammation" "inflammatory" "inflammed" "inflated" "inflationary" "inflexible" "inflict" "infraction" "infringe" "infringement" "infringements" "infuriate" "infuriated" "infuriating" "infuriatingly" "inglorious" "ingrate" "ingratitude" "inhibit" "inhibition" "inhospitable" "inhospitality" "inhuman" "inhumane" "inhumanity" "inimical" "inimically" "iniquitous" "iniquity" "injudicious" "injure" "injurious" "injury" "injustice" "injustices" "innuendo" "inoperable" "inopportune" "inordinate" "inordinately" "insane" "insanely" "insanity" "insatiable" "insecure" "insecurity" "insensible" "insensitive" "insensitively" "insensitivity" "insidious" "insidiously" "insignificance" "insignificant" "insignificantly" "insincere" "insincerely" "insincerity" "insinuate" "insinuating" "insinuation" "insociable" "insolence" "insolent" "insolently" "insolvent" "insouciance" "instability" "instable" "instigate" "instigator" "instigators" "insubordinate" "insubstantial" "insubstantially" "insufferable" "insufferably" "insufficiency" "insufficient" "insufficiently" "insular" "insult" "insulted" "insulting" "insultingly" "insults" "insupportable" "insupportably" "insurmountable" "insurmountably" "insurrection" "intefere" "inteferes" "intense" "interfere" "interference" "interferes" "intermittent" "interrupt" "interruption" "interruptions" "intimidate" "intimidating" "intimidatingly" "intimidation" "intolerable" "intolerablely" "intolerance" "intoxicate" "intractable" "intransigence" "intransigent" "intrude" "intrusion" "intrusive" "inundate" "inundated" "invader" "invalid" "invalidate" "invalidity" "invasive" "invective" "inveigle" "invidious" "invidiously" "invidiousness" "invisible" "involuntarily" "involuntary" "irascible" "irate" "irately" "ire" "irk" "irked" "irking" "irks" "irksome" "irksomely" "irksomeness" "irksomenesses" "ironic" "ironical" "ironically" "ironies" "irony" "irragularity" "irrational" "irrationalities" "irrationality" "irrationally" "irrationals" "irreconcilable" "irrecoverable" "irrecoverableness" "irrecoverablenesses" "irrecoverably" "irredeemable" "irredeemably" "irreformable" "irregular" "irregularity" "irrelevance" "irrelevant" "irreparable" "irreplacible" "irrepressible" "irresolute" "irresolvable" "irresponsible" "irresponsibly" "irretating" "irretrievable" "irreversible" "irritable" "irritably" "irritant" "irritate" "irritated" "irritating" "irritation" "irritations" "isolate" "isolated" "isolation" "issue" "issues" "itch" "itching" "itchy" "jabber" "jaded" "jagged" "jam" "jarring" "jaundiced" "jealous" "jealously" "jealousness" "jealousy" "jeer" "jeering" "jeeringly" "jeers" "jeopardize" "jeopardy" "jerk" "jerky" "jitter" "jitters" "jittery" "job-killing" "jobless" "joke" "joker" "jolt" "judder" "juddering" "judders" "jumpy" "junk" "junky" "junkyard" "jutter" "jutters" "kaput" "kill" "killed" "killer" "killing" "killjoy" "kills" "knave" "knife" "knock" "knotted" "kook" "kooky" "lack" "lackadaisical" "lacked" "lackey" "lackeys" "lacking" "lackluster" "lacks" "laconic" "lag" "lagged" "lagging" "laggy" "lags" "laid-off" "lambast" "lambaste" "lame" "lame-duck" "lament" "lamentable" "lamentably" "languid" "languish" "languor" "languorous" "languorously" "lanky" "lapse" "lapsed" "lapses" "lascivious" "last-ditch" "latency" "laughable" "laughably" "laughingstock" "lawbreaker" "lawbreaking" "lawless" "lawlessness" "layoff" "layoff-happy" "lazy" "leak" "leakage" "leakages" "leaking" "leaks" "leaky" "lech" "lecher" "lecherous" "lechery" "leech" "leer" "leery" "left-leaning" "lemon" "lengthy" "less-developed" "lesser-known" "letch" "lethal" "lethargic" "lethargy" "lewd" "lewdly" "lewdness" "liability" "liable" "liar" "liars" "licentious" "licentiously" "licentiousness" "lie" "lied" "lier" "lies" "life-threatening" "lifeless" "limit" "limitation" "limitations" "limited" "limits" "limp" "listless" "litigious" "little-known" "livid" "lividly" "loath" "loathe" "loathing" "loathly" "loathsome" "loathsomely" "lone" "loneliness" "lonely" "loner" "lonesome" "long-time" "long-winded" "longing" "longingly" "loophole" "loopholes" "loose" "loot" "lorn" "lose" "loser" "losers" "loses" "losing" "loss" "losses" "lost" "loud" "louder" "lousy" "loveless" "lovelorn" "low-rated" "lowly" "ludicrous" "ludicrously" "lugubrious" "lukewarm" "lull" "lumpy" "lunatic" "lunaticism" "lurch" "lure" "lurid" "lurk" "lurking" "lying" "macabre" "mad" "madden" "maddening" "maddeningly" "madder" "madly" "madman" "madness" "maladjusted" "maladjustment" "malady" "malaise" "malcontent" "malcontented" "maledict" "malevolence" "malevolent" "malevolently" "malice" "malicious" "maliciously" "maliciousness" "malign" "malignant" "malodorous" "maltreatment" "mangle" "mangled" "mangles" "mangling" "mania" "maniac" "maniacal" "manic" "manipulate" "manipulation" "manipulative" "manipulators" "mar" "marginal" "marginally" "martyrdom" "martyrdom-seeking" "mashed" "massacre" "massacres" "<NAME>te" "mawkish" "mawkishly" "mawkishness" "meager" "meaningless" "meanness" "measly" "meddle" "meddlesome" "mediocre" "mediocrity" "melancholy" "melodramatic" "melodramatically" "meltdown" "menace" "menacing" "menacingly" "mendacious" "mendacity" "menial" "merciless" "mercilessly" "mess" "messed" "messes" "messing" "messy" "midget" "miff" "militancy" "mindless" "mindlessly" "mirage" "mire" "misalign" "misaligned" "misaligns" "misapprehend" "misbecome" "misbecoming" "misbegotten" "misbehave" "misbehavior" "miscalculate" "miscalculation" "miscellaneous" "mischief" "mischievous" "mischievously" "misconception" "misconceptions" "miscreant" "miscreants" "misdirection" "miser" "miserable" "miserableness" "miserably" "miseries" "miserly" "misery" "misfit" "misfortune" "misgiving" "misgivings" "misguidance" "misguide" "misguided" "mishandle" "mishap" "misinform" "misinformed" "misinterpret" "misjudge" "misjudgment" "mislead" "misleading" "misleadingly" "mislike" "mismanage" "mispronounce" "mispronounced" "mispronounces" "misread" "misreading" "misrepresent" "misrepresentation" "miss" "missed" "misses" "misstatement" "mist" "mistake" "mistaken" "mistakenly" "mistakes" "mistified" "mistress" "mistrust" "mistrustful" "mistrustfully" "mists" "misunderstand" "misunderstanding" "misunderstandings" "misunderstood" "misuse" "moan" "mobster" "mock" "mocked" "mockeries" "mockery" "mocking" "mockingly" "mocks" "molest" "molestation" "monotonous" "monotony" "monster" "monstrosities" "monstrosity" "monstrous" "monstrously" "moody" "moot" "mope" "morbid" "morbidly" "mordant" "mordantly" "moribund" "moron" "moronic" "morons" "mortification" "mortified" "mortify" "mortifying" "motionless" "motley" "mourn" "mourner" "mournful" "mournfully" "muddle" "muddy" "mudslinger" "mudslinging" "mulish" "multi-polarization" "mundane" "murder" "murderer" "murderous" "murderously" "murky" "muscle-flexing" "mushy" "musty" "mysterious" "mysteriously" "mystery" "mystify" "myth" "nag" "nagging" "naive" "naively" "narrower" "nastily" "nastiness" "nasty" "naughty" "nauseate" "nauseates" "nauseating" "nauseatingly" "na�ve" "nebulous" "nebulously" "needless" "needlessly" "needy" "nefarious" "nefariously" "negate" "negation" "negative" "negatives" "negativity" "neglect" "neglected" "negligence" "negligent" "nemesis" "nepotism" "nervous" "nervously" "nervousness" "nettle" "nettlesome" "neurotic" "neurotically" "niggle" "niggles" "nightmare" "nightmarish" "nightmarishly" "nitpick" "nitpicking" "noise" "noises" "noisier" "noisy" "non-confidence" "nonexistent" "nonresponsive" "nonsense" "nosey" "notoriety" "notorious" "notoriously" "noxious" "nuisance" "numb" "obese" "object" "objection" "objectionable" "objections" "oblique" "obliterate" "obliterated" "oblivious" "obnoxious" "obnoxiously" "obscene" "obscenely" "obscenity" "obscure" "obscured" "obscures" "obscurity" "obsess" "obsessive" "obsessively" "obsessiveness" "obsolete" "obstacle" "obstinate" "obstinately" "obstruct" "obstructed" "obstructing" "obstruction" "obstructs" "obtrusive" "obtuse" "occlude" "occluded" "occludes" "occluding" "odd" "odder" "oddest" "oddities" "oddity" "oddly" "odor" "offence" "offend" "offender" "offending" "offenses" "offensive" "offensively" "offensiveness" "officious" "ominous" "ominously" "omission" "omit" "one-sided" "onerous" "onerously" "onslaught" "opinionated" "opponent" "opportunistic" "oppose" "opposition" "oppositions" "oppress" "oppression" "oppressive" "oppressively" "oppressiveness" "oppressors" "ordeal" "orphan" "ostracize" "outbreak" "outburst" "outbursts" "outcast" "outcry" "outlaw" "outmoded" "outrage" "outraged" "outrageous" "outrageously" "outrageousness" "outrages" "outsider" "over-acted" "over-awe" "over-balanced" "over-hyped" "over-priced" "over-valuation" "overact" "overacted" "overawe" "overbalance" "overbalanced" "overbearing" "overbearingly" "overblown" "overdo" "overdone" "overdue" "overemphasize" "overheat" "overkill" "overloaded" "overlook" "overpaid" "overpayed" "overplay" "overpower" "overpriced" "overrated" "overreach" "overrun" "overshadow" "oversight" "oversights" "oversimplification" "oversimplified" "oversimplify" "oversize" "overstate" "overstated" "overstatement" "overstatements" "overstates" "overtaxed" "overthrow" "overthrows" "overturn" "overweight" "overwhelm" "overwhelmed" "overwhelming" "overwhelmingly" "overwhelms" "overzealous" "overzealously" "overzelous" "pain" "painful" "painfull" "painfully" "pains" "pale" "pales" "paltry" "pan" "pandemonium" "pander" "pandering" "panders" "panic" "panick" "panicked" "panicking" "panicky" "paradoxical" "paradoxically" "paralize" "paralyzed" "paranoia" "paranoid" "parasite" "pariah" "parody" "partiality" "partisan" "partisans" "passe" "passive" "passiveness" "pathetic" "pathetically" "patronize" "paucity" "pauper" "paupers" "payback" "peculiar" "peculiarly" "pedantic" "peeled" "peeve" "peeved" "peevish" "peevishly" "penalize" "penalty" "perfidious" "perfidity" "perfunctory" "peril" "perilous" "perilously" "perish" "pernicious" "perplex" "perplexed" "perplexing" "perplexity" "persecute" "persecution" "pertinacious" "pertinaciously" "pertinacity" "perturb" "perturbed" "pervasive" "perverse" "perversely" "perversion" "perversity" "pervert" "perverted" "perverts" "pessimism" "pessimistic" "pessimistically" "pest" "pestilent" "petrified" "petrify" "pettifog" "petty" "phobia" "phobic" "phony" "picket" "picketed" "picketing" "pickets" "picky" "pig" "pigs" "pillage" "pillory" "pimple" "pinch" "pique" "pitiable" "pitiful" "pitifully" "pitiless" "pitilessly" "pittance" "pity" "plagiarize" "plague" "plasticky" "plaything" "plea" "pleas" "plebeian" "plight" "plot" "plotters" "ploy" "plunder" "plunderer" "pointless" "pointlessly" "poison" "poisonous" "poisonously" "pokey" "poky" "polarisation" "polemize" "pollute" "polluter" "polluters" "polution" "pompous" "poor" "poorer" "poorest" "poorly" "posturing" "pout" "poverty" "powerless" "prate" "pratfall" "prattle" "precarious" "precariously" "precipitate" "precipitous" "predatory" "predicament" "prejudge" "prejudice" "prejudices" "prejudicial" "premeditated" "preoccupy" "preposterous" "preposterously" "presumptuous" "presumptuously" "pretence" "pretend" "pretense" "pretentious" "pretentiously" "prevaricate" "pricey" "pricier" "prick" "prickle" "prickles" "prideful" "prik" "primitive" "prison" "prisoner" "problem" "problematic" "problems" "procrastinate" "procrastinates" "procrastination" "profane" "profanity" "prohibit" "prohibitive" "prohibitively" "propaganda" "propagandize" "proprietary" "prosecute" "protest" "protested" "protesting" "protests" "protracted" "provocation" "provocative" "provoke" "pry" "pugnacious" "pugnaciously" "pugnacity" "punch" "punish" "punishable" "punitive" "punk" "puny" "puppet" "puppets" "puzzled" "puzzlement" "puzzling" "quack" "qualm" "qualms" "quandary" "quarrel" "quarrellous" "quarrellously" "quarrels" "quarrelsome" "quash" "queer" "questionable" "quibble" "quibbles" "quitter" "rabid" "racism" "racist" "racists" "racy" "radical" "radicalization" "radically" "radicals" "rage" "ragged" "raging" "rail" "raked" "rampage" "rampant" "ramshackle" "rancor" "randomly" "rankle" "rant" "ranted" "ranting" "rantingly" "rants" "rape" "raped" "raping" "rascal" "rascals" "rash" "rattle" "rattled" "rattles" "ravage" "raving" "reactionary" "rebellious" "rebuff" "rebuke" "recalcitrant" "recant" "recession" "recessionary" "reckless" "recklessly" "recklessness" "recoil" "recourses" "redundancy" "redundant" "refusal" "refuse" "refused" "refuses" "refusing" "refutation" "refute" "refuted" "refutes" "refuting" "regress" "regression" "regressive" "regret" "regreted" "regretful" "regretfully" "regrets" "regrettable" "regrettably" "regretted" "reject" "rejected" "rejecting" "rejection" "rejects" "relapse" "relentless" "relentlessly" "relentlessness" "reluctance" "reluctant" "reluctantly" "remorse" "remorseful" "remorsefully" "remorseless" "remorselessly" "remorselessness" "renounce" "renunciation" "repel" "repetitive" "reprehensible" "reprehensibly" "reprehension" "reprehensive" "repress" "repression" "repressive" "reprimand" "reproach" "reproachful" "reprove" "reprovingly" "repudiate" "repudiation" "repugn" "repugnance" "repugnant" "repugnantly" "repulse" "repulsed" "repulsing" "repulsive" "repulsively" "repulsiveness" "resent" "resentful" "resentment" "resignation" "resigned" "resistance" "restless" "restlessness" "restrict" "restricted" "restriction" "restrictive" "resurgent" "retaliate" "retaliatory" "retard" "retarded" "retardedness" "retards" "reticent" "retract" "retreat" "retreated" "revenge" "revengeful" "revengefully" "revert" "revile" "reviled" "revoke" "revolt" "revolting" "revoltingly" "revulsion" "revulsive" "rhapsodize" "rhetoric" "rhetorical" "ricer" "ridicule" "ridicules" "ridiculous" "ridiculously" "rife" "rift" "rifts" "rigid" "rigidity" "rigidness" "rile" "riled" "rip" "rip-off" "ripoff" "ripped" "risk" "risks" "risky" "rival" "rivalry" "roadblocks" "rocky" "rogue" "rollercoaster" "rot" "rotten" "rough" "rremediable" "rubbish" "rude" "rue" "ruffian" "ruffle" "ruin" "ruined" "ruining" "ruinous" "ruins" "rumbling" "rumor" "rumors" "rumours" "rumple" "run-down" "runaway" "rupture" "rust" "rusts" "rusty" "rut" "ruthless" "ruthlessly" "ruthlessness" "ruts" "sabotage" "sack" "sacrificed" "sad" "sadden" "sadly" "sadness" "sag" "sagged" "sagging" "saggy" "sags" "salacious" "sanctimonious" "sap" "sarcasm" "sarcastic" "sarcastically" "sardonic" "sardonically" "sass" "satirical" "satirize" "savage" "savaged" "savagery" "savages" "scaly" "scam" "scams" "scandal" "scandalize" "scandalized" "scandalous" "scandalously" "scandals" "scandel" "scandels" "scant" "scapegoat" "scar" "scarce" "scarcely" "scarcity" "scare" "scared" "scarier" "scariest" "scarily" "scarred" "scars" "scary" "scathing" "scathingly" "sceptical" "scoff" "scoffingly" "scold" "scolded" "scolding" "scoldingly" "scorching" "scorchingly" "scorn" "scornful" "scornfully" "scoundrel" "scourge" "scowl" "scramble" "scrambled" "scrambles" "scrambling" "scrap" "scratch" "scratched" "scratches" "scratchy" "scream" "screech" "screw-up" "screwed" "screwed-up" "screwy" "scuff" "scuffs" "scum" "scummy" "second-class" "second-tier" "secretive" "sedentary" "seedy" "seethe" "seething" "self-coup" "self-criticism" "self-defeating" "self-destructive" "self-humiliation" "self-interest" "self-interested" "self-serving" "selfinterested" "selfish" "selfishly" "selfishness" "semi-retarded" "senile" "sensationalize" "senseless" "senselessly" "seriousness" "sermonize" "servitude" "set-up" "setback" "setbacks" "sever" "severe" "severity" "sh*t" "shabby" "shadowy" "shady" "shake" "shaky" "shallow" "sham" "shambles" "shame" "shameful" "shamefully" "shamefulness" "shameless" "shamelessly" "shamelessness" "shark" "sharply" "shatter" "shemale" "shimmer" "shimmy" "shipwreck" "shirk" "shirker" "shit" "shiver" "shock" "shocked" "shocking" "shockingly" "shoddy" "short-lived" "shortage" "shortchange" "shortcoming" "shortcomings" "shortness" "shortsighted" "shortsightedness" "showdown" "shrew" "shriek" "shrill" "shrilly" "shrivel" "shroud" "shrouded" "shrug" "shun" "shunned" "sick" "sicken" "sickening" "sickeningly" "sickly" "sickness" "sidetrack" "sidetracked" "siege" "sillily" "silly" "simplistic" "simplistically" "sin" "sinful" "sinfully" "sinister" "sinisterly" "sink" "sinking" "skeletons" "skeptic" "skeptical" "skeptically" "skepticism" "sketchy" "skimpy" "skinny" "skittish" "skittishly" "skulk" "slack" "slander" "slanderer" "slanderous" "slanderously" "slanders" "slap" "slashing" "slaughter" "slaughtered" "slave" "slaves" "sleazy" "slime" "slog" "slogged" "slogging" "slogs" "sloooooooooooooow" "sloooow" "slooow" "sloow" "sloppily" "sloppy" "sloth" "slothful" "slow" "slow-moving" "slowed" "slower" "slowest" "slowly" "sloww" "slowww" "slowwww" "slug" "sluggish" "slump" "slumping" "slumpping" "slur" "slut" "sluts" "sly" "smack" "smallish" "smash" "smear" "smell" "smelled" "smelling" "smells" "smelly" "smelt" "smoke" "smokescreen" "smolder" "smoldering" "smother" "smoulder" "smouldering" "smudge" "smudged" "smudges" "smudging" "smug" "smugly" "smut" "smuttier" "smuttiest" "smutty" "snag" "snagged" "snagging" "snags" "snappish" "snappishly" "snare" "snarky" "snarl" "sneak" "sneakily" "sneaky" "sneer" "sneering" "sneeringly" "snob" "snobbish" "snobby" "snobish" "snobs" "snub" "so-cal" "soapy" "sob" "sober" "sobering" "solemn" "solicitude" "somber" "sore" "sorely" "soreness" "sorrow" "sorrowful" "sorrowfully" "sorry" "sour" "sourly" "spade" "spank" "spendy" "spew" "spewed" "spewing" "spews" "spilling" "spinster" "spiritless" "spite" "spiteful" "spitefully" "spitefulness" "splatter" "split" "splitting" "spoil" "spoilage" "spoilages" "spoiled" "spoilled" "spoils" "spook" "spookier" "spookiest" "spookily" "spooky" "spoon-fed" "spoon-feed" "spoonfed" "sporadic" "spotty" "spurious" "spurn" "sputter" "squabble" "squabbling" "squander" "squash" "squeak" "squeaks" "squeaky" "squeal" "squealing" "squeals" "squirm" "stab" "stagnant" "stagnate" "stagnation" "staid" "stain" "stains" "stale" "stalemate" "stall" "stalls" "stammer" "stampede" "standstill" "stark" "starkly" "startle" "startling" "startlingly" "starvation" "starve" "static" "steal" "stealing" "steals" "steep" "steeply" "stench" "stereotype" "stereotypical" "stereotypically" "stern" "stew" "sticky" "stiff" "stiffness" "stifle" "stifling" "stiflingly" "stigma" "stigmatize" "sting" "stinging" "stingingly" "stingy" "stink" "stinks" "stodgy" "stole" "stolen" "stooge" "stooges" "stormy" "straggle" "straggler" "strain" "strained" "straining" "strange" "strangely" "stranger" "strangest" "strangle" "streaky" "strenuous" "stress" "stresses" "stressful" "stressfully" "stricken" "strict" "strictly" "strident" "stridently" "strife" "strike" "stringent" "stringently" "struck" "struggle" "struggled" "struggles" "struggling" "strut" "stubborn" "stubbornly" "stubbornness" "stuck" "stuffy" "stumble" "stumbled" "stumbles" "stump" "stumped" "stumps" "stun" "stunt" "stunted" "stupid" "stupidest" "stupidity" "stupidly" "stupified" "stupify" "stupor" "stutter" "stuttered" "stuttering" "stutters" "sty" "stymied" "sub-par" "subdued" "subjected" "subjection" "subjugate" "subjugation" "submissive" "subordinate" "subpoena" "subpoenas" "subservience" "subservient" "substandard" "subtract" "subversion" "subversive" "subversively" "subvert" "succumb" "suck" "sucked" "sucker" "sucks" "sucky" "sue" "sued" "sueing" "sues" "suffer" "suffered" "sufferer" "sufferers" "suffering" "suffers" "suffocate" "sugar-coat" "sugar-coated" "sugarcoated" "suicidal" "suicide" "sulk" "sullen" "sully" "sunder" "sunk" "sunken" "superficial" "superficiality" "superficially" "superfluous" "superstition" "superstitious" "suppress" "suppression" "surrender" "susceptible" "suspect" "suspicion" "suspicions" "suspicious" "suspiciously" "swagger" "swamped" "sweaty" "swelled" "swelling" "swindle" "swipe" "swollen" "symptom" "symptoms" "syndrome" "taboo" "tacky" "taint" "tainted" "tamper" "tangle" "tangled" "tangles" "tank" "tanked" "tanks" "tantrum" "tardy" "tarnish" "tarnished" "tarnishes" "tarnishing" "tattered" "taunt" "taunting" "tauntingly" "taunts" "taut" "tawdry" "taxing" "tease" "teasingly" "tedious" "tediously" "temerity" "temper" "tempest" "temptation" "tenderness" "tense" "tension" "tentative" "tentatively" "tenuous" "tenuously" "tepid" "terrible" "terribleness" "terribly" "terror" "terror-genic" "terrorism" "terrorize" "testily" "testy" "tetchily" "tetchy" "thankless" "thicker" "thirst" "thorny" "thoughtless" "thoughtlessly" "thoughtlessness" "thrash" "threat" "threaten" "threatening" "threats" "threesome" "throb" "throbbed" "throbbing" "throbs" "throttle" "thug" "thumb-down" "thumbs-down" "thwart" "time-consuming" "timid" "timidity" "timidly" "timidness" "tin-y" "tingled" "tingling" "tired" "tiresome" "tiring" "tiringly" "toil" "toll" "top-heavy" "topple" "torment" "tormented" "torrent" "tortuous" "torture" "tortured" "tortures" "torturing" "torturous" "torturously" "totalitarian" "touchy" "toughness" "tout" "touted" "touts" "toxic" "traduce" "tragedy" "tragic" "tragically" "traitor" "traitorous" "traitorously" "tramp" "trample" "transgress" "transgression" "trap" "traped" "trapped" "trash" "trashed" "trashy" "trauma" "traumatic" "traumatically" "traumatize" "traumatized" "travesties" "travesty" "treacherous" "treacherously" "treachery" "treason" "treasonous" "trick" "tricked" "trickery" "tricky" "trivial" "trivialize" "trouble" "troubled" "troublemaker" "troubles" "troublesome" "troublesomely" "troubling" "troublingly" "truant" "tumble" "tumbled" "tumbles" "tumultuous" "turbulent" "turmoil" "twist" "twisted" "twists" "two-faced" "two-faces" "tyrannical" "tyrannically" "tyranny" "tyrant" "ugh" "uglier" "ugliest" "ugliness" "ugly" "ulterior" "ultimatum" "ultimatums" "ultra-hardline" "un-viewable" "unable" "unacceptable" "unacceptablely" "unacceptably" "unaccessible" "unaccustomed" "unachievable" "unaffordable" "unappealing" "unattractive" "unauthentic" "unavailable" "unavoidably" "unbearable" "unbearablely" "unbelievable" "unbelievably" "uncaring" "uncertain" "uncivil" "uncivilized" "unclean" "unclear" "uncollectible" "uncomfortable" "uncomfortably" "uncomfy" "uncompetitive" "uncompromising" "uncompromisingly" "unconfirmed" "unconstitutional" "uncontrolled" "unconvincing" "unconvincingly" "uncooperative" "uncouth" "uncreative" "undecided" "undefined" "undependability" "undependable" "undercut" "undercuts" "undercutting" "underdog" "underestimate" "underlings" "undermine" "undermined" "undermines" "undermining" "underpaid" "underpowered" "undersized" "undesirable" "undetermined" "undid" "undignified" "undissolved" "undocumented" "undone" "undue" "unease" "uneasily" "uneasiness" "uneasy" "uneconomical" "unemployed" "unequal" "unethical" "uneven" "uneventful" "unexpected" "unexpectedly" "unexplained" "unfairly" "unfaithful" "unfaithfully" "unfamiliar" "unfavorable" "unfeeling" "unfinished" "unfit" "unforeseen" "unforgiving" "unfortunate" "unfortunately" "unfounded" "unfriendly" "unfulfilled" "unfunded" "ungovernable" "ungrateful" "unhappily" "unhappiness" "unhappy" "unhealthy" "unhelpful" "unilateralism" "unimaginable" "unimaginably" "unimportant" "uninformed" "uninsured" "unintelligible" "unintelligile" "unipolar" "unjust" "unjustifiable" "unjustifiably" "unjustified" "unjustly" "unkind" "unkindly" "unknown" "unlamentable" "unlamentably" "unlawful" "unlawfully" "unlawfulness" "unleash" "unlicensed" "unlikely" "unlucky" "unmoved" "unnatural" "unnaturally" "unnecessary" "unneeded" "unnerve" "unnerved" "unnerving" "unnervingly" "unnoticed" "unobserved" "unorthodox" "unorthodoxy" "unpleasant" "unpleasantries" "unpopular" "unpredictable" "unprepared" "unproductive" "unprofitable" "unprove" "unproved" "unproven" "unproves" "unproving" "unqualified" "unravel" "unraveled" "unreachable" "unreadable" "unrealistic" "unreasonable" "unreasonably" "unrelenting" "unrelentingly" "unreliability" "unreliable" "unresolved" "unresponsive" "unrest" "unruly" "unsafe" "unsatisfactory" "unsavory" "unscrupulous" "unscrupulously" "unsecure" "unseemly" "unsettle" "unsettled" "unsettling" "unsettlingly" "unskilled" "unsophisticated" "unsound" "unspeakable" "unspeakablely" "unspecified" "unstable" "unsteadily" "unsteadiness" "unsteady" "unsuccessful" "unsuccessfully" "unsupported" "unsupportive" "unsure" "unsuspecting" "unsustainable" "untenable" "untested" "unthinkable" "unthinkably" "untimely" "untouched" "untrue" "untrustworthy" "untruthful" "unusable" "unusably" "unuseable" "unuseably" "unusual" "unusually" "unviewable" "unwanted" "unwarranted" "unwatchable" "unwelcome" "unwell" "unwieldy" "unwilling" "unwillingly" "unwillingness" "unwise" "unwisely" "unworkable" "unworthy" "unyielding" "upbraid" "upheaval" "uprising" "uproar" "uproarious" "uproariously" "uproarous" "uproarously" "uproot" "upset" "upseting" "upsets" "upsetting" "upsettingly" "urgent" "useless" "usurp" "usurper" "utterly" "vagrant" "vague" "vagueness" "vain" "vainly" "vanity" "vehement" "vehemently" "vengeance" "vengeful" "vengefully" "vengefulness" "venom" "venomous" "venomously" "vent" "vestiges" "vex" "vexation" "vexing" "vexingly" "vibrate" "vibrated" "vibrates" "vibrating" "vibration" "vice" "vicious" "viciously" "viciousness" "victimize" "vile" "vileness" "vilify" "villainous" "villainously" "villains" "villian" "villianous" "villianously" "villify" "vindictive" "vindictively" "vindictiveness" "violate" "violation" "violator" "violators" "violent" "violently" "viper" "virulence" "virulent" "virulently" "virus" "vociferous" "vociferously" "volatile" "volatility" "vomit" "vomited" "vomiting" "vomits" "vulgar" "vulnerable" "wack" "wail" "wallow" "wane" "waning" "wanton" "war-like" "warily" "wariness" "warlike" "warned" "warning" "warp" "warped" "wary" "washed-out" "waste" "wasted" "wasteful" "wastefulness" "wasting" "water-down" "watered-down" "wayward" "weak" "weaken" "weakening" "weaker" "weakness" "weaknesses" "weariness" "wearisome" "weary" "wedge" "weed" "weep" "weird" "weirdly" "wheedle" "whimper" "whine" "whining" "whiny" "whips" "whore" "whores" "wicked" "wickedly" "wickedness" "wild" "wildly" "wiles" "wilt" "wily" "wimpy" "wince" "wobble" "wobbled" "wobbles" "woe" "woebegone" "woeful" "woefully" "womanizer" "womanizing" "worn" "worried" "worriedly" "worrier" "worries" "worrisome" "worry" "worrying" "worryingly" "worse" "worsen" "worsening" "worst" "worthless" "worthlessly" "worthlessness" "wound" "wounds" "wrangle" "wrath" "wreak" "wreaked" "wreaks" "wreck" "wrest" "wrestle" "wretch" "wretched" "wretchedly" "wretchedness" "wrinkle" "wrinkled" "wrinkles" "wrip" "wripped" "wripping" "writhe" "wrong" "wrongful" "wrongly" "wrought" "yawn" "zap" "zapped" "zaps" "zealot" "zealous" "zealously" "zombie"}) (def pos #{"a+" "abound" "abounds" "abundance" "abundant" "accessable" "accessible" "acclaim" "acclaimed" "acclamation" "accolade" "accolades" "accommodative" "accomodative" "accomplish" "accomplished" "accomplishment" "accomplishments" "accurate" "accurately" "achievable" "achievement" "achievements" "achievible" "acumen" "adaptable" "adaptive" "adequate" "adjustable" "admirable" "admirably" "admiration" "admire" "admirer" "admiring" "admiringly" "adorable" "adore" "adored" "adorer" "adoring" "adoringly" "adroit" "adroitly" "adulate" "adulation" "adulatory" "advanced" "advantage" "advantageous" "advantageously" "advantages" "adventuresome" "adventurous" "advocate" "advocated" "advocates" "affability" "affable" "affably" "affectation" "affection" "affectionate" "affinity" "affirm" "affirmation" "affirmative" "affluence" "affluent" "afford" "affordable" "affordably" "afordable" "agile" "agilely" "agility" "agreeable" "agreeableness" "agreeably" "all-around" "alluring" "alluringly" "altruistic" "altruistically" "amaze" "amazed" "amazement" "amazes" "amazing" "amazingly" "ambitious" "ambitiously" "ameliorate" "amenable" "amenity" "amiability" "amiabily" "amiable" "amicability" "amicable" "amicably" "amity" "ample" "amply" "amuse" "amusing" "amusingly" "angel" "angelic" "apotheosis" "appeal" "appealing" "applaud" "appreciable" "appreciate" "appreciated" "appreciates" "appreciative" "appreciatively" "appropriate" "approval" "approve" "ardent" "ardently" "ardor" "articulate" "aspiration" "aspirations" "aspire" "assurance" "assurances" "assure" "assuredly" "assuring" "astonish" "astonished" "astonishing" "astonishingly" "astonishment" "astound" "astounded" "astounding" "astoundingly" "astutely" "attentive" "attraction" "attractive" "attractively" "attune" "audible" "audibly" "auspicious" "authentic" "authoritative" "autonomous" "available" "aver" "avid" "avidly" "award" "awarded" "awards" "awe" "awed" "awesome" "awesomely" "awesomeness" "awestruck" "awsome" "backbone" "balanced" "bargain" "beauteous" "beautiful" "beautifullly" "beautifully" "beautify" "beauty" "beckon" "beckoned" "beckoning" "beckons" "believable" "believeable" "beloved" "benefactor" "beneficent" "beneficial" "beneficially" "beneficiary" "benefit" "benefits" "benevolence" "benevolent" "benifits" "best" "best-known" "best-performing" "best-selling" "better" "better-known" "better-than-expected" "beutifully" "blameless" "bless" "blessing" "bliss" "blissful" "blissfully" "blithe" "blockbuster" "bloom" "blossom" "bolster" "bonny" "bonus" "bonuses" "boom" "booming" "boost" "boundless" "bountiful" "brainiest" "brainy" "brand-new" "brave" "bravery" "bravo" "breakthrough" "breakthroughs" "breathlessness" "breathtaking" "breathtakingly" "breeze" "bright" "brighten" "brighter" "brightest" "brilliance" "brilliances" "brilliant" "brilliantly" "brisk" "brotherly" "bullish" "buoyant" "cajole" "calm" "calming" "calmness" "capability" "capable" "capably" "captivate" "captivating" "carefree" "cashback" "cashbacks" "catchy" "celebrate" "celebrated" "celebration" "celebratory" "champ" "champion" "charisma" "charismatic" "charitable" "charm" "charming" "charmingly" "chaste" "cheaper" "cheapest" "cheer" "cheerful" "cheery" "cherish" "cherished" "cherub" "chic" "chivalrous" "chivalry" "civility" "civilize" "clarity" "classic" "classy" "clean" "cleaner" "cleanest" "cleanliness" "cleanly" "clear" "clear-cut" "cleared" "clearer" "clearly" "clears" "clever" "cleverly" "cohere" "coherence" "coherent" "cohesive" "colorful" "comely" "comfort" "comfortable" "comfortably" "comforting" "comfy" "commend" "commendable" "commendably" "commitment" "commodious" "compact" "compactly" "compassion" "compassionate" "compatible" "competitive" "complement" "complementary" "complemented" "complements" "compliant" "compliment" "complimentary" "comprehensive" "conciliate" "conciliatory" "concise" "confidence" "confident" "congenial" "congratulate" "congratulation" "congratulations" "congratulatory" "conscientious" "considerate" "consistent" "consistently" "constructive" "consummate" "contentment" "continuity" "contrasty" "contribution" "convenience" "convenient" "conveniently" "convience" "convienient" "convient" "convincing" "convincingly" "cool" "coolest" "cooperative" "cooperatively" "cornerstone" "correct" "correctly" "cost-effective" "cost-saving" "counter-attack" "counter-attacks" "courage" "courageous" "courageously" "courageousness" "courteous" "courtly" "covenant" "cozy" "creative" "credence" "credible" "crisp" "crisper" "cure" "cure-all" "cushy" "cute" "cuteness" "danke" "danken" "daring" "daringly" "darling" "dashing" "dauntless" "dawn" "dazzle" "dazzled" "dazzling" "dead-cheap" "dead-on" "decency" "decent" "decisive" "decisiveness" "dedicated" "defeat" "defeated" "defeating" "defeats" "defender" "deference" "deft" "deginified" "delectable" "delicacy" "delicate" "delicious" "delight" "delighted" "delightful" "delightfully" "delightfulness" "dependable" "dependably" "deservedly" "deserving" "desirable" "desiring" "desirous" "destiny" "detachable" "devout" "dexterous" "dexterously" "dextrous" "dignified" "dignify" "dignity" "diligence" "diligent" "diligently" "diplomatic" "dirt-cheap" "distinction" "distinctive" "distinguished" "diversified" "divine" "divinely" "dominate" "dominated" "dominates" "dote" "dotingly" "doubtless" "dreamland" "dumbfounded" "dumbfounding" "dummy-proof" "durable" "dynamic" "eager" "eagerly" "eagerness" "earnest" "earnestly" "earnestness" "ease" "eased" "eases" "easier" "easiest" "easiness" "easing" "easy" "easy-to-use" "easygoing" "ebullience" "ebullient" "ebulliently" "ecenomical" "economical" "ecstasies" "ecstasy" "ecstatic" "ecstatically" "edify" "educated" "effective" "effectively" "effectiveness" "effectual" "efficacious" "efficient" "efficiently" "effortless" "effortlessly" "effusion" "effusive" "effusively" "effusiveness" "elan" "elate" "elated" "elatedly" "elation" "electrify" "elegance" "elegant" "elegantly" "elevate" "elite" "eloquence" "eloquent" "eloquently" "embolden" "eminence" "eminent" "empathize" "empathy" "empower" "empowerment" "enchant" "enchanted" "enchanting" "enchantingly" "encourage" "encouragement" "encouraging" "encouragingly" "endear" "endearing" "endorse" "endorsed" "endorsement" "endorses" "endorsing" "energetic" "energize" "energy-efficient" "energy-saving" "engaging" "engrossing" "enhance" "enhanced" "enhancement" "enhances" "enjoy" "enjoyable" "enjoyably" "enjoyed" "enjoying" "enjoyment" "enjoys" "enlighten" "enlightenment" "enliven" "ennoble" "enough" "enrapt" "enrapture" "enraptured" "enrich" "enrichment" "enterprising" "entertain" "entertaining" "entertains" "enthral" "enthrall" "enthralled" "enthuse" "enthusiasm" "enthusiast" "enthusiastic" "enthusiastically" "entice" "enticed" "enticing" "enticingly" "entranced" "entrancing" "entrust" "enviable" "enviably" "envious" "enviously" "enviousness" "envy" "equitable" "ergonomical" "err-free" "erudite" "ethical" "eulogize" "euphoria" "euphoric" "euphorically" "evaluative" "evenly" "eventful" "everlasting" "evocative" "exalt" "exaltation" "exalted" "exaltedly" "exalting" "exaltingly" "examplar" "examplary" "excallent" "exceed" "exceeded" "exceeding" "exceedingly" "exceeds" "excel" "exceled" "excelent" "excellant" "excelled" "excellence" "excellency" "excellent" "excellently" "excels" "exceptional" "exceptionally" "excite" "excited" "excitedly" "excitedness" "excitement" "excites" "exciting" "excitingly" "exellent" "exemplar" "exemplary" "exhilarate" "exhilarating" "exhilaratingly" "exhilaration" "exonerate" "expansive" "expeditiously" "expertly" "exquisite" "exquisitely" "extol" "extoll" "extraordinarily" "extraordinary" "exuberance" "exuberant" "exuberantly" "exult" "exultant" "exultation" "exultingly" "eye-catch" "eye-catching" "eyecatch" "eyecatching" "fabulous" "fabulously" "facilitate" "fair" "fairly" "fairness" "faith" "faithful" "faithfully" "faithfulness" "fame" "famed" "famous" "famously" "fancier" "fancinating" "fancy" "fanfare" "fans" "fantastic" "fantastically" "fascinate" "fascinating" "fascinatingly" "fascination" "fashionable" "fashionably" "fast" "fast-growing" "fast-paced" "faster" "fastest" "fastest-growing" "faultless" "fav" "fave" "favor" "favorable" "favored" "favorite" "favorited" "favour" "fearless" "fearlessly" "feasible" "feasibly" "feat" "feature-rich" "fecilitous" "feisty" "felicitate" "felicitous" "felicity" "fertile" "fervent" "fervently" "fervid" "fervidly" "fervor" "festive" "fidelity" "fiery" "fine" "fine-looking" "finely" "finer" "finest" "firmer" "first-class" "first-in-class" "first-rate" "flashy" "flatter" "flattering" "flatteringly" "flawless" "flawlessly" "flexibility" "flexible" "flourish" "flourishing" "fluent" "flutter" "fond" "fondly" "fondness" "foolproof" "foremost" "foresight" "formidable" "fortitude" "fortuitous" "fortuitously" "fortunate" "fortunately" "fortune" "fragrant" "free" "freed" "freedom" "freedoms" "fresh" "fresher" "freshest" "friendliness" "friendly" "frolic" "frugal" "fruitful" "ftw" "fulfillment" "fun" "futurestic" "futuristic" "gaiety" "gaily" "gain" "gained" "gainful" "gainfully" "gaining" "gains" "gallant" "gallantly" "galore" "geekier" "geeky" "gem" "gems" "generosity" "generous" "generously" "genial" "genius" "gentle" "gentlest" "genuine" "gifted" "glad" "gladden" "gladly" "gladness" "glamorous" "glee" "gleeful" "gleefully" "glimmer" "glimmering" "glisten" "glistening" "glitter" "glitz" "glorify" "glorious" "gloriously" "glory" "glow" "glowing" "glowingly" "god-given" "god-send" "godlike" "godsend" "gold" "golden" "good" "goodly" "goodness" "goodwill" "goood" "gooood" "gorgeous" "gorgeously" "grace" "graceful" "gracefully" "gracious" "graciously" "graciousness" "grand" "grandeur" "grateful" "gratefully" "gratification" "gratified" "gratifies" "gratify" "gratifying" "gratifyingly" "gratitude" "great" "greatest" "greatness" "grin" "groundbreaking" "guarantee" "guidance" "guiltless" "gumption" "gush" "gusto" "gutsy" "hail" "halcyon" "hale" "hallmark" "hallmarks" "hallowed" "handier" "handily" "hands-down" "handsome" "handsomely" "handy" "happier" "happily" "happiness" "happy" "hard-working" "hardier" "hardy" "harmless" "harmonious" "harmoniously" "harmonize" "harmony" "headway" "heal" "healthful" "healthy" "hearten" "heartening" "heartfelt" "heartily" "heartwarming" "heaven" "heavenly" "helped" "helpful" "helping" "hero" "heroic" "heroically" "heroine" "heroize" "heros" "high-quality" "high-spirited" "hilarious" "holy" "homage" "honest" "honesty" "honor" "honorable" "honored" "honoring" "hooray" "hopeful" "hospitable" "hot" "hotcake" "hotcakes" "hottest" "hug" "humane" "humble" "humility" "humor" "humorous" "humorously" "humour" "humourous" "ideal" "idealize" "ideally" "idol" "idolize" "idolized" "idyllic" "illuminate" "illuminati" "illuminating" "illumine" "illustrious" "ilu" "imaculate" "imaginative" "immaculate" "immaculately" "immense" "impartial" "impartiality" "impartially" "impassioned" "impeccable" "impeccably" "important" "impress" "impressed" "impresses" "impressive" "impressively" "impressiveness" "improve" "improved" "improvement" "improvements" "improves" "improving" "incredible" "incredibly" "indebted" "individualized" "indulgence" "indulgent" "industrious" "inestimable" "inestimably" "inexpensive" "infallibility" "infallible" "infallibly" "influential" "ingenious" "ingeniously" "ingenuity" "ingenuous" "ingenuously" "innocuous" "innovation" "innovative" "inpressed" "insightful" "insightfully" "inspiration" "inspirational" "inspire" "inspiring" "instantly" "instructive" "instrumental" "integral" "integrated" "intelligence" "intelligent" "intelligible" "interesting" "interests" "intimacy" "intimate" "intricate" "intrigue" "intriguing" "intriguingly" "intuitive" "invaluable" "invaluablely" "inventive" "invigorate" "invigorating" "invincibility" "invincible" "inviolable" "inviolate" "invulnerable" "irreplaceable" "irreproachable" "irresistible" "irresistibly" "issue-free" "jaw-droping" "jaw-dropping" "jollify" "jolly" "jovial" "joy" "joyful" "joyfully" "joyous" "joyously" "jubilant" "jubilantly" "jubilate" "jubilation" "jubiliant" "judicious" "justly" "keen" "keenly" "keenness" "kid-friendly" "kindliness" "kindly" "kindness" "knowledgeable" "kudos" "large-capacity" "laud" "laudable" "laudably" "lavish" "lavishly" "law-abiding" "lawful" "lawfully" "lead" "leading" "leads" "lean" "led" "legendary" "leverage" "levity" "liberate" "liberation" "liberty" "lifesaver" "light-hearted" "lighter" "likable" "like" "liked" "likes" "liking" "lionhearted" "lively" "logical" "long-lasting" "lovable" "lovably" "love" "loved" "loveliness" "lovely" "lover" "loves" "loving" "low-cost" "low-price" "low-priced" "low-risk" "lower-priced" "loyal" "loyalty" "lucid" "lucidly" "luck" "luckier" "luckiest" "luckiness" "lucky" "lucrative" "luminous" "lush" "luster" "lustrous" "luxuriant" "luxuriate" "luxurious" "luxuriously" "luxury" "lyrical" "magic" "magical" "magnanimous" "magnanimously" "magnificence" "magnificent" "magnificently" "majestic" "majesty" "manageable" "maneuverable" "marvel" "marveled" "marvelled" "marvellous" "marvelous" "marvelously" "marvelousness" "marvels" "master" "masterful" "masterfully" "masterpiece" "masterpieces" "masters" "mastery" "matchless" "mature" "maturely" "maturity" "meaningful" "memorable" "merciful" "mercifully" "mercy" "merit" "meritorious" "merrily" "merriment" "merriness" "merry" "mesmerize" "mesmerized" "mesmerizes" "mesmerizing" "mesmerizingly" "meticulous" "meticulously" "mightily" "mighty" "mind-blowing" "miracle" "miracles" "miraculous" "miraculously" "miraculousness" "modern" "modest" "modesty" "momentous" "monumental" "monumentally" "morality" "motivated" "multi-purpose" "navigable" "neat" "neatest" "neatly" "nice" "nicely" "nicer" "nicest" "nifty" "nimble" "noble" "nobly" "noiseless" "non-violence" "non-violent" "notably" "noteworthy" "nourish" "nourishing" "nourishment" "novelty" "nurturing" "oasis" "obsession" "obsessions" "obtainable" "openly" "openness" "optimal" "optimism" "optimistic" "opulent" "orderly" "originality" "outdo" "outdone" "outperform" "outperformed" "outperforming" "outperforms" "outshine" "outshone" "outsmart" "outstanding" "outstandingly" "outstrip" "outwit" "ovation" "overjoyed" "overtake" "overtaken" "overtakes" "overtaking" "overtook" "overture" "pain-free" "painless" "painlessly" "palatial" "pamper" "pampered" "pamperedly" "pamperedness" "pampers" "panoramic" "paradise" "paramount" "pardon" "passion" "passionate" "passionately" "patience" "patient" "patiently" "patriot" "patriotic" "peace" "peaceable" "peaceful" "peacefully" "peacekeepers" "peach" "peerless" "pep" "pepped" "pepping" "peppy" "peps" "perfect" "perfection" "perfectly" "permissible" "perseverance" "persevere" "personages" "personalized" "phenomenal" "phenomenally" "picturesque" "piety" "pinnacle" "playful" "playfully" "pleasant" "pleasantly" "pleased" "pleases" "pleasing" "pleasingly" "pleasurable" "pleasurably" "pleasure" "plentiful" "pluses" "plush" "plusses" "poetic" "poeticize" "poignant" "poise" "poised" "polished" "polite" "politeness" "popular" "portable" "posh" "positive" "positively" "positives" "powerful" "powerfully" "praise" "praiseworthy" "praising" "pre-eminent" "precious" "precise" "precisely" "preeminent" "prefer" "preferable" "preferably" "prefered" "preferes" "preferring" "prefers" "premier" "prestige" "prestigious" "prettily" "pretty" "priceless" "pride" "principled" "privilege" "privileged" "prize" "proactive" "problem-free" "problem-solver" "prodigious" "prodigiously" "prodigy" "productive" "productively" "proficient" "proficiently" "profound" "profoundly" "profuse" "profusion" "progress" "progressive" "prolific" "prominence" "prominent" "promise" "promised" "promises" "promising" "promoter" "prompt" "promptly" "proper" "properly" "propitious" "propitiously" "pros" "prosper" "prosperity" "prosperous" "prospros" "protect" "protection" "protective" "proud" "proven" "proves" "providence" "proving" "prowess" "prudence" "prudent" "prudently" "punctual" "pure" "purify" "purposeful" "quaint" "qualified" "qualify" "quicker" "quiet" "quieter" "radiance" "radiant" "rapid" "rapport" "rapt" "rapture" "raptureous" "raptureously" "rapturous" "rapturously" "rational" "razor-sharp" "reachable" "readable" "readily" "ready" "reaffirm" "reaffirmation" "realistic" "realizable" "reasonable" "reasonably" "reasoned" "reassurance" "reassure" "receptive" "reclaim" "recomend" "recommend" "recommendation" "recommendations" "recommended" "reconcile" "reconciliation" "record-setting" "recover" "recovery" "rectification" "rectify" "rectifying" "redeem" "redeeming" "redemption" "refine" "refined" "refinement" "reform" "reformed" "reforming" "reforms" "refresh" "refreshed" "refreshing" "refund" "refunded" "regal" "regally" "regard" "rejoice" "rejoicing" "rejoicingly" "rejuvenate" "rejuvenated" "rejuvenating" "relaxed" "relent" "reliable" "reliably" "relief" "relish" "remarkable" "remarkably" "remedy" "remission" "remunerate" "renaissance" "renewed" "renown" "renowned" "replaceable" "reputable" "reputation" "resilient" "resolute" "resound" "resounding" "resourceful" "resourcefulness" "respect" "respectable" "respectful" "respectfully" "respite" "resplendent" "responsibly" "responsive" "restful" "restored" "restructure" "restructured" "restructuring" "retractable" "revel" "revelation" "revere" "reverence" "reverent" "reverently" "revitalize" "revival" "revive" "revives" "revolutionary" "revolutionize" "revolutionized" "revolutionizes" "reward" "rewarding" "rewardingly" "rich" "richer" "richly" "richness" "right" "righten" "righteous" "righteously" "righteousness" "rightful" "rightfully" "rightly" "rightness" "risk-free" "robust" "rock-star" "rock-stars" "rockstar" "rockstars" "romantic" "romantically" "romanticize" "roomier" "roomy" "rosy" "safe" "safely" "sagacity" "sagely" "saint" "saintliness" "saintly" "salutary" "salute" "sane" "satisfactorily" "satisfactory" "satisfied" "satisfies" "satisfy" "satisfying" "satisified" "saver" "savings" "savior" "savvy" "scenic" "seamless" "seasoned" "secure" "securely" "selective" "self-determination" "self-respect" "self-satisfaction" "self-sufficiency" "self-sufficient" "sensation" "sensational" "sensationally" "sensations" "sensible" "sensibly" "sensitive" "serene" "serenity" "sexy" "sharp" "sharper" "sharpest" "shimmering" "shimmeringly" "shine" "shiny" "significant" "silent" "simpler" "simplest" "simplified" "simplifies" "simplify" "simplifying" "sincere" "sincerely" "sincerity" "skill" "skilled" "skillful" "skillfully" "slammin" "sleek" "slick" "smart" "smarter" "smartest" "smartly" "smile" "smiles" "smiling" "smilingly" "smitten" "smooth" "smoother" "smoothes" "smoothest" "smoothly" "snappy" "snazzy" "sociable" "soft" "softer" "solace" "solicitous" "solicitously" "solid" "solidarity" "soothe" "soothingly" "sophisticated" "soulful" "soundly" "soundness" "spacious" "sparkle" "sparkling" "spectacular" "spectacularly" "speedily" "speedy" "spellbind" "spellbinding" "spellbindingly" "spellbound" "spirited" "spiritual" "splendid" "splendidly" "splendor" "spontaneous" "sporty" "spotless" "sprightly" "stability" "stabilize" "stable" "stainless" "standout" "state-of-the-art" "stately" "statuesque" "staunch" "staunchly" "staunchness" "steadfast" "steadfastly" "steadfastness" "steadiest" "steadiness" "steady" "stellar" "stellarly" "stimulate" "stimulates" "stimulating" "stimulative" "stirringly" "straighten" "straightforward" "streamlined" "striking" "strikingly" "striving" "strong" "stronger" "strongest" "stunned" "stunning" "stunningly" "stupendous" "stupendously" "sturdier" "sturdy" "stylish" "stylishly" "stylized" "suave" "suavely" "sublime" "subsidize" "subsidized" "subsidizes" "subsidizing" "substantive" "succeed" "succeeded" "succeeding" "succeeds" "succes" "success" "successes" "successful" "successfully" "suffice" "sufficed" "suffices" "sufficient" "sufficiently" "suitable" "sumptuous" "sumptuously" "sumptuousness" "super" "superb" "superbly" "superior" "superiority" "supple" "support" "supported" "supporter" "supporting" "supportive" "supports" "supremacy" "supreme" "supremely" "supurb" "supurbly" "surmount" "surpass" "surreal" "survival" "survivor" "sustainability" "sustainable" "swank" "swankier" "swankiest" "swanky" "sweeping" "sweet" "sweeten" "sweetheart" "sweetly" "sweetness" "swift" "swiftness" "talent" "talented" "talents" "tantalize" "tantalizing" "tantalizingly" "tempt" "tempting" "temptingly" "tenacious" "tenaciously" "tenacity" "tender" "tenderly" "terrific" "terrifically" "thank" "thankful" "thinner" "thoughtful" "thoughtfully" "thoughtfulness" "thrift" "thrifty" "thrill" "thrilled" "thrilling" "thrillingly" "thrills" "thrive" "thriving" "thumb-up" "thumbs-up" "tickle" "tidy" "time-honored" "timely" "tingle" "titillate" "titillating" "titillatingly" "togetherness" "tolerable" "toll-free" "top" "top-notch" "top-quality" "topnotch" "tops" "tough" "tougher" "toughest" "traction" "tranquil" "tranquility" "transparent" "treasure" "tremendously" "trendy" "triumph" "triumphal" "triumphant" "triumphantly" "trivially" "trophy" "trouble-free" "trump" "trumpet" "trust" "trusted" "trusting" "trustingly" "trustworthiness" "trustworthy" "trusty" "truthful" "truthfully" "truthfulness" "twinkly" "ultra-crisp" "unabashed" "unabashedly" "unaffected" "unassailable" "unbeatable" "unbiased" "unbound" "uncomplicated" "unconditional" "undamaged" "undaunted" "understandable" "undisputable" "undisputably" "undisputed" "unencumbered" "unequivocal" "unequivocally" "unfazed" "unfettered" "unforgettable" "unity" "unlimited" "unmatched" "unparalleled" "unquestionable" "unquestionably" "unreal" "unrestricted" "unrivaled" "unselfish" "unwavering" "upbeat" "upgradable" "upgradeable" "upgraded" "upheld" "uphold" "uplift" "uplifting" "upliftingly" "upliftment" "upscale" "usable" "useable" "useful" "user-friendly" "user-replaceable" "valiant" "valiantly" "valor" "valuable" "variety" "venerate" "verifiable" "veritable" "versatile" "versatility" "vibrant" "vibrantly" "victorious" "victory" "viewable" "vigilance" "vigilant" "virtue" "virtuous" "virtuously" "visionary" "vivacious" "vivid" "vouch" "vouchsafe" "warm" "warmer" "warmhearted" "warmly" "warmth" "wealthy" "welcome" "well" "well-backlit" "well-balanced" "well-behaved" "well-being" "well-bred" "well-connected" "well-educated" "well-established" "well-informed" "well-intentioned" "well-known" "well-made" "well-managed" "well-mannered" "well-positioned" "well-received" "well-regarded" "well-rounded" "well-run" "well-wishers" "wellbeing" "whoa" "wholeheartedly" "wholesome" "whooa" "whoooa" "wieldy" "willing" "willingly" "willingness" "win" "windfall" "winnable" "winner" "winners" "winning" "wins" "wisdom" "wise" "wisely" "witty" "won" "wonder" "wonderful" "wonderfully" "wonderous" "wonderously" "wonders" "wondrous" "woo" "work" "workable" "worked" "works" "world-famous" "worth" "worth-while" "worthiness" "worthwhile" "worthy" "wow" "wowed" "wowing" "wows" "yay" "youthful" "zeal" "zenith" "zest" "zippy"})
true
(ns plugh.util.sent-analysis (:require [clojure.string :as str] [clojure.core.async :as async])) (declare pos neg) (defn calc-sentiment [line] (let [splits (str/split (str/lower-case (str/replace (str/replace line #"\p{Punct}" " ") #"\p{Cntrl}" " ")) #" +")] {:pos (count (filter pos splits)) :neg (* -1 (count (filter neg splits)))} )) (defn xform [the-func the-chan] (async/map< (fn [z] (do ;; (println "Xform from " z " to " (the-func z)) (the-func z))) the-chan)) (defn xfilter [the-func the-chan] (async/filter< (fn [z] (do ;; (println "Filtering incoming value " z) (the-func z))) the-chan)) (defn flow [the-func seed the-chan] (let [cur-val (atom seed)] (async/map< (fn [mv] (let [new-val (the-func @cur-val mv)] (reset! cur-val new-val) new-val)) the-chan))) (defn arrow-update-func [the-var func-map] (reduce (fn [cur v] (let [[the-key the-func] v] (assoc cur the-key (the-func (the-key cur))))) the-var (into [] func-map))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; Opinion Lexicon: Negative & Positive ; ; This file contains a list of NEGATIVE and POSITIVE opinion words (or sentiment words). ; Copied from https://github.com/redmonk/bluebird ; ; This file and the papers can all be downloaded from ; http://www.cs.uic.edu/~liub/FBS/sentiment-analysis.html ; ; If you use this list, please cite one of the following two papers: ; ; PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI. "Mining and Summarizing Customer Reviews." ; Proceedings of the ACM SIGKDD International Conference on Knowledge ; Discovery and Data Mining (KDD-2004), Aug 22-25, 2004, Seattle, ; Washington, USA, ; PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI. "Opinion Observer: Analyzing ; and Comparing Opinions on the Web." Proceedings of the 14th ; International World Wide Web conference (WWW-2005), May 10-14, ; 2005, Chiba, Japan. ; ; Notes: ; 1. The appearance of an opinion word in a sentence does not necessarily ; mean that the sentence expresses a positive or negative opinion. ; See the paper below: ; ; PI:NAME:<NAME>END_PI. "Sentiment Analysis and Subjectivity." An chapter in ; Handbook of Natural Language Processing, Second Edition, ; (editors: PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI), 2010. ; ; 2. You will notice many misspelled words in the list. They are not ; mistakes. They are included as these misspelled words appear ; frequently in social media content. ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (def neg #{"2-faced" "2-faces" "abnormal" "abolish" "abominable" "abominably" "abominate" "abomination" "abort" "aborted" "aborts" "abrade" "abrasive" "abrupt" "abruptly" "abscond" "absence" "absent-minded" "absentee" "absurd" "absurdity" "absurdly" "absurdness" "abuse" "abused" "abuses" "abusive" "abysmal" "abysmally" "abyss" "accidental" "accost" "accursed" "accusation" "accusations" "accuse" "accuses" "accusing" "accusingly" "acerbate" "acerbic" "acerbically" "ache" "ached" "aches" "achey" "aching" "acrid" "acridly" "acridness" "acrimonious" "acrimoniously" "acrimony" "adamant" "adamantly" "addict" "addicted" "addicting" "addicts" "admonish" "admonisher" "admonishingly" "admonishment" "admonition" "adulterate" "adulterated" "adulteration" "adulterier" "adversarial" "adversary" "adverse" "adversity" "afflict" "affliction" "afflictive" "affront" "afraid" "aggravate" "aggravating" "aggravation" "aggression" "aggressive" "aggressiveness" "aggressor" "aggrieve" "aggrieved" "aggrivation" "aghast" "agonies" "agonize" "agonizing" "agonizingly" "agony" "aground" "ail" "ailing" "ailment" "aimless" "alarm" "alarmed" "alarming" "alarmingly" "alienate" "alienated" "alienation" "allegation" "allegations" "allege" "allergic" "allergies" "allergy" "aloof" "altercation" "ambiguity" "ambiguous" "ambivalence" "ambivalent" "ambush" "amiss" "amputate" "anarchism" "anarchist" "anarchistic" "anarchy" "anemic" "anger" "angrily" "angriness" "angry" "anguish" "animosity" "annihilate" "annihilation" "annoy" "annoyance" "annoyances" "annoyed" "annoying" "annoyingly" "annoys" "anomalous" "anomaly" "antagonism" "antagonist" "antagonistic" "antagonize" "anti-" "anti-american" "anti-israeli" "anti-occupation" "anti-proliferation" "anti-semites" "anti-social" "anti-us" "anti-white" "antipathy" "antiquated" "antithetical" "anxieties" "anxiety" "anxious" "anxiously" "anxiousness" "apathetic" "apathetically" "apathy" "apocalypse" "apocalyptic" "apologist" "apologists" "appal" "appall" "appalled" "appalling" "appallingly" "apprehension" "apprehensions" "apprehensive" "apprehensively" "arbitrary" "arcane" "archaic" "arduous" "arduously" "argumentative" "arrogance" "arrogant" "arrogantly" "ashamed" "asinine" "asininely" "asinininity" "askance" "asperse" "aspersion" "aspersions" "assail" "assassin" "assassinate" "assault" "assult" "astray" "asunder" "atrocious" "atrocities" "atrocity" "atrophy" "attack" "attacks" "audacious" "audaciously" "audaciousness" "audacity" "audiciously" "austere" "authoritarian" "autocrat" "autocratic" "avalanche" "avarice" "avaricious" "avariciously" "avenge" "averse" "aversion" "aweful" "awful" "awfully" "awfulness" "awkward" "awkwardness" "ax" "babble" "back-logged" "back-wood" "back-woods" "backache" "backaches" "backaching" "backbite" "backbiting" "backward" "backwardness" "backwood" "backwoods" "bad" "badly" "baffle" "baffled" "bafflement" "baffling" "bait" "balk" "banal" "banalize" "bane" "banish" "banishment" "bankrupt" "barbarian" "barbaric" "barbarically" "barbarity" "barbarous" "barbarously" "barren" "baseless" "bash" "bashed" "bashful" "bashing" "bastard" "bastards" "battered" "battering" "batty" "bearish" "beastly" "bedlam" "bedlamite" "befoul" "beg" "beggar" "beggarly" "begging" "beguile" "belabor" "belated" "beleaguer" "belie" "belittle" "belittled" "belittling" "bellicose" "belligerence" "belligerent" "belligerently" "bemoan" "bemoaning" "bemused" "bent" "berate" "bereave" "bereavement" "bereft" "berserk" "beseech" "beset" "besiege" "besmirch" "bestial" "betray" "betrayal" "betrayals" "betrayer" "betraying" "betrays" "bewail" "beware" "bewilder" "bewildered" "bewildering" "bewilderingly" "bewilderment" "bewitch" "bias" "biased" "biases" "bicker" "bickering" "bid-rigging" "bigotries" "bigotry" "bitch" "bitchy" "biting" "bitingly" "bitter" "bitterly" "bitterness" "bizarre" "blab" "blabber" "blackmail" "blah" "blame" "blameworthy" "bland" "blandish" "blaspheme" "blasphemous" "blasphemy" "blasted" "blatant" "blatantly" "blather" "bleak" "bleakly" "bleakness" "bleed" "bleeding" "bleeds" "blemish" "blind" "blinding" "blindingly" "blindside" "blister" "blistering" "bloated" "blockage" "blockhead" "bloodshed" "bloodthirsty" "bloody" "blotchy" "blow" "blunder" "blundering" "blunders" "blunt" "blur" "bluring" "blurred" "blurring" "blurry" "blurs" "blurt" "boastful" "boggle" "bogus" "boil" "boiling" "boisterous" "bomb" "bombard" "bombardment" "bombastic" "bondage" "bonPI:NAME:<NAME>END_PI" "bore" "bored" "boredom" "bores" "boring" "botch" "bother" "bothered" "bothering" "bothers" "bothersome" "bowdlerize" "boycott" "brPI:NAME:<NAME>END_PI" "bragger" "brainless" "brainwash" "brash" "brashly" "brashness" "brat" "bravado" "brazen" "brazenly" "brazenness" "breach" "break" "break-up" "break-ups" "breakdown" "breaking" "breaks" "breakup" "breakups" "bribery" "brimstone" "bristle" "brittle" "broke" "broken" "broken-hearted" "brood" "browbeat" "bruise" "bruised" "bruises" "bruising" "brusque" "brutal" "brutalising" "brutalities" "brutality" "brutalize" "brutalizing" "brutally" "brute" "brutish" "bs" "buckle" "bug" "bugging" "buggy" "bugs" "bulkier" "bulkiness" "bulky" "bulkyness" "bull****" "bull----" "bullies" "bullshit" "bullshyt" "bully" "bullying" "bullyingly" "bum" "bump" "bumped" "bumping" "bumpping" "bumps" "bumpy" "bungle" "bungler" "bungling" "bunk" "burden" "burdensome" "burdensomely" "burn" "burned" "burning" "burns" "bust" "busts" "busybody" "butcher" "butchery" "buzzing" "byzantine" "cackle" "calamities" "calamitous" "calamitously" "calamity" "callous" "calumniate" "calumniation" "calumnies" "calumnious" "calumniously" "calumny" "cancer" "cancerous" "cannibal" "cannibalize" "capitulate" "capricious" "capriciously" "capriciousness" "capsize" "careless" "carelessness" "caricature" "carnage" "carp" "cartoonish" "cash-strapped" "castigate" "castrated" "casualty" "cataclysm" "cataclysmal" "cataclysmic" "cataclysmically" "catastrophe" "catastrophes" "catastrophic" "catastrophically" "catastrophies" "caustic" "caustically" "cautionary" "cave" "censure" "chafe" "chaff" "chagrin" "challenging" "chaos" "chaotic" "chasten" "chastise" "chastisement" "chatter" "chatterbox" "cheap" "cheapen" "cheaply" "cheat" "cheated" "cheater" "cheating" "cheats" "checkered" "cheerless" "cheesy" "chide" "childish" "chill" "chilly" "chintzy" "choke" "choleric" "choppy" "chore" "chronic" "chunky" "clamor" "clamorous" "clash" "cliche" "cliched" "clique" "clog" "clogged" "clogs" "cloud" "clouding" "cloudy" "clueless" "clumsy" "clunky" "coarse" "cocky" "coerce" "coercion" "coercive" "cold" "coldly" "collapse" "collude" "collusion" "combative" "combust" "comical" "commiserate" "commonplace" "commotion" "commotions" "complacent" "complain" "complained" "complaining" "complains" "complaint" "complaints" "complex" "complicated" "complication" "complicit" "compulsion" "compulsive" "concede" "conceded" "conceit" "conceited" "concen" "concens" "concern" "concerned" "concerns" "concession" "concessions" "condemn" "condemnable" "condemnation" "condemned" "condemns" "condescend" "condescending" "condescendingly" "condescension" "confess" "confession" "confessions" "confined" "conflict" "conflicted" "conflicting" "conflicts" "confound" "confounded" "confounding" "confront" "confrontation" "confrontational" "confuse" "confused" "confuses" "confusing" "confusion" "confusions" "congested" "congestion" "cons" "conscons" "conservative" "conspicuous" "conspicuously" "conspiracies" "conspiracy" "conspirator" "conspiratorial" "conspire" "consternation" "contagious" "contaminate" "contaminated" "contaminates" "contaminating" "contamination" "contempt" "contemptible" "contemptuous" "contemptuously" "contend" "contention" "contentious" "contort" "contortions" "contradict" "contradiction" "contradictory" "contrariness" "contravene" "contrive" "contrived" "controversial" "controversy" "convoluted" "corrode" "corrosion" "corrosions" "corrosive" "corrupt" "corrupted" "corrupting" "corruption" "corrupts" "corruptted" "costlier" "costly" "counter-productive" "counterproductive" "coupists" "covetous" "coward" "cowardly" "crabby" "crack" "cracked" "cracks" "craftily" "craftly" "crafty" "cramp" "cramped" "cramping" "cranky" "crap" "crappy" "craps" "crash" "crashed" "crashes" "crashing" "crass" "craven" "cravenly" "craze" "crazily" "craziness" "crazy" "creak" "creaking" "creaks" "credulous" "creep" "creeping" "creeps" "creepy" "crept" "crime" "criminal" "cringe" "cringed" "cringes" "cripple" "crippled" "cripples" "crippling" "crisis" "critic" "critical" "criticism" "criticisms" "criticize" "criticized" "criticizing" "critics" "cronyism" "crook" "crooked" "crooks" "crowded" "crowdedness" "crude" "cruel" "crueler" "cruelest" "cruelly" "cruelness" "cruelties" "cruelty" "crumble" "crumbling" "crummy" "crumple" "crumpled" "crumples" "crush" "crushed" "crushing" "cry" "culpable" "culprit" "cumbersome" "cunt" "cunts" "cuplrit" "curse" "cursed" "curses" "curt" "cuss" "cussed" "cutthroat" "cynical" "cynicism" "d*mn" "damage" "damaged" "damages" "damaging" "damn" "damnable" "damnably" "damnation" "damned" "damning" "damper" "danger" "dangerous" "dangerousness" "dark" "darken" "darkened" "darker" "darkness" "dastard" "dastardly" "daunt" "daunting" "dauntingly" "dawdle" "daze" "dazed" "dead" "deadbeat" "deadlock" "deadly" "deadweight" "deaf" "dearth" "death" "debacle" "debase" "debasement" "debaser" "debatable" "debauch" "debaucher" "debauchery" "debilitate" "debilitating" "debility" "debt" "debts" "decadence" "decadent" "decay" "decayed" "deceit" "deceitful" "deceitfully" "deceitfulness" "deceive" "deceiver" "deceivers" "deceiving" "deception" "deceptive" "deceptively" "declaim" "decline" "declines" "declining" "decrement" "decrepit" "decrepitude" "decry" "defamation" "defamations" "defamatory" "defame" "defect" "defective" "defects" "defensive" "defiance" "defiant" "defiantly" "deficiencies" "deficiency" "deficient" "defile" "defiler" "deform" "deformed" "defrauding" "defunct" "defy" "degenerate" "degenerately" "degeneration" "degradation" "degrade" "degrading" "degradingly" "dehumanization" "dehumanize" "deign" "deject" "dejected" "dejectedly" "dejection" "delay" "delayed" "delaying" "delays" "delinquency" "delinquent" "delirious" "delirium" "delude" "deluded" "deluge" "delusion" "delusional" "delusions" "demean" "demeaning" "demise" "demolish" "demolisher" "demon" "demonic" "demonize" "demonized" "demonizes" "demonizing" "demoralize" "demoralizing" "demoralizingly" "denial" "denied" "denies" "denigrate" "denounce" "dense" "dent" "dented" "dents" "denunciate" "denunciation" "denunciations" "deny" "denying" "deplete" "deplorable" "deplorably" "deplore" "deploring" "deploringly" "deprave" "depraved" "depravedly" "deprecate" "depress" "depressed" "depressing" "depressingly" "depression" "depressions" "deprive" "deprived" "deride" "derision" "derisive" "derisively" "derisiveness" "derogatory" "desecrate" "desert" "desertion" "desiccate" "desiccated" "desititute" "desolate" "desolately" "desolation" "despair" "despairing" "despairingly" "desperate" "desperately" "desperation" "despicable" "despicably" "despise" "despised" "despoil" "despoiler" "despondence" "despondency" "despondent" "despondently" "despot" "despotic" "despotism" "destabilisation" "destains" "destitute" "destitution" "destroy" "destroyer" "destruction" "destructive" "desultory" "deter" "deteriorate" "deteriorating" "deterioration" "deterrent" "detest" "detestable" "detestably" "detested" "detesting" "detests" "detract" "detracted" "detracting" "detraction" "detracts" "detriment" "detrimental" "devastate" "devastated" "devastates" "devastating" "devastatingly" "devastation" "deviate" "deviation" "devil" "devilish" "devilishly" "devilment" "devilry" "devious" "deviously" "deviousness" "devoid" "diabolic" "diabolical" "diabolically" "diametrically" "diappointed" "diatribe" "diatribes" "dick" "dictator" "dictatorial" "die" "die-hard" "died" "dies" "difficult" "difficulties" "difficulty" "diffidence" "dilapidated" "dilemma" "dilly-dally" "dim" "dimmer" "din" "ding" "dings" "dinky" "dire" "direly" "direness" "dirt" "dirtbag" "dirtbags" "dirts" "dirty" "disable" "disabled" "disaccord" "disadvantage" "disadvantaged" "disadvantageous" "disadvantages" "disaffect" "disaffected" "disaffirm" "disagree" "disagreeable" "disagreeably" "disagreed" "disagreeing" "disagreement" "disagrees" "disallow" "disapointed" "disapointing" "disapointment" "disappoint" "disappointed" "disappointing" "disappointingly" "disappointment" "disappointments" "disappoints" "disapprobation" "disapproval" "disapprove" "disapproving" "disarm" "disarray" "disaster" "disasterous" "disastrous" "disastrously" "disavow" "disavowal" "disbelief" "disbelieve" "disbeliever" "disclaim" "discombobulate" "discomfit" "discomfititure" "discomfort" "discompose" "disconcert" "disconcerted" "disconcerting" "disconcertingly" "disconsolate" "disconsolately" "disconsolation" "discontent" "discontented" "discontentedly" "discontinued" "discontinuity" "discontinuous" "discord" "discordance" "discordant" "discountenance" "discourage" "discouragement" "discouraging" "discouragingly" "discourteous" "discourteously" "discoutinous" "discredit" "discrepant" "discriminate" "discrimination" "discriminatory" "disdain" "disdained" "disdainful" "disdainfully" "disfavor" "disgrace" "disgraced" "disgraceful" "disgracefully" "disgruntle" "disgruntled" "disgust" "disgusted" "disgustedly" "disgustful" "disgustfully" "disgusting" "disgustingly" "dishearten" "disheartening" "dishearteningly" "dishonest" "dishonestly" "dishonesty" "dishonor" "dishonorable" "dishonorablely" "disillusion" "disillusioned" "disillusionment" "disillusions" "disinclination" "disinclined" "disingenuous" "disingenuously" "disintegrate" "disintegrated" "disintegrates" "disintegration" "disinterest" "disinterested" "dislike" "disliked" "dislikes" "disliking" "dislocated" "disloyal" "disloyalty" "dismal" "dismally" "dismalness" "dismay" "dismayed" "dismaying" "dismayingly" "dismissive" "dismissively" "disobedience" "disobedient" "disobey" "disoobedient" "disorder" "disordered" "disorderly" "disorganized" "disorient" "disoriented" "disown" "disparage" "disparaging" "disparagingly" "dispensable" "dispirit" "dispirited" "dispiritedly" "dispiriting" "displace" "displaced" "displease" "displeased" "displeasing" "displeasure" "disproportionate" "disprove" "disputable" "dispute" "disputed" "disquiet" "disquieting" "disquietingly" "disquietude" "disregard" "disregardful" "disreputable" "disrepute" "disrespect" "disrespectable" "disrespectablity" "disrespectful" "disrespectfully" "disrespectfulness" "disrespecting" "disrupt" "disruption" "disruptive" "diss" "dissapointed" "dissappointed" "dissappointing" "dissatisfaction" "dissatisfactory" "dissatisfied" "dissatisfies" "dissatisfy" "dissatisfying" "dissed" "dissemble" "dissembler" "dissension" "dissent" "dissenter" "dissention" "disservice" "disses" "dissidence" "dissident" "dissidents" "dissing" "dissocial" "dissolute" "dissolution" "dissonance" "dissonant" "dissonantly" "dissuade" "dissuasive" "distains" "distaste" "distasteful" "distastefully" "distort" "distorted" "distortion" "distorts" "distract" "distracting" "distraction" "distraught" "distraughtly" "distraughtness" "distress" "distressed" "distressing" "distressingly" "distrust" "distrustful" "distrusting" "disturb" "disturbance" "disturbed" "disturbing" "disturbingly" "disunity" "disvalue" "divergent" "divisive" "divisively" "divisiveness" "dizzing" "dizzingly" "dizzy" "doddering" "dodgey" "dogged" "doggedly" "dogmatic" "doldrums" "domineer" "domineering" "donside" "doom" "doomed" "doomsday" "dope" "doubt" "doubtful" "doubtfully" "doubts" "douchbag" "douchebag" "douchebags" "downbeat" "downcast" "downer" "downfall" "downfallen" "downgrade" "downhearted" "downheartedly" "downhill" "downside" "downsides" "downturn" "downturns" "drab" "draconian" "draconic" "drag" "dragged" "dragging" "dragoon" "drags" "drain" "drained" "draining" "drains" "drastic" "drastically" "drawback" "drawbacks" "dread" "dreadful" "dreadfully" "dreadfulness" "dreary" "dripped" "dripping" "drippy" "drips" "drones" "droop" "droops" "drop-out" "drop-outs" "dropout" "dropouts" "drought" "drowning" "drunk" "drunkard" "drunken" "dubious" "dubiously" "dubitable" "dud" "dull" "dullard" "dumb" "dumbfound" "dump" "dumped" "dumping" "dumps" "dunce" "dungeon" "dungeons" "dupe" "dust" "dusty" "dwindling" "dying" "earsplitting" "eccentric" "eccentricity" "effigy" "effrontery" "egocentric" "egomania" "egotism" "egotistical" "egotistically" "egregious" "egregiously" "election-rigger" "elimination" "emaciated" "emasculate" "embarrass" "embarrassing" "embarrassingly" "embarrassment" "embattled" "embroil" "embroiled" "embroilment" "emergency" "emphatic" "emphatically" "emptiness" "encroach" "encroachment" "endanger" "enemies" "enemy" "enervate" "enfeeble" "enflame" "engulf" "enjoin" "enmity" "enrage" "enraged" "enraging" "enslave" "entangle" "entanglement" "entrap" "entrapment" "envious" "enviously" "enviousness" "epidemic" "equivocal" "erase" "erode" "erodes" "erosion" "err" "errant" "erratic" "erratically" "erroneous" "erroneously" "error" "errors" "eruptions" "escapade" "eschew" "estranged" "evade" "evasion" "evasive" "evil" "evildoer" "evils" "eviscerate" "exacerbate" "exagerate" "exagerated" "exagerates" "exaggerate" "exaggeration" "exasperate" "exasperated" "exasperating" "exasperatingly" "exasperation" "excessive" "excessively" "exclusion" "excoriate" "excruciating" "excruciatingly" "excuse" "excuses" "execrate" "exhaust" "exhausted" "exhaustion" "exhausts" "exhorbitant" "exhort" "exile" "exorbitant" "exorbitantance" "exorbitantly" "expel" "expensive" "expire" "expired" "explode" "exploit" "exploitation" "explosive" "expropriate" "expropriation" "expulse" "expunge" "exterminate" "extermination" "extinguish" "extort" "extortion" "extraneous" "extravagance" "extravagant" "extravagantly" "extremism" "extremist" "extremists" "eyesore" "f**k" "fabricate" "fabrication" "facetious" "facetiously" "fail" "failed" "failing" "fails" "failure" "failures" "faint" "fainthearted" "faithless" "fake" "fall" "fallacies" "fallacious" "fallaciously" "fallaciousness" "fallacy" "fallen" "falling" "fallout" "falls" "false" "falsehood" "falsely" "falsify" "falter" "faltered" "famine" "famished" "fanatic" "fanatical" "fanatically" "fanaticism" "fanatics" "fanciful" "far-fetched" "farce" "farcical" "farcical-yet-provocative" "farcically" "farfetched" "fascism" "fascist" "fastidious" "fastidiously" "fastuous" "fat" "fat-cat" "fat-cats" "fatal" "fatalistic" "fatalistically" "fatally" "fatcat" "fatcats" "fateful" "fatefully" "fathomless" "fatigue" "fatigued" "fatique" "fatty" "fatuity" "fatuous" "fatuously" "fault" "faults" "faulty" "fawningly" "faze" "fear" "fearful" "fearfully" "fears" "fearsome" "feckless" "feeble" "feeblely" "feebleminded" "feign" "feint" "fell" "felon" "felonious" "ferociously" "ferocity" "fetid" "fever" "feverish" "fevers" "fiasco" "fib" "fibber" "fickle" "fiction" "fictional" "fictitious" "fidget" "fidgety" "fiend" "fiendish" "fierce" "figurehead" "filth" "filthy" "finagle" "finicky" "fissures" "fist" "flabbergast" "flabbergasted" "flagging" "flagrant" "flagrantly" "flair" "flairs" "flak" "flake" "flakey" "flakieness" "flaking" "flaky" "flare" "flares" "flareup" "flareups" "flat-out" "flaunt" "flaw" "flawed" "flaws" "flee" "fleed" "fleeing" "fleer" "flees" "fleeting" "flicering" "flicker" "flickering" "flickers" "flighty" "flimflam" "flimsy" "flirt" "flirty" "floored" "flounder" "floundering" "flout" "fluster" "foe" "fool" "fooled" "foolhardy" "foolish" "foolishly" "foolishness" "forbid" "forbidden" "forbidding" "forceful" "foreboding" "forebodingly" "forfeit" "forged" "forgetful" "forgetfully" "forgetfulness" "forlorn" "forlornly" "forsake" "forsaken" "forswear" "foul" "foully" "foulness" "fractious" "fractiously" "fracture" "fragile" "fragmented" "frail" "frantic" "frantically" "franticly" "fraud" "fraudulent" "fraught" "frazzle" "frazzled" "freak" "freaking" "freakish" "freakishly" "freaks" "freeze" "freezes" "freezing" "frenetic" "frenetically" "frenzied" "frenzy" "fret" "fretful" "frets" "friction" "frictions" "fried" "friggin" "frigging" "fright" "frighten" "frightening" "frighteningly" "frightful" "frightfully" "frigid" "frost" "frown" "froze" "frozen" "fruitless" "fruitlessly" "frustrate" "frustrated" "frustrates" "frustrating" "frustratingly" "frustration" "frustrations" "fuck" "fucking" "fudge" "fugitive" "full-blown" "fulminate" "fumble" "fume" "fumes" "fundamentalism" "funky" "funnily" "funny" "furious" "furiously" "furor" "fury" "fuss" "fussy" "fustigate" "fusty" "futile" "futilely" "futility" "fuzzy" "gabble" "gaff" "gaffe" "gainsay" "gainsayer" "gall" "galling" "gallingly" "galls" "gangster" "gape" "garbage" "garish" "gasp" "gauche" "gaudy" "gawk" "gawky" "geezer" "genocide" "get-rich" "ghastly" "ghetto" "ghosting" "gibber" "gibberish" "gibe" "giddy" "gimmick" "gimmicked" "gimmicking" "gimmicks" "gimmicky" "glare" "glaringly" "glib" "glibly" "glitch" "glitches" "gloatingly" "gloom" "gloomy" "glower" "glum" "glut" "gnawing" "goad" "goading" "god-awful" "goof" "goofy" "goon" "gossip" "graceless" "gracelessly" "graft" "grainy" "grapple" "grate" "grating" "gravely" "greasy" "greed" "greedy" "grief" "grievance" "grievances" "grieve" "grieving" "grievous" "grievously" "grim" "grimace" "grind" "gripe" "gripes" "grisly" "gritty" "gross" "grossly" "grotesque" "grouch" "grouchy" "groundless" "grouse" "growl" "grudge" "grudges" "grudging" "grudgingly" "gruesome" "gruesomely" "gruff" "grumble" "grumpier" "grumpiest" "grumpily" "grumpish" "grumpy" "guile" "guilt" "guiltily" "guilty" "gullible" "gutless" "gutter" "hack" "hacks" "haggard" "haggle" "hairloss" "halfhearted" "halfheartedly" "hallucinate" "hallucination" "hamper" "hampered" "handicapped" "hang" "hangs" "haphazard" "hapless" "harangue" "harass" "harassed" "harasses" "harassment" "harboring" "harbors" "hard" "hard-hit" "hard-line" "hard-liner" "hardball" "harden" "hardened" "hardheaded" "hardhearted" "hardliner" "hardliners" "hardship" "hardships" "harm" "harmed" "harmful" "harms" "harpy" "harridan" "harried" "harrow" "harsh" "harshly" "hasseling" "hassle" "hassled" "hassles" "haste" "hastily" "hasty" "hate" "hated" "hateful" "hatefully" "hatefulness" "hater" "haters" "hates" "hating" "hatred" "haughtily" "haughty" "haunt" "haunting" "havoc" "hawkish" "haywire" "hazard" "hazardous" "haze" "hazy" "head-aches" "headache" "headaches" "heartbreaker" "heartbreaking" "heartbreakingly" "heartless" "heathen" "heavy-handed" "heavyhearted" "heck" "heckle" "heckled" "heckles" "hectic" "hedge" "hedonistic" "heedless" "hefty" "hegemonism" "hegemonistic" "hegemony" "heinous" "hell" "hell-bent" "hellion" "hells" "helpless" "helplessly" "helplessness" "heresy" "heretic" "heretical" "hesitant" "hestitant" "hideous" "hideously" "hideousness" "high-priced" "hiliarious" "hinder" "hindrance" "hiss" "hissed" "hissing" "ho-hum" "hoard" "hoax" "hobble" "hogs" "hollow" "hoodium" "hoodwink" "hooligan" "hopeless" "hopelessly" "hopelessness" "horde" "horrendous" "horrendously" "horrible" "horrid" "horrific" "horrified" "horrifies" "horrify" "horrifying" "horrifys" "hostage" "hostile" "hostilities" "hostility" "hotbeds" "hothead" "hotheaded" "hothouse" "hubris" "huckster" "hum" "humid" "humiliate" "humiliating" "humiliation" "humming" "hung" "hurt" "hurted" "hurtful" "hurting" "hurts" "hustler" "hype" "hypocricy" "hypocrisy" "hypocrite" "hypocrites" "hypocritical" "hypocritically" "hysteria" "hysteric" "hysterical" "hysterically" "hysterics" "idiocies" "idiocy" "idiot" "idiotic" "idiotically" "idiots" "idle" "ignoble" "ignominious" "ignominiously" "ignominy" "ignorance" "ignorant" "ignore" "ill-advised" "ill-conceived" "ill-defined" "ill-designed" "ill-fated" "ill-favored" "ill-formed" "ill-mannered" "ill-natured" "ill-sorted" "ill-tempered" "ill-treated" "ill-treatment" "ill-usage" "ill-used" "illegal" "illegally" "illegitimate" "illicit" "illiterate" "illness" "illogic" "illogical" "illogically" "illusion" "illusions" "illusory" "imaginary" "imbalance" "imbecile" "imbroglio" "immaterial" "immature" "imminence" "imminently" "immobilized" "immoderate" "immoderately" "immodest" "immoral" "immorality" "immorally" "immovable" "impair" "impaired" "impasse" "impatience" "impatient" "impatiently" "impeach" "impedance" "impede" "impediment" "impending" "impenitent" "imperfect" "imperfection" "imperfections" "imperfectly" "imperialist" "imperil" "imperious" "imperiously" "impermissible" "impersonal" "impertinent" "impetuous" "impetuously" "impiety" "impinge" "impious" "implacable" "implausible" "implausibly" "implicate" "implication" "implode" "impolite" "impolitely" "impolitic" "importunate" "importune" "impose" "imposers" "imposing" "imposition" "impossible" "impossiblity" "impossibly" "impotent" "impoverish" "impoverished" "impractical" "imprecate" "imprecise" "imprecisely" "imprecision" "imprison" "imprisonment" "improbability" "improbable" "improbably" "improper" "improperly" "impropriety" "imprudence" "imprudent" "impudence" "impudent" "impudently" "impugn" "impulsive" "impulsively" "impunity" "impure" "impurity" "inability" "inaccuracies" "inaccuracy" "inaccurate" "inaccurately" "inaction" "inactive" "inadequacy" "inadequate" "inadequately" "inadverent" "inadverently" "inadvisable" "inadvisably" "inane" "inanely" "inappropriate" "inappropriately" "inapt" "inaptitude" "inarticulate" "inattentive" "inaudible" "incapable" "incapably" "incautious" "incendiary" "incense" "incessant" "incessantly" "incite" "incitement" "incivility" "inclement" "incognizant" "incoherence" "incoherent" "incoherently" "incommensurate" "incomparable" "incomparably" "incompatability" "incompatibility" "incompatible" "incompetence" "incompetent" "incompetently" "incomplete" "incompliant" "incomprehensible" "incomprehension" "inconceivable" "inconceivably" "incongruous" "incongruously" "inconsequent" "inconsequential" "inconsequentially" "inconsequently" "inconsiderate" "inconsiderately" "inconsistence" "inconsistencies" "inconsistency" "inconsistent" "inconsolable" "inconsolably" "inconstant" "inconvenience" "inconveniently" "incorrect" "incorrectly" "incorrigible" "incorrigibly" "incredulous" "incredulously" "inculcate" "indecency" "indecent" "indecently" "indecision" "indecisive" "indecisively" "indecorum" "indefensible" "indelicate" "indeterminable" "indeterminably" "indeterminate" "indifference" "indifferent" "indigent" "indignant" "indignantly" "indignation" "indignity" "indiscernible" "indiscreet" "indiscreetly" "indiscretion" "indiscriminate" "indiscriminately" "indiscriminating" "indistinguishable" "indoctrinate" "indoctrination" "indolent" "indulge" "ineffective" "ineffectively" "ineffectiveness" "ineffectual" "ineffectually" "ineffectualness" "inefficacious" "inefficacy" "inefficiency" "inefficient" "inefficiently" "inelegance" "inelegant" "ineligible" "ineloquent" "ineloquently" "inept" "ineptitude" "ineptly" "inequalities" "inequality" "inequitable" "inequitably" "inequities" "inescapable" "inescapably" "inessential" "inevitable" "inevitably" "inexcusable" "inexcusably" "inexorable" "inexorably" "inexperience" "inexperienced" "inexpert" "inexpertly" "inexpiable" "inexplainable" "inextricable" "inextricably" "infamous" "infamously" "infamy" "infected" "infection" "infections" "inferior" "inferiority" "infernal" "infest" "infested" "infidel" "infidels" "infiltrator" "infiltrators" "infirm" "inflame" "inflammation" "inflammatory" "inflammed" "inflated" "inflationary" "inflexible" "inflict" "infraction" "infringe" "infringement" "infringements" "infuriate" "infuriated" "infuriating" "infuriatingly" "inglorious" "ingrate" "ingratitude" "inhibit" "inhibition" "inhospitable" "inhospitality" "inhuman" "inhumane" "inhumanity" "inimical" "inimically" "iniquitous" "iniquity" "injudicious" "injure" "injurious" "injury" "injustice" "injustices" "innuendo" "inoperable" "inopportune" "inordinate" "inordinately" "insane" "insanely" "insanity" "insatiable" "insecure" "insecurity" "insensible" "insensitive" "insensitively" "insensitivity" "insidious" "insidiously" "insignificance" "insignificant" "insignificantly" "insincere" "insincerely" "insincerity" "insinuate" "insinuating" "insinuation" "insociable" "insolence" "insolent" "insolently" "insolvent" "insouciance" "instability" "instable" "instigate" "instigator" "instigators" "insubordinate" "insubstantial" "insubstantially" "insufferable" "insufferably" "insufficiency" "insufficient" "insufficiently" "insular" "insult" "insulted" "insulting" "insultingly" "insults" "insupportable" "insupportably" "insurmountable" "insurmountably" "insurrection" "intefere" "inteferes" "intense" "interfere" "interference" "interferes" "intermittent" "interrupt" "interruption" "interruptions" "intimidate" "intimidating" "intimidatingly" "intimidation" "intolerable" "intolerablely" "intolerance" "intoxicate" "intractable" "intransigence" "intransigent" "intrude" "intrusion" "intrusive" "inundate" "inundated" "invader" "invalid" "invalidate" "invalidity" "invasive" "invective" "inveigle" "invidious" "invidiously" "invidiousness" "invisible" "involuntarily" "involuntary" "irascible" "irate" "irately" "ire" "irk" "irked" "irking" "irks" "irksome" "irksomely" "irksomeness" "irksomenesses" "ironic" "ironical" "ironically" "ironies" "irony" "irragularity" "irrational" "irrationalities" "irrationality" "irrationally" "irrationals" "irreconcilable" "irrecoverable" "irrecoverableness" "irrecoverablenesses" "irrecoverably" "irredeemable" "irredeemably" "irreformable" "irregular" "irregularity" "irrelevance" "irrelevant" "irreparable" "irreplacible" "irrepressible" "irresolute" "irresolvable" "irresponsible" "irresponsibly" "irretating" "irretrievable" "irreversible" "irritable" "irritably" "irritant" "irritate" "irritated" "irritating" "irritation" "irritations" "isolate" "isolated" "isolation" "issue" "issues" "itch" "itching" "itchy" "jabber" "jaded" "jagged" "jam" "jarring" "jaundiced" "jealous" "jealously" "jealousness" "jealousy" "jeer" "jeering" "jeeringly" "jeers" "jeopardize" "jeopardy" "jerk" "jerky" "jitter" "jitters" "jittery" "job-killing" "jobless" "joke" "joker" "jolt" "judder" "juddering" "judders" "jumpy" "junk" "junky" "junkyard" "jutter" "jutters" "kaput" "kill" "killed" "killer" "killing" "killjoy" "kills" "knave" "knife" "knock" "knotted" "kook" "kooky" "lack" "lackadaisical" "lacked" "lackey" "lackeys" "lacking" "lackluster" "lacks" "laconic" "lag" "lagged" "lagging" "laggy" "lags" "laid-off" "lambast" "lambaste" "lame" "lame-duck" "lament" "lamentable" "lamentably" "languid" "languish" "languor" "languorous" "languorously" "lanky" "lapse" "lapsed" "lapses" "lascivious" "last-ditch" "latency" "laughable" "laughably" "laughingstock" "lawbreaker" "lawbreaking" "lawless" "lawlessness" "layoff" "layoff-happy" "lazy" "leak" "leakage" "leakages" "leaking" "leaks" "leaky" "lech" "lecher" "lecherous" "lechery" "leech" "leer" "leery" "left-leaning" "lemon" "lengthy" "less-developed" "lesser-known" "letch" "lethal" "lethargic" "lethargy" "lewd" "lewdly" "lewdness" "liability" "liable" "liar" "liars" "licentious" "licentiously" "licentiousness" "lie" "lied" "lier" "lies" "life-threatening" "lifeless" "limit" "limitation" "limitations" "limited" "limits" "limp" "listless" "litigious" "little-known" "livid" "lividly" "loath" "loathe" "loathing" "loathly" "loathsome" "loathsomely" "lone" "loneliness" "lonely" "loner" "lonesome" "long-time" "long-winded" "longing" "longingly" "loophole" "loopholes" "loose" "loot" "lorn" "lose" "loser" "losers" "loses" "losing" "loss" "losses" "lost" "loud" "louder" "lousy" "loveless" "lovelorn" "low-rated" "lowly" "ludicrous" "ludicrously" "lugubrious" "lukewarm" "lull" "lumpy" "lunatic" "lunaticism" "lurch" "lure" "lurid" "lurk" "lurking" "lying" "macabre" "mad" "madden" "maddening" "maddeningly" "madder" "madly" "madman" "madness" "maladjusted" "maladjustment" "malady" "malaise" "malcontent" "malcontented" "maledict" "malevolence" "malevolent" "malevolently" "malice" "malicious" "maliciously" "maliciousness" "malign" "malignant" "malodorous" "maltreatment" "mangle" "mangled" "mangles" "mangling" "mania" "maniac" "maniacal" "manic" "manipulate" "manipulation" "manipulative" "manipulators" "mar" "marginal" "marginally" "martyrdom" "martyrdom-seeking" "mashed" "massacre" "massacres" "PI:NAME:<NAME>END_PIte" "mawkish" "mawkishly" "mawkishness" "meager" "meaningless" "meanness" "measly" "meddle" "meddlesome" "mediocre" "mediocrity" "melancholy" "melodramatic" "melodramatically" "meltdown" "menace" "menacing" "menacingly" "mendacious" "mendacity" "menial" "merciless" "mercilessly" "mess" "messed" "messes" "messing" "messy" "midget" "miff" "militancy" "mindless" "mindlessly" "mirage" "mire" "misalign" "misaligned" "misaligns" "misapprehend" "misbecome" "misbecoming" "misbegotten" "misbehave" "misbehavior" "miscalculate" "miscalculation" "miscellaneous" "mischief" "mischievous" "mischievously" "misconception" "misconceptions" "miscreant" "miscreants" "misdirection" "miser" "miserable" "miserableness" "miserably" "miseries" "miserly" "misery" "misfit" "misfortune" "misgiving" "misgivings" "misguidance" "misguide" "misguided" "mishandle" "mishap" "misinform" "misinformed" "misinterpret" "misjudge" "misjudgment" "mislead" "misleading" "misleadingly" "mislike" "mismanage" "mispronounce" "mispronounced" "mispronounces" "misread" "misreading" "misrepresent" "misrepresentation" "miss" "missed" "misses" "misstatement" "mist" "mistake" "mistaken" "mistakenly" "mistakes" "mistified" "mistress" "mistrust" "mistrustful" "mistrustfully" "mists" "misunderstand" "misunderstanding" "misunderstandings" "misunderstood" "misuse" "moan" "mobster" "mock" "mocked" "mockeries" "mockery" "mocking" "mockingly" "mocks" "molest" "molestation" "monotonous" "monotony" "monster" "monstrosities" "monstrosity" "monstrous" "monstrously" "moody" "moot" "mope" "morbid" "morbidly" "mordant" "mordantly" "moribund" "moron" "moronic" "morons" "mortification" "mortified" "mortify" "mortifying" "motionless" "motley" "mourn" "mourner" "mournful" "mournfully" "muddle" "muddy" "mudslinger" "mudslinging" "mulish" "multi-polarization" "mundane" "murder" "murderer" "murderous" "murderously" "murky" "muscle-flexing" "mushy" "musty" "mysterious" "mysteriously" "mystery" "mystify" "myth" "nag" "nagging" "naive" "naively" "narrower" "nastily" "nastiness" "nasty" "naughty" "nauseate" "nauseates" "nauseating" "nauseatingly" "na�ve" "nebulous" "nebulously" "needless" "needlessly" "needy" "nefarious" "nefariously" "negate" "negation" "negative" "negatives" "negativity" "neglect" "neglected" "negligence" "negligent" "nemesis" "nepotism" "nervous" "nervously" "nervousness" "nettle" "nettlesome" "neurotic" "neurotically" "niggle" "niggles" "nightmare" "nightmarish" "nightmarishly" "nitpick" "nitpicking" "noise" "noises" "noisier" "noisy" "non-confidence" "nonexistent" "nonresponsive" "nonsense" "nosey" "notoriety" "notorious" "notoriously" "noxious" "nuisance" "numb" "obese" "object" "objection" "objectionable" "objections" "oblique" "obliterate" "obliterated" "oblivious" "obnoxious" "obnoxiously" "obscene" "obscenely" "obscenity" "obscure" "obscured" "obscures" "obscurity" "obsess" "obsessive" "obsessively" "obsessiveness" "obsolete" "obstacle" "obstinate" "obstinately" "obstruct" "obstructed" "obstructing" "obstruction" "obstructs" "obtrusive" "obtuse" "occlude" "occluded" "occludes" "occluding" "odd" "odder" "oddest" "oddities" "oddity" "oddly" "odor" "offence" "offend" "offender" "offending" "offenses" "offensive" "offensively" "offensiveness" "officious" "ominous" "ominously" "omission" "omit" "one-sided" "onerous" "onerously" "onslaught" "opinionated" "opponent" "opportunistic" "oppose" "opposition" "oppositions" "oppress" "oppression" "oppressive" "oppressively" "oppressiveness" "oppressors" "ordeal" "orphan" "ostracize" "outbreak" "outburst" "outbursts" "outcast" "outcry" "outlaw" "outmoded" "outrage" "outraged" "outrageous" "outrageously" "outrageousness" "outrages" "outsider" "over-acted" "over-awe" "over-balanced" "over-hyped" "over-priced" "over-valuation" "overact" "overacted" "overawe" "overbalance" "overbalanced" "overbearing" "overbearingly" "overblown" "overdo" "overdone" "overdue" "overemphasize" "overheat" "overkill" "overloaded" "overlook" "overpaid" "overpayed" "overplay" "overpower" "overpriced" "overrated" "overreach" "overrun" "overshadow" "oversight" "oversights" "oversimplification" "oversimplified" "oversimplify" "oversize" "overstate" "overstated" "overstatement" "overstatements" "overstates" "overtaxed" "overthrow" "overthrows" "overturn" "overweight" "overwhelm" "overwhelmed" "overwhelming" "overwhelmingly" "overwhelms" "overzealous" "overzealously" "overzelous" "pain" "painful" "painfull" "painfully" "pains" "pale" "pales" "paltry" "pan" "pandemonium" "pander" "pandering" "panders" "panic" "panick" "panicked" "panicking" "panicky" "paradoxical" "paradoxically" "paralize" "paralyzed" "paranoia" "paranoid" "parasite" "pariah" "parody" "partiality" "partisan" "partisans" "passe" "passive" "passiveness" "pathetic" "pathetically" "patronize" "paucity" "pauper" "paupers" "payback" "peculiar" "peculiarly" "pedantic" "peeled" "peeve" "peeved" "peevish" "peevishly" "penalize" "penalty" "perfidious" "perfidity" "perfunctory" "peril" "perilous" "perilously" "perish" "pernicious" "perplex" "perplexed" "perplexing" "perplexity" "persecute" "persecution" "pertinacious" "pertinaciously" "pertinacity" "perturb" "perturbed" "pervasive" "perverse" "perversely" "perversion" "perversity" "pervert" "perverted" "perverts" "pessimism" "pessimistic" "pessimistically" "pest" "pestilent" "petrified" "petrify" "pettifog" "petty" "phobia" "phobic" "phony" "picket" "picketed" "picketing" "pickets" "picky" "pig" "pigs" "pillage" "pillory" "pimple" "pinch" "pique" "pitiable" "pitiful" "pitifully" "pitiless" "pitilessly" "pittance" "pity" "plagiarize" "plague" "plasticky" "plaything" "plea" "pleas" "plebeian" "plight" "plot" "plotters" "ploy" "plunder" "plunderer" "pointless" "pointlessly" "poison" "poisonous" "poisonously" "pokey" "poky" "polarisation" "polemize" "pollute" "polluter" "polluters" "polution" "pompous" "poor" "poorer" "poorest" "poorly" "posturing" "pout" "poverty" "powerless" "prate" "pratfall" "prattle" "precarious" "precariously" "precipitate" "precipitous" "predatory" "predicament" "prejudge" "prejudice" "prejudices" "prejudicial" "premeditated" "preoccupy" "preposterous" "preposterously" "presumptuous" "presumptuously" "pretence" "pretend" "pretense" "pretentious" "pretentiously" "prevaricate" "pricey" "pricier" "prick" "prickle" "prickles" "prideful" "prik" "primitive" "prison" "prisoner" "problem" "problematic" "problems" "procrastinate" "procrastinates" "procrastination" "profane" "profanity" "prohibit" "prohibitive" "prohibitively" "propaganda" "propagandize" "proprietary" "prosecute" "protest" "protested" "protesting" "protests" "protracted" "provocation" "provocative" "provoke" "pry" "pugnacious" "pugnaciously" "pugnacity" "punch" "punish" "punishable" "punitive" "punk" "puny" "puppet" "puppets" "puzzled" "puzzlement" "puzzling" "quack" "qualm" "qualms" "quandary" "quarrel" "quarrellous" "quarrellously" "quarrels" "quarrelsome" "quash" "queer" "questionable" "quibble" "quibbles" "quitter" "rabid" "racism" "racist" "racists" "racy" "radical" "radicalization" "radically" "radicals" "rage" "ragged" "raging" "rail" "raked" "rampage" "rampant" "ramshackle" "rancor" "randomly" "rankle" "rant" "ranted" "ranting" "rantingly" "rants" "rape" "raped" "raping" "rascal" "rascals" "rash" "rattle" "rattled" "rattles" "ravage" "raving" "reactionary" "rebellious" "rebuff" "rebuke" "recalcitrant" "recant" "recession" "recessionary" "reckless" "recklessly" "recklessness" "recoil" "recourses" "redundancy" "redundant" "refusal" "refuse" "refused" "refuses" "refusing" "refutation" "refute" "refuted" "refutes" "refuting" "regress" "regression" "regressive" "regret" "regreted" "regretful" "regretfully" "regrets" "regrettable" "regrettably" "regretted" "reject" "rejected" "rejecting" "rejection" "rejects" "relapse" "relentless" "relentlessly" "relentlessness" "reluctance" "reluctant" "reluctantly" "remorse" "remorseful" "remorsefully" "remorseless" "remorselessly" "remorselessness" "renounce" "renunciation" "repel" "repetitive" "reprehensible" "reprehensibly" "reprehension" "reprehensive" "repress" "repression" "repressive" "reprimand" "reproach" "reproachful" "reprove" "reprovingly" "repudiate" "repudiation" "repugn" "repugnance" "repugnant" "repugnantly" "repulse" "repulsed" "repulsing" "repulsive" "repulsively" "repulsiveness" "resent" "resentful" "resentment" "resignation" "resigned" "resistance" "restless" "restlessness" "restrict" "restricted" "restriction" "restrictive" "resurgent" "retaliate" "retaliatory" "retard" "retarded" "retardedness" "retards" "reticent" "retract" "retreat" "retreated" "revenge" "revengeful" "revengefully" "revert" "revile" "reviled" "revoke" "revolt" "revolting" "revoltingly" "revulsion" "revulsive" "rhapsodize" "rhetoric" "rhetorical" "ricer" "ridicule" "ridicules" "ridiculous" "ridiculously" "rife" "rift" "rifts" "rigid" "rigidity" "rigidness" "rile" "riled" "rip" "rip-off" "ripoff" "ripped" "risk" "risks" "risky" "rival" "rivalry" "roadblocks" "rocky" "rogue" "rollercoaster" "rot" "rotten" "rough" "rremediable" "rubbish" "rude" "rue" "ruffian" "ruffle" "ruin" "ruined" "ruining" "ruinous" "ruins" "rumbling" "rumor" "rumors" "rumours" "rumple" "run-down" "runaway" "rupture" "rust" "rusts" "rusty" "rut" "ruthless" "ruthlessly" "ruthlessness" "ruts" "sabotage" "sack" "sacrificed" "sad" "sadden" "sadly" "sadness" "sag" "sagged" "sagging" "saggy" "sags" "salacious" "sanctimonious" "sap" "sarcasm" "sarcastic" "sarcastically" "sardonic" "sardonically" "sass" "satirical" "satirize" "savage" "savaged" "savagery" "savages" "scaly" "scam" "scams" "scandal" "scandalize" "scandalized" "scandalous" "scandalously" "scandals" "scandel" "scandels" "scant" "scapegoat" "scar" "scarce" "scarcely" "scarcity" "scare" "scared" "scarier" "scariest" "scarily" "scarred" "scars" "scary" "scathing" "scathingly" "sceptical" "scoff" "scoffingly" "scold" "scolded" "scolding" "scoldingly" "scorching" "scorchingly" "scorn" "scornful" "scornfully" "scoundrel" "scourge" "scowl" "scramble" "scrambled" "scrambles" "scrambling" "scrap" "scratch" "scratched" "scratches" "scratchy" "scream" "screech" "screw-up" "screwed" "screwed-up" "screwy" "scuff" "scuffs" "scum" "scummy" "second-class" "second-tier" "secretive" "sedentary" "seedy" "seethe" "seething" "self-coup" "self-criticism" "self-defeating" "self-destructive" "self-humiliation" "self-interest" "self-interested" "self-serving" "selfinterested" "selfish" "selfishly" "selfishness" "semi-retarded" "senile" "sensationalize" "senseless" "senselessly" "seriousness" "sermonize" "servitude" "set-up" "setback" "setbacks" "sever" "severe" "severity" "sh*t" "shabby" "shadowy" "shady" "shake" "shaky" "shallow" "sham" "shambles" "shame" "shameful" "shamefully" "shamefulness" "shameless" "shamelessly" "shamelessness" "shark" "sharply" "shatter" "shemale" "shimmer" "shimmy" "shipwreck" "shirk" "shirker" "shit" "shiver" "shock" "shocked" "shocking" "shockingly" "shoddy" "short-lived" "shortage" "shortchange" "shortcoming" "shortcomings" "shortness" "shortsighted" "shortsightedness" "showdown" "shrew" "shriek" "shrill" "shrilly" "shrivel" "shroud" "shrouded" "shrug" "shun" "shunned" "sick" "sicken" "sickening" "sickeningly" "sickly" "sickness" "sidetrack" "sidetracked" "siege" "sillily" "silly" "simplistic" "simplistically" "sin" "sinful" "sinfully" "sinister" "sinisterly" "sink" "sinking" "skeletons" "skeptic" "skeptical" "skeptically" "skepticism" "sketchy" "skimpy" "skinny" "skittish" "skittishly" "skulk" "slack" "slander" "slanderer" "slanderous" "slanderously" "slanders" "slap" "slashing" "slaughter" "slaughtered" "slave" "slaves" "sleazy" "slime" "slog" "slogged" "slogging" "slogs" "sloooooooooooooow" "sloooow" "slooow" "sloow" "sloppily" "sloppy" "sloth" "slothful" "slow" "slow-moving" "slowed" "slower" "slowest" "slowly" "sloww" "slowww" "slowwww" "slug" "sluggish" "slump" "slumping" "slumpping" "slur" "slut" "sluts" "sly" "smack" "smallish" "smash" "smear" "smell" "smelled" "smelling" "smells" "smelly" "smelt" "smoke" "smokescreen" "smolder" "smoldering" "smother" "smoulder" "smouldering" "smudge" "smudged" "smudges" "smudging" "smug" "smugly" "smut" "smuttier" "smuttiest" "smutty" "snag" "snagged" "snagging" "snags" "snappish" "snappishly" "snare" "snarky" "snarl" "sneak" "sneakily" "sneaky" "sneer" "sneering" "sneeringly" "snob" "snobbish" "snobby" "snobish" "snobs" "snub" "so-cal" "soapy" "sob" "sober" "sobering" "solemn" "solicitude" "somber" "sore" "sorely" "soreness" "sorrow" "sorrowful" "sorrowfully" "sorry" "sour" "sourly" "spade" "spank" "spendy" "spew" "spewed" "spewing" "spews" "spilling" "spinster" "spiritless" "spite" "spiteful" "spitefully" "spitefulness" "splatter" "split" "splitting" "spoil" "spoilage" "spoilages" "spoiled" "spoilled" "spoils" "spook" "spookier" "spookiest" "spookily" "spooky" "spoon-fed" "spoon-feed" "spoonfed" "sporadic" "spotty" "spurious" "spurn" "sputter" "squabble" "squabbling" "squander" "squash" "squeak" "squeaks" "squeaky" "squeal" "squealing" "squeals" "squirm" "stab" "stagnant" "stagnate" "stagnation" "staid" "stain" "stains" "stale" "stalemate" "stall" "stalls" "stammer" "stampede" "standstill" "stark" "starkly" "startle" "startling" "startlingly" "starvation" "starve" "static" "steal" "stealing" "steals" "steep" "steeply" "stench" "stereotype" "stereotypical" "stereotypically" "stern" "stew" "sticky" "stiff" "stiffness" "stifle" "stifling" "stiflingly" "stigma" "stigmatize" "sting" "stinging" "stingingly" "stingy" "stink" "stinks" "stodgy" "stole" "stolen" "stooge" "stooges" "stormy" "straggle" "straggler" "strain" "strained" "straining" "strange" "strangely" "stranger" "strangest" "strangle" "streaky" "strenuous" "stress" "stresses" "stressful" "stressfully" "stricken" "strict" "strictly" "strident" "stridently" "strife" "strike" "stringent" "stringently" "struck" "struggle" "struggled" "struggles" "struggling" "strut" "stubborn" "stubbornly" "stubbornness" "stuck" "stuffy" "stumble" "stumbled" "stumbles" "stump" "stumped" "stumps" "stun" "stunt" "stunted" "stupid" "stupidest" "stupidity" "stupidly" "stupified" "stupify" "stupor" "stutter" "stuttered" "stuttering" "stutters" "sty" "stymied" "sub-par" "subdued" "subjected" "subjection" "subjugate" "subjugation" "submissive" "subordinate" "subpoena" "subpoenas" "subservience" "subservient" "substandard" "subtract" "subversion" "subversive" "subversively" "subvert" "succumb" "suck" "sucked" "sucker" "sucks" "sucky" "sue" "sued" "sueing" "sues" "suffer" "suffered" "sufferer" "sufferers" "suffering" "suffers" "suffocate" "sugar-coat" "sugar-coated" "sugarcoated" "suicidal" "suicide" "sulk" "sullen" "sully" "sunder" "sunk" "sunken" "superficial" "superficiality" "superficially" "superfluous" "superstition" "superstitious" "suppress" "suppression" "surrender" "susceptible" "suspect" "suspicion" "suspicions" "suspicious" "suspiciously" "swagger" "swamped" "sweaty" "swelled" "swelling" "swindle" "swipe" "swollen" "symptom" "symptoms" "syndrome" "taboo" "tacky" "taint" "tainted" "tamper" "tangle" "tangled" "tangles" "tank" "tanked" "tanks" "tantrum" "tardy" "tarnish" "tarnished" "tarnishes" "tarnishing" "tattered" "taunt" "taunting" "tauntingly" "taunts" "taut" "tawdry" "taxing" "tease" "teasingly" "tedious" "tediously" "temerity" "temper" "tempest" "temptation" "tenderness" "tense" "tension" "tentative" "tentatively" "tenuous" "tenuously" "tepid" "terrible" "terribleness" "terribly" "terror" "terror-genic" "terrorism" "terrorize" "testily" "testy" "tetchily" "tetchy" "thankless" "thicker" "thirst" "thorny" "thoughtless" "thoughtlessly" "thoughtlessness" "thrash" "threat" "threaten" "threatening" "threats" "threesome" "throb" "throbbed" "throbbing" "throbs" "throttle" "thug" "thumb-down" "thumbs-down" "thwart" "time-consuming" "timid" "timidity" "timidly" "timidness" "tin-y" "tingled" "tingling" "tired" "tiresome" "tiring" "tiringly" "toil" "toll" "top-heavy" "topple" "torment" "tormented" "torrent" "tortuous" "torture" "tortured" "tortures" "torturing" "torturous" "torturously" "totalitarian" "touchy" "toughness" "tout" "touted" "touts" "toxic" "traduce" "tragedy" "tragic" "tragically" "traitor" "traitorous" "traitorously" "tramp" "trample" "transgress" "transgression" "trap" "traped" "trapped" "trash" "trashed" "trashy" "trauma" "traumatic" "traumatically" "traumatize" "traumatized" "travesties" "travesty" "treacherous" "treacherously" "treachery" "treason" "treasonous" "trick" "tricked" "trickery" "tricky" "trivial" "trivialize" "trouble" "troubled" "troublemaker" "troubles" "troublesome" "troublesomely" "troubling" "troublingly" "truant" "tumble" "tumbled" "tumbles" "tumultuous" "turbulent" "turmoil" "twist" "twisted" "twists" "two-faced" "two-faces" "tyrannical" "tyrannically" "tyranny" "tyrant" "ugh" "uglier" "ugliest" "ugliness" "ugly" "ulterior" "ultimatum" "ultimatums" "ultra-hardline" "un-viewable" "unable" "unacceptable" "unacceptablely" "unacceptably" "unaccessible" "unaccustomed" "unachievable" "unaffordable" "unappealing" "unattractive" "unauthentic" "unavailable" "unavoidably" "unbearable" "unbearablely" "unbelievable" "unbelievably" "uncaring" "uncertain" "uncivil" "uncivilized" "unclean" "unclear" "uncollectible" "uncomfortable" "uncomfortably" "uncomfy" "uncompetitive" "uncompromising" "uncompromisingly" "unconfirmed" "unconstitutional" "uncontrolled" "unconvincing" "unconvincingly" "uncooperative" "uncouth" "uncreative" "undecided" "undefined" "undependability" "undependable" "undercut" "undercuts" "undercutting" "underdog" "underestimate" "underlings" "undermine" "undermined" "undermines" "undermining" "underpaid" "underpowered" "undersized" "undesirable" "undetermined" "undid" "undignified" "undissolved" "undocumented" "undone" "undue" "unease" "uneasily" "uneasiness" "uneasy" "uneconomical" "unemployed" "unequal" "unethical" "uneven" "uneventful" "unexpected" "unexpectedly" "unexplained" "unfairly" "unfaithful" "unfaithfully" "unfamiliar" "unfavorable" "unfeeling" "unfinished" "unfit" "unforeseen" "unforgiving" "unfortunate" "unfortunately" "unfounded" "unfriendly" "unfulfilled" "unfunded" "ungovernable" "ungrateful" "unhappily" "unhappiness" "unhappy" "unhealthy" "unhelpful" "unilateralism" "unimaginable" "unimaginably" "unimportant" "uninformed" "uninsured" "unintelligible" "unintelligile" "unipolar" "unjust" "unjustifiable" "unjustifiably" "unjustified" "unjustly" "unkind" "unkindly" "unknown" "unlamentable" "unlamentably" "unlawful" "unlawfully" "unlawfulness" "unleash" "unlicensed" "unlikely" "unlucky" "unmoved" "unnatural" "unnaturally" "unnecessary" "unneeded" "unnerve" "unnerved" "unnerving" "unnervingly" "unnoticed" "unobserved" "unorthodox" "unorthodoxy" "unpleasant" "unpleasantries" "unpopular" "unpredictable" "unprepared" "unproductive" "unprofitable" "unprove" "unproved" "unproven" "unproves" "unproving" "unqualified" "unravel" "unraveled" "unreachable" "unreadable" "unrealistic" "unreasonable" "unreasonably" "unrelenting" "unrelentingly" "unreliability" "unreliable" "unresolved" "unresponsive" "unrest" "unruly" "unsafe" "unsatisfactory" "unsavory" "unscrupulous" "unscrupulously" "unsecure" "unseemly" "unsettle" "unsettled" "unsettling" "unsettlingly" "unskilled" "unsophisticated" "unsound" "unspeakable" "unspeakablely" "unspecified" "unstable" "unsteadily" "unsteadiness" "unsteady" "unsuccessful" "unsuccessfully" "unsupported" "unsupportive" "unsure" "unsuspecting" "unsustainable" "untenable" "untested" "unthinkable" "unthinkably" "untimely" "untouched" "untrue" "untrustworthy" "untruthful" "unusable" "unusably" "unuseable" "unuseably" "unusual" "unusually" "unviewable" "unwanted" "unwarranted" "unwatchable" "unwelcome" "unwell" "unwieldy" "unwilling" "unwillingly" "unwillingness" "unwise" "unwisely" "unworkable" "unworthy" "unyielding" "upbraid" "upheaval" "uprising" "uproar" "uproarious" "uproariously" "uproarous" "uproarously" "uproot" "upset" "upseting" "upsets" "upsetting" "upsettingly" "urgent" "useless" "usurp" "usurper" "utterly" "vagrant" "vague" "vagueness" "vain" "vainly" "vanity" "vehement" "vehemently" "vengeance" "vengeful" "vengefully" "vengefulness" "venom" "venomous" "venomously" "vent" "vestiges" "vex" "vexation" "vexing" "vexingly" "vibrate" "vibrated" "vibrates" "vibrating" "vibration" "vice" "vicious" "viciously" "viciousness" "victimize" "vile" "vileness" "vilify" "villainous" "villainously" "villains" "villian" "villianous" "villianously" "villify" "vindictive" "vindictively" "vindictiveness" "violate" "violation" "violator" "violators" "violent" "violently" "viper" "virulence" "virulent" "virulently" "virus" "vociferous" "vociferously" "volatile" "volatility" "vomit" "vomited" "vomiting" "vomits" "vulgar" "vulnerable" "wack" "wail" "wallow" "wane" "waning" "wanton" "war-like" "warily" "wariness" "warlike" "warned" "warning" "warp" "warped" "wary" "washed-out" "waste" "wasted" "wasteful" "wastefulness" "wasting" "water-down" "watered-down" "wayward" "weak" "weaken" "weakening" "weaker" "weakness" "weaknesses" "weariness" "wearisome" "weary" "wedge" "weed" "weep" "weird" "weirdly" "wheedle" "whimper" "whine" "whining" "whiny" "whips" "whore" "whores" "wicked" "wickedly" "wickedness" "wild" "wildly" "wiles" "wilt" "wily" "wimpy" "wince" "wobble" "wobbled" "wobbles" "woe" "woebegone" "woeful" "woefully" "womanizer" "womanizing" "worn" "worried" "worriedly" "worrier" "worries" "worrisome" "worry" "worrying" "worryingly" "worse" "worsen" "worsening" "worst" "worthless" "worthlessly" "worthlessness" "wound" "wounds" "wrangle" "wrath" "wreak" "wreaked" "wreaks" "wreck" "wrest" "wrestle" "wretch" "wretched" "wretchedly" "wretchedness" "wrinkle" "wrinkled" "wrinkles" "wrip" "wripped" "wripping" "writhe" "wrong" "wrongful" "wrongly" "wrought" "yawn" "zap" "zapped" "zaps" "zealot" "zealous" "zealously" "zombie"}) (def pos #{"a+" "abound" "abounds" "abundance" "abundant" "accessable" "accessible" "acclaim" "acclaimed" "acclamation" "accolade" "accolades" "accommodative" "accomodative" "accomplish" "accomplished" "accomplishment" "accomplishments" "accurate" "accurately" "achievable" "achievement" "achievements" "achievible" "acumen" "adaptable" "adaptive" "adequate" "adjustable" "admirable" "admirably" "admiration" "admire" "admirer" "admiring" "admiringly" "adorable" "adore" "adored" "adorer" "adoring" "adoringly" "adroit" "adroitly" "adulate" "adulation" "adulatory" "advanced" "advantage" "advantageous" "advantageously" "advantages" "adventuresome" "adventurous" "advocate" "advocated" "advocates" "affability" "affable" "affably" "affectation" "affection" "affectionate" "affinity" "affirm" "affirmation" "affirmative" "affluence" "affluent" "afford" "affordable" "affordably" "afordable" "agile" "agilely" "agility" "agreeable" "agreeableness" "agreeably" "all-around" "alluring" "alluringly" "altruistic" "altruistically" "amaze" "amazed" "amazement" "amazes" "amazing" "amazingly" "ambitious" "ambitiously" "ameliorate" "amenable" "amenity" "amiability" "amiabily" "amiable" "amicability" "amicable" "amicably" "amity" "ample" "amply" "amuse" "amusing" "amusingly" "angel" "angelic" "apotheosis" "appeal" "appealing" "applaud" "appreciable" "appreciate" "appreciated" "appreciates" "appreciative" "appreciatively" "appropriate" "approval" "approve" "ardent" "ardently" "ardor" "articulate" "aspiration" "aspirations" "aspire" "assurance" "assurances" "assure" "assuredly" "assuring" "astonish" "astonished" "astonishing" "astonishingly" "astonishment" "astound" "astounded" "astounding" "astoundingly" "astutely" "attentive" "attraction" "attractive" "attractively" "attune" "audible" "audibly" "auspicious" "authentic" "authoritative" "autonomous" "available" "aver" "avid" "avidly" "award" "awarded" "awards" "awe" "awed" "awesome" "awesomely" "awesomeness" "awestruck" "awsome" "backbone" "balanced" "bargain" "beauteous" "beautiful" "beautifullly" "beautifully" "beautify" "beauty" "beckon" "beckoned" "beckoning" "beckons" "believable" "believeable" "beloved" "benefactor" "beneficent" "beneficial" "beneficially" "beneficiary" "benefit" "benefits" "benevolence" "benevolent" "benifits" "best" "best-known" "best-performing" "best-selling" "better" "better-known" "better-than-expected" "beutifully" "blameless" "bless" "blessing" "bliss" "blissful" "blissfully" "blithe" "blockbuster" "bloom" "blossom" "bolster" "bonny" "bonus" "bonuses" "boom" "booming" "boost" "boundless" "bountiful" "brainiest" "brainy" "brand-new" "brave" "bravery" "bravo" "breakthrough" "breakthroughs" "breathlessness" "breathtaking" "breathtakingly" "breeze" "bright" "brighten" "brighter" "brightest" "brilliance" "brilliances" "brilliant" "brilliantly" "brisk" "brotherly" "bullish" "buoyant" "cajole" "calm" "calming" "calmness" "capability" "capable" "capably" "captivate" "captivating" "carefree" "cashback" "cashbacks" "catchy" "celebrate" "celebrated" "celebration" "celebratory" "champ" "champion" "charisma" "charismatic" "charitable" "charm" "charming" "charmingly" "chaste" "cheaper" "cheapest" "cheer" "cheerful" "cheery" "cherish" "cherished" "cherub" "chic" "chivalrous" "chivalry" "civility" "civilize" "clarity" "classic" "classy" "clean" "cleaner" "cleanest" "cleanliness" "cleanly" "clear" "clear-cut" "cleared" "clearer" "clearly" "clears" "clever" "cleverly" "cohere" "coherence" "coherent" "cohesive" "colorful" "comely" "comfort" "comfortable" "comfortably" "comforting" "comfy" "commend" "commendable" "commendably" "commitment" "commodious" "compact" "compactly" "compassion" "compassionate" "compatible" "competitive" "complement" "complementary" "complemented" "complements" "compliant" "compliment" "complimentary" "comprehensive" "conciliate" "conciliatory" "concise" "confidence" "confident" "congenial" "congratulate" "congratulation" "congratulations" "congratulatory" "conscientious" "considerate" "consistent" "consistently" "constructive" "consummate" "contentment" "continuity" "contrasty" "contribution" "convenience" "convenient" "conveniently" "convience" "convienient" "convient" "convincing" "convincingly" "cool" "coolest" "cooperative" "cooperatively" "cornerstone" "correct" "correctly" "cost-effective" "cost-saving" "counter-attack" "counter-attacks" "courage" "courageous" "courageously" "courageousness" "courteous" "courtly" "covenant" "cozy" "creative" "credence" "credible" "crisp" "crisper" "cure" "cure-all" "cushy" "cute" "cuteness" "danke" "danken" "daring" "daringly" "darling" "dashing" "dauntless" "dawn" "dazzle" "dazzled" "dazzling" "dead-cheap" "dead-on" "decency" "decent" "decisive" "decisiveness" "dedicated" "defeat" "defeated" "defeating" "defeats" "defender" "deference" "deft" "deginified" "delectable" "delicacy" "delicate" "delicious" "delight" "delighted" "delightful" "delightfully" "delightfulness" "dependable" "dependably" "deservedly" "deserving" "desirable" "desiring" "desirous" "destiny" "detachable" "devout" "dexterous" "dexterously" "dextrous" "dignified" "dignify" "dignity" "diligence" "diligent" "diligently" "diplomatic" "dirt-cheap" "distinction" "distinctive" "distinguished" "diversified" "divine" "divinely" "dominate" "dominated" "dominates" "dote" "dotingly" "doubtless" "dreamland" "dumbfounded" "dumbfounding" "dummy-proof" "durable" "dynamic" "eager" "eagerly" "eagerness" "earnest" "earnestly" "earnestness" "ease" "eased" "eases" "easier" "easiest" "easiness" "easing" "easy" "easy-to-use" "easygoing" "ebullience" "ebullient" "ebulliently" "ecenomical" "economical" "ecstasies" "ecstasy" "ecstatic" "ecstatically" "edify" "educated" "effective" "effectively" "effectiveness" "effectual" "efficacious" "efficient" "efficiently" "effortless" "effortlessly" "effusion" "effusive" "effusively" "effusiveness" "elan" "elate" "elated" "elatedly" "elation" "electrify" "elegance" "elegant" "elegantly" "elevate" "elite" "eloquence" "eloquent" "eloquently" "embolden" "eminence" "eminent" "empathize" "empathy" "empower" "empowerment" "enchant" "enchanted" "enchanting" "enchantingly" "encourage" "encouragement" "encouraging" "encouragingly" "endear" "endearing" "endorse" "endorsed" "endorsement" "endorses" "endorsing" "energetic" "energize" "energy-efficient" "energy-saving" "engaging" "engrossing" "enhance" "enhanced" "enhancement" "enhances" "enjoy" "enjoyable" "enjoyably" "enjoyed" "enjoying" "enjoyment" "enjoys" "enlighten" "enlightenment" "enliven" "ennoble" "enough" "enrapt" "enrapture" "enraptured" "enrich" "enrichment" "enterprising" "entertain" "entertaining" "entertains" "enthral" "enthrall" "enthralled" "enthuse" "enthusiasm" "enthusiast" "enthusiastic" "enthusiastically" "entice" "enticed" "enticing" "enticingly" "entranced" "entrancing" "entrust" "enviable" "enviably" "envious" "enviously" "enviousness" "envy" "equitable" "ergonomical" "err-free" "erudite" "ethical" "eulogize" "euphoria" "euphoric" "euphorically" "evaluative" "evenly" "eventful" "everlasting" "evocative" "exalt" "exaltation" "exalted" "exaltedly" "exalting" "exaltingly" "examplar" "examplary" "excallent" "exceed" "exceeded" "exceeding" "exceedingly" "exceeds" "excel" "exceled" "excelent" "excellant" "excelled" "excellence" "excellency" "excellent" "excellently" "excels" "exceptional" "exceptionally" "excite" "excited" "excitedly" "excitedness" "excitement" "excites" "exciting" "excitingly" "exellent" "exemplar" "exemplary" "exhilarate" "exhilarating" "exhilaratingly" "exhilaration" "exonerate" "expansive" "expeditiously" "expertly" "exquisite" "exquisitely" "extol" "extoll" "extraordinarily" "extraordinary" "exuberance" "exuberant" "exuberantly" "exult" "exultant" "exultation" "exultingly" "eye-catch" "eye-catching" "eyecatch" "eyecatching" "fabulous" "fabulously" "facilitate" "fair" "fairly" "fairness" "faith" "faithful" "faithfully" "faithfulness" "fame" "famed" "famous" "famously" "fancier" "fancinating" "fancy" "fanfare" "fans" "fantastic" "fantastically" "fascinate" "fascinating" "fascinatingly" "fascination" "fashionable" "fashionably" "fast" "fast-growing" "fast-paced" "faster" "fastest" "fastest-growing" "faultless" "fav" "fave" "favor" "favorable" "favored" "favorite" "favorited" "favour" "fearless" "fearlessly" "feasible" "feasibly" "feat" "feature-rich" "fecilitous" "feisty" "felicitate" "felicitous" "felicity" "fertile" "fervent" "fervently" "fervid" "fervidly" "fervor" "festive" "fidelity" "fiery" "fine" "fine-looking" "finely" "finer" "finest" "firmer" "first-class" "first-in-class" "first-rate" "flashy" "flatter" "flattering" "flatteringly" "flawless" "flawlessly" "flexibility" "flexible" "flourish" "flourishing" "fluent" "flutter" "fond" "fondly" "fondness" "foolproof" "foremost" "foresight" "formidable" "fortitude" "fortuitous" "fortuitously" "fortunate" "fortunately" "fortune" "fragrant" "free" "freed" "freedom" "freedoms" "fresh" "fresher" "freshest" "friendliness" "friendly" "frolic" "frugal" "fruitful" "ftw" "fulfillment" "fun" "futurestic" "futuristic" "gaiety" "gaily" "gain" "gained" "gainful" "gainfully" "gaining" "gains" "gallant" "gallantly" "galore" "geekier" "geeky" "gem" "gems" "generosity" "generous" "generously" "genial" "genius" "gentle" "gentlest" "genuine" "gifted" "glad" "gladden" "gladly" "gladness" "glamorous" "glee" "gleeful" "gleefully" "glimmer" "glimmering" "glisten" "glistening" "glitter" "glitz" "glorify" "glorious" "gloriously" "glory" "glow" "glowing" "glowingly" "god-given" "god-send" "godlike" "godsend" "gold" "golden" "good" "goodly" "goodness" "goodwill" "goood" "gooood" "gorgeous" "gorgeously" "grace" "graceful" "gracefully" "gracious" "graciously" "graciousness" "grand" "grandeur" "grateful" "gratefully" "gratification" "gratified" "gratifies" "gratify" "gratifying" "gratifyingly" "gratitude" "great" "greatest" "greatness" "grin" "groundbreaking" "guarantee" "guidance" "guiltless" "gumption" "gush" "gusto" "gutsy" "hail" "halcyon" "hale" "hallmark" "hallmarks" "hallowed" "handier" "handily" "hands-down" "handsome" "handsomely" "handy" "happier" "happily" "happiness" "happy" "hard-working" "hardier" "hardy" "harmless" "harmonious" "harmoniously" "harmonize" "harmony" "headway" "heal" "healthful" "healthy" "hearten" "heartening" "heartfelt" "heartily" "heartwarming" "heaven" "heavenly" "helped" "helpful" "helping" "hero" "heroic" "heroically" "heroine" "heroize" "heros" "high-quality" "high-spirited" "hilarious" "holy" "homage" "honest" "honesty" "honor" "honorable" "honored" "honoring" "hooray" "hopeful" "hospitable" "hot" "hotcake" "hotcakes" "hottest" "hug" "humane" "humble" "humility" "humor" "humorous" "humorously" "humour" "humourous" "ideal" "idealize" "ideally" "idol" "idolize" "idolized" "idyllic" "illuminate" "illuminati" "illuminating" "illumine" "illustrious" "ilu" "imaculate" "imaginative" "immaculate" "immaculately" "immense" "impartial" "impartiality" "impartially" "impassioned" "impeccable" "impeccably" "important" "impress" "impressed" "impresses" "impressive" "impressively" "impressiveness" "improve" "improved" "improvement" "improvements" "improves" "improving" "incredible" "incredibly" "indebted" "individualized" "indulgence" "indulgent" "industrious" "inestimable" "inestimably" "inexpensive" "infallibility" "infallible" "infallibly" "influential" "ingenious" "ingeniously" "ingenuity" "ingenuous" "ingenuously" "innocuous" "innovation" "innovative" "inpressed" "insightful" "insightfully" "inspiration" "inspirational" "inspire" "inspiring" "instantly" "instructive" "instrumental" "integral" "integrated" "intelligence" "intelligent" "intelligible" "interesting" "interests" "intimacy" "intimate" "intricate" "intrigue" "intriguing" "intriguingly" "intuitive" "invaluable" "invaluablely" "inventive" "invigorate" "invigorating" "invincibility" "invincible" "inviolable" "inviolate" "invulnerable" "irreplaceable" "irreproachable" "irresistible" "irresistibly" "issue-free" "jaw-droping" "jaw-dropping" "jollify" "jolly" "jovial" "joy" "joyful" "joyfully" "joyous" "joyously" "jubilant" "jubilantly" "jubilate" "jubilation" "jubiliant" "judicious" "justly" "keen" "keenly" "keenness" "kid-friendly" "kindliness" "kindly" "kindness" "knowledgeable" "kudos" "large-capacity" "laud" "laudable" "laudably" "lavish" "lavishly" "law-abiding" "lawful" "lawfully" "lead" "leading" "leads" "lean" "led" "legendary" "leverage" "levity" "liberate" "liberation" "liberty" "lifesaver" "light-hearted" "lighter" "likable" "like" "liked" "likes" "liking" "lionhearted" "lively" "logical" "long-lasting" "lovable" "lovably" "love" "loved" "loveliness" "lovely" "lover" "loves" "loving" "low-cost" "low-price" "low-priced" "low-risk" "lower-priced" "loyal" "loyalty" "lucid" "lucidly" "luck" "luckier" "luckiest" "luckiness" "lucky" "lucrative" "luminous" "lush" "luster" "lustrous" "luxuriant" "luxuriate" "luxurious" "luxuriously" "luxury" "lyrical" "magic" "magical" "magnanimous" "magnanimously" "magnificence" "magnificent" "magnificently" "majestic" "majesty" "manageable" "maneuverable" "marvel" "marveled" "marvelled" "marvellous" "marvelous" "marvelously" "marvelousness" "marvels" "master" "masterful" "masterfully" "masterpiece" "masterpieces" "masters" "mastery" "matchless" "mature" "maturely" "maturity" "meaningful" "memorable" "merciful" "mercifully" "mercy" "merit" "meritorious" "merrily" "merriment" "merriness" "merry" "mesmerize" "mesmerized" "mesmerizes" "mesmerizing" "mesmerizingly" "meticulous" "meticulously" "mightily" "mighty" "mind-blowing" "miracle" "miracles" "miraculous" "miraculously" "miraculousness" "modern" "modest" "modesty" "momentous" "monumental" "monumentally" "morality" "motivated" "multi-purpose" "navigable" "neat" "neatest" "neatly" "nice" "nicely" "nicer" "nicest" "nifty" "nimble" "noble" "nobly" "noiseless" "non-violence" "non-violent" "notably" "noteworthy" "nourish" "nourishing" "nourishment" "novelty" "nurturing" "oasis" "obsession" "obsessions" "obtainable" "openly" "openness" "optimal" "optimism" "optimistic" "opulent" "orderly" "originality" "outdo" "outdone" "outperform" "outperformed" "outperforming" "outperforms" "outshine" "outshone" "outsmart" "outstanding" "outstandingly" "outstrip" "outwit" "ovation" "overjoyed" "overtake" "overtaken" "overtakes" "overtaking" "overtook" "overture" "pain-free" "painless" "painlessly" "palatial" "pamper" "pampered" "pamperedly" "pamperedness" "pampers" "panoramic" "paradise" "paramount" "pardon" "passion" "passionate" "passionately" "patience" "patient" "patiently" "patriot" "patriotic" "peace" "peaceable" "peaceful" "peacefully" "peacekeepers" "peach" "peerless" "pep" "pepped" "pepping" "peppy" "peps" "perfect" "perfection" "perfectly" "permissible" "perseverance" "persevere" "personages" "personalized" "phenomenal" "phenomenally" "picturesque" "piety" "pinnacle" "playful" "playfully" "pleasant" "pleasantly" "pleased" "pleases" "pleasing" "pleasingly" "pleasurable" "pleasurably" "pleasure" "plentiful" "pluses" "plush" "plusses" "poetic" "poeticize" "poignant" "poise" "poised" "polished" "polite" "politeness" "popular" "portable" "posh" "positive" "positively" "positives" "powerful" "powerfully" "praise" "praiseworthy" "praising" "pre-eminent" "precious" "precise" "precisely" "preeminent" "prefer" "preferable" "preferably" "prefered" "preferes" "preferring" "prefers" "premier" "prestige" "prestigious" "prettily" "pretty" "priceless" "pride" "principled" "privilege" "privileged" "prize" "proactive" "problem-free" "problem-solver" "prodigious" "prodigiously" "prodigy" "productive" "productively" "proficient" "proficiently" "profound" "profoundly" "profuse" "profusion" "progress" "progressive" "prolific" "prominence" "prominent" "promise" "promised" "promises" "promising" "promoter" "prompt" "promptly" "proper" "properly" "propitious" "propitiously" "pros" "prosper" "prosperity" "prosperous" "prospros" "protect" "protection" "protective" "proud" "proven" "proves" "providence" "proving" "prowess" "prudence" "prudent" "prudently" "punctual" "pure" "purify" "purposeful" "quaint" "qualified" "qualify" "quicker" "quiet" "quieter" "radiance" "radiant" "rapid" "rapport" "rapt" "rapture" "raptureous" "raptureously" "rapturous" "rapturously" "rational" "razor-sharp" "reachable" "readable" "readily" "ready" "reaffirm" "reaffirmation" "realistic" "realizable" "reasonable" "reasonably" "reasoned" "reassurance" "reassure" "receptive" "reclaim" "recomend" "recommend" "recommendation" "recommendations" "recommended" "reconcile" "reconciliation" "record-setting" "recover" "recovery" "rectification" "rectify" "rectifying" "redeem" "redeeming" "redemption" "refine" "refined" "refinement" "reform" "reformed" "reforming" "reforms" "refresh" "refreshed" "refreshing" "refund" "refunded" "regal" "regally" "regard" "rejoice" "rejoicing" "rejoicingly" "rejuvenate" "rejuvenated" "rejuvenating" "relaxed" "relent" "reliable" "reliably" "relief" "relish" "remarkable" "remarkably" "remedy" "remission" "remunerate" "renaissance" "renewed" "renown" "renowned" "replaceable" "reputable" "reputation" "resilient" "resolute" "resound" "resounding" "resourceful" "resourcefulness" "respect" "respectable" "respectful" "respectfully" "respite" "resplendent" "responsibly" "responsive" "restful" "restored" "restructure" "restructured" "restructuring" "retractable" "revel" "revelation" "revere" "reverence" "reverent" "reverently" "revitalize" "revival" "revive" "revives" "revolutionary" "revolutionize" "revolutionized" "revolutionizes" "reward" "rewarding" "rewardingly" "rich" "richer" "richly" "richness" "right" "righten" "righteous" "righteously" "righteousness" "rightful" "rightfully" "rightly" "rightness" "risk-free" "robust" "rock-star" "rock-stars" "rockstar" "rockstars" "romantic" "romantically" "romanticize" "roomier" "roomy" "rosy" "safe" "safely" "sagacity" "sagely" "saint" "saintliness" "saintly" "salutary" "salute" "sane" "satisfactorily" "satisfactory" "satisfied" "satisfies" "satisfy" "satisfying" "satisified" "saver" "savings" "savior" "savvy" "scenic" "seamless" "seasoned" "secure" "securely" "selective" "self-determination" "self-respect" "self-satisfaction" "self-sufficiency" "self-sufficient" "sensation" "sensational" "sensationally" "sensations" "sensible" "sensibly" "sensitive" "serene" "serenity" "sexy" "sharp" "sharper" "sharpest" "shimmering" "shimmeringly" "shine" "shiny" "significant" "silent" "simpler" "simplest" "simplified" "simplifies" "simplify" "simplifying" "sincere" "sincerely" "sincerity" "skill" "skilled" "skillful" "skillfully" "slammin" "sleek" "slick" "smart" "smarter" "smartest" "smartly" "smile" "smiles" "smiling" "smilingly" "smitten" "smooth" "smoother" "smoothes" "smoothest" "smoothly" "snappy" "snazzy" "sociable" "soft" "softer" "solace" "solicitous" "solicitously" "solid" "solidarity" "soothe" "soothingly" "sophisticated" "soulful" "soundly" "soundness" "spacious" "sparkle" "sparkling" "spectacular" "spectacularly" "speedily" "speedy" "spellbind" "spellbinding" "spellbindingly" "spellbound" "spirited" "spiritual" "splendid" "splendidly" "splendor" "spontaneous" "sporty" "spotless" "sprightly" "stability" "stabilize" "stable" "stainless" "standout" "state-of-the-art" "stately" "statuesque" "staunch" "staunchly" "staunchness" "steadfast" "steadfastly" "steadfastness" "steadiest" "steadiness" "steady" "stellar" "stellarly" "stimulate" "stimulates" "stimulating" "stimulative" "stirringly" "straighten" "straightforward" "streamlined" "striking" "strikingly" "striving" "strong" "stronger" "strongest" "stunned" "stunning" "stunningly" "stupendous" "stupendously" "sturdier" "sturdy" "stylish" "stylishly" "stylized" "suave" "suavely" "sublime" "subsidize" "subsidized" "subsidizes" "subsidizing" "substantive" "succeed" "succeeded" "succeeding" "succeeds" "succes" "success" "successes" "successful" "successfully" "suffice" "sufficed" "suffices" "sufficient" "sufficiently" "suitable" "sumptuous" "sumptuously" "sumptuousness" "super" "superb" "superbly" "superior" "superiority" "supple" "support" "supported" "supporter" "supporting" "supportive" "supports" "supremacy" "supreme" "supremely" "supurb" "supurbly" "surmount" "surpass" "surreal" "survival" "survivor" "sustainability" "sustainable" "swank" "swankier" "swankiest" "swanky" "sweeping" "sweet" "sweeten" "sweetheart" "sweetly" "sweetness" "swift" "swiftness" "talent" "talented" "talents" "tantalize" "tantalizing" "tantalizingly" "tempt" "tempting" "temptingly" "tenacious" "tenaciously" "tenacity" "tender" "tenderly" "terrific" "terrifically" "thank" "thankful" "thinner" "thoughtful" "thoughtfully" "thoughtfulness" "thrift" "thrifty" "thrill" "thrilled" "thrilling" "thrillingly" "thrills" "thrive" "thriving" "thumb-up" "thumbs-up" "tickle" "tidy" "time-honored" "timely" "tingle" "titillate" "titillating" "titillatingly" "togetherness" "tolerable" "toll-free" "top" "top-notch" "top-quality" "topnotch" "tops" "tough" "tougher" "toughest" "traction" "tranquil" "tranquility" "transparent" "treasure" "tremendously" "trendy" "triumph" "triumphal" "triumphant" "triumphantly" "trivially" "trophy" "trouble-free" "trump" "trumpet" "trust" "trusted" "trusting" "trustingly" "trustworthiness" "trustworthy" "trusty" "truthful" "truthfully" "truthfulness" "twinkly" "ultra-crisp" "unabashed" "unabashedly" "unaffected" "unassailable" "unbeatable" "unbiased" "unbound" "uncomplicated" "unconditional" "undamaged" "undaunted" "understandable" "undisputable" "undisputably" "undisputed" "unencumbered" "unequivocal" "unequivocally" "unfazed" "unfettered" "unforgettable" "unity" "unlimited" "unmatched" "unparalleled" "unquestionable" "unquestionably" "unreal" "unrestricted" "unrivaled" "unselfish" "unwavering" "upbeat" "upgradable" "upgradeable" "upgraded" "upheld" "uphold" "uplift" "uplifting" "upliftingly" "upliftment" "upscale" "usable" "useable" "useful" "user-friendly" "user-replaceable" "valiant" "valiantly" "valor" "valuable" "variety" "venerate" "verifiable" "veritable" "versatile" "versatility" "vibrant" "vibrantly" "victorious" "victory" "viewable" "vigilance" "vigilant" "virtue" "virtuous" "virtuously" "visionary" "vivacious" "vivid" "vouch" "vouchsafe" "warm" "warmer" "warmhearted" "warmly" "warmth" "wealthy" "welcome" "well" "well-backlit" "well-balanced" "well-behaved" "well-being" "well-bred" "well-connected" "well-educated" "well-established" "well-informed" "well-intentioned" "well-known" "well-made" "well-managed" "well-mannered" "well-positioned" "well-received" "well-regarded" "well-rounded" "well-run" "well-wishers" "wellbeing" "whoa" "wholeheartedly" "wholesome" "whooa" "whoooa" "wieldy" "willing" "willingly" "willingness" "win" "windfall" "winnable" "winner" "winners" "winning" "wins" "wisdom" "wise" "wisely" "witty" "won" "wonder" "wonderful" "wonderfully" "wonderous" "wonderously" "wonders" "wondrous" "woo" "work" "workable" "worked" "works" "world-famous" "worth" "worth-while" "worthiness" "worthwhile" "worthy" "wow" "wowed" "wowing" "wows" "yay" "youthful" "zeal" "zenith" "zest" "zippy"})
[ { "context": "ole group subgroup idx opts)\n :password \"password\"}))\n\n(defn init!\n \"Create a structure of keycloa", "end": 1441, "score": 0.9992846846580505, "start": 1433, "tag": "PASSWORD", "value": "password" }, { "context": "\" Add user \\\"%s\\\" to group \\\"%s\\\"\" (:username user) subgroup-name))\n (add-user-to-g", "end": 3862, "score": 0.9966142773628235, "start": 3858, "tag": "USERNAME", "value": "user" }, { "context": ")))))))))\n\n ;;Static users\n (doseq [{:keys [username] :as user} (:users data)]\n (let [created-use", "end": 4038, "score": 0.7703920006752014, "start": 4030, "tag": "USERNAME", "value": "username" } ]
src/keycloak/starter.clj
emilaasa/keycloak-clojure
0
(ns keycloak.starter (:require [keycloak.admin :refer :all] [keycloak.user :as user] [keycloak.deployment :as deployment :refer [keycloak-client client-conf]] [talltale.core :as talltale :refer :all] [me.raynes.fs :as fs])) (defn export-secret! [keycloak-client realm-name client-id key] (let [secret (get-client-secret keycloak-client realm-name client-id) home (System/getenv "HOME") secrets-file (clojure.java.io/file home ".secrets.edn") _ (fs/touch secrets-file) secrets (or (clojure.edn/read-string (slurp secrets-file)) {})] (println (format "Secret of client \"%s\" exported in file %s at key [:keycloak %s]" client-id (str secrets-file) key)) (spit secrets-file (assoc-in secrets [:keycloak key] secret)))) (defn create-mappers! [keycloak-client realm-name client-id] (println "Create protocol mappers for client" client-id) (create-protocol-mapper! keycloak-client realm-name client-id (group-membership-mapper "group-mapper" "group")) (create-protocol-mapper! keycloak-client realm-name client-id (user-attribute-mapper "org-ref-mapper" "org-ref" "org-ref" "String"))) (defn generate-user [username-creator-fn role group subgroup idx & opts] (merge (talltale/person) {:username (apply username-creator-fn role group subgroup idx opts) :password "password"})) (defn init! "Create a structure of keycloak objects (realm, clients, roles) and fill it with groups and users" [admin-client data] (let [realm-name (get-in data [:realm :name]) {:keys [themes login tokens smtp]} (:realm data)] (try (create-realm! admin-client realm-name themes login tokens smtp) (println (format "Realm \"%s\" created" realm-name)) (catch javax.ws.rs.ClientErrorException cee (when (= (-> cee (.getResponse) (.getStatus)) 409) (update-realm! admin-client realm-name themes login tokens smtp) (println (format "Realm \"%s\" updated" realm-name)))) (catch Exception e (println "Can't create Realm" e)(get-realm admin-client realm-name))) (doseq [{:keys [name public? redirect-uris web-origins] :as client-data} (:clients data)] (let [client (client client-data)] (create-client! admin-client realm-name client) (println (format "Client \"%s\" created in realm %s" name realm-name))) (create-mappers! admin-client realm-name name) (export-secret! admin-client realm-name name (keyword (str "secret-" name)))) (println (format "%s Clients created in realm %s" (count (:clients data)) realm-name)) (doseq [role (:roles data)] (try (create-role! admin-client realm-name role) (catch Exception e (get-role admin-client realm-name role)))) (doseq [{:keys [name subgroups]} (:groups data)] (let [group (create-group! admin-client realm-name name)] (println (format "Group \"%s\" created" name)) (doseq [[idx {subgroup-name :name attributes :attributes}] (map-indexed vector subgroups)] (let [subgroup (create-subgroup! admin-client realm-name (.getId group) subgroup-name attributes)] (println (format " Subgroup \"%s\" created in group \"%s\"" subgroup-name name)) ;;Generated users (doseq [role (:roles data)] (doseq [i (range 1 (inc (:generated-users-by-group-and-role data)))] (let [user (generate-user (:username-creator-fn data) role name subgroup i) created-user (user/create-or-update-user! admin-client realm-name user (:realm-roles data) (:client-roles data))] (println (format " User \"%s\" created" (:username user))) (println (format " Add user \"%s\" to group \"%s\"" (:username user) subgroup-name)) (add-user-to-group! admin-client realm-name (.getId subgroup) (.getId created-user))))))))) ;;Static users (doseq [{:keys [username] :as user} (:users data)] (let [created-user (user/create-or-update-user! admin-client realm-name user (:realm-roles user) (:client-roles user))] (println (format "User \"%s\" created" username)) (doseq [subgroup-name (:in-subgroups user)] (let [subgroup-id (get-subgroup-id admin-client realm-name (get-group-id admin-client realm-name (:group user)) subgroup-name)] (println (format "Add user \"%s\" to group \"%s\"" username subgroup-name)) (add-user-to-group! admin-client realm-name subgroup-id (.getId created-user)))))) (println (format "Keycloak with realm \"%s\" initialized" realm-name)) data))
57485
(ns keycloak.starter (:require [keycloak.admin :refer :all] [keycloak.user :as user] [keycloak.deployment :as deployment :refer [keycloak-client client-conf]] [talltale.core :as talltale :refer :all] [me.raynes.fs :as fs])) (defn export-secret! [keycloak-client realm-name client-id key] (let [secret (get-client-secret keycloak-client realm-name client-id) home (System/getenv "HOME") secrets-file (clojure.java.io/file home ".secrets.edn") _ (fs/touch secrets-file) secrets (or (clojure.edn/read-string (slurp secrets-file)) {})] (println (format "Secret of client \"%s\" exported in file %s at key [:keycloak %s]" client-id (str secrets-file) key)) (spit secrets-file (assoc-in secrets [:keycloak key] secret)))) (defn create-mappers! [keycloak-client realm-name client-id] (println "Create protocol mappers for client" client-id) (create-protocol-mapper! keycloak-client realm-name client-id (group-membership-mapper "group-mapper" "group")) (create-protocol-mapper! keycloak-client realm-name client-id (user-attribute-mapper "org-ref-mapper" "org-ref" "org-ref" "String"))) (defn generate-user [username-creator-fn role group subgroup idx & opts] (merge (talltale/person) {:username (apply username-creator-fn role group subgroup idx opts) :password "<PASSWORD>"})) (defn init! "Create a structure of keycloak objects (realm, clients, roles) and fill it with groups and users" [admin-client data] (let [realm-name (get-in data [:realm :name]) {:keys [themes login tokens smtp]} (:realm data)] (try (create-realm! admin-client realm-name themes login tokens smtp) (println (format "Realm \"%s\" created" realm-name)) (catch javax.ws.rs.ClientErrorException cee (when (= (-> cee (.getResponse) (.getStatus)) 409) (update-realm! admin-client realm-name themes login tokens smtp) (println (format "Realm \"%s\" updated" realm-name)))) (catch Exception e (println "Can't create Realm" e)(get-realm admin-client realm-name))) (doseq [{:keys [name public? redirect-uris web-origins] :as client-data} (:clients data)] (let [client (client client-data)] (create-client! admin-client realm-name client) (println (format "Client \"%s\" created in realm %s" name realm-name))) (create-mappers! admin-client realm-name name) (export-secret! admin-client realm-name name (keyword (str "secret-" name)))) (println (format "%s Clients created in realm %s" (count (:clients data)) realm-name)) (doseq [role (:roles data)] (try (create-role! admin-client realm-name role) (catch Exception e (get-role admin-client realm-name role)))) (doseq [{:keys [name subgroups]} (:groups data)] (let [group (create-group! admin-client realm-name name)] (println (format "Group \"%s\" created" name)) (doseq [[idx {subgroup-name :name attributes :attributes}] (map-indexed vector subgroups)] (let [subgroup (create-subgroup! admin-client realm-name (.getId group) subgroup-name attributes)] (println (format " Subgroup \"%s\" created in group \"%s\"" subgroup-name name)) ;;Generated users (doseq [role (:roles data)] (doseq [i (range 1 (inc (:generated-users-by-group-and-role data)))] (let [user (generate-user (:username-creator-fn data) role name subgroup i) created-user (user/create-or-update-user! admin-client realm-name user (:realm-roles data) (:client-roles data))] (println (format " User \"%s\" created" (:username user))) (println (format " Add user \"%s\" to group \"%s\"" (:username user) subgroup-name)) (add-user-to-group! admin-client realm-name (.getId subgroup) (.getId created-user))))))))) ;;Static users (doseq [{:keys [username] :as user} (:users data)] (let [created-user (user/create-or-update-user! admin-client realm-name user (:realm-roles user) (:client-roles user))] (println (format "User \"%s\" created" username)) (doseq [subgroup-name (:in-subgroups user)] (let [subgroup-id (get-subgroup-id admin-client realm-name (get-group-id admin-client realm-name (:group user)) subgroup-name)] (println (format "Add user \"%s\" to group \"%s\"" username subgroup-name)) (add-user-to-group! admin-client realm-name subgroup-id (.getId created-user)))))) (println (format "Keycloak with realm \"%s\" initialized" realm-name)) data))
true
(ns keycloak.starter (:require [keycloak.admin :refer :all] [keycloak.user :as user] [keycloak.deployment :as deployment :refer [keycloak-client client-conf]] [talltale.core :as talltale :refer :all] [me.raynes.fs :as fs])) (defn export-secret! [keycloak-client realm-name client-id key] (let [secret (get-client-secret keycloak-client realm-name client-id) home (System/getenv "HOME") secrets-file (clojure.java.io/file home ".secrets.edn") _ (fs/touch secrets-file) secrets (or (clojure.edn/read-string (slurp secrets-file)) {})] (println (format "Secret of client \"%s\" exported in file %s at key [:keycloak %s]" client-id (str secrets-file) key)) (spit secrets-file (assoc-in secrets [:keycloak key] secret)))) (defn create-mappers! [keycloak-client realm-name client-id] (println "Create protocol mappers for client" client-id) (create-protocol-mapper! keycloak-client realm-name client-id (group-membership-mapper "group-mapper" "group")) (create-protocol-mapper! keycloak-client realm-name client-id (user-attribute-mapper "org-ref-mapper" "org-ref" "org-ref" "String"))) (defn generate-user [username-creator-fn role group subgroup idx & opts] (merge (talltale/person) {:username (apply username-creator-fn role group subgroup idx opts) :password "PI:PASSWORD:<PASSWORD>END_PI"})) (defn init! "Create a structure of keycloak objects (realm, clients, roles) and fill it with groups and users" [admin-client data] (let [realm-name (get-in data [:realm :name]) {:keys [themes login tokens smtp]} (:realm data)] (try (create-realm! admin-client realm-name themes login tokens smtp) (println (format "Realm \"%s\" created" realm-name)) (catch javax.ws.rs.ClientErrorException cee (when (= (-> cee (.getResponse) (.getStatus)) 409) (update-realm! admin-client realm-name themes login tokens smtp) (println (format "Realm \"%s\" updated" realm-name)))) (catch Exception e (println "Can't create Realm" e)(get-realm admin-client realm-name))) (doseq [{:keys [name public? redirect-uris web-origins] :as client-data} (:clients data)] (let [client (client client-data)] (create-client! admin-client realm-name client) (println (format "Client \"%s\" created in realm %s" name realm-name))) (create-mappers! admin-client realm-name name) (export-secret! admin-client realm-name name (keyword (str "secret-" name)))) (println (format "%s Clients created in realm %s" (count (:clients data)) realm-name)) (doseq [role (:roles data)] (try (create-role! admin-client realm-name role) (catch Exception e (get-role admin-client realm-name role)))) (doseq [{:keys [name subgroups]} (:groups data)] (let [group (create-group! admin-client realm-name name)] (println (format "Group \"%s\" created" name)) (doseq [[idx {subgroup-name :name attributes :attributes}] (map-indexed vector subgroups)] (let [subgroup (create-subgroup! admin-client realm-name (.getId group) subgroup-name attributes)] (println (format " Subgroup \"%s\" created in group \"%s\"" subgroup-name name)) ;;Generated users (doseq [role (:roles data)] (doseq [i (range 1 (inc (:generated-users-by-group-and-role data)))] (let [user (generate-user (:username-creator-fn data) role name subgroup i) created-user (user/create-or-update-user! admin-client realm-name user (:realm-roles data) (:client-roles data))] (println (format " User \"%s\" created" (:username user))) (println (format " Add user \"%s\" to group \"%s\"" (:username user) subgroup-name)) (add-user-to-group! admin-client realm-name (.getId subgroup) (.getId created-user))))))))) ;;Static users (doseq [{:keys [username] :as user} (:users data)] (let [created-user (user/create-or-update-user! admin-client realm-name user (:realm-roles user) (:client-roles user))] (println (format "User \"%s\" created" username)) (doseq [subgroup-name (:in-subgroups user)] (let [subgroup-id (get-subgroup-id admin-client realm-name (get-group-id admin-client realm-name (:group user)) subgroup-name)] (println (format "Add user \"%s\" to group \"%s\"" username subgroup-name)) (add-user-to-group! admin-client realm-name subgroup-id (.getId created-user)))))) (println (format "Keycloak with realm \"%s\" initialized" realm-name)) data))
[ { "context": ";;\n;; Copyright © 2020 Sam Ritchie.\n;; This work is based on the Scmutils system of ", "end": 34, "score": 0.9997925162315369, "start": 23, "tag": "NAME", "value": "Sam Ritchie" } ]
test/numerical/quadrature/infinite_test.cljc
dynamic-notebook/functional-numerics
4
;; ;; Copyright © 2020 Sam Ritchie. ;; This work is based on the Scmutils system of MIT/GNU Scheme: ;; Copyright © 2002 Massachusetts Institute of Technology ;; ;; This is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3 of the License, or (at ;; your option) any later version. ;; ;; This software is distributed in the hope that it will be useful, but ;; WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;; General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with this code; if not, see <http://www.gnu.org/licenses/>. ;; (ns sicmutils.numerical.quadrature.infinite-test (:require [clojure.test :refer [is deftest testing]] [same :refer [ish? zeroish? with-comparator] #?@(:cljs [:include-macros true])] [sicmutils.numerical.quadrature.adaptive :as qa] [sicmutils.numerical.quadrature.bulirsch-stoer :as bs] [sicmutils.numerical.quadrature.infinite :as qi] [sicmutils.value :as v])) (def ^:private integrator (qa/adaptive bs/open-integral bs/closed-integral)) (deftest improper-tests (binding [qa/*neighborhood-width* 0] (testing "Euler's constant" ;; https://en.wikipedia.org/wiki/Euler%E2%80%93Mascheroni_constant (let [f (fn [x] (* (Math/log x) (Math/exp (- x))))] (is (ish? {:converged? true :result -0.5772156418405041} ((qi/improper integrator) f 0 ##Inf)) "The improper integral converges.") (is (ish? {:converged? true :result -2.7965685938222346E-9} ((qi/improper integrator) f 0 ##Inf {:infinite-breakpoint 100})) "A breakpoint that's too big ruins the calculation by pushing the variable-change region to the right.") (is (= (integrator f 0 10) ((qi/improper integrator) f 0 10)) "With non-infinite bounds, integration passes through."))) (testing "full integration" (let [f (fn [x] (* x (Math/exp (- (* x x))))) integrate (qi/improper integrator)] (is (zeroish? (+ (:result (integrate f ##-Inf 0)) (:result (integrate f 0 ##Inf))))) (is (ish? {:converged? true :result 0} (integrate f ##-Inf ##Inf)) "We can handle the full range all at once.")))))
14235
;; ;; Copyright © 2020 <NAME>. ;; This work is based on the Scmutils system of MIT/GNU Scheme: ;; Copyright © 2002 Massachusetts Institute of Technology ;; ;; This is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3 of the License, or (at ;; your option) any later version. ;; ;; This software is distributed in the hope that it will be useful, but ;; WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;; General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with this code; if not, see <http://www.gnu.org/licenses/>. ;; (ns sicmutils.numerical.quadrature.infinite-test (:require [clojure.test :refer [is deftest testing]] [same :refer [ish? zeroish? with-comparator] #?@(:cljs [:include-macros true])] [sicmutils.numerical.quadrature.adaptive :as qa] [sicmutils.numerical.quadrature.bulirsch-stoer :as bs] [sicmutils.numerical.quadrature.infinite :as qi] [sicmutils.value :as v])) (def ^:private integrator (qa/adaptive bs/open-integral bs/closed-integral)) (deftest improper-tests (binding [qa/*neighborhood-width* 0] (testing "Euler's constant" ;; https://en.wikipedia.org/wiki/Euler%E2%80%93Mascheroni_constant (let [f (fn [x] (* (Math/log x) (Math/exp (- x))))] (is (ish? {:converged? true :result -0.5772156418405041} ((qi/improper integrator) f 0 ##Inf)) "The improper integral converges.") (is (ish? {:converged? true :result -2.7965685938222346E-9} ((qi/improper integrator) f 0 ##Inf {:infinite-breakpoint 100})) "A breakpoint that's too big ruins the calculation by pushing the variable-change region to the right.") (is (= (integrator f 0 10) ((qi/improper integrator) f 0 10)) "With non-infinite bounds, integration passes through."))) (testing "full integration" (let [f (fn [x] (* x (Math/exp (- (* x x))))) integrate (qi/improper integrator)] (is (zeroish? (+ (:result (integrate f ##-Inf 0)) (:result (integrate f 0 ##Inf))))) (is (ish? {:converged? true :result 0} (integrate f ##-Inf ##Inf)) "We can handle the full range all at once.")))))
true
;; ;; Copyright © 2020 PI:NAME:<NAME>END_PI. ;; This work is based on the Scmutils system of MIT/GNU Scheme: ;; Copyright © 2002 Massachusetts Institute of Technology ;; ;; This is free software; you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation; either version 3 of the License, or (at ;; your option) any later version. ;; ;; This software is distributed in the hope that it will be useful, but ;; WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;; General Public License for more details. ;; ;; You should have received a copy of the GNU General Public License ;; along with this code; if not, see <http://www.gnu.org/licenses/>. ;; (ns sicmutils.numerical.quadrature.infinite-test (:require [clojure.test :refer [is deftest testing]] [same :refer [ish? zeroish? with-comparator] #?@(:cljs [:include-macros true])] [sicmutils.numerical.quadrature.adaptive :as qa] [sicmutils.numerical.quadrature.bulirsch-stoer :as bs] [sicmutils.numerical.quadrature.infinite :as qi] [sicmutils.value :as v])) (def ^:private integrator (qa/adaptive bs/open-integral bs/closed-integral)) (deftest improper-tests (binding [qa/*neighborhood-width* 0] (testing "Euler's constant" ;; https://en.wikipedia.org/wiki/Euler%E2%80%93Mascheroni_constant (let [f (fn [x] (* (Math/log x) (Math/exp (- x))))] (is (ish? {:converged? true :result -0.5772156418405041} ((qi/improper integrator) f 0 ##Inf)) "The improper integral converges.") (is (ish? {:converged? true :result -2.7965685938222346E-9} ((qi/improper integrator) f 0 ##Inf {:infinite-breakpoint 100})) "A breakpoint that's too big ruins the calculation by pushing the variable-change region to the right.") (is (= (integrator f 0 10) ((qi/improper integrator) f 0 10)) "With non-infinite bounds, integration passes through."))) (testing "full integration" (let [f (fn [x] (* x (Math/exp (- (* x x))))) integrate (qi/improper integrator)] (is (zeroish? (+ (:result (integrate f ##-Inf 0)) (:result (integrate f 0 ##Inf))))) (is (ish? {:converged? true :result 0} (integrate f ##-Inf ##Inf)) "We can handle the full range all at once.")))))
[ { "context": ";;\n;;\n;; Copyright 2013 Netflix, Inc.\n;;\n;; Licensed under the Apache License", "end": 32, "score": 0.7390389442443848, "start": 25, "tag": "NAME", "value": "Netflix" } ]
src/test/clojure/pigpen/script_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.script-test (:use clojure.test pigpen.script) (:require [pigpen.extensions.test :refer [test-diff pigsym-zero pigsym-inc]])) (deftest test-format-field (is (= (#'pigpen.script/format-field "abc") "'abc'")) (is (= (#'pigpen.script/format-field "a'b'c") "'a\\'b\\'c'")) (is (= (#'pigpen.script/format-field 'foo) "foo")) (is (= (#'pigpen.script/format-field '[[foo bar]]) "foo::bar")) (is (= (#'pigpen.script/format-field '[[foo bar baz]]) "foo::bar::baz")) (is (= (#'pigpen.script/format-field '[[foo] bar]) "foo.bar")) (is (= (#'pigpen.script/format-field '[[foo bar] baz]) "foo::bar.baz"))) (deftest test-expr->script (is (= (#'pigpen.script/expr->script nil) nil)) (is (= (#'pigpen.script/expr->script "a'b\\c") "'a\\'b\\\\c'")) (is (= (#'pigpen.script/expr->script 42) "42")) (is (= (#'pigpen.script/expr->script 'foo) "foo")) (is (= (#'pigpen.script/expr->script '(clojure.core/let [foo '2] foo)) "2")) (is (= (#'pigpen.script/expr->script '(clojure.core/let [foo '2] (and (= bar foo) (> baz 3)))) "((bar == 2) AND (baz > 3))"))) ;; ********** Util ********** (deftest test-code (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (is (= ["DEFINE udf1 pigpen.PigPenFnDataByteArray('(require (quote [pigpen.pig]))','identity');\n\n" "udf1()"] (command->script '{:type :code :expr {:init (require '[pigpen.pig]) :func identity} :return DataByteArray :args []} {}))))) (deftest test-register (is (= "REGISTER foo.jar;\n\n" (command->script '{:type :register :jar "foo.jar"} {})))) (deftest test-option (is (= "SET pig.maxCombinedSplitSize 1000000;\n\n" (command->script '{:type :option :option "pig.maxCombinedSplitSize" :value 1000000} {})))) ;; ********** IO ********** (deftest test-storage (is (= "\n USING PigStorage()" (command->script '{:type :storage :func "PigStorage" :args []} {}))) (is (= "\n USING PigStorage('foo', 'bar')" (command->script '{:type :storage :func "PigStorage" :args ["foo" "bar"]} {})))) (deftest test-load (is (= "load0 = LOAD 'foo'\n USING PigStorage()\n AS (a, b, c);\n\n" (command->script '{:type :load :id load0 :location "foo" :storage {:type :storage :func "PigStorage" :args []} :fields [a b c] :opts {:type :load-opts}} {}))) (is (= "load0 = LOAD 'foo'\n USING PigStorage();\n\n" (command->script '{:type :load :id load0 :location "foo" :storage {:type :storage :func "PigStorage" :args []} :fields [a b c] :opts {:type :load-opts :implicit-schema true}} {}))) (is (= "load0 = LOAD 'foo' USING PigStorage() AS (a:chararray, b:chararray, c:chararray);\n\n" (command->script '{:type :load :id load0 :location "foo" :storage {:type :storage :func "PigStorage" :args []} :fields [a b c] :opts {:type :load-opts :cast "chararray"}} {})))) (deftest test-store (is (= "STORE relation0 INTO 'foo'\n USING PigStorage();\n\n" (command->script '{:type :store :id store0 :ancestors [relation0] :location "foo" :storage {:type :storage :func "PigStorage" :args []} :opts {:type :store-opts}} {})))) ;; ********** Map ********** (deftest test-projection-field (is (= [nil "a AS b"] (command->script '{:type :projection-field :field a :alias b} {})))) (deftest test-projection-func (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (is (= ["DEFINE udf1 pigpen.PigPenFnDataByteArray('','(fn [x] (* x x))');\n\n" "udf1('a', a) AS b"] (command->script '{:type :projection-func :code {:type :code :expr {:init nil :func (fn [x] (* x x))} :return "DataByteArray" :args ["a" a]} :alias b} {}))))) (deftest test-generate (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (is (= "DEFINE udf1 pigpen.PigPenFnDataByteArray('','(fn [x] (* x x))'); generate0 = FOREACH relation0 GENERATE a AS b, udf1('a', a) AS b;\n\n" (command->script '{:type :generate :id generate0 :ancestors [relation0] :projections [{:type :projection-field :field a :alias b} {:type :projection-func :code {:type :code :expr {:init nil :func (fn [x] (* x x))} :return "DataByteArray" :args ["a" a]} :alias b}]} {}))))) (deftest test-generate-flatten (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (is (= "DEFINE udf1 pigpen.PigPenFnDataBag('','(fn [x] [x x])'); generate0 = FOREACH relation0 GENERATE FLATTEN(udf1('a', a)) AS b;\n\n" (command->script '{:type :generate :id generate0 :ancestors [relation0] :projections [{:type :projection-flat :code {:type :code :expr {:init nil :func (fn [x] [x x])} :return "DataBag" :args ["a" a]} :alias b}]} {}))))) (deftest test-order (is (= "order0 = ORDER relation0 BY key1 ASC, key2 DESC PARALLEL 10;\n\n" (command->script '{:type :order :id order0 :description nil :ancestors [relation0] :fields [key value] :field-type :frozen :sort-keys [key1 :asc key2 :desc] :opts {:type :order-opts :parallel 10}} {})))) (deftest test-rank (is (= "rank0 = RANK relation0 BY key ASC DENSE;\n\n" (command->script '{:type :rank :id rank0 :description nil :ancestors [relation0] :fields [key value] :field-type :frozen :sort-keys [key :asc] :opts {:type :rank-opts :dense true}} {}))) (is (= "rank0 = RANK relation0;\n\n" (command->script '{:type :rank :id rank0 :description nil :ancestors [relation0] :fields [key value] :field-type :frozen :sort-keys [] :opts {:type :rank-opts}} {})))) ;; ********** Filter ********** (deftest test-filter (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (is (= "DEFINE udf1 pigpen.PigPenFnBoolean('','(fn [x] (even? x))'); filter0 = FILTER relation0 BY udf1('a', a);\n\n" (command->script '{:type :filter :id filter0 :ancestors [relation0] :code {:type :code :expr {:init nil :func (fn [x] (even? x))} :return "Boolean" :args ["a" a]}} {}))))) (deftest test-filter-native (is (= "filter_native0 = FILTER relation0 BY ((foo == 1) AND (bar > 2));\n\n" (command->script '{:type :filter-native :id filter-native0 :ancestors [relation0] :expr '(and (= foo 1) (> bar 2))} {})))) (deftest test-distinct (let [state {:partitioner (atom -1)}] (testing "normal" (is (= "distinct0 = DISTINCT relation0 PARALLEL 20;\n\n" (command->script '{:type :distinct :id distinct0 :ancestors [relation0] :opts {:type :distinct-opts :parallel 20}} state)))) (testing "with partitioner" (is (= "SET PigPenPartitioner0_type 'frozen'; SET PigPenPartitioner0_init ''; SET PigPenPartitioner0_func '(fn [n key] (mod (hash key) n))'; distinct0 = DISTINCT relation0 PARTITION BY pigpen.PigPenPartitioner0;\n\n" (command->script '{:type :distinct :id distinct0 :ancestors [relation0] :opts {:type :distinct-opts :partition-by (fn [n key] (mod (hash key) n))}} state)))) (testing "with native partitioner" (is (= "SET PigPenPartitioner1_type 'native'; SET PigPenPartitioner1_init ''; SET PigPenPartitioner1_func '(fn [n key] (mod (hash key) n))'; distinct0 = DISTINCT relation0 PARTITION BY pigpen.PigPenPartitioner1;\n\n" (command->script '{:type :distinct :id distinct0 :ancestors [relation0] :opts {:type :distinct-opts :partition-by (fn [n key] (mod (hash key) n)) :partition-type :native}} state)))))) (deftest test-limit (is (= "limit0 = LIMIT relation0 100;\n\n" (command->script '{:type :limit :id limit0 :ancestors [relation0] :n 100 :opts {:mode #{:script}}} {})))) (deftest test-sample (is (= "sample0 = SAMPLE relation0 0.01;\n\n" (command->script '{:type :sample :id sample0 :ancestors [relation0] :p 0.01 :opts {:mode #{:script}}} {})))) ;; ********** Combine ********** (deftest test-union (is (= "union0 = UNION r0, r1;\n\n" (command->script '{:type :union :id union0 :fields [value] :ancestors [r0 r1] :opts {:type :union-opts}} {})))) (deftest test-group (is (= "group0 = COGROUP r0 BY (a);\n\n" (command->script '{:type :group :id group0 :keys [[a]] :join-types [:optional] :ancestors [r0] :opts {:type :group-opts}} {}))) (is (= "group0 = COGROUP r0 BY (a, b);\n\n" (command->script '{:type :group :id group0 :keys [[a b]] :join-types [:optional] :ancestors [r0] :opts {:type :group-opts}} {}))) (is (= "group0 = COGROUP r0 BY (a), r1 BY (b);\n\n" (command->script '{:type :group :id group0 :keys [[a] [b]] :join-types [:optional :optional] :ancestors [r0 r1] :opts {:type :group-opts}} {}))) (is (= "group0 = COGROUP r0 BY (a), r1 BY (b) USING 'merge' PARALLEL 2;\n\n" (command->script '{:type :group :id group0 :keys [[a] [b]] :join-types [:optional :optional] :ancestors [r0 r1] :opts {:type :group-opts :strategy :merge :parallel 2}} {}))) (is (= "group0 = COGROUP r0 BY (a) INNER, r1 BY (b) INNER;\n\n" (command->script '{:type :group :id group0 :keys [[a] [b]] :join-types [:required :required] :ancestors [r0 r1] :opts {:type :group-opts}} {}))) (is (= "group0 = COGROUP r0 ALL;\n\n" (command->script '{:type :group :id group0 :keys [:pigpen.raw/group-all] :join-types [:optional] :ancestors [r0] :opts {:type :group-opts}} {})))) (deftest test-join (is (= "join0 = JOIN r0 BY (a), r1 BY (b);\n\n" (command->script '{:type :join :id join0 :keys [[a] [b]] :join-types [:required :required] :ancestors [r0 r1] :opts {:type :group-opts}} {}))) (is (= "join0 = JOIN r0 BY (a, b), r1 BY (b, c) USING 'replicated' PARALLEL 2;\n\n" (command->script '{:type :join :id join0 :keys [[a b] [b c]] :join-types [:required :required] :ancestors [r0 r1] :opts {:type :group-opts :strategy :replicated :parallel 2}} {}))) (is (= "join0 = JOIN r0 BY (a, b) LEFT OUTER, r1 BY (b, c);\n\n" (command->script '{:type :join :id join0 :keys [[a b] [b c]] :join-types [:required :optional] :ancestors [r0 r1] :opts {:type :group-opts}} {})))) ;; ********** Script ********** ;; TODO test-script
101717
;; ;; ;; 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.script-test (:use clojure.test pigpen.script) (:require [pigpen.extensions.test :refer [test-diff pigsym-zero pigsym-inc]])) (deftest test-format-field (is (= (#'pigpen.script/format-field "abc") "'abc'")) (is (= (#'pigpen.script/format-field "a'b'c") "'a\\'b\\'c'")) (is (= (#'pigpen.script/format-field 'foo) "foo")) (is (= (#'pigpen.script/format-field '[[foo bar]]) "foo::bar")) (is (= (#'pigpen.script/format-field '[[foo bar baz]]) "foo::bar::baz")) (is (= (#'pigpen.script/format-field '[[foo] bar]) "foo.bar")) (is (= (#'pigpen.script/format-field '[[foo bar] baz]) "foo::bar.baz"))) (deftest test-expr->script (is (= (#'pigpen.script/expr->script nil) nil)) (is (= (#'pigpen.script/expr->script "a'b\\c") "'a\\'b\\\\c'")) (is (= (#'pigpen.script/expr->script 42) "42")) (is (= (#'pigpen.script/expr->script 'foo) "foo")) (is (= (#'pigpen.script/expr->script '(clojure.core/let [foo '2] foo)) "2")) (is (= (#'pigpen.script/expr->script '(clojure.core/let [foo '2] (and (= bar foo) (> baz 3)))) "((bar == 2) AND (baz > 3))"))) ;; ********** Util ********** (deftest test-code (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (is (= ["DEFINE udf1 pigpen.PigPenFnDataByteArray('(require (quote [pigpen.pig]))','identity');\n\n" "udf1()"] (command->script '{:type :code :expr {:init (require '[pigpen.pig]) :func identity} :return DataByteArray :args []} {}))))) (deftest test-register (is (= "REGISTER foo.jar;\n\n" (command->script '{:type :register :jar "foo.jar"} {})))) (deftest test-option (is (= "SET pig.maxCombinedSplitSize 1000000;\n\n" (command->script '{:type :option :option "pig.maxCombinedSplitSize" :value 1000000} {})))) ;; ********** IO ********** (deftest test-storage (is (= "\n USING PigStorage()" (command->script '{:type :storage :func "PigStorage" :args []} {}))) (is (= "\n USING PigStorage('foo', 'bar')" (command->script '{:type :storage :func "PigStorage" :args ["foo" "bar"]} {})))) (deftest test-load (is (= "load0 = LOAD 'foo'\n USING PigStorage()\n AS (a, b, c);\n\n" (command->script '{:type :load :id load0 :location "foo" :storage {:type :storage :func "PigStorage" :args []} :fields [a b c] :opts {:type :load-opts}} {}))) (is (= "load0 = LOAD 'foo'\n USING PigStorage();\n\n" (command->script '{:type :load :id load0 :location "foo" :storage {:type :storage :func "PigStorage" :args []} :fields [a b c] :opts {:type :load-opts :implicit-schema true}} {}))) (is (= "load0 = LOAD 'foo' USING PigStorage() AS (a:chararray, b:chararray, c:chararray);\n\n" (command->script '{:type :load :id load0 :location "foo" :storage {:type :storage :func "PigStorage" :args []} :fields [a b c] :opts {:type :load-opts :cast "chararray"}} {})))) (deftest test-store (is (= "STORE relation0 INTO 'foo'\n USING PigStorage();\n\n" (command->script '{:type :store :id store0 :ancestors [relation0] :location "foo" :storage {:type :storage :func "PigStorage" :args []} :opts {:type :store-opts}} {})))) ;; ********** Map ********** (deftest test-projection-field (is (= [nil "a AS b"] (command->script '{:type :projection-field :field a :alias b} {})))) (deftest test-projection-func (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (is (= ["DEFINE udf1 pigpen.PigPenFnDataByteArray('','(fn [x] (* x x))');\n\n" "udf1('a', a) AS b"] (command->script '{:type :projection-func :code {:type :code :expr {:init nil :func (fn [x] (* x x))} :return "DataByteArray" :args ["a" a]} :alias b} {}))))) (deftest test-generate (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (is (= "DEFINE udf1 pigpen.PigPenFnDataByteArray('','(fn [x] (* x x))'); generate0 = FOREACH relation0 GENERATE a AS b, udf1('a', a) AS b;\n\n" (command->script '{:type :generate :id generate0 :ancestors [relation0] :projections [{:type :projection-field :field a :alias b} {:type :projection-func :code {:type :code :expr {:init nil :func (fn [x] (* x x))} :return "DataByteArray" :args ["a" a]} :alias b}]} {}))))) (deftest test-generate-flatten (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (is (= "DEFINE udf1 pigpen.PigPenFnDataBag('','(fn [x] [x x])'); generate0 = FOREACH relation0 GENERATE FLATTEN(udf1('a', a)) AS b;\n\n" (command->script '{:type :generate :id generate0 :ancestors [relation0] :projections [{:type :projection-flat :code {:type :code :expr {:init nil :func (fn [x] [x x])} :return "DataBag" :args ["a" a]} :alias b}]} {}))))) (deftest test-order (is (= "order0 = ORDER relation0 BY key1 ASC, key2 DESC PARALLEL 10;\n\n" (command->script '{:type :order :id order0 :description nil :ancestors [relation0] :fields [key value] :field-type :frozen :sort-keys [key1 :asc key2 :desc] :opts {:type :order-opts :parallel 10}} {})))) (deftest test-rank (is (= "rank0 = RANK relation0 BY key ASC DENSE;\n\n" (command->script '{:type :rank :id rank0 :description nil :ancestors [relation0] :fields [key value] :field-type :frozen :sort-keys [key :asc] :opts {:type :rank-opts :dense true}} {}))) (is (= "rank0 = RANK relation0;\n\n" (command->script '{:type :rank :id rank0 :description nil :ancestors [relation0] :fields [key value] :field-type :frozen :sort-keys [] :opts {:type :rank-opts}} {})))) ;; ********** Filter ********** (deftest test-filter (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (is (= "DEFINE udf1 pigpen.PigPenFnBoolean('','(fn [x] (even? x))'); filter0 = FILTER relation0 BY udf1('a', a);\n\n" (command->script '{:type :filter :id filter0 :ancestors [relation0] :code {:type :code :expr {:init nil :func (fn [x] (even? x))} :return "Boolean" :args ["a" a]}} {}))))) (deftest test-filter-native (is (= "filter_native0 = FILTER relation0 BY ((foo == 1) AND (bar > 2));\n\n" (command->script '{:type :filter-native :id filter-native0 :ancestors [relation0] :expr '(and (= foo 1) (> bar 2))} {})))) (deftest test-distinct (let [state {:partitioner (atom -1)}] (testing "normal" (is (= "distinct0 = DISTINCT relation0 PARALLEL 20;\n\n" (command->script '{:type :distinct :id distinct0 :ancestors [relation0] :opts {:type :distinct-opts :parallel 20}} state)))) (testing "with partitioner" (is (= "SET PigPenPartitioner0_type 'frozen'; SET PigPenPartitioner0_init ''; SET PigPenPartitioner0_func '(fn [n key] (mod (hash key) n))'; distinct0 = DISTINCT relation0 PARTITION BY pigpen.PigPenPartitioner0;\n\n" (command->script '{:type :distinct :id distinct0 :ancestors [relation0] :opts {:type :distinct-opts :partition-by (fn [n key] (mod (hash key) n))}} state)))) (testing "with native partitioner" (is (= "SET PigPenPartitioner1_type 'native'; SET PigPenPartitioner1_init ''; SET PigPenPartitioner1_func '(fn [n key] (mod (hash key) n))'; distinct0 = DISTINCT relation0 PARTITION BY pigpen.PigPenPartitioner1;\n\n" (command->script '{:type :distinct :id distinct0 :ancestors [relation0] :opts {:type :distinct-opts :partition-by (fn [n key] (mod (hash key) n)) :partition-type :native}} state)))))) (deftest test-limit (is (= "limit0 = LIMIT relation0 100;\n\n" (command->script '{:type :limit :id limit0 :ancestors [relation0] :n 100 :opts {:mode #{:script}}} {})))) (deftest test-sample (is (= "sample0 = SAMPLE relation0 0.01;\n\n" (command->script '{:type :sample :id sample0 :ancestors [relation0] :p 0.01 :opts {:mode #{:script}}} {})))) ;; ********** Combine ********** (deftest test-union (is (= "union0 = UNION r0, r1;\n\n" (command->script '{:type :union :id union0 :fields [value] :ancestors [r0 r1] :opts {:type :union-opts}} {})))) (deftest test-group (is (= "group0 = COGROUP r0 BY (a);\n\n" (command->script '{:type :group :id group0 :keys [[a]] :join-types [:optional] :ancestors [r0] :opts {:type :group-opts}} {}))) (is (= "group0 = COGROUP r0 BY (a, b);\n\n" (command->script '{:type :group :id group0 :keys [[a b]] :join-types [:optional] :ancestors [r0] :opts {:type :group-opts}} {}))) (is (= "group0 = COGROUP r0 BY (a), r1 BY (b);\n\n" (command->script '{:type :group :id group0 :keys [[a] [b]] :join-types [:optional :optional] :ancestors [r0 r1] :opts {:type :group-opts}} {}))) (is (= "group0 = COGROUP r0 BY (a), r1 BY (b) USING 'merge' PARALLEL 2;\n\n" (command->script '{:type :group :id group0 :keys [[a] [b]] :join-types [:optional :optional] :ancestors [r0 r1] :opts {:type :group-opts :strategy :merge :parallel 2}} {}))) (is (= "group0 = COGROUP r0 BY (a) INNER, r1 BY (b) INNER;\n\n" (command->script '{:type :group :id group0 :keys [[a] [b]] :join-types [:required :required] :ancestors [r0 r1] :opts {:type :group-opts}} {}))) (is (= "group0 = COGROUP r0 ALL;\n\n" (command->script '{:type :group :id group0 :keys [:pigpen.raw/group-all] :join-types [:optional] :ancestors [r0] :opts {:type :group-opts}} {})))) (deftest test-join (is (= "join0 = JOIN r0 BY (a), r1 BY (b);\n\n" (command->script '{:type :join :id join0 :keys [[a] [b]] :join-types [:required :required] :ancestors [r0 r1] :opts {:type :group-opts}} {}))) (is (= "join0 = JOIN r0 BY (a, b), r1 BY (b, c) USING 'replicated' PARALLEL 2;\n\n" (command->script '{:type :join :id join0 :keys [[a b] [b c]] :join-types [:required :required] :ancestors [r0 r1] :opts {:type :group-opts :strategy :replicated :parallel 2}} {}))) (is (= "join0 = JOIN r0 BY (a, b) LEFT OUTER, r1 BY (b, c);\n\n" (command->script '{:type :join :id join0 :keys [[a b] [b c]] :join-types [:required :optional] :ancestors [r0 r1] :opts {:type :group-opts}} {})))) ;; ********** Script ********** ;; TODO test-script
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.script-test (:use clojure.test pigpen.script) (:require [pigpen.extensions.test :refer [test-diff pigsym-zero pigsym-inc]])) (deftest test-format-field (is (= (#'pigpen.script/format-field "abc") "'abc'")) (is (= (#'pigpen.script/format-field "a'b'c") "'a\\'b\\'c'")) (is (= (#'pigpen.script/format-field 'foo) "foo")) (is (= (#'pigpen.script/format-field '[[foo bar]]) "foo::bar")) (is (= (#'pigpen.script/format-field '[[foo bar baz]]) "foo::bar::baz")) (is (= (#'pigpen.script/format-field '[[foo] bar]) "foo.bar")) (is (= (#'pigpen.script/format-field '[[foo bar] baz]) "foo::bar.baz"))) (deftest test-expr->script (is (= (#'pigpen.script/expr->script nil) nil)) (is (= (#'pigpen.script/expr->script "a'b\\c") "'a\\'b\\\\c'")) (is (= (#'pigpen.script/expr->script 42) "42")) (is (= (#'pigpen.script/expr->script 'foo) "foo")) (is (= (#'pigpen.script/expr->script '(clojure.core/let [foo '2] foo)) "2")) (is (= (#'pigpen.script/expr->script '(clojure.core/let [foo '2] (and (= bar foo) (> baz 3)))) "((bar == 2) AND (baz > 3))"))) ;; ********** Util ********** (deftest test-code (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (is (= ["DEFINE udf1 pigpen.PigPenFnDataByteArray('(require (quote [pigpen.pig]))','identity');\n\n" "udf1()"] (command->script '{:type :code :expr {:init (require '[pigpen.pig]) :func identity} :return DataByteArray :args []} {}))))) (deftest test-register (is (= "REGISTER foo.jar;\n\n" (command->script '{:type :register :jar "foo.jar"} {})))) (deftest test-option (is (= "SET pig.maxCombinedSplitSize 1000000;\n\n" (command->script '{:type :option :option "pig.maxCombinedSplitSize" :value 1000000} {})))) ;; ********** IO ********** (deftest test-storage (is (= "\n USING PigStorage()" (command->script '{:type :storage :func "PigStorage" :args []} {}))) (is (= "\n USING PigStorage('foo', 'bar')" (command->script '{:type :storage :func "PigStorage" :args ["foo" "bar"]} {})))) (deftest test-load (is (= "load0 = LOAD 'foo'\n USING PigStorage()\n AS (a, b, c);\n\n" (command->script '{:type :load :id load0 :location "foo" :storage {:type :storage :func "PigStorage" :args []} :fields [a b c] :opts {:type :load-opts}} {}))) (is (= "load0 = LOAD 'foo'\n USING PigStorage();\n\n" (command->script '{:type :load :id load0 :location "foo" :storage {:type :storage :func "PigStorage" :args []} :fields [a b c] :opts {:type :load-opts :implicit-schema true}} {}))) (is (= "load0 = LOAD 'foo' USING PigStorage() AS (a:chararray, b:chararray, c:chararray);\n\n" (command->script '{:type :load :id load0 :location "foo" :storage {:type :storage :func "PigStorage" :args []} :fields [a b c] :opts {:type :load-opts :cast "chararray"}} {})))) (deftest test-store (is (= "STORE relation0 INTO 'foo'\n USING PigStorage();\n\n" (command->script '{:type :store :id store0 :ancestors [relation0] :location "foo" :storage {:type :storage :func "PigStorage" :args []} :opts {:type :store-opts}} {})))) ;; ********** Map ********** (deftest test-projection-field (is (= [nil "a AS b"] (command->script '{:type :projection-field :field a :alias b} {})))) (deftest test-projection-func (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (is (= ["DEFINE udf1 pigpen.PigPenFnDataByteArray('','(fn [x] (* x x))');\n\n" "udf1('a', a) AS b"] (command->script '{:type :projection-func :code {:type :code :expr {:init nil :func (fn [x] (* x x))} :return "DataByteArray" :args ["a" a]} :alias b} {}))))) (deftest test-generate (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (is (= "DEFINE udf1 pigpen.PigPenFnDataByteArray('','(fn [x] (* x x))'); generate0 = FOREACH relation0 GENERATE a AS b, udf1('a', a) AS b;\n\n" (command->script '{:type :generate :id generate0 :ancestors [relation0] :projections [{:type :projection-field :field a :alias b} {:type :projection-func :code {:type :code :expr {:init nil :func (fn [x] (* x x))} :return "DataByteArray" :args ["a" a]} :alias b}]} {}))))) (deftest test-generate-flatten (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (is (= "DEFINE udf1 pigpen.PigPenFnDataBag('','(fn [x] [x x])'); generate0 = FOREACH relation0 GENERATE FLATTEN(udf1('a', a)) AS b;\n\n" (command->script '{:type :generate :id generate0 :ancestors [relation0] :projections [{:type :projection-flat :code {:type :code :expr {:init nil :func (fn [x] [x x])} :return "DataBag" :args ["a" a]} :alias b}]} {}))))) (deftest test-order (is (= "order0 = ORDER relation0 BY key1 ASC, key2 DESC PARALLEL 10;\n\n" (command->script '{:type :order :id order0 :description nil :ancestors [relation0] :fields [key value] :field-type :frozen :sort-keys [key1 :asc key2 :desc] :opts {:type :order-opts :parallel 10}} {})))) (deftest test-rank (is (= "rank0 = RANK relation0 BY key ASC DENSE;\n\n" (command->script '{:type :rank :id rank0 :description nil :ancestors [relation0] :fields [key value] :field-type :frozen :sort-keys [key :asc] :opts {:type :rank-opts :dense true}} {}))) (is (= "rank0 = RANK relation0;\n\n" (command->script '{:type :rank :id rank0 :description nil :ancestors [relation0] :fields [key value] :field-type :frozen :sort-keys [] :opts {:type :rank-opts}} {})))) ;; ********** Filter ********** (deftest test-filter (with-redefs [pigpen.raw/pigsym (pigsym-inc)] (is (= "DEFINE udf1 pigpen.PigPenFnBoolean('','(fn [x] (even? x))'); filter0 = FILTER relation0 BY udf1('a', a);\n\n" (command->script '{:type :filter :id filter0 :ancestors [relation0] :code {:type :code :expr {:init nil :func (fn [x] (even? x))} :return "Boolean" :args ["a" a]}} {}))))) (deftest test-filter-native (is (= "filter_native0 = FILTER relation0 BY ((foo == 1) AND (bar > 2));\n\n" (command->script '{:type :filter-native :id filter-native0 :ancestors [relation0] :expr '(and (= foo 1) (> bar 2))} {})))) (deftest test-distinct (let [state {:partitioner (atom -1)}] (testing "normal" (is (= "distinct0 = DISTINCT relation0 PARALLEL 20;\n\n" (command->script '{:type :distinct :id distinct0 :ancestors [relation0] :opts {:type :distinct-opts :parallel 20}} state)))) (testing "with partitioner" (is (= "SET PigPenPartitioner0_type 'frozen'; SET PigPenPartitioner0_init ''; SET PigPenPartitioner0_func '(fn [n key] (mod (hash key) n))'; distinct0 = DISTINCT relation0 PARTITION BY pigpen.PigPenPartitioner0;\n\n" (command->script '{:type :distinct :id distinct0 :ancestors [relation0] :opts {:type :distinct-opts :partition-by (fn [n key] (mod (hash key) n))}} state)))) (testing "with native partitioner" (is (= "SET PigPenPartitioner1_type 'native'; SET PigPenPartitioner1_init ''; SET PigPenPartitioner1_func '(fn [n key] (mod (hash key) n))'; distinct0 = DISTINCT relation0 PARTITION BY pigpen.PigPenPartitioner1;\n\n" (command->script '{:type :distinct :id distinct0 :ancestors [relation0] :opts {:type :distinct-opts :partition-by (fn [n key] (mod (hash key) n)) :partition-type :native}} state)))))) (deftest test-limit (is (= "limit0 = LIMIT relation0 100;\n\n" (command->script '{:type :limit :id limit0 :ancestors [relation0] :n 100 :opts {:mode #{:script}}} {})))) (deftest test-sample (is (= "sample0 = SAMPLE relation0 0.01;\n\n" (command->script '{:type :sample :id sample0 :ancestors [relation0] :p 0.01 :opts {:mode #{:script}}} {})))) ;; ********** Combine ********** (deftest test-union (is (= "union0 = UNION r0, r1;\n\n" (command->script '{:type :union :id union0 :fields [value] :ancestors [r0 r1] :opts {:type :union-opts}} {})))) (deftest test-group (is (= "group0 = COGROUP r0 BY (a);\n\n" (command->script '{:type :group :id group0 :keys [[a]] :join-types [:optional] :ancestors [r0] :opts {:type :group-opts}} {}))) (is (= "group0 = COGROUP r0 BY (a, b);\n\n" (command->script '{:type :group :id group0 :keys [[a b]] :join-types [:optional] :ancestors [r0] :opts {:type :group-opts}} {}))) (is (= "group0 = COGROUP r0 BY (a), r1 BY (b);\n\n" (command->script '{:type :group :id group0 :keys [[a] [b]] :join-types [:optional :optional] :ancestors [r0 r1] :opts {:type :group-opts}} {}))) (is (= "group0 = COGROUP r0 BY (a), r1 BY (b) USING 'merge' PARALLEL 2;\n\n" (command->script '{:type :group :id group0 :keys [[a] [b]] :join-types [:optional :optional] :ancestors [r0 r1] :opts {:type :group-opts :strategy :merge :parallel 2}} {}))) (is (= "group0 = COGROUP r0 BY (a) INNER, r1 BY (b) INNER;\n\n" (command->script '{:type :group :id group0 :keys [[a] [b]] :join-types [:required :required] :ancestors [r0 r1] :opts {:type :group-opts}} {}))) (is (= "group0 = COGROUP r0 ALL;\n\n" (command->script '{:type :group :id group0 :keys [:pigpen.raw/group-all] :join-types [:optional] :ancestors [r0] :opts {:type :group-opts}} {})))) (deftest test-join (is (= "join0 = JOIN r0 BY (a), r1 BY (b);\n\n" (command->script '{:type :join :id join0 :keys [[a] [b]] :join-types [:required :required] :ancestors [r0 r1] :opts {:type :group-opts}} {}))) (is (= "join0 = JOIN r0 BY (a, b), r1 BY (b, c) USING 'replicated' PARALLEL 2;\n\n" (command->script '{:type :join :id join0 :keys [[a b] [b c]] :join-types [:required :required] :ancestors [r0 r1] :opts {:type :group-opts :strategy :replicated :parallel 2}} {}))) (is (= "join0 = JOIN r0 BY (a, b) LEFT OUTER, r1 BY (b, c);\n\n" (command->script '{:type :join :id join0 :keys [[a b] [b c]] :join-types [:required :optional] :ancestors [r0 r1] :opts {:type :group-opts}} {})))) ;; ********** Script ********** ;; TODO test-script
[ { "context": "plication\"\n :platform :GCM}))\n\n(def gcm-token \"XYZ\")\n\n(defn create-platform-endpoint! [creds arn]\n ", "end": 1753, "score": 0.4650286138057709, "start": 1750, "tag": "KEY", "value": "XYZ" } ]
test/eulalie/test/sns.cljc
nervous-systems/eulalie
93
(ns eulalie.test.sns (:require [eulalie.core :as eulalie] [eulalie.sns] [eulalie.util.xml :as x] [glossop.core #? (:clj :refer :cljs :refer-macros) [go-catching <?]] [eulalie.test.common :as test.common #? (:clj :refer :cljs :refer-macros) [deftest is]])) (defn sns! [creds target content & [req-overrides]] (go-catching (let [req (merge {:service :sns :target target :max-retries 0 :body content :creds creds} req-overrides)] (:body (<? (test.common/issue-raw! req)))))) (defn create-topic! [creds] (sns! creds :create-topic {:name "the-best-topic"})) (deftest ^:integration ^:aws create-topic (test.common/with-aws (fn [creds] (go-catching (is (= "arn:" (some-> (create-topic! creds) <? (subs 0 4)))))))) (deftest ^:integration ^:aws add-permission (test.common/with-aws (fn [creds] (go-catching (if (not-empty test.common/aws-account-id) (is (-> (sns! creds :add-permission {:accounts [test.common/aws-account-id] :actions [:publish :get-topic-attributes] :label "eulalie-add-permission-test" :topic-arn (<? (create-topic! creds))}) <? :add-permission-response)) (println "Warning: Skipping test due to absence of AWS_ACCOUNT_ID var")))))) (defn create-gcm-application! [creds] (sns! creds :create-platform-application {:attrs {:platform-credential test.common/gcm-api-key} :name "the-best-application" :platform :GCM})) (def gcm-token "XYZ") (defn create-platform-endpoint! [creds arn] (sns! creds :create-platform-endpoint {:platform-application-arn arn :token gcm-token})) (deftest ^:integration ^:aws create-platform-application (test.common/with-aws (fn [creds] (go-catching (is (= "arn:" (some-> (create-gcm-application! creds) <? (subs 0 4)))))))) ;; This is failing on Travis, but not locally - investigate. ;; (deftest ^:integration ^:aws set-platform-application-attributes ;; (test.common/with-aws ;; (fn [creds] ;; (go-catching ;; (let [arn (<? (create-gcm-application! creds))] ;; (<? (sns! creds ;; :set-platform-application-attributes ;; {:platform-application-arn arn ;; :attrs {:success-feedback-sample-rate 50}})) ;; (is (:success-feedback-sample-rate ;; (<? (sns! creds ;; :get-platform-application-attributes ;; {:platform-application-arn arn}))))))))) (deftest ^:integration ^:aws delete-platform-application+ (test.common/with-aws (fn [creds] (go-catching (let [arn (<? (create-gcm-application! creds))] (is (<? (sns! creds :delete-platform-application {:platform-application-arn arn})))))))) (defn create-platform-application! [creds name] (sns! creds :create-platform-application {:platform :GCM :name name :attrs {:platform-credential test.common/gcm-api-key}})) (defn with-transient-app! [f] (test.common/with-aws (fn [creds] (go-catching (let [arn (<? (create-platform-application! creds (str "eulalie-transient-" (rand-int 0xFFFF))))] (try (<? (f creds arn)) (finally (<? (sns! creds :delete-platform-application {:platform-application-arn arn}))))))))) (deftest ^:integration ^:aws publish (test.common/with-aws (fn [creds] (go-catching (is (-> (sns! creds :publish {:topic-arn (<? (create-topic! creds)) :subject "Hello" :message {:default "OK" :GCM {:data {:message "This is the GCM"}}} :attrs {:name [:string "OK"]}}) <? string?)))))) (deftest ^:integration ^:aws get-topic-attributes (test.common/with-aws (fn [creds] (go-catching (let [arn (<? (create-topic! creds))] (is (map? (:policy (<? (sns! creds :get-topic-attributes {:topic-arn arn})))))))))) (deftest ^:integration ^:aws get-endpoint-attributes (with-transient-app! (fn [creds p-arn] (go-catching (let [e-arn (<? (create-platform-endpoint! creds p-arn))] (is (= gcm-token (:token (<? (sns! creds :get-endpoint-attributes {:endpoint-arn e-arn})))))))))) (deftest ^:integration ^:aws list-endpoints-by-platform-application (with-transient-app! (fn [creds p-arn] (go-catching (let [e-arn (<? (create-platform-endpoint! creds p-arn)) arns (->> (sns! creds :list-endpoints-by-platform-application {:platform-application-arn p-arn}) <? (map :arn) (into #{}))] (is (arns e-arn)))))))
80949
(ns eulalie.test.sns (:require [eulalie.core :as eulalie] [eulalie.sns] [eulalie.util.xml :as x] [glossop.core #? (:clj :refer :cljs :refer-macros) [go-catching <?]] [eulalie.test.common :as test.common #? (:clj :refer :cljs :refer-macros) [deftest is]])) (defn sns! [creds target content & [req-overrides]] (go-catching (let [req (merge {:service :sns :target target :max-retries 0 :body content :creds creds} req-overrides)] (:body (<? (test.common/issue-raw! req)))))) (defn create-topic! [creds] (sns! creds :create-topic {:name "the-best-topic"})) (deftest ^:integration ^:aws create-topic (test.common/with-aws (fn [creds] (go-catching (is (= "arn:" (some-> (create-topic! creds) <? (subs 0 4)))))))) (deftest ^:integration ^:aws add-permission (test.common/with-aws (fn [creds] (go-catching (if (not-empty test.common/aws-account-id) (is (-> (sns! creds :add-permission {:accounts [test.common/aws-account-id] :actions [:publish :get-topic-attributes] :label "eulalie-add-permission-test" :topic-arn (<? (create-topic! creds))}) <? :add-permission-response)) (println "Warning: Skipping test due to absence of AWS_ACCOUNT_ID var")))))) (defn create-gcm-application! [creds] (sns! creds :create-platform-application {:attrs {:platform-credential test.common/gcm-api-key} :name "the-best-application" :platform :GCM})) (def gcm-token "<KEY>") (defn create-platform-endpoint! [creds arn] (sns! creds :create-platform-endpoint {:platform-application-arn arn :token gcm-token})) (deftest ^:integration ^:aws create-platform-application (test.common/with-aws (fn [creds] (go-catching (is (= "arn:" (some-> (create-gcm-application! creds) <? (subs 0 4)))))))) ;; This is failing on Travis, but not locally - investigate. ;; (deftest ^:integration ^:aws set-platform-application-attributes ;; (test.common/with-aws ;; (fn [creds] ;; (go-catching ;; (let [arn (<? (create-gcm-application! creds))] ;; (<? (sns! creds ;; :set-platform-application-attributes ;; {:platform-application-arn arn ;; :attrs {:success-feedback-sample-rate 50}})) ;; (is (:success-feedback-sample-rate ;; (<? (sns! creds ;; :get-platform-application-attributes ;; {:platform-application-arn arn}))))))))) (deftest ^:integration ^:aws delete-platform-application+ (test.common/with-aws (fn [creds] (go-catching (let [arn (<? (create-gcm-application! creds))] (is (<? (sns! creds :delete-platform-application {:platform-application-arn arn})))))))) (defn create-platform-application! [creds name] (sns! creds :create-platform-application {:platform :GCM :name name :attrs {:platform-credential test.common/gcm-api-key}})) (defn with-transient-app! [f] (test.common/with-aws (fn [creds] (go-catching (let [arn (<? (create-platform-application! creds (str "eulalie-transient-" (rand-int 0xFFFF))))] (try (<? (f creds arn)) (finally (<? (sns! creds :delete-platform-application {:platform-application-arn arn}))))))))) (deftest ^:integration ^:aws publish (test.common/with-aws (fn [creds] (go-catching (is (-> (sns! creds :publish {:topic-arn (<? (create-topic! creds)) :subject "Hello" :message {:default "OK" :GCM {:data {:message "This is the GCM"}}} :attrs {:name [:string "OK"]}}) <? string?)))))) (deftest ^:integration ^:aws get-topic-attributes (test.common/with-aws (fn [creds] (go-catching (let [arn (<? (create-topic! creds))] (is (map? (:policy (<? (sns! creds :get-topic-attributes {:topic-arn arn})))))))))) (deftest ^:integration ^:aws get-endpoint-attributes (with-transient-app! (fn [creds p-arn] (go-catching (let [e-arn (<? (create-platform-endpoint! creds p-arn))] (is (= gcm-token (:token (<? (sns! creds :get-endpoint-attributes {:endpoint-arn e-arn})))))))))) (deftest ^:integration ^:aws list-endpoints-by-platform-application (with-transient-app! (fn [creds p-arn] (go-catching (let [e-arn (<? (create-platform-endpoint! creds p-arn)) arns (->> (sns! creds :list-endpoints-by-platform-application {:platform-application-arn p-arn}) <? (map :arn) (into #{}))] (is (arns e-arn)))))))
true
(ns eulalie.test.sns (:require [eulalie.core :as eulalie] [eulalie.sns] [eulalie.util.xml :as x] [glossop.core #? (:clj :refer :cljs :refer-macros) [go-catching <?]] [eulalie.test.common :as test.common #? (:clj :refer :cljs :refer-macros) [deftest is]])) (defn sns! [creds target content & [req-overrides]] (go-catching (let [req (merge {:service :sns :target target :max-retries 0 :body content :creds creds} req-overrides)] (:body (<? (test.common/issue-raw! req)))))) (defn create-topic! [creds] (sns! creds :create-topic {:name "the-best-topic"})) (deftest ^:integration ^:aws create-topic (test.common/with-aws (fn [creds] (go-catching (is (= "arn:" (some-> (create-topic! creds) <? (subs 0 4)))))))) (deftest ^:integration ^:aws add-permission (test.common/with-aws (fn [creds] (go-catching (if (not-empty test.common/aws-account-id) (is (-> (sns! creds :add-permission {:accounts [test.common/aws-account-id] :actions [:publish :get-topic-attributes] :label "eulalie-add-permission-test" :topic-arn (<? (create-topic! creds))}) <? :add-permission-response)) (println "Warning: Skipping test due to absence of AWS_ACCOUNT_ID var")))))) (defn create-gcm-application! [creds] (sns! creds :create-platform-application {:attrs {:platform-credential test.common/gcm-api-key} :name "the-best-application" :platform :GCM})) (def gcm-token "PI:KEY:<KEY>END_PI") (defn create-platform-endpoint! [creds arn] (sns! creds :create-platform-endpoint {:platform-application-arn arn :token gcm-token})) (deftest ^:integration ^:aws create-platform-application (test.common/with-aws (fn [creds] (go-catching (is (= "arn:" (some-> (create-gcm-application! creds) <? (subs 0 4)))))))) ;; This is failing on Travis, but not locally - investigate. ;; (deftest ^:integration ^:aws set-platform-application-attributes ;; (test.common/with-aws ;; (fn [creds] ;; (go-catching ;; (let [arn (<? (create-gcm-application! creds))] ;; (<? (sns! creds ;; :set-platform-application-attributes ;; {:platform-application-arn arn ;; :attrs {:success-feedback-sample-rate 50}})) ;; (is (:success-feedback-sample-rate ;; (<? (sns! creds ;; :get-platform-application-attributes ;; {:platform-application-arn arn}))))))))) (deftest ^:integration ^:aws delete-platform-application+ (test.common/with-aws (fn [creds] (go-catching (let [arn (<? (create-gcm-application! creds))] (is (<? (sns! creds :delete-platform-application {:platform-application-arn arn})))))))) (defn create-platform-application! [creds name] (sns! creds :create-platform-application {:platform :GCM :name name :attrs {:platform-credential test.common/gcm-api-key}})) (defn with-transient-app! [f] (test.common/with-aws (fn [creds] (go-catching (let [arn (<? (create-platform-application! creds (str "eulalie-transient-" (rand-int 0xFFFF))))] (try (<? (f creds arn)) (finally (<? (sns! creds :delete-platform-application {:platform-application-arn arn}))))))))) (deftest ^:integration ^:aws publish (test.common/with-aws (fn [creds] (go-catching (is (-> (sns! creds :publish {:topic-arn (<? (create-topic! creds)) :subject "Hello" :message {:default "OK" :GCM {:data {:message "This is the GCM"}}} :attrs {:name [:string "OK"]}}) <? string?)))))) (deftest ^:integration ^:aws get-topic-attributes (test.common/with-aws (fn [creds] (go-catching (let [arn (<? (create-topic! creds))] (is (map? (:policy (<? (sns! creds :get-topic-attributes {:topic-arn arn})))))))))) (deftest ^:integration ^:aws get-endpoint-attributes (with-transient-app! (fn [creds p-arn] (go-catching (let [e-arn (<? (create-platform-endpoint! creds p-arn))] (is (= gcm-token (:token (<? (sns! creds :get-endpoint-attributes {:endpoint-arn e-arn})))))))))) (deftest ^:integration ^:aws list-endpoints-by-platform-application (with-transient-app! (fn [creds p-arn] (go-catching (let [e-arn (<? (create-platform-endpoint! creds p-arn)) arns (->> (sns! creds :list-endpoints-by-platform-application {:platform-application-arn p-arn}) <? (map :arn) (into #{}))] (is (arns e-arn)))))))
[ { "context": "n.company.com/.*\\\" {:username \\\"abc\\\" :password \\\"xyz\\\"}}\n\n would be applied to all repositories with ", "end": 3853, "score": 0.6737359166145325, "start": 3850, "tag": "PASSWORD", "value": "xyz" }, { "context": " :port (.getPort url)\n :username username\n :password password\n :non-proxy", "end": 4795, "score": 0.9977993965148926, "start": 4787, "tag": "USERNAME", "value": "username" }, { "context": ")\n :username username\n :password password\n :non-proxy-hosts (get-non-proxy-hosts)}", "end": 4824, "score": 0.9966044425964355, "start": 4816, "tag": "PASSWORD", "value": "password" }, { "context": " (println \"If so see https://github.com/ato/clojars-web/wiki/Releases.\")))\n (throw (e", "end": 7954, "score": 0.9515640735626221, "start": 7951, "tag": "USERNAME", "value": "ato" } ]
test/conflicts/mined/leiningen-74b0dc5b660434a54c64e161f7d4396087af3763-092ccd7b37288e306aab0563bc69bbb1a10e525/O.clj
nazrhom/vcs-clojure
3
(ns leiningen.core.classpath "Calculate project classpaths by resolving dependencies via Aether." (:require [cemerick.pomegranate.aether :as aether] [cemerick.pomegranate :as pomegranate] [clojure.java.io :as io] [clojure.string :as str] [leiningen.core.user :as user] [leiningen.core.utils :as utils] [pedantic.core :as pedantic]) (:import (java.util.jar JarFile) (org.sonatype.aether.graph Exclusion) (org.sonatype.aether.resolution DependencyResolutionException))) ;; Basically just for re-throwing a more comprehensible error. (defn- read-dependency-project [root dep] (let [project-file (io/file root "checkouts" dep "project.clj")] (if (.exists project-file) (let [project (.getAbsolutePath project-file)] ;; TODO 3.0: core.project and core.classpath currently rely upon each other *uk* (require 'leiningen.core.project) (try ((resolve 'leiningen.core.project/read) project [:default]) (catch Exception e (throw (Exception. (format "Problem loading %s" project) e))))) (println "WARN ignoring checkouts directory" dep "as it does not contain a project.clj file.")))) (alter-var-root #'read-dependency-project memoize) (defn- checkout-dep-paths [project dep-project] ;; can't mapcat here since :checkout-deps-shares points to vectors and strings (flatten (map #(% dep-project) (:checkout-deps-shares project)))) (defn ^:internal checkout-deps-paths "Checkout dependencies are used to place source for a dependency project directly on the classpath rather than having to install the dependency and restart the dependent project." [project] (apply concat (for [dep (.list (io/file (:root project) "checkouts")) :let [dep-project (read-dependency-project (:root project) dep)] :when dep-project] (checkout-dep-paths project dep-project)))) (defn extract-native-deps [files native-path native-prefixes] (doseq [file files :let [native-prefix (get native-prefixes file "native/") jar (JarFile. file)] entry (enumeration-seq (.entries jar)) :when (.startsWith (.getName entry) native-prefix)] (let [f (io/file native-path (subs (.getName entry) (count native-prefix)))] (if (.isDirectory entry) (.mkdirs f) (do (.mkdirs (.getParentFile f)) (io/copy (.getInputStream jar entry) f)))))) (defn when-stale "Call f with args when keys in project.clj have changed since the last run. Stores value of project keys in stale directory inside :target-path. Because multiple callers may check the same keys, you must also provide a token to keep your stale value separate. Returns true if the code was executed and nil otherwise." [token keys project f & args] (let [file (io/file (:target-path project) "stale" (str (name token) "." (str/join "+" (map name keys)))) current-value (pr-str (map (juxt identity project) keys)) old-value (and (.exists file) (slurp file))] (when (and (:name project) (:target-path project) (not= current-value old-value)) (apply f args) (.mkdirs (.getParentFile file)) (spit file (doall current-value)) true))) (defn add-repo-auth "Repository credentials (a map containing some of #{:username :password :passphrase :private-key-file}) are discovered from: 1. Looking up the repository URL in the ~/.lein/credentials.clj.gpg map 2. Scanning that map for regular expression keys that match the repository URL. So, a credentials map that contains an entry: {#\"http://maven.company.com/.*\" {:username \"abc\" :password \"xyz\"}} would be applied to all repositories with URLs matching the regex key that didn't have an explicit entry." [[id repo]] [id (-> repo user/profile-auth user/resolve-credentials)]) (defn get-non-proxy-hosts [] (let [system-no-proxy (System/getenv "no_proxy") lein-no-proxy (System/getenv "http_no_proxy")] (if (and (empty? lein-no-proxy) (not-empty system-no-proxy)) (->> (str/split system-no-proxy #",") (map #(str "*" %)) (str/join "|")) (System/getenv "http_no_proxy")))) (defn get-proxy-settings "Returns a map of the JVM proxy settings" ([] (get-proxy-settings "http_proxy")) ([key] (if-let [proxy (System/getenv key)] (let [url (utils/build-url proxy) user-info (.getUserInfo url) [username password] (and user-info (.split user-info ":"))] {:host (.getHost url) :port (.getPort url) :username username :password password :non-proxy-hosts (get-non-proxy-hosts)})))) (defn- update-policies [update checksum [repo-name opts]] [repo-name (merge {:update (or update :daily) :checksum (or checksum :fail)} opts)]) (defn- print-failures [e] (doseq [result (.getArtifactResults (.getResult e)) :when (not (.isResolved result)) exception (.getExceptions result)] (println (.getMessage exception))) (doseq [ex (.getCollectExceptions (.getResult e)) ex2 (.getExceptions (.getResult ex))] (println (.getMessage ex2)))) (defn- root-cause [e] (last (take-while identity (iterate (memfn getCause) e)))) (def ^:private get-dependencies-memoized (memoize (fn [dependencies-key {:keys [repositories local-repo offline? update checksum mirrors] :as project} {:keys [add-classpath? repository-session-fn] :as args}] {:pre [(every? vector? (get project dependencies-key))]} (try ((if add-classpath? pomegranate/add-dependencies aether/resolve-dependencies) :repository-session-fn repository-session-fn :local-repo local-repo :offline? offline? :repositories (->> repositories (map add-repo-auth) (map (partial update-policies update checksum))) :coordinates (get project dependencies-key) :mirrors (->> mirrors (map add-repo-auth) (map (partial update-policies update checksum))) :transfer-listener (bound-fn [e] (let [{:keys [type resource error]} e] (let [{:keys [repository name size trace]} resource] (let [aether-repos (if trace (.getRepositories (.getData trace)))] (case type :started (if-let [repo (first (filter #(or (= (.getUrl %) repository) ;; sometimes the "base" url ;; doesn't have a slash on it (= (str (.getUrl %) "/") repository)) aether-repos))] (locking *out* (println "Retrieving" name "from" (.getId repo))) ;; else case happens for metadata files ) nil))))) :proxy (get-proxy-settings)) (catch DependencyResolutionException e (binding [*out* *err*] ;; Cannot recur from catch/finally so have to put this in its own defn (print-failures e) (println "This could be due to a typo in :dependencies or network issues.") (println "If you are behind a proxy, try setting the 'http_proxy' environment variable.") #_(when-not (some #(= "https://clojars.org/repo/" (:url (second %))) repositories) (println "It's possible the specified jar is in the old Clojars Classic repo.") (println "If so see https://github.com/ato/clojars-web/wiki/Releases."))) (throw (ex-info "Could not resolve dependencies" {:suppress-msg true :exit-code 1} e))) (catch Exception e (if (and (instance? java.net.UnknownHostException (root-cause e)) (not offline?)) (get-dependencies-memoized dependencies-key (assoc project :offline? true)) (throw e))))))) (defn- group-artifact [artifact] (if (= (.getGroupId artifact) (.getArtifactId artifact)) (.getGroupId artifact) (str (.getGroupId artifact) "/" (.getArtifactId artifact)))) (defn- dependency-str [dependency & [version]] (if-let [artifact (and dependency (.getArtifact dependency))] (str "[" (group-artifact artifact) " \"" (or version (.getVersion artifact)) "\"" (if-let [classifier (.getClassifier artifact)] (if (not (empty? classifier)) (str " :classifier \"" classifier "\""))) (if-let [extension (.getExtension artifact)] (if (not= extension "jar") (str " :extension \"" extension "\""))) (if-let [exclusions (seq (.getExclusions dependency))] (str " :exclusions " (mapv (comp symbol group-artifact) exclusions))) "]"))) (defn- message-for [path & [show-constraint?]] (->> path (map #(dependency-str (.getDependency %) (.getVersionConstraint %))) (remove nil?) (interpose " -> ") (apply str))) (defn- message-for-version [{:keys [node parents]}] (message-for (conj parents node))) (defn- exclusion-for-range [node parents] (let [top-level (second parents) excluded-artifact (.getArtifact (.getDependency node)) exclusion (Exclusion. (.getGroupId excluded-artifact) (.getArtifactId excluded-artifact) "*" "*") exclusion-set (into #{exclusion} (.getExclusions (.getDependency top-level))) with-exclusion (.setExclusions (.getDependency top-level) exclusion-set)] (dependency-str with-exclusion))) (defn- message-for-range [{:keys [node parents]}] (str (message-for (conj parents node) :constraints) "\n" "Consider using " (exclusion-for-range node parents) ".")) (defn- exclusion-for-override [{:keys [node parents]}] (exclusion-for-range node parents)) (defn- message-for-override [{:keys [accepted ignoreds ranges]}] {:accepted (message-for-version accepted) :ignoreds (map message-for-version ignoreds) :ranges (map message-for-range ranges) :exclusions (map exclusion-for-override ignoreds)}) (defn- pedantic-print-ranges [messages] (when-not (empty? messages) (println "WARNING!!! version ranges found for:") (doseq [dep-string messages] (println dep-string)) (println))) (defn- pedantic-print-overrides [messages] (when-not (empty? messages) (println "Possibly confusing dependencies found:") (doseq [{:keys [accepted ignoreds ranges exclusions]} messages] (println accepted) (println " overrides") (doseq [ignored (interpose " and" ignoreds)] (println ignored)) (when-not (empty? ranges) (println " possibly due to a version range in") (doseq [r ranges] (println r))) (println "\nConsider using these exclusions:") (doseq [ex exclusions] (println ex)) (println)))) (alter-var-root #'pedantic-print-ranges memoize) (alter-var-root #'pedantic-print-overrides memoize) (defn- pedantic-do [pedantic-setting ranges overrides] (when pedantic-setting ;; Need to turn everything into a string before calling ;; pedantic-print-*, otherwise we can't memoize due to bad equality ;; semantics on aether GraphEdge objects. (pedantic-print-ranges (distinct (map message-for-range ranges))) (pedantic-print-overrides (map message-for-override overrides)) (when (and (= :abort pedantic-setting) (not (empty? (concat ranges overrides)))) (require 'leiningen.core.main) ((resolve 'leiningen.core.main/abort) ; cyclic dependency =\ "Aborting due to version ranges.")))) (defn- pedantic-session [project ranges overrides] (if (:pedantic? project) #(-> % aether/repository-session (pedantic/use-transformer ranges overrides)))) ;; Exclusion(groupId, artifactId, classifier, extension) (defn ^:internal get-dependencies [dependencies-key project & args] (let [ranges (atom []), overrides (atom []) session (pedantic-session project ranges overrides) args (assoc (apply hash-map args) :repository-session-fn session) trimmed (select-keys project [dependencies-key :repositories :checksum :local-repo :offline? :update :mirrors]) deps-result (get-dependencies-memoized dependencies-key trimmed args)] (pedantic-do (:pedantic? project) @ranges @overrides) deps-result)) (defn- get-original-dependency "Return a match to dep (a single dependency vector) in dependencies (a dependencies vector, such as :dependencies in project.clj). Matching is done on the basis of the group/artifact id and version." [dep dependencies] (some (fn [v] ; not certain if this is the best matching fn (when (= (subvec dep 0 2) (subvec v 0 2 )) v)) dependencies)) (defn get-native-prefix "Return the :native-prefix of a dependency vector, or nil." [[id version & {:as opts}]] (get opts :native-prefix)) (defn- get-native-prefixes "Given a dependencies vector (such as :dependencies in project.clj) and a dependencies tree, as returned by get-dependencies, return a mapping from the Files those dependencies entail to the :native-prefix, if any, referenced in the dependencies vector." [dependencies dependencies-tree] (let [override-deps (->> (map #(get-original-dependency % dependencies) (keys dependencies-tree)) (map get-native-prefix))] (->> (aether/dependency-files dependencies-tree) (#(map vector % override-deps)) (filter second) (filter #(re-find #"\.(jar|zip)$" (.getName (first %)))) (into {})))) (defn resolve-dependencies "Delegate dependencies to pomegranate. This will ensure they are downloaded into ~/.m2/repository and that native components of dependencies have been extracted to :native-path. If :add-classpath? is logically true, will add the resolved dependencies to Leiningen's classpath. Returns a seq of the dependencies' files." [dependencies-key {:keys [repositories native-path] :as project} & rest] (let [dependencies-tree (apply get-dependencies dependencies-key project rest) jars (->> dependencies-tree (aether/dependency-files) (filter #(re-find #"\.(jar|zip)$" (.getName %)))) native-prefixes (get-native-prefixes (get project dependencies-key) dependencies-tree)] (when-not (= :plugins dependencies-key) (or (when-stale :extract-native [dependencies-key] project extract-native-deps jars native-path native-prefixes) ;; Always extract native deps from SNAPSHOT jars. (extract-native-deps (filter #(re-find #"SNAPSHOT" (.getName %)) jars) native-path native-prefixes))) jars)) (defn dependency-hierarchy "Returns a graph of the project's dependencies." [dependencies-key project & options] (if-let [deps-list (get project dependencies-key)] (aether/dependency-hierarchy deps-list (apply get-dependencies dependencies-key project options)))) (defn- normalize-path [root path] (let [f (io/file path) ; http://tinyurl.com/ab5vtqf abs (.getAbsolutePath (if (or (.isAbsolute f) (.startsWith (.getPath f) "\\")) f (io/file root path))) sep (System/getProperty "path.separator")] (str/replace abs sep (str "\\" sep)))) (defn ext-dependency? "Should the given dependency be loaded in the extensions classloader?" [dep] (second (some #(if (= :ext (first %)) dep) (partition 2 dep)))) (defn ext-classpath "Classpath of the extensions dependencies in project as a list of strings." [project] (seq (->> (filter ext-dependency? (:dependencies project)) (assoc project :dependencies) (resolve-dependencies :dependencies) (map (memfn getAbsolutePath))))) (defn get-classpath "Return the classpath for project as a list of strings." [project] (for [path (concat (:test-paths project) (:source-paths project) (:resource-paths project) [(:compile-path project)] (checkout-deps-paths project) (for [dep (resolve-dependencies :dependencies project)] (.getAbsolutePath dep))) :when path] (normalize-path (:root project) path)))
109103
(ns leiningen.core.classpath "Calculate project classpaths by resolving dependencies via Aether." (:require [cemerick.pomegranate.aether :as aether] [cemerick.pomegranate :as pomegranate] [clojure.java.io :as io] [clojure.string :as str] [leiningen.core.user :as user] [leiningen.core.utils :as utils] [pedantic.core :as pedantic]) (:import (java.util.jar JarFile) (org.sonatype.aether.graph Exclusion) (org.sonatype.aether.resolution DependencyResolutionException))) ;; Basically just for re-throwing a more comprehensible error. (defn- read-dependency-project [root dep] (let [project-file (io/file root "checkouts" dep "project.clj")] (if (.exists project-file) (let [project (.getAbsolutePath project-file)] ;; TODO 3.0: core.project and core.classpath currently rely upon each other *uk* (require 'leiningen.core.project) (try ((resolve 'leiningen.core.project/read) project [:default]) (catch Exception e (throw (Exception. (format "Problem loading %s" project) e))))) (println "WARN ignoring checkouts directory" dep "as it does not contain a project.clj file.")))) (alter-var-root #'read-dependency-project memoize) (defn- checkout-dep-paths [project dep-project] ;; can't mapcat here since :checkout-deps-shares points to vectors and strings (flatten (map #(% dep-project) (:checkout-deps-shares project)))) (defn ^:internal checkout-deps-paths "Checkout dependencies are used to place source for a dependency project directly on the classpath rather than having to install the dependency and restart the dependent project." [project] (apply concat (for [dep (.list (io/file (:root project) "checkouts")) :let [dep-project (read-dependency-project (:root project) dep)] :when dep-project] (checkout-dep-paths project dep-project)))) (defn extract-native-deps [files native-path native-prefixes] (doseq [file files :let [native-prefix (get native-prefixes file "native/") jar (JarFile. file)] entry (enumeration-seq (.entries jar)) :when (.startsWith (.getName entry) native-prefix)] (let [f (io/file native-path (subs (.getName entry) (count native-prefix)))] (if (.isDirectory entry) (.mkdirs f) (do (.mkdirs (.getParentFile f)) (io/copy (.getInputStream jar entry) f)))))) (defn when-stale "Call f with args when keys in project.clj have changed since the last run. Stores value of project keys in stale directory inside :target-path. Because multiple callers may check the same keys, you must also provide a token to keep your stale value separate. Returns true if the code was executed and nil otherwise." [token keys project f & args] (let [file (io/file (:target-path project) "stale" (str (name token) "." (str/join "+" (map name keys)))) current-value (pr-str (map (juxt identity project) keys)) old-value (and (.exists file) (slurp file))] (when (and (:name project) (:target-path project) (not= current-value old-value)) (apply f args) (.mkdirs (.getParentFile file)) (spit file (doall current-value)) true))) (defn add-repo-auth "Repository credentials (a map containing some of #{:username :password :passphrase :private-key-file}) are discovered from: 1. Looking up the repository URL in the ~/.lein/credentials.clj.gpg map 2. Scanning that map for regular expression keys that match the repository URL. So, a credentials map that contains an entry: {#\"http://maven.company.com/.*\" {:username \"abc\" :password \"<PASSWORD>\"}} would be applied to all repositories with URLs matching the regex key that didn't have an explicit entry." [[id repo]] [id (-> repo user/profile-auth user/resolve-credentials)]) (defn get-non-proxy-hosts [] (let [system-no-proxy (System/getenv "no_proxy") lein-no-proxy (System/getenv "http_no_proxy")] (if (and (empty? lein-no-proxy) (not-empty system-no-proxy)) (->> (str/split system-no-proxy #",") (map #(str "*" %)) (str/join "|")) (System/getenv "http_no_proxy")))) (defn get-proxy-settings "Returns a map of the JVM proxy settings" ([] (get-proxy-settings "http_proxy")) ([key] (if-let [proxy (System/getenv key)] (let [url (utils/build-url proxy) user-info (.getUserInfo url) [username password] (and user-info (.split user-info ":"))] {:host (.getHost url) :port (.getPort url) :username username :password <PASSWORD> :non-proxy-hosts (get-non-proxy-hosts)})))) (defn- update-policies [update checksum [repo-name opts]] [repo-name (merge {:update (or update :daily) :checksum (or checksum :fail)} opts)]) (defn- print-failures [e] (doseq [result (.getArtifactResults (.getResult e)) :when (not (.isResolved result)) exception (.getExceptions result)] (println (.getMessage exception))) (doseq [ex (.getCollectExceptions (.getResult e)) ex2 (.getExceptions (.getResult ex))] (println (.getMessage ex2)))) (defn- root-cause [e] (last (take-while identity (iterate (memfn getCause) e)))) (def ^:private get-dependencies-memoized (memoize (fn [dependencies-key {:keys [repositories local-repo offline? update checksum mirrors] :as project} {:keys [add-classpath? repository-session-fn] :as args}] {:pre [(every? vector? (get project dependencies-key))]} (try ((if add-classpath? pomegranate/add-dependencies aether/resolve-dependencies) :repository-session-fn repository-session-fn :local-repo local-repo :offline? offline? :repositories (->> repositories (map add-repo-auth) (map (partial update-policies update checksum))) :coordinates (get project dependencies-key) :mirrors (->> mirrors (map add-repo-auth) (map (partial update-policies update checksum))) :transfer-listener (bound-fn [e] (let [{:keys [type resource error]} e] (let [{:keys [repository name size trace]} resource] (let [aether-repos (if trace (.getRepositories (.getData trace)))] (case type :started (if-let [repo (first (filter #(or (= (.getUrl %) repository) ;; sometimes the "base" url ;; doesn't have a slash on it (= (str (.getUrl %) "/") repository)) aether-repos))] (locking *out* (println "Retrieving" name "from" (.getId repo))) ;; else case happens for metadata files ) nil))))) :proxy (get-proxy-settings)) (catch DependencyResolutionException e (binding [*out* *err*] ;; Cannot recur from catch/finally so have to put this in its own defn (print-failures e) (println "This could be due to a typo in :dependencies or network issues.") (println "If you are behind a proxy, try setting the 'http_proxy' environment variable.") #_(when-not (some #(= "https://clojars.org/repo/" (:url (second %))) repositories) (println "It's possible the specified jar is in the old Clojars Classic repo.") (println "If so see https://github.com/ato/clojars-web/wiki/Releases."))) (throw (ex-info "Could not resolve dependencies" {:suppress-msg true :exit-code 1} e))) (catch Exception e (if (and (instance? java.net.UnknownHostException (root-cause e)) (not offline?)) (get-dependencies-memoized dependencies-key (assoc project :offline? true)) (throw e))))))) (defn- group-artifact [artifact] (if (= (.getGroupId artifact) (.getArtifactId artifact)) (.getGroupId artifact) (str (.getGroupId artifact) "/" (.getArtifactId artifact)))) (defn- dependency-str [dependency & [version]] (if-let [artifact (and dependency (.getArtifact dependency))] (str "[" (group-artifact artifact) " \"" (or version (.getVersion artifact)) "\"" (if-let [classifier (.getClassifier artifact)] (if (not (empty? classifier)) (str " :classifier \"" classifier "\""))) (if-let [extension (.getExtension artifact)] (if (not= extension "jar") (str " :extension \"" extension "\""))) (if-let [exclusions (seq (.getExclusions dependency))] (str " :exclusions " (mapv (comp symbol group-artifact) exclusions))) "]"))) (defn- message-for [path & [show-constraint?]] (->> path (map #(dependency-str (.getDependency %) (.getVersionConstraint %))) (remove nil?) (interpose " -> ") (apply str))) (defn- message-for-version [{:keys [node parents]}] (message-for (conj parents node))) (defn- exclusion-for-range [node parents] (let [top-level (second parents) excluded-artifact (.getArtifact (.getDependency node)) exclusion (Exclusion. (.getGroupId excluded-artifact) (.getArtifactId excluded-artifact) "*" "*") exclusion-set (into #{exclusion} (.getExclusions (.getDependency top-level))) with-exclusion (.setExclusions (.getDependency top-level) exclusion-set)] (dependency-str with-exclusion))) (defn- message-for-range [{:keys [node parents]}] (str (message-for (conj parents node) :constraints) "\n" "Consider using " (exclusion-for-range node parents) ".")) (defn- exclusion-for-override [{:keys [node parents]}] (exclusion-for-range node parents)) (defn- message-for-override [{:keys [accepted ignoreds ranges]}] {:accepted (message-for-version accepted) :ignoreds (map message-for-version ignoreds) :ranges (map message-for-range ranges) :exclusions (map exclusion-for-override ignoreds)}) (defn- pedantic-print-ranges [messages] (when-not (empty? messages) (println "WARNING!!! version ranges found for:") (doseq [dep-string messages] (println dep-string)) (println))) (defn- pedantic-print-overrides [messages] (when-not (empty? messages) (println "Possibly confusing dependencies found:") (doseq [{:keys [accepted ignoreds ranges exclusions]} messages] (println accepted) (println " overrides") (doseq [ignored (interpose " and" ignoreds)] (println ignored)) (when-not (empty? ranges) (println " possibly due to a version range in") (doseq [r ranges] (println r))) (println "\nConsider using these exclusions:") (doseq [ex exclusions] (println ex)) (println)))) (alter-var-root #'pedantic-print-ranges memoize) (alter-var-root #'pedantic-print-overrides memoize) (defn- pedantic-do [pedantic-setting ranges overrides] (when pedantic-setting ;; Need to turn everything into a string before calling ;; pedantic-print-*, otherwise we can't memoize due to bad equality ;; semantics on aether GraphEdge objects. (pedantic-print-ranges (distinct (map message-for-range ranges))) (pedantic-print-overrides (map message-for-override overrides)) (when (and (= :abort pedantic-setting) (not (empty? (concat ranges overrides)))) (require 'leiningen.core.main) ((resolve 'leiningen.core.main/abort) ; cyclic dependency =\ "Aborting due to version ranges.")))) (defn- pedantic-session [project ranges overrides] (if (:pedantic? project) #(-> % aether/repository-session (pedantic/use-transformer ranges overrides)))) ;; Exclusion(groupId, artifactId, classifier, extension) (defn ^:internal get-dependencies [dependencies-key project & args] (let [ranges (atom []), overrides (atom []) session (pedantic-session project ranges overrides) args (assoc (apply hash-map args) :repository-session-fn session) trimmed (select-keys project [dependencies-key :repositories :checksum :local-repo :offline? :update :mirrors]) deps-result (get-dependencies-memoized dependencies-key trimmed args)] (pedantic-do (:pedantic? project) @ranges @overrides) deps-result)) (defn- get-original-dependency "Return a match to dep (a single dependency vector) in dependencies (a dependencies vector, such as :dependencies in project.clj). Matching is done on the basis of the group/artifact id and version." [dep dependencies] (some (fn [v] ; not certain if this is the best matching fn (when (= (subvec dep 0 2) (subvec v 0 2 )) v)) dependencies)) (defn get-native-prefix "Return the :native-prefix of a dependency vector, or nil." [[id version & {:as opts}]] (get opts :native-prefix)) (defn- get-native-prefixes "Given a dependencies vector (such as :dependencies in project.clj) and a dependencies tree, as returned by get-dependencies, return a mapping from the Files those dependencies entail to the :native-prefix, if any, referenced in the dependencies vector." [dependencies dependencies-tree] (let [override-deps (->> (map #(get-original-dependency % dependencies) (keys dependencies-tree)) (map get-native-prefix))] (->> (aether/dependency-files dependencies-tree) (#(map vector % override-deps)) (filter second) (filter #(re-find #"\.(jar|zip)$" (.getName (first %)))) (into {})))) (defn resolve-dependencies "Delegate dependencies to pomegranate. This will ensure they are downloaded into ~/.m2/repository and that native components of dependencies have been extracted to :native-path. If :add-classpath? is logically true, will add the resolved dependencies to Leiningen's classpath. Returns a seq of the dependencies' files." [dependencies-key {:keys [repositories native-path] :as project} & rest] (let [dependencies-tree (apply get-dependencies dependencies-key project rest) jars (->> dependencies-tree (aether/dependency-files) (filter #(re-find #"\.(jar|zip)$" (.getName %)))) native-prefixes (get-native-prefixes (get project dependencies-key) dependencies-tree)] (when-not (= :plugins dependencies-key) (or (when-stale :extract-native [dependencies-key] project extract-native-deps jars native-path native-prefixes) ;; Always extract native deps from SNAPSHOT jars. (extract-native-deps (filter #(re-find #"SNAPSHOT" (.getName %)) jars) native-path native-prefixes))) jars)) (defn dependency-hierarchy "Returns a graph of the project's dependencies." [dependencies-key project & options] (if-let [deps-list (get project dependencies-key)] (aether/dependency-hierarchy deps-list (apply get-dependencies dependencies-key project options)))) (defn- normalize-path [root path] (let [f (io/file path) ; http://tinyurl.com/ab5vtqf abs (.getAbsolutePath (if (or (.isAbsolute f) (.startsWith (.getPath f) "\\")) f (io/file root path))) sep (System/getProperty "path.separator")] (str/replace abs sep (str "\\" sep)))) (defn ext-dependency? "Should the given dependency be loaded in the extensions classloader?" [dep] (second (some #(if (= :ext (first %)) dep) (partition 2 dep)))) (defn ext-classpath "Classpath of the extensions dependencies in project as a list of strings." [project] (seq (->> (filter ext-dependency? (:dependencies project)) (assoc project :dependencies) (resolve-dependencies :dependencies) (map (memfn getAbsolutePath))))) (defn get-classpath "Return the classpath for project as a list of strings." [project] (for [path (concat (:test-paths project) (:source-paths project) (:resource-paths project) [(:compile-path project)] (checkout-deps-paths project) (for [dep (resolve-dependencies :dependencies project)] (.getAbsolutePath dep))) :when path] (normalize-path (:root project) path)))
true
(ns leiningen.core.classpath "Calculate project classpaths by resolving dependencies via Aether." (:require [cemerick.pomegranate.aether :as aether] [cemerick.pomegranate :as pomegranate] [clojure.java.io :as io] [clojure.string :as str] [leiningen.core.user :as user] [leiningen.core.utils :as utils] [pedantic.core :as pedantic]) (:import (java.util.jar JarFile) (org.sonatype.aether.graph Exclusion) (org.sonatype.aether.resolution DependencyResolutionException))) ;; Basically just for re-throwing a more comprehensible error. (defn- read-dependency-project [root dep] (let [project-file (io/file root "checkouts" dep "project.clj")] (if (.exists project-file) (let [project (.getAbsolutePath project-file)] ;; TODO 3.0: core.project and core.classpath currently rely upon each other *uk* (require 'leiningen.core.project) (try ((resolve 'leiningen.core.project/read) project [:default]) (catch Exception e (throw (Exception. (format "Problem loading %s" project) e))))) (println "WARN ignoring checkouts directory" dep "as it does not contain a project.clj file.")))) (alter-var-root #'read-dependency-project memoize) (defn- checkout-dep-paths [project dep-project] ;; can't mapcat here since :checkout-deps-shares points to vectors and strings (flatten (map #(% dep-project) (:checkout-deps-shares project)))) (defn ^:internal checkout-deps-paths "Checkout dependencies are used to place source for a dependency project directly on the classpath rather than having to install the dependency and restart the dependent project." [project] (apply concat (for [dep (.list (io/file (:root project) "checkouts")) :let [dep-project (read-dependency-project (:root project) dep)] :when dep-project] (checkout-dep-paths project dep-project)))) (defn extract-native-deps [files native-path native-prefixes] (doseq [file files :let [native-prefix (get native-prefixes file "native/") jar (JarFile. file)] entry (enumeration-seq (.entries jar)) :when (.startsWith (.getName entry) native-prefix)] (let [f (io/file native-path (subs (.getName entry) (count native-prefix)))] (if (.isDirectory entry) (.mkdirs f) (do (.mkdirs (.getParentFile f)) (io/copy (.getInputStream jar entry) f)))))) (defn when-stale "Call f with args when keys in project.clj have changed since the last run. Stores value of project keys in stale directory inside :target-path. Because multiple callers may check the same keys, you must also provide a token to keep your stale value separate. Returns true if the code was executed and nil otherwise." [token keys project f & args] (let [file (io/file (:target-path project) "stale" (str (name token) "." (str/join "+" (map name keys)))) current-value (pr-str (map (juxt identity project) keys)) old-value (and (.exists file) (slurp file))] (when (and (:name project) (:target-path project) (not= current-value old-value)) (apply f args) (.mkdirs (.getParentFile file)) (spit file (doall current-value)) true))) (defn add-repo-auth "Repository credentials (a map containing some of #{:username :password :passphrase :private-key-file}) are discovered from: 1. Looking up the repository URL in the ~/.lein/credentials.clj.gpg map 2. Scanning that map for regular expression keys that match the repository URL. So, a credentials map that contains an entry: {#\"http://maven.company.com/.*\" {:username \"abc\" :password \"PI:PASSWORD:<PASSWORD>END_PI\"}} would be applied to all repositories with URLs matching the regex key that didn't have an explicit entry." [[id repo]] [id (-> repo user/profile-auth user/resolve-credentials)]) (defn get-non-proxy-hosts [] (let [system-no-proxy (System/getenv "no_proxy") lein-no-proxy (System/getenv "http_no_proxy")] (if (and (empty? lein-no-proxy) (not-empty system-no-proxy)) (->> (str/split system-no-proxy #",") (map #(str "*" %)) (str/join "|")) (System/getenv "http_no_proxy")))) (defn get-proxy-settings "Returns a map of the JVM proxy settings" ([] (get-proxy-settings "http_proxy")) ([key] (if-let [proxy (System/getenv key)] (let [url (utils/build-url proxy) user-info (.getUserInfo url) [username password] (and user-info (.split user-info ":"))] {:host (.getHost url) :port (.getPort url) :username username :password PI:PASSWORD:<PASSWORD>END_PI :non-proxy-hosts (get-non-proxy-hosts)})))) (defn- update-policies [update checksum [repo-name opts]] [repo-name (merge {:update (or update :daily) :checksum (or checksum :fail)} opts)]) (defn- print-failures [e] (doseq [result (.getArtifactResults (.getResult e)) :when (not (.isResolved result)) exception (.getExceptions result)] (println (.getMessage exception))) (doseq [ex (.getCollectExceptions (.getResult e)) ex2 (.getExceptions (.getResult ex))] (println (.getMessage ex2)))) (defn- root-cause [e] (last (take-while identity (iterate (memfn getCause) e)))) (def ^:private get-dependencies-memoized (memoize (fn [dependencies-key {:keys [repositories local-repo offline? update checksum mirrors] :as project} {:keys [add-classpath? repository-session-fn] :as args}] {:pre [(every? vector? (get project dependencies-key))]} (try ((if add-classpath? pomegranate/add-dependencies aether/resolve-dependencies) :repository-session-fn repository-session-fn :local-repo local-repo :offline? offline? :repositories (->> repositories (map add-repo-auth) (map (partial update-policies update checksum))) :coordinates (get project dependencies-key) :mirrors (->> mirrors (map add-repo-auth) (map (partial update-policies update checksum))) :transfer-listener (bound-fn [e] (let [{:keys [type resource error]} e] (let [{:keys [repository name size trace]} resource] (let [aether-repos (if trace (.getRepositories (.getData trace)))] (case type :started (if-let [repo (first (filter #(or (= (.getUrl %) repository) ;; sometimes the "base" url ;; doesn't have a slash on it (= (str (.getUrl %) "/") repository)) aether-repos))] (locking *out* (println "Retrieving" name "from" (.getId repo))) ;; else case happens for metadata files ) nil))))) :proxy (get-proxy-settings)) (catch DependencyResolutionException e (binding [*out* *err*] ;; Cannot recur from catch/finally so have to put this in its own defn (print-failures e) (println "This could be due to a typo in :dependencies or network issues.") (println "If you are behind a proxy, try setting the 'http_proxy' environment variable.") #_(when-not (some #(= "https://clojars.org/repo/" (:url (second %))) repositories) (println "It's possible the specified jar is in the old Clojars Classic repo.") (println "If so see https://github.com/ato/clojars-web/wiki/Releases."))) (throw (ex-info "Could not resolve dependencies" {:suppress-msg true :exit-code 1} e))) (catch Exception e (if (and (instance? java.net.UnknownHostException (root-cause e)) (not offline?)) (get-dependencies-memoized dependencies-key (assoc project :offline? true)) (throw e))))))) (defn- group-artifact [artifact] (if (= (.getGroupId artifact) (.getArtifactId artifact)) (.getGroupId artifact) (str (.getGroupId artifact) "/" (.getArtifactId artifact)))) (defn- dependency-str [dependency & [version]] (if-let [artifact (and dependency (.getArtifact dependency))] (str "[" (group-artifact artifact) " \"" (or version (.getVersion artifact)) "\"" (if-let [classifier (.getClassifier artifact)] (if (not (empty? classifier)) (str " :classifier \"" classifier "\""))) (if-let [extension (.getExtension artifact)] (if (not= extension "jar") (str " :extension \"" extension "\""))) (if-let [exclusions (seq (.getExclusions dependency))] (str " :exclusions " (mapv (comp symbol group-artifact) exclusions))) "]"))) (defn- message-for [path & [show-constraint?]] (->> path (map #(dependency-str (.getDependency %) (.getVersionConstraint %))) (remove nil?) (interpose " -> ") (apply str))) (defn- message-for-version [{:keys [node parents]}] (message-for (conj parents node))) (defn- exclusion-for-range [node parents] (let [top-level (second parents) excluded-artifact (.getArtifact (.getDependency node)) exclusion (Exclusion. (.getGroupId excluded-artifact) (.getArtifactId excluded-artifact) "*" "*") exclusion-set (into #{exclusion} (.getExclusions (.getDependency top-level))) with-exclusion (.setExclusions (.getDependency top-level) exclusion-set)] (dependency-str with-exclusion))) (defn- message-for-range [{:keys [node parents]}] (str (message-for (conj parents node) :constraints) "\n" "Consider using " (exclusion-for-range node parents) ".")) (defn- exclusion-for-override [{:keys [node parents]}] (exclusion-for-range node parents)) (defn- message-for-override [{:keys [accepted ignoreds ranges]}] {:accepted (message-for-version accepted) :ignoreds (map message-for-version ignoreds) :ranges (map message-for-range ranges) :exclusions (map exclusion-for-override ignoreds)}) (defn- pedantic-print-ranges [messages] (when-not (empty? messages) (println "WARNING!!! version ranges found for:") (doseq [dep-string messages] (println dep-string)) (println))) (defn- pedantic-print-overrides [messages] (when-not (empty? messages) (println "Possibly confusing dependencies found:") (doseq [{:keys [accepted ignoreds ranges exclusions]} messages] (println accepted) (println " overrides") (doseq [ignored (interpose " and" ignoreds)] (println ignored)) (when-not (empty? ranges) (println " possibly due to a version range in") (doseq [r ranges] (println r))) (println "\nConsider using these exclusions:") (doseq [ex exclusions] (println ex)) (println)))) (alter-var-root #'pedantic-print-ranges memoize) (alter-var-root #'pedantic-print-overrides memoize) (defn- pedantic-do [pedantic-setting ranges overrides] (when pedantic-setting ;; Need to turn everything into a string before calling ;; pedantic-print-*, otherwise we can't memoize due to bad equality ;; semantics on aether GraphEdge objects. (pedantic-print-ranges (distinct (map message-for-range ranges))) (pedantic-print-overrides (map message-for-override overrides)) (when (and (= :abort pedantic-setting) (not (empty? (concat ranges overrides)))) (require 'leiningen.core.main) ((resolve 'leiningen.core.main/abort) ; cyclic dependency =\ "Aborting due to version ranges.")))) (defn- pedantic-session [project ranges overrides] (if (:pedantic? project) #(-> % aether/repository-session (pedantic/use-transformer ranges overrides)))) ;; Exclusion(groupId, artifactId, classifier, extension) (defn ^:internal get-dependencies [dependencies-key project & args] (let [ranges (atom []), overrides (atom []) session (pedantic-session project ranges overrides) args (assoc (apply hash-map args) :repository-session-fn session) trimmed (select-keys project [dependencies-key :repositories :checksum :local-repo :offline? :update :mirrors]) deps-result (get-dependencies-memoized dependencies-key trimmed args)] (pedantic-do (:pedantic? project) @ranges @overrides) deps-result)) (defn- get-original-dependency "Return a match to dep (a single dependency vector) in dependencies (a dependencies vector, such as :dependencies in project.clj). Matching is done on the basis of the group/artifact id and version." [dep dependencies] (some (fn [v] ; not certain if this is the best matching fn (when (= (subvec dep 0 2) (subvec v 0 2 )) v)) dependencies)) (defn get-native-prefix "Return the :native-prefix of a dependency vector, or nil." [[id version & {:as opts}]] (get opts :native-prefix)) (defn- get-native-prefixes "Given a dependencies vector (such as :dependencies in project.clj) and a dependencies tree, as returned by get-dependencies, return a mapping from the Files those dependencies entail to the :native-prefix, if any, referenced in the dependencies vector." [dependencies dependencies-tree] (let [override-deps (->> (map #(get-original-dependency % dependencies) (keys dependencies-tree)) (map get-native-prefix))] (->> (aether/dependency-files dependencies-tree) (#(map vector % override-deps)) (filter second) (filter #(re-find #"\.(jar|zip)$" (.getName (first %)))) (into {})))) (defn resolve-dependencies "Delegate dependencies to pomegranate. This will ensure they are downloaded into ~/.m2/repository and that native components of dependencies have been extracted to :native-path. If :add-classpath? is logically true, will add the resolved dependencies to Leiningen's classpath. Returns a seq of the dependencies' files." [dependencies-key {:keys [repositories native-path] :as project} & rest] (let [dependencies-tree (apply get-dependencies dependencies-key project rest) jars (->> dependencies-tree (aether/dependency-files) (filter #(re-find #"\.(jar|zip)$" (.getName %)))) native-prefixes (get-native-prefixes (get project dependencies-key) dependencies-tree)] (when-not (= :plugins dependencies-key) (or (when-stale :extract-native [dependencies-key] project extract-native-deps jars native-path native-prefixes) ;; Always extract native deps from SNAPSHOT jars. (extract-native-deps (filter #(re-find #"SNAPSHOT" (.getName %)) jars) native-path native-prefixes))) jars)) (defn dependency-hierarchy "Returns a graph of the project's dependencies." [dependencies-key project & options] (if-let [deps-list (get project dependencies-key)] (aether/dependency-hierarchy deps-list (apply get-dependencies dependencies-key project options)))) (defn- normalize-path [root path] (let [f (io/file path) ; http://tinyurl.com/ab5vtqf abs (.getAbsolutePath (if (or (.isAbsolute f) (.startsWith (.getPath f) "\\")) f (io/file root path))) sep (System/getProperty "path.separator")] (str/replace abs sep (str "\\" sep)))) (defn ext-dependency? "Should the given dependency be loaded in the extensions classloader?" [dep] (second (some #(if (= :ext (first %)) dep) (partition 2 dep)))) (defn ext-classpath "Classpath of the extensions dependencies in project as a list of strings." [project] (seq (->> (filter ext-dependency? (:dependencies project)) (assoc project :dependencies) (resolve-dependencies :dependencies) (map (memfn getAbsolutePath))))) (defn get-classpath "Return the classpath for project as a list of strings." [project] (for [path (concat (:test-paths project) (:source-paths project) (:resource-paths project) [(:compile-path project)] (checkout-deps-paths project) (for [dep (resolve-dependencies :dependencies project)] (.getAbsolutePath dep))) :when path] (normalize-path (:root project) path)))
[ { "context": "\"signing-key\"\n (it \"example\"\n (should=\n \"c4afb1cc5771d871763a393e44b703571b55cc28424d1a5e86da6ed3c154a4b9\"\n (let [secret-access-key \"wJalrXUtnFEMI/K7M", "end": 1036, "score": 0.9996761679649353, "start": 972, "tag": "KEY", "value": "c4afb1cc5771d871763a393e44b703571b55cc28424d1a5e86da6ed3c154a4b9" }, { "context": "e86da6ed3c154a4b9\"\n (let [secret-access-key \"wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY\"\n request-date (t/date-time 2015 8 ", "end": 1106, "score": 0.9997258186340332, "start": 1069, "tag": "KEY", "value": "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLE" }, { "context": "www-form-urlencoded\"\n (let [secret-access-key \"wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY\"\n request-date (t/date-time 2011 9 9 23 ", "end": 1462, "score": 0.9997649788856506, "start": 1422, "tag": "KEY", "value": "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY" }, { "context": "62f047318703b92e6f4f38884e4a7ab7b1d6426ca46a8bd1c26cbc\"\n (authorization \"AKIDEXAMPLE\"\n ", "end": 2198, "score": 0.9812644720077515, "start": 2194, "tag": "KEY", "value": "6cbc" }, { "context": "7ab7b1d6426ca46a8bd1c26cbc\"\n (authorization \"AKIDEXAMPLE\"\n \"wJalrXUtnFEMI/K7MDENG+bPxR", "end": 2233, "score": 0.9222511649131775, "start": 2222, "tag": "KEY", "value": "AKIDEXAMPLE" }, { "context": "authorization \"AKIDEXAMPLE\"\n \"wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY\"\n ", "end": 2270, "score": 0.8591817021369934, "start": 2257, "tag": "KEY", "value": "wJalrXUtnFEMI" }, { "context": "AKIDEXAMPLE\"\n \"wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY\"\n (t/da", "end": 2275, "score": 0.5963637828826904, "start": 2272, "tag": "KEY", "value": "7MD" }, { "context": "XAMPLE\"\n \"wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY\"\n (t/date-time 2011", "end": 2287, "score": 0.6392205953598022, "start": 2277, "tag": "KEY", "value": "G+bPxRfiCY" } ]
spec/http_kit_aws4/core_spec.clj
Yleisradio/http-kit-aws4
10
(ns http-kit-aws4.core-spec (:require [speclj.core :refer :all] [http-kit-aws4.core :refer [string-to-sign signing-key signature authorization request-date]] [buddy.core.codecs :as codecs] [clj-time.core :as t])) (describe "string-to-sign" (it "post-x-www-form-urlencoded" (let [canonical-request "POST\n/\n\ncontent-type:application/x-www-form-urlencoded\ndate:Mon, 09 Sep 2011 23:36:00 GMT\nhost:host.foo.com\n\ncontent-type;date;host\n3ba8907e7a252327488df390ed517c45b96dead033600219bdca7107d1d3f88a" expected "AWS4-HMAC-SHA256\n20110909T233600Z\n20110909/us-east-1/host/aws4_request\n4c5c6e4b52fb5fb947a8733982a8a5a61b14f04345cbfe6e739236c76dd48f74"] (should= expected (string-to-sign (t/date-time 2011 9 9 23 36 0) "us-east-1" "host" canonical-request))))) (describe "signing-key" (it "example" (should= "c4afb1cc5771d871763a393e44b703571b55cc28424d1a5e86da6ed3c154a4b9" (let [secret-access-key "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY" request-date (t/date-time 2015 8 30 0 0 0) region "us-east-1" service "iam"] (->> (signing-key secret-access-key request-date region service) (codecs/bytes->hex)))))) (describe "signature" (it "post-x-www-form-urlencoded" (let [secret-access-key "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY" request-date (t/date-time 2011 9 9 23 36 0) region "us-east-1" service "host" skey (signing-key secret-access-key request-date region service) sts "AWS4-HMAC-SHA256\n20110909T233600Z\n20110909/us-east-1/host/aws4_request\n4c5c6e4b52fb5fb947a8733982a8a5a61b14f04345cbfe6e739236c76dd48f74"] (should= "5a15b22cf462f047318703b92e6f4f38884e4a7ab7b1d6426ca46a8bd1c26cbc" (signature skey sts))))) (describe "authorization" (it "post-x-www-form-urlencoded" (should= "AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/aws4_request, SignedHeaders=content-type;date;host, Signature=5a15b22cf462f047318703b92e6f4f38884e4a7ab7b1d6426ca46a8bd1c26cbc" (authorization "AKIDEXAMPLE" "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY" (t/date-time 2011 9 9 23 36 0) "us-east-1" "host" "content-type;date;host" "POST\n/\n\ncontent-type:application/x-www-form-urlencoded\ndate:Mon, 09 Sep 2011 23:36:00 GMT\nhost:host.foo.com\n\ncontent-type;date;host\n3ba8907e7a252327488df390ed517c45b96dead033600219bdca7107d1d3f88a")))) (describe "request-date" (it "use Date header if present" (should= (t/date-time 2011 9 9 23 36 0) (request-date {"Date" "Fri, 09 Sep 2011 23:36:00 GMT"}))))
7642
(ns http-kit-aws4.core-spec (:require [speclj.core :refer :all] [http-kit-aws4.core :refer [string-to-sign signing-key signature authorization request-date]] [buddy.core.codecs :as codecs] [clj-time.core :as t])) (describe "string-to-sign" (it "post-x-www-form-urlencoded" (let [canonical-request "POST\n/\n\ncontent-type:application/x-www-form-urlencoded\ndate:Mon, 09 Sep 2011 23:36:00 GMT\nhost:host.foo.com\n\ncontent-type;date;host\n3ba8907e7a252327488df390ed517c45b96dead033600219bdca7107d1d3f88a" expected "AWS4-HMAC-SHA256\n20110909T233600Z\n20110909/us-east-1/host/aws4_request\n4c5c6e4b52fb5fb947a8733982a8a5a61b14f04345cbfe6e739236c76dd48f74"] (should= expected (string-to-sign (t/date-time 2011 9 9 23 36 0) "us-east-1" "host" canonical-request))))) (describe "signing-key" (it "example" (should= "<KEY>" (let [secret-access-key "<KEY>KEY" request-date (t/date-time 2015 8 30 0 0 0) region "us-east-1" service "iam"] (->> (signing-key secret-access-key request-date region service) (codecs/bytes->hex)))))) (describe "signature" (it "post-x-www-form-urlencoded" (let [secret-access-key "<KEY>" request-date (t/date-time 2011 9 9 23 36 0) region "us-east-1" service "host" skey (signing-key secret-access-key request-date region service) sts "AWS4-HMAC-SHA256\n20110909T233600Z\n20110909/us-east-1/host/aws4_request\n4c5c6e4b52fb5fb947a8733982a8a5a61b14f04345cbfe6e739236c76dd48f74"] (should= "5a15b22cf462f047318703b92e6f4f38884e4a7ab7b1d6426ca46a8bd1c26cbc" (signature skey sts))))) (describe "authorization" (it "post-x-www-form-urlencoded" (should= "AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/aws4_request, SignedHeaders=content-type;date;host, Signature=5a15b22cf462f047318703b92e6f4f38884e4a7ab7b1d6426ca46a8bd1c2<KEY>" (authorization "<KEY>" "<KEY>/K<KEY>EN<KEY>EXAMPLEKEY" (t/date-time 2011 9 9 23 36 0) "us-east-1" "host" "content-type;date;host" "POST\n/\n\ncontent-type:application/x-www-form-urlencoded\ndate:Mon, 09 Sep 2011 23:36:00 GMT\nhost:host.foo.com\n\ncontent-type;date;host\n3ba8907e7a252327488df390ed517c45b96dead033600219bdca7107d1d3f88a")))) (describe "request-date" (it "use Date header if present" (should= (t/date-time 2011 9 9 23 36 0) (request-date {"Date" "Fri, 09 Sep 2011 23:36:00 GMT"}))))
true
(ns http-kit-aws4.core-spec (:require [speclj.core :refer :all] [http-kit-aws4.core :refer [string-to-sign signing-key signature authorization request-date]] [buddy.core.codecs :as codecs] [clj-time.core :as t])) (describe "string-to-sign" (it "post-x-www-form-urlencoded" (let [canonical-request "POST\n/\n\ncontent-type:application/x-www-form-urlencoded\ndate:Mon, 09 Sep 2011 23:36:00 GMT\nhost:host.foo.com\n\ncontent-type;date;host\n3ba8907e7a252327488df390ed517c45b96dead033600219bdca7107d1d3f88a" expected "AWS4-HMAC-SHA256\n20110909T233600Z\n20110909/us-east-1/host/aws4_request\n4c5c6e4b52fb5fb947a8733982a8a5a61b14f04345cbfe6e739236c76dd48f74"] (should= expected (string-to-sign (t/date-time 2011 9 9 23 36 0) "us-east-1" "host" canonical-request))))) (describe "signing-key" (it "example" (should= "PI:KEY:<KEY>END_PI" (let [secret-access-key "PI:KEY:<KEY>END_PIKEY" request-date (t/date-time 2015 8 30 0 0 0) region "us-east-1" service "iam"] (->> (signing-key secret-access-key request-date region service) (codecs/bytes->hex)))))) (describe "signature" (it "post-x-www-form-urlencoded" (let [secret-access-key "PI:KEY:<KEY>END_PI" request-date (t/date-time 2011 9 9 23 36 0) region "us-east-1" service "host" skey (signing-key secret-access-key request-date region service) sts "AWS4-HMAC-SHA256\n20110909T233600Z\n20110909/us-east-1/host/aws4_request\n4c5c6e4b52fb5fb947a8733982a8a5a61b14f04345cbfe6e739236c76dd48f74"] (should= "5a15b22cf462f047318703b92e6f4f38884e4a7ab7b1d6426ca46a8bd1c26cbc" (signature skey sts))))) (describe "authorization" (it "post-x-www-form-urlencoded" (should= "AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20110909/us-east-1/host/aws4_request, SignedHeaders=content-type;date;host, Signature=5a15b22cf462f047318703b92e6f4f38884e4a7ab7b1d6426ca46a8bd1c2PI:KEY:<KEY>END_PI" (authorization "PI:KEY:<KEY>END_PI" "PI:KEY:<KEY>END_PI/KPI:KEY:<KEY>END_PIENPI:KEY:<KEY>END_PIEXAMPLEKEY" (t/date-time 2011 9 9 23 36 0) "us-east-1" "host" "content-type;date;host" "POST\n/\n\ncontent-type:application/x-www-form-urlencoded\ndate:Mon, 09 Sep 2011 23:36:00 GMT\nhost:host.foo.com\n\ncontent-type;date;host\n3ba8907e7a252327488df390ed517c45b96dead033600219bdca7107d1d3f88a")))) (describe "request-date" (it "use Date header if present" (should= (t/date-time 2011 9 9 23 36 0) (request-date {"Date" "Fri, 09 Sep 2011 23:36:00 GMT"}))))
[ { "context": "q] (fresh [x] (is-smth q x \"swimmer\"))) => (just \"aardvark\")\n (run* [q] (is-smth \"cheetah\" \"fastest\" \"lan", "end": 1880, "score": 0.9676877856254578, "start": 1872, "tag": "NAME", "value": "aardvark" } ]
test/ai_zootson/core_test.clj
Deraen/ai-zootson
1
(ns ai-zootson.core-test (:refer-clojure :exclude [==]) (:require [midje.sweet :refer :all] [clojure.core.logic :refer :all] [clojure.core.logic.pldb :as pldb] [ai-zootson.core :refer :all] [ai-zootson.domain :refer :all] [ai-zootson.questions :refer :all] )) (fact init (pldb/with-db (read-files) ;; There should be as many animals as in test input... (count (run* [q] (animal q))) => 100 ;; From zoo.data and continents.txt (run* [q] (lives-in "aardvark" q true)) => (just "africa") (count (run* [q] (classify q "reptile"))) => 5 (run* [q] (classify q "reptile") (has-prop q "hair" true)) => empty? (run* [q] (has-prop "crayfish" "legs" q)) => (just 6) (run* [q] (has-prop "deer" "venomous" false)) => seq? ;; From facts.txt ;; Examples (run* [q] (fresh [x] (some-animal "anteater" x) (lives-in x q true))) => (just "africa") (run* [q] (lives-in q "south america" true) (is-smth q "bat")) => (just "vampire") (run* [q] (do-smth q "feed" "worm")) => (just "mongoose") (run* [q] (has-prop "lynx" "tail" q)) => (contains "short") (run* [q] (fresh [x] (is-smth-of q "national symbol" x))) => (just "kiwi") ;; FIXME: swim (run* [q] (can-animal "aardvark" "swimmer")) => seq? (run* [q] (fresh [x] (has-prop q "ear" x))) => (just "elephant") (run* [q] (has-prop "bear" "fins" true) (has-prop "dogfish" "fins" true)) => empty (run* [q] (check-fact "deer" "poisonous" false)) => seq? (run* [q] (is-able q "meow")) => (just "girl" "pussycat") (run* [q] (check-fact "elephant" "eggs" false)) => seq? (run* [q] (is-able "girl" "meow")) => seq? ;; Others (run* [q] (is-smth "aardvark" "good" "swimmer")) => seq? (run* [q] (fresh [x] (is-smth q x "swimmer"))) => (just "aardvark") (run* [q] (is-smth "cheetah" "fastest" "land animal")) => seq? ;; own_facts.txt (run* [q] (conde [(== q "crayfish") (is-less q "dolphin" "size")] [(== q "dolphin") (is-less q "crayfish" "size")])) => (just "crayfish") (run* [q] (conde [(== q "crayfish") (is-more q "dolphin" "size")] [(== q "dolphin") (is-more q "crayfish" "size")])) => (just "dolphin") (run* [q] (is-less "girl" "boy" "speed")) => seq? (run* [q] (is-less "boy" "girl" "speed")) => seq? (run* [q] (is-more "girl" "boy" "speed")) => empty? (run* [q] (is-more "boy" "girl" "speed")) => seq? )) (facts "questions" (let [db (-> (read-files) (ai-zootson.facts/read-fact "Girls and wolves can howl."))] (tabular (fact answer-question (answer-question db ?line) => ?expected) ?line ?expected "Where do aardvarks live?" "Africa" ;; Sample q "Where do anteaters live?" "Africa" "How many reptiles do you know?" "5" "How many mammals do you know?" "41" "What hairy reptiles do you know?" "none" ;; variant of previous where own_facts contains an answer ;; "What stupid reptiles do you know?" "seasnake" "Mention a bat that lives in South America." "vampire" "What kind of a tail does a lynx have?" "short" "How many legs does a crayfish have?" "6" "Is it true that deer are not poisonous?" "yes" "Is it true that deer are poisonous?" "no" "Is it false that deer are not poisonous?" "no" "Is it false that deer are poisonous?" "yes" "Which animals are able to meow?" "girl, pussycat" "Is it true that elephants do not lay eggs?" "yes" "Is it true that elephants do lay eggs?" "no" "Is it false that elephants do not lay eggs?" "no" "Is it false that elephants do lay eggs?" "yes" "Is it false that girls cannot meow?" "yes" "Is it true that girls cannot meow?" "no" "Is it false that girls can meow?" "no" "Is it true that girls can meow?" "yes" "Which is smaller: dolphin or crayfish?" "crayfish" "Which is smaller: crayfish or dolphin?" "crayfish" "Which is larger: crayfish or dolphin?" "dolphin" "Which is bigger: crayfish or dolphin?" "dolphin" "Is a lobster smaller than a crayfish?" "no" "Is a crayfish smaller than a lobster" "yes" "Is a lobster larger than a crayfish?" "yes" "Is a crayfish larger than a lobster" "no" "Is a crayfish larger than a girl" "no idea" ;; Cheetah is fastest animal "Are girls slower than a cheetah?" "yes" "Are cheetah faster than a girls" "yes" "Are cheetah faster than a worm" "yes" "Are worm slower than a cheetah" "yes" "Which is faster: cheetah or girl" "cheetah" "Are boys faster than a girls" "yes" "Are girls faster than a boys" "no" "Are boys slower than a girls" "no" "Are worms less intelligent than a octopuses" "yes" "Are worms more intelligent than a octopuses" "no" "Are worms more intelligent than a girls" "no idea" "Which is more intelligent: octopus or worm" "octopus" "Which is less intelligent worm or octopus" "worm" "Which is more intelligent: girl or octopus" "girl" "Do bears and dogfish have fins?" "no" "Mention an animal that is a national symbol. " "kiwi" "Which animal has ears?" "elephant" "What venomous reptiles do you know?" "seasnake, pitviper" "Can aardvarks swim?" "yes" "Which animal eats worms?" "mongoose" "What mongoose eats?" "no idea" "Where do pumas live?" "South America, North America" "What kind of legs does a lynx have" "no idea" "Which animals are able to howl" "girl, wolf" ;; Catfish isn't a land animal "Are cheetahs faster than catfish?" "no idea" )))
33629
(ns ai-zootson.core-test (:refer-clojure :exclude [==]) (:require [midje.sweet :refer :all] [clojure.core.logic :refer :all] [clojure.core.logic.pldb :as pldb] [ai-zootson.core :refer :all] [ai-zootson.domain :refer :all] [ai-zootson.questions :refer :all] )) (fact init (pldb/with-db (read-files) ;; There should be as many animals as in test input... (count (run* [q] (animal q))) => 100 ;; From zoo.data and continents.txt (run* [q] (lives-in "aardvark" q true)) => (just "africa") (count (run* [q] (classify q "reptile"))) => 5 (run* [q] (classify q "reptile") (has-prop q "hair" true)) => empty? (run* [q] (has-prop "crayfish" "legs" q)) => (just 6) (run* [q] (has-prop "deer" "venomous" false)) => seq? ;; From facts.txt ;; Examples (run* [q] (fresh [x] (some-animal "anteater" x) (lives-in x q true))) => (just "africa") (run* [q] (lives-in q "south america" true) (is-smth q "bat")) => (just "vampire") (run* [q] (do-smth q "feed" "worm")) => (just "mongoose") (run* [q] (has-prop "lynx" "tail" q)) => (contains "short") (run* [q] (fresh [x] (is-smth-of q "national symbol" x))) => (just "kiwi") ;; FIXME: swim (run* [q] (can-animal "aardvark" "swimmer")) => seq? (run* [q] (fresh [x] (has-prop q "ear" x))) => (just "elephant") (run* [q] (has-prop "bear" "fins" true) (has-prop "dogfish" "fins" true)) => empty (run* [q] (check-fact "deer" "poisonous" false)) => seq? (run* [q] (is-able q "meow")) => (just "girl" "pussycat") (run* [q] (check-fact "elephant" "eggs" false)) => seq? (run* [q] (is-able "girl" "meow")) => seq? ;; Others (run* [q] (is-smth "aardvark" "good" "swimmer")) => seq? (run* [q] (fresh [x] (is-smth q x "swimmer"))) => (just "<NAME>") (run* [q] (is-smth "cheetah" "fastest" "land animal")) => seq? ;; own_facts.txt (run* [q] (conde [(== q "crayfish") (is-less q "dolphin" "size")] [(== q "dolphin") (is-less q "crayfish" "size")])) => (just "crayfish") (run* [q] (conde [(== q "crayfish") (is-more q "dolphin" "size")] [(== q "dolphin") (is-more q "crayfish" "size")])) => (just "dolphin") (run* [q] (is-less "girl" "boy" "speed")) => seq? (run* [q] (is-less "boy" "girl" "speed")) => seq? (run* [q] (is-more "girl" "boy" "speed")) => empty? (run* [q] (is-more "boy" "girl" "speed")) => seq? )) (facts "questions" (let [db (-> (read-files) (ai-zootson.facts/read-fact "Girls and wolves can howl."))] (tabular (fact answer-question (answer-question db ?line) => ?expected) ?line ?expected "Where do aardvarks live?" "Africa" ;; Sample q "Where do anteaters live?" "Africa" "How many reptiles do you know?" "5" "How many mammals do you know?" "41" "What hairy reptiles do you know?" "none" ;; variant of previous where own_facts contains an answer ;; "What stupid reptiles do you know?" "seasnake" "Mention a bat that lives in South America." "vampire" "What kind of a tail does a lynx have?" "short" "How many legs does a crayfish have?" "6" "Is it true that deer are not poisonous?" "yes" "Is it true that deer are poisonous?" "no" "Is it false that deer are not poisonous?" "no" "Is it false that deer are poisonous?" "yes" "Which animals are able to meow?" "girl, pussycat" "Is it true that elephants do not lay eggs?" "yes" "Is it true that elephants do lay eggs?" "no" "Is it false that elephants do not lay eggs?" "no" "Is it false that elephants do lay eggs?" "yes" "Is it false that girls cannot meow?" "yes" "Is it true that girls cannot meow?" "no" "Is it false that girls can meow?" "no" "Is it true that girls can meow?" "yes" "Which is smaller: dolphin or crayfish?" "crayfish" "Which is smaller: crayfish or dolphin?" "crayfish" "Which is larger: crayfish or dolphin?" "dolphin" "Which is bigger: crayfish or dolphin?" "dolphin" "Is a lobster smaller than a crayfish?" "no" "Is a crayfish smaller than a lobster" "yes" "Is a lobster larger than a crayfish?" "yes" "Is a crayfish larger than a lobster" "no" "Is a crayfish larger than a girl" "no idea" ;; Cheetah is fastest animal "Are girls slower than a cheetah?" "yes" "Are cheetah faster than a girls" "yes" "Are cheetah faster than a worm" "yes" "Are worm slower than a cheetah" "yes" "Which is faster: cheetah or girl" "cheetah" "Are boys faster than a girls" "yes" "Are girls faster than a boys" "no" "Are boys slower than a girls" "no" "Are worms less intelligent than a octopuses" "yes" "Are worms more intelligent than a octopuses" "no" "Are worms more intelligent than a girls" "no idea" "Which is more intelligent: octopus or worm" "octopus" "Which is less intelligent worm or octopus" "worm" "Which is more intelligent: girl or octopus" "girl" "Do bears and dogfish have fins?" "no" "Mention an animal that is a national symbol. " "kiwi" "Which animal has ears?" "elephant" "What venomous reptiles do you know?" "seasnake, pitviper" "Can aardvarks swim?" "yes" "Which animal eats worms?" "mongoose" "What mongoose eats?" "no idea" "Where do pumas live?" "South America, North America" "What kind of legs does a lynx have" "no idea" "Which animals are able to howl" "girl, wolf" ;; Catfish isn't a land animal "Are cheetahs faster than catfish?" "no idea" )))
true
(ns ai-zootson.core-test (:refer-clojure :exclude [==]) (:require [midje.sweet :refer :all] [clojure.core.logic :refer :all] [clojure.core.logic.pldb :as pldb] [ai-zootson.core :refer :all] [ai-zootson.domain :refer :all] [ai-zootson.questions :refer :all] )) (fact init (pldb/with-db (read-files) ;; There should be as many animals as in test input... (count (run* [q] (animal q))) => 100 ;; From zoo.data and continents.txt (run* [q] (lives-in "aardvark" q true)) => (just "africa") (count (run* [q] (classify q "reptile"))) => 5 (run* [q] (classify q "reptile") (has-prop q "hair" true)) => empty? (run* [q] (has-prop "crayfish" "legs" q)) => (just 6) (run* [q] (has-prop "deer" "venomous" false)) => seq? ;; From facts.txt ;; Examples (run* [q] (fresh [x] (some-animal "anteater" x) (lives-in x q true))) => (just "africa") (run* [q] (lives-in q "south america" true) (is-smth q "bat")) => (just "vampire") (run* [q] (do-smth q "feed" "worm")) => (just "mongoose") (run* [q] (has-prop "lynx" "tail" q)) => (contains "short") (run* [q] (fresh [x] (is-smth-of q "national symbol" x))) => (just "kiwi") ;; FIXME: swim (run* [q] (can-animal "aardvark" "swimmer")) => seq? (run* [q] (fresh [x] (has-prop q "ear" x))) => (just "elephant") (run* [q] (has-prop "bear" "fins" true) (has-prop "dogfish" "fins" true)) => empty (run* [q] (check-fact "deer" "poisonous" false)) => seq? (run* [q] (is-able q "meow")) => (just "girl" "pussycat") (run* [q] (check-fact "elephant" "eggs" false)) => seq? (run* [q] (is-able "girl" "meow")) => seq? ;; Others (run* [q] (is-smth "aardvark" "good" "swimmer")) => seq? (run* [q] (fresh [x] (is-smth q x "swimmer"))) => (just "PI:NAME:<NAME>END_PI") (run* [q] (is-smth "cheetah" "fastest" "land animal")) => seq? ;; own_facts.txt (run* [q] (conde [(== q "crayfish") (is-less q "dolphin" "size")] [(== q "dolphin") (is-less q "crayfish" "size")])) => (just "crayfish") (run* [q] (conde [(== q "crayfish") (is-more q "dolphin" "size")] [(== q "dolphin") (is-more q "crayfish" "size")])) => (just "dolphin") (run* [q] (is-less "girl" "boy" "speed")) => seq? (run* [q] (is-less "boy" "girl" "speed")) => seq? (run* [q] (is-more "girl" "boy" "speed")) => empty? (run* [q] (is-more "boy" "girl" "speed")) => seq? )) (facts "questions" (let [db (-> (read-files) (ai-zootson.facts/read-fact "Girls and wolves can howl."))] (tabular (fact answer-question (answer-question db ?line) => ?expected) ?line ?expected "Where do aardvarks live?" "Africa" ;; Sample q "Where do anteaters live?" "Africa" "How many reptiles do you know?" "5" "How many mammals do you know?" "41" "What hairy reptiles do you know?" "none" ;; variant of previous where own_facts contains an answer ;; "What stupid reptiles do you know?" "seasnake" "Mention a bat that lives in South America." "vampire" "What kind of a tail does a lynx have?" "short" "How many legs does a crayfish have?" "6" "Is it true that deer are not poisonous?" "yes" "Is it true that deer are poisonous?" "no" "Is it false that deer are not poisonous?" "no" "Is it false that deer are poisonous?" "yes" "Which animals are able to meow?" "girl, pussycat" "Is it true that elephants do not lay eggs?" "yes" "Is it true that elephants do lay eggs?" "no" "Is it false that elephants do not lay eggs?" "no" "Is it false that elephants do lay eggs?" "yes" "Is it false that girls cannot meow?" "yes" "Is it true that girls cannot meow?" "no" "Is it false that girls can meow?" "no" "Is it true that girls can meow?" "yes" "Which is smaller: dolphin or crayfish?" "crayfish" "Which is smaller: crayfish or dolphin?" "crayfish" "Which is larger: crayfish or dolphin?" "dolphin" "Which is bigger: crayfish or dolphin?" "dolphin" "Is a lobster smaller than a crayfish?" "no" "Is a crayfish smaller than a lobster" "yes" "Is a lobster larger than a crayfish?" "yes" "Is a crayfish larger than a lobster" "no" "Is a crayfish larger than a girl" "no idea" ;; Cheetah is fastest animal "Are girls slower than a cheetah?" "yes" "Are cheetah faster than a girls" "yes" "Are cheetah faster than a worm" "yes" "Are worm slower than a cheetah" "yes" "Which is faster: cheetah or girl" "cheetah" "Are boys faster than a girls" "yes" "Are girls faster than a boys" "no" "Are boys slower than a girls" "no" "Are worms less intelligent than a octopuses" "yes" "Are worms more intelligent than a octopuses" "no" "Are worms more intelligent than a girls" "no idea" "Which is more intelligent: octopus or worm" "octopus" "Which is less intelligent worm or octopus" "worm" "Which is more intelligent: girl or octopus" "girl" "Do bears and dogfish have fins?" "no" "Mention an animal that is a national symbol. " "kiwi" "Which animal has ears?" "elephant" "What venomous reptiles do you know?" "seasnake, pitviper" "Can aardvarks swim?" "yes" "Which animal eats worms?" "mongoose" "What mongoose eats?" "no idea" "Where do pumas live?" "South America, North America" "What kind of legs does a lynx have" "no idea" "Which animals are able to howl" "girl, wolf" ;; Catfish isn't a land animal "Are cheetahs faster than catfish?" "no idea" )))
[ { "context": "t xit]]))\n\n(def cy js/cy)\n\n(def DEFAULT-USERNAME \"admin\")\n(def DEFAULT-PASSWORD \"hunter2\")\n\n(defn login\n ", "end": 137, "score": 0.9961984753608704, "start": 132, "tag": "USERNAME", "value": "admin" }, { "context": " DEFAULT-USERNAME \"admin\")\n(def DEFAULT-PASSWORD \"hunter2\")\n\n(defn login\n ([]\n (login DEFAULT-USERNAME D", "end": 170, "score": 0.9990755915641785, "start": 163, "tag": "PASSWORD", "value": "hunter2" } ]
cypress/integration/dinsro/login_page.cljs
duck1123/dinsro
2
(ns dinsro.login-page (:require-macros [latte.core :refer [describe beforeEach it xit]])) (def cy js/cy) (def DEFAULT-USERNAME "admin") (def DEFAULT-PASSWORD "hunter2") (defn login ([] (login DEFAULT-USERNAME DEFAULT-PASSWORD)) ([username password] (.. cy (log "logging in")) (.. cy (get ":nth-child(1) > .control > div > .input") clear (type username)) (.. cy (get ":nth-child(2) > .control > div > .input") clear (type password)) (.. cy (get ".control > .ui") click))) (describe "Login Page" (beforeEach [] (.visit cy "/login")) (xit "should have a login link" [] ;; (.. cy (get ":nth-child(1) > .control > div > .input") clear (type "admin")) ;; (.. cy (get ":nth-child(2) > .control > div > .input") clear (type "hunter3")) ;; (.. cy (get ".control > .ui") click) (login) (.. cy (get ".notification") (should "exist")) ;; (.. cy (get ".title")) ;; (.. cy (get ".login-link") (as "login-link")) ;; (.. cy (get "@login-link") (should "contain" "login")) ;; (.. cy (get "@login-link") click) ;; (.. cy (get ".title") (should "contain" "Login")) ))
101327
(ns dinsro.login-page (:require-macros [latte.core :refer [describe beforeEach it xit]])) (def cy js/cy) (def DEFAULT-USERNAME "admin") (def DEFAULT-PASSWORD "<PASSWORD>") (defn login ([] (login DEFAULT-USERNAME DEFAULT-PASSWORD)) ([username password] (.. cy (log "logging in")) (.. cy (get ":nth-child(1) > .control > div > .input") clear (type username)) (.. cy (get ":nth-child(2) > .control > div > .input") clear (type password)) (.. cy (get ".control > .ui") click))) (describe "Login Page" (beforeEach [] (.visit cy "/login")) (xit "should have a login link" [] ;; (.. cy (get ":nth-child(1) > .control > div > .input") clear (type "admin")) ;; (.. cy (get ":nth-child(2) > .control > div > .input") clear (type "hunter3")) ;; (.. cy (get ".control > .ui") click) (login) (.. cy (get ".notification") (should "exist")) ;; (.. cy (get ".title")) ;; (.. cy (get ".login-link") (as "login-link")) ;; (.. cy (get "@login-link") (should "contain" "login")) ;; (.. cy (get "@login-link") click) ;; (.. cy (get ".title") (should "contain" "Login")) ))
true
(ns dinsro.login-page (:require-macros [latte.core :refer [describe beforeEach it xit]])) (def cy js/cy) (def DEFAULT-USERNAME "admin") (def DEFAULT-PASSWORD "PI:PASSWORD:<PASSWORD>END_PI") (defn login ([] (login DEFAULT-USERNAME DEFAULT-PASSWORD)) ([username password] (.. cy (log "logging in")) (.. cy (get ":nth-child(1) > .control > div > .input") clear (type username)) (.. cy (get ":nth-child(2) > .control > div > .input") clear (type password)) (.. cy (get ".control > .ui") click))) (describe "Login Page" (beforeEach [] (.visit cy "/login")) (xit "should have a login link" [] ;; (.. cy (get ":nth-child(1) > .control > div > .input") clear (type "admin")) ;; (.. cy (get ":nth-child(2) > .control > div > .input") clear (type "hunter3")) ;; (.. cy (get ".control > .ui") click) (login) (.. cy (get ".notification") (should "exist")) ;; (.. cy (get ".title")) ;; (.. cy (get ".login-link") (as "login-link")) ;; (.. cy (get "@login-link") (should "contain" "login")) ;; (.. cy (get "@login-link") click) ;; (.. cy (get ".title") (should "contain" "Login")) ))
[ { "context": "ontext))\n user-token (e/login (s/context) \"user1\" [\"group-guid2\" \"group-guid3\"])\n admin-rea", "end": 1932, "score": 0.8391693830490112, "start": 1927, "tag": "USERNAME", "value": "user1" }, { "context": "])\n admin-read-token (e/login (s/context) \"admin\" [\"admin-read-group-guid\" \"group-guid3\"])\n ", "end": 2017, "score": 0.831603467464447, "start": 2012, "tag": "USERNAME", "value": "admin" }, { "context": "])\n prov-admin-token (e/login (s/context) \"prov-admin\" [\"prov-admin-group-guid\" \"group-guid3\"])]\n", "end": 2319, "score": 0.510265052318573, "start": 2315, "tag": "USERNAME", "value": "prov" }, { "context": " prov-admin-token (e/login (s/context) \"prov-admin\" [\"prov-admin-group-guid\" \"group-guid3\"])]\n\n (", "end": 2325, "score": 0.7121923565864563, "start": 2320, "tag": "PASSWORD", "value": "admin" } ]
system-int-test/test/cmr/system_int_test/admin/admin_permissions_test.clj
sxu123/Common-Metadata-Repository
0
(ns cmr.system-int-test.admin.admin-permissions-test "Verifies the correct administrative permissions are enforced admin only apis" (:require [clojure.test :refer :all] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.search-util :as search] [cmr.system-int-test.utils.index-util :as index] [cmr.mock-echo.client.echo-util :as e] [cmr.system-int-test.utils.url-helper :as url] [cmr.system-int-test.system :as s] [clj-http.client :as client])) (use-fixtures :each (ingest/reset-fixture {"provguid1" "PROV1"} {:grant-all-search? false :grant-all-ingest? false})) (defn has-action-permission? "Attempts to perform the given action using the url and method with the token. Returns true if the action was successful." [url method token] (let [response (client/request {:url url :method method :query-params {:token token} :connection-manager (s/conn-mgr) :throw-exceptions false}) status (:status response)] ;; Make sure the status returned is success or 401 (is (some #{status} [200 201 204 401])) (not= status 401))) (deftest ingest-management-permission-test ;; Grant admin-group-guid admin permission (e/grant-group-admin (s/context) "admin-read-group-guid" :read) (e/grant-group-admin (s/context) "admin-update-group-guid" :update) (e/grant-group-admin (s/context) "admin-read-update-group-guid" :read :update) ;; Grant provider admin permission, but not system permission (e/grant-group-provider-admin (s/context) "prov-admin-group-guid" "provguid1" :read :update :delete) (let [guest-token (e/login-guest (s/context)) user-token (e/login (s/context) "user1" ["group-guid2" "group-guid3"]) admin-read-token (e/login (s/context) "admin" ["admin-read-group-guid" "group-guid3"]) admin-update-token (e/login (s/context) "admin" ["admin-update-group-guid" "group-guid3"]) admin-read-update-token (e/login (s/context) "admin" ["admin-read-update-group-guid" "group-guid3"]) prov-admin-token (e/login (s/context) "prov-admin" ["prov-admin-group-guid" "group-guid3"])] (are [url] (and (not (has-action-permission? url :post prov-admin-token)) (not (has-action-permission? url :post guest-token)) (not (has-action-permission? url :post user-token)) (not (has-action-permission? url :post admin-read-token)) (has-action-permission? url :post admin-update-token) (has-action-permission? url :post admin-read-update-token)) (url/search-clear-cache-url) (url/search-reset-url) (url/indexer-clear-cache-url) (url/indexer-reset-url) (url/enable-ingest-writes-url) (url/disable-ingest-writes-url) (url/enable-search-writes-url) (url/disable-search-writes-url) (url/enable-access-control-writes-url) (url/disable-access-control-writes-url) (url/mdb-reset-url) (url/index-set-reset-url) (url/cubby-reset-url) (url/reindex-collection-permitted-groups-url) (url/reindex-all-collections-url) (url/cleanup-expired-collections-url) (url/access-control-reindex-acls-url))))
47170
(ns cmr.system-int-test.admin.admin-permissions-test "Verifies the correct administrative permissions are enforced admin only apis" (:require [clojure.test :refer :all] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.search-util :as search] [cmr.system-int-test.utils.index-util :as index] [cmr.mock-echo.client.echo-util :as e] [cmr.system-int-test.utils.url-helper :as url] [cmr.system-int-test.system :as s] [clj-http.client :as client])) (use-fixtures :each (ingest/reset-fixture {"provguid1" "PROV1"} {:grant-all-search? false :grant-all-ingest? false})) (defn has-action-permission? "Attempts to perform the given action using the url and method with the token. Returns true if the action was successful." [url method token] (let [response (client/request {:url url :method method :query-params {:token token} :connection-manager (s/conn-mgr) :throw-exceptions false}) status (:status response)] ;; Make sure the status returned is success or 401 (is (some #{status} [200 201 204 401])) (not= status 401))) (deftest ingest-management-permission-test ;; Grant admin-group-guid admin permission (e/grant-group-admin (s/context) "admin-read-group-guid" :read) (e/grant-group-admin (s/context) "admin-update-group-guid" :update) (e/grant-group-admin (s/context) "admin-read-update-group-guid" :read :update) ;; Grant provider admin permission, but not system permission (e/grant-group-provider-admin (s/context) "prov-admin-group-guid" "provguid1" :read :update :delete) (let [guest-token (e/login-guest (s/context)) user-token (e/login (s/context) "user1" ["group-guid2" "group-guid3"]) admin-read-token (e/login (s/context) "admin" ["admin-read-group-guid" "group-guid3"]) admin-update-token (e/login (s/context) "admin" ["admin-update-group-guid" "group-guid3"]) admin-read-update-token (e/login (s/context) "admin" ["admin-read-update-group-guid" "group-guid3"]) prov-admin-token (e/login (s/context) "prov-<PASSWORD>" ["prov-admin-group-guid" "group-guid3"])] (are [url] (and (not (has-action-permission? url :post prov-admin-token)) (not (has-action-permission? url :post guest-token)) (not (has-action-permission? url :post user-token)) (not (has-action-permission? url :post admin-read-token)) (has-action-permission? url :post admin-update-token) (has-action-permission? url :post admin-read-update-token)) (url/search-clear-cache-url) (url/search-reset-url) (url/indexer-clear-cache-url) (url/indexer-reset-url) (url/enable-ingest-writes-url) (url/disable-ingest-writes-url) (url/enable-search-writes-url) (url/disable-search-writes-url) (url/enable-access-control-writes-url) (url/disable-access-control-writes-url) (url/mdb-reset-url) (url/index-set-reset-url) (url/cubby-reset-url) (url/reindex-collection-permitted-groups-url) (url/reindex-all-collections-url) (url/cleanup-expired-collections-url) (url/access-control-reindex-acls-url))))
true
(ns cmr.system-int-test.admin.admin-permissions-test "Verifies the correct administrative permissions are enforced admin only apis" (:require [clojure.test :refer :all] [cmr.system-int-test.utils.ingest-util :as ingest] [cmr.system-int-test.utils.search-util :as search] [cmr.system-int-test.utils.index-util :as index] [cmr.mock-echo.client.echo-util :as e] [cmr.system-int-test.utils.url-helper :as url] [cmr.system-int-test.system :as s] [clj-http.client :as client])) (use-fixtures :each (ingest/reset-fixture {"provguid1" "PROV1"} {:grant-all-search? false :grant-all-ingest? false})) (defn has-action-permission? "Attempts to perform the given action using the url and method with the token. Returns true if the action was successful." [url method token] (let [response (client/request {:url url :method method :query-params {:token token} :connection-manager (s/conn-mgr) :throw-exceptions false}) status (:status response)] ;; Make sure the status returned is success or 401 (is (some #{status} [200 201 204 401])) (not= status 401))) (deftest ingest-management-permission-test ;; Grant admin-group-guid admin permission (e/grant-group-admin (s/context) "admin-read-group-guid" :read) (e/grant-group-admin (s/context) "admin-update-group-guid" :update) (e/grant-group-admin (s/context) "admin-read-update-group-guid" :read :update) ;; Grant provider admin permission, but not system permission (e/grant-group-provider-admin (s/context) "prov-admin-group-guid" "provguid1" :read :update :delete) (let [guest-token (e/login-guest (s/context)) user-token (e/login (s/context) "user1" ["group-guid2" "group-guid3"]) admin-read-token (e/login (s/context) "admin" ["admin-read-group-guid" "group-guid3"]) admin-update-token (e/login (s/context) "admin" ["admin-update-group-guid" "group-guid3"]) admin-read-update-token (e/login (s/context) "admin" ["admin-read-update-group-guid" "group-guid3"]) prov-admin-token (e/login (s/context) "prov-PI:PASSWORD:<PASSWORD>END_PI" ["prov-admin-group-guid" "group-guid3"])] (are [url] (and (not (has-action-permission? url :post prov-admin-token)) (not (has-action-permission? url :post guest-token)) (not (has-action-permission? url :post user-token)) (not (has-action-permission? url :post admin-read-token)) (has-action-permission? url :post admin-update-token) (has-action-permission? url :post admin-read-update-token)) (url/search-clear-cache-url) (url/search-reset-url) (url/indexer-clear-cache-url) (url/indexer-reset-url) (url/enable-ingest-writes-url) (url/disable-ingest-writes-url) (url/enable-search-writes-url) (url/disable-search-writes-url) (url/enable-access-control-writes-url) (url/disable-access-control-writes-url) (url/mdb-reset-url) (url/index-set-reset-url) (url/cubby-reset-url) (url/reindex-collection-permitted-groups-url) (url/reindex-all-collections-url) (url/cleanup-expired-collections-url) (url/access-control-reindex-acls-url))))
[ { "context": "any other, from this software.\n\n(ns\n #^{:author \"Konrad Hinsen\"\n :doc \"Various small macros\"}\n clojure.cont", "end": 529, "score": 0.9998847842216492, "start": 516, "tag": "NAME", "value": "Konrad Hinsen" }, { "context": "us small macros\"}\n clojure.contrib.macros)\n\n;; By Konrad Hinsen\n(defmacro const\n \"Evaluate the constant expressi", "end": 611, "score": 0.9998790621757507, "start": 598, "tag": "NAME", "value": "Konrad Hinsen" }, { "context": "r at compile time.\"\n [expr]\n (eval expr))\n\n;; By Konrad Hinsen\n; This macro is made obsolete by Clojure's built-", "end": 731, "score": 0.9998772740364075, "start": 718, "tag": "NAME", "value": "Konrad Hinsen" }, { "context": "3 fn-bindings))))]\n `(let ~fns ~@exprs)))\n\n ;; By Konrad Hinsen\n\n (defn- unqualified-symbol\n [s]\n (let [s-str (", "end": 1432, "score": 0.9998601078987122, "start": 1419, "tag": "NAME", "value": "Konrad Hinsen" } ]
ThirdParty/clojure-contrib-1.1.0/src/clojure/contrib/macros.clj
allertonm/Couverjure
3
;; Various useful macros ;; ;; Everybody is invited to add their own little macros here! ;; ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this ;; distribution. By using this software in any fashion, you are ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. (ns #^{:author "Konrad Hinsen" :doc "Various small macros"} clojure.contrib.macros) ;; By Konrad Hinsen (defmacro const "Evaluate the constant expression expr at compile time." [expr] (eval expr)) ;; By Konrad Hinsen ; This macro is made obsolete by Clojure's built-in letfn. I renamed it to ; letfn- (to avoid a name clash) but leave it in for a while, since its ; syntax is not quite the same as Clojure's. Expect this to disappear ; in the long run! (defmacro letfn- "OBSOLETE: use clojure.core/letfn A variant of let for local function definitions. fn-bindings consists of name/args/body triples, with (letfn [name args body] ...) being equivalent to (let [name (fn name args body)] ...)." [fn-bindings & exprs] (let [makefn (fn [[name args body]] (list name (list 'fn name args body))) fns (vec (apply concat (map makefn (partition 3 fn-bindings))))] `(let ~fns ~@exprs))) ;; By Konrad Hinsen (defn- unqualified-symbol [s] (let [s-str (str s)] (symbol (subs s-str (inc (.indexOf s-str (int \/))))))) (defn- bound-var? [var] (try (do (deref var) true) (catch java.lang.IllegalStateException e false))) (defn- fns-from-ns [ns ns-symbol] (apply concat (for [[k v] (ns-publics ns) :when (and (bound-var? v) (fn? @v) (not (:macro (meta v))))] [k (symbol (str ns-symbol) (str k))]))) (defn- expand-symbol [ns-or-var-sym] (if (= ns-or-var-sym '*ns*) (fns-from-ns *ns* (ns-name *ns*)) (if-let [ns (find-ns ns-or-var-sym)] (fns-from-ns ns ns-or-var-sym) (list (unqualified-symbol ns-or-var-sym) ns-or-var-sym)))) (defmacro with-direct-linking "EXPERIMENTAL! Compiles the functions in body with direct links to the functions named in symbols, i.e. without a var lookup for each invocation. Symbols is a vector of symbols that name either vars or namespaces. A namespace reference is replaced by the list of all symbols in the namespace that are bound to functions. If symbols is not provided, the default value ['clojure.core] is used. The symbol *ns* can be used to refer to the current namespace." {:arglists '([symbols? & body])} [& body] (let [[symbols body] (if (vector? (first body)) [(first body) (rest body)] [['clojure.core] body]) bindings (vec (mapcat expand-symbol symbols))] `(let ~bindings ~@body)))
49526
;; Various useful macros ;; ;; Everybody is invited to add their own little macros here! ;; ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this ;; distribution. By using this software in any fashion, you are ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. (ns #^{:author "<NAME>" :doc "Various small macros"} clojure.contrib.macros) ;; By <NAME> (defmacro const "Evaluate the constant expression expr at compile time." [expr] (eval expr)) ;; By <NAME> ; This macro is made obsolete by Clojure's built-in letfn. I renamed it to ; letfn- (to avoid a name clash) but leave it in for a while, since its ; syntax is not quite the same as Clojure's. Expect this to disappear ; in the long run! (defmacro letfn- "OBSOLETE: use clojure.core/letfn A variant of let for local function definitions. fn-bindings consists of name/args/body triples, with (letfn [name args body] ...) being equivalent to (let [name (fn name args body)] ...)." [fn-bindings & exprs] (let [makefn (fn [[name args body]] (list name (list 'fn name args body))) fns (vec (apply concat (map makefn (partition 3 fn-bindings))))] `(let ~fns ~@exprs))) ;; By <NAME> (defn- unqualified-symbol [s] (let [s-str (str s)] (symbol (subs s-str (inc (.indexOf s-str (int \/))))))) (defn- bound-var? [var] (try (do (deref var) true) (catch java.lang.IllegalStateException e false))) (defn- fns-from-ns [ns ns-symbol] (apply concat (for [[k v] (ns-publics ns) :when (and (bound-var? v) (fn? @v) (not (:macro (meta v))))] [k (symbol (str ns-symbol) (str k))]))) (defn- expand-symbol [ns-or-var-sym] (if (= ns-or-var-sym '*ns*) (fns-from-ns *ns* (ns-name *ns*)) (if-let [ns (find-ns ns-or-var-sym)] (fns-from-ns ns ns-or-var-sym) (list (unqualified-symbol ns-or-var-sym) ns-or-var-sym)))) (defmacro with-direct-linking "EXPERIMENTAL! Compiles the functions in body with direct links to the functions named in symbols, i.e. without a var lookup for each invocation. Symbols is a vector of symbols that name either vars or namespaces. A namespace reference is replaced by the list of all symbols in the namespace that are bound to functions. If symbols is not provided, the default value ['clojure.core] is used. The symbol *ns* can be used to refer to the current namespace." {:arglists '([symbols? & body])} [& body] (let [[symbols body] (if (vector? (first body)) [(first body) (rest body)] [['clojure.core] body]) bindings (vec (mapcat expand-symbol symbols))] `(let ~bindings ~@body)))
true
;; Various useful macros ;; ;; Everybody is invited to add their own little macros here! ;; ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this ;; distribution. By using this software in any fashion, you are ;; agreeing to be bound by the terms of this license. You must not ;; remove this notice, or any other, from this software. (ns #^{:author "PI:NAME:<NAME>END_PI" :doc "Various small macros"} clojure.contrib.macros) ;; By PI:NAME:<NAME>END_PI (defmacro const "Evaluate the constant expression expr at compile time." [expr] (eval expr)) ;; By PI:NAME:<NAME>END_PI ; This macro is made obsolete by Clojure's built-in letfn. I renamed it to ; letfn- (to avoid a name clash) but leave it in for a while, since its ; syntax is not quite the same as Clojure's. Expect this to disappear ; in the long run! (defmacro letfn- "OBSOLETE: use clojure.core/letfn A variant of let for local function definitions. fn-bindings consists of name/args/body triples, with (letfn [name args body] ...) being equivalent to (let [name (fn name args body)] ...)." [fn-bindings & exprs] (let [makefn (fn [[name args body]] (list name (list 'fn name args body))) fns (vec (apply concat (map makefn (partition 3 fn-bindings))))] `(let ~fns ~@exprs))) ;; By PI:NAME:<NAME>END_PI (defn- unqualified-symbol [s] (let [s-str (str s)] (symbol (subs s-str (inc (.indexOf s-str (int \/))))))) (defn- bound-var? [var] (try (do (deref var) true) (catch java.lang.IllegalStateException e false))) (defn- fns-from-ns [ns ns-symbol] (apply concat (for [[k v] (ns-publics ns) :when (and (bound-var? v) (fn? @v) (not (:macro (meta v))))] [k (symbol (str ns-symbol) (str k))]))) (defn- expand-symbol [ns-or-var-sym] (if (= ns-or-var-sym '*ns*) (fns-from-ns *ns* (ns-name *ns*)) (if-let [ns (find-ns ns-or-var-sym)] (fns-from-ns ns ns-or-var-sym) (list (unqualified-symbol ns-or-var-sym) ns-or-var-sym)))) (defmacro with-direct-linking "EXPERIMENTAL! Compiles the functions in body with direct links to the functions named in symbols, i.e. without a var lookup for each invocation. Symbols is a vector of symbols that name either vars or namespaces. A namespace reference is replaced by the list of all symbols in the namespace that are bound to functions. If symbols is not provided, the default value ['clojure.core] is used. The symbol *ns* can be used to refer to the current namespace." {:arglists '([symbols? & body])} [& body] (let [[symbols body] (if (vector? (first body)) [(first body) (rest body)] [['clojure.core] body]) bindings (vec (mapcat expand-symbol symbols))] `(let ~bindings ~@body)))
[ { "context": "\n [:li \"Flocking Behaviors\"]\n [:li \"Based on Craig Reynold's Flocking Algorithms\"]\n [:li \"Stateless*\"]\n ", "end": 2613, "score": 0.9987009167671204, "start": 2600, "tag": "NAME", "value": "Craig Reynold" } ]
data/train/clojure/222169d5f4a2fd53f29dc5e9526674506583c194stuff.cljc
harshp8l/deep-learning-lang-detection
84
(ns state.stuff (:require [reveal.clj.code-sample :as c])) (def concerns [:section [:h2 "Separation of Concerns"] [:ul [:li "Data"] [:li "Functions"] [:li "State Management"] [:li "UI/UX"]]]) (def atomic-bridges [:section [:h2 "Atomic Bridges"] [:ul [:li "Clojure atoms, agents, and refs should manage all state"] [:li "add-watch is your friend"] [:li "They are the bridge"] [:li "All interactions are with the refs"] [:li "Compared to beans' complexity"]]]) (def data [:section [:h2 "Data is King"] [:ul [:li "Model everything as data"] [:li "Clojure Data Structures" [:ul [:li "Heterogeneous"] [:li "Nestable"] [:li "Common interfaces"]]]]]) (def whats-it-about-oop [:section [:h2 "Object Oriented Programming"] [:h3 "A Familiar Paradigm"] [:ul [:li "Objects contain state in the form of fields"] [:li "Fields are generally mutable (setters)"] [:li "They are often observable or observed (e.g. Beans, PCLs, etc.)"] [:li "Wiring all of these items up produces a program"]]]) (def whats-it-about-fp [:section [:h2 "Functional Program"] [:h3 "A Growingly Popular Paradigm"] [:ul [:li "Computation is modeled as the application of functions to values"] [:li "Values = no mutable state"] [:li "To those new to FP, this makes NO sense"] [:li "How can you do anything useful if nothing changes?"]]]) ;;$$ are not inline (def equations [:section [:p "$${dR\\over dt} = \\alpha R - \\beta R F$$"] [:p "$$f(x) = sin(x)$$"] [:p "This is an equation \\({dR\\over dt} = \\alpha R - \\beta R F\\) that is inline."]]) (def functions [:section [:p "$${dR\\over dt} = \\alpha R - \\beta R F$$"] [:p "This is an equation \\({dR\\over dt} = \\alpha R - \\beta R F\\) that is inline."]]) (def code [:section [:h2 "Code"] (c/code-block "src/cljc/state/test.clj")]) (def scala-the-good [:section [:h2 "Scala"] [:ul [:li "Introduced to Scala ~2009"] [:li "Excellent bridge language" [:ol [:li "Scala as Java"] [:li "Scala immutable collections"] [:li "Scala collection operations"] [:li "Functions everywhere"]]]]]) (def scala-the-bad [:section [:h2 "Scala: Questions"] [:ul [:li "How do I do heterogeneous collections?"] [:li "How do I modify nested value types (case classes)?"] [:li "How do I manage global application state?"]]]) (def canvas [:section [:h2 "Teaser"] [:ul {:style "float:left;width:50%;" } [:li "Flocking Behaviors"] [:li "Based on Craig Reynold's Flocking Algorithms"] [:li "Stateless*"] [:li "Stick around to see how it's done"]] [:canvas {:id "flocking-canvas" :style "float:right;width:50%;" }] [:script { :type "text/javascript" :src "js/flocking.js"}] [:script { :type "text/javascript" } "flocking.game_launcher.launch_app(document.getElementById(\"flocking-canvas\"), 400, 400, 20);"] ]) (def predator-prey [:section [:h2 "Stateless Predator Prey"] [:div {:style "float:left;width:400px;" } [:div [:small [:label { :style "display: inline-block; width: 250px;" } "Initial Prey Population"]] [:input {:id "prey-population-slider" :type "range" :min 0 :max 500 :step 1 }]] [:div [:small [:label { :style "display: inline-block; width: 250px;" } "Initial Predator Population"]] [:input {:id "predator-population-slider" :type "range" :min 0 :max 500 :step 1 }]] [:div [:small [:label { :style "display: inline-block; width: 250px;" } "Reproduction Rate"]] [:input {:id "reproduction-rate-slider" :type "range" :min 0 :max 500 :step 1 }]] [:div [:small [:label { :style "display: inline-block; width: 250px;" } "Predation Rate"]] [:input {:id "predation-rate-slider" :type "range" :min 0 :max 500 :step 1 }]] [:div [:small [:label { :style "display: inline-block; width: 250px;" } "Growth Rate"]] [:input {:id "growth-rate-slider" :type "range" :min 0 :max 500 :step 1 }]] [:div [:small [:label { :style "display: inline-block; width: 250px;" } "Death Rate"]] [:input {:id "death-rate-slider" :type "range" :min 0 :max 500 :step 1 }]]] [:canvas {:id "rk-canvas" :width 400 :height 400 :style "border:1px solid #000000;" }] [:script { :type "text/javascript" :src "js/rk.js"}] [:script { :type "text/javascript" } "numerics.canvasui.init(document.getElementById(\"rk-canvas\"));"]])
97237
(ns state.stuff (:require [reveal.clj.code-sample :as c])) (def concerns [:section [:h2 "Separation of Concerns"] [:ul [:li "Data"] [:li "Functions"] [:li "State Management"] [:li "UI/UX"]]]) (def atomic-bridges [:section [:h2 "Atomic Bridges"] [:ul [:li "Clojure atoms, agents, and refs should manage all state"] [:li "add-watch is your friend"] [:li "They are the bridge"] [:li "All interactions are with the refs"] [:li "Compared to beans' complexity"]]]) (def data [:section [:h2 "Data is King"] [:ul [:li "Model everything as data"] [:li "Clojure Data Structures" [:ul [:li "Heterogeneous"] [:li "Nestable"] [:li "Common interfaces"]]]]]) (def whats-it-about-oop [:section [:h2 "Object Oriented Programming"] [:h3 "A Familiar Paradigm"] [:ul [:li "Objects contain state in the form of fields"] [:li "Fields are generally mutable (setters)"] [:li "They are often observable or observed (e.g. Beans, PCLs, etc.)"] [:li "Wiring all of these items up produces a program"]]]) (def whats-it-about-fp [:section [:h2 "Functional Program"] [:h3 "A Growingly Popular Paradigm"] [:ul [:li "Computation is modeled as the application of functions to values"] [:li "Values = no mutable state"] [:li "To those new to FP, this makes NO sense"] [:li "How can you do anything useful if nothing changes?"]]]) ;;$$ are not inline (def equations [:section [:p "$${dR\\over dt} = \\alpha R - \\beta R F$$"] [:p "$$f(x) = sin(x)$$"] [:p "This is an equation \\({dR\\over dt} = \\alpha R - \\beta R F\\) that is inline."]]) (def functions [:section [:p "$${dR\\over dt} = \\alpha R - \\beta R F$$"] [:p "This is an equation \\({dR\\over dt} = \\alpha R - \\beta R F\\) that is inline."]]) (def code [:section [:h2 "Code"] (c/code-block "src/cljc/state/test.clj")]) (def scala-the-good [:section [:h2 "Scala"] [:ul [:li "Introduced to Scala ~2009"] [:li "Excellent bridge language" [:ol [:li "Scala as Java"] [:li "Scala immutable collections"] [:li "Scala collection operations"] [:li "Functions everywhere"]]]]]) (def scala-the-bad [:section [:h2 "Scala: Questions"] [:ul [:li "How do I do heterogeneous collections?"] [:li "How do I modify nested value types (case classes)?"] [:li "How do I manage global application state?"]]]) (def canvas [:section [:h2 "Teaser"] [:ul {:style "float:left;width:50%;" } [:li "Flocking Behaviors"] [:li "Based on <NAME>'s Flocking Algorithms"] [:li "Stateless*"] [:li "Stick around to see how it's done"]] [:canvas {:id "flocking-canvas" :style "float:right;width:50%;" }] [:script { :type "text/javascript" :src "js/flocking.js"}] [:script { :type "text/javascript" } "flocking.game_launcher.launch_app(document.getElementById(\"flocking-canvas\"), 400, 400, 20);"] ]) (def predator-prey [:section [:h2 "Stateless Predator Prey"] [:div {:style "float:left;width:400px;" } [:div [:small [:label { :style "display: inline-block; width: 250px;" } "Initial Prey Population"]] [:input {:id "prey-population-slider" :type "range" :min 0 :max 500 :step 1 }]] [:div [:small [:label { :style "display: inline-block; width: 250px;" } "Initial Predator Population"]] [:input {:id "predator-population-slider" :type "range" :min 0 :max 500 :step 1 }]] [:div [:small [:label { :style "display: inline-block; width: 250px;" } "Reproduction Rate"]] [:input {:id "reproduction-rate-slider" :type "range" :min 0 :max 500 :step 1 }]] [:div [:small [:label { :style "display: inline-block; width: 250px;" } "Predation Rate"]] [:input {:id "predation-rate-slider" :type "range" :min 0 :max 500 :step 1 }]] [:div [:small [:label { :style "display: inline-block; width: 250px;" } "Growth Rate"]] [:input {:id "growth-rate-slider" :type "range" :min 0 :max 500 :step 1 }]] [:div [:small [:label { :style "display: inline-block; width: 250px;" } "Death Rate"]] [:input {:id "death-rate-slider" :type "range" :min 0 :max 500 :step 1 }]]] [:canvas {:id "rk-canvas" :width 400 :height 400 :style "border:1px solid #000000;" }] [:script { :type "text/javascript" :src "js/rk.js"}] [:script { :type "text/javascript" } "numerics.canvasui.init(document.getElementById(\"rk-canvas\"));"]])
true
(ns state.stuff (:require [reveal.clj.code-sample :as c])) (def concerns [:section [:h2 "Separation of Concerns"] [:ul [:li "Data"] [:li "Functions"] [:li "State Management"] [:li "UI/UX"]]]) (def atomic-bridges [:section [:h2 "Atomic Bridges"] [:ul [:li "Clojure atoms, agents, and refs should manage all state"] [:li "add-watch is your friend"] [:li "They are the bridge"] [:li "All interactions are with the refs"] [:li "Compared to beans' complexity"]]]) (def data [:section [:h2 "Data is King"] [:ul [:li "Model everything as data"] [:li "Clojure Data Structures" [:ul [:li "Heterogeneous"] [:li "Nestable"] [:li "Common interfaces"]]]]]) (def whats-it-about-oop [:section [:h2 "Object Oriented Programming"] [:h3 "A Familiar Paradigm"] [:ul [:li "Objects contain state in the form of fields"] [:li "Fields are generally mutable (setters)"] [:li "They are often observable or observed (e.g. Beans, PCLs, etc.)"] [:li "Wiring all of these items up produces a program"]]]) (def whats-it-about-fp [:section [:h2 "Functional Program"] [:h3 "A Growingly Popular Paradigm"] [:ul [:li "Computation is modeled as the application of functions to values"] [:li "Values = no mutable state"] [:li "To those new to FP, this makes NO sense"] [:li "How can you do anything useful if nothing changes?"]]]) ;;$$ are not inline (def equations [:section [:p "$${dR\\over dt} = \\alpha R - \\beta R F$$"] [:p "$$f(x) = sin(x)$$"] [:p "This is an equation \\({dR\\over dt} = \\alpha R - \\beta R F\\) that is inline."]]) (def functions [:section [:p "$${dR\\over dt} = \\alpha R - \\beta R F$$"] [:p "This is an equation \\({dR\\over dt} = \\alpha R - \\beta R F\\) that is inline."]]) (def code [:section [:h2 "Code"] (c/code-block "src/cljc/state/test.clj")]) (def scala-the-good [:section [:h2 "Scala"] [:ul [:li "Introduced to Scala ~2009"] [:li "Excellent bridge language" [:ol [:li "Scala as Java"] [:li "Scala immutable collections"] [:li "Scala collection operations"] [:li "Functions everywhere"]]]]]) (def scala-the-bad [:section [:h2 "Scala: Questions"] [:ul [:li "How do I do heterogeneous collections?"] [:li "How do I modify nested value types (case classes)?"] [:li "How do I manage global application state?"]]]) (def canvas [:section [:h2 "Teaser"] [:ul {:style "float:left;width:50%;" } [:li "Flocking Behaviors"] [:li "Based on PI:NAME:<NAME>END_PI's Flocking Algorithms"] [:li "Stateless*"] [:li "Stick around to see how it's done"]] [:canvas {:id "flocking-canvas" :style "float:right;width:50%;" }] [:script { :type "text/javascript" :src "js/flocking.js"}] [:script { :type "text/javascript" } "flocking.game_launcher.launch_app(document.getElementById(\"flocking-canvas\"), 400, 400, 20);"] ]) (def predator-prey [:section [:h2 "Stateless Predator Prey"] [:div {:style "float:left;width:400px;" } [:div [:small [:label { :style "display: inline-block; width: 250px;" } "Initial Prey Population"]] [:input {:id "prey-population-slider" :type "range" :min 0 :max 500 :step 1 }]] [:div [:small [:label { :style "display: inline-block; width: 250px;" } "Initial Predator Population"]] [:input {:id "predator-population-slider" :type "range" :min 0 :max 500 :step 1 }]] [:div [:small [:label { :style "display: inline-block; width: 250px;" } "Reproduction Rate"]] [:input {:id "reproduction-rate-slider" :type "range" :min 0 :max 500 :step 1 }]] [:div [:small [:label { :style "display: inline-block; width: 250px;" } "Predation Rate"]] [:input {:id "predation-rate-slider" :type "range" :min 0 :max 500 :step 1 }]] [:div [:small [:label { :style "display: inline-block; width: 250px;" } "Growth Rate"]] [:input {:id "growth-rate-slider" :type "range" :min 0 :max 500 :step 1 }]] [:div [:small [:label { :style "display: inline-block; width: 250px;" } "Death Rate"]] [:input {:id "death-rate-slider" :type "range" :min 0 :max 500 :step 1 }]]] [:canvas {:id "rk-canvas" :width 400 :height 400 :style "border:1px solid #000000;" }] [:script { :type "text/javascript" :src "js/rk.js"}] [:script { :type "text/javascript" } "numerics.canvasui.init(document.getElementById(\"rk-canvas\"));"]])
[ { "context": " {\n :error-message \"I'm sorry Dave,\\nI'm afraid I can't do that.\"\n })\n ", "end": 849, "score": 0.9962844848632812, "start": 845, "tag": "NAME", "value": "Dave" } ]
desktop/src-common/brain_gain_or_drain/screens/error.clj
RAMart/brain-gain-or-drain
0
(ns brain-gain-or-drain.screens.error (:refer-clojure :exclude [bound?]) (:require [play-clj.core :refer :all] [brain-gain-or-drain.entity :refer :all])) (defn- layout [screen-width screen-height entities] (for [entity entities] (case (:type entity) :error-message (assoc entity :x (-> screen-width (- (:width entity)) (/ 2)) :y (-> screen-height (- (:height entity)) (/ 2))) entity))) (defscreen error-screen :on-show (fn [screen entities] (update! screen :camera (orthographic) :renderer (stage) :resources { :error-message "I'm sorry Dave,\nI'm afraid I can't do that." }) [{:type :error-message :color :white :align :center}]) :on-render (fn [screen entities] (clear! 0.75 0 0 1) (->> entities (bind-entities (:resources screen)) (layout (stage! screen :get-width) (stage! screen :get-height)) (render! screen))) :on-resize (fn [screen entities] (width! screen (-> :width game (/ 2)))))
51896
(ns brain-gain-or-drain.screens.error (:refer-clojure :exclude [bound?]) (:require [play-clj.core :refer :all] [brain-gain-or-drain.entity :refer :all])) (defn- layout [screen-width screen-height entities] (for [entity entities] (case (:type entity) :error-message (assoc entity :x (-> screen-width (- (:width entity)) (/ 2)) :y (-> screen-height (- (:height entity)) (/ 2))) entity))) (defscreen error-screen :on-show (fn [screen entities] (update! screen :camera (orthographic) :renderer (stage) :resources { :error-message "I'm sorry <NAME>,\nI'm afraid I can't do that." }) [{:type :error-message :color :white :align :center}]) :on-render (fn [screen entities] (clear! 0.75 0 0 1) (->> entities (bind-entities (:resources screen)) (layout (stage! screen :get-width) (stage! screen :get-height)) (render! screen))) :on-resize (fn [screen entities] (width! screen (-> :width game (/ 2)))))
true
(ns brain-gain-or-drain.screens.error (:refer-clojure :exclude [bound?]) (:require [play-clj.core :refer :all] [brain-gain-or-drain.entity :refer :all])) (defn- layout [screen-width screen-height entities] (for [entity entities] (case (:type entity) :error-message (assoc entity :x (-> screen-width (- (:width entity)) (/ 2)) :y (-> screen-height (- (:height entity)) (/ 2))) entity))) (defscreen error-screen :on-show (fn [screen entities] (update! screen :camera (orthographic) :renderer (stage) :resources { :error-message "I'm sorry PI:NAME:<NAME>END_PI,\nI'm afraid I can't do that." }) [{:type :error-message :color :white :align :center}]) :on-render (fn [screen entities] (clear! 0.75 0 0 1) (->> entities (bind-entities (:resources screen)) (layout (stage! screen :get-width) (stage! screen :get-height)) (render! screen))) :on-resize (fn [screen entities] (width! screen (-> :width game (/ 2)))))
[ { "context": "ent position (for a movement check)\n; \n; HIVE - by John Yianni\n; \"A Game Buzzing With Possibilities\"\n; http:", "end": 586, "score": 0.9998430013656616, "start": 575, "tag": "NAME", "value": "John Yianni" }, { "context": "mobile by another Pillbug.\n\n; Clarification from John Yianni: The Pillbug using its special ability does not\n;", "end": 9345, "score": 0.9996131658554077, "start": 9334, "tag": "NAME", "value": "John Yianni" }, { "context": "has been forbidden for both black and white.\n; John Yianni supports this change, which is intended to elimin", "end": 13975, "score": 0.9985997080802917, "start": 13964, "tag": "NAME", "value": "John Yianni" } ]
src/hive/core/domain/rules.clj
Trylobot/hive-clj
2
(ns hive.core.domain.rules) (require '[clojure.set :as set]) (use 'hive.core.util) (require '[hive.core.domain.position :as position]) (require '[hive.core.domain.piece :as piece]) (require '[hive.core.domain.range :as range]) (require '[hive.core.domain.board :as board]) (require '[hive.core.domain.turn :as turn]) ; rules ; ; this module is used to represent the rules of hive. ; it can provide a list of valid end positions for a piece, ; given a board state (for a placement check) ; or a board state and a current position (for a movement check) ; ; HIVE - by John Yianni ; "A Game Buzzing With Possibilities" ; http://gen42.com ; ; Playing the Game ; Play begins with one player placing a piece from their hand to the centre of the table ; and the next player joining one of their own pieces to it edge to edge. Players then ; take turns to either place or move any one of their pieces. ; ; The Hive ; The pieces in play define the playing surface, known as the Hive. ; Placing ; A new piece can be introduced into the game at any time. However, with the exception ; of the first piece placed by each player, pieces may not be placed next to a piece of ; the opponent's colour. It is possible to win the game without placing all your pieces, ; but once a piece has been placed, it cannot be removed. ; ; Placing your Queen Bee ; Your Queen Bee can be placed at any time from your first to your fourth turn. You ; must place your Queen Bee on your fourth turn if you have not placed it before. (defn force-queen-placement? "returns true if queen must be placed this turn" [color board turn-number] (let [num-queens (count (board/search-pieces board color :queen-bee)) is-fourth-turn (or (= 6 turn-number) (= 7 turn-number))] (and is-fourth-turn (= 0 num-queens)) )) ; http://boardgamegeek.com/wiki/page/Hive_FAQ ; You cannot place your queen as your first move. (defn allow-queen-placement? "returns true if queen may be placed this turn" [turn-number] (> turn-number 1) ) ; Moving ; Once your Queen Bee has been placed (but not before), you can decide whether to use ; each turn after that to place another piece or to move one of the pieces that have ; already been placed. Each creature has its own way of moving. When moving, it is ; possible to move pieces to a position where they touch one or more of your opponent's ; pieces. ; All pieces must always touch at least one other piece. If a piece is the only ; connection between two parts of the Hive, it may not be moved. (See 'One Hive rule') (defn any-movement-allowed? "returns true if any movement is allowed, due to having placed a queen" [color board] (> (count (board/search-pieces board color :queen-bee)) 0) ) ; The End of the Game ; The game ends as soon as one Queen Bee is completely surrounded by pieces of any colour. ; The person whose Queen Bee is surrounded loses the game, unless the last piece to ; surround their Queen Bee also completes the surrounding of the other Queen Bee. In that ; case the game is drawn. A draw may also be agreed if both players are in a position where ; they are forced to move the same two pieces over and over again, without any possibility ; of the stalemate being resolved. (defn game-over? "describes which end state, if any, has been reached" [board] (let [num-directions (count position/direction-vectors) queens (map (fn [piece] (let [occupied-adjacencies (board/lookup-occupied-adjacencies board (:position piece))] (assoc piece :surrounded (= num-directions (count occupied-adjacencies))) )) (board/search-pieces board nil :queen-bee)) color-test (fn [color] #(= color (:color (:piece %)))) white (first (filter (color-test :white) queens)) black (first (filter (color-test :black) queens))] (cond (and (:surrounded white) (:surrounded black)) {:game-over true, :is-draw true, :winner nil} (:surrounded white) {:game-over true, :is-draw false, :winner :black} (:surrounded black) {:game-over true, :is-draw false, :winner :white} :else {:game-over false, :is-draw false, :winner nil}) )) ; Queen Bee ; The Queen Bee can move only one space per turn. (defn find-valid-movement-queen-bee "get movement for position by the rules of the queen bee" [board position] (board/lookup-adjacent-slide-positions board position) ) ; Beetle ; The Beetle, like the Queen Bee, moves only space per turn around the Hive, but ; can also move on top of the Hive. A piece with a beetle on top of it is unable ; to move and for the purposes of the placing rules, the stack takes on the ; colour of the Beetle. ; ; From its position on top of the Hive, the Beetle can move from piece to piece ; across the top of the Hive. It can also drop into spaces that are surrounded ; and therefore not accessible to most other creatures. ; ; The only way to block a Beetle that is on top of the Hive is to move another ; Beetle on top of it. All Beetles and Mosquitoes can be stacked on top of each ; other. ; ; When it is first placed, the Beetle is placed in the same way as all the other ; pieces. It cannot be placed directly on top of the Hive, even though it can ; be moved there later. ; ; http://www.boardgamegeek.com/wiki/page/Hive_FAQ#toc8 ; Q: Are beetles affected by the Freedom To Move rule? ; A: Yes. (albeit in a different way): Beetles cannot slide through "gates" (defn find-valid-movement-beetle "get movement for position by the rules of the beetle" [board position] (set/union (board/lookup-adjacent-slide-positions board position) (board/lookup-adjacent-climb-positions board position) ) ) ; Grasshopper ; The Grasshopper does not move around the outside of the Hive like the other ; creatures. Instead it jumps from its space over any number of pieces (but ; at least one) to the next unoccupied space along a straight row of joined ; pieces. ; ; This gives it the advantage of being able to fill in a space which is ; surrounded by other pieces. (defn find-valid-movement-grasshopper "get movement for position by the rules of the grasshopper" [board position] (let [adjacent-positions (board/lookup-adjacent-positions board position) free-spaces (map (fn [direction] (board/find-free-space-in-direction board position direction)) (keys adjacent-positions))] free-spaces )) ; Spider ; The Spider moves three spaces per turn - no more, no less. It must move in a ; direct path and cannot backtrack on itself. It may only move around pieces ; that it is in direct contact with on each step of its move. It may not move ; across to a piece that it is not in direct contact with. (defn find-valid-movement-spider "get movement for position by the rules of the spider" [board position] (board/find-unique-paths-matching-conditions board position 3 0)) ; Soldier Ant ; The Soldier Ant can move from its position to any other position around the ; Hive provided the restrictions are adhered to. (defn find-valid-movement-soldier-ant "get movement for position by the rules of the soldier-ant" [board position] (board/lookup-slide-destinations board position)) ; Ladybug ; The Ladybug moves three spaces; two on top of the Hive, and then one down. ; It must move exactly two on top of the Hive and then move one down on its ; last move. It may not move around the outside of the Hive and may not end ; its movement on top of the Hive. Even though it cannot block by landing ; on top of other pieces like the Beetle, it can move into or out of surrounded ; spaces. It also has the advantage of being much faster. (defn find-valid-movement-ladybug "get movement for position by the rules of the ladybug" [board position] (let [distance-spec 3 height-spec { "1-2" {:min 1, :max :infinity} "3" 0 } valid-paths (board/find-unique-paths-matching-conditions board position distance-spec height-spec )] (set (keys valid-paths)) )) ; Pillbug ; The Pillbug moves like the Queen Bee - one space at a time - but it has a ; special ability that it may use instead of moving. This ability allows the ; Pillbug to move an adjacent unstacked piece (whether friend or enemy) two ; spaces: up onto the pillbug itself, then down into an empty space adjacent ; to itself. Some exceptions for this ability: ; - The Pillbug may not move the piece most recently moved by the opponent. ; - The Pillbug may not move any piece in a stack of pieces. ; - The Pillbug may not move a piece if it splits the hive (One Hive rule) ; - The Pillbug may not move a piece through a too-narrow gap of stacked ; pieces (Freedom to Move rule) ; Any piece which physically moved (directly or by the Pillbug) is rendered ; immobile on the next player's turn; it cannot move or be moved, nor use its ; special ability. The Mosquito can mimic either the movement or special ; ability of the Pillbug, even when the Pillbug it is touching has been rendered ; immobile by another Pillbug. ; Clarification from John Yianni: The Pillbug using its special ability does not ; count as "movement" from the perspective of an opposing player's Pillbug, and ; thus does not grant it immunity from being moved by the opposing Pillbug. Only ; physically moved pieces have such protection. ; Further Clarification: A stunned Pillbug (one that was just moved by a Pillbug) ; cannot use its special ability. (defn find-valid-movement-pillbug "get movement for position by the rules of the pillbug" [board position] (board/lookup-adjacent-slide-positions board position) ) (defn find-valid-special-abilities-pillbug "get special abilities for position by the rules of the pillbug" [board position turn-history] (let [adjacencies (board/lookup-adjacent-positions board position) categorized-adjacencies (reduce (fn [result [direction adjacency]] (let [stack-cw (get adjacencies (position/rotation-clockwise direction)) stack-ccw (get adjacencies (position/rotation-counter-clockwise direction))] (if (and (<= (:height stack-cw) 1) (<= (:height stack-ccw))) ; piece not sliding through a "gate" (cond (== (:height adjacency) 0) ; empty space (update-in result [:free] conj (:position adjacency)) (and (== (:height adjacency) 1) (board/contiguous? (board/remove-piece board (:position adjacency)))) ; single piece (update-in result [:occupied] conj (:position adjacency)) :else result) result) )) {:free #{}, :occupied #{}} adjacencies) free-adjacencies (:free categorized-adjacencies) occupied-adjacencies (:occupied categorized-adjacencies) last-turn (last turn-history) valid-occupied-adjacencies (filter #(not= (:destination last-turn) %) occupied-adjacencies)] (zipmap valid-occupied-adjacencies (repeat (count valid-occupied-adjacencies) free-adjacencies)) )) ; Mosquito ; The Mosquito is placed in the same way as the other pieces. Once in play, the ; Mosquito takes on the movement characteristics of any creature it touches at ; the time, including your opponents', thus changing its characteristics ; throughout the game. ; Exception: if moved as a Beetle on top of the Hive, it continues to move as ; a Beetle until it climbs down from the Hive. If when on the ground level it ; is next to a stacked Beetle, it may move as a Beetle and not the piece below ; the Beetle. If touching another Mosquito only (including a stacked Mosquito) ; and no other piece, it may not move. (defn find-valid-movement-mosquito "get movement for position by the rules of the mosquito" [board position] (if (> (board/lookup-piece-stack-height position) 1) ; mosquito is atop the hive; move like a beetle (find-valid-movement-beetle board position) ; mosquito is at ground-level; move according to adjacent piece types (set (mapcat identity (map (fn [piece-type] (case piece-type :queen-bee (find-valid-movement-queen-bee board position) :beetle (find-valid-movement-beetle board position) :grasshopper (find-valid-movement-grasshopper board position) :spider (find-valid-movement-spider board position) :soldier-ant (find-valid-movement-soldier-ant board position) :mosquito nil :ladybug (find-valid-movement-ladybug board position) :pillbug (find-valid-movement-pillbug board position) nil )) (board/lookup-adjacent-piece-types board position)))) )) (defn find-valid-special-abilities-mosquito "get special abilities for position by the rules of the mosquito" [board position turn-history] (if (> (board/lookup-piece-stack-height position) 1) nil (set (mapcat identity (map (fn [piece-type] (case piece-type :pillbug (find-valid-special-abilities-pillbug board position) nil )) (board/lookup-adjacent-piece-types board position)))) )) ; Unable to Move or Place ; If a player can not place a new piece or move an existing piece, the turn passes ; to their opponent who then takes their turn again. The game continues in this way ; until the player is able to move or place one of their pieces, or until their ; Queen Bee is surrounded. ; http://boardspace.net/english/about_hive.html ; Rules Change: at boardspace the "Queen" opening has been forbidden for both black and white. ; John Yianni supports this change, which is intended to eliminate the problem of excess draws in "queen opening" games. (defn find-valid-placement-positions "returns the set of valid placement positions for the given color" [color board turn-number] (board/search-free-spaces board (if (> turn-number 1) color nil)) ) ; One Hive rule ; The pieces in play must be linked at all times. At no time can you leave a piece ; stranded (not joined to the Hive) or separate the Hive in two. ; Freedom to Move ; The creatures can only move in a sliding movement. If a piece is surrounded to ; the point that it can no longer physically slide out of its position, it may ; not be moved. The only exceptions are the Grasshopper (which jumps into or out ; of a space), the Beetle and Ladybug (which climb up and down) and the Mosquito ; (which can mimic one of the three). Similarly, no piece may move into a space ; that it cannot physically slide into. ; When first introduced to the game, a piece may be placed into a space that is ; surrounded as long as it does not violate any of the placing rules, in particular ; the rule about pieces not being allowed to touch pieces of the other colour when ; they are first placed. (defn find-valid-movement "returns all valid moves for the piece at the given position (if stacked, top of stack)" [board position] (if (board/contiguous? (board/remove-piece board position)) (let [piece-type (:type (board/lookup-piece board position))] (case piece-type :queen-bee (find-valid-movement-queen-bee board position) :beetle (find-valid-movement-beetle board position) :grasshopper (find-valid-movement-grasshopper board position) :spider (find-valid-movement-spider board position) :soldier-ant (find-valid-movement-soldier-ant board position) :mosquito (find-valid-movement-mosquito board position) :ladybug (find-valid-movement-ladybug board position) :pillbug (find-valid-movement-pillbug board position) )) nil) ) (defn find-valid-special-abilities "" [board position turn-history] (let [piece-type (:type (board/lookup-piece board position))] (case piece-type :queen-bee nil :beetle nil :grasshopper nil :spider nil :soldier-ant nil :mosquito (find-valid-special-abilities-mosquito board position turn-history) :ladybug nil :pillbug (find-valid-special-abilities-pillbug board position turn-history) )) ) ; TODO: define a game-state as a schema (defn lookup-possible-turns "given a full game state, return all possible next turns" [color board hand turn-number turn-history] (if (game-over? board) nil (let [last-turn (last turn-history) owned-piece-positions (board/search-top-pieces board color nil) possible-placement-positions (find-valid-placement-positions color board turn-number) possible-placement-piece-types (if (force-queen-placement? color board turn-number) #{:queen-bee} (if (allow-queen-placement? turn-number) (set (keys hand)) (set (remove #{:queen-bee} (keys hand))) )) possible-piece-actions (if (any-movement-allowed? color board) (filter #(second %) ; toss out any positions mapped to falsey values (zipmap owned-piece-positions (map (fn [position] (if (and (= :special-ability (:turn-type last-turn)) (= :pillbug (:type (board/lookup-piece board (:ability-user last-turn)))) (= position (:destination last-turn) )) ; piece is not eligible for movement because it is stunned by pillbug's special ability nil ; piece at <position> has potential movement or special abilities of its own { :movement (find-valid-movement board position) :special-abilities (find-valid-special-abilities board position turn-history) } )) owned-piece-positions) )) nil ) possible-forfeit (and (empty? possible-placement-positions) (empty? possible-placement-piece-types) (empty? possible-piece-actions)) ] { :placement-positions possible-placement-positions :placement-piece-types possible-placement-piece-types :existing-piece-actions possible-piece-actions :must-only-forfeit possible-forfeit } )) )
24830
(ns hive.core.domain.rules) (require '[clojure.set :as set]) (use 'hive.core.util) (require '[hive.core.domain.position :as position]) (require '[hive.core.domain.piece :as piece]) (require '[hive.core.domain.range :as range]) (require '[hive.core.domain.board :as board]) (require '[hive.core.domain.turn :as turn]) ; rules ; ; this module is used to represent the rules of hive. ; it can provide a list of valid end positions for a piece, ; given a board state (for a placement check) ; or a board state and a current position (for a movement check) ; ; HIVE - by <NAME> ; "A Game Buzzing With Possibilities" ; http://gen42.com ; ; Playing the Game ; Play begins with one player placing a piece from their hand to the centre of the table ; and the next player joining one of their own pieces to it edge to edge. Players then ; take turns to either place or move any one of their pieces. ; ; The Hive ; The pieces in play define the playing surface, known as the Hive. ; Placing ; A new piece can be introduced into the game at any time. However, with the exception ; of the first piece placed by each player, pieces may not be placed next to a piece of ; the opponent's colour. It is possible to win the game without placing all your pieces, ; but once a piece has been placed, it cannot be removed. ; ; Placing your Queen Bee ; Your Queen Bee can be placed at any time from your first to your fourth turn. You ; must place your Queen Bee on your fourth turn if you have not placed it before. (defn force-queen-placement? "returns true if queen must be placed this turn" [color board turn-number] (let [num-queens (count (board/search-pieces board color :queen-bee)) is-fourth-turn (or (= 6 turn-number) (= 7 turn-number))] (and is-fourth-turn (= 0 num-queens)) )) ; http://boardgamegeek.com/wiki/page/Hive_FAQ ; You cannot place your queen as your first move. (defn allow-queen-placement? "returns true if queen may be placed this turn" [turn-number] (> turn-number 1) ) ; Moving ; Once your Queen Bee has been placed (but not before), you can decide whether to use ; each turn after that to place another piece or to move one of the pieces that have ; already been placed. Each creature has its own way of moving. When moving, it is ; possible to move pieces to a position where they touch one or more of your opponent's ; pieces. ; All pieces must always touch at least one other piece. If a piece is the only ; connection between two parts of the Hive, it may not be moved. (See 'One Hive rule') (defn any-movement-allowed? "returns true if any movement is allowed, due to having placed a queen" [color board] (> (count (board/search-pieces board color :queen-bee)) 0) ) ; The End of the Game ; The game ends as soon as one Queen Bee is completely surrounded by pieces of any colour. ; The person whose Queen Bee is surrounded loses the game, unless the last piece to ; surround their Queen Bee also completes the surrounding of the other Queen Bee. In that ; case the game is drawn. A draw may also be agreed if both players are in a position where ; they are forced to move the same two pieces over and over again, without any possibility ; of the stalemate being resolved. (defn game-over? "describes which end state, if any, has been reached" [board] (let [num-directions (count position/direction-vectors) queens (map (fn [piece] (let [occupied-adjacencies (board/lookup-occupied-adjacencies board (:position piece))] (assoc piece :surrounded (= num-directions (count occupied-adjacencies))) )) (board/search-pieces board nil :queen-bee)) color-test (fn [color] #(= color (:color (:piece %)))) white (first (filter (color-test :white) queens)) black (first (filter (color-test :black) queens))] (cond (and (:surrounded white) (:surrounded black)) {:game-over true, :is-draw true, :winner nil} (:surrounded white) {:game-over true, :is-draw false, :winner :black} (:surrounded black) {:game-over true, :is-draw false, :winner :white} :else {:game-over false, :is-draw false, :winner nil}) )) ; Queen Bee ; The Queen Bee can move only one space per turn. (defn find-valid-movement-queen-bee "get movement for position by the rules of the queen bee" [board position] (board/lookup-adjacent-slide-positions board position) ) ; Beetle ; The Beetle, like the Queen Bee, moves only space per turn around the Hive, but ; can also move on top of the Hive. A piece with a beetle on top of it is unable ; to move and for the purposes of the placing rules, the stack takes on the ; colour of the Beetle. ; ; From its position on top of the Hive, the Beetle can move from piece to piece ; across the top of the Hive. It can also drop into spaces that are surrounded ; and therefore not accessible to most other creatures. ; ; The only way to block a Beetle that is on top of the Hive is to move another ; Beetle on top of it. All Beetles and Mosquitoes can be stacked on top of each ; other. ; ; When it is first placed, the Beetle is placed in the same way as all the other ; pieces. It cannot be placed directly on top of the Hive, even though it can ; be moved there later. ; ; http://www.boardgamegeek.com/wiki/page/Hive_FAQ#toc8 ; Q: Are beetles affected by the Freedom To Move rule? ; A: Yes. (albeit in a different way): Beetles cannot slide through "gates" (defn find-valid-movement-beetle "get movement for position by the rules of the beetle" [board position] (set/union (board/lookup-adjacent-slide-positions board position) (board/lookup-adjacent-climb-positions board position) ) ) ; Grasshopper ; The Grasshopper does not move around the outside of the Hive like the other ; creatures. Instead it jumps from its space over any number of pieces (but ; at least one) to the next unoccupied space along a straight row of joined ; pieces. ; ; This gives it the advantage of being able to fill in a space which is ; surrounded by other pieces. (defn find-valid-movement-grasshopper "get movement for position by the rules of the grasshopper" [board position] (let [adjacent-positions (board/lookup-adjacent-positions board position) free-spaces (map (fn [direction] (board/find-free-space-in-direction board position direction)) (keys adjacent-positions))] free-spaces )) ; Spider ; The Spider moves three spaces per turn - no more, no less. It must move in a ; direct path and cannot backtrack on itself. It may only move around pieces ; that it is in direct contact with on each step of its move. It may not move ; across to a piece that it is not in direct contact with. (defn find-valid-movement-spider "get movement for position by the rules of the spider" [board position] (board/find-unique-paths-matching-conditions board position 3 0)) ; Soldier Ant ; The Soldier Ant can move from its position to any other position around the ; Hive provided the restrictions are adhered to. (defn find-valid-movement-soldier-ant "get movement for position by the rules of the soldier-ant" [board position] (board/lookup-slide-destinations board position)) ; Ladybug ; The Ladybug moves three spaces; two on top of the Hive, and then one down. ; It must move exactly two on top of the Hive and then move one down on its ; last move. It may not move around the outside of the Hive and may not end ; its movement on top of the Hive. Even though it cannot block by landing ; on top of other pieces like the Beetle, it can move into or out of surrounded ; spaces. It also has the advantage of being much faster. (defn find-valid-movement-ladybug "get movement for position by the rules of the ladybug" [board position] (let [distance-spec 3 height-spec { "1-2" {:min 1, :max :infinity} "3" 0 } valid-paths (board/find-unique-paths-matching-conditions board position distance-spec height-spec )] (set (keys valid-paths)) )) ; Pillbug ; The Pillbug moves like the Queen Bee - one space at a time - but it has a ; special ability that it may use instead of moving. This ability allows the ; Pillbug to move an adjacent unstacked piece (whether friend or enemy) two ; spaces: up onto the pillbug itself, then down into an empty space adjacent ; to itself. Some exceptions for this ability: ; - The Pillbug may not move the piece most recently moved by the opponent. ; - The Pillbug may not move any piece in a stack of pieces. ; - The Pillbug may not move a piece if it splits the hive (One Hive rule) ; - The Pillbug may not move a piece through a too-narrow gap of stacked ; pieces (Freedom to Move rule) ; Any piece which physically moved (directly or by the Pillbug) is rendered ; immobile on the next player's turn; it cannot move or be moved, nor use its ; special ability. The Mosquito can mimic either the movement or special ; ability of the Pillbug, even when the Pillbug it is touching has been rendered ; immobile by another Pillbug. ; Clarification from <NAME>: The Pillbug using its special ability does not ; count as "movement" from the perspective of an opposing player's Pillbug, and ; thus does not grant it immunity from being moved by the opposing Pillbug. Only ; physically moved pieces have such protection. ; Further Clarification: A stunned Pillbug (one that was just moved by a Pillbug) ; cannot use its special ability. (defn find-valid-movement-pillbug "get movement for position by the rules of the pillbug" [board position] (board/lookup-adjacent-slide-positions board position) ) (defn find-valid-special-abilities-pillbug "get special abilities for position by the rules of the pillbug" [board position turn-history] (let [adjacencies (board/lookup-adjacent-positions board position) categorized-adjacencies (reduce (fn [result [direction adjacency]] (let [stack-cw (get adjacencies (position/rotation-clockwise direction)) stack-ccw (get adjacencies (position/rotation-counter-clockwise direction))] (if (and (<= (:height stack-cw) 1) (<= (:height stack-ccw))) ; piece not sliding through a "gate" (cond (== (:height adjacency) 0) ; empty space (update-in result [:free] conj (:position adjacency)) (and (== (:height adjacency) 1) (board/contiguous? (board/remove-piece board (:position adjacency)))) ; single piece (update-in result [:occupied] conj (:position adjacency)) :else result) result) )) {:free #{}, :occupied #{}} adjacencies) free-adjacencies (:free categorized-adjacencies) occupied-adjacencies (:occupied categorized-adjacencies) last-turn (last turn-history) valid-occupied-adjacencies (filter #(not= (:destination last-turn) %) occupied-adjacencies)] (zipmap valid-occupied-adjacencies (repeat (count valid-occupied-adjacencies) free-adjacencies)) )) ; Mosquito ; The Mosquito is placed in the same way as the other pieces. Once in play, the ; Mosquito takes on the movement characteristics of any creature it touches at ; the time, including your opponents', thus changing its characteristics ; throughout the game. ; Exception: if moved as a Beetle on top of the Hive, it continues to move as ; a Beetle until it climbs down from the Hive. If when on the ground level it ; is next to a stacked Beetle, it may move as a Beetle and not the piece below ; the Beetle. If touching another Mosquito only (including a stacked Mosquito) ; and no other piece, it may not move. (defn find-valid-movement-mosquito "get movement for position by the rules of the mosquito" [board position] (if (> (board/lookup-piece-stack-height position) 1) ; mosquito is atop the hive; move like a beetle (find-valid-movement-beetle board position) ; mosquito is at ground-level; move according to adjacent piece types (set (mapcat identity (map (fn [piece-type] (case piece-type :queen-bee (find-valid-movement-queen-bee board position) :beetle (find-valid-movement-beetle board position) :grasshopper (find-valid-movement-grasshopper board position) :spider (find-valid-movement-spider board position) :soldier-ant (find-valid-movement-soldier-ant board position) :mosquito nil :ladybug (find-valid-movement-ladybug board position) :pillbug (find-valid-movement-pillbug board position) nil )) (board/lookup-adjacent-piece-types board position)))) )) (defn find-valid-special-abilities-mosquito "get special abilities for position by the rules of the mosquito" [board position turn-history] (if (> (board/lookup-piece-stack-height position) 1) nil (set (mapcat identity (map (fn [piece-type] (case piece-type :pillbug (find-valid-special-abilities-pillbug board position) nil )) (board/lookup-adjacent-piece-types board position)))) )) ; Unable to Move or Place ; If a player can not place a new piece or move an existing piece, the turn passes ; to their opponent who then takes their turn again. The game continues in this way ; until the player is able to move or place one of their pieces, or until their ; Queen Bee is surrounded. ; http://boardspace.net/english/about_hive.html ; Rules Change: at boardspace the "Queen" opening has been forbidden for both black and white. ; <NAME> supports this change, which is intended to eliminate the problem of excess draws in "queen opening" games. (defn find-valid-placement-positions "returns the set of valid placement positions for the given color" [color board turn-number] (board/search-free-spaces board (if (> turn-number 1) color nil)) ) ; One Hive rule ; The pieces in play must be linked at all times. At no time can you leave a piece ; stranded (not joined to the Hive) or separate the Hive in two. ; Freedom to Move ; The creatures can only move in a sliding movement. If a piece is surrounded to ; the point that it can no longer physically slide out of its position, it may ; not be moved. The only exceptions are the Grasshopper (which jumps into or out ; of a space), the Beetle and Ladybug (which climb up and down) and the Mosquito ; (which can mimic one of the three). Similarly, no piece may move into a space ; that it cannot physically slide into. ; When first introduced to the game, a piece may be placed into a space that is ; surrounded as long as it does not violate any of the placing rules, in particular ; the rule about pieces not being allowed to touch pieces of the other colour when ; they are first placed. (defn find-valid-movement "returns all valid moves for the piece at the given position (if stacked, top of stack)" [board position] (if (board/contiguous? (board/remove-piece board position)) (let [piece-type (:type (board/lookup-piece board position))] (case piece-type :queen-bee (find-valid-movement-queen-bee board position) :beetle (find-valid-movement-beetle board position) :grasshopper (find-valid-movement-grasshopper board position) :spider (find-valid-movement-spider board position) :soldier-ant (find-valid-movement-soldier-ant board position) :mosquito (find-valid-movement-mosquito board position) :ladybug (find-valid-movement-ladybug board position) :pillbug (find-valid-movement-pillbug board position) )) nil) ) (defn find-valid-special-abilities "" [board position turn-history] (let [piece-type (:type (board/lookup-piece board position))] (case piece-type :queen-bee nil :beetle nil :grasshopper nil :spider nil :soldier-ant nil :mosquito (find-valid-special-abilities-mosquito board position turn-history) :ladybug nil :pillbug (find-valid-special-abilities-pillbug board position turn-history) )) ) ; TODO: define a game-state as a schema (defn lookup-possible-turns "given a full game state, return all possible next turns" [color board hand turn-number turn-history] (if (game-over? board) nil (let [last-turn (last turn-history) owned-piece-positions (board/search-top-pieces board color nil) possible-placement-positions (find-valid-placement-positions color board turn-number) possible-placement-piece-types (if (force-queen-placement? color board turn-number) #{:queen-bee} (if (allow-queen-placement? turn-number) (set (keys hand)) (set (remove #{:queen-bee} (keys hand))) )) possible-piece-actions (if (any-movement-allowed? color board) (filter #(second %) ; toss out any positions mapped to falsey values (zipmap owned-piece-positions (map (fn [position] (if (and (= :special-ability (:turn-type last-turn)) (= :pillbug (:type (board/lookup-piece board (:ability-user last-turn)))) (= position (:destination last-turn) )) ; piece is not eligible for movement because it is stunned by pillbug's special ability nil ; piece at <position> has potential movement or special abilities of its own { :movement (find-valid-movement board position) :special-abilities (find-valid-special-abilities board position turn-history) } )) owned-piece-positions) )) nil ) possible-forfeit (and (empty? possible-placement-positions) (empty? possible-placement-piece-types) (empty? possible-piece-actions)) ] { :placement-positions possible-placement-positions :placement-piece-types possible-placement-piece-types :existing-piece-actions possible-piece-actions :must-only-forfeit possible-forfeit } )) )
true
(ns hive.core.domain.rules) (require '[clojure.set :as set]) (use 'hive.core.util) (require '[hive.core.domain.position :as position]) (require '[hive.core.domain.piece :as piece]) (require '[hive.core.domain.range :as range]) (require '[hive.core.domain.board :as board]) (require '[hive.core.domain.turn :as turn]) ; rules ; ; this module is used to represent the rules of hive. ; it can provide a list of valid end positions for a piece, ; given a board state (for a placement check) ; or a board state and a current position (for a movement check) ; ; HIVE - by PI:NAME:<NAME>END_PI ; "A Game Buzzing With Possibilities" ; http://gen42.com ; ; Playing the Game ; Play begins with one player placing a piece from their hand to the centre of the table ; and the next player joining one of their own pieces to it edge to edge. Players then ; take turns to either place or move any one of their pieces. ; ; The Hive ; The pieces in play define the playing surface, known as the Hive. ; Placing ; A new piece can be introduced into the game at any time. However, with the exception ; of the first piece placed by each player, pieces may not be placed next to a piece of ; the opponent's colour. It is possible to win the game without placing all your pieces, ; but once a piece has been placed, it cannot be removed. ; ; Placing your Queen Bee ; Your Queen Bee can be placed at any time from your first to your fourth turn. You ; must place your Queen Bee on your fourth turn if you have not placed it before. (defn force-queen-placement? "returns true if queen must be placed this turn" [color board turn-number] (let [num-queens (count (board/search-pieces board color :queen-bee)) is-fourth-turn (or (= 6 turn-number) (= 7 turn-number))] (and is-fourth-turn (= 0 num-queens)) )) ; http://boardgamegeek.com/wiki/page/Hive_FAQ ; You cannot place your queen as your first move. (defn allow-queen-placement? "returns true if queen may be placed this turn" [turn-number] (> turn-number 1) ) ; Moving ; Once your Queen Bee has been placed (but not before), you can decide whether to use ; each turn after that to place another piece or to move one of the pieces that have ; already been placed. Each creature has its own way of moving. When moving, it is ; possible to move pieces to a position where they touch one or more of your opponent's ; pieces. ; All pieces must always touch at least one other piece. If a piece is the only ; connection between two parts of the Hive, it may not be moved. (See 'One Hive rule') (defn any-movement-allowed? "returns true if any movement is allowed, due to having placed a queen" [color board] (> (count (board/search-pieces board color :queen-bee)) 0) ) ; The End of the Game ; The game ends as soon as one Queen Bee is completely surrounded by pieces of any colour. ; The person whose Queen Bee is surrounded loses the game, unless the last piece to ; surround their Queen Bee also completes the surrounding of the other Queen Bee. In that ; case the game is drawn. A draw may also be agreed if both players are in a position where ; they are forced to move the same two pieces over and over again, without any possibility ; of the stalemate being resolved. (defn game-over? "describes which end state, if any, has been reached" [board] (let [num-directions (count position/direction-vectors) queens (map (fn [piece] (let [occupied-adjacencies (board/lookup-occupied-adjacencies board (:position piece))] (assoc piece :surrounded (= num-directions (count occupied-adjacencies))) )) (board/search-pieces board nil :queen-bee)) color-test (fn [color] #(= color (:color (:piece %)))) white (first (filter (color-test :white) queens)) black (first (filter (color-test :black) queens))] (cond (and (:surrounded white) (:surrounded black)) {:game-over true, :is-draw true, :winner nil} (:surrounded white) {:game-over true, :is-draw false, :winner :black} (:surrounded black) {:game-over true, :is-draw false, :winner :white} :else {:game-over false, :is-draw false, :winner nil}) )) ; Queen Bee ; The Queen Bee can move only one space per turn. (defn find-valid-movement-queen-bee "get movement for position by the rules of the queen bee" [board position] (board/lookup-adjacent-slide-positions board position) ) ; Beetle ; The Beetle, like the Queen Bee, moves only space per turn around the Hive, but ; can also move on top of the Hive. A piece with a beetle on top of it is unable ; to move and for the purposes of the placing rules, the stack takes on the ; colour of the Beetle. ; ; From its position on top of the Hive, the Beetle can move from piece to piece ; across the top of the Hive. It can also drop into spaces that are surrounded ; and therefore not accessible to most other creatures. ; ; The only way to block a Beetle that is on top of the Hive is to move another ; Beetle on top of it. All Beetles and Mosquitoes can be stacked on top of each ; other. ; ; When it is first placed, the Beetle is placed in the same way as all the other ; pieces. It cannot be placed directly on top of the Hive, even though it can ; be moved there later. ; ; http://www.boardgamegeek.com/wiki/page/Hive_FAQ#toc8 ; Q: Are beetles affected by the Freedom To Move rule? ; A: Yes. (albeit in a different way): Beetles cannot slide through "gates" (defn find-valid-movement-beetle "get movement for position by the rules of the beetle" [board position] (set/union (board/lookup-adjacent-slide-positions board position) (board/lookup-adjacent-climb-positions board position) ) ) ; Grasshopper ; The Grasshopper does not move around the outside of the Hive like the other ; creatures. Instead it jumps from its space over any number of pieces (but ; at least one) to the next unoccupied space along a straight row of joined ; pieces. ; ; This gives it the advantage of being able to fill in a space which is ; surrounded by other pieces. (defn find-valid-movement-grasshopper "get movement for position by the rules of the grasshopper" [board position] (let [adjacent-positions (board/lookup-adjacent-positions board position) free-spaces (map (fn [direction] (board/find-free-space-in-direction board position direction)) (keys adjacent-positions))] free-spaces )) ; Spider ; The Spider moves three spaces per turn - no more, no less. It must move in a ; direct path and cannot backtrack on itself. It may only move around pieces ; that it is in direct contact with on each step of its move. It may not move ; across to a piece that it is not in direct contact with. (defn find-valid-movement-spider "get movement for position by the rules of the spider" [board position] (board/find-unique-paths-matching-conditions board position 3 0)) ; Soldier Ant ; The Soldier Ant can move from its position to any other position around the ; Hive provided the restrictions are adhered to. (defn find-valid-movement-soldier-ant "get movement for position by the rules of the soldier-ant" [board position] (board/lookup-slide-destinations board position)) ; Ladybug ; The Ladybug moves three spaces; two on top of the Hive, and then one down. ; It must move exactly two on top of the Hive and then move one down on its ; last move. It may not move around the outside of the Hive and may not end ; its movement on top of the Hive. Even though it cannot block by landing ; on top of other pieces like the Beetle, it can move into or out of surrounded ; spaces. It also has the advantage of being much faster. (defn find-valid-movement-ladybug "get movement for position by the rules of the ladybug" [board position] (let [distance-spec 3 height-spec { "1-2" {:min 1, :max :infinity} "3" 0 } valid-paths (board/find-unique-paths-matching-conditions board position distance-spec height-spec )] (set (keys valid-paths)) )) ; Pillbug ; The Pillbug moves like the Queen Bee - one space at a time - but it has a ; special ability that it may use instead of moving. This ability allows the ; Pillbug to move an adjacent unstacked piece (whether friend or enemy) two ; spaces: up onto the pillbug itself, then down into an empty space adjacent ; to itself. Some exceptions for this ability: ; - The Pillbug may not move the piece most recently moved by the opponent. ; - The Pillbug may not move any piece in a stack of pieces. ; - The Pillbug may not move a piece if it splits the hive (One Hive rule) ; - The Pillbug may not move a piece through a too-narrow gap of stacked ; pieces (Freedom to Move rule) ; Any piece which physically moved (directly or by the Pillbug) is rendered ; immobile on the next player's turn; it cannot move or be moved, nor use its ; special ability. The Mosquito can mimic either the movement or special ; ability of the Pillbug, even when the Pillbug it is touching has been rendered ; immobile by another Pillbug. ; Clarification from PI:NAME:<NAME>END_PI: The Pillbug using its special ability does not ; count as "movement" from the perspective of an opposing player's Pillbug, and ; thus does not grant it immunity from being moved by the opposing Pillbug. Only ; physically moved pieces have such protection. ; Further Clarification: A stunned Pillbug (one that was just moved by a Pillbug) ; cannot use its special ability. (defn find-valid-movement-pillbug "get movement for position by the rules of the pillbug" [board position] (board/lookup-adjacent-slide-positions board position) ) (defn find-valid-special-abilities-pillbug "get special abilities for position by the rules of the pillbug" [board position turn-history] (let [adjacencies (board/lookup-adjacent-positions board position) categorized-adjacencies (reduce (fn [result [direction adjacency]] (let [stack-cw (get adjacencies (position/rotation-clockwise direction)) stack-ccw (get adjacencies (position/rotation-counter-clockwise direction))] (if (and (<= (:height stack-cw) 1) (<= (:height stack-ccw))) ; piece not sliding through a "gate" (cond (== (:height adjacency) 0) ; empty space (update-in result [:free] conj (:position adjacency)) (and (== (:height adjacency) 1) (board/contiguous? (board/remove-piece board (:position adjacency)))) ; single piece (update-in result [:occupied] conj (:position adjacency)) :else result) result) )) {:free #{}, :occupied #{}} adjacencies) free-adjacencies (:free categorized-adjacencies) occupied-adjacencies (:occupied categorized-adjacencies) last-turn (last turn-history) valid-occupied-adjacencies (filter #(not= (:destination last-turn) %) occupied-adjacencies)] (zipmap valid-occupied-adjacencies (repeat (count valid-occupied-adjacencies) free-adjacencies)) )) ; Mosquito ; The Mosquito is placed in the same way as the other pieces. Once in play, the ; Mosquito takes on the movement characteristics of any creature it touches at ; the time, including your opponents', thus changing its characteristics ; throughout the game. ; Exception: if moved as a Beetle on top of the Hive, it continues to move as ; a Beetle until it climbs down from the Hive. If when on the ground level it ; is next to a stacked Beetle, it may move as a Beetle and not the piece below ; the Beetle. If touching another Mosquito only (including a stacked Mosquito) ; and no other piece, it may not move. (defn find-valid-movement-mosquito "get movement for position by the rules of the mosquito" [board position] (if (> (board/lookup-piece-stack-height position) 1) ; mosquito is atop the hive; move like a beetle (find-valid-movement-beetle board position) ; mosquito is at ground-level; move according to adjacent piece types (set (mapcat identity (map (fn [piece-type] (case piece-type :queen-bee (find-valid-movement-queen-bee board position) :beetle (find-valid-movement-beetle board position) :grasshopper (find-valid-movement-grasshopper board position) :spider (find-valid-movement-spider board position) :soldier-ant (find-valid-movement-soldier-ant board position) :mosquito nil :ladybug (find-valid-movement-ladybug board position) :pillbug (find-valid-movement-pillbug board position) nil )) (board/lookup-adjacent-piece-types board position)))) )) (defn find-valid-special-abilities-mosquito "get special abilities for position by the rules of the mosquito" [board position turn-history] (if (> (board/lookup-piece-stack-height position) 1) nil (set (mapcat identity (map (fn [piece-type] (case piece-type :pillbug (find-valid-special-abilities-pillbug board position) nil )) (board/lookup-adjacent-piece-types board position)))) )) ; Unable to Move or Place ; If a player can not place a new piece or move an existing piece, the turn passes ; to their opponent who then takes their turn again. The game continues in this way ; until the player is able to move or place one of their pieces, or until their ; Queen Bee is surrounded. ; http://boardspace.net/english/about_hive.html ; Rules Change: at boardspace the "Queen" opening has been forbidden for both black and white. ; PI:NAME:<NAME>END_PI supports this change, which is intended to eliminate the problem of excess draws in "queen opening" games. (defn find-valid-placement-positions "returns the set of valid placement positions for the given color" [color board turn-number] (board/search-free-spaces board (if (> turn-number 1) color nil)) ) ; One Hive rule ; The pieces in play must be linked at all times. At no time can you leave a piece ; stranded (not joined to the Hive) or separate the Hive in two. ; Freedom to Move ; The creatures can only move in a sliding movement. If a piece is surrounded to ; the point that it can no longer physically slide out of its position, it may ; not be moved. The only exceptions are the Grasshopper (which jumps into or out ; of a space), the Beetle and Ladybug (which climb up and down) and the Mosquito ; (which can mimic one of the three). Similarly, no piece may move into a space ; that it cannot physically slide into. ; When first introduced to the game, a piece may be placed into a space that is ; surrounded as long as it does not violate any of the placing rules, in particular ; the rule about pieces not being allowed to touch pieces of the other colour when ; they are first placed. (defn find-valid-movement "returns all valid moves for the piece at the given position (if stacked, top of stack)" [board position] (if (board/contiguous? (board/remove-piece board position)) (let [piece-type (:type (board/lookup-piece board position))] (case piece-type :queen-bee (find-valid-movement-queen-bee board position) :beetle (find-valid-movement-beetle board position) :grasshopper (find-valid-movement-grasshopper board position) :spider (find-valid-movement-spider board position) :soldier-ant (find-valid-movement-soldier-ant board position) :mosquito (find-valid-movement-mosquito board position) :ladybug (find-valid-movement-ladybug board position) :pillbug (find-valid-movement-pillbug board position) )) nil) ) (defn find-valid-special-abilities "" [board position turn-history] (let [piece-type (:type (board/lookup-piece board position))] (case piece-type :queen-bee nil :beetle nil :grasshopper nil :spider nil :soldier-ant nil :mosquito (find-valid-special-abilities-mosquito board position turn-history) :ladybug nil :pillbug (find-valid-special-abilities-pillbug board position turn-history) )) ) ; TODO: define a game-state as a schema (defn lookup-possible-turns "given a full game state, return all possible next turns" [color board hand turn-number turn-history] (if (game-over? board) nil (let [last-turn (last turn-history) owned-piece-positions (board/search-top-pieces board color nil) possible-placement-positions (find-valid-placement-positions color board turn-number) possible-placement-piece-types (if (force-queen-placement? color board turn-number) #{:queen-bee} (if (allow-queen-placement? turn-number) (set (keys hand)) (set (remove #{:queen-bee} (keys hand))) )) possible-piece-actions (if (any-movement-allowed? color board) (filter #(second %) ; toss out any positions mapped to falsey values (zipmap owned-piece-positions (map (fn [position] (if (and (= :special-ability (:turn-type last-turn)) (= :pillbug (:type (board/lookup-piece board (:ability-user last-turn)))) (= position (:destination last-turn) )) ; piece is not eligible for movement because it is stunned by pillbug's special ability nil ; piece at <position> has potential movement or special abilities of its own { :movement (find-valid-movement board position) :special-abilities (find-valid-special-abilities board position turn-history) } )) owned-piece-positions) )) nil ) possible-forfeit (and (empty? possible-placement-positions) (empty? possible-placement-piece-types) (empty? possible-piece-actions)) ] { :placement-positions possible-placement-positions :placement-piece-types possible-placement-piece-types :existing-piece-actions possible-piece-actions :must-only-forfeit possible-forfeit } )) )
[ { "context": "est;MVCC=true\"})\n (db/create-user! {:username \"newuser\"\n :password \"pass\"\n ", "end": 542, "score": 0.9987598061561584, "start": 535, "tag": "USERNAME", "value": "newuser" }, { "context": "ername \"newuser\"\n :password \"pass\"\n :admin false})\n (f))", "end": 581, "score": 0.9995147585868835, "start": 577, "tag": "PASSWORD", "value": "pass" }, { "context": "he preparation\"\n :user \"newuser\"})\n\n(deftest get-recipe\n (jdbc/with-db-transacti", "end": 900, "score": 0.996180534362793, "start": 893, "tag": "USERNAME", "value": "newuser" }, { "context": " {:username \"newuser\"\n; :", "end": 4370, "score": 0.9996820688247681, "start": 4363, "tag": "USERNAME", "value": "newuser" }, { "context": " :password \"pass\"\n; :", "end": 4434, "score": 0.9995191097259521, "start": 4430, "tag": "PASSWORD", "value": "pass" }, { "context": " {:username \"newuser\"\n; ", "end": 4629, "score": 0.9996005296707153, "start": 4622, "tag": "USERNAME", "value": "newuser" }, { "context": " (:lang (db/get-user t-conn {:username \"newuser\"}))))))\n", "end": 4823, "score": 0.999626874923706, "start": 4816, "tag": "USERNAME", "value": "newuser" } ]
test/copa/test/db/recipes.clj
hjrnunes/copa
2
(ns copa.test.db.recipes (:require [copa.db.core :refer [*db*] :as db] [luminus-migrations.core :as migrations] [clojure.test :refer :all] [clojure.java.jdbc :as jdbc] [copa.config :refer [env]] [mount.core :as mount]) (:import (java.sql SQLException))) (use-fixtures :once (fn [f] (mount/start #'copa.config/env #'copa.db.core/*db*) (migrations/migrate ["reset"] {:database-url "jdbc:h2:./copa_test;MVCC=true"}) (db/create-user! {:username "newuser" :password "pass" :admin false}) (f))) (def sample-recipe {:name "a recipe" :description "a description" :portions "3" :source "a source" :preparation "the preparation" :user "newuser"}) (deftest get-recipe (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (let [res (db/create-recipe! t-conn sample-recipe) id (get res (keyword "scope_identity()"))] (testing "get a recipe by id" (is (= sample-recipe (dissoc (db/get-recipe t-conn {:recipe_id id}) :recipe_id)))) (testing "get a recipe by name" (is (= sample-recipe (dissoc (db/get-recipe-by-name t-conn {:name "a recipe"}) :recipe_id))))))) (deftest insert-recipe (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (testing "inserting new recipe" (db/create-recipe! t-conn sample-recipe) (is (= sample-recipe (dissoc (db/get-recipe-by-name t-conn {:name "a recipe"}) :recipe_id)))) (testing "insert another recipe with same name fails" (is (thrown? SQLException (db/create-recipe! t-conn sample-recipe)))) (testing "insert recipe without user fails" (is (thrown? SQLException (dissoc (assoc (db/create-recipe! t-conn sample-recipe) :name "another name") :user)))) (testing "insert recipe without name fails" (is (thrown? SQLException (dissoc (db/create-recipe! t-conn sample-recipe) :name)))) (testing "insert recipe without preparation fails" (is (thrown? SQLException (dissoc (assoc (db/create-recipe! t-conn sample-recipe) :name "yet another name") :preparation)))))) (deftest delete-recipe (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (testing "deleting a recipe" (let [res (db/create-recipe! t-conn sample-recipe) id (get res (keyword "scope_identity()"))] (is (= 1 (db/delete-recipe! t-conn {:recipe_id id}))) (is (= nil (db/get-recipe t-conn {:recipe_id id}))))))) (deftest update-recipe (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (let [res (db/create-recipe! t-conn sample-recipe) id (get res (keyword "scope_identity()")) updted (assoc sample-recipe :name "another name" :recipe_id id)] (is (= 1 (db/update-recipe! t-conn updted))) (is (= updted (db/get-recipe t-conn {:recipe_id id})))))) ; ;(deftest update-user-lang ; (jdbc/with-db-transaction [t-conn *db*] ; (jdbc/db-set-rollback-only! t-conn) ; (db/create-user! t-conn ; {:username "newuser" ; :password "pass" ; :admin false}) ; (db/update-user-lang! t-conn ; {:username "newuser" ; :lang "cz"}) ; (is (= "cz" ; (:lang (db/get-user t-conn {:username "newuser"}))))))
41135
(ns copa.test.db.recipes (:require [copa.db.core :refer [*db*] :as db] [luminus-migrations.core :as migrations] [clojure.test :refer :all] [clojure.java.jdbc :as jdbc] [copa.config :refer [env]] [mount.core :as mount]) (:import (java.sql SQLException))) (use-fixtures :once (fn [f] (mount/start #'copa.config/env #'copa.db.core/*db*) (migrations/migrate ["reset"] {:database-url "jdbc:h2:./copa_test;MVCC=true"}) (db/create-user! {:username "newuser" :password "<PASSWORD>" :admin false}) (f))) (def sample-recipe {:name "a recipe" :description "a description" :portions "3" :source "a source" :preparation "the preparation" :user "newuser"}) (deftest get-recipe (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (let [res (db/create-recipe! t-conn sample-recipe) id (get res (keyword "scope_identity()"))] (testing "get a recipe by id" (is (= sample-recipe (dissoc (db/get-recipe t-conn {:recipe_id id}) :recipe_id)))) (testing "get a recipe by name" (is (= sample-recipe (dissoc (db/get-recipe-by-name t-conn {:name "a recipe"}) :recipe_id))))))) (deftest insert-recipe (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (testing "inserting new recipe" (db/create-recipe! t-conn sample-recipe) (is (= sample-recipe (dissoc (db/get-recipe-by-name t-conn {:name "a recipe"}) :recipe_id)))) (testing "insert another recipe with same name fails" (is (thrown? SQLException (db/create-recipe! t-conn sample-recipe)))) (testing "insert recipe without user fails" (is (thrown? SQLException (dissoc (assoc (db/create-recipe! t-conn sample-recipe) :name "another name") :user)))) (testing "insert recipe without name fails" (is (thrown? SQLException (dissoc (db/create-recipe! t-conn sample-recipe) :name)))) (testing "insert recipe without preparation fails" (is (thrown? SQLException (dissoc (assoc (db/create-recipe! t-conn sample-recipe) :name "yet another name") :preparation)))))) (deftest delete-recipe (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (testing "deleting a recipe" (let [res (db/create-recipe! t-conn sample-recipe) id (get res (keyword "scope_identity()"))] (is (= 1 (db/delete-recipe! t-conn {:recipe_id id}))) (is (= nil (db/get-recipe t-conn {:recipe_id id}))))))) (deftest update-recipe (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (let [res (db/create-recipe! t-conn sample-recipe) id (get res (keyword "scope_identity()")) updted (assoc sample-recipe :name "another name" :recipe_id id)] (is (= 1 (db/update-recipe! t-conn updted))) (is (= updted (db/get-recipe t-conn {:recipe_id id})))))) ; ;(deftest update-user-lang ; (jdbc/with-db-transaction [t-conn *db*] ; (jdbc/db-set-rollback-only! t-conn) ; (db/create-user! t-conn ; {:username "newuser" ; :password "<PASSWORD>" ; :admin false}) ; (db/update-user-lang! t-conn ; {:username "newuser" ; :lang "cz"}) ; (is (= "cz" ; (:lang (db/get-user t-conn {:username "newuser"}))))))
true
(ns copa.test.db.recipes (:require [copa.db.core :refer [*db*] :as db] [luminus-migrations.core :as migrations] [clojure.test :refer :all] [clojure.java.jdbc :as jdbc] [copa.config :refer [env]] [mount.core :as mount]) (:import (java.sql SQLException))) (use-fixtures :once (fn [f] (mount/start #'copa.config/env #'copa.db.core/*db*) (migrations/migrate ["reset"] {:database-url "jdbc:h2:./copa_test;MVCC=true"}) (db/create-user! {:username "newuser" :password "PI:PASSWORD:<PASSWORD>END_PI" :admin false}) (f))) (def sample-recipe {:name "a recipe" :description "a description" :portions "3" :source "a source" :preparation "the preparation" :user "newuser"}) (deftest get-recipe (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (let [res (db/create-recipe! t-conn sample-recipe) id (get res (keyword "scope_identity()"))] (testing "get a recipe by id" (is (= sample-recipe (dissoc (db/get-recipe t-conn {:recipe_id id}) :recipe_id)))) (testing "get a recipe by name" (is (= sample-recipe (dissoc (db/get-recipe-by-name t-conn {:name "a recipe"}) :recipe_id))))))) (deftest insert-recipe (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (testing "inserting new recipe" (db/create-recipe! t-conn sample-recipe) (is (= sample-recipe (dissoc (db/get-recipe-by-name t-conn {:name "a recipe"}) :recipe_id)))) (testing "insert another recipe with same name fails" (is (thrown? SQLException (db/create-recipe! t-conn sample-recipe)))) (testing "insert recipe without user fails" (is (thrown? SQLException (dissoc (assoc (db/create-recipe! t-conn sample-recipe) :name "another name") :user)))) (testing "insert recipe without name fails" (is (thrown? SQLException (dissoc (db/create-recipe! t-conn sample-recipe) :name)))) (testing "insert recipe without preparation fails" (is (thrown? SQLException (dissoc (assoc (db/create-recipe! t-conn sample-recipe) :name "yet another name") :preparation)))))) (deftest delete-recipe (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (testing "deleting a recipe" (let [res (db/create-recipe! t-conn sample-recipe) id (get res (keyword "scope_identity()"))] (is (= 1 (db/delete-recipe! t-conn {:recipe_id id}))) (is (= nil (db/get-recipe t-conn {:recipe_id id}))))))) (deftest update-recipe (jdbc/with-db-transaction [t-conn *db*] (jdbc/db-set-rollback-only! t-conn) (let [res (db/create-recipe! t-conn sample-recipe) id (get res (keyword "scope_identity()")) updted (assoc sample-recipe :name "another name" :recipe_id id)] (is (= 1 (db/update-recipe! t-conn updted))) (is (= updted (db/get-recipe t-conn {:recipe_id id})))))) ; ;(deftest update-user-lang ; (jdbc/with-db-transaction [t-conn *db*] ; (jdbc/db-set-rollback-only! t-conn) ; (db/create-user! t-conn ; {:username "newuser" ; :password "PI:PASSWORD:<PASSWORD>END_PI" ; :admin false}) ; (db/update-user-lang! t-conn ; {:username "newuser" ; :lang "cz"}) ; (is (= "cz" ; (:lang (db/get-user t-conn {:username "newuser"}))))))
[ { "context": "pos 0\n :remote-cursors [{:name \"Alice\"\n :pos [3 2 9", "end": 3911, "score": 0.9998406171798706, "start": 3906, "tag": "NAME", "value": "Alice" }, { "context": "een\"}\n {:name \"Bob\"\n :pos [5 2 2", "end": 4063, "score": 0.999835729598999, "start": 4060, "tag": "NAME", "value": "Bob" } ]
src/thingy/core.cljs
acobster/live-proto
0
(ns thingy.core (:require [clojure.datafy :refer [datafy]] [reagent.core :as r] [thingy.dom :as dom] [thingy.events :as events] [thingy.util :refer [vconj inject-at]])) (defprotocol EditablePath (path [this root])) (extend-protocol EditablePath js/Element (path [this root] (dom/path this root)) js/Text (path [this root] (dom/path this root))) (defprotocol EditEvent (edit-event [this root] [this root args])) (extend-protocol EditEvent js/Selection (edit-event [this root] (let [data (datafy this) {:keys [anchor-node anchor-offset focus-node focus-offset]} data] {:within-root? (and (dom/ancestor? root anchor-node) (dom/ancestor? root focus-node)) :anchor-path (vconj (dom/path anchor-node root) anchor-offset) :focus-path (vconj (dom/path focus-node root) focus-offset)}))) (defn- ->contenteditable [elem state] (vec (-> elem (assoc-in [1 :content-editable] true) (assoc-in [1 :on-key-press] (events/emitter state :contenteditable-keypress))))) (defn- ->editable [node root conf state] ; TODO apply tranformations dynamically according to tools/config {:elem (->contenteditable (datafy node) state) :path (dom/path node root) :conf conf}) (defn cursor [c] [:span.cursor {:style {:border-color (:color c) :background-color (:color c)}} [:span.cursor-meta {:style {:color (or (:text-color c) "white") :background-color (:color c)} :content-editable false} (:name c)]]) ;; TODO account for cursor positions when computing new paths (defn place-cursor [html {:keys [pos] :as c}] (let [elem-pos (butlast (butlast pos)) node-pos (last (butlast pos)) strpos (last pos) elem (get-in html (butlast (butlast pos))) node (get elem node-pos) [elem-left elem-right] (split-at node-pos elem) [left-text right-text] (split-at strpos node) with-cursor [(apply str left-text) (cursor c) (apply str right-text)]] (assoc-in html elem-pos (vec (concat elem-left with-cursor (rest elem-right)))))) (defn ->with-cursors [fragment cursors] (reduce place-cursor fragment cursors)) (defn tools [ed] (:tools (:conf ed))) (defn query-editables [configs root state] (set (reduce (fn [editables {:keys [selector] :as conf}] (let [elems (dom/all selector root) these (map #(->editable % root conf state) elems)] (concat editables these))) [] configs))) ;; TODO do this over real event channels (defn simulate-remote-cursor-movement! [state max-ms] (let [dice (rand-int 10) path [:remote-cursors (rand-int 2) :pos 2]] (cond (= dice 7) (swap! state assoc-in path (rand-int 50)) (> dice 5) (swap! state update-in path #(max 0 (dec %))) :else (swap! state update-in path #(min (inc %) 80)))) (js/setTimeout (fn [] (simulate-remote-cursor-movement! state max-ms)) (rand-int max-ms))) ;; => (defn ^:export init-component [root conf] (let [state (r/atom {}) eds (query-editables (:editables conf) root state) root-fragment (reduce (fn [fragment ed] (assoc-in fragment (:path ed) (:elem ed))) (dom/fragment root) eds) ] ;; TODO listen for real update Events on a channel ;(simulate-remote-cursor-movement! state 3000) (reset! state {:root-content-fragment root-fragment :conf conf :dom-root root :editables eds :caret-pos 0 :remote-cursors [{:name "Alice" :pos [3 2 9] :color "green"} {:name "Bob" :pos [5 2 25] :color "purple"}]}) (r/create-class {:render (fn [] (->with-cursors (:root-content-fragment @state) (:remote-cursors @state))) :component-did-update (fn [] (let [{:keys [dom-root caret-pos]} @state focus-node (dom/path->node dom-root (butlast caret-pos)) sel (dom/selection) range (js/document.createRange)] (js/console.log (clj->js caret-pos)) (js/console.log focus-node (last caret-pos)) ;; TODO why does this fail? ;(.setStart range focus-node (last caret-pos)) (.setStart range focus-node 0) (.collapse range true) (.removeAllRanges sel) (.addRange sel range)))}))) (defn ^:export editable! [root conf] (let [component (init-component root conf)] (r/render [component] root)))
35475
(ns thingy.core (:require [clojure.datafy :refer [datafy]] [reagent.core :as r] [thingy.dom :as dom] [thingy.events :as events] [thingy.util :refer [vconj inject-at]])) (defprotocol EditablePath (path [this root])) (extend-protocol EditablePath js/Element (path [this root] (dom/path this root)) js/Text (path [this root] (dom/path this root))) (defprotocol EditEvent (edit-event [this root] [this root args])) (extend-protocol EditEvent js/Selection (edit-event [this root] (let [data (datafy this) {:keys [anchor-node anchor-offset focus-node focus-offset]} data] {:within-root? (and (dom/ancestor? root anchor-node) (dom/ancestor? root focus-node)) :anchor-path (vconj (dom/path anchor-node root) anchor-offset) :focus-path (vconj (dom/path focus-node root) focus-offset)}))) (defn- ->contenteditable [elem state] (vec (-> elem (assoc-in [1 :content-editable] true) (assoc-in [1 :on-key-press] (events/emitter state :contenteditable-keypress))))) (defn- ->editable [node root conf state] ; TODO apply tranformations dynamically according to tools/config {:elem (->contenteditable (datafy node) state) :path (dom/path node root) :conf conf}) (defn cursor [c] [:span.cursor {:style {:border-color (:color c) :background-color (:color c)}} [:span.cursor-meta {:style {:color (or (:text-color c) "white") :background-color (:color c)} :content-editable false} (:name c)]]) ;; TODO account for cursor positions when computing new paths (defn place-cursor [html {:keys [pos] :as c}] (let [elem-pos (butlast (butlast pos)) node-pos (last (butlast pos)) strpos (last pos) elem (get-in html (butlast (butlast pos))) node (get elem node-pos) [elem-left elem-right] (split-at node-pos elem) [left-text right-text] (split-at strpos node) with-cursor [(apply str left-text) (cursor c) (apply str right-text)]] (assoc-in html elem-pos (vec (concat elem-left with-cursor (rest elem-right)))))) (defn ->with-cursors [fragment cursors] (reduce place-cursor fragment cursors)) (defn tools [ed] (:tools (:conf ed))) (defn query-editables [configs root state] (set (reduce (fn [editables {:keys [selector] :as conf}] (let [elems (dom/all selector root) these (map #(->editable % root conf state) elems)] (concat editables these))) [] configs))) ;; TODO do this over real event channels (defn simulate-remote-cursor-movement! [state max-ms] (let [dice (rand-int 10) path [:remote-cursors (rand-int 2) :pos 2]] (cond (= dice 7) (swap! state assoc-in path (rand-int 50)) (> dice 5) (swap! state update-in path #(max 0 (dec %))) :else (swap! state update-in path #(min (inc %) 80)))) (js/setTimeout (fn [] (simulate-remote-cursor-movement! state max-ms)) (rand-int max-ms))) ;; => (defn ^:export init-component [root conf] (let [state (r/atom {}) eds (query-editables (:editables conf) root state) root-fragment (reduce (fn [fragment ed] (assoc-in fragment (:path ed) (:elem ed))) (dom/fragment root) eds) ] ;; TODO listen for real update Events on a channel ;(simulate-remote-cursor-movement! state 3000) (reset! state {:root-content-fragment root-fragment :conf conf :dom-root root :editables eds :caret-pos 0 :remote-cursors [{:name "<NAME>" :pos [3 2 9] :color "green"} {:name "<NAME>" :pos [5 2 25] :color "purple"}]}) (r/create-class {:render (fn [] (->with-cursors (:root-content-fragment @state) (:remote-cursors @state))) :component-did-update (fn [] (let [{:keys [dom-root caret-pos]} @state focus-node (dom/path->node dom-root (butlast caret-pos)) sel (dom/selection) range (js/document.createRange)] (js/console.log (clj->js caret-pos)) (js/console.log focus-node (last caret-pos)) ;; TODO why does this fail? ;(.setStart range focus-node (last caret-pos)) (.setStart range focus-node 0) (.collapse range true) (.removeAllRanges sel) (.addRange sel range)))}))) (defn ^:export editable! [root conf] (let [component (init-component root conf)] (r/render [component] root)))
true
(ns thingy.core (:require [clojure.datafy :refer [datafy]] [reagent.core :as r] [thingy.dom :as dom] [thingy.events :as events] [thingy.util :refer [vconj inject-at]])) (defprotocol EditablePath (path [this root])) (extend-protocol EditablePath js/Element (path [this root] (dom/path this root)) js/Text (path [this root] (dom/path this root))) (defprotocol EditEvent (edit-event [this root] [this root args])) (extend-protocol EditEvent js/Selection (edit-event [this root] (let [data (datafy this) {:keys [anchor-node anchor-offset focus-node focus-offset]} data] {:within-root? (and (dom/ancestor? root anchor-node) (dom/ancestor? root focus-node)) :anchor-path (vconj (dom/path anchor-node root) anchor-offset) :focus-path (vconj (dom/path focus-node root) focus-offset)}))) (defn- ->contenteditable [elem state] (vec (-> elem (assoc-in [1 :content-editable] true) (assoc-in [1 :on-key-press] (events/emitter state :contenteditable-keypress))))) (defn- ->editable [node root conf state] ; TODO apply tranformations dynamically according to tools/config {:elem (->contenteditable (datafy node) state) :path (dom/path node root) :conf conf}) (defn cursor [c] [:span.cursor {:style {:border-color (:color c) :background-color (:color c)}} [:span.cursor-meta {:style {:color (or (:text-color c) "white") :background-color (:color c)} :content-editable false} (:name c)]]) ;; TODO account for cursor positions when computing new paths (defn place-cursor [html {:keys [pos] :as c}] (let [elem-pos (butlast (butlast pos)) node-pos (last (butlast pos)) strpos (last pos) elem (get-in html (butlast (butlast pos))) node (get elem node-pos) [elem-left elem-right] (split-at node-pos elem) [left-text right-text] (split-at strpos node) with-cursor [(apply str left-text) (cursor c) (apply str right-text)]] (assoc-in html elem-pos (vec (concat elem-left with-cursor (rest elem-right)))))) (defn ->with-cursors [fragment cursors] (reduce place-cursor fragment cursors)) (defn tools [ed] (:tools (:conf ed))) (defn query-editables [configs root state] (set (reduce (fn [editables {:keys [selector] :as conf}] (let [elems (dom/all selector root) these (map #(->editable % root conf state) elems)] (concat editables these))) [] configs))) ;; TODO do this over real event channels (defn simulate-remote-cursor-movement! [state max-ms] (let [dice (rand-int 10) path [:remote-cursors (rand-int 2) :pos 2]] (cond (= dice 7) (swap! state assoc-in path (rand-int 50)) (> dice 5) (swap! state update-in path #(max 0 (dec %))) :else (swap! state update-in path #(min (inc %) 80)))) (js/setTimeout (fn [] (simulate-remote-cursor-movement! state max-ms)) (rand-int max-ms))) ;; => (defn ^:export init-component [root conf] (let [state (r/atom {}) eds (query-editables (:editables conf) root state) root-fragment (reduce (fn [fragment ed] (assoc-in fragment (:path ed) (:elem ed))) (dom/fragment root) eds) ] ;; TODO listen for real update Events on a channel ;(simulate-remote-cursor-movement! state 3000) (reset! state {:root-content-fragment root-fragment :conf conf :dom-root root :editables eds :caret-pos 0 :remote-cursors [{:name "PI:NAME:<NAME>END_PI" :pos [3 2 9] :color "green"} {:name "PI:NAME:<NAME>END_PI" :pos [5 2 25] :color "purple"}]}) (r/create-class {:render (fn [] (->with-cursors (:root-content-fragment @state) (:remote-cursors @state))) :component-did-update (fn [] (let [{:keys [dom-root caret-pos]} @state focus-node (dom/path->node dom-root (butlast caret-pos)) sel (dom/selection) range (js/document.createRange)] (js/console.log (clj->js caret-pos)) (js/console.log focus-node (last caret-pos)) ;; TODO why does this fail? ;(.setStart range focus-node (last caret-pos)) (.setStart range focus-node 0) (.collapse range true) (.removeAllRanges sel) (.addRange sel range)))}))) (defn ^:export editable! [root conf] (let [component (init-component root conf)] (r/render [component] root)))
[ { "context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio", "end": 30, "score": 0.9998143911361694, "start": 19, "tag": "NAME", "value": "Rich Hickey" }, { "context": "ice, or any other, from this software.\n;\n;\tAuthor: David Miller\n\n; Test of gen-class facility.\n;\n; Place this fil", "end": 488, "score": 0.9997619986534119, "start": 476, "tag": "NAME", "value": "David Miller" } ]
Clojure/clojure/samples/attributes/testattribute.clj
AydarLukmanov/ArcadiaGodot
328
; 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: David Miller ; Test of gen-class facility. ; ; Place this file in the clojure subdirectory of your main directory. ; Compile the file C.cs via: csc /t:library C.cs ; Place C.dll in your root directory. ; Start Clojure and do: ; (System.Reflection.Assembly/LoadFrom "C.dll") ; (compile 'clojure.testattribute) ; ; You should then be able to play games such as: (ns clojure.testattribute) (def x (dm.Pet/Dog)) (gen-interface :name ^{System.SerializableAttribute {} dm.PetTypeAttribute x} test.I1 :methods [ [m1 [] Object] ]) (definterface ^{System.SerializableAttribute {} dm.PetTypeAttribute x} I2 (m2 [])) ; (seq (.GetCustomAttributes test.I1 true)) ; (seq (.GetCustomAttributes I2 true)) (definterface ^{ dm.PetTypeAttribute x } I3 (^{ dm.PetTypeAttribute x } m1 [ x y]) (m2 [x ^{ dm.PetTypeAttribute x } y])) (deftype ^{System.SerializableAttribute {}} T1 [a ^{ dm.PetTypeAttribute x } b] I3 (^{ dm.PetTypeAttribute x } m1 [_ p q] p) (m2 [_ p ^{ dm.PetTypeAttribute x } q] q) )
109562
; 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> ; Test of gen-class facility. ; ; Place this file in the clojure subdirectory of your main directory. ; Compile the file C.cs via: csc /t:library C.cs ; Place C.dll in your root directory. ; Start Clojure and do: ; (System.Reflection.Assembly/LoadFrom "C.dll") ; (compile 'clojure.testattribute) ; ; You should then be able to play games such as: (ns clojure.testattribute) (def x (dm.Pet/Dog)) (gen-interface :name ^{System.SerializableAttribute {} dm.PetTypeAttribute x} test.I1 :methods [ [m1 [] Object] ]) (definterface ^{System.SerializableAttribute {} dm.PetTypeAttribute x} I2 (m2 [])) ; (seq (.GetCustomAttributes test.I1 true)) ; (seq (.GetCustomAttributes I2 true)) (definterface ^{ dm.PetTypeAttribute x } I3 (^{ dm.PetTypeAttribute x } m1 [ x y]) (m2 [x ^{ dm.PetTypeAttribute x } y])) (deftype ^{System.SerializableAttribute {}} T1 [a ^{ dm.PetTypeAttribute x } b] I3 (^{ dm.PetTypeAttribute x } m1 [_ p q] p) (m2 [_ p ^{ dm.PetTypeAttribute x } q] q) )
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 ; Test of gen-class facility. ; ; Place this file in the clojure subdirectory of your main directory. ; Compile the file C.cs via: csc /t:library C.cs ; Place C.dll in your root directory. ; Start Clojure and do: ; (System.Reflection.Assembly/LoadFrom "C.dll") ; (compile 'clojure.testattribute) ; ; You should then be able to play games such as: (ns clojure.testattribute) (def x (dm.Pet/Dog)) (gen-interface :name ^{System.SerializableAttribute {} dm.PetTypeAttribute x} test.I1 :methods [ [m1 [] Object] ]) (definterface ^{System.SerializableAttribute {} dm.PetTypeAttribute x} I2 (m2 [])) ; (seq (.GetCustomAttributes test.I1 true)) ; (seq (.GetCustomAttributes I2 true)) (definterface ^{ dm.PetTypeAttribute x } I3 (^{ dm.PetTypeAttribute x } m1 [ x y]) (m2 [x ^{ dm.PetTypeAttribute x } y])) (deftype ^{System.SerializableAttribute {}} T1 [a ^{ dm.PetTypeAttribute x } b] I3 (^{ dm.PetTypeAttribute x } m1 [_ p q] p) (m2 [_ p ^{ dm.PetTypeAttribute x } q] q) )
[ { "context": "org\\\"\n :api-key \\\"EDC33DA4D977CFDF7B90545565E07324\\\"\n :app-id \\\"admi", "end": 650, "score": 0.9996482729911804, "start": 618, "tag": "KEY", "value": "EDC33DA4D977CFDF7B90545565E07324" }, { "context": "7324\\\"\n :app-id \\\"administer\\\"})\n\n (osf/defuser osf-test-user {:uri \\\"http://", "end": 706, "score": 0.7596719861030579, "start": 696, "tag": "KEY", "value": "administer" } ]
src/clj_osf/sparql.clj
structureddynamics/clj-osf
4
(ns clj-osf.sparql "Send a SPARQL Query to a OSF SPARQL web service endpoint The SPARQL Web service is used to send custom SPARQL queries against the OSF data structure. This is a general purpose querying Web service. To use the SPARQL code, you have to: ``` ;; Use/require the namespace (require '[clj-osf.sparql :as sparql]) ;; Define the OSF Sandbox credentials (or your own): (require '[clj-osf.core :as osf]) (osf/defosf osf-test-endpoint {:protocol :http :domain \"sandbox.opensemanticframework.org\" :api-key \"EDC33DA4D977CFDF7B90545565E07324\" :app-id \"administer\"}) (osf/defuser osf-test-user {:uri \"http://sandbox.opensemanticframework.org/wsf/users/admin\"}) ``` [Open Semantic Framework Endpoint Documentation](http://wiki.opensemanticframework.org/index.php/SPARQL#Web_Service_Endpoint_Information)" (:require [clj-osf.core :as core] [clojure.string :as string])) (defn dataset "URI of the dataset to query. Only use this function when you don't have FROM NAMED clauses in your SPARQL query. The usage of this function is **Optional** ##### Parameters * `[uri]` The dataset URI where the record is indexed. ##### Usage ``` (sparql/sparql (sparql/dataset \"http://sandbox.opensemanticframework.org/datasets/test/\")) ```" [uri] {:dataset uri}) (defn default-graph-uri "Specify the URI of the default graph to use for this SPARQL query. The usage of this function is **Optional** ##### Parameters * `[uri]` URI of the default graph ##### Usage ``` (sparql/sparql (sparql/default-graph-uri \"http://sandbox.opensemanticframework.org/datasets/test/\")) ```" [uri] {:default-graph-uri uri}) (defn named-graph-uri "Specify the URI of the named graph to use for this SPARQL query. The usage of this function is **Optional** ##### Parameters * `[uri]` URI of the named graph ##### Usage ``` (sparql/sparql (sparql/named-graph-uri \"http://sandbox.opensemanticframework.org/datasets/test/\")) ```" [uri] {:named-graph-uri uri}) (defn query "SPARQL query to send to the endpoint. The usage of this function is **Required** ##### Parameters * `[q]` SPARQL query to send to the endpoint ##### Usage ``` (sparql/sparql (sparql/named-graph-uri \"http://sandbox.opensemanticframework.org/datasets/test/\")) ```" [q] {:query q}) (defn sparql "SPARQL query. **Required** ##### Usage ``` (sparql/sparql (sparql/dataset \"http://sandbox.opensemanticframework.org/datasets/test/\") (sparql/query \"select * where {?s ?p ?o}\")) ```" [& body] (let [params (apply merge body) default (apply merge (query "") (dataset "") (default-graph-uri "") (named-graph-uri "") (core/->mime "application/sparql-results+json") (core/->post)) params (merge default params)] (core/osf-query "/ws/sparql/" params)))
16147
(ns clj-osf.sparql "Send a SPARQL Query to a OSF SPARQL web service endpoint The SPARQL Web service is used to send custom SPARQL queries against the OSF data structure. This is a general purpose querying Web service. To use the SPARQL code, you have to: ``` ;; Use/require the namespace (require '[clj-osf.sparql :as sparql]) ;; Define the OSF Sandbox credentials (or your own): (require '[clj-osf.core :as osf]) (osf/defosf osf-test-endpoint {:protocol :http :domain \"sandbox.opensemanticframework.org\" :api-key \"<KEY>\" :app-id \"<KEY>\"}) (osf/defuser osf-test-user {:uri \"http://sandbox.opensemanticframework.org/wsf/users/admin\"}) ``` [Open Semantic Framework Endpoint Documentation](http://wiki.opensemanticframework.org/index.php/SPARQL#Web_Service_Endpoint_Information)" (:require [clj-osf.core :as core] [clojure.string :as string])) (defn dataset "URI of the dataset to query. Only use this function when you don't have FROM NAMED clauses in your SPARQL query. The usage of this function is **Optional** ##### Parameters * `[uri]` The dataset URI where the record is indexed. ##### Usage ``` (sparql/sparql (sparql/dataset \"http://sandbox.opensemanticframework.org/datasets/test/\")) ```" [uri] {:dataset uri}) (defn default-graph-uri "Specify the URI of the default graph to use for this SPARQL query. The usage of this function is **Optional** ##### Parameters * `[uri]` URI of the default graph ##### Usage ``` (sparql/sparql (sparql/default-graph-uri \"http://sandbox.opensemanticframework.org/datasets/test/\")) ```" [uri] {:default-graph-uri uri}) (defn named-graph-uri "Specify the URI of the named graph to use for this SPARQL query. The usage of this function is **Optional** ##### Parameters * `[uri]` URI of the named graph ##### Usage ``` (sparql/sparql (sparql/named-graph-uri \"http://sandbox.opensemanticframework.org/datasets/test/\")) ```" [uri] {:named-graph-uri uri}) (defn query "SPARQL query to send to the endpoint. The usage of this function is **Required** ##### Parameters * `[q]` SPARQL query to send to the endpoint ##### Usage ``` (sparql/sparql (sparql/named-graph-uri \"http://sandbox.opensemanticframework.org/datasets/test/\")) ```" [q] {:query q}) (defn sparql "SPARQL query. **Required** ##### Usage ``` (sparql/sparql (sparql/dataset \"http://sandbox.opensemanticframework.org/datasets/test/\") (sparql/query \"select * where {?s ?p ?o}\")) ```" [& body] (let [params (apply merge body) default (apply merge (query "") (dataset "") (default-graph-uri "") (named-graph-uri "") (core/->mime "application/sparql-results+json") (core/->post)) params (merge default params)] (core/osf-query "/ws/sparql/" params)))
true
(ns clj-osf.sparql "Send a SPARQL Query to a OSF SPARQL web service endpoint The SPARQL Web service is used to send custom SPARQL queries against the OSF data structure. This is a general purpose querying Web service. To use the SPARQL code, you have to: ``` ;; Use/require the namespace (require '[clj-osf.sparql :as sparql]) ;; Define the OSF Sandbox credentials (or your own): (require '[clj-osf.core :as osf]) (osf/defosf osf-test-endpoint {:protocol :http :domain \"sandbox.opensemanticframework.org\" :api-key \"PI:KEY:<KEY>END_PI\" :app-id \"PI:KEY:<KEY>END_PI\"}) (osf/defuser osf-test-user {:uri \"http://sandbox.opensemanticframework.org/wsf/users/admin\"}) ``` [Open Semantic Framework Endpoint Documentation](http://wiki.opensemanticframework.org/index.php/SPARQL#Web_Service_Endpoint_Information)" (:require [clj-osf.core :as core] [clojure.string :as string])) (defn dataset "URI of the dataset to query. Only use this function when you don't have FROM NAMED clauses in your SPARQL query. The usage of this function is **Optional** ##### Parameters * `[uri]` The dataset URI where the record is indexed. ##### Usage ``` (sparql/sparql (sparql/dataset \"http://sandbox.opensemanticframework.org/datasets/test/\")) ```" [uri] {:dataset uri}) (defn default-graph-uri "Specify the URI of the default graph to use for this SPARQL query. The usage of this function is **Optional** ##### Parameters * `[uri]` URI of the default graph ##### Usage ``` (sparql/sparql (sparql/default-graph-uri \"http://sandbox.opensemanticframework.org/datasets/test/\")) ```" [uri] {:default-graph-uri uri}) (defn named-graph-uri "Specify the URI of the named graph to use for this SPARQL query. The usage of this function is **Optional** ##### Parameters * `[uri]` URI of the named graph ##### Usage ``` (sparql/sparql (sparql/named-graph-uri \"http://sandbox.opensemanticframework.org/datasets/test/\")) ```" [uri] {:named-graph-uri uri}) (defn query "SPARQL query to send to the endpoint. The usage of this function is **Required** ##### Parameters * `[q]` SPARQL query to send to the endpoint ##### Usage ``` (sparql/sparql (sparql/named-graph-uri \"http://sandbox.opensemanticframework.org/datasets/test/\")) ```" [q] {:query q}) (defn sparql "SPARQL query. **Required** ##### Usage ``` (sparql/sparql (sparql/dataset \"http://sandbox.opensemanticframework.org/datasets/test/\") (sparql/query \"select * where {?s ?p ?o}\")) ```" [& body] (let [params (apply merge body) default (apply merge (query "") (dataset "") (default-graph-uri "") (named-graph-uri "") (core/->mime "application/sparql-results+json") (core/->post)) params (merge default params)] (core/osf-query "/ws/sparql/" params)))
[ { "context": "({\\\"username\\\": \\\"\"\n (:username user)\n \"\\\"});});\")))])\n\n (if (=", "end": 1932, "score": 0.7022519707679749, "start": 1928, "tag": "USERNAME", "value": "user" }, { "context": " (str \"ga('set', '&uid', '\" (:username user) \"');\"))\n \"ga('send', 'pageview');\"]", "end": 2811, "score": 0.5240549445152283, "start": 2807, "tag": "USERNAME", "value": "user" }, { "context": " [:p\n [:input.form-control {:type \"password\" :name \"password\" :value \"\" :placeholder \"New pas", "end": 5985, "score": 0.6049068570137024, "start": 5977, "tag": "PASSWORD", "value": "password" } ]
src/clj/web/pages.clj
MNeMoNiCuZ/netrunner
0
(ns web.pages (:require [clj-time.core :as t] [clj-time.coerce :as c] [cheshire.core :as json] [hiccup.page :as hiccup] [monger.collection :as mc] [monger.operators :refer :all] [monger.result :refer [acknowledged?]] [web.db :refer [db object-id]] [web.config :refer [server-config]] [web.utils :refer [response]])) (defn layout [{:keys [version user] :as req} & content] (hiccup/html5 [:head [:meta {:charset "utf-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=0.6, minimal-ui"}] [:meta {:name "apple-mobile-web-app-capable" :content "yes"}] [:link {:rel "apple-touch-icon" :href "img/icons/jinteki_167.png"}] [:title "Jinteki"] (hiccup/include-css "/css/carousel.css") (hiccup/include-css (str "/css/netrunner.css?v=" version)) (hiccup/include-css "/lib/toastr/toastr.min.css") (hiccup/include-css "/lib/jqueryui/themes/base/jquery-ui.min.css")] [:body content (hiccup/include-js "/lib/jquery/jquery.min.js") (hiccup/include-js "/lib/jqueryui/jquery-ui.min.js") (hiccup/include-js "/lib/bootstrap/dist/js/bootstrap.js") (hiccup/include-js "/lib/moment/min/moment.min.js") (hiccup/include-js "/lib/marked/marked.min.js") (hiccup/include-js "/lib/toastr/toastr.min.js") (hiccup/include-js "/lib/howler/dist/howler.min.js") (hiccup/include-js "https://browser.sentry-cdn.com/4.1.1/bundle.min.js") [:script {:type "text/javascript"} (str "var user=" (json/generate-string user) ";")] (when-let [sentry-dsn (:sentry-dsn server-config)] [:script {:type "text/javascript"} (str "Sentry.init({ dsn: '" sentry-dsn "' });" (when user (str "Sentry.configureScope((scope) => {scope.setUser({\"username\": \"" (:username user) "\"});});")))]) (if (= "dev" @web.config/server-mode) (list (hiccup/include-js "/cljs/goog/base.js") (hiccup/include-js (str "cljs/app10.js?v=" version)) [:script (for [req ["dev.figwheel"]] (str "goog.require(\"" req "\");"))]) (list (hiccup/include-js (str "js/app10.js?v=" version)) [:script "(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-20250150-2', 'www.jinteki.net');" (when user (str "ga('set', '&uid', '" (:username user) "');")) "ga('send', 'pageview');"]))])) (defn index-page [req] (layout req [:nav.topnav.blue-shade [:div#left-menu] [:div#right-menu] [:div#status]] [:div#auth-forms] [:div#main.carousel.slide {:data-interval "false"} [:div.carousel-inner [:div.item.active [:div.home-bg] [:div.container [:h1 "Play Android: Netrunner in your browser"] [:div#news] [:div#chat]]] [:div.item [:div.cardbrowser-bg] [:div#cardbrowser]] [:div.item [:div.deckbuilder-bg] [:div.container [:div#deckbuilder]]] [:div.item [:div#gamelobby] [:div#gameboard]] [:div.item [:div.help-bg] [:div#help]] [:div.item [:div.account-bg] [:div#account]] [:div.item [:div.stats-bg] [:div#stats]] [:div.item [:div.about-bg] [:div#about]] [:div.item [:div.about-bg] [:div#tournament]]]] [:audio#ting [:source {:src "/sound/ting.mp3" :type "audio/mp3"}] [:source {:src "/sound/ting.ogg" :type "audio/ogg"}]])) (defn announce-page [req] (hiccup/html5 [:head [:title "Announce"] (hiccup/include-css "/css/netrunner.css")] [:body [:div.reset-bg] [:form.panel.blue-shade.reset-form {:method "POST"} [:h3 "Announcement"] [:p [:textarea.form-control {:rows 5 :style "height: 80px; width: 250px" :name "message" :autofocus true :required "required"}]] [:p [:button.btn.btn-primary {:type "submit"} "Submit"]]]])) (defn version-page [{:keys [version] :as req}] (hiccup/html5 [:head [:title "App Version"] (hiccup/include-css "/css/netrunner.css")] [:body [:div.reset-bg] [:form.panel.blue-shade.reset-form {:method "POST"} [:h3 "App Version"] [:p [:input {:type "text" :name "version" :value version}]] [:p [:button.btn.btn-primary {:type "submit"} "Submit"]]]])) (defn fetch-page [req] (hiccup/html5 [:head [:title "Update Card Data"] (hiccup/include-css "/css/netrunner.css")] [:body [:div.reset-bg] [:form.panel.blue-shade.reset-form {:method "POST"} (when-let [card-info (mc/find-one-as-map db "config" {})] [:div.admin [:div [:h3 "Card Version:"] (:cards-version card-info)] [:div [:h3 "Last Updated:"] (:last-updated card-info)]]) [:br] [:button.btn.btn-primary {:type "submit"} "Fetch Cards"]]])) (defn reset-password-page [{{:keys [token]} :params}] (if-let [user (mc/find-one-as-map db "users" {:resetPasswordToken token :resetPasswordExpires {"$gt" (c/to-date (t/now))}})] (hiccup/html5 [:head [:title "Jinteki"] (hiccup/include-css "/css/netrunner.css")] [:body [:div.reset-bg] [:form.panel.blue-shade.reset-form {:method "POST"} [:h3 "Password Reset"] [:p [:input.form-control {:type "password" :name "password" :value "" :placeholder "New password" :autofocus true :required "required"}]] [:p [:input.form-control {:type "password" :name "confirm" :value "" :placeholder "Confirm password" :required "required"}]] [:p [:button.btn.btn-primary {:type "submit"} "Update Password"]]]]) (response 404 {:message "Sorry, but that reset token is invalid or has expired."})))
4350
(ns web.pages (:require [clj-time.core :as t] [clj-time.coerce :as c] [cheshire.core :as json] [hiccup.page :as hiccup] [monger.collection :as mc] [monger.operators :refer :all] [monger.result :refer [acknowledged?]] [web.db :refer [db object-id]] [web.config :refer [server-config]] [web.utils :refer [response]])) (defn layout [{:keys [version user] :as req} & content] (hiccup/html5 [:head [:meta {:charset "utf-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=0.6, minimal-ui"}] [:meta {:name "apple-mobile-web-app-capable" :content "yes"}] [:link {:rel "apple-touch-icon" :href "img/icons/jinteki_167.png"}] [:title "Jinteki"] (hiccup/include-css "/css/carousel.css") (hiccup/include-css (str "/css/netrunner.css?v=" version)) (hiccup/include-css "/lib/toastr/toastr.min.css") (hiccup/include-css "/lib/jqueryui/themes/base/jquery-ui.min.css")] [:body content (hiccup/include-js "/lib/jquery/jquery.min.js") (hiccup/include-js "/lib/jqueryui/jquery-ui.min.js") (hiccup/include-js "/lib/bootstrap/dist/js/bootstrap.js") (hiccup/include-js "/lib/moment/min/moment.min.js") (hiccup/include-js "/lib/marked/marked.min.js") (hiccup/include-js "/lib/toastr/toastr.min.js") (hiccup/include-js "/lib/howler/dist/howler.min.js") (hiccup/include-js "https://browser.sentry-cdn.com/4.1.1/bundle.min.js") [:script {:type "text/javascript"} (str "var user=" (json/generate-string user) ";")] (when-let [sentry-dsn (:sentry-dsn server-config)] [:script {:type "text/javascript"} (str "Sentry.init({ dsn: '" sentry-dsn "' });" (when user (str "Sentry.configureScope((scope) => {scope.setUser({\"username\": \"" (:username user) "\"});});")))]) (if (= "dev" @web.config/server-mode) (list (hiccup/include-js "/cljs/goog/base.js") (hiccup/include-js (str "cljs/app10.js?v=" version)) [:script (for [req ["dev.figwheel"]] (str "goog.require(\"" req "\");"))]) (list (hiccup/include-js (str "js/app10.js?v=" version)) [:script "(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-20250150-2', 'www.jinteki.net');" (when user (str "ga('set', '&uid', '" (:username user) "');")) "ga('send', 'pageview');"]))])) (defn index-page [req] (layout req [:nav.topnav.blue-shade [:div#left-menu] [:div#right-menu] [:div#status]] [:div#auth-forms] [:div#main.carousel.slide {:data-interval "false"} [:div.carousel-inner [:div.item.active [:div.home-bg] [:div.container [:h1 "Play Android: Netrunner in your browser"] [:div#news] [:div#chat]]] [:div.item [:div.cardbrowser-bg] [:div#cardbrowser]] [:div.item [:div.deckbuilder-bg] [:div.container [:div#deckbuilder]]] [:div.item [:div#gamelobby] [:div#gameboard]] [:div.item [:div.help-bg] [:div#help]] [:div.item [:div.account-bg] [:div#account]] [:div.item [:div.stats-bg] [:div#stats]] [:div.item [:div.about-bg] [:div#about]] [:div.item [:div.about-bg] [:div#tournament]]]] [:audio#ting [:source {:src "/sound/ting.mp3" :type "audio/mp3"}] [:source {:src "/sound/ting.ogg" :type "audio/ogg"}]])) (defn announce-page [req] (hiccup/html5 [:head [:title "Announce"] (hiccup/include-css "/css/netrunner.css")] [:body [:div.reset-bg] [:form.panel.blue-shade.reset-form {:method "POST"} [:h3 "Announcement"] [:p [:textarea.form-control {:rows 5 :style "height: 80px; width: 250px" :name "message" :autofocus true :required "required"}]] [:p [:button.btn.btn-primary {:type "submit"} "Submit"]]]])) (defn version-page [{:keys [version] :as req}] (hiccup/html5 [:head [:title "App Version"] (hiccup/include-css "/css/netrunner.css")] [:body [:div.reset-bg] [:form.panel.blue-shade.reset-form {:method "POST"} [:h3 "App Version"] [:p [:input {:type "text" :name "version" :value version}]] [:p [:button.btn.btn-primary {:type "submit"} "Submit"]]]])) (defn fetch-page [req] (hiccup/html5 [:head [:title "Update Card Data"] (hiccup/include-css "/css/netrunner.css")] [:body [:div.reset-bg] [:form.panel.blue-shade.reset-form {:method "POST"} (when-let [card-info (mc/find-one-as-map db "config" {})] [:div.admin [:div [:h3 "Card Version:"] (:cards-version card-info)] [:div [:h3 "Last Updated:"] (:last-updated card-info)]]) [:br] [:button.btn.btn-primary {:type "submit"} "Fetch Cards"]]])) (defn reset-password-page [{{:keys [token]} :params}] (if-let [user (mc/find-one-as-map db "users" {:resetPasswordToken token :resetPasswordExpires {"$gt" (c/to-date (t/now))}})] (hiccup/html5 [:head [:title "Jinteki"] (hiccup/include-css "/css/netrunner.css")] [:body [:div.reset-bg] [:form.panel.blue-shade.reset-form {:method "POST"} [:h3 "Password Reset"] [:p [:input.form-control {:type "<PASSWORD>" :name "password" :value "" :placeholder "New password" :autofocus true :required "required"}]] [:p [:input.form-control {:type "password" :name "confirm" :value "" :placeholder "Confirm password" :required "required"}]] [:p [:button.btn.btn-primary {:type "submit"} "Update Password"]]]]) (response 404 {:message "Sorry, but that reset token is invalid or has expired."})))
true
(ns web.pages (:require [clj-time.core :as t] [clj-time.coerce :as c] [cheshire.core :as json] [hiccup.page :as hiccup] [monger.collection :as mc] [monger.operators :refer :all] [monger.result :refer [acknowledged?]] [web.db :refer [db object-id]] [web.config :refer [server-config]] [web.utils :refer [response]])) (defn layout [{:keys [version user] :as req} & content] (hiccup/html5 [:head [:meta {:charset "utf-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=0.6, minimal-ui"}] [:meta {:name "apple-mobile-web-app-capable" :content "yes"}] [:link {:rel "apple-touch-icon" :href "img/icons/jinteki_167.png"}] [:title "Jinteki"] (hiccup/include-css "/css/carousel.css") (hiccup/include-css (str "/css/netrunner.css?v=" version)) (hiccup/include-css "/lib/toastr/toastr.min.css") (hiccup/include-css "/lib/jqueryui/themes/base/jquery-ui.min.css")] [:body content (hiccup/include-js "/lib/jquery/jquery.min.js") (hiccup/include-js "/lib/jqueryui/jquery-ui.min.js") (hiccup/include-js "/lib/bootstrap/dist/js/bootstrap.js") (hiccup/include-js "/lib/moment/min/moment.min.js") (hiccup/include-js "/lib/marked/marked.min.js") (hiccup/include-js "/lib/toastr/toastr.min.js") (hiccup/include-js "/lib/howler/dist/howler.min.js") (hiccup/include-js "https://browser.sentry-cdn.com/4.1.1/bundle.min.js") [:script {:type "text/javascript"} (str "var user=" (json/generate-string user) ";")] (when-let [sentry-dsn (:sentry-dsn server-config)] [:script {:type "text/javascript"} (str "Sentry.init({ dsn: '" sentry-dsn "' });" (when user (str "Sentry.configureScope((scope) => {scope.setUser({\"username\": \"" (:username user) "\"});});")))]) (if (= "dev" @web.config/server-mode) (list (hiccup/include-js "/cljs/goog/base.js") (hiccup/include-js (str "cljs/app10.js?v=" version)) [:script (for [req ["dev.figwheel"]] (str "goog.require(\"" req "\");"))]) (list (hiccup/include-js (str "js/app10.js?v=" version)) [:script "(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-20250150-2', 'www.jinteki.net');" (when user (str "ga('set', '&uid', '" (:username user) "');")) "ga('send', 'pageview');"]))])) (defn index-page [req] (layout req [:nav.topnav.blue-shade [:div#left-menu] [:div#right-menu] [:div#status]] [:div#auth-forms] [:div#main.carousel.slide {:data-interval "false"} [:div.carousel-inner [:div.item.active [:div.home-bg] [:div.container [:h1 "Play Android: Netrunner in your browser"] [:div#news] [:div#chat]]] [:div.item [:div.cardbrowser-bg] [:div#cardbrowser]] [:div.item [:div.deckbuilder-bg] [:div.container [:div#deckbuilder]]] [:div.item [:div#gamelobby] [:div#gameboard]] [:div.item [:div.help-bg] [:div#help]] [:div.item [:div.account-bg] [:div#account]] [:div.item [:div.stats-bg] [:div#stats]] [:div.item [:div.about-bg] [:div#about]] [:div.item [:div.about-bg] [:div#tournament]]]] [:audio#ting [:source {:src "/sound/ting.mp3" :type "audio/mp3"}] [:source {:src "/sound/ting.ogg" :type "audio/ogg"}]])) (defn announce-page [req] (hiccup/html5 [:head [:title "Announce"] (hiccup/include-css "/css/netrunner.css")] [:body [:div.reset-bg] [:form.panel.blue-shade.reset-form {:method "POST"} [:h3 "Announcement"] [:p [:textarea.form-control {:rows 5 :style "height: 80px; width: 250px" :name "message" :autofocus true :required "required"}]] [:p [:button.btn.btn-primary {:type "submit"} "Submit"]]]])) (defn version-page [{:keys [version] :as req}] (hiccup/html5 [:head [:title "App Version"] (hiccup/include-css "/css/netrunner.css")] [:body [:div.reset-bg] [:form.panel.blue-shade.reset-form {:method "POST"} [:h3 "App Version"] [:p [:input {:type "text" :name "version" :value version}]] [:p [:button.btn.btn-primary {:type "submit"} "Submit"]]]])) (defn fetch-page [req] (hiccup/html5 [:head [:title "Update Card Data"] (hiccup/include-css "/css/netrunner.css")] [:body [:div.reset-bg] [:form.panel.blue-shade.reset-form {:method "POST"} (when-let [card-info (mc/find-one-as-map db "config" {})] [:div.admin [:div [:h3 "Card Version:"] (:cards-version card-info)] [:div [:h3 "Last Updated:"] (:last-updated card-info)]]) [:br] [:button.btn.btn-primary {:type "submit"} "Fetch Cards"]]])) (defn reset-password-page [{{:keys [token]} :params}] (if-let [user (mc/find-one-as-map db "users" {:resetPasswordToken token :resetPasswordExpires {"$gt" (c/to-date (t/now))}})] (hiccup/html5 [:head [:title "Jinteki"] (hiccup/include-css "/css/netrunner.css")] [:body [:div.reset-bg] [:form.panel.blue-shade.reset-form {:method "POST"} [:h3 "Password Reset"] [:p [:input.form-control {:type "PI:PASSWORD:<PASSWORD>END_PI" :name "password" :value "" :placeholder "New password" :autofocus true :required "required"}]] [:p [:input.form-control {:type "password" :name "confirm" :value "" :placeholder "Confirm password" :required "required"}]] [:p [:button.btn.btn-primary {:type "submit"} "Update Password"]]]]) (response 404 {:message "Sorry, but that reset token is invalid or has expired."})))
[ { "context": "iberator + Compojure\"\n\n :url \"https://github.com/ertugrulcetin/patika\"\n\n :author \"Ertuğrul Çetin\"\n\n :license {", "end": 162, "score": 0.9947991967201233, "start": 149, "tag": "USERNAME", "value": "ertugrulcetin" }, { "context": "ps://github.com/ertugrulcetin/patika\"\n\n :author \"Ertuğrul Çetin\"\n\n :license {:name \"MIT License\" :url \"https://o", "end": 197, "score": 0.9998962879180908, "start": 183, "tag": "NAME", "value": "Ertuğrul Çetin" } ]
project.clj
ertugrulcetin/patika
14
(defproject patika "0.1.11" :description "Clojure routing library which is an abstraction over Liberator + Compojure" :url "https://github.com/ertugrulcetin/patika" :author "Ertuğrul Çetin" :license {:name "MIT License" :url "https://opensource.org/licenses/MIT"} :deploy-repositories [["clojars" {:sign-releases false :url "https://clojars.org/repo"}] ["releases" {:sign-releases false :url "https://clojars.org/repo"}] ["snapshots" {:sign-releases false :url "https://clojars.org/repo"}]] :dependencies [[org.clojure/clojure "1.10.1"] [org.clojure/data.json "1.0.0"] [org.clojure/tools.logging "1.0.0"] [org.clojure/java.classpath "1.0.0"] [org.clojure/tools.namespace "1.0.0"] [compojure "1.6.1"] [liberator "0.15.3"]])
69266
(defproject patika "0.1.11" :description "Clojure routing library which is an abstraction over Liberator + Compojure" :url "https://github.com/ertugrulcetin/patika" :author "<NAME>" :license {:name "MIT License" :url "https://opensource.org/licenses/MIT"} :deploy-repositories [["clojars" {:sign-releases false :url "https://clojars.org/repo"}] ["releases" {:sign-releases false :url "https://clojars.org/repo"}] ["snapshots" {:sign-releases false :url "https://clojars.org/repo"}]] :dependencies [[org.clojure/clojure "1.10.1"] [org.clojure/data.json "1.0.0"] [org.clojure/tools.logging "1.0.0"] [org.clojure/java.classpath "1.0.0"] [org.clojure/tools.namespace "1.0.0"] [compojure "1.6.1"] [liberator "0.15.3"]])
true
(defproject patika "0.1.11" :description "Clojure routing library which is an abstraction over Liberator + Compojure" :url "https://github.com/ertugrulcetin/patika" :author "PI:NAME:<NAME>END_PI" :license {:name "MIT License" :url "https://opensource.org/licenses/MIT"} :deploy-repositories [["clojars" {:sign-releases false :url "https://clojars.org/repo"}] ["releases" {:sign-releases false :url "https://clojars.org/repo"}] ["snapshots" {:sign-releases false :url "https://clojars.org/repo"}]] :dependencies [[org.clojure/clojure "1.10.1"] [org.clojure/data.json "1.0.0"] [org.clojure/tools.logging "1.0.0"] [org.clojure/java.classpath "1.0.0"] [org.clojure/tools.namespace "1.0.0"] [compojure "1.6.1"] [liberator "0.15.3"]])
[ { "context": "; Copyright (c) 2017-present Walmart, Inc.\n;\n; Licensed under the Apache License", "end": 30, "score": 0.5376325249671936, "start": 29, "tag": "NAME", "value": "W" } ]
src/com/walmartlabs/lacinia/trace.clj
jeffp42ker/lacinia
0
; Copyright (c) 2017-present Walmart, Inc. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns com.walmartlabs.lacinia.trace "Light-weight, asynchronous logging built around tap>. Follows the same pattern as clojure.core/assert: When tracing is not compiled, the tracing macros should create no runtime overhead. When tracing is compiled, a check occurs to see if tracing is enabled; only then do the most expensive operations (e.g., identifying the function containing the trace call) occur, as well as the call to clojure.core/tap>." {:no-doc true} (:require [io.aviso.exception :refer [demangle]] [clojure.string :as string] [clojure.pprint :refer [pprint]])) (def ^:dynamic *compile-trace* "If false (the default), calls to trace evaluate to nil." false) (def ^:dynamic *enable-trace* "If false (the default is true) then compiled calls to trace are a no-op." true) (defn set-compile-trace! [value] (alter-var-root #'*compile-trace* (constantly value))) (defn set-enable-trace! [value] (alter-var-root #'*enable-trace* (constantly value))) (defn ^:private extract-fn-name [class-name] (let [[ns-id & raw-function-ids] (string/split class-name #"\$") fn-name (->> raw-function-ids (map #(string/replace % #"__\d+" "")) (map demangle) (string/join "/"))] (symbol (demangle ns-id) fn-name))) (defn ^:private in-trace-ns? [^StackTraceElement frame] (string/starts-with? (.getClassName frame) "com.walmartlabs.lacinia.trace$")) (defn ^:no-doc extract-in [] (let [stack-frame (->> (Thread/currentThread) .getStackTrace (drop 1) ; Thread/getStackTrace (drop-while in-trace-ns?) first)] (extract-fn-name (.getClassName ^StackTraceElement stack-frame)))) (defmacro ^:no-doc emit-trace [trace-line & kvs] ;; Maps are expected to be small; array-map ensures that the keys are in insertion order. `(when *enable-trace* (tap> (array-map :in (extract-in) ~@(when trace-line [:line trace-line]) :thread (.getName (Thread/currentThread)) ~@kvs)) nil)) (defmacro trace "Calls to trace generate a map that is passed to `tap>`. The map includes keys: :in - a symbol of the namespace and function :line - the line number of the trace invocation (if available) :thread - the string name of the current thread Additional keys and values may be supplied. trace may expand to nil, if compilation is disabled. Any invocation of trace evaluates to nil." [& kvs] (assert (even? (count kvs)) "pass key/value pairs") (when *compile-trace* (let [{:keys [line]} (meta &form)] `(emit-trace ~line ~@kvs)))) (defmacro trace> "A version of trace that works inside -> thread expressions. Within the trace body, `%` is bound to the threaded value. When compilation is disabled, `(trace> <form>)` is replaced by just `<form>`." [value & kvs] (assert (even? (count kvs)) "pass key/value pairs") (if-not *compile-trace* value (let [{:keys [line]} (meta &form)] `(let [~'% ~value] (emit-trace ~line ~@kvs) ~'%)))) (defmacro trace>> "A version of trace that works inside ->> thread expressions. Within the trace body, `%` is bound to the threaded value. When compilation is disabled, `(trace>> <form>)` expands to just `<form>`." ;; This is tricky because the value comes at the end due to ->> so we have to ;; work harder (fortunately, at compile time) to separate the value expression ;; from the keys and values. [& kvs-then-value] (let [value (last kvs-then-value) kvs (butlast kvs-then-value)] (assert (even? (count kvs)) "pass key/value pairs") (if-not *compile-trace* value (let [{:keys [line]} (meta &form)] `(let [~'% ~value] (emit-trace ~line ~@kvs) ~'%))))) (defn setup-default "Enables tracing output with a default tap of `pprint`." [] (set-compile-trace! true) (set-enable-trace! true) (add-tap pprint))
98391
; Copyright (c) 2017-present <NAME>almart, Inc. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns com.walmartlabs.lacinia.trace "Light-weight, asynchronous logging built around tap>. Follows the same pattern as clojure.core/assert: When tracing is not compiled, the tracing macros should create no runtime overhead. When tracing is compiled, a check occurs to see if tracing is enabled; only then do the most expensive operations (e.g., identifying the function containing the trace call) occur, as well as the call to clojure.core/tap>." {:no-doc true} (:require [io.aviso.exception :refer [demangle]] [clojure.string :as string] [clojure.pprint :refer [pprint]])) (def ^:dynamic *compile-trace* "If false (the default), calls to trace evaluate to nil." false) (def ^:dynamic *enable-trace* "If false (the default is true) then compiled calls to trace are a no-op." true) (defn set-compile-trace! [value] (alter-var-root #'*compile-trace* (constantly value))) (defn set-enable-trace! [value] (alter-var-root #'*enable-trace* (constantly value))) (defn ^:private extract-fn-name [class-name] (let [[ns-id & raw-function-ids] (string/split class-name #"\$") fn-name (->> raw-function-ids (map #(string/replace % #"__\d+" "")) (map demangle) (string/join "/"))] (symbol (demangle ns-id) fn-name))) (defn ^:private in-trace-ns? [^StackTraceElement frame] (string/starts-with? (.getClassName frame) "com.walmartlabs.lacinia.trace$")) (defn ^:no-doc extract-in [] (let [stack-frame (->> (Thread/currentThread) .getStackTrace (drop 1) ; Thread/getStackTrace (drop-while in-trace-ns?) first)] (extract-fn-name (.getClassName ^StackTraceElement stack-frame)))) (defmacro ^:no-doc emit-trace [trace-line & kvs] ;; Maps are expected to be small; array-map ensures that the keys are in insertion order. `(when *enable-trace* (tap> (array-map :in (extract-in) ~@(when trace-line [:line trace-line]) :thread (.getName (Thread/currentThread)) ~@kvs)) nil)) (defmacro trace "Calls to trace generate a map that is passed to `tap>`. The map includes keys: :in - a symbol of the namespace and function :line - the line number of the trace invocation (if available) :thread - the string name of the current thread Additional keys and values may be supplied. trace may expand to nil, if compilation is disabled. Any invocation of trace evaluates to nil." [& kvs] (assert (even? (count kvs)) "pass key/value pairs") (when *compile-trace* (let [{:keys [line]} (meta &form)] `(emit-trace ~line ~@kvs)))) (defmacro trace> "A version of trace that works inside -> thread expressions. Within the trace body, `%` is bound to the threaded value. When compilation is disabled, `(trace> <form>)` is replaced by just `<form>`." [value & kvs] (assert (even? (count kvs)) "pass key/value pairs") (if-not *compile-trace* value (let [{:keys [line]} (meta &form)] `(let [~'% ~value] (emit-trace ~line ~@kvs) ~'%)))) (defmacro trace>> "A version of trace that works inside ->> thread expressions. Within the trace body, `%` is bound to the threaded value. When compilation is disabled, `(trace>> <form>)` expands to just `<form>`." ;; This is tricky because the value comes at the end due to ->> so we have to ;; work harder (fortunately, at compile time) to separate the value expression ;; from the keys and values. [& kvs-then-value] (let [value (last kvs-then-value) kvs (butlast kvs-then-value)] (assert (even? (count kvs)) "pass key/value pairs") (if-not *compile-trace* value (let [{:keys [line]} (meta &form)] `(let [~'% ~value] (emit-trace ~line ~@kvs) ~'%))))) (defn setup-default "Enables tracing output with a default tap of `pprint`." [] (set-compile-trace! true) (set-enable-trace! true) (add-tap pprint))
true
; Copyright (c) 2017-present PI:NAME:<NAME>END_PIalmart, Inc. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns com.walmartlabs.lacinia.trace "Light-weight, asynchronous logging built around tap>. Follows the same pattern as clojure.core/assert: When tracing is not compiled, the tracing macros should create no runtime overhead. When tracing is compiled, a check occurs to see if tracing is enabled; only then do the most expensive operations (e.g., identifying the function containing the trace call) occur, as well as the call to clojure.core/tap>." {:no-doc true} (:require [io.aviso.exception :refer [demangle]] [clojure.string :as string] [clojure.pprint :refer [pprint]])) (def ^:dynamic *compile-trace* "If false (the default), calls to trace evaluate to nil." false) (def ^:dynamic *enable-trace* "If false (the default is true) then compiled calls to trace are a no-op." true) (defn set-compile-trace! [value] (alter-var-root #'*compile-trace* (constantly value))) (defn set-enable-trace! [value] (alter-var-root #'*enable-trace* (constantly value))) (defn ^:private extract-fn-name [class-name] (let [[ns-id & raw-function-ids] (string/split class-name #"\$") fn-name (->> raw-function-ids (map #(string/replace % #"__\d+" "")) (map demangle) (string/join "/"))] (symbol (demangle ns-id) fn-name))) (defn ^:private in-trace-ns? [^StackTraceElement frame] (string/starts-with? (.getClassName frame) "com.walmartlabs.lacinia.trace$")) (defn ^:no-doc extract-in [] (let [stack-frame (->> (Thread/currentThread) .getStackTrace (drop 1) ; Thread/getStackTrace (drop-while in-trace-ns?) first)] (extract-fn-name (.getClassName ^StackTraceElement stack-frame)))) (defmacro ^:no-doc emit-trace [trace-line & kvs] ;; Maps are expected to be small; array-map ensures that the keys are in insertion order. `(when *enable-trace* (tap> (array-map :in (extract-in) ~@(when trace-line [:line trace-line]) :thread (.getName (Thread/currentThread)) ~@kvs)) nil)) (defmacro trace "Calls to trace generate a map that is passed to `tap>`. The map includes keys: :in - a symbol of the namespace and function :line - the line number of the trace invocation (if available) :thread - the string name of the current thread Additional keys and values may be supplied. trace may expand to nil, if compilation is disabled. Any invocation of trace evaluates to nil." [& kvs] (assert (even? (count kvs)) "pass key/value pairs") (when *compile-trace* (let [{:keys [line]} (meta &form)] `(emit-trace ~line ~@kvs)))) (defmacro trace> "A version of trace that works inside -> thread expressions. Within the trace body, `%` is bound to the threaded value. When compilation is disabled, `(trace> <form>)` is replaced by just `<form>`." [value & kvs] (assert (even? (count kvs)) "pass key/value pairs") (if-not *compile-trace* value (let [{:keys [line]} (meta &form)] `(let [~'% ~value] (emit-trace ~line ~@kvs) ~'%)))) (defmacro trace>> "A version of trace that works inside ->> thread expressions. Within the trace body, `%` is bound to the threaded value. When compilation is disabled, `(trace>> <form>)` expands to just `<form>`." ;; This is tricky because the value comes at the end due to ->> so we have to ;; work harder (fortunately, at compile time) to separate the value expression ;; from the keys and values. [& kvs-then-value] (let [value (last kvs-then-value) kvs (butlast kvs-then-value)] (assert (even? (count kvs)) "pass key/value pairs") (if-not *compile-trace* value (let [{:keys [line]} (meta &form)] `(let [~'% ~value] (emit-trace ~line ~@kvs) ~'%))))) (defn setup-default "Enables tracing output with a default tap of `pprint`." [] (set-compile-trace! true) (set-enable-trace! true) (add-tap pprint))
[ { "context": "ogic WorkBench -- Combinatory logic, Examples from Raymond Smullyan: How to Mock a Mockingbird\n\n; Copyright ", "end": 65, "score": 0.6860241889953613, "start": 58, "tag": "NAME", "value": "Raymond" }, { "context": ": How to Mock a Mockingbird\n\n; Copyright (c) 2019 Burkhardt Renz, THM. All rights reserved.\n; The use and distribu", "end": 139, "score": 0.999879777431488, "start": 125, "tag": "NAME", "value": "Burkhardt Renz" } ]
src/lwb/cl/examples/smullyan.clj
esb-lwb/lwb
22
; lwb Logic WorkBench -- Combinatory logic, Examples from Raymond Smullyan: How to Mock a Mockingbird ; Copyright (c) 2019 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.cl.examples.smullyan (:require [lwb.cl :refer :all] [lwb.cl.repl :refer :all])) ;; Chap 9: To Mock a Mockingbird ---------------------------------------------- (reset-combinators) ;; Mockingbird p.73 (def-combinator '[M x] '[x x] "Mockingbird") (show-combinators) ;; Composition ;; Definition: C composes A with B if for every x: C x = A (B x). ;; The composition condition: For every A, B exists C that composes A with B. ;; Definition: A is fond of B if A B = B. ;; Definition: A is called egocentric if A A = A, i.e. A is fond of itself. ;; Definition: Two combinators A, B agree on x if A x = B x. ;; Definition: A is agreeable if for every B there is a x such that A x = B x. ;; Definition: Two combinators A and B are compatible if there are x, y such that A x = y and B y = x. ;; Definition: A combinator A is happy if there are x, y such that A x = y and A y = x, ;; i.e. A is compatible with itself. ;; Definition: A combinator A is normal if exists B such that A B = B, i.e. exists B such that A is fond of B. ;; Definition: A combinator B is hopelessly egocentric if B B = B. ;; Definition: A is fixated on B if for every x: A x = B. ;; Kestrel p.77 (def-combinator '[K x y] '[x] "Kestrel") (show-combinators) ;; Left cancellation law for kestrels: if K x = K y then x = y. ;; Identity Bird aka Idiot p.78 (def-combinator '[I x] '[x] "Identity Bird") (show-combinators) ;; Lark p.80 (def-combinator '[L x y] '[x (y y)] "Lark") (show-combinators) ;; 24 ; Given L and I, then there is a M with M x = x x. (session '[L I x]) (red :L) (red :I) ; or (weak-reduce '[L I x]) ; L I x -> x x, i.e. M = L I ;; 25 ; Given L, then every bird x is fond of at least one bird (session '[x (L x (L x))]) (exp :L) ; x (L x (L x)) = L x (L x) ; Any bird x is fond of L x (L x) = (L x) (L x) ;; 26 ; Given L, then there is a bird of whom L L is fond (session '[L L ((L (L L)) (L (L L)))]) (red :L) ; => [L (L (L L) (L (L L)) (L (L L) (L (L L))))] ;; Chap 10: Is There a Sage Bird? --------------------------------------------- ; A sage bird Theta is a bird with x (Theta x) = Theta x, aka a fixed point combinator ; There is such a bird: the composition of M and L (session '[M (L x)]) (red :M) (red :L) (exp :M) (session '[x (M (L x))]) (red :M) (exp :L) (exp :M) ; [x (M (L x))] = [M (L x)] ;; Chap 11: Birds Galore ------------------------------------------------------ ; Introduction (max-parens '[x y (z w y) v]) ; => [(((x y) ((z w) y)) v)] (max-parens '[(x y z) (w v x)]) ; => [(((x y) z) ((w v) x))] (max-parens '[x y (z w v) (x z)]) ; => [(((x y) ((z w) v)) (x z))] (max-parens '[x y (z w v) x z]) ; => [((((x y) ((z w) v)) x) z)] (max-parens '[x (y (z w v)) x z]) ; => [(((x (y ((z w) v))) x) z)] (= (max-parens '[x y z (A B)]) (max-parens '[(x y z) (A B)])) ; => true (= (max-parens '[x y w]) (max-parens (subst '[z w] '[z] '(x y)))) ; => true (= (max-parens '[w x y]) (max-parens (subst '[w z] '[z] '(x y)))) ; => false ;; Bluebird p.95 (def-combinator '[B x y z] '[x (y z)] "Bluebird") (show-combinators) ;; 1 ; Given B then the composition law holds (session '[(B f g) x]) (red :B) ; => [f (g x)] i.e. [B f g] composes f with g. ; Let's use this fact (session '[B M L x]) (red :B) (red :M) (red :L) (exp :M) (exp :B 2) ; => [x (B M L x) i.e. B M L is a sage bird ;; 2 ; Given B and M, write down an expression in terms of B, M, x that describes a bird of which x is fond. (session '[(M (B x M))]) (red :M) (red :B) ; => [x (M (B x M))] (session '[x (M (B x M))]) (exp :B) (exp :M) ; => [M (B x M)] ; x is fond of M (B x M) ;; 3 ; Given B and M, find egocentric bird (session '[M (B M M)]) (red :M) (red :B) (red :M) ; => [M (B M M) (M (B M M))] ; M (B M M) is egocentric, i.e. Z = Z Z ;; 4 ; Given B, M and K, find hopelessly egocentric bird ; M (B K M) is hopelessly egocentric , i.e. for all x: Z x = Z (session '[M (B K M) x]) (red :M) (red :B) (red :K) ; => [M (B K M)] (session '[M (B K M)]) (exp :K) (swap '?1 '[x]) (exp :B) (exp :M) ; => [M (B K M) x] ;; Dove p.97 (def-combinator '[D x y z w] '[x y (z w)] "Dove") (show-combinators) ;; 5 ; D can be derived from B alone, how? (session '[B B x y z w]) (red :B) (red :B) ; => [x y (z w)], i.e. D = B B. (= (weak-reduce '[B B x y z w]) (weak-reduce '[D x y z w])) ; => true ;; Blackbird p.97 (def-combinator '[B1 x y z w] '[x (y z w)] "Blackbird") (show-combinators) ;; 6 ; Given B, then there is a D and a B1 too: ; D = B B, and B1 = D B = B B B (weak-reduce '[D B x y z w]) ; => [x (y z w)], i.e. B1 = D B. (weak-reduce '[B B B x y z w]) ; => [x (y z w)], i.e. B1 = B B B. ;; Eagle p.97 (def-combinator '[E x y z w v] '[x y (z w v)] "Eagle") (show-combinators) ;; 7 ; Derive E from B (weak-reduce '[B B1 x y z w v]) ; => [x y (z w v)], i.e. E = B B1 = B (B B B). ;; Bunting p.97 (def-combinator '[B2 x y z w v] '[x (y z w v)] "Bunting") (show-combinators) ;; 8 ; Given B find B2 (weak-reduce '[E B x y z w v]) ; => x (y z w v)] (weak-reduce '[B B1 B x y z w v]) ; => [x (y z w v)], i.e. B2 = B (B B B) B ; but this is true too (weak-reduce '[B B B1 x y z w v]) ; => [x (y z w v)], i.e. B2 = B B (B B B) ;; Dickcissel p.97 (def-combinator '[D1 x y z w v] '[x y z (w v)] "Dickcissel") (show-combinators) ;; 9 ; Derive D1 from B (weak-reduce '[B1 B x y z w v]) ; => [x y z (w v)] (weak-reduce '[B B B B x y z w v]) ; => [x y z (w v)], i.e. D1 = B B B B (weak-reduce '[B (B B) x y z w v]) ; => [x y z (w v)], i.e. D1 = B (B B) ;; Becard p.98 (def-combinator '[B3 x y z w] '[x (y (z w))] "Becard") (show-combinators) ;; 10 ; Derive B3 from B (weak-reduce '[D1 B x y z w]) ; => [x (y (z w))] (weak-reduce '[B (B B) B x y z w]) ; => [x (y (z w))] (weak-reduce '[B B B B B x y z w]) ; => [x (y (z w))] ;; Dovekie p.98 (def-combinator '[D2 x y z w v] '[x (y z) (w v)] "Dovekie") (show-combinators) ;; 11 ; Derive D2 from B (weak-reduce '[B B (B B) x y z w v]) ; => [x (y z) (w v)], i.e. D2 = B B (B B) (weak-reduce '[D D x y z w v]) ; => [x (y z) (w v)], i.e. D2 = D D ;; Bald Eagle p.98 (def-combinator '[Ê x y1 y2 y3 z1 z2 z3] '[x (y1 y2 y3) (z1 z2 z3)] "Bald Eagle") (show-combinators) ;; 12 ; Derive Ê from B (weak-reduce '[E E x y_1 y_2 y_3 z_1 z_2 z_3]) ; => [x (y_1 y_2 y_3) (z_1 z_2 z_3)] (weak-reduce '[B (B B B) (B (B B B)) x y_1 y_2 y_3 z_1 z_2 z_3]) ; => [x (y_1 y_2 y_3) (z_1 z_2 z_3)], i.e. Ê = B (B B B) (B (B B B)) ;; Warbler p.99 (def-combinator '[W x y] '[x y y] "Warbler") (show-combinators) ;; 14 ; Derive M from W and I (weak-reduce '[W I x]) (weak-reduce '[M x]) ; => M = W I ;; 15 ; Derive I from W and K (weak-reduce '[W K x]) ; => W K = I ;; 13 ; Now derive M from W and K (weak-reduce '[W (W K) x]) ; => [x x], i.e. W (W K) = M. ; in steps: (session '[W (W K) x]) (red :W) (red :W) (red :K) ;; Cardinal p.100 (def-combinator '[C x y z] '[x z y] "Cardinal") (show-combinators) ;; 16 ; Derive I from C and K (weak-reduce '[C K K x]) ; => [x], i.e. C K K = I. (weak-reduce '[C K C x]) ; => [x] (weak-reduce '[C K any x]) ; => [x] ;; Trush p.100 (def-combinator '[T x y] '[y x] "Trush") (show-combinators) ;; 17 ; Derive T from C and I (weak-reduce '[C I x y]) ; => [y x], i.e. T = C I. ;; Definition: A and B commute if A B = B A ;; 19 ; Given B, T and M find a bird that commutes with every bird (session '[M (B T M) x]) (red :M) (red :B) (red :T) ; => [x (M (B T M))], i.e. M (B T M) commutes with any x. ;; Robin p.101 (def-combinator '[R x y z] '[y z x] "Robin") (show-combinators) ;; 20 ; Derive R from B and T (weak-reduce '[B B T x y z]) ; => y z x], i.e. R = B B T. ;; 21 ; Derive C from R alone (weak-reduce '[R R R x y z]) ; => [x z y], i.e. R R R = C ; Derive C from B B T with 9 letters (weak-reduce '[B B T (B B T) (B B T) x y z]) ; => [x z y] ; A shorter term with 8 letters? (weak-reduce '[B B T (B B T) (B B T)]) ; => [B (T (B B T)) (B B T)] hence (weak-reduce '[B (T (B B T)) (B B T) x y z]) ; => [x z y] ;; 22 Two useful laws ;; 22a (session '[C x y z]) (red :C) (exp :R) (exp :R 2) ; => [R x R y z], i.e. C x = R x R. ;; 22b (session '[C x y z]) (red :C) (exp :R) (exp :T 2) (exp :B) ; => [B (T x) R y z], i.e. C x = B (T x) R. ;; 23 ; Derive R from C (weak-reduce '[C C x y z]) ; => [y z x] (= (weak-reduce '[C C x y z]) (weak-reduce '[R x y z])) ; => true ;; Finch p.102 (def-combinator '[F x y z] '[z y x] "Finch") ;; 24 (weak-reduce '[B C R x y z]) ; => [z y x] (weak-reduce '[B (R R R) R x y z]) ; => [z y x] (weak-reduce '[B C (C C) x y z]) ; => [z y x] ;; 25 (weak-reduce '[E T T E T x y z]) ; => [z y x] ;; 26 (weak-reduce '[B C R x y z]) (weak-reduce '[B (R R R) R x y z]) (weak-reduce '[B (B (T (B B T)) (B B T)) (B B T) x y z]) ; => [z y x] (weak-reduce '[E T T E T x y z]) (weak-reduce '[B (B B B) T T (B (B B B)) T x y z]) ; => [z y x] (weak-reduce '[B (B B B) T T (B (B B B)) T]) ; => [B (T T) (B (B B B) T)], thus (weak-reduce '[B (T T) (B (B B B) T) x y z] ) ; => [z y x] a bit shorter than the solution above ;; Vireo p.103 (def-combinator '[V x y z] '[z x y] "Vireo") ;; 27 (weak-reduce '[C F x y z]) ; => [z x y], i.e. V = C F (weak-reduce '[B C T x y z]) ; => [z x y], i.e. V = B C T ;; 28 (weak-reduce '[R R R F x y z]) ; => [z x y], and also (weak-reduce '[R F R x y z]) ; => [z x y] ;; 29 (weak-reduce '[C V x y z]) ; => [z y x], i.e. C V = F ;; 30 (weak-reduce '[R K K x]) ; => [x] (weak-reduce '[R R K x]) ; => [x] ;; Cardinal once removed p.104 (def-combinator '[C* x y z w] '[x y w z] "Cardinal once removed") ;; 31 (weak-reduce '[B C x y z w]) ; => [x y w z], i.e. C* = B C ;; Robin once removed p.104 (def-combinator '[R* x y z w] '[x z w y] "Robin once removed") ;; 32 (weak-reduce '[B C (B C) x y z w]) ; => [x z w y], i.e. R* = B C (B C) = C* C* ;; Finch once removed p.104 (def-combinator '[F* x y z w] '[x w z y] "Finch once removed") ;; 33 (weak-reduce '[B C* R* x y z w]) (weak-reduce '[B C* (C* C*) x y z w]) ; => [x w z y], i.e. F* = B C* R* = B C* (C* C*) ;; Vireo once removed p.104 (def-combinator '[V* x y z w] '[x w y z] "Vireo once removed") ;; 34 (= (weak-reduce '[C* F* x y z w]) (weak-reduce '[V* x y z w])) ; => true ;; Cardinal twice removed p.105 (def-combinator '[C** x y z_1 z_2 z_3] '[x y z_1 z_3 z_2] "Cardinal twice removed") ;; Robin twice removed p.105 (def-combinator '[R** x y z_1 z_2 z_3] '[x y z_2 z_3 z_1] "Robin twice removed") ;; Finch twice removed p.105 (def-combinator '[F** x y z_1 z_2 z_3] '[x y z_3 z_2 z_1] "Finch twice removed") ;; Vireo twice removed p.105 (def-combinator '[V** x y z_1 z_2 z_3] '[x y z_3 z_1 z_2] "Vireo twice removed") ;; 35 (= (weak-reduce '[C** x y z_1 z_2 z_3]) (weak-reduce '[B C* x y z_1 z_2 z_3])) ; => true, i.e. C** = B C* (= (weak-reduce '[R** x y z_1 z_2 z_3]) (weak-reduce '[B R* x y z_1 z_2 z_3])) ; => true, i.e. R** = B R* (= (weak-reduce '[F** x y z_1 z_2 z_3]) (weak-reduce '[B F* x y z_1 z_2 z_3])) ; => true, i.e. F** = B F* (= (weak-reduce '[V** x y z_1 z_2 z_3]) (weak-reduce '[B V* x y z_1 z_2 z_3])) ; => true, i.e. V** = B V* ;; 36 (= (weak-reduce '[V x y z]) (weak-reduce '[C* T x y z])) ; => true, i.e. V = C* T ;; Queer p.105 (def-combinator '[Q x y z] '[y (x z)] "Queer") ;; 39 (= (weak-reduce '[Q x y z]) (weak-reduce '[C B x y z])) ; => true, i.e. Q = C B (= (weak-reduce '[Q x y z]) (weak-reduce '[B (T B) (B B T) x y z])) ; => true, i.e. Q = B (T B) (B B T) ;; Quixotic p.106 (def-combinator '[Q1 x y z] '[x (z y)] "Quixotic") ;; 38 (= (weak-reduce '[Q1 x y z]) (weak-reduce '[B C B x y z])) ; => true i.e. Q1 = B C B (= (weak-reduce '[Q1 x y z]) (weak-reduce '[C* B x y z])) ; => true i.e. Q1 = C* B (= (weak-reduce '[Q1 x y z]) (weak-reduce '[B (B B T (B B T) (B B T)) B x y z])) ; => true ;; Quizzical p.106 (def-combinator '[Q2 x y z] '[y (z x)] "Quizzical") ;; 39 (= (weak-reduce '[Q2 x y z]) (weak-reduce '[C (B C B) x y z])) ; => true, i.e. Q2 = C (B C B) ;; Quirky p.106 (def-combinator '[Q3 x y z] '[z (x y)] "Quirky") ;; 41 (= (weak-reduce '[Q3 x y z]) (weak-reduce '[B T x y z])) ; => true, i.e. Q3 = B T (= (weak-reduce '[Q3 x y z]) (weak-reduce '[V* B x y z])) ; => true, i.e. Q3 = V* B ;; Quacky p.106 (def-combinator '[Q4 x y z] '[z (y x)] "Quacky") ;; 44 (= (weak-reduce '[Q4 x y z]) (weak-reduce '[Q1 T x y z])) ; => true, i.e. Q4 = Q1 T (= (weak-reduce '[Q4 x y z]) (weak-reduce '[B C B T x y z])) ; => true, i.e. Q4 = B C B T (= (weak-reduce '[Q4 x y z]) (weak-reduce '[C Q3 x y z])) ; => true, i.e. Q4 = C Q3 ;; 45 (= (weak-reduce '[B x y z]) (weak-reduce '[Q T (Q Q) x y z])) ; => true, i.e. B = Q T (Q Q) ;; 46 (= (weak-reduce '[C x y z]) (weak-reduce '[Q Q (Q T) x y z])) ; => true, i.e. C = Q Q (Q T) ;; Goldfinch p.107 (def-combinator '[G x y z w] '[x w (y z)] "Goldfinch") ;; 47 (= (weak-reduce '[G x y z w]) (weak-reduce '[B B C x y z w])) ; => true, i.e. G = B B C ;; Chap 12: Mockingbirds, Warblers and Starlings ------------------------------ ;; Double Mockingbird p.118 (def-combinator '[M2 x y] '[x y (x y)] "Double Mockingbird") ;; 1 (= (weak-reduce '[M2 x y]) (weak-reduce '[B M x y])) ; => true, i.e. M2 = B M ;; 2 (= (weak-reduce '[L x y]) (weak-reduce '[C B M x y])) ; => true, i.e. L = C B M (= (weak-reduce '[L x y] (weak-reduce '[B (T M) B x y]))) ; => true, i.e. L = B (T M) B ;; 3 (= (weak-reduce '[L x y]) (weak-reduce '[B W B x y])) ; => true, i.e. L = B W B ;; 4 (= (weak-reduce '[L x y]) (weak-reduce '[Q M x y])) ; => true, i.e. L = Q M ;; Converse Warbler p.119 (def-combinator '[W' x y] '[y x x] "Converse Warbler") ;; 5 (= (weak-reduce '[W' x y]) (weak-reduce '[C W x y])) ; => true, i.e. W' = C W (= (weak-reduce '[W' x y]) (weak-reduce '[B M R x y])) ; => true, i.e. W' = B M R (= (weak-reduce '[W' x y]) (weak-reduce '[B M (B B T) x y])) ; => true, i.e. W' = B M (B B T) (= (weak-reduce '[W' x y]) (weak-reduce '[B (B M B) T x y])) ; => true, i.e. W' = B (B M B) T ;; 6 (= (weak-reduce '[W x y]) (weak-reduce '[C W' x y])) ; => true, i.e. W = C W' (= (weak-reduce '[W x y]) (weak-reduce '[C (B M R) x y])) ; => true, i.e. W = C (B M R) ;; 7 (= (weak-reduce '[W x y]) (weak-reduce '[B (T (B M (B B T))) (B B T) x y])) ; => true (= (weak-reduce '[W x y]) (weak-reduce '[B (T (B (B M B)T)) (B B T) x y])) ; => true ;; 8 (= (weak-reduce '[M x]) (weak-reduce '[W T x])) ; => true, i.e. M = W T ;; Warbler Once Removed p.120 (def-combinator '[W* x y z] '[x y z z] "Warbler once removed") ;; Warbler Twice Removed p.120 (def-combinator '[W** x y z w] '[x y z w w] "Warbler twice removed") ;; 9 (= (weak-reduce '[W* x y z]) (weak-reduce '[B W x y z])) ; => true, i.e. W* = B W (= (weak-reduce '[W** x y z w]) (weak-reduce '[B (B W) x y z w])) ; => true, i.e. W** = B (B W) ;; Hummingbird p.120 (def-combinator '[H x y z] '[x y z y] "Hummingbird") ;; 10 (= (weak-reduce '[H x y z]) (weak-reduce '[B W (B C) x y z])) ; => true, i.e. H = B W (B C) ;; 11 (= (weak-reduce '[W x y z]) (weak-reduce '[C (H R) x y z])) ; => true, i.e. W = C (H R) ;; Starling p.121 (def-combinator '[S x y z] '[x z (y z)] "Starling") ;; 12 ; S from B C W (= (weak-reduce '[S x y z]) (weak-reduce '[B (B W) (B B C) x y z])) ; => true, i.e. S = B (B W) (B B C) ; S from B T M ?? brute force!! (def S-red1 (subst '[B (B W) (B B C)] '[W] '[B (T (B M (B B T))) (B B T)])) (weak-reduce (comb-concat S-red1 '[x] '[y] '[z])) ; => [x z (y z)] (def S-red2 (subst S-red1 '[C] '[B (T (B B T)) (B B T)])) (weak-reduce (comb-concat S-red2 '[x] '[y] '[z])) S-red2 ; => [B (B (B (T (B M (B B T))) (B B T))) (B B (B (T (B B T)) (B B T)))] ; S from B W G (= (weak-reduce '[S x y z]) (weak-reduce '[B (B W) G x y z])) ; => true, i.e. S = B (B W) G ;; 13 (= (weak-reduce '[H x y z]) (weak-reduce '[S (C C) x y z])) ; => true, i.e. H = S (C C) (= (weak-reduce '[H x y z]) (weak-reduce '[S R x y z])) ; => true, i.e. H = S R ;; 14 (= (weak-reduce '[W x y z]) (weak-reduce '[R (S R R) R x y z])) ; => true, i.e. W = R (S R R) R (= (weak-reduce '[W x y z]) (weak-reduce '[C (S (C C) (C C)) x y z])) ; => true, i.e. W = C (S (C C) (C C)) ;; 15 (= (weak-reduce '[W x y z]) (weak-reduce '[S T x y z])) ; => true, i.e. W = S T ;; 16 (= (weak-reduce '[M x]) (weak-reduce '[S T T x])) ; => true, i.e. M = S T T ;; Bases: ;; Church B, T, M, I ;; Curry B, C, W, I ;; alt B, C, S, I ;; G1 p.124 G1 = B (B B C) (def-combinator '[G1 x y z w v] '[x y v (z w)] "G1") ; G1 from B T (= (weak-reduce '[G1 x y z w v]) (weak-reduce '[B (B B C) x y z w v])) (= (weak-reduce '[G1 x y z w v]) (weak-reduce '[B G x y z w v])) (= (weak-reduce '[G1 x y z w v]) (weak-reduce '[B (B B (B (T (B B T)) (B B T))) x y z w v])) ; => all true ;; G2 p.124 G2 = G1 (B M) (def-combinator '[G2 x y z w] '[x w (x w) (y z)] "G2") ; G2 from G1 M (= (weak-reduce '[G2 x y z w]) (weak-reduce '[G1 (B M) x y z w])) ; => true ;; I2 p.124 I2 = B (T I) (T I) (def-combinator '[I2 x] '[x I I] "I2") ; I2 from B T I (= (weak-reduce '[I2 x] (weak-reduce '[B (T I) (T I) x]))) ; => true ; I2 (F x) = x (weak-reduce '[I2 (F x)]) ; => x ; G2 F (Q I2) = W (= (weak-reduce '[G2 F (Q I2) x y z] (weak-reduce '[W x y z]))) ; S = B (B (B W) C) (B B) (= (weak-reduce '[S x y z] (weak-reduce '[B (B (B W) C) (B B) x y z]))) ;; Phoenix p. 124 Phi = B (B S) B (def-combinator '[Phi x y z w] '[x (y w) (z w)] "Phoenix") ; Phi from S B (= (weak-reduce '[Phi x y z w] (weak-reduce '[B (B S) B x y z w]))) ;; Psi p.124 Psi = B H (B B (B B)) (def-combinator '[Psi x y z w] '[x (y z) (y w)] "Psi") ; Psi from B H (= (weak-reduce '[Psi x y z w] (weak-reduce '[B H (B B (B B)) x y z w]))) ;; H* p. 124 H* = B H (def-combinator '[H* x y z w] '[x y z w z] "Hummingbird once removed") (weak-reduce '[B H x y z w]) ; Psi from B C W (= (weak-reduce '[Psi x y z w] (weak-reduce '[H* D2 x y z w]))) (= (weak-reduce '[Psi x y z w] (weak-reduce '[B H D2 x y z w]))) (= (weak-reduce '[Psi x y z w] (weak-reduce '[B (B W (B C)) (B B (B B)) x y z w]))) ; Phi from B Psi K (= (weak-reduce '[Psi x y z w] (weak-reduce '[Phi (Phi (Phi B)) B (K K) x y z w]))) ;; Gamma p.124 Gamma = Phi (Phi (Phi B)) B (def-combinator '[Gamma x y z w v] '[y (z w) (x y w v)] "Gamma") (= (weak-reduce '[Gamma x y z w v] (weak-reduce '[Phi (Phi (Phi B)) B x y z w v]))) ; Psi from Gamma and K (= (weak-reduce '[Psi x y z w] (weak-reduce '[Gamma (K K) x y z w v]))) ; => true, i.e. Psi = Gamma (K K) ;; S' p.125 S' = C S (def-combinator '[S' x y z] '[y z (x z)] "S'") (= (weak-reduce '[S' x y z] (weak-reduce '[C S x y z]))) (= (weak-reduce '[S' I x y z] (weak-reduce '[W x y z]))) ; => true, i.e. W = S' I ; Q^ such that C Q^ W = S ;; Q^ = Q (Q Q (Q Q)) Q (weak-reduce '[C (Q (Q Q (Q Q)) Q) W x y z]) ; => [x z (y z)] ;; Chap 13: A Gallery of Sage Birds ------------------------------------------- ;; Order of a combinator ;; The order of a combinator is the number of variables that are needed to express the combinator. ;; Examples: ;; Order 1: I and M ;; Order 2: T, L, W ;; Order 3: S, B, C, R, F ... ;; Order 7: Ê ;; Proper (and improper) combinators ;; A combinator having some order is called proper ;; T I is not proper: T I x -> x I, T I x y -> x I y we get not rid of I, so T I has no order ;; I T is proper since I T = T, and T is proper ;; Sage birds ;; A sage bird is a bird Theta such that for all x: x (Theta x) = Theta x ;; Sage birds are improper combinators, but they can be expressed in terms of proper ;; combinators. ;; Since Sage birds are often called Y ;; 1 A sage bird from M, B and R (show-combinator :M) (show-combinator :B) (show-combinator :R) (session '[B M (R M B) x]) (red :B) (red :M) (red :R) (red :B) (red :M) (exp :B 2) (red :B) (exp :M) (exp :B 2) ; => [x (B M (R M B) x)] ;; 2 A sage bird from B, C and M (show-combinator :C) (session '[B M (C B M) x]) (red :B) (red :M) (red :C) (red :B) (red :M) (exp :C 2) (exp :C 4) (exp :M ) (exp :B 2) ; => [x (B M (C B M) x)] ;; 3 A sage bird from M, B and L (show-combinator :L) (session '[B M L x]) (red :B) (red :M) (red :L) (exp :M) (exp :B 2) ; => [x (B M L x)] ;; 4 A sage bird from M, B and W (show-combinator :W) (session '[B M (B W B) x]) (red :B) (red :M) (red :B) (red :W) (red :B) (exp :M) (exp :B 2) ; => [x (B M (B W B) x)] ;; 6 A sage bird from Q, L, W (show-combinator :Q) (session '[W (Q L (Q L)) x]) (red :W) (red :Q) (red :Q) (red :L) (exp :Q 2) (exp :Q 2) (exp :W) ; => [x (W (Q L (Q L)) x)] ;; 5, 7 A sage bird from B, C and W (show-combinator :C) (session '[W (B (C B (B W B)) (B W B)) x]) (red :W) (red :B) (red :C) (red :B) (red :B) (red :W) (red :B) (exp :B 2) (exp :C 2) (exp :B 2) (exp :W) ; => [x (W (B (C B (B W B)) (B W B)) x)] ;; 8 A sage bird from Q and M (session '[Q (Q M) M x]) (red :Q) (red :M) (red :Q) (exp :Q 2) ; => [x (Q (Q M) M x)] ;; 9 A sage bird from S and L (session '[S L L x]) (red :S) (red :L) (exp :S) ; => [x (S L L x)] ;; 10 A sage bird from B, W and S - Curry's sage bird (session '[W S (B W B) x]) (red :W) (red :S) (red :B) (red :W) (red :B) (exp :S) (exp :W) ; => [x (W S (B W B) x)] ;; Turing Bird U p.132 U = L (S (C T)) (def-combinator '[U x y] '[y (x x y)] "Turing Bird") (weak-reduce '[L (S (C T)) x y]) ; => [y (x x y)] ;; 11 A Turing bird from B, M and T (show-combinator :T) ; W, L, Q are derivable from B, M and T (weak-reduce '[B W (L Q) x y]) ; => y (x x y)] ;; 12 A sage bird from U (session '[U U x]) (red :U) ; => x (U U x)], i.e. U U is a sage bird ;; Owl O p.133 U = B W (C B) (def-combinator '[O x y] '[y (x y)] "Owl") ;; 13 O form B, C, W (weak-reduce '[B W (C B) x y]) ; => [y (x y)] ;; 14 U from O and L (= (weak-reduce '[L O x y]) (weak-reduce '[U x y])) ; => U = L O ;; 15 M from O and I (= (weak-reduce '[M x]) (weak-reduce '[O I x])) ; => M = O I ;; 16 O from S and I (= (weak-reduce '[O x y]) (weak-reduce '[S I x y])) ; => O = S I ;; Two combinators A1 and A2 are similar if for all x: A1 x = A2 x ;; A theory of combinators is called extensional if similar birds are identical. ;; I.e. there is exactly on identity combinator, one starling and so forth. ;; Chap 19: Aristocratic Birds ----------------------------------------------- ; Jaybird p.181 J = [B (B C) (W (B C (B (B B B))))] (def-combinator '[J x y z w] '[x y (x w z)] "Jaybird") ;; 1 J from B C W (weak-reduce '[B (B C) (W (B C (B (B B B)))) x y z w]) ; => x y (x w z)] ;; 2 Q1 from J and I (= (weak-reduce '[Q1 x y z]) (weak-reduce '[J I x y z])) ; => Q1 = J I ;; 3 T from Q1 and I (= (weak-reduce '[T x y]) (weak-reduce '[Q1 I x y])) ; => T = Q1 I = J I I ;; 4 R from J and T (= (weak-reduce '[R x y z]) (weak-reduce '[J T x y z])) ; => R = J T ;; 5 B from C and Q1 (= (weak-reduce '[B x y z]) (weak-reduce '[C (Q1 C) Q1 x y z])) ; => B = C (Q1 C) Q1 (= (weak-reduce '[B x y z]) (weak-reduce '[C (J I C) (J I) x y z])) ; => B = C (J I C) (J I) ; J1 p.183 J1 = B J T (def-combinator '[J1 x y z w] '[y x (w x z)] "J1") ;; 6 J1 from J, B and T (weak-reduce '[B J T x y z w]) ; => [y x (w x z)] ;; 7 M from C, T, J1 (= (weak-reduce '[M x]) (weak-reduce '[C (C (C J1 T) T) T x])) ; => M = C (C (C J1 T) T) T ;; Chap 20: Craig's Discovery ------------------------------------------------- ;; 1 Q3 from G and I (= (weak-reduce '[Q3 x y z]) (weak-reduce '[G I x y z])) ; => Q3 = G I ;; 2 T from G and I (= (weak-reduce '[T x y]) (weak-reduce '[G I I x y])) ;=> T = G I I ;; 3 C from G and I (= (weak-reduce '[C x y z]) (weak-reduce '[G G I I x y z])) ; => C = G G I I ;; 4 B from C Q (= (weak-reduce '[R x y z]) (weak-reduce '[C C x y z])) ; => R = C C (= (weak-reduce '[Q x y z]) (weak-reduce '[G R Q3 x y z])) ; => Q = G R Q3 (= (weak-reduce '[B x y z]) (weak-reduce '[C Q x y z])) ; => B = C Q
17590
; lwb Logic WorkBench -- Combinatory logic, Examples from <NAME> Smullyan: How to Mock a Mockingbird ; Copyright (c) 2019 <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.cl.examples.smullyan (:require [lwb.cl :refer :all] [lwb.cl.repl :refer :all])) ;; Chap 9: To Mock a Mockingbird ---------------------------------------------- (reset-combinators) ;; Mockingbird p.73 (def-combinator '[M x] '[x x] "Mockingbird") (show-combinators) ;; Composition ;; Definition: C composes A with B if for every x: C x = A (B x). ;; The composition condition: For every A, B exists C that composes A with B. ;; Definition: A is fond of B if A B = B. ;; Definition: A is called egocentric if A A = A, i.e. A is fond of itself. ;; Definition: Two combinators A, B agree on x if A x = B x. ;; Definition: A is agreeable if for every B there is a x such that A x = B x. ;; Definition: Two combinators A and B are compatible if there are x, y such that A x = y and B y = x. ;; Definition: A combinator A is happy if there are x, y such that A x = y and A y = x, ;; i.e. A is compatible with itself. ;; Definition: A combinator A is normal if exists B such that A B = B, i.e. exists B such that A is fond of B. ;; Definition: A combinator B is hopelessly egocentric if B B = B. ;; Definition: A is fixated on B if for every x: A x = B. ;; Kestrel p.77 (def-combinator '[K x y] '[x] "Kestrel") (show-combinators) ;; Left cancellation law for kestrels: if K x = K y then x = y. ;; Identity Bird aka Idiot p.78 (def-combinator '[I x] '[x] "Identity Bird") (show-combinators) ;; Lark p.80 (def-combinator '[L x y] '[x (y y)] "Lark") (show-combinators) ;; 24 ; Given L and I, then there is a M with M x = x x. (session '[L I x]) (red :L) (red :I) ; or (weak-reduce '[L I x]) ; L I x -> x x, i.e. M = L I ;; 25 ; Given L, then every bird x is fond of at least one bird (session '[x (L x (L x))]) (exp :L) ; x (L x (L x)) = L x (L x) ; Any bird x is fond of L x (L x) = (L x) (L x) ;; 26 ; Given L, then there is a bird of whom L L is fond (session '[L L ((L (L L)) (L (L L)))]) (red :L) ; => [L (L (L L) (L (L L)) (L (L L) (L (L L))))] ;; Chap 10: Is There a Sage Bird? --------------------------------------------- ; A sage bird Theta is a bird with x (Theta x) = Theta x, aka a fixed point combinator ; There is such a bird: the composition of M and L (session '[M (L x)]) (red :M) (red :L) (exp :M) (session '[x (M (L x))]) (red :M) (exp :L) (exp :M) ; [x (M (L x))] = [M (L x)] ;; Chap 11: Birds Galore ------------------------------------------------------ ; Introduction (max-parens '[x y (z w y) v]) ; => [(((x y) ((z w) y)) v)] (max-parens '[(x y z) (w v x)]) ; => [(((x y) z) ((w v) x))] (max-parens '[x y (z w v) (x z)]) ; => [(((x y) ((z w) v)) (x z))] (max-parens '[x y (z w v) x z]) ; => [((((x y) ((z w) v)) x) z)] (max-parens '[x (y (z w v)) x z]) ; => [(((x (y ((z w) v))) x) z)] (= (max-parens '[x y z (A B)]) (max-parens '[(x y z) (A B)])) ; => true (= (max-parens '[x y w]) (max-parens (subst '[z w] '[z] '(x y)))) ; => true (= (max-parens '[w x y]) (max-parens (subst '[w z] '[z] '(x y)))) ; => false ;; Bluebird p.95 (def-combinator '[B x y z] '[x (y z)] "Bluebird") (show-combinators) ;; 1 ; Given B then the composition law holds (session '[(B f g) x]) (red :B) ; => [f (g x)] i.e. [B f g] composes f with g. ; Let's use this fact (session '[B M L x]) (red :B) (red :M) (red :L) (exp :M) (exp :B 2) ; => [x (B M L x) i.e. B M L is a sage bird ;; 2 ; Given B and M, write down an expression in terms of B, M, x that describes a bird of which x is fond. (session '[(M (B x M))]) (red :M) (red :B) ; => [x (M (B x M))] (session '[x (M (B x M))]) (exp :B) (exp :M) ; => [M (B x M)] ; x is fond of M (B x M) ;; 3 ; Given B and M, find egocentric bird (session '[M (B M M)]) (red :M) (red :B) (red :M) ; => [M (B M M) (M (B M M))] ; M (B M M) is egocentric, i.e. Z = Z Z ;; 4 ; Given B, M and K, find hopelessly egocentric bird ; M (B K M) is hopelessly egocentric , i.e. for all x: Z x = Z (session '[M (B K M) x]) (red :M) (red :B) (red :K) ; => [M (B K M)] (session '[M (B K M)]) (exp :K) (swap '?1 '[x]) (exp :B) (exp :M) ; => [M (B K M) x] ;; Dove p.97 (def-combinator '[D x y z w] '[x y (z w)] "Dove") (show-combinators) ;; 5 ; D can be derived from B alone, how? (session '[B B x y z w]) (red :B) (red :B) ; => [x y (z w)], i.e. D = B B. (= (weak-reduce '[B B x y z w]) (weak-reduce '[D x y z w])) ; => true ;; Blackbird p.97 (def-combinator '[B1 x y z w] '[x (y z w)] "Blackbird") (show-combinators) ;; 6 ; Given B, then there is a D and a B1 too: ; D = B B, and B1 = D B = B B B (weak-reduce '[D B x y z w]) ; => [x (y z w)], i.e. B1 = D B. (weak-reduce '[B B B x y z w]) ; => [x (y z w)], i.e. B1 = B B B. ;; Eagle p.97 (def-combinator '[E x y z w v] '[x y (z w v)] "Eagle") (show-combinators) ;; 7 ; Derive E from B (weak-reduce '[B B1 x y z w v]) ; => [x y (z w v)], i.e. E = B B1 = B (B B B). ;; Bunting p.97 (def-combinator '[B2 x y z w v] '[x (y z w v)] "Bunting") (show-combinators) ;; 8 ; Given B find B2 (weak-reduce '[E B x y z w v]) ; => x (y z w v)] (weak-reduce '[B B1 B x y z w v]) ; => [x (y z w v)], i.e. B2 = B (B B B) B ; but this is true too (weak-reduce '[B B B1 x y z w v]) ; => [x (y z w v)], i.e. B2 = B B (B B B) ;; Dickcissel p.97 (def-combinator '[D1 x y z w v] '[x y z (w v)] "Dickcissel") (show-combinators) ;; 9 ; Derive D1 from B (weak-reduce '[B1 B x y z w v]) ; => [x y z (w v)] (weak-reduce '[B B B B x y z w v]) ; => [x y z (w v)], i.e. D1 = B B B B (weak-reduce '[B (B B) x y z w v]) ; => [x y z (w v)], i.e. D1 = B (B B) ;; Becard p.98 (def-combinator '[B3 x y z w] '[x (y (z w))] "Becard") (show-combinators) ;; 10 ; Derive B3 from B (weak-reduce '[D1 B x y z w]) ; => [x (y (z w))] (weak-reduce '[B (B B) B x y z w]) ; => [x (y (z w))] (weak-reduce '[B B B B B x y z w]) ; => [x (y (z w))] ;; Dovekie p.98 (def-combinator '[D2 x y z w v] '[x (y z) (w v)] "Dovekie") (show-combinators) ;; 11 ; Derive D2 from B (weak-reduce '[B B (B B) x y z w v]) ; => [x (y z) (w v)], i.e. D2 = B B (B B) (weak-reduce '[D D x y z w v]) ; => [x (y z) (w v)], i.e. D2 = D D ;; Bald Eagle p.98 (def-combinator '[Ê x y1 y2 y3 z1 z2 z3] '[x (y1 y2 y3) (z1 z2 z3)] "Bald Eagle") (show-combinators) ;; 12 ; Derive Ê from B (weak-reduce '[E E x y_1 y_2 y_3 z_1 z_2 z_3]) ; => [x (y_1 y_2 y_3) (z_1 z_2 z_3)] (weak-reduce '[B (B B B) (B (B B B)) x y_1 y_2 y_3 z_1 z_2 z_3]) ; => [x (y_1 y_2 y_3) (z_1 z_2 z_3)], i.e. Ê = B (B B B) (B (B B B)) ;; Warbler p.99 (def-combinator '[W x y] '[x y y] "Warbler") (show-combinators) ;; 14 ; Derive M from W and I (weak-reduce '[W I x]) (weak-reduce '[M x]) ; => M = W I ;; 15 ; Derive I from W and K (weak-reduce '[W K x]) ; => W K = I ;; 13 ; Now derive M from W and K (weak-reduce '[W (W K) x]) ; => [x x], i.e. W (W K) = M. ; in steps: (session '[W (W K) x]) (red :W) (red :W) (red :K) ;; Cardinal p.100 (def-combinator '[C x y z] '[x z y] "Cardinal") (show-combinators) ;; 16 ; Derive I from C and K (weak-reduce '[C K K x]) ; => [x], i.e. C K K = I. (weak-reduce '[C K C x]) ; => [x] (weak-reduce '[C K any x]) ; => [x] ;; Trush p.100 (def-combinator '[T x y] '[y x] "Trush") (show-combinators) ;; 17 ; Derive T from C and I (weak-reduce '[C I x y]) ; => [y x], i.e. T = C I. ;; Definition: A and B commute if A B = B A ;; 19 ; Given B, T and M find a bird that commutes with every bird (session '[M (B T M) x]) (red :M) (red :B) (red :T) ; => [x (M (B T M))], i.e. M (B T M) commutes with any x. ;; Robin p.101 (def-combinator '[R x y z] '[y z x] "Robin") (show-combinators) ;; 20 ; Derive R from B and T (weak-reduce '[B B T x y z]) ; => y z x], i.e. R = B B T. ;; 21 ; Derive C from R alone (weak-reduce '[R R R x y z]) ; => [x z y], i.e. R R R = C ; Derive C from B B T with 9 letters (weak-reduce '[B B T (B B T) (B B T) x y z]) ; => [x z y] ; A shorter term with 8 letters? (weak-reduce '[B B T (B B T) (B B T)]) ; => [B (T (B B T)) (B B T)] hence (weak-reduce '[B (T (B B T)) (B B T) x y z]) ; => [x z y] ;; 22 Two useful laws ;; 22a (session '[C x y z]) (red :C) (exp :R) (exp :R 2) ; => [R x R y z], i.e. C x = R x R. ;; 22b (session '[C x y z]) (red :C) (exp :R) (exp :T 2) (exp :B) ; => [B (T x) R y z], i.e. C x = B (T x) R. ;; 23 ; Derive R from C (weak-reduce '[C C x y z]) ; => [y z x] (= (weak-reduce '[C C x y z]) (weak-reduce '[R x y z])) ; => true ;; Finch p.102 (def-combinator '[F x y z] '[z y x] "Finch") ;; 24 (weak-reduce '[B C R x y z]) ; => [z y x] (weak-reduce '[B (R R R) R x y z]) ; => [z y x] (weak-reduce '[B C (C C) x y z]) ; => [z y x] ;; 25 (weak-reduce '[E T T E T x y z]) ; => [z y x] ;; 26 (weak-reduce '[B C R x y z]) (weak-reduce '[B (R R R) R x y z]) (weak-reduce '[B (B (T (B B T)) (B B T)) (B B T) x y z]) ; => [z y x] (weak-reduce '[E T T E T x y z]) (weak-reduce '[B (B B B) T T (B (B B B)) T x y z]) ; => [z y x] (weak-reduce '[B (B B B) T T (B (B B B)) T]) ; => [B (T T) (B (B B B) T)], thus (weak-reduce '[B (T T) (B (B B B) T) x y z] ) ; => [z y x] a bit shorter than the solution above ;; Vireo p.103 (def-combinator '[V x y z] '[z x y] "Vireo") ;; 27 (weak-reduce '[C F x y z]) ; => [z x y], i.e. V = C F (weak-reduce '[B C T x y z]) ; => [z x y], i.e. V = B C T ;; 28 (weak-reduce '[R R R F x y z]) ; => [z x y], and also (weak-reduce '[R F R x y z]) ; => [z x y] ;; 29 (weak-reduce '[C V x y z]) ; => [z y x], i.e. C V = F ;; 30 (weak-reduce '[R K K x]) ; => [x] (weak-reduce '[R R K x]) ; => [x] ;; Cardinal once removed p.104 (def-combinator '[C* x y z w] '[x y w z] "Cardinal once removed") ;; 31 (weak-reduce '[B C x y z w]) ; => [x y w z], i.e. C* = B C ;; Robin once removed p.104 (def-combinator '[R* x y z w] '[x z w y] "Robin once removed") ;; 32 (weak-reduce '[B C (B C) x y z w]) ; => [x z w y], i.e. R* = B C (B C) = C* C* ;; Finch once removed p.104 (def-combinator '[F* x y z w] '[x w z y] "Finch once removed") ;; 33 (weak-reduce '[B C* R* x y z w]) (weak-reduce '[B C* (C* C*) x y z w]) ; => [x w z y], i.e. F* = B C* R* = B C* (C* C*) ;; Vireo once removed p.104 (def-combinator '[V* x y z w] '[x w y z] "Vireo once removed") ;; 34 (= (weak-reduce '[C* F* x y z w]) (weak-reduce '[V* x y z w])) ; => true ;; Cardinal twice removed p.105 (def-combinator '[C** x y z_1 z_2 z_3] '[x y z_1 z_3 z_2] "Cardinal twice removed") ;; Robin twice removed p.105 (def-combinator '[R** x y z_1 z_2 z_3] '[x y z_2 z_3 z_1] "Robin twice removed") ;; Finch twice removed p.105 (def-combinator '[F** x y z_1 z_2 z_3] '[x y z_3 z_2 z_1] "Finch twice removed") ;; Vireo twice removed p.105 (def-combinator '[V** x y z_1 z_2 z_3] '[x y z_3 z_1 z_2] "Vireo twice removed") ;; 35 (= (weak-reduce '[C** x y z_1 z_2 z_3]) (weak-reduce '[B C* x y z_1 z_2 z_3])) ; => true, i.e. C** = B C* (= (weak-reduce '[R** x y z_1 z_2 z_3]) (weak-reduce '[B R* x y z_1 z_2 z_3])) ; => true, i.e. R** = B R* (= (weak-reduce '[F** x y z_1 z_2 z_3]) (weak-reduce '[B F* x y z_1 z_2 z_3])) ; => true, i.e. F** = B F* (= (weak-reduce '[V** x y z_1 z_2 z_3]) (weak-reduce '[B V* x y z_1 z_2 z_3])) ; => true, i.e. V** = B V* ;; 36 (= (weak-reduce '[V x y z]) (weak-reduce '[C* T x y z])) ; => true, i.e. V = C* T ;; Queer p.105 (def-combinator '[Q x y z] '[y (x z)] "Queer") ;; 39 (= (weak-reduce '[Q x y z]) (weak-reduce '[C B x y z])) ; => true, i.e. Q = C B (= (weak-reduce '[Q x y z]) (weak-reduce '[B (T B) (B B T) x y z])) ; => true, i.e. Q = B (T B) (B B T) ;; Quixotic p.106 (def-combinator '[Q1 x y z] '[x (z y)] "Quixotic") ;; 38 (= (weak-reduce '[Q1 x y z]) (weak-reduce '[B C B x y z])) ; => true i.e. Q1 = B C B (= (weak-reduce '[Q1 x y z]) (weak-reduce '[C* B x y z])) ; => true i.e. Q1 = C* B (= (weak-reduce '[Q1 x y z]) (weak-reduce '[B (B B T (B B T) (B B T)) B x y z])) ; => true ;; Quizzical p.106 (def-combinator '[Q2 x y z] '[y (z x)] "Quizzical") ;; 39 (= (weak-reduce '[Q2 x y z]) (weak-reduce '[C (B C B) x y z])) ; => true, i.e. Q2 = C (B C B) ;; Quirky p.106 (def-combinator '[Q3 x y z] '[z (x y)] "Quirky") ;; 41 (= (weak-reduce '[Q3 x y z]) (weak-reduce '[B T x y z])) ; => true, i.e. Q3 = B T (= (weak-reduce '[Q3 x y z]) (weak-reduce '[V* B x y z])) ; => true, i.e. Q3 = V* B ;; Quacky p.106 (def-combinator '[Q4 x y z] '[z (y x)] "Quacky") ;; 44 (= (weak-reduce '[Q4 x y z]) (weak-reduce '[Q1 T x y z])) ; => true, i.e. Q4 = Q1 T (= (weak-reduce '[Q4 x y z]) (weak-reduce '[B C B T x y z])) ; => true, i.e. Q4 = B C B T (= (weak-reduce '[Q4 x y z]) (weak-reduce '[C Q3 x y z])) ; => true, i.e. Q4 = C Q3 ;; 45 (= (weak-reduce '[B x y z]) (weak-reduce '[Q T (Q Q) x y z])) ; => true, i.e. B = Q T (Q Q) ;; 46 (= (weak-reduce '[C x y z]) (weak-reduce '[Q Q (Q T) x y z])) ; => true, i.e. C = Q Q (Q T) ;; Goldfinch p.107 (def-combinator '[G x y z w] '[x w (y z)] "Goldfinch") ;; 47 (= (weak-reduce '[G x y z w]) (weak-reduce '[B B C x y z w])) ; => true, i.e. G = B B C ;; Chap 12: Mockingbirds, Warblers and Starlings ------------------------------ ;; Double Mockingbird p.118 (def-combinator '[M2 x y] '[x y (x y)] "Double Mockingbird") ;; 1 (= (weak-reduce '[M2 x y]) (weak-reduce '[B M x y])) ; => true, i.e. M2 = B M ;; 2 (= (weak-reduce '[L x y]) (weak-reduce '[C B M x y])) ; => true, i.e. L = C B M (= (weak-reduce '[L x y] (weak-reduce '[B (T M) B x y]))) ; => true, i.e. L = B (T M) B ;; 3 (= (weak-reduce '[L x y]) (weak-reduce '[B W B x y])) ; => true, i.e. L = B W B ;; 4 (= (weak-reduce '[L x y]) (weak-reduce '[Q M x y])) ; => true, i.e. L = Q M ;; Converse Warbler p.119 (def-combinator '[W' x y] '[y x x] "Converse Warbler") ;; 5 (= (weak-reduce '[W' x y]) (weak-reduce '[C W x y])) ; => true, i.e. W' = C W (= (weak-reduce '[W' x y]) (weak-reduce '[B M R x y])) ; => true, i.e. W' = B M R (= (weak-reduce '[W' x y]) (weak-reduce '[B M (B B T) x y])) ; => true, i.e. W' = B M (B B T) (= (weak-reduce '[W' x y]) (weak-reduce '[B (B M B) T x y])) ; => true, i.e. W' = B (B M B) T ;; 6 (= (weak-reduce '[W x y]) (weak-reduce '[C W' x y])) ; => true, i.e. W = C W' (= (weak-reduce '[W x y]) (weak-reduce '[C (B M R) x y])) ; => true, i.e. W = C (B M R) ;; 7 (= (weak-reduce '[W x y]) (weak-reduce '[B (T (B M (B B T))) (B B T) x y])) ; => true (= (weak-reduce '[W x y]) (weak-reduce '[B (T (B (B M B)T)) (B B T) x y])) ; => true ;; 8 (= (weak-reduce '[M x]) (weak-reduce '[W T x])) ; => true, i.e. M = W T ;; Warbler Once Removed p.120 (def-combinator '[W* x y z] '[x y z z] "Warbler once removed") ;; Warbler Twice Removed p.120 (def-combinator '[W** x y z w] '[x y z w w] "Warbler twice removed") ;; 9 (= (weak-reduce '[W* x y z]) (weak-reduce '[B W x y z])) ; => true, i.e. W* = B W (= (weak-reduce '[W** x y z w]) (weak-reduce '[B (B W) x y z w])) ; => true, i.e. W** = B (B W) ;; Hummingbird p.120 (def-combinator '[H x y z] '[x y z y] "Hummingbird") ;; 10 (= (weak-reduce '[H x y z]) (weak-reduce '[B W (B C) x y z])) ; => true, i.e. H = B W (B C) ;; 11 (= (weak-reduce '[W x y z]) (weak-reduce '[C (H R) x y z])) ; => true, i.e. W = C (H R) ;; Starling p.121 (def-combinator '[S x y z] '[x z (y z)] "Starling") ;; 12 ; S from B C W (= (weak-reduce '[S x y z]) (weak-reduce '[B (B W) (B B C) x y z])) ; => true, i.e. S = B (B W) (B B C) ; S from B T M ?? brute force!! (def S-red1 (subst '[B (B W) (B B C)] '[W] '[B (T (B M (B B T))) (B B T)])) (weak-reduce (comb-concat S-red1 '[x] '[y] '[z])) ; => [x z (y z)] (def S-red2 (subst S-red1 '[C] '[B (T (B B T)) (B B T)])) (weak-reduce (comb-concat S-red2 '[x] '[y] '[z])) S-red2 ; => [B (B (B (T (B M (B B T))) (B B T))) (B B (B (T (B B T)) (B B T)))] ; S from B W G (= (weak-reduce '[S x y z]) (weak-reduce '[B (B W) G x y z])) ; => true, i.e. S = B (B W) G ;; 13 (= (weak-reduce '[H x y z]) (weak-reduce '[S (C C) x y z])) ; => true, i.e. H = S (C C) (= (weak-reduce '[H x y z]) (weak-reduce '[S R x y z])) ; => true, i.e. H = S R ;; 14 (= (weak-reduce '[W x y z]) (weak-reduce '[R (S R R) R x y z])) ; => true, i.e. W = R (S R R) R (= (weak-reduce '[W x y z]) (weak-reduce '[C (S (C C) (C C)) x y z])) ; => true, i.e. W = C (S (C C) (C C)) ;; 15 (= (weak-reduce '[W x y z]) (weak-reduce '[S T x y z])) ; => true, i.e. W = S T ;; 16 (= (weak-reduce '[M x]) (weak-reduce '[S T T x])) ; => true, i.e. M = S T T ;; Bases: ;; Church B, T, M, I ;; Curry B, C, W, I ;; alt B, C, S, I ;; G1 p.124 G1 = B (B B C) (def-combinator '[G1 x y z w v] '[x y v (z w)] "G1") ; G1 from B T (= (weak-reduce '[G1 x y z w v]) (weak-reduce '[B (B B C) x y z w v])) (= (weak-reduce '[G1 x y z w v]) (weak-reduce '[B G x y z w v])) (= (weak-reduce '[G1 x y z w v]) (weak-reduce '[B (B B (B (T (B B T)) (B B T))) x y z w v])) ; => all true ;; G2 p.124 G2 = G1 (B M) (def-combinator '[G2 x y z w] '[x w (x w) (y z)] "G2") ; G2 from G1 M (= (weak-reduce '[G2 x y z w]) (weak-reduce '[G1 (B M) x y z w])) ; => true ;; I2 p.124 I2 = B (T I) (T I) (def-combinator '[I2 x] '[x I I] "I2") ; I2 from B T I (= (weak-reduce '[I2 x] (weak-reduce '[B (T I) (T I) x]))) ; => true ; I2 (F x) = x (weak-reduce '[I2 (F x)]) ; => x ; G2 F (Q I2) = W (= (weak-reduce '[G2 F (Q I2) x y z] (weak-reduce '[W x y z]))) ; S = B (B (B W) C) (B B) (= (weak-reduce '[S x y z] (weak-reduce '[B (B (B W) C) (B B) x y z]))) ;; Phoenix p. 124 Phi = B (B S) B (def-combinator '[Phi x y z w] '[x (y w) (z w)] "Phoenix") ; Phi from S B (= (weak-reduce '[Phi x y z w] (weak-reduce '[B (B S) B x y z w]))) ;; Psi p.124 Psi = B H (B B (B B)) (def-combinator '[Psi x y z w] '[x (y z) (y w)] "Psi") ; Psi from B H (= (weak-reduce '[Psi x y z w] (weak-reduce '[B H (B B (B B)) x y z w]))) ;; H* p. 124 H* = B H (def-combinator '[H* x y z w] '[x y z w z] "Hummingbird once removed") (weak-reduce '[B H x y z w]) ; Psi from B C W (= (weak-reduce '[Psi x y z w] (weak-reduce '[H* D2 x y z w]))) (= (weak-reduce '[Psi x y z w] (weak-reduce '[B H D2 x y z w]))) (= (weak-reduce '[Psi x y z w] (weak-reduce '[B (B W (B C)) (B B (B B)) x y z w]))) ; Phi from B Psi K (= (weak-reduce '[Psi x y z w] (weak-reduce '[Phi (Phi (Phi B)) B (K K) x y z w]))) ;; Gamma p.124 Gamma = Phi (Phi (Phi B)) B (def-combinator '[Gamma x y z w v] '[y (z w) (x y w v)] "Gamma") (= (weak-reduce '[Gamma x y z w v] (weak-reduce '[Phi (Phi (Phi B)) B x y z w v]))) ; Psi from Gamma and K (= (weak-reduce '[Psi x y z w] (weak-reduce '[Gamma (K K) x y z w v]))) ; => true, i.e. Psi = Gamma (K K) ;; S' p.125 S' = C S (def-combinator '[S' x y z] '[y z (x z)] "S'") (= (weak-reduce '[S' x y z] (weak-reduce '[C S x y z]))) (= (weak-reduce '[S' I x y z] (weak-reduce '[W x y z]))) ; => true, i.e. W = S' I ; Q^ such that C Q^ W = S ;; Q^ = Q (Q Q (Q Q)) Q (weak-reduce '[C (Q (Q Q (Q Q)) Q) W x y z]) ; => [x z (y z)] ;; Chap 13: A Gallery of Sage Birds ------------------------------------------- ;; Order of a combinator ;; The order of a combinator is the number of variables that are needed to express the combinator. ;; Examples: ;; Order 1: I and M ;; Order 2: T, L, W ;; Order 3: S, B, C, R, F ... ;; Order 7: Ê ;; Proper (and improper) combinators ;; A combinator having some order is called proper ;; T I is not proper: T I x -> x I, T I x y -> x I y we get not rid of I, so T I has no order ;; I T is proper since I T = T, and T is proper ;; Sage birds ;; A sage bird is a bird Theta such that for all x: x (Theta x) = Theta x ;; Sage birds are improper combinators, but they can be expressed in terms of proper ;; combinators. ;; Since Sage birds are often called Y ;; 1 A sage bird from M, B and R (show-combinator :M) (show-combinator :B) (show-combinator :R) (session '[B M (R M B) x]) (red :B) (red :M) (red :R) (red :B) (red :M) (exp :B 2) (red :B) (exp :M) (exp :B 2) ; => [x (B M (R M B) x)] ;; 2 A sage bird from B, C and M (show-combinator :C) (session '[B M (C B M) x]) (red :B) (red :M) (red :C) (red :B) (red :M) (exp :C 2) (exp :C 4) (exp :M ) (exp :B 2) ; => [x (B M (C B M) x)] ;; 3 A sage bird from M, B and L (show-combinator :L) (session '[B M L x]) (red :B) (red :M) (red :L) (exp :M) (exp :B 2) ; => [x (B M L x)] ;; 4 A sage bird from M, B and W (show-combinator :W) (session '[B M (B W B) x]) (red :B) (red :M) (red :B) (red :W) (red :B) (exp :M) (exp :B 2) ; => [x (B M (B W B) x)] ;; 6 A sage bird from Q, L, W (show-combinator :Q) (session '[W (Q L (Q L)) x]) (red :W) (red :Q) (red :Q) (red :L) (exp :Q 2) (exp :Q 2) (exp :W) ; => [x (W (Q L (Q L)) x)] ;; 5, 7 A sage bird from B, C and W (show-combinator :C) (session '[W (B (C B (B W B)) (B W B)) x]) (red :W) (red :B) (red :C) (red :B) (red :B) (red :W) (red :B) (exp :B 2) (exp :C 2) (exp :B 2) (exp :W) ; => [x (W (B (C B (B W B)) (B W B)) x)] ;; 8 A sage bird from Q and M (session '[Q (Q M) M x]) (red :Q) (red :M) (red :Q) (exp :Q 2) ; => [x (Q (Q M) M x)] ;; 9 A sage bird from S and L (session '[S L L x]) (red :S) (red :L) (exp :S) ; => [x (S L L x)] ;; 10 A sage bird from B, W and S - Curry's sage bird (session '[W S (B W B) x]) (red :W) (red :S) (red :B) (red :W) (red :B) (exp :S) (exp :W) ; => [x (W S (B W B) x)] ;; Turing Bird U p.132 U = L (S (C T)) (def-combinator '[U x y] '[y (x x y)] "Turing Bird") (weak-reduce '[L (S (C T)) x y]) ; => [y (x x y)] ;; 11 A Turing bird from B, M and T (show-combinator :T) ; W, L, Q are derivable from B, M and T (weak-reduce '[B W (L Q) x y]) ; => y (x x y)] ;; 12 A sage bird from U (session '[U U x]) (red :U) ; => x (U U x)], i.e. U U is a sage bird ;; Owl O p.133 U = B W (C B) (def-combinator '[O x y] '[y (x y)] "Owl") ;; 13 O form B, C, W (weak-reduce '[B W (C B) x y]) ; => [y (x y)] ;; 14 U from O and L (= (weak-reduce '[L O x y]) (weak-reduce '[U x y])) ; => U = L O ;; 15 M from O and I (= (weak-reduce '[M x]) (weak-reduce '[O I x])) ; => M = O I ;; 16 O from S and I (= (weak-reduce '[O x y]) (weak-reduce '[S I x y])) ; => O = S I ;; Two combinators A1 and A2 are similar if for all x: A1 x = A2 x ;; A theory of combinators is called extensional if similar birds are identical. ;; I.e. there is exactly on identity combinator, one starling and so forth. ;; Chap 19: Aristocratic Birds ----------------------------------------------- ; Jaybird p.181 J = [B (B C) (W (B C (B (B B B))))] (def-combinator '[J x y z w] '[x y (x w z)] "Jaybird") ;; 1 J from B C W (weak-reduce '[B (B C) (W (B C (B (B B B)))) x y z w]) ; => x y (x w z)] ;; 2 Q1 from J and I (= (weak-reduce '[Q1 x y z]) (weak-reduce '[J I x y z])) ; => Q1 = J I ;; 3 T from Q1 and I (= (weak-reduce '[T x y]) (weak-reduce '[Q1 I x y])) ; => T = Q1 I = J I I ;; 4 R from J and T (= (weak-reduce '[R x y z]) (weak-reduce '[J T x y z])) ; => R = J T ;; 5 B from C and Q1 (= (weak-reduce '[B x y z]) (weak-reduce '[C (Q1 C) Q1 x y z])) ; => B = C (Q1 C) Q1 (= (weak-reduce '[B x y z]) (weak-reduce '[C (J I C) (J I) x y z])) ; => B = C (J I C) (J I) ; J1 p.183 J1 = B J T (def-combinator '[J1 x y z w] '[y x (w x z)] "J1") ;; 6 J1 from J, B and T (weak-reduce '[B J T x y z w]) ; => [y x (w x z)] ;; 7 M from C, T, J1 (= (weak-reduce '[M x]) (weak-reduce '[C (C (C J1 T) T) T x])) ; => M = C (C (C J1 T) T) T ;; Chap 20: Craig's Discovery ------------------------------------------------- ;; 1 Q3 from G and I (= (weak-reduce '[Q3 x y z]) (weak-reduce '[G I x y z])) ; => Q3 = G I ;; 2 T from G and I (= (weak-reduce '[T x y]) (weak-reduce '[G I I x y])) ;=> T = G I I ;; 3 C from G and I (= (weak-reduce '[C x y z]) (weak-reduce '[G G I I x y z])) ; => C = G G I I ;; 4 B from C Q (= (weak-reduce '[R x y z]) (weak-reduce '[C C x y z])) ; => R = C C (= (weak-reduce '[Q x y z]) (weak-reduce '[G R Q3 x y z])) ; => Q = G R Q3 (= (weak-reduce '[B x y z]) (weak-reduce '[C Q x y z])) ; => B = C Q
true
; lwb Logic WorkBench -- Combinatory logic, Examples from PI:NAME:<NAME>END_PI Smullyan: How to Mock a Mockingbird ; Copyright (c) 2019 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.cl.examples.smullyan (:require [lwb.cl :refer :all] [lwb.cl.repl :refer :all])) ;; Chap 9: To Mock a Mockingbird ---------------------------------------------- (reset-combinators) ;; Mockingbird p.73 (def-combinator '[M x] '[x x] "Mockingbird") (show-combinators) ;; Composition ;; Definition: C composes A with B if for every x: C x = A (B x). ;; The composition condition: For every A, B exists C that composes A with B. ;; Definition: A is fond of B if A B = B. ;; Definition: A is called egocentric if A A = A, i.e. A is fond of itself. ;; Definition: Two combinators A, B agree on x if A x = B x. ;; Definition: A is agreeable if for every B there is a x such that A x = B x. ;; Definition: Two combinators A and B are compatible if there are x, y such that A x = y and B y = x. ;; Definition: A combinator A is happy if there are x, y such that A x = y and A y = x, ;; i.e. A is compatible with itself. ;; Definition: A combinator A is normal if exists B such that A B = B, i.e. exists B such that A is fond of B. ;; Definition: A combinator B is hopelessly egocentric if B B = B. ;; Definition: A is fixated on B if for every x: A x = B. ;; Kestrel p.77 (def-combinator '[K x y] '[x] "Kestrel") (show-combinators) ;; Left cancellation law for kestrels: if K x = K y then x = y. ;; Identity Bird aka Idiot p.78 (def-combinator '[I x] '[x] "Identity Bird") (show-combinators) ;; Lark p.80 (def-combinator '[L x y] '[x (y y)] "Lark") (show-combinators) ;; 24 ; Given L and I, then there is a M with M x = x x. (session '[L I x]) (red :L) (red :I) ; or (weak-reduce '[L I x]) ; L I x -> x x, i.e. M = L I ;; 25 ; Given L, then every bird x is fond of at least one bird (session '[x (L x (L x))]) (exp :L) ; x (L x (L x)) = L x (L x) ; Any bird x is fond of L x (L x) = (L x) (L x) ;; 26 ; Given L, then there is a bird of whom L L is fond (session '[L L ((L (L L)) (L (L L)))]) (red :L) ; => [L (L (L L) (L (L L)) (L (L L) (L (L L))))] ;; Chap 10: Is There a Sage Bird? --------------------------------------------- ; A sage bird Theta is a bird with x (Theta x) = Theta x, aka a fixed point combinator ; There is such a bird: the composition of M and L (session '[M (L x)]) (red :M) (red :L) (exp :M) (session '[x (M (L x))]) (red :M) (exp :L) (exp :M) ; [x (M (L x))] = [M (L x)] ;; Chap 11: Birds Galore ------------------------------------------------------ ; Introduction (max-parens '[x y (z w y) v]) ; => [(((x y) ((z w) y)) v)] (max-parens '[(x y z) (w v x)]) ; => [(((x y) z) ((w v) x))] (max-parens '[x y (z w v) (x z)]) ; => [(((x y) ((z w) v)) (x z))] (max-parens '[x y (z w v) x z]) ; => [((((x y) ((z w) v)) x) z)] (max-parens '[x (y (z w v)) x z]) ; => [(((x (y ((z w) v))) x) z)] (= (max-parens '[x y z (A B)]) (max-parens '[(x y z) (A B)])) ; => true (= (max-parens '[x y w]) (max-parens (subst '[z w] '[z] '(x y)))) ; => true (= (max-parens '[w x y]) (max-parens (subst '[w z] '[z] '(x y)))) ; => false ;; Bluebird p.95 (def-combinator '[B x y z] '[x (y z)] "Bluebird") (show-combinators) ;; 1 ; Given B then the composition law holds (session '[(B f g) x]) (red :B) ; => [f (g x)] i.e. [B f g] composes f with g. ; Let's use this fact (session '[B M L x]) (red :B) (red :M) (red :L) (exp :M) (exp :B 2) ; => [x (B M L x) i.e. B M L is a sage bird ;; 2 ; Given B and M, write down an expression in terms of B, M, x that describes a bird of which x is fond. (session '[(M (B x M))]) (red :M) (red :B) ; => [x (M (B x M))] (session '[x (M (B x M))]) (exp :B) (exp :M) ; => [M (B x M)] ; x is fond of M (B x M) ;; 3 ; Given B and M, find egocentric bird (session '[M (B M M)]) (red :M) (red :B) (red :M) ; => [M (B M M) (M (B M M))] ; M (B M M) is egocentric, i.e. Z = Z Z ;; 4 ; Given B, M and K, find hopelessly egocentric bird ; M (B K M) is hopelessly egocentric , i.e. for all x: Z x = Z (session '[M (B K M) x]) (red :M) (red :B) (red :K) ; => [M (B K M)] (session '[M (B K M)]) (exp :K) (swap '?1 '[x]) (exp :B) (exp :M) ; => [M (B K M) x] ;; Dove p.97 (def-combinator '[D x y z w] '[x y (z w)] "Dove") (show-combinators) ;; 5 ; D can be derived from B alone, how? (session '[B B x y z w]) (red :B) (red :B) ; => [x y (z w)], i.e. D = B B. (= (weak-reduce '[B B x y z w]) (weak-reduce '[D x y z w])) ; => true ;; Blackbird p.97 (def-combinator '[B1 x y z w] '[x (y z w)] "Blackbird") (show-combinators) ;; 6 ; Given B, then there is a D and a B1 too: ; D = B B, and B1 = D B = B B B (weak-reduce '[D B x y z w]) ; => [x (y z w)], i.e. B1 = D B. (weak-reduce '[B B B x y z w]) ; => [x (y z w)], i.e. B1 = B B B. ;; Eagle p.97 (def-combinator '[E x y z w v] '[x y (z w v)] "Eagle") (show-combinators) ;; 7 ; Derive E from B (weak-reduce '[B B1 x y z w v]) ; => [x y (z w v)], i.e. E = B B1 = B (B B B). ;; Bunting p.97 (def-combinator '[B2 x y z w v] '[x (y z w v)] "Bunting") (show-combinators) ;; 8 ; Given B find B2 (weak-reduce '[E B x y z w v]) ; => x (y z w v)] (weak-reduce '[B B1 B x y z w v]) ; => [x (y z w v)], i.e. B2 = B (B B B) B ; but this is true too (weak-reduce '[B B B1 x y z w v]) ; => [x (y z w v)], i.e. B2 = B B (B B B) ;; Dickcissel p.97 (def-combinator '[D1 x y z w v] '[x y z (w v)] "Dickcissel") (show-combinators) ;; 9 ; Derive D1 from B (weak-reduce '[B1 B x y z w v]) ; => [x y z (w v)] (weak-reduce '[B B B B x y z w v]) ; => [x y z (w v)], i.e. D1 = B B B B (weak-reduce '[B (B B) x y z w v]) ; => [x y z (w v)], i.e. D1 = B (B B) ;; Becard p.98 (def-combinator '[B3 x y z w] '[x (y (z w))] "Becard") (show-combinators) ;; 10 ; Derive B3 from B (weak-reduce '[D1 B x y z w]) ; => [x (y (z w))] (weak-reduce '[B (B B) B x y z w]) ; => [x (y (z w))] (weak-reduce '[B B B B B x y z w]) ; => [x (y (z w))] ;; Dovekie p.98 (def-combinator '[D2 x y z w v] '[x (y z) (w v)] "Dovekie") (show-combinators) ;; 11 ; Derive D2 from B (weak-reduce '[B B (B B) x y z w v]) ; => [x (y z) (w v)], i.e. D2 = B B (B B) (weak-reduce '[D D x y z w v]) ; => [x (y z) (w v)], i.e. D2 = D D ;; Bald Eagle p.98 (def-combinator '[Ê x y1 y2 y3 z1 z2 z3] '[x (y1 y2 y3) (z1 z2 z3)] "Bald Eagle") (show-combinators) ;; 12 ; Derive Ê from B (weak-reduce '[E E x y_1 y_2 y_3 z_1 z_2 z_3]) ; => [x (y_1 y_2 y_3) (z_1 z_2 z_3)] (weak-reduce '[B (B B B) (B (B B B)) x y_1 y_2 y_3 z_1 z_2 z_3]) ; => [x (y_1 y_2 y_3) (z_1 z_2 z_3)], i.e. Ê = B (B B B) (B (B B B)) ;; Warbler p.99 (def-combinator '[W x y] '[x y y] "Warbler") (show-combinators) ;; 14 ; Derive M from W and I (weak-reduce '[W I x]) (weak-reduce '[M x]) ; => M = W I ;; 15 ; Derive I from W and K (weak-reduce '[W K x]) ; => W K = I ;; 13 ; Now derive M from W and K (weak-reduce '[W (W K) x]) ; => [x x], i.e. W (W K) = M. ; in steps: (session '[W (W K) x]) (red :W) (red :W) (red :K) ;; Cardinal p.100 (def-combinator '[C x y z] '[x z y] "Cardinal") (show-combinators) ;; 16 ; Derive I from C and K (weak-reduce '[C K K x]) ; => [x], i.e. C K K = I. (weak-reduce '[C K C x]) ; => [x] (weak-reduce '[C K any x]) ; => [x] ;; Trush p.100 (def-combinator '[T x y] '[y x] "Trush") (show-combinators) ;; 17 ; Derive T from C and I (weak-reduce '[C I x y]) ; => [y x], i.e. T = C I. ;; Definition: A and B commute if A B = B A ;; 19 ; Given B, T and M find a bird that commutes with every bird (session '[M (B T M) x]) (red :M) (red :B) (red :T) ; => [x (M (B T M))], i.e. M (B T M) commutes with any x. ;; Robin p.101 (def-combinator '[R x y z] '[y z x] "Robin") (show-combinators) ;; 20 ; Derive R from B and T (weak-reduce '[B B T x y z]) ; => y z x], i.e. R = B B T. ;; 21 ; Derive C from R alone (weak-reduce '[R R R x y z]) ; => [x z y], i.e. R R R = C ; Derive C from B B T with 9 letters (weak-reduce '[B B T (B B T) (B B T) x y z]) ; => [x z y] ; A shorter term with 8 letters? (weak-reduce '[B B T (B B T) (B B T)]) ; => [B (T (B B T)) (B B T)] hence (weak-reduce '[B (T (B B T)) (B B T) x y z]) ; => [x z y] ;; 22 Two useful laws ;; 22a (session '[C x y z]) (red :C) (exp :R) (exp :R 2) ; => [R x R y z], i.e. C x = R x R. ;; 22b (session '[C x y z]) (red :C) (exp :R) (exp :T 2) (exp :B) ; => [B (T x) R y z], i.e. C x = B (T x) R. ;; 23 ; Derive R from C (weak-reduce '[C C x y z]) ; => [y z x] (= (weak-reduce '[C C x y z]) (weak-reduce '[R x y z])) ; => true ;; Finch p.102 (def-combinator '[F x y z] '[z y x] "Finch") ;; 24 (weak-reduce '[B C R x y z]) ; => [z y x] (weak-reduce '[B (R R R) R x y z]) ; => [z y x] (weak-reduce '[B C (C C) x y z]) ; => [z y x] ;; 25 (weak-reduce '[E T T E T x y z]) ; => [z y x] ;; 26 (weak-reduce '[B C R x y z]) (weak-reduce '[B (R R R) R x y z]) (weak-reduce '[B (B (T (B B T)) (B B T)) (B B T) x y z]) ; => [z y x] (weak-reduce '[E T T E T x y z]) (weak-reduce '[B (B B B) T T (B (B B B)) T x y z]) ; => [z y x] (weak-reduce '[B (B B B) T T (B (B B B)) T]) ; => [B (T T) (B (B B B) T)], thus (weak-reduce '[B (T T) (B (B B B) T) x y z] ) ; => [z y x] a bit shorter than the solution above ;; Vireo p.103 (def-combinator '[V x y z] '[z x y] "Vireo") ;; 27 (weak-reduce '[C F x y z]) ; => [z x y], i.e. V = C F (weak-reduce '[B C T x y z]) ; => [z x y], i.e. V = B C T ;; 28 (weak-reduce '[R R R F x y z]) ; => [z x y], and also (weak-reduce '[R F R x y z]) ; => [z x y] ;; 29 (weak-reduce '[C V x y z]) ; => [z y x], i.e. C V = F ;; 30 (weak-reduce '[R K K x]) ; => [x] (weak-reduce '[R R K x]) ; => [x] ;; Cardinal once removed p.104 (def-combinator '[C* x y z w] '[x y w z] "Cardinal once removed") ;; 31 (weak-reduce '[B C x y z w]) ; => [x y w z], i.e. C* = B C ;; Robin once removed p.104 (def-combinator '[R* x y z w] '[x z w y] "Robin once removed") ;; 32 (weak-reduce '[B C (B C) x y z w]) ; => [x z w y], i.e. R* = B C (B C) = C* C* ;; Finch once removed p.104 (def-combinator '[F* x y z w] '[x w z y] "Finch once removed") ;; 33 (weak-reduce '[B C* R* x y z w]) (weak-reduce '[B C* (C* C*) x y z w]) ; => [x w z y], i.e. F* = B C* R* = B C* (C* C*) ;; Vireo once removed p.104 (def-combinator '[V* x y z w] '[x w y z] "Vireo once removed") ;; 34 (= (weak-reduce '[C* F* x y z w]) (weak-reduce '[V* x y z w])) ; => true ;; Cardinal twice removed p.105 (def-combinator '[C** x y z_1 z_2 z_3] '[x y z_1 z_3 z_2] "Cardinal twice removed") ;; Robin twice removed p.105 (def-combinator '[R** x y z_1 z_2 z_3] '[x y z_2 z_3 z_1] "Robin twice removed") ;; Finch twice removed p.105 (def-combinator '[F** x y z_1 z_2 z_3] '[x y z_3 z_2 z_1] "Finch twice removed") ;; Vireo twice removed p.105 (def-combinator '[V** x y z_1 z_2 z_3] '[x y z_3 z_1 z_2] "Vireo twice removed") ;; 35 (= (weak-reduce '[C** x y z_1 z_2 z_3]) (weak-reduce '[B C* x y z_1 z_2 z_3])) ; => true, i.e. C** = B C* (= (weak-reduce '[R** x y z_1 z_2 z_3]) (weak-reduce '[B R* x y z_1 z_2 z_3])) ; => true, i.e. R** = B R* (= (weak-reduce '[F** x y z_1 z_2 z_3]) (weak-reduce '[B F* x y z_1 z_2 z_3])) ; => true, i.e. F** = B F* (= (weak-reduce '[V** x y z_1 z_2 z_3]) (weak-reduce '[B V* x y z_1 z_2 z_3])) ; => true, i.e. V** = B V* ;; 36 (= (weak-reduce '[V x y z]) (weak-reduce '[C* T x y z])) ; => true, i.e. V = C* T ;; Queer p.105 (def-combinator '[Q x y z] '[y (x z)] "Queer") ;; 39 (= (weak-reduce '[Q x y z]) (weak-reduce '[C B x y z])) ; => true, i.e. Q = C B (= (weak-reduce '[Q x y z]) (weak-reduce '[B (T B) (B B T) x y z])) ; => true, i.e. Q = B (T B) (B B T) ;; Quixotic p.106 (def-combinator '[Q1 x y z] '[x (z y)] "Quixotic") ;; 38 (= (weak-reduce '[Q1 x y z]) (weak-reduce '[B C B x y z])) ; => true i.e. Q1 = B C B (= (weak-reduce '[Q1 x y z]) (weak-reduce '[C* B x y z])) ; => true i.e. Q1 = C* B (= (weak-reduce '[Q1 x y z]) (weak-reduce '[B (B B T (B B T) (B B T)) B x y z])) ; => true ;; Quizzical p.106 (def-combinator '[Q2 x y z] '[y (z x)] "Quizzical") ;; 39 (= (weak-reduce '[Q2 x y z]) (weak-reduce '[C (B C B) x y z])) ; => true, i.e. Q2 = C (B C B) ;; Quirky p.106 (def-combinator '[Q3 x y z] '[z (x y)] "Quirky") ;; 41 (= (weak-reduce '[Q3 x y z]) (weak-reduce '[B T x y z])) ; => true, i.e. Q3 = B T (= (weak-reduce '[Q3 x y z]) (weak-reduce '[V* B x y z])) ; => true, i.e. Q3 = V* B ;; Quacky p.106 (def-combinator '[Q4 x y z] '[z (y x)] "Quacky") ;; 44 (= (weak-reduce '[Q4 x y z]) (weak-reduce '[Q1 T x y z])) ; => true, i.e. Q4 = Q1 T (= (weak-reduce '[Q4 x y z]) (weak-reduce '[B C B T x y z])) ; => true, i.e. Q4 = B C B T (= (weak-reduce '[Q4 x y z]) (weak-reduce '[C Q3 x y z])) ; => true, i.e. Q4 = C Q3 ;; 45 (= (weak-reduce '[B x y z]) (weak-reduce '[Q T (Q Q) x y z])) ; => true, i.e. B = Q T (Q Q) ;; 46 (= (weak-reduce '[C x y z]) (weak-reduce '[Q Q (Q T) x y z])) ; => true, i.e. C = Q Q (Q T) ;; Goldfinch p.107 (def-combinator '[G x y z w] '[x w (y z)] "Goldfinch") ;; 47 (= (weak-reduce '[G x y z w]) (weak-reduce '[B B C x y z w])) ; => true, i.e. G = B B C ;; Chap 12: Mockingbirds, Warblers and Starlings ------------------------------ ;; Double Mockingbird p.118 (def-combinator '[M2 x y] '[x y (x y)] "Double Mockingbird") ;; 1 (= (weak-reduce '[M2 x y]) (weak-reduce '[B M x y])) ; => true, i.e. M2 = B M ;; 2 (= (weak-reduce '[L x y]) (weak-reduce '[C B M x y])) ; => true, i.e. L = C B M (= (weak-reduce '[L x y] (weak-reduce '[B (T M) B x y]))) ; => true, i.e. L = B (T M) B ;; 3 (= (weak-reduce '[L x y]) (weak-reduce '[B W B x y])) ; => true, i.e. L = B W B ;; 4 (= (weak-reduce '[L x y]) (weak-reduce '[Q M x y])) ; => true, i.e. L = Q M ;; Converse Warbler p.119 (def-combinator '[W' x y] '[y x x] "Converse Warbler") ;; 5 (= (weak-reduce '[W' x y]) (weak-reduce '[C W x y])) ; => true, i.e. W' = C W (= (weak-reduce '[W' x y]) (weak-reduce '[B M R x y])) ; => true, i.e. W' = B M R (= (weak-reduce '[W' x y]) (weak-reduce '[B M (B B T) x y])) ; => true, i.e. W' = B M (B B T) (= (weak-reduce '[W' x y]) (weak-reduce '[B (B M B) T x y])) ; => true, i.e. W' = B (B M B) T ;; 6 (= (weak-reduce '[W x y]) (weak-reduce '[C W' x y])) ; => true, i.e. W = C W' (= (weak-reduce '[W x y]) (weak-reduce '[C (B M R) x y])) ; => true, i.e. W = C (B M R) ;; 7 (= (weak-reduce '[W x y]) (weak-reduce '[B (T (B M (B B T))) (B B T) x y])) ; => true (= (weak-reduce '[W x y]) (weak-reduce '[B (T (B (B M B)T)) (B B T) x y])) ; => true ;; 8 (= (weak-reduce '[M x]) (weak-reduce '[W T x])) ; => true, i.e. M = W T ;; Warbler Once Removed p.120 (def-combinator '[W* x y z] '[x y z z] "Warbler once removed") ;; Warbler Twice Removed p.120 (def-combinator '[W** x y z w] '[x y z w w] "Warbler twice removed") ;; 9 (= (weak-reduce '[W* x y z]) (weak-reduce '[B W x y z])) ; => true, i.e. W* = B W (= (weak-reduce '[W** x y z w]) (weak-reduce '[B (B W) x y z w])) ; => true, i.e. W** = B (B W) ;; Hummingbird p.120 (def-combinator '[H x y z] '[x y z y] "Hummingbird") ;; 10 (= (weak-reduce '[H x y z]) (weak-reduce '[B W (B C) x y z])) ; => true, i.e. H = B W (B C) ;; 11 (= (weak-reduce '[W x y z]) (weak-reduce '[C (H R) x y z])) ; => true, i.e. W = C (H R) ;; Starling p.121 (def-combinator '[S x y z] '[x z (y z)] "Starling") ;; 12 ; S from B C W (= (weak-reduce '[S x y z]) (weak-reduce '[B (B W) (B B C) x y z])) ; => true, i.e. S = B (B W) (B B C) ; S from B T M ?? brute force!! (def S-red1 (subst '[B (B W) (B B C)] '[W] '[B (T (B M (B B T))) (B B T)])) (weak-reduce (comb-concat S-red1 '[x] '[y] '[z])) ; => [x z (y z)] (def S-red2 (subst S-red1 '[C] '[B (T (B B T)) (B B T)])) (weak-reduce (comb-concat S-red2 '[x] '[y] '[z])) S-red2 ; => [B (B (B (T (B M (B B T))) (B B T))) (B B (B (T (B B T)) (B B T)))] ; S from B W G (= (weak-reduce '[S x y z]) (weak-reduce '[B (B W) G x y z])) ; => true, i.e. S = B (B W) G ;; 13 (= (weak-reduce '[H x y z]) (weak-reduce '[S (C C) x y z])) ; => true, i.e. H = S (C C) (= (weak-reduce '[H x y z]) (weak-reduce '[S R x y z])) ; => true, i.e. H = S R ;; 14 (= (weak-reduce '[W x y z]) (weak-reduce '[R (S R R) R x y z])) ; => true, i.e. W = R (S R R) R (= (weak-reduce '[W x y z]) (weak-reduce '[C (S (C C) (C C)) x y z])) ; => true, i.e. W = C (S (C C) (C C)) ;; 15 (= (weak-reduce '[W x y z]) (weak-reduce '[S T x y z])) ; => true, i.e. W = S T ;; 16 (= (weak-reduce '[M x]) (weak-reduce '[S T T x])) ; => true, i.e. M = S T T ;; Bases: ;; Church B, T, M, I ;; Curry B, C, W, I ;; alt B, C, S, I ;; G1 p.124 G1 = B (B B C) (def-combinator '[G1 x y z w v] '[x y v (z w)] "G1") ; G1 from B T (= (weak-reduce '[G1 x y z w v]) (weak-reduce '[B (B B C) x y z w v])) (= (weak-reduce '[G1 x y z w v]) (weak-reduce '[B G x y z w v])) (= (weak-reduce '[G1 x y z w v]) (weak-reduce '[B (B B (B (T (B B T)) (B B T))) x y z w v])) ; => all true ;; G2 p.124 G2 = G1 (B M) (def-combinator '[G2 x y z w] '[x w (x w) (y z)] "G2") ; G2 from G1 M (= (weak-reduce '[G2 x y z w]) (weak-reduce '[G1 (B M) x y z w])) ; => true ;; I2 p.124 I2 = B (T I) (T I) (def-combinator '[I2 x] '[x I I] "I2") ; I2 from B T I (= (weak-reduce '[I2 x] (weak-reduce '[B (T I) (T I) x]))) ; => true ; I2 (F x) = x (weak-reduce '[I2 (F x)]) ; => x ; G2 F (Q I2) = W (= (weak-reduce '[G2 F (Q I2) x y z] (weak-reduce '[W x y z]))) ; S = B (B (B W) C) (B B) (= (weak-reduce '[S x y z] (weak-reduce '[B (B (B W) C) (B B) x y z]))) ;; Phoenix p. 124 Phi = B (B S) B (def-combinator '[Phi x y z w] '[x (y w) (z w)] "Phoenix") ; Phi from S B (= (weak-reduce '[Phi x y z w] (weak-reduce '[B (B S) B x y z w]))) ;; Psi p.124 Psi = B H (B B (B B)) (def-combinator '[Psi x y z w] '[x (y z) (y w)] "Psi") ; Psi from B H (= (weak-reduce '[Psi x y z w] (weak-reduce '[B H (B B (B B)) x y z w]))) ;; H* p. 124 H* = B H (def-combinator '[H* x y z w] '[x y z w z] "Hummingbird once removed") (weak-reduce '[B H x y z w]) ; Psi from B C W (= (weak-reduce '[Psi x y z w] (weak-reduce '[H* D2 x y z w]))) (= (weak-reduce '[Psi x y z w] (weak-reduce '[B H D2 x y z w]))) (= (weak-reduce '[Psi x y z w] (weak-reduce '[B (B W (B C)) (B B (B B)) x y z w]))) ; Phi from B Psi K (= (weak-reduce '[Psi x y z w] (weak-reduce '[Phi (Phi (Phi B)) B (K K) x y z w]))) ;; Gamma p.124 Gamma = Phi (Phi (Phi B)) B (def-combinator '[Gamma x y z w v] '[y (z w) (x y w v)] "Gamma") (= (weak-reduce '[Gamma x y z w v] (weak-reduce '[Phi (Phi (Phi B)) B x y z w v]))) ; Psi from Gamma and K (= (weak-reduce '[Psi x y z w] (weak-reduce '[Gamma (K K) x y z w v]))) ; => true, i.e. Psi = Gamma (K K) ;; S' p.125 S' = C S (def-combinator '[S' x y z] '[y z (x z)] "S'") (= (weak-reduce '[S' x y z] (weak-reduce '[C S x y z]))) (= (weak-reduce '[S' I x y z] (weak-reduce '[W x y z]))) ; => true, i.e. W = S' I ; Q^ such that C Q^ W = S ;; Q^ = Q (Q Q (Q Q)) Q (weak-reduce '[C (Q (Q Q (Q Q)) Q) W x y z]) ; => [x z (y z)] ;; Chap 13: A Gallery of Sage Birds ------------------------------------------- ;; Order of a combinator ;; The order of a combinator is the number of variables that are needed to express the combinator. ;; Examples: ;; Order 1: I and M ;; Order 2: T, L, W ;; Order 3: S, B, C, R, F ... ;; Order 7: Ê ;; Proper (and improper) combinators ;; A combinator having some order is called proper ;; T I is not proper: T I x -> x I, T I x y -> x I y we get not rid of I, so T I has no order ;; I T is proper since I T = T, and T is proper ;; Sage birds ;; A sage bird is a bird Theta such that for all x: x (Theta x) = Theta x ;; Sage birds are improper combinators, but they can be expressed in terms of proper ;; combinators. ;; Since Sage birds are often called Y ;; 1 A sage bird from M, B and R (show-combinator :M) (show-combinator :B) (show-combinator :R) (session '[B M (R M B) x]) (red :B) (red :M) (red :R) (red :B) (red :M) (exp :B 2) (red :B) (exp :M) (exp :B 2) ; => [x (B M (R M B) x)] ;; 2 A sage bird from B, C and M (show-combinator :C) (session '[B M (C B M) x]) (red :B) (red :M) (red :C) (red :B) (red :M) (exp :C 2) (exp :C 4) (exp :M ) (exp :B 2) ; => [x (B M (C B M) x)] ;; 3 A sage bird from M, B and L (show-combinator :L) (session '[B M L x]) (red :B) (red :M) (red :L) (exp :M) (exp :B 2) ; => [x (B M L x)] ;; 4 A sage bird from M, B and W (show-combinator :W) (session '[B M (B W B) x]) (red :B) (red :M) (red :B) (red :W) (red :B) (exp :M) (exp :B 2) ; => [x (B M (B W B) x)] ;; 6 A sage bird from Q, L, W (show-combinator :Q) (session '[W (Q L (Q L)) x]) (red :W) (red :Q) (red :Q) (red :L) (exp :Q 2) (exp :Q 2) (exp :W) ; => [x (W (Q L (Q L)) x)] ;; 5, 7 A sage bird from B, C and W (show-combinator :C) (session '[W (B (C B (B W B)) (B W B)) x]) (red :W) (red :B) (red :C) (red :B) (red :B) (red :W) (red :B) (exp :B 2) (exp :C 2) (exp :B 2) (exp :W) ; => [x (W (B (C B (B W B)) (B W B)) x)] ;; 8 A sage bird from Q and M (session '[Q (Q M) M x]) (red :Q) (red :M) (red :Q) (exp :Q 2) ; => [x (Q (Q M) M x)] ;; 9 A sage bird from S and L (session '[S L L x]) (red :S) (red :L) (exp :S) ; => [x (S L L x)] ;; 10 A sage bird from B, W and S - Curry's sage bird (session '[W S (B W B) x]) (red :W) (red :S) (red :B) (red :W) (red :B) (exp :S) (exp :W) ; => [x (W S (B W B) x)] ;; Turing Bird U p.132 U = L (S (C T)) (def-combinator '[U x y] '[y (x x y)] "Turing Bird") (weak-reduce '[L (S (C T)) x y]) ; => [y (x x y)] ;; 11 A Turing bird from B, M and T (show-combinator :T) ; W, L, Q are derivable from B, M and T (weak-reduce '[B W (L Q) x y]) ; => y (x x y)] ;; 12 A sage bird from U (session '[U U x]) (red :U) ; => x (U U x)], i.e. U U is a sage bird ;; Owl O p.133 U = B W (C B) (def-combinator '[O x y] '[y (x y)] "Owl") ;; 13 O form B, C, W (weak-reduce '[B W (C B) x y]) ; => [y (x y)] ;; 14 U from O and L (= (weak-reduce '[L O x y]) (weak-reduce '[U x y])) ; => U = L O ;; 15 M from O and I (= (weak-reduce '[M x]) (weak-reduce '[O I x])) ; => M = O I ;; 16 O from S and I (= (weak-reduce '[O x y]) (weak-reduce '[S I x y])) ; => O = S I ;; Two combinators A1 and A2 are similar if for all x: A1 x = A2 x ;; A theory of combinators is called extensional if similar birds are identical. ;; I.e. there is exactly on identity combinator, one starling and so forth. ;; Chap 19: Aristocratic Birds ----------------------------------------------- ; Jaybird p.181 J = [B (B C) (W (B C (B (B B B))))] (def-combinator '[J x y z w] '[x y (x w z)] "Jaybird") ;; 1 J from B C W (weak-reduce '[B (B C) (W (B C (B (B B B)))) x y z w]) ; => x y (x w z)] ;; 2 Q1 from J and I (= (weak-reduce '[Q1 x y z]) (weak-reduce '[J I x y z])) ; => Q1 = J I ;; 3 T from Q1 and I (= (weak-reduce '[T x y]) (weak-reduce '[Q1 I x y])) ; => T = Q1 I = J I I ;; 4 R from J and T (= (weak-reduce '[R x y z]) (weak-reduce '[J T x y z])) ; => R = J T ;; 5 B from C and Q1 (= (weak-reduce '[B x y z]) (weak-reduce '[C (Q1 C) Q1 x y z])) ; => B = C (Q1 C) Q1 (= (weak-reduce '[B x y z]) (weak-reduce '[C (J I C) (J I) x y z])) ; => B = C (J I C) (J I) ; J1 p.183 J1 = B J T (def-combinator '[J1 x y z w] '[y x (w x z)] "J1") ;; 6 J1 from J, B and T (weak-reduce '[B J T x y z w]) ; => [y x (w x z)] ;; 7 M from C, T, J1 (= (weak-reduce '[M x]) (weak-reduce '[C (C (C J1 T) T) T x])) ; => M = C (C (C J1 T) T) T ;; Chap 20: Craig's Discovery ------------------------------------------------- ;; 1 Q3 from G and I (= (weak-reduce '[Q3 x y z]) (weak-reduce '[G I x y z])) ; => Q3 = G I ;; 2 T from G and I (= (weak-reduce '[T x y]) (weak-reduce '[G I I x y])) ;=> T = G I I ;; 3 C from G and I (= (weak-reduce '[C x y z]) (weak-reduce '[G G I I x y z])) ; => C = G G I I ;; 4 B from C Q (= (weak-reduce '[R x y z]) (weak-reduce '[C C x y z])) ; => R = C C (= (weak-reduce '[Q x y z]) (weak-reduce '[G R Q3 x y z])) ; => Q = G R Q3 (= (weak-reduce '[B x y z]) (weak-reduce '[C Q x y z])) ; => B = C Q
[ { "context": "ider\n scsynth DSP engine.\"\n :author \"Jeff Rose\"}\n overtone.core.sc\n (:import\n (java.net Ine", "end": 191, "score": 0.9998770952224731, "start": 182, "tag": "NAME", "value": "Jeff Rose" }, { "context": "ork, at least on my laptopt\n(defonce SERVER-HOST \"127.0.0.1\")\n(defonce SERVER-PORT nil) ; nil means a random ", "end": 803, "score": 0.9997726082801819, "start": 794, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "f-set server-thread* sc-thread))\n (connect \"127.0.0.1\" port)\n :booting))))\n\n(defn boot\n \"Boot ei", "end": 13780, "score": 0.9997687935829163, "start": 13771, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
data/clojure/c970c64bc07c2e5c4fba80207793d684_sc.clj
maxim5/code-inspector
5
(ns ^{:doc "An interface to the SuperCollider synthesis server. This is at heart an OSC client library for the SuperCollider scsynth DSP engine." :author "Jeff Rose"} overtone.core.sc (:import (java.net InetSocketAddress) (java.util.regex Pattern) (java.util.concurrent TimeUnit TimeoutException) (java.io BufferedInputStream) (supercollider ScSynth ScSynthStartedListener MessageReceivedListener) (java.util BitSet)) (:require [overtone.core.log :as log]) (:use (overtone.core event config setup util time-utils synthdef) [clojure.contrib.java-utils :only [file]] (clojure.contrib shell-out pprint) osc)) ; TODO: Make this work correctly ; NOTE: "localhost" doesn't work, at least on my laptopt (defonce SERVER-HOST "127.0.0.1") (defonce SERVER-PORT nil) ; nil means a random port ; Max number of milliseconds to wait for a reply from the server (defonce REPLY-TIMEOUT 500) (defonce server-thread* (ref nil)) (defonce server* (ref nil)) (defonce status* (ref :no-audio)) (defonce sc-world* (ref nil)) ; Server limits (defonce MAX-NODES 1024) (defonce MAX-BUFFERS 1024) (defonce MAX-SDEFS 1024) (defonce MAX-AUDIO-BUS 128) (defonce MAX-CONTROL-BUS 4096) (defonce MAX-OSC-SAMPLES 8192) ; We use bit sets to store the allocation state of resources on the audio server. ; These typically get allocated on usage by the client, and then freed either by ; client request or automatically by receiving notifications from the server. ; (e.g. When an envelope trigger fires to free a synth.) (defonce allocator-bits {:node (BitSet. MAX-NODES) :audio-buffer (BitSet. MAX-BUFFERS) :audio-bus (BitSet. MAX-NODES) :control-bus (BitSet. MAX-NODES)}) (defonce allocator-limits {:node MAX-NODES :sdefs MAX-SDEFS :audio-bus MAX-AUDIO-BUS :control-bus MAX-CONTROL-BUS}) (defn alloc-id "Allocate a new ID for the type corresponding to key." [k] (let [bits (get allocator-bits k) limit (get allocator-limits k)] (locking bits (let [id (.nextClearBit bits 0)] (if (= limit id) (throw (Exception. (str "No more " (name k) " ids available!"))) (do (.set bits id) id)))))) (defn free-id "Free the id of type key." [k id] (let [bits (get allocator-bits k) limit (get allocator-limits k)] (locking bits (.clear bits id)))) (defn all-ids "Get all of the currently allocated ids for key." [k] (let [bits (get allocator-bits k) limit (get allocator-limits k)] (locking bits (loop [ids [] idx 0] (let [id (.nextSetBit bits idx)] (if (and (> id -1) (< idx limit)) (recur (conj ids id) (inc id)) ids)))))) (defn clear-ids "Clear all ids allocated for key." [k] (println "clear-ids........................") (locking (get allocator-bits k) (doseq [id (all-ids k)] (free-id k id)))) (defonce ROOT-GROUP 0) (defonce SYNTH-GROUP 1) (defn connected? [] (= :connected @status*)) (declare boot) ; The base handler for receiving osc messages just forwards the message on ; as an event using the osc path as the event key. (on ::osc-msg-received (fn [{{path :path args :args} :msg}] (event path :path path :args args))) (defn snd "Sends an OSC message." [path & args] (if (connected?) (apply osc-send @server* path args) (log/debug "### trying to snd while disconnected! ###")) (log/debug "(snd " path args ")")) (defmacro at "All messages sent within the body will be sent in the same timestamped OSC bundle. This bundling is thread-local, so you don't have to worry about accidentally scheduling packets into a bundle started on another thread." [time-ms & body] `(in-osc-bundle @server* ~time-ms (do ~@body))) (defn debug "Control debug output from both the Overtone and the audio server." [& [on-off]] (if (or on-off (nil? on-off)) (do (log/level :debug) (osc-debug true) (snd "/dumpOSC" 1)) (do (log/level :error) (osc-debug false) (snd "/dumpOSC" 0)))) ; Notifications from Server ; These messages are sent as notification of some event to all clients who have registered via the /notify command . ; All of these have the same arguments: ; int - node ID ; int - the node's parent group ID ; int - previous node ID, -1 if no previous node. ; int - next node ID, -1 if no next node. ; int - 1 if the node is a group, 0 if it is a synth ; ; The following two arguments are only sent if the node is a group: ; int - the ID of the head node, -1 if there is no head node. ; int - the ID of the tail node, -1 if there is no tail node. ; ; /n_go - a node was created ; /n_end - a node was destroyed ; /n_on - a node was turned on ; /n_off - a node was turned off ; /n_move - a node was moved ; /n_info - in reply to /n_query ; ; Trigger Notifications ; ; This command is the mechanism that synths can use to trigger events in ; clients. The node ID is the node that is sending the trigger. The trigger ID ; and value are determined by inputs to the SendTrig unit generator which is ; the originator of this message. ; ; /tr a trigger message ; ; int - node ID ; int - trigger ID ; float - trigger value (defn notify "Turn on notification messages from the audio server. This lets us free synth IDs when they are automatically freed with envelope triggers. It also lets us receive custom messages from various trigger ugens." [notify?] (snd "/notify" (if (false? notify?) 0 1))) (defn- node-destroyed "Frees up a synth node to keep in sync with the server." [id] (log/debug (format "node-destroyed: %d" id)) (free-id :node id)) (defn- node-created "Called when a node is created on the synth." [id] (log/debug (format "node-created: %d" id))) ; Setup the feedback handlers with the audio server. (on "/n_end" #(node-destroyed (first (:args %)))) (on "/n_go" #(node-created (first (:args %)))) (def N-RETRIES 20) (declare reset) (defn- connect-internal [] (log/debug "Connecting to internal SuperCollider server") (let [send-fn (fn [peer-obj buffer] (.send @sc-world* buffer)) peer (assoc (osc-peer) :send-fn send-fn)] (.addMessageReceivedListener @sc-world* (proxy [MessageReceivedListener] [] (messageReceived [buf size] (event ::osc-msg-received :msg (osc-decode-packet buf))))) (dosync (ref-set server* peer)) (snd "/status") (dosync (ref-set status* :connected)) (notify true) ; turn on notifications now that we can communicate (reset) (event :connected))) (defn- connect-external [host port] (log/debug "Connecting to external SuperCollider server: " host ":" port) (let [sc-server (osc-client host port)] (osc-listen sc-server #(event ::osc-msg-received :msg %)) (dosync (ref-set server* sc-server) (ref-set status* :connecting)) ; Runs once when we receive the first status.reply message (on "status.reply" #(do (dosync (ref-set status* :connected)) (notify true) ; turn on notifications now that we can communicate (reset) (event :connected) :done)) ; Send /status in a loop until we get a reply (loop [cnt 0] (log/debug "connect loop...") (when (and (< cnt N-RETRIES) (= @status* :connecting)) (log/debug "sending status...") (snd "/status") (Thread/sleep 100) (recur (inc cnt)))))) ; TODO: setup an error-handler in the case that we can't connect to the server (defn connect "Connect to an external SC audio server on the specified host and port." [& [host port]] (if (and host port) (.run (Thread. #(connect-external host port))) (connect-internal)) ) (defonce running?* (atom false)) (def server-log* (ref [])) (defn server-log "Print the server log." [] (doseq [msg @server-log*] (print msg))) ;Replies to sender with the following message. ;status.reply ; int - 1. unused. ; int - number of unit generators. ; int - number of synths. ; int - number of groups. ; int - number of loaded synth definitions. ; float - average percent CPU usage for signal processing ; float - peak percent CPU usage for signal processing ; double - nominal sample rate ; double - actual sample rate (defn recv [path & [timeout]] (let [p (promise)] (on path #(do (deliver p %) :done)) (if timeout (try (.get (future @p) timeout TimeUnit/MILLISECONDS) (catch TimeoutException t :timeout)) @p))) (defn- parse-status [args] (let [[_ ugens synths groups loaded avg peak nominal actual] args] {:n-ugens ugens :n-synths synths :n-groups groups :n-loaded-synths loaded :avg-cpu avg :peak-cpu peak :nominal-sample-rate nominal :actual-sample-rate actual})) (def STATUS-TIMEOUT 500) (defn status "Check the status of the audio server." [] (if (= :connected @status*) (let [p (promise)] (on "/status.reply" #(do (deliver p (parse-status (:args %))) :done)) (snd "/status") (try (.get (future @p) STATUS-TIMEOUT TimeUnit/MILLISECONDS) (catch TimeoutException t :timeout))) @status*)) (defn wait-sync "Wait until the audio server has completed all asynchronous commands currently in execution." [& [timeout]] (let [sync-id (rand-int 999999) _ (snd "/sync" sync-id) reply (recv "/synced" (if timeout timeout REPLY-TIMEOUT)) reply-id (first (:args reply))] (= sync-id reply-id))) (defn connect-jack-ports "Connect the jack input and output ports as best we can. If jack ports are always different names with different drivers or hardware then we need to find a better strategy to auto-connect." ([] (connect-jack-ports 2)) ([n-channels] (let [port-list (sh "jack_lsp") sc-ins (re-seq #"SuperCollider.*:in_[0-9]*" port-list) sc-outs (re-seq #"SuperCollider.*:out_[0-9]*" port-list) system-ins (re-seq #"system:capture_[0-9]*" port-list) system-outs (re-seq #"system:playback_[0-9]*" port-list) interface-ins (re-seq #"system:AC[0-9]*_dev[0-9]*_.*In.*" port-list) interface-outs (re-seq #"system:AP[0-9]*_dev[0-9]*_LineOut.*" port-list) connections (partition 2 (concat (interleave sc-outs system-outs) (interleave sc-outs interface-outs) (interleave system-ins sc-ins) (interleave interface-ins sc-ins)))] (doseq [[src dest] connections] (sh "jack_connect" src dest) (log/info "jack_connect " src dest))))) (def SC-PATHS {:linux "scsynth" :windows "C:/Program Files/SuperCollider/scsynth.exe" :mac "/Applications/SuperCollider/scsynth" }) (def SC-ARGS {:linux [] :windows [] :mac ["-U" "/Applications/SuperCollider/plugins"] }) (defonce _jack_connector_ (if (= :linux (@config* :os)) (on :connected #(connect-jack-ports)))) (defonce scsynth-server* (ref nil)) (defn internal-booter [port] (reset! running?* true) (log/info "booting internal audio server listening on port: " port) (let [server (ScSynth.)] (.addScSynthStartedListener server (proxy [ScSynthStartedListener] [] (started [] (event :booted)))) (dosync (ref-set sc-world* server)) (.run server))) (defn boot-internal ([] (boot-internal (+ (rand-int 50000) 2000))) ([port] (log/info "boot-internal: " port) (if (not @running?*) (let [sc-thread (Thread. #(internal-booter port))] (.setDaemon sc-thread true) (log/debug "Booting SuperCollider internal server (scsynth)...") (.start sc-thread) (dosync (ref-set server-thread* sc-thread)) (on :booted connect) :booting)))) (defn- sc-log "Pull audio server log data from a pipe and store for later printing." [stream read-buf] (while (pos? (.available stream)) (let [n (min (count read-buf) (.available stream)) _ (.read stream read-buf 0 n) msg (String. read-buf 0 n)] (dosync (alter server-log* conj msg)) (log/info (String. read-buf 0 n))))) (defn- external-booter "Boot thread to start the external audio server process and hook up to STDOUT for log messages." [cmd] (reset! running?* true) (log/debug "booting external audio server...") (let [proc (.exec (Runtime/getRuntime) cmd) in-stream (BufferedInputStream. (.getInputStream proc)) err-stream (BufferedInputStream. (.getErrorStream proc)) read-buf (make-array Byte/TYPE 256)] (while @running?* (sc-log in-stream read-buf) (sc-log err-stream read-buf) (Thread/sleep 250)) (.destroy proc))) (defn boot-external "Boot the audio server in an external process and tell it to listen on a specific port." ([port] (if (not @running?*) (let [cmd (into-array String (concat [(SC-PATHS (@config* :os)) "-u" (str port)] (SC-ARGS (@config* :os)))) sc-thread (Thread. #(external-booter cmd))] (.setDaemon sc-thread true) (log/debug "Booting SuperCollider server (scsynth)...") (.start sc-thread) (dosync (ref-set server-thread* sc-thread)) (connect "127.0.0.1" port) :booting)))) (defn boot "Boot either the internal or external audio server." ([] (boot (get @config* :server :internal) SERVER-HOST SERVER-PORT)) ([which & [host port]] (let [port (if (nil? port) (+ (rand-int 50000) 2000) port)] (cond (= :internal which) (boot-internal port) (= :external which) (boot-external host port))))) (defn quit "Quit the SuperCollider synth process." [] (log/info "quiting supercollider") (sync-event :quit) (when (connected?) (snd "/quit") (log/debug "SERVER: " @server*) (osc-close @server* true)) (reset! running?* false) (dosync (ref-set server* nil) (ref-set status* :no-audio))) ; TODO: Come up with a better way to delay shutdown until all of the :quit event handlers ; have executed. For now we just use 500ms. (defonce _shutdown-hook (.addShutdownHook (Runtime/getRuntime) (Thread. #(do (quit) (Thread/sleep 500))))) ; Synths, Busses, Controls and Groups are all Nodes. Groups are linked lists ; and group zero is the root of the graph. Nodes can be added to a group in ; one of these 5 positions relative to either the full list, or a specified node. (def POSITION {:head 0 :tail 1 :before-node 2 :after-node 3 :replace-node 4}) ;; Sending a synth-id of -1 lets the server choose an ID (defn node "Instantiate a synth node on the audio server. Takes the synth name and a set of argument name/value pairs. Optionally use :target <node/group-id> and :position <pos> to specify where the node should be located. The position can be one of :head, :tail :before-node, :after-node, or :replace-node. (node \"foo\") (node \"foo\" :pitch 60) (node \"foo\" :pitch 60 :target 0) (node \"foo\" :pitch 60 :target 2 :position :tail) " [synth-name & args] (if (not (connected?)) (throw (Exception. "Not connected to synthesis engine. Please boot or connect."))) (let [id (alloc-id :node) argmap (apply hash-map args) position ((get argmap :position :tail) POSITION) target (get argmap :target 0) args (flatten (seq (-> argmap (dissoc :position) (dissoc :target)))) args (stringify (floatify args))] ;(println "node " synth-name id position target args) (apply snd "/s_new" synth-name id position target args) id)) (defn node-free "Remove a synth node" [& node-ids] {:pre [(connected?)]} (apply snd "/n_free" node-ids) (doseq [id node-ids] (free-id :node id))) (defn node-run "Start a stopped synth node." [node-id] {:pre [(connected?)]} (snd "/n_run" node-id 1)) (defn node-stop "Stop a running synth node." {:pre [(connected?)]} [node-id] (snd "/n_run" node-id 0)) (defn node-place "Place a node :before or :after another node." [node-id position target-id] {:pre [(connected?)]} (cond (= :before position) (snd "/n_before" node-id target-id) (= :after position) (snd "/n_after" node-id target-id))) (defn node-control "Set control values for a node." [node-id & name-values] {:pre [(connected?)]} (apply snd "/n_set" node-id (stringify name-values)) node-id) ; This can be extended to support setting multiple ranges at once if necessary... (defn node-control-range "Set a range of controls all at once, or if node-id is a group control all nodes in the group." [node-id ctl-start & ctl-vals] {:pre [(connected?)]} (apply snd "/n_setn" node-id ctl-start (count ctl-vals) ctl-vals)) (defn node-map-controls "Connect a node's controls to a control bus." [node-id & names-busses] {:pre [(connected?)]} (apply snd "/n_map" node-id names-busses)) (defn group "Create a new group as a child of the target group." [position target-id] {:pre [(connected?)]} (let [id (alloc-id :node)] (snd "/g_new" id (get POSITION position) target-id) id)) (defn group-free "Free the specified group." [& group-ids] {:pre [(connected?)]} (apply node-free group-ids) ) (defn post-tree "Posts a representation of this group's node subtree, i.e. all the groups and synths contained within it, optionally including the current control values for synths." [id & [with-args?]] {:pre [(connected?)]} (snd "/g_dumpTree" id with-args?)) ;/g_queryTree get a representation of this group's node subtree. ; [ ; int - group ID ; int - flag: if not 0 the current control (arg) values for synths will be included ; ] * N ; ; Request a representation of this group's node subtree, i.e. all the groups and ; synths contained within it. Replies to the sender with a /g_queryTree.reply ; message listing all of the nodes contained within the group in the following ; format: ; ; int - flag: if synth control values are included 1, else 0 ; int - node ID of the requested group ; int - number of child nodes contained within the requested group ; then for each node in the subtree: ; [ ; int - node ID ; int - number of child nodes contained within this node. If -1this is a synth, if >=0 it's a group ; then, if this node is a synth: ; symbol - the SynthDef name for this node. ; then, if flag (see above) is true: ; int - numControls for this synth (M) ; [ ; symbol or int: control name or index ; float or symbol: value or control bus mapping symbol (e.g. 'c1') ; ] * M ; ] * the number of nodes in the subtree (def *data* nil) (defn- parse-synth-tree [id ctls?] (let [sname (first *data*)] (if ctls? (let [n-ctls (second *data*) [ctl-data new-data] (split-at (* 2 n-ctls) (nnext *data*)) ctls (apply hash-map ctl-data)] (set! *data* new-data) {:synth sname :id id :controls ctls}) (do (set! *data* (next *data*)) {:synth sname :id id})))) (defn- parse-node-tree-helper [ctls?] (let [[id n-children & new-data] *data*] (set! *data* new-data) (cond (neg? n-children) (parse-synth-tree id ctls?) ; synth (= 0 n-children) {:group id :children nil} (pos? n-children) {:group id :children (doall (map (fn [i] (parse-node-tree-helper ctls?)) (range n-children)))}))) (defn- parse-node-tree [data] (let [ctls? (= 1 (first data))] (binding [*data* (next data)] (parse-node-tree-helper ctls?)))) ; N.B. The order of nodes corresponds to their execution order on the server. ; Thus child nodes (those contained within a group) are listed immediately ; following their parent. See the method Server:queryAllNodes for an example of ; how to process this reply. (defn node-tree "Returns a data structure representing the current arrangement of groups and synthesizer instances residing on the audio server." ([] (node-tree 0)) ([id & [ctls?]] (let [ctls? (if (or (= 1 ctls?) (= true ctls?)) 1 0)] (snd "/g_queryTree" id ctls?) (let [tree (:args (recv "/g_queryTree.reply" REPLY-TIMEOUT))] (with-meta (parse-node-tree tree) {:type ::node-tree}))))) (defn prepend-node "Add a synth node to the end of a group list." [g n] (snd "/g_head" g n)) (defn append-node "Add a synth node to the end of a group list." [g n] (snd "/g_tail" g n)) (defn group-clear "Free all child synth nodes in a group." [group-id] (snd "/g_freeAll" group-id)) (defn clear-msg-queue "Remove any scheduled OSC messages from the run queue." [] (snd "/clearSched")) (defn sync-all "Wait until all asynchronous server operations have been completed." [] (recv "/synced")) ; The /done message just has a single argument: ; "/done" "s" <completed-command> ; ; where the command would be /b_alloc and others. (defn on-done "Runs a one shot handler that takes no arguments when an OSC /done message from scsynth arrives with a matching path. Look at load-sample for an example of usage. " [path handler] (on "/done" #(if (= path (first (:args %))) (do (handler) :done)))) ; TODO: Look into multi-channel buffers. Probably requires adding multi-id allocation ; support to the bit allocator too... ; size is in samples (defn buffer "Allocate a new buffer for storing audio data." [size & [channels]] (let [channels (or channels 1) id (alloc-id :audio-buffer) ready? (atom false)] (on-done "/b_alloc" #(reset! ready? true)) (snd "/b_alloc" id size channels) (with-meta {:id id :size size :ready? ready?} {:type ::buffer}))) (defn ready? "Check whether a sample or a buffer has completed allocating and/or loading data." [buf] @(:ready? buf)) (defn buffer? [buf] (isa? (type buf) ::buffer)) (defn- buf-or-id [b] (cond (buffer? b) (:id b) (number? b) b :default (throw (Exception. "Not a valid buffer: " b)))) (defn buffer-free "Free an audio buffer and the memory it was consuming." [buf] (snd "/b_free" (:id buf)) (free-id :audio-buffer (:id buf)) :done) ; TODO: Test me... (defn buffer-read "Read a section of an audio buffer." [buf start len] (assert (buffer? buf)) (loop [reqd 0] (when (< reqd len) (let [to-req (min MAX-OSC-SAMPLES (- len reqd))] (snd "/b_getn" (:id buf) (+ start reqd) to-req) (recur (+ reqd to-req))))) (let [samples (float-array len)] (loop [recvd 0] (if (= recvd len) samples (let [msg (recv "/b_setn" REPLY-TIMEOUT) ;_ (println "b_setn msg: " (take 3 (:args msg))) [buf-id bstart blen & samps] (:args msg)] (loop [idx bstart samps samps] (when samps (aset-float samples idx (first samps)) (recur (inc idx) (next samps)))) (recur (+ recvd blen))))))) ;; TODO: test me... (defn buffer-write "Write into a section of an audio buffer." [buf start len data] (assert (buffer? buf)) (snd "/b_setn" (:id buf) start len data)) (defn save-buffer "Save the float audio data in an audio buffer to a wav file." [buf path & args] (assert (buffer? buf)) (let [arg-map (merge (apply hash-map args) {:header "wav" :samples "float" :n-frames -1 :start-frame 0 :leave-open 0}) {:keys [header samples n-frames start-frame leave-open]} arg-map] (snd "/b_write" (:id buf) path header samples n-frames start-frame leave-open) :done)) (defmulti buffer-id type) (defmethod buffer-id java.lang.Integer [id] id) (defmethod buffer-id ::buffer [buf] (:id buf)) (defn buffer-data "Get the floating point data for a buffer on the internal server." [buf] (let [buf-id (buffer-id buf) snd-buf (.getSndBufAsFloatArray @sc-world* buf-id)] snd-buf)) (defn buffer-info [buf] (snd "/b_query" (buffer-id buf)) (let [msg (recv "/b_info" REPLY-TIMEOUT) [buf-id n-frames n-channels rate] (:args msg)] {:n-frames n-frames :n-channels n-channels :rate rate})) (defn sample-info [s] (buffer-info (:buf s))) (defonce loaded-synthdefs* (ref {})) (defn load-synthdef "Load a Clojure synth definition onto the audio server." [sdef] (assert (synthdef? sdef)) (dosync (alter loaded-synthdefs* assoc (:name sdef) sdef)) (if (connected?) (snd "/d_recv" (synthdef-bytes sdef)))) (defn- load-all-synthdefs [] (doseq [[sname sdef] @loaded-synthdefs*] (println "loading synthdef: " sname) (snd "/d_recv" (synthdef-bytes sdef)))) (defonce _synthdef-handler_ (on :connected load-all-synthdefs)) (defn load-synth-file "Load a synth definition file onto the audio server." [path] (snd "/d_recv" (synthdef-bytes (synthdef-read path)))) ; TODO: need to clear all the buffers and busses ; * Think about a sane policy for setting up state, especially when we are connected ; with many peers on one or more servers... (defn reset "Clear all synthesizers, groups and pending messages from the audio server and then recreates the active synth groups." [] (clear-msg-queue) (group-clear SYNTH-GROUP) ; clear the synth group (sync-event :reset)) (defonce _connect-handler_ (on :connected #(group :tail ROOT-GROUP))) (defn restart "Reset everything and restart the SuperCollider process." [] (reset) (quit) (boot)) (defmulti hit-at (fn [& args] (type (second args)))) (defmethod hit-at String [time-ms synth & args] (at time-ms (apply node synth args))) (defmethod hit-at clojure.lang.Keyword [time-ms synth & args] (at time-ms (apply node (name synth) args))) (defmethod hit-at ::sample [time-ms synth & args] (apply hit-at time-ms "granular" :buf (get-in synth [:buf :id]) args)) (defmethod hit-at :default [& args] (throw (Exception. (str "Hit doesn't know how to play the given synth type: " args)))) ; Turn hit into a multimethod ; Convert samples to be a map object instead of an ID (defn hit "Fire off a synth or sample at a specified time. These are the same: (hit :kick) (hit \"kick\") (hit (now) \"kick\") Or you can get fancier like this: (hit (now) :sin :pitch 60) (doseq [i (range 10)] (hit (+ (now) (* i 250)) :sin :pitch 60 :dur 0.1)) " ([] (hit-at (now) "ping" :pitch (choose [60 65 72 77]))) ([& args] (apply hit-at (if (isa? (type (first args)) Number) args (cons (now) args))))) (defmacro check "Try out an anonymous synth definition. Useful for experimentation. If the root node is not an out ugen, then it will add one automatically." [body] `(do (load-synthdef (synth "audition-synth" {} ~body)) (let [note# (hit (now) "audition-synth")] (at (+ (now) 1000) (node-free note#))))) (defn ctl "Modify synth parameters, optionally at a specified time. (hit :sin :pitch 50) => 1000 (ctl 1000 :pitch 40) (ctl (+ (now) 2000) 1000 :pitch 60) " [& args] (let [[time-ms synth-id ctls] (if (odd? (count args)) [(now) (first args) (next args)] [(first args) (second args) (drop 2 args)])] ;(println time-ms synth-id ": " ctls) (at time-ms (apply node-control synth-id (stringify ctls))))) (defn kill "Free one or more synth nodes. Functions that create instance of synth definitions, such as hit, return a handle for the synth node that was created. (let [handle (hit :sin)] ; returns => synth-handle (kill (+ 1000 (now)) handle)) ; a single handle without a time kills immediately (kill handle) ; or a bunch of synth handles can be removed at once (kill (hit) (hit) (hit)) ; or a seq of synth handles can be removed at once (kill [(hit) (hit) (hit)]) " [& ids] (apply node-free (flatten ids)) :killed) (defn load-instruments [] (doseq [synth (filter #(synthdef? %1) (map #(var-get %1) (vals (ns-publics 'overtone.instrument))))] ;(println "loading synth: " (:name synth)) (load-synthdef synth))) ;(defn update ; "Update a voice or standalone synth with new settings." ; [voice & args] ; (let [[names vals] (synth-args (apply hash-map args)) ; synth (if (voice? voice) (:synth voice) voice)] ; (.set synth names vals))) ;(defmethod play-note :synth [voice note-num dur & args] ; (let [args (assoc (apply hash-map args) :note note-num) ; synth (trigger (:synth voice) args)] ; (schedule #(release synth) dur) ; synth)) (defn- name-synth-args [args names] (loop [args args names names named []] (if args (recur (next args) (next names) (concat named [(first names) (first args)])) named))) (defn synth-player "Returns a player function for a named synth. Used by (synth ...) internally, but can be used to generate a player for a pre-compiled synth. The function generated will accept two optional arguments that must come first, the :target and :position (see the node function docs). (foo) (foo :target 0 :position :tail) or if foo has two arguments: (foo 440 0.3) (foo :target 0 :position :tail 440 0.3) at the head of group 2: (foo :target 2 :position :head 440 0.3) These can also be abbreviated: (foo :tgt 2 :pos :head) " [sname arg-names] (fn [& args] (let [[args sgroup] (if (or (= :target (first args)) (= :tgt (first args))) [(drop 2 args) (second args)] [args ROOT-GROUP]) [args pos] (if (or (= :position (first args)) (= :pos (first args))) [(drop 2 args) (second args)] [args :tail]) controller (partial node-control sgroup) player (partial node sname :target sgroup :position pos) [tgt-fn args] (if (= :ctl (first args)) [controller (rest args)] [player args]) args (map #(if (buffer? %) (:id %) %) args) named-args (if (keyword? (first args)) args (name-synth-args args arg-names))] (apply tgt-fn named-args)))) (defonce _auto-boot_ (boot))
73132
(ns ^{:doc "An interface to the SuperCollider synthesis server. This is at heart an OSC client library for the SuperCollider scsynth DSP engine." :author "<NAME>"} overtone.core.sc (:import (java.net InetSocketAddress) (java.util.regex Pattern) (java.util.concurrent TimeUnit TimeoutException) (java.io BufferedInputStream) (supercollider ScSynth ScSynthStartedListener MessageReceivedListener) (java.util BitSet)) (:require [overtone.core.log :as log]) (:use (overtone.core event config setup util time-utils synthdef) [clojure.contrib.java-utils :only [file]] (clojure.contrib shell-out pprint) osc)) ; TODO: Make this work correctly ; NOTE: "localhost" doesn't work, at least on my laptopt (defonce SERVER-HOST "127.0.0.1") (defonce SERVER-PORT nil) ; nil means a random port ; Max number of milliseconds to wait for a reply from the server (defonce REPLY-TIMEOUT 500) (defonce server-thread* (ref nil)) (defonce server* (ref nil)) (defonce status* (ref :no-audio)) (defonce sc-world* (ref nil)) ; Server limits (defonce MAX-NODES 1024) (defonce MAX-BUFFERS 1024) (defonce MAX-SDEFS 1024) (defonce MAX-AUDIO-BUS 128) (defonce MAX-CONTROL-BUS 4096) (defonce MAX-OSC-SAMPLES 8192) ; We use bit sets to store the allocation state of resources on the audio server. ; These typically get allocated on usage by the client, and then freed either by ; client request or automatically by receiving notifications from the server. ; (e.g. When an envelope trigger fires to free a synth.) (defonce allocator-bits {:node (BitSet. MAX-NODES) :audio-buffer (BitSet. MAX-BUFFERS) :audio-bus (BitSet. MAX-NODES) :control-bus (BitSet. MAX-NODES)}) (defonce allocator-limits {:node MAX-NODES :sdefs MAX-SDEFS :audio-bus MAX-AUDIO-BUS :control-bus MAX-CONTROL-BUS}) (defn alloc-id "Allocate a new ID for the type corresponding to key." [k] (let [bits (get allocator-bits k) limit (get allocator-limits k)] (locking bits (let [id (.nextClearBit bits 0)] (if (= limit id) (throw (Exception. (str "No more " (name k) " ids available!"))) (do (.set bits id) id)))))) (defn free-id "Free the id of type key." [k id] (let [bits (get allocator-bits k) limit (get allocator-limits k)] (locking bits (.clear bits id)))) (defn all-ids "Get all of the currently allocated ids for key." [k] (let [bits (get allocator-bits k) limit (get allocator-limits k)] (locking bits (loop [ids [] idx 0] (let [id (.nextSetBit bits idx)] (if (and (> id -1) (< idx limit)) (recur (conj ids id) (inc id)) ids)))))) (defn clear-ids "Clear all ids allocated for key." [k] (println "clear-ids........................") (locking (get allocator-bits k) (doseq [id (all-ids k)] (free-id k id)))) (defonce ROOT-GROUP 0) (defonce SYNTH-GROUP 1) (defn connected? [] (= :connected @status*)) (declare boot) ; The base handler for receiving osc messages just forwards the message on ; as an event using the osc path as the event key. (on ::osc-msg-received (fn [{{path :path args :args} :msg}] (event path :path path :args args))) (defn snd "Sends an OSC message." [path & args] (if (connected?) (apply osc-send @server* path args) (log/debug "### trying to snd while disconnected! ###")) (log/debug "(snd " path args ")")) (defmacro at "All messages sent within the body will be sent in the same timestamped OSC bundle. This bundling is thread-local, so you don't have to worry about accidentally scheduling packets into a bundle started on another thread." [time-ms & body] `(in-osc-bundle @server* ~time-ms (do ~@body))) (defn debug "Control debug output from both the Overtone and the audio server." [& [on-off]] (if (or on-off (nil? on-off)) (do (log/level :debug) (osc-debug true) (snd "/dumpOSC" 1)) (do (log/level :error) (osc-debug false) (snd "/dumpOSC" 0)))) ; Notifications from Server ; These messages are sent as notification of some event to all clients who have registered via the /notify command . ; All of these have the same arguments: ; int - node ID ; int - the node's parent group ID ; int - previous node ID, -1 if no previous node. ; int - next node ID, -1 if no next node. ; int - 1 if the node is a group, 0 if it is a synth ; ; The following two arguments are only sent if the node is a group: ; int - the ID of the head node, -1 if there is no head node. ; int - the ID of the tail node, -1 if there is no tail node. ; ; /n_go - a node was created ; /n_end - a node was destroyed ; /n_on - a node was turned on ; /n_off - a node was turned off ; /n_move - a node was moved ; /n_info - in reply to /n_query ; ; Trigger Notifications ; ; This command is the mechanism that synths can use to trigger events in ; clients. The node ID is the node that is sending the trigger. The trigger ID ; and value are determined by inputs to the SendTrig unit generator which is ; the originator of this message. ; ; /tr a trigger message ; ; int - node ID ; int - trigger ID ; float - trigger value (defn notify "Turn on notification messages from the audio server. This lets us free synth IDs when they are automatically freed with envelope triggers. It also lets us receive custom messages from various trigger ugens." [notify?] (snd "/notify" (if (false? notify?) 0 1))) (defn- node-destroyed "Frees up a synth node to keep in sync with the server." [id] (log/debug (format "node-destroyed: %d" id)) (free-id :node id)) (defn- node-created "Called when a node is created on the synth." [id] (log/debug (format "node-created: %d" id))) ; Setup the feedback handlers with the audio server. (on "/n_end" #(node-destroyed (first (:args %)))) (on "/n_go" #(node-created (first (:args %)))) (def N-RETRIES 20) (declare reset) (defn- connect-internal [] (log/debug "Connecting to internal SuperCollider server") (let [send-fn (fn [peer-obj buffer] (.send @sc-world* buffer)) peer (assoc (osc-peer) :send-fn send-fn)] (.addMessageReceivedListener @sc-world* (proxy [MessageReceivedListener] [] (messageReceived [buf size] (event ::osc-msg-received :msg (osc-decode-packet buf))))) (dosync (ref-set server* peer)) (snd "/status") (dosync (ref-set status* :connected)) (notify true) ; turn on notifications now that we can communicate (reset) (event :connected))) (defn- connect-external [host port] (log/debug "Connecting to external SuperCollider server: " host ":" port) (let [sc-server (osc-client host port)] (osc-listen sc-server #(event ::osc-msg-received :msg %)) (dosync (ref-set server* sc-server) (ref-set status* :connecting)) ; Runs once when we receive the first status.reply message (on "status.reply" #(do (dosync (ref-set status* :connected)) (notify true) ; turn on notifications now that we can communicate (reset) (event :connected) :done)) ; Send /status in a loop until we get a reply (loop [cnt 0] (log/debug "connect loop...") (when (and (< cnt N-RETRIES) (= @status* :connecting)) (log/debug "sending status...") (snd "/status") (Thread/sleep 100) (recur (inc cnt)))))) ; TODO: setup an error-handler in the case that we can't connect to the server (defn connect "Connect to an external SC audio server on the specified host and port." [& [host port]] (if (and host port) (.run (Thread. #(connect-external host port))) (connect-internal)) ) (defonce running?* (atom false)) (def server-log* (ref [])) (defn server-log "Print the server log." [] (doseq [msg @server-log*] (print msg))) ;Replies to sender with the following message. ;status.reply ; int - 1. unused. ; int - number of unit generators. ; int - number of synths. ; int - number of groups. ; int - number of loaded synth definitions. ; float - average percent CPU usage for signal processing ; float - peak percent CPU usage for signal processing ; double - nominal sample rate ; double - actual sample rate (defn recv [path & [timeout]] (let [p (promise)] (on path #(do (deliver p %) :done)) (if timeout (try (.get (future @p) timeout TimeUnit/MILLISECONDS) (catch TimeoutException t :timeout)) @p))) (defn- parse-status [args] (let [[_ ugens synths groups loaded avg peak nominal actual] args] {:n-ugens ugens :n-synths synths :n-groups groups :n-loaded-synths loaded :avg-cpu avg :peak-cpu peak :nominal-sample-rate nominal :actual-sample-rate actual})) (def STATUS-TIMEOUT 500) (defn status "Check the status of the audio server." [] (if (= :connected @status*) (let [p (promise)] (on "/status.reply" #(do (deliver p (parse-status (:args %))) :done)) (snd "/status") (try (.get (future @p) STATUS-TIMEOUT TimeUnit/MILLISECONDS) (catch TimeoutException t :timeout))) @status*)) (defn wait-sync "Wait until the audio server has completed all asynchronous commands currently in execution." [& [timeout]] (let [sync-id (rand-int 999999) _ (snd "/sync" sync-id) reply (recv "/synced" (if timeout timeout REPLY-TIMEOUT)) reply-id (first (:args reply))] (= sync-id reply-id))) (defn connect-jack-ports "Connect the jack input and output ports as best we can. If jack ports are always different names with different drivers or hardware then we need to find a better strategy to auto-connect." ([] (connect-jack-ports 2)) ([n-channels] (let [port-list (sh "jack_lsp") sc-ins (re-seq #"SuperCollider.*:in_[0-9]*" port-list) sc-outs (re-seq #"SuperCollider.*:out_[0-9]*" port-list) system-ins (re-seq #"system:capture_[0-9]*" port-list) system-outs (re-seq #"system:playback_[0-9]*" port-list) interface-ins (re-seq #"system:AC[0-9]*_dev[0-9]*_.*In.*" port-list) interface-outs (re-seq #"system:AP[0-9]*_dev[0-9]*_LineOut.*" port-list) connections (partition 2 (concat (interleave sc-outs system-outs) (interleave sc-outs interface-outs) (interleave system-ins sc-ins) (interleave interface-ins sc-ins)))] (doseq [[src dest] connections] (sh "jack_connect" src dest) (log/info "jack_connect " src dest))))) (def SC-PATHS {:linux "scsynth" :windows "C:/Program Files/SuperCollider/scsynth.exe" :mac "/Applications/SuperCollider/scsynth" }) (def SC-ARGS {:linux [] :windows [] :mac ["-U" "/Applications/SuperCollider/plugins"] }) (defonce _jack_connector_ (if (= :linux (@config* :os)) (on :connected #(connect-jack-ports)))) (defonce scsynth-server* (ref nil)) (defn internal-booter [port] (reset! running?* true) (log/info "booting internal audio server listening on port: " port) (let [server (ScSynth.)] (.addScSynthStartedListener server (proxy [ScSynthStartedListener] [] (started [] (event :booted)))) (dosync (ref-set sc-world* server)) (.run server))) (defn boot-internal ([] (boot-internal (+ (rand-int 50000) 2000))) ([port] (log/info "boot-internal: " port) (if (not @running?*) (let [sc-thread (Thread. #(internal-booter port))] (.setDaemon sc-thread true) (log/debug "Booting SuperCollider internal server (scsynth)...") (.start sc-thread) (dosync (ref-set server-thread* sc-thread)) (on :booted connect) :booting)))) (defn- sc-log "Pull audio server log data from a pipe and store for later printing." [stream read-buf] (while (pos? (.available stream)) (let [n (min (count read-buf) (.available stream)) _ (.read stream read-buf 0 n) msg (String. read-buf 0 n)] (dosync (alter server-log* conj msg)) (log/info (String. read-buf 0 n))))) (defn- external-booter "Boot thread to start the external audio server process and hook up to STDOUT for log messages." [cmd] (reset! running?* true) (log/debug "booting external audio server...") (let [proc (.exec (Runtime/getRuntime) cmd) in-stream (BufferedInputStream. (.getInputStream proc)) err-stream (BufferedInputStream. (.getErrorStream proc)) read-buf (make-array Byte/TYPE 256)] (while @running?* (sc-log in-stream read-buf) (sc-log err-stream read-buf) (Thread/sleep 250)) (.destroy proc))) (defn boot-external "Boot the audio server in an external process and tell it to listen on a specific port." ([port] (if (not @running?*) (let [cmd (into-array String (concat [(SC-PATHS (@config* :os)) "-u" (str port)] (SC-ARGS (@config* :os)))) sc-thread (Thread. #(external-booter cmd))] (.setDaemon sc-thread true) (log/debug "Booting SuperCollider server (scsynth)...") (.start sc-thread) (dosync (ref-set server-thread* sc-thread)) (connect "127.0.0.1" port) :booting)))) (defn boot "Boot either the internal or external audio server." ([] (boot (get @config* :server :internal) SERVER-HOST SERVER-PORT)) ([which & [host port]] (let [port (if (nil? port) (+ (rand-int 50000) 2000) port)] (cond (= :internal which) (boot-internal port) (= :external which) (boot-external host port))))) (defn quit "Quit the SuperCollider synth process." [] (log/info "quiting supercollider") (sync-event :quit) (when (connected?) (snd "/quit") (log/debug "SERVER: " @server*) (osc-close @server* true)) (reset! running?* false) (dosync (ref-set server* nil) (ref-set status* :no-audio))) ; TODO: Come up with a better way to delay shutdown until all of the :quit event handlers ; have executed. For now we just use 500ms. (defonce _shutdown-hook (.addShutdownHook (Runtime/getRuntime) (Thread. #(do (quit) (Thread/sleep 500))))) ; Synths, Busses, Controls and Groups are all Nodes. Groups are linked lists ; and group zero is the root of the graph. Nodes can be added to a group in ; one of these 5 positions relative to either the full list, or a specified node. (def POSITION {:head 0 :tail 1 :before-node 2 :after-node 3 :replace-node 4}) ;; Sending a synth-id of -1 lets the server choose an ID (defn node "Instantiate a synth node on the audio server. Takes the synth name and a set of argument name/value pairs. Optionally use :target <node/group-id> and :position <pos> to specify where the node should be located. The position can be one of :head, :tail :before-node, :after-node, or :replace-node. (node \"foo\") (node \"foo\" :pitch 60) (node \"foo\" :pitch 60 :target 0) (node \"foo\" :pitch 60 :target 2 :position :tail) " [synth-name & args] (if (not (connected?)) (throw (Exception. "Not connected to synthesis engine. Please boot or connect."))) (let [id (alloc-id :node) argmap (apply hash-map args) position ((get argmap :position :tail) POSITION) target (get argmap :target 0) args (flatten (seq (-> argmap (dissoc :position) (dissoc :target)))) args (stringify (floatify args))] ;(println "node " synth-name id position target args) (apply snd "/s_new" synth-name id position target args) id)) (defn node-free "Remove a synth node" [& node-ids] {:pre [(connected?)]} (apply snd "/n_free" node-ids) (doseq [id node-ids] (free-id :node id))) (defn node-run "Start a stopped synth node." [node-id] {:pre [(connected?)]} (snd "/n_run" node-id 1)) (defn node-stop "Stop a running synth node." {:pre [(connected?)]} [node-id] (snd "/n_run" node-id 0)) (defn node-place "Place a node :before or :after another node." [node-id position target-id] {:pre [(connected?)]} (cond (= :before position) (snd "/n_before" node-id target-id) (= :after position) (snd "/n_after" node-id target-id))) (defn node-control "Set control values for a node." [node-id & name-values] {:pre [(connected?)]} (apply snd "/n_set" node-id (stringify name-values)) node-id) ; This can be extended to support setting multiple ranges at once if necessary... (defn node-control-range "Set a range of controls all at once, or if node-id is a group control all nodes in the group." [node-id ctl-start & ctl-vals] {:pre [(connected?)]} (apply snd "/n_setn" node-id ctl-start (count ctl-vals) ctl-vals)) (defn node-map-controls "Connect a node's controls to a control bus." [node-id & names-busses] {:pre [(connected?)]} (apply snd "/n_map" node-id names-busses)) (defn group "Create a new group as a child of the target group." [position target-id] {:pre [(connected?)]} (let [id (alloc-id :node)] (snd "/g_new" id (get POSITION position) target-id) id)) (defn group-free "Free the specified group." [& group-ids] {:pre [(connected?)]} (apply node-free group-ids) ) (defn post-tree "Posts a representation of this group's node subtree, i.e. all the groups and synths contained within it, optionally including the current control values for synths." [id & [with-args?]] {:pre [(connected?)]} (snd "/g_dumpTree" id with-args?)) ;/g_queryTree get a representation of this group's node subtree. ; [ ; int - group ID ; int - flag: if not 0 the current control (arg) values for synths will be included ; ] * N ; ; Request a representation of this group's node subtree, i.e. all the groups and ; synths contained within it. Replies to the sender with a /g_queryTree.reply ; message listing all of the nodes contained within the group in the following ; format: ; ; int - flag: if synth control values are included 1, else 0 ; int - node ID of the requested group ; int - number of child nodes contained within the requested group ; then for each node in the subtree: ; [ ; int - node ID ; int - number of child nodes contained within this node. If -1this is a synth, if >=0 it's a group ; then, if this node is a synth: ; symbol - the SynthDef name for this node. ; then, if flag (see above) is true: ; int - numControls for this synth (M) ; [ ; symbol or int: control name or index ; float or symbol: value or control bus mapping symbol (e.g. 'c1') ; ] * M ; ] * the number of nodes in the subtree (def *data* nil) (defn- parse-synth-tree [id ctls?] (let [sname (first *data*)] (if ctls? (let [n-ctls (second *data*) [ctl-data new-data] (split-at (* 2 n-ctls) (nnext *data*)) ctls (apply hash-map ctl-data)] (set! *data* new-data) {:synth sname :id id :controls ctls}) (do (set! *data* (next *data*)) {:synth sname :id id})))) (defn- parse-node-tree-helper [ctls?] (let [[id n-children & new-data] *data*] (set! *data* new-data) (cond (neg? n-children) (parse-synth-tree id ctls?) ; synth (= 0 n-children) {:group id :children nil} (pos? n-children) {:group id :children (doall (map (fn [i] (parse-node-tree-helper ctls?)) (range n-children)))}))) (defn- parse-node-tree [data] (let [ctls? (= 1 (first data))] (binding [*data* (next data)] (parse-node-tree-helper ctls?)))) ; N.B. The order of nodes corresponds to their execution order on the server. ; Thus child nodes (those contained within a group) are listed immediately ; following their parent. See the method Server:queryAllNodes for an example of ; how to process this reply. (defn node-tree "Returns a data structure representing the current arrangement of groups and synthesizer instances residing on the audio server." ([] (node-tree 0)) ([id & [ctls?]] (let [ctls? (if (or (= 1 ctls?) (= true ctls?)) 1 0)] (snd "/g_queryTree" id ctls?) (let [tree (:args (recv "/g_queryTree.reply" REPLY-TIMEOUT))] (with-meta (parse-node-tree tree) {:type ::node-tree}))))) (defn prepend-node "Add a synth node to the end of a group list." [g n] (snd "/g_head" g n)) (defn append-node "Add a synth node to the end of a group list." [g n] (snd "/g_tail" g n)) (defn group-clear "Free all child synth nodes in a group." [group-id] (snd "/g_freeAll" group-id)) (defn clear-msg-queue "Remove any scheduled OSC messages from the run queue." [] (snd "/clearSched")) (defn sync-all "Wait until all asynchronous server operations have been completed." [] (recv "/synced")) ; The /done message just has a single argument: ; "/done" "s" <completed-command> ; ; where the command would be /b_alloc and others. (defn on-done "Runs a one shot handler that takes no arguments when an OSC /done message from scsynth arrives with a matching path. Look at load-sample for an example of usage. " [path handler] (on "/done" #(if (= path (first (:args %))) (do (handler) :done)))) ; TODO: Look into multi-channel buffers. Probably requires adding multi-id allocation ; support to the bit allocator too... ; size is in samples (defn buffer "Allocate a new buffer for storing audio data." [size & [channels]] (let [channels (or channels 1) id (alloc-id :audio-buffer) ready? (atom false)] (on-done "/b_alloc" #(reset! ready? true)) (snd "/b_alloc" id size channels) (with-meta {:id id :size size :ready? ready?} {:type ::buffer}))) (defn ready? "Check whether a sample or a buffer has completed allocating and/or loading data." [buf] @(:ready? buf)) (defn buffer? [buf] (isa? (type buf) ::buffer)) (defn- buf-or-id [b] (cond (buffer? b) (:id b) (number? b) b :default (throw (Exception. "Not a valid buffer: " b)))) (defn buffer-free "Free an audio buffer and the memory it was consuming." [buf] (snd "/b_free" (:id buf)) (free-id :audio-buffer (:id buf)) :done) ; TODO: Test me... (defn buffer-read "Read a section of an audio buffer." [buf start len] (assert (buffer? buf)) (loop [reqd 0] (when (< reqd len) (let [to-req (min MAX-OSC-SAMPLES (- len reqd))] (snd "/b_getn" (:id buf) (+ start reqd) to-req) (recur (+ reqd to-req))))) (let [samples (float-array len)] (loop [recvd 0] (if (= recvd len) samples (let [msg (recv "/b_setn" REPLY-TIMEOUT) ;_ (println "b_setn msg: " (take 3 (:args msg))) [buf-id bstart blen & samps] (:args msg)] (loop [idx bstart samps samps] (when samps (aset-float samples idx (first samps)) (recur (inc idx) (next samps)))) (recur (+ recvd blen))))))) ;; TODO: test me... (defn buffer-write "Write into a section of an audio buffer." [buf start len data] (assert (buffer? buf)) (snd "/b_setn" (:id buf) start len data)) (defn save-buffer "Save the float audio data in an audio buffer to a wav file." [buf path & args] (assert (buffer? buf)) (let [arg-map (merge (apply hash-map args) {:header "wav" :samples "float" :n-frames -1 :start-frame 0 :leave-open 0}) {:keys [header samples n-frames start-frame leave-open]} arg-map] (snd "/b_write" (:id buf) path header samples n-frames start-frame leave-open) :done)) (defmulti buffer-id type) (defmethod buffer-id java.lang.Integer [id] id) (defmethod buffer-id ::buffer [buf] (:id buf)) (defn buffer-data "Get the floating point data for a buffer on the internal server." [buf] (let [buf-id (buffer-id buf) snd-buf (.getSndBufAsFloatArray @sc-world* buf-id)] snd-buf)) (defn buffer-info [buf] (snd "/b_query" (buffer-id buf)) (let [msg (recv "/b_info" REPLY-TIMEOUT) [buf-id n-frames n-channels rate] (:args msg)] {:n-frames n-frames :n-channels n-channels :rate rate})) (defn sample-info [s] (buffer-info (:buf s))) (defonce loaded-synthdefs* (ref {})) (defn load-synthdef "Load a Clojure synth definition onto the audio server." [sdef] (assert (synthdef? sdef)) (dosync (alter loaded-synthdefs* assoc (:name sdef) sdef)) (if (connected?) (snd "/d_recv" (synthdef-bytes sdef)))) (defn- load-all-synthdefs [] (doseq [[sname sdef] @loaded-synthdefs*] (println "loading synthdef: " sname) (snd "/d_recv" (synthdef-bytes sdef)))) (defonce _synthdef-handler_ (on :connected load-all-synthdefs)) (defn load-synth-file "Load a synth definition file onto the audio server." [path] (snd "/d_recv" (synthdef-bytes (synthdef-read path)))) ; TODO: need to clear all the buffers and busses ; * Think about a sane policy for setting up state, especially when we are connected ; with many peers on one or more servers... (defn reset "Clear all synthesizers, groups and pending messages from the audio server and then recreates the active synth groups." [] (clear-msg-queue) (group-clear SYNTH-GROUP) ; clear the synth group (sync-event :reset)) (defonce _connect-handler_ (on :connected #(group :tail ROOT-GROUP))) (defn restart "Reset everything and restart the SuperCollider process." [] (reset) (quit) (boot)) (defmulti hit-at (fn [& args] (type (second args)))) (defmethod hit-at String [time-ms synth & args] (at time-ms (apply node synth args))) (defmethod hit-at clojure.lang.Keyword [time-ms synth & args] (at time-ms (apply node (name synth) args))) (defmethod hit-at ::sample [time-ms synth & args] (apply hit-at time-ms "granular" :buf (get-in synth [:buf :id]) args)) (defmethod hit-at :default [& args] (throw (Exception. (str "Hit doesn't know how to play the given synth type: " args)))) ; Turn hit into a multimethod ; Convert samples to be a map object instead of an ID (defn hit "Fire off a synth or sample at a specified time. These are the same: (hit :kick) (hit \"kick\") (hit (now) \"kick\") Or you can get fancier like this: (hit (now) :sin :pitch 60) (doseq [i (range 10)] (hit (+ (now) (* i 250)) :sin :pitch 60 :dur 0.1)) " ([] (hit-at (now) "ping" :pitch (choose [60 65 72 77]))) ([& args] (apply hit-at (if (isa? (type (first args)) Number) args (cons (now) args))))) (defmacro check "Try out an anonymous synth definition. Useful for experimentation. If the root node is not an out ugen, then it will add one automatically." [body] `(do (load-synthdef (synth "audition-synth" {} ~body)) (let [note# (hit (now) "audition-synth")] (at (+ (now) 1000) (node-free note#))))) (defn ctl "Modify synth parameters, optionally at a specified time. (hit :sin :pitch 50) => 1000 (ctl 1000 :pitch 40) (ctl (+ (now) 2000) 1000 :pitch 60) " [& args] (let [[time-ms synth-id ctls] (if (odd? (count args)) [(now) (first args) (next args)] [(first args) (second args) (drop 2 args)])] ;(println time-ms synth-id ": " ctls) (at time-ms (apply node-control synth-id (stringify ctls))))) (defn kill "Free one or more synth nodes. Functions that create instance of synth definitions, such as hit, return a handle for the synth node that was created. (let [handle (hit :sin)] ; returns => synth-handle (kill (+ 1000 (now)) handle)) ; a single handle without a time kills immediately (kill handle) ; or a bunch of synth handles can be removed at once (kill (hit) (hit) (hit)) ; or a seq of synth handles can be removed at once (kill [(hit) (hit) (hit)]) " [& ids] (apply node-free (flatten ids)) :killed) (defn load-instruments [] (doseq [synth (filter #(synthdef? %1) (map #(var-get %1) (vals (ns-publics 'overtone.instrument))))] ;(println "loading synth: " (:name synth)) (load-synthdef synth))) ;(defn update ; "Update a voice or standalone synth with new settings." ; [voice & args] ; (let [[names vals] (synth-args (apply hash-map args)) ; synth (if (voice? voice) (:synth voice) voice)] ; (.set synth names vals))) ;(defmethod play-note :synth [voice note-num dur & args] ; (let [args (assoc (apply hash-map args) :note note-num) ; synth (trigger (:synth voice) args)] ; (schedule #(release synth) dur) ; synth)) (defn- name-synth-args [args names] (loop [args args names names named []] (if args (recur (next args) (next names) (concat named [(first names) (first args)])) named))) (defn synth-player "Returns a player function for a named synth. Used by (synth ...) internally, but can be used to generate a player for a pre-compiled synth. The function generated will accept two optional arguments that must come first, the :target and :position (see the node function docs). (foo) (foo :target 0 :position :tail) or if foo has two arguments: (foo 440 0.3) (foo :target 0 :position :tail 440 0.3) at the head of group 2: (foo :target 2 :position :head 440 0.3) These can also be abbreviated: (foo :tgt 2 :pos :head) " [sname arg-names] (fn [& args] (let [[args sgroup] (if (or (= :target (first args)) (= :tgt (first args))) [(drop 2 args) (second args)] [args ROOT-GROUP]) [args pos] (if (or (= :position (first args)) (= :pos (first args))) [(drop 2 args) (second args)] [args :tail]) controller (partial node-control sgroup) player (partial node sname :target sgroup :position pos) [tgt-fn args] (if (= :ctl (first args)) [controller (rest args)] [player args]) args (map #(if (buffer? %) (:id %) %) args) named-args (if (keyword? (first args)) args (name-synth-args args arg-names))] (apply tgt-fn named-args)))) (defonce _auto-boot_ (boot))
true
(ns ^{:doc "An interface to the SuperCollider synthesis server. This is at heart an OSC client library for the SuperCollider scsynth DSP engine." :author "PI:NAME:<NAME>END_PI"} overtone.core.sc (:import (java.net InetSocketAddress) (java.util.regex Pattern) (java.util.concurrent TimeUnit TimeoutException) (java.io BufferedInputStream) (supercollider ScSynth ScSynthStartedListener MessageReceivedListener) (java.util BitSet)) (:require [overtone.core.log :as log]) (:use (overtone.core event config setup util time-utils synthdef) [clojure.contrib.java-utils :only [file]] (clojure.contrib shell-out pprint) osc)) ; TODO: Make this work correctly ; NOTE: "localhost" doesn't work, at least on my laptopt (defonce SERVER-HOST "127.0.0.1") (defonce SERVER-PORT nil) ; nil means a random port ; Max number of milliseconds to wait for a reply from the server (defonce REPLY-TIMEOUT 500) (defonce server-thread* (ref nil)) (defonce server* (ref nil)) (defonce status* (ref :no-audio)) (defonce sc-world* (ref nil)) ; Server limits (defonce MAX-NODES 1024) (defonce MAX-BUFFERS 1024) (defonce MAX-SDEFS 1024) (defonce MAX-AUDIO-BUS 128) (defonce MAX-CONTROL-BUS 4096) (defonce MAX-OSC-SAMPLES 8192) ; We use bit sets to store the allocation state of resources on the audio server. ; These typically get allocated on usage by the client, and then freed either by ; client request or automatically by receiving notifications from the server. ; (e.g. When an envelope trigger fires to free a synth.) (defonce allocator-bits {:node (BitSet. MAX-NODES) :audio-buffer (BitSet. MAX-BUFFERS) :audio-bus (BitSet. MAX-NODES) :control-bus (BitSet. MAX-NODES)}) (defonce allocator-limits {:node MAX-NODES :sdefs MAX-SDEFS :audio-bus MAX-AUDIO-BUS :control-bus MAX-CONTROL-BUS}) (defn alloc-id "Allocate a new ID for the type corresponding to key." [k] (let [bits (get allocator-bits k) limit (get allocator-limits k)] (locking bits (let [id (.nextClearBit bits 0)] (if (= limit id) (throw (Exception. (str "No more " (name k) " ids available!"))) (do (.set bits id) id)))))) (defn free-id "Free the id of type key." [k id] (let [bits (get allocator-bits k) limit (get allocator-limits k)] (locking bits (.clear bits id)))) (defn all-ids "Get all of the currently allocated ids for key." [k] (let [bits (get allocator-bits k) limit (get allocator-limits k)] (locking bits (loop [ids [] idx 0] (let [id (.nextSetBit bits idx)] (if (and (> id -1) (< idx limit)) (recur (conj ids id) (inc id)) ids)))))) (defn clear-ids "Clear all ids allocated for key." [k] (println "clear-ids........................") (locking (get allocator-bits k) (doseq [id (all-ids k)] (free-id k id)))) (defonce ROOT-GROUP 0) (defonce SYNTH-GROUP 1) (defn connected? [] (= :connected @status*)) (declare boot) ; The base handler for receiving osc messages just forwards the message on ; as an event using the osc path as the event key. (on ::osc-msg-received (fn [{{path :path args :args} :msg}] (event path :path path :args args))) (defn snd "Sends an OSC message." [path & args] (if (connected?) (apply osc-send @server* path args) (log/debug "### trying to snd while disconnected! ###")) (log/debug "(snd " path args ")")) (defmacro at "All messages sent within the body will be sent in the same timestamped OSC bundle. This bundling is thread-local, so you don't have to worry about accidentally scheduling packets into a bundle started on another thread." [time-ms & body] `(in-osc-bundle @server* ~time-ms (do ~@body))) (defn debug "Control debug output from both the Overtone and the audio server." [& [on-off]] (if (or on-off (nil? on-off)) (do (log/level :debug) (osc-debug true) (snd "/dumpOSC" 1)) (do (log/level :error) (osc-debug false) (snd "/dumpOSC" 0)))) ; Notifications from Server ; These messages are sent as notification of some event to all clients who have registered via the /notify command . ; All of these have the same arguments: ; int - node ID ; int - the node's parent group ID ; int - previous node ID, -1 if no previous node. ; int - next node ID, -1 if no next node. ; int - 1 if the node is a group, 0 if it is a synth ; ; The following two arguments are only sent if the node is a group: ; int - the ID of the head node, -1 if there is no head node. ; int - the ID of the tail node, -1 if there is no tail node. ; ; /n_go - a node was created ; /n_end - a node was destroyed ; /n_on - a node was turned on ; /n_off - a node was turned off ; /n_move - a node was moved ; /n_info - in reply to /n_query ; ; Trigger Notifications ; ; This command is the mechanism that synths can use to trigger events in ; clients. The node ID is the node that is sending the trigger. The trigger ID ; and value are determined by inputs to the SendTrig unit generator which is ; the originator of this message. ; ; /tr a trigger message ; ; int - node ID ; int - trigger ID ; float - trigger value (defn notify "Turn on notification messages from the audio server. This lets us free synth IDs when they are automatically freed with envelope triggers. It also lets us receive custom messages from various trigger ugens." [notify?] (snd "/notify" (if (false? notify?) 0 1))) (defn- node-destroyed "Frees up a synth node to keep in sync with the server." [id] (log/debug (format "node-destroyed: %d" id)) (free-id :node id)) (defn- node-created "Called when a node is created on the synth." [id] (log/debug (format "node-created: %d" id))) ; Setup the feedback handlers with the audio server. (on "/n_end" #(node-destroyed (first (:args %)))) (on "/n_go" #(node-created (first (:args %)))) (def N-RETRIES 20) (declare reset) (defn- connect-internal [] (log/debug "Connecting to internal SuperCollider server") (let [send-fn (fn [peer-obj buffer] (.send @sc-world* buffer)) peer (assoc (osc-peer) :send-fn send-fn)] (.addMessageReceivedListener @sc-world* (proxy [MessageReceivedListener] [] (messageReceived [buf size] (event ::osc-msg-received :msg (osc-decode-packet buf))))) (dosync (ref-set server* peer)) (snd "/status") (dosync (ref-set status* :connected)) (notify true) ; turn on notifications now that we can communicate (reset) (event :connected))) (defn- connect-external [host port] (log/debug "Connecting to external SuperCollider server: " host ":" port) (let [sc-server (osc-client host port)] (osc-listen sc-server #(event ::osc-msg-received :msg %)) (dosync (ref-set server* sc-server) (ref-set status* :connecting)) ; Runs once when we receive the first status.reply message (on "status.reply" #(do (dosync (ref-set status* :connected)) (notify true) ; turn on notifications now that we can communicate (reset) (event :connected) :done)) ; Send /status in a loop until we get a reply (loop [cnt 0] (log/debug "connect loop...") (when (and (< cnt N-RETRIES) (= @status* :connecting)) (log/debug "sending status...") (snd "/status") (Thread/sleep 100) (recur (inc cnt)))))) ; TODO: setup an error-handler in the case that we can't connect to the server (defn connect "Connect to an external SC audio server on the specified host and port." [& [host port]] (if (and host port) (.run (Thread. #(connect-external host port))) (connect-internal)) ) (defonce running?* (atom false)) (def server-log* (ref [])) (defn server-log "Print the server log." [] (doseq [msg @server-log*] (print msg))) ;Replies to sender with the following message. ;status.reply ; int - 1. unused. ; int - number of unit generators. ; int - number of synths. ; int - number of groups. ; int - number of loaded synth definitions. ; float - average percent CPU usage for signal processing ; float - peak percent CPU usage for signal processing ; double - nominal sample rate ; double - actual sample rate (defn recv [path & [timeout]] (let [p (promise)] (on path #(do (deliver p %) :done)) (if timeout (try (.get (future @p) timeout TimeUnit/MILLISECONDS) (catch TimeoutException t :timeout)) @p))) (defn- parse-status [args] (let [[_ ugens synths groups loaded avg peak nominal actual] args] {:n-ugens ugens :n-synths synths :n-groups groups :n-loaded-synths loaded :avg-cpu avg :peak-cpu peak :nominal-sample-rate nominal :actual-sample-rate actual})) (def STATUS-TIMEOUT 500) (defn status "Check the status of the audio server." [] (if (= :connected @status*) (let [p (promise)] (on "/status.reply" #(do (deliver p (parse-status (:args %))) :done)) (snd "/status") (try (.get (future @p) STATUS-TIMEOUT TimeUnit/MILLISECONDS) (catch TimeoutException t :timeout))) @status*)) (defn wait-sync "Wait until the audio server has completed all asynchronous commands currently in execution." [& [timeout]] (let [sync-id (rand-int 999999) _ (snd "/sync" sync-id) reply (recv "/synced" (if timeout timeout REPLY-TIMEOUT)) reply-id (first (:args reply))] (= sync-id reply-id))) (defn connect-jack-ports "Connect the jack input and output ports as best we can. If jack ports are always different names with different drivers or hardware then we need to find a better strategy to auto-connect." ([] (connect-jack-ports 2)) ([n-channels] (let [port-list (sh "jack_lsp") sc-ins (re-seq #"SuperCollider.*:in_[0-9]*" port-list) sc-outs (re-seq #"SuperCollider.*:out_[0-9]*" port-list) system-ins (re-seq #"system:capture_[0-9]*" port-list) system-outs (re-seq #"system:playback_[0-9]*" port-list) interface-ins (re-seq #"system:AC[0-9]*_dev[0-9]*_.*In.*" port-list) interface-outs (re-seq #"system:AP[0-9]*_dev[0-9]*_LineOut.*" port-list) connections (partition 2 (concat (interleave sc-outs system-outs) (interleave sc-outs interface-outs) (interleave system-ins sc-ins) (interleave interface-ins sc-ins)))] (doseq [[src dest] connections] (sh "jack_connect" src dest) (log/info "jack_connect " src dest))))) (def SC-PATHS {:linux "scsynth" :windows "C:/Program Files/SuperCollider/scsynth.exe" :mac "/Applications/SuperCollider/scsynth" }) (def SC-ARGS {:linux [] :windows [] :mac ["-U" "/Applications/SuperCollider/plugins"] }) (defonce _jack_connector_ (if (= :linux (@config* :os)) (on :connected #(connect-jack-ports)))) (defonce scsynth-server* (ref nil)) (defn internal-booter [port] (reset! running?* true) (log/info "booting internal audio server listening on port: " port) (let [server (ScSynth.)] (.addScSynthStartedListener server (proxy [ScSynthStartedListener] [] (started [] (event :booted)))) (dosync (ref-set sc-world* server)) (.run server))) (defn boot-internal ([] (boot-internal (+ (rand-int 50000) 2000))) ([port] (log/info "boot-internal: " port) (if (not @running?*) (let [sc-thread (Thread. #(internal-booter port))] (.setDaemon sc-thread true) (log/debug "Booting SuperCollider internal server (scsynth)...") (.start sc-thread) (dosync (ref-set server-thread* sc-thread)) (on :booted connect) :booting)))) (defn- sc-log "Pull audio server log data from a pipe and store for later printing." [stream read-buf] (while (pos? (.available stream)) (let [n (min (count read-buf) (.available stream)) _ (.read stream read-buf 0 n) msg (String. read-buf 0 n)] (dosync (alter server-log* conj msg)) (log/info (String. read-buf 0 n))))) (defn- external-booter "Boot thread to start the external audio server process and hook up to STDOUT for log messages." [cmd] (reset! running?* true) (log/debug "booting external audio server...") (let [proc (.exec (Runtime/getRuntime) cmd) in-stream (BufferedInputStream. (.getInputStream proc)) err-stream (BufferedInputStream. (.getErrorStream proc)) read-buf (make-array Byte/TYPE 256)] (while @running?* (sc-log in-stream read-buf) (sc-log err-stream read-buf) (Thread/sleep 250)) (.destroy proc))) (defn boot-external "Boot the audio server in an external process and tell it to listen on a specific port." ([port] (if (not @running?*) (let [cmd (into-array String (concat [(SC-PATHS (@config* :os)) "-u" (str port)] (SC-ARGS (@config* :os)))) sc-thread (Thread. #(external-booter cmd))] (.setDaemon sc-thread true) (log/debug "Booting SuperCollider server (scsynth)...") (.start sc-thread) (dosync (ref-set server-thread* sc-thread)) (connect "127.0.0.1" port) :booting)))) (defn boot "Boot either the internal or external audio server." ([] (boot (get @config* :server :internal) SERVER-HOST SERVER-PORT)) ([which & [host port]] (let [port (if (nil? port) (+ (rand-int 50000) 2000) port)] (cond (= :internal which) (boot-internal port) (= :external which) (boot-external host port))))) (defn quit "Quit the SuperCollider synth process." [] (log/info "quiting supercollider") (sync-event :quit) (when (connected?) (snd "/quit") (log/debug "SERVER: " @server*) (osc-close @server* true)) (reset! running?* false) (dosync (ref-set server* nil) (ref-set status* :no-audio))) ; TODO: Come up with a better way to delay shutdown until all of the :quit event handlers ; have executed. For now we just use 500ms. (defonce _shutdown-hook (.addShutdownHook (Runtime/getRuntime) (Thread. #(do (quit) (Thread/sleep 500))))) ; Synths, Busses, Controls and Groups are all Nodes. Groups are linked lists ; and group zero is the root of the graph. Nodes can be added to a group in ; one of these 5 positions relative to either the full list, or a specified node. (def POSITION {:head 0 :tail 1 :before-node 2 :after-node 3 :replace-node 4}) ;; Sending a synth-id of -1 lets the server choose an ID (defn node "Instantiate a synth node on the audio server. Takes the synth name and a set of argument name/value pairs. Optionally use :target <node/group-id> and :position <pos> to specify where the node should be located. The position can be one of :head, :tail :before-node, :after-node, or :replace-node. (node \"foo\") (node \"foo\" :pitch 60) (node \"foo\" :pitch 60 :target 0) (node \"foo\" :pitch 60 :target 2 :position :tail) " [synth-name & args] (if (not (connected?)) (throw (Exception. "Not connected to synthesis engine. Please boot or connect."))) (let [id (alloc-id :node) argmap (apply hash-map args) position ((get argmap :position :tail) POSITION) target (get argmap :target 0) args (flatten (seq (-> argmap (dissoc :position) (dissoc :target)))) args (stringify (floatify args))] ;(println "node " synth-name id position target args) (apply snd "/s_new" synth-name id position target args) id)) (defn node-free "Remove a synth node" [& node-ids] {:pre [(connected?)]} (apply snd "/n_free" node-ids) (doseq [id node-ids] (free-id :node id))) (defn node-run "Start a stopped synth node." [node-id] {:pre [(connected?)]} (snd "/n_run" node-id 1)) (defn node-stop "Stop a running synth node." {:pre [(connected?)]} [node-id] (snd "/n_run" node-id 0)) (defn node-place "Place a node :before or :after another node." [node-id position target-id] {:pre [(connected?)]} (cond (= :before position) (snd "/n_before" node-id target-id) (= :after position) (snd "/n_after" node-id target-id))) (defn node-control "Set control values for a node." [node-id & name-values] {:pre [(connected?)]} (apply snd "/n_set" node-id (stringify name-values)) node-id) ; This can be extended to support setting multiple ranges at once if necessary... (defn node-control-range "Set a range of controls all at once, or if node-id is a group control all nodes in the group." [node-id ctl-start & ctl-vals] {:pre [(connected?)]} (apply snd "/n_setn" node-id ctl-start (count ctl-vals) ctl-vals)) (defn node-map-controls "Connect a node's controls to a control bus." [node-id & names-busses] {:pre [(connected?)]} (apply snd "/n_map" node-id names-busses)) (defn group "Create a new group as a child of the target group." [position target-id] {:pre [(connected?)]} (let [id (alloc-id :node)] (snd "/g_new" id (get POSITION position) target-id) id)) (defn group-free "Free the specified group." [& group-ids] {:pre [(connected?)]} (apply node-free group-ids) ) (defn post-tree "Posts a representation of this group's node subtree, i.e. all the groups and synths contained within it, optionally including the current control values for synths." [id & [with-args?]] {:pre [(connected?)]} (snd "/g_dumpTree" id with-args?)) ;/g_queryTree get a representation of this group's node subtree. ; [ ; int - group ID ; int - flag: if not 0 the current control (arg) values for synths will be included ; ] * N ; ; Request a representation of this group's node subtree, i.e. all the groups and ; synths contained within it. Replies to the sender with a /g_queryTree.reply ; message listing all of the nodes contained within the group in the following ; format: ; ; int - flag: if synth control values are included 1, else 0 ; int - node ID of the requested group ; int - number of child nodes contained within the requested group ; then for each node in the subtree: ; [ ; int - node ID ; int - number of child nodes contained within this node. If -1this is a synth, if >=0 it's a group ; then, if this node is a synth: ; symbol - the SynthDef name for this node. ; then, if flag (see above) is true: ; int - numControls for this synth (M) ; [ ; symbol or int: control name or index ; float or symbol: value or control bus mapping symbol (e.g. 'c1') ; ] * M ; ] * the number of nodes in the subtree (def *data* nil) (defn- parse-synth-tree [id ctls?] (let [sname (first *data*)] (if ctls? (let [n-ctls (second *data*) [ctl-data new-data] (split-at (* 2 n-ctls) (nnext *data*)) ctls (apply hash-map ctl-data)] (set! *data* new-data) {:synth sname :id id :controls ctls}) (do (set! *data* (next *data*)) {:synth sname :id id})))) (defn- parse-node-tree-helper [ctls?] (let [[id n-children & new-data] *data*] (set! *data* new-data) (cond (neg? n-children) (parse-synth-tree id ctls?) ; synth (= 0 n-children) {:group id :children nil} (pos? n-children) {:group id :children (doall (map (fn [i] (parse-node-tree-helper ctls?)) (range n-children)))}))) (defn- parse-node-tree [data] (let [ctls? (= 1 (first data))] (binding [*data* (next data)] (parse-node-tree-helper ctls?)))) ; N.B. The order of nodes corresponds to their execution order on the server. ; Thus child nodes (those contained within a group) are listed immediately ; following their parent. See the method Server:queryAllNodes for an example of ; how to process this reply. (defn node-tree "Returns a data structure representing the current arrangement of groups and synthesizer instances residing on the audio server." ([] (node-tree 0)) ([id & [ctls?]] (let [ctls? (if (or (= 1 ctls?) (= true ctls?)) 1 0)] (snd "/g_queryTree" id ctls?) (let [tree (:args (recv "/g_queryTree.reply" REPLY-TIMEOUT))] (with-meta (parse-node-tree tree) {:type ::node-tree}))))) (defn prepend-node "Add a synth node to the end of a group list." [g n] (snd "/g_head" g n)) (defn append-node "Add a synth node to the end of a group list." [g n] (snd "/g_tail" g n)) (defn group-clear "Free all child synth nodes in a group." [group-id] (snd "/g_freeAll" group-id)) (defn clear-msg-queue "Remove any scheduled OSC messages from the run queue." [] (snd "/clearSched")) (defn sync-all "Wait until all asynchronous server operations have been completed." [] (recv "/synced")) ; The /done message just has a single argument: ; "/done" "s" <completed-command> ; ; where the command would be /b_alloc and others. (defn on-done "Runs a one shot handler that takes no arguments when an OSC /done message from scsynth arrives with a matching path. Look at load-sample for an example of usage. " [path handler] (on "/done" #(if (= path (first (:args %))) (do (handler) :done)))) ; TODO: Look into multi-channel buffers. Probably requires adding multi-id allocation ; support to the bit allocator too... ; size is in samples (defn buffer "Allocate a new buffer for storing audio data." [size & [channels]] (let [channels (or channels 1) id (alloc-id :audio-buffer) ready? (atom false)] (on-done "/b_alloc" #(reset! ready? true)) (snd "/b_alloc" id size channels) (with-meta {:id id :size size :ready? ready?} {:type ::buffer}))) (defn ready? "Check whether a sample or a buffer has completed allocating and/or loading data." [buf] @(:ready? buf)) (defn buffer? [buf] (isa? (type buf) ::buffer)) (defn- buf-or-id [b] (cond (buffer? b) (:id b) (number? b) b :default (throw (Exception. "Not a valid buffer: " b)))) (defn buffer-free "Free an audio buffer and the memory it was consuming." [buf] (snd "/b_free" (:id buf)) (free-id :audio-buffer (:id buf)) :done) ; TODO: Test me... (defn buffer-read "Read a section of an audio buffer." [buf start len] (assert (buffer? buf)) (loop [reqd 0] (when (< reqd len) (let [to-req (min MAX-OSC-SAMPLES (- len reqd))] (snd "/b_getn" (:id buf) (+ start reqd) to-req) (recur (+ reqd to-req))))) (let [samples (float-array len)] (loop [recvd 0] (if (= recvd len) samples (let [msg (recv "/b_setn" REPLY-TIMEOUT) ;_ (println "b_setn msg: " (take 3 (:args msg))) [buf-id bstart blen & samps] (:args msg)] (loop [idx bstart samps samps] (when samps (aset-float samples idx (first samps)) (recur (inc idx) (next samps)))) (recur (+ recvd blen))))))) ;; TODO: test me... (defn buffer-write "Write into a section of an audio buffer." [buf start len data] (assert (buffer? buf)) (snd "/b_setn" (:id buf) start len data)) (defn save-buffer "Save the float audio data in an audio buffer to a wav file." [buf path & args] (assert (buffer? buf)) (let [arg-map (merge (apply hash-map args) {:header "wav" :samples "float" :n-frames -1 :start-frame 0 :leave-open 0}) {:keys [header samples n-frames start-frame leave-open]} arg-map] (snd "/b_write" (:id buf) path header samples n-frames start-frame leave-open) :done)) (defmulti buffer-id type) (defmethod buffer-id java.lang.Integer [id] id) (defmethod buffer-id ::buffer [buf] (:id buf)) (defn buffer-data "Get the floating point data for a buffer on the internal server." [buf] (let [buf-id (buffer-id buf) snd-buf (.getSndBufAsFloatArray @sc-world* buf-id)] snd-buf)) (defn buffer-info [buf] (snd "/b_query" (buffer-id buf)) (let [msg (recv "/b_info" REPLY-TIMEOUT) [buf-id n-frames n-channels rate] (:args msg)] {:n-frames n-frames :n-channels n-channels :rate rate})) (defn sample-info [s] (buffer-info (:buf s))) (defonce loaded-synthdefs* (ref {})) (defn load-synthdef "Load a Clojure synth definition onto the audio server." [sdef] (assert (synthdef? sdef)) (dosync (alter loaded-synthdefs* assoc (:name sdef) sdef)) (if (connected?) (snd "/d_recv" (synthdef-bytes sdef)))) (defn- load-all-synthdefs [] (doseq [[sname sdef] @loaded-synthdefs*] (println "loading synthdef: " sname) (snd "/d_recv" (synthdef-bytes sdef)))) (defonce _synthdef-handler_ (on :connected load-all-synthdefs)) (defn load-synth-file "Load a synth definition file onto the audio server." [path] (snd "/d_recv" (synthdef-bytes (synthdef-read path)))) ; TODO: need to clear all the buffers and busses ; * Think about a sane policy for setting up state, especially when we are connected ; with many peers on one or more servers... (defn reset "Clear all synthesizers, groups and pending messages from the audio server and then recreates the active synth groups." [] (clear-msg-queue) (group-clear SYNTH-GROUP) ; clear the synth group (sync-event :reset)) (defonce _connect-handler_ (on :connected #(group :tail ROOT-GROUP))) (defn restart "Reset everything and restart the SuperCollider process." [] (reset) (quit) (boot)) (defmulti hit-at (fn [& args] (type (second args)))) (defmethod hit-at String [time-ms synth & args] (at time-ms (apply node synth args))) (defmethod hit-at clojure.lang.Keyword [time-ms synth & args] (at time-ms (apply node (name synth) args))) (defmethod hit-at ::sample [time-ms synth & args] (apply hit-at time-ms "granular" :buf (get-in synth [:buf :id]) args)) (defmethod hit-at :default [& args] (throw (Exception. (str "Hit doesn't know how to play the given synth type: " args)))) ; Turn hit into a multimethod ; Convert samples to be a map object instead of an ID (defn hit "Fire off a synth or sample at a specified time. These are the same: (hit :kick) (hit \"kick\") (hit (now) \"kick\") Or you can get fancier like this: (hit (now) :sin :pitch 60) (doseq [i (range 10)] (hit (+ (now) (* i 250)) :sin :pitch 60 :dur 0.1)) " ([] (hit-at (now) "ping" :pitch (choose [60 65 72 77]))) ([& args] (apply hit-at (if (isa? (type (first args)) Number) args (cons (now) args))))) (defmacro check "Try out an anonymous synth definition. Useful for experimentation. If the root node is not an out ugen, then it will add one automatically." [body] `(do (load-synthdef (synth "audition-synth" {} ~body)) (let [note# (hit (now) "audition-synth")] (at (+ (now) 1000) (node-free note#))))) (defn ctl "Modify synth parameters, optionally at a specified time. (hit :sin :pitch 50) => 1000 (ctl 1000 :pitch 40) (ctl (+ (now) 2000) 1000 :pitch 60) " [& args] (let [[time-ms synth-id ctls] (if (odd? (count args)) [(now) (first args) (next args)] [(first args) (second args) (drop 2 args)])] ;(println time-ms synth-id ": " ctls) (at time-ms (apply node-control synth-id (stringify ctls))))) (defn kill "Free one or more synth nodes. Functions that create instance of synth definitions, such as hit, return a handle for the synth node that was created. (let [handle (hit :sin)] ; returns => synth-handle (kill (+ 1000 (now)) handle)) ; a single handle without a time kills immediately (kill handle) ; or a bunch of synth handles can be removed at once (kill (hit) (hit) (hit)) ; or a seq of synth handles can be removed at once (kill [(hit) (hit) (hit)]) " [& ids] (apply node-free (flatten ids)) :killed) (defn load-instruments [] (doseq [synth (filter #(synthdef? %1) (map #(var-get %1) (vals (ns-publics 'overtone.instrument))))] ;(println "loading synth: " (:name synth)) (load-synthdef synth))) ;(defn update ; "Update a voice or standalone synth with new settings." ; [voice & args] ; (let [[names vals] (synth-args (apply hash-map args)) ; synth (if (voice? voice) (:synth voice) voice)] ; (.set synth names vals))) ;(defmethod play-note :synth [voice note-num dur & args] ; (let [args (assoc (apply hash-map args) :note note-num) ; synth (trigger (:synth voice) args)] ; (schedule #(release synth) dur) ; synth)) (defn- name-synth-args [args names] (loop [args args names names named []] (if args (recur (next args) (next names) (concat named [(first names) (first args)])) named))) (defn synth-player "Returns a player function for a named synth. Used by (synth ...) internally, but can be used to generate a player for a pre-compiled synth. The function generated will accept two optional arguments that must come first, the :target and :position (see the node function docs). (foo) (foo :target 0 :position :tail) or if foo has two arguments: (foo 440 0.3) (foo :target 0 :position :tail 440 0.3) at the head of group 2: (foo :target 2 :position :head 440 0.3) These can also be abbreviated: (foo :tgt 2 :pos :head) " [sname arg-names] (fn [& args] (let [[args sgroup] (if (or (= :target (first args)) (= :tgt (first args))) [(drop 2 args) (second args)] [args ROOT-GROUP]) [args pos] (if (or (= :position (first args)) (= :pos (first args))) [(drop 2 args) (second args)] [args :tail]) controller (partial node-control sgroup) player (partial node sname :target sgroup :position pos) [tgt-fn args] (if (= :ctl (first args)) [controller (rest args)] [player args]) args (map #(if (buffer? %) (:id %) %) args) named-args (if (keyword? (first args)) args (name-synth-args args arg-names))] (apply tgt-fn named-args)))) (defonce _auto-boot_ (boot))
[ { "context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"John Alan McDonald\" :date \"2016-11-10\"\n :doc \"Artificial data f", "end": 105, "score": 0.999872088432312, "start": 87, "tag": "NAME", "value": "John Alan McDonald" } ]
src/test/clojure/zana/test/functions/record.clj
wahpenayo/zana
2
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "John Alan McDonald" :date "2016-11-10" :doc "Artificial data for unit tests." } zana.test.functions.record (:require [clojure.string :as s] [clojure.test :as test] [clojure.repl :as repl] [zana.api :as z] [zana.test.functions.kolor :as kolor] [zana.test.functions.primate :as primate]) (:import [zana.test.java Kolor])) ;; mvn -Dtest=zana.test.functions.record clojure:test ;;------------------------------------------------------------------------------ (z/define-datum Record [^double x0 ^double x1 ^double x2 ^double x3 ^double x4 ^double x5 ^zana.test.java.Kolor kolor ^clojure.lang.Keyword primate ^double true-probability ^double true-class ^double predicted-probability ^double predicted-class]) ;;------------------------------------------------------------------------------ (def attributes {:x0 x0 :x1 x1 :x2 x2 :x3 x3 :x4 x4 :x5 x5 :kolor kolor :primate primate :ground-truth true-class :prediction predicted-class}) ;;------------------------------------------------------------------------------ (defn make-diagonal-step-function [^double bias] (assert (<= 0.0 bias 1.0)) (let [l0 0.0 w0 1.0 l1 0.0 w1 1.0] (fn step ^double [^Record datum] (let [u0 (/ (- (x0 datum) l0) w0) u1 (/ (- (x1 datum) l1) w1) diagonal? (or (and (<= u0 0.5) (<= u1 0.5)) (and (>= u0 0.5) (>= u1 0.5)))] (* bias (if (kolor/primary? (kolor datum)) (if diagonal? 1.0 0.0) (if diagonal? 0.0 1.0))))))) ;;------------------------------------------------------------------------------ (defn make-pyramid-function [^double bias] (assert (<= 0.0 bias 1.0)) (let [l0 0.0 w0 1.0 l1 0.0 w1 1.0] (fn pyramid ^double [^Record datum] (let [u0 (/ (- (x0 datum) l0) w0) _(assert (<= 0.0 u0 1.0)) u1 (/ (- (x1 datum) l1) w1) _(assert (<= 0.0 u1 1.0)) u (* 0.5 (+ (Math/min u0 (- 1.0 u0)) (Math/min u1 (- 1.0 u1)))) _(assert (<= 0.0 u 1.0)) p (* bias (if (kolor/primary? (kolor datum)) u (- 1.0 u)))] (assert (<= 0.0 p 1.0)) p)))) ;;------------------------------------------------------------------------------ (defn make-spikes-function [^double bias] (assert (<= 0.0 bias 1.0)) (fn spikes ^double [^Record datum] (let [u0 (x0 datum) _ (assert (<= 0.0 u0 1.0)) u1 (x1 datum) _ (assert (<= 0.0 u1 1.0)) k (kolor datum) [^double mu0 ^double mu1] (cond (= k Kolor/RED) [0.25 0.26] (= k Kolor/GREEN) [0.51 0.27] (= k Kolor/BLUE) [0.78 0.28] (= k Kolor/CYAN) [0.29 0.79] (= k Kolor/MAGENTA) [0.52 0.74] (= k Kolor/YELLOW) [0.68 0.73]) v0 (- mu0 u0) v1 (- mu1 u1) r (Math/sqrt (+ (* v0 v0) (* v1 v1))) a 0.3 a-r (Math/max 0.0 (- a r)) p (* bias (/ (* a-r a-r) (* a a)))] (assert (<= 0.0 p 1.0)) p))) ;;------------------------------------------------------------------------------ (defn make-cone-function [^double bias] (assert (<= 0.0 bias 1.0)) (let [l0 0.0 w0 1.0 l1 0.0 w1 1.0] (fn cone ^double [^Record datum] (let [u0 (/ (- (x0 datum) l0) w0) u0 (- (* 2.0 u0) 1.0) u1 (/ (- (x1 datum) l1) w1) u1 (- (* 2.0 u1) 1.0) u (- 1.0 (* 0.5 (+ (* u0 u0) (* u1 u1))))] (if (kolor/primary? (kolor datum)) u (- 1.0 u)))))) ;;------------------------------------------------------------------------------ ;; TODO: queue? (def ^:private seed0 "7CFA49EF4DF2F09D5F58B2F9198D4211") (def ^:private seed1 "38268047490594E3278EEA0E5182D7A2") (def ^:private seed2 "7DFBA14AB78F049E5DAA711428C8CBEF") (def ^:private seed3 "0B4773B2C811374096880EA2B045E6EF") (def ^:private seed4 "087E31A05DDF780B29574B4E83D92615") (def ^:private seed5 "0751BC45236182BDE2C6E92A513CF383") (def ^:private seed6 "28EE35787E1481D72D901EF53516B3A6") (def ^:private seed7 "2D3DF75EC1459A4B26C0B29449D959CC") (def ^:private seed8 "BD504A2D507F96F63889FFA3A1EBBAC6") ;;------------------------------------------------------------------------------ (defn generator [^clojure.lang.IFn$OD prob] (let [^clojure.lang.IFn$D generate-x0 (z/continuous-uniform-generator seed0) ^clojure.lang.IFn$D generate-x1 (z/continuous-uniform-generator seed1) ;;^clojure.lang.IFn$D generate-x2 (z/continuous-uniform-generator seed2) ;;^clojure.lang.IFn$D generate-x3 (z/continuous-uniform-generator seed3) ;;^clojure.lang.IFn$D generate-x4 (z/continuous-uniform-generator seed4) ;;^clojure.lang.IFn$D generate-x5 (z/continuous-uniform-generator seed5) generate-kolor (kolor/generator seed6) generate-primate (primate/generator seed7) generate-01 (z/bernoulli-generator seed8)] (fn random-record ^Record [_] (let [x0 (.invokePrim generate-x0) x1 (.invokePrim generate-x1) x2 (Math/min x0 x1) ;;(.invokePrim generate-x2) x3 (Math/max x0 x1) ;;(.invokePrim generate-x4) x4 (+ x0 x1) ;;(.invokePrim generate-x4) x5 (- x0 x1) ;;(.invokePrim generate-x5) kolor (generate-kolor) primate (generate-primate) datum (Record. x0 x1 x2 x3 x4 x5 kolor primate Double/NaN Double/NaN Double/NaN Double/NaN) p (prob datum) _(assert (<= 0.0 p 1.0)) c (generate-01 p)] (assoc datum :true-class c :true-probability p))))) ;;------------------------------------------------------------------------------ (defn enum-valued? [f] (println) (println f) (let [[ns n] (s/split (pr-str (class f)) #"\$") s (symbol ns n) r (resolve s) m (meta r) a (first (:arglists m)) tag (:tag (meta a)) codomain (resolve tag) tf (and (instance? Class codomain) (.isEnum ^Class codomain)) ] (prn ns n) (prn (class s) s) (prn (class r) r) (prn a) (prn (class codomain) codomain) (prn tf) tf)) ;;------------------------------------------------------------------------------ (test/deftest enum-codomain (enum-valued? x0) (enum-valued? kolor) (enum-valued? primate) )
9128
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "<NAME>" :date "2016-11-10" :doc "Artificial data for unit tests." } zana.test.functions.record (:require [clojure.string :as s] [clojure.test :as test] [clojure.repl :as repl] [zana.api :as z] [zana.test.functions.kolor :as kolor] [zana.test.functions.primate :as primate]) (:import [zana.test.java Kolor])) ;; mvn -Dtest=zana.test.functions.record clojure:test ;;------------------------------------------------------------------------------ (z/define-datum Record [^double x0 ^double x1 ^double x2 ^double x3 ^double x4 ^double x5 ^zana.test.java.Kolor kolor ^clojure.lang.Keyword primate ^double true-probability ^double true-class ^double predicted-probability ^double predicted-class]) ;;------------------------------------------------------------------------------ (def attributes {:x0 x0 :x1 x1 :x2 x2 :x3 x3 :x4 x4 :x5 x5 :kolor kolor :primate primate :ground-truth true-class :prediction predicted-class}) ;;------------------------------------------------------------------------------ (defn make-diagonal-step-function [^double bias] (assert (<= 0.0 bias 1.0)) (let [l0 0.0 w0 1.0 l1 0.0 w1 1.0] (fn step ^double [^Record datum] (let [u0 (/ (- (x0 datum) l0) w0) u1 (/ (- (x1 datum) l1) w1) diagonal? (or (and (<= u0 0.5) (<= u1 0.5)) (and (>= u0 0.5) (>= u1 0.5)))] (* bias (if (kolor/primary? (kolor datum)) (if diagonal? 1.0 0.0) (if diagonal? 0.0 1.0))))))) ;;------------------------------------------------------------------------------ (defn make-pyramid-function [^double bias] (assert (<= 0.0 bias 1.0)) (let [l0 0.0 w0 1.0 l1 0.0 w1 1.0] (fn pyramid ^double [^Record datum] (let [u0 (/ (- (x0 datum) l0) w0) _(assert (<= 0.0 u0 1.0)) u1 (/ (- (x1 datum) l1) w1) _(assert (<= 0.0 u1 1.0)) u (* 0.5 (+ (Math/min u0 (- 1.0 u0)) (Math/min u1 (- 1.0 u1)))) _(assert (<= 0.0 u 1.0)) p (* bias (if (kolor/primary? (kolor datum)) u (- 1.0 u)))] (assert (<= 0.0 p 1.0)) p)))) ;;------------------------------------------------------------------------------ (defn make-spikes-function [^double bias] (assert (<= 0.0 bias 1.0)) (fn spikes ^double [^Record datum] (let [u0 (x0 datum) _ (assert (<= 0.0 u0 1.0)) u1 (x1 datum) _ (assert (<= 0.0 u1 1.0)) k (kolor datum) [^double mu0 ^double mu1] (cond (= k Kolor/RED) [0.25 0.26] (= k Kolor/GREEN) [0.51 0.27] (= k Kolor/BLUE) [0.78 0.28] (= k Kolor/CYAN) [0.29 0.79] (= k Kolor/MAGENTA) [0.52 0.74] (= k Kolor/YELLOW) [0.68 0.73]) v0 (- mu0 u0) v1 (- mu1 u1) r (Math/sqrt (+ (* v0 v0) (* v1 v1))) a 0.3 a-r (Math/max 0.0 (- a r)) p (* bias (/ (* a-r a-r) (* a a)))] (assert (<= 0.0 p 1.0)) p))) ;;------------------------------------------------------------------------------ (defn make-cone-function [^double bias] (assert (<= 0.0 bias 1.0)) (let [l0 0.0 w0 1.0 l1 0.0 w1 1.0] (fn cone ^double [^Record datum] (let [u0 (/ (- (x0 datum) l0) w0) u0 (- (* 2.0 u0) 1.0) u1 (/ (- (x1 datum) l1) w1) u1 (- (* 2.0 u1) 1.0) u (- 1.0 (* 0.5 (+ (* u0 u0) (* u1 u1))))] (if (kolor/primary? (kolor datum)) u (- 1.0 u)))))) ;;------------------------------------------------------------------------------ ;; TODO: queue? (def ^:private seed0 "7CFA49EF4DF2F09D5F58B2F9198D4211") (def ^:private seed1 "38268047490594E3278EEA0E5182D7A2") (def ^:private seed2 "7DFBA14AB78F049E5DAA711428C8CBEF") (def ^:private seed3 "0B4773B2C811374096880EA2B045E6EF") (def ^:private seed4 "087E31A05DDF780B29574B4E83D92615") (def ^:private seed5 "0751BC45236182BDE2C6E92A513CF383") (def ^:private seed6 "28EE35787E1481D72D901EF53516B3A6") (def ^:private seed7 "2D3DF75EC1459A4B26C0B29449D959CC") (def ^:private seed8 "BD504A2D507F96F63889FFA3A1EBBAC6") ;;------------------------------------------------------------------------------ (defn generator [^clojure.lang.IFn$OD prob] (let [^clojure.lang.IFn$D generate-x0 (z/continuous-uniform-generator seed0) ^clojure.lang.IFn$D generate-x1 (z/continuous-uniform-generator seed1) ;;^clojure.lang.IFn$D generate-x2 (z/continuous-uniform-generator seed2) ;;^clojure.lang.IFn$D generate-x3 (z/continuous-uniform-generator seed3) ;;^clojure.lang.IFn$D generate-x4 (z/continuous-uniform-generator seed4) ;;^clojure.lang.IFn$D generate-x5 (z/continuous-uniform-generator seed5) generate-kolor (kolor/generator seed6) generate-primate (primate/generator seed7) generate-01 (z/bernoulli-generator seed8)] (fn random-record ^Record [_] (let [x0 (.invokePrim generate-x0) x1 (.invokePrim generate-x1) x2 (Math/min x0 x1) ;;(.invokePrim generate-x2) x3 (Math/max x0 x1) ;;(.invokePrim generate-x4) x4 (+ x0 x1) ;;(.invokePrim generate-x4) x5 (- x0 x1) ;;(.invokePrim generate-x5) kolor (generate-kolor) primate (generate-primate) datum (Record. x0 x1 x2 x3 x4 x5 kolor primate Double/NaN Double/NaN Double/NaN Double/NaN) p (prob datum) _(assert (<= 0.0 p 1.0)) c (generate-01 p)] (assoc datum :true-class c :true-probability p))))) ;;------------------------------------------------------------------------------ (defn enum-valued? [f] (println) (println f) (let [[ns n] (s/split (pr-str (class f)) #"\$") s (symbol ns n) r (resolve s) m (meta r) a (first (:arglists m)) tag (:tag (meta a)) codomain (resolve tag) tf (and (instance? Class codomain) (.isEnum ^Class codomain)) ] (prn ns n) (prn (class s) s) (prn (class r) r) (prn a) (prn (class codomain) codomain) (prn tf) tf)) ;;------------------------------------------------------------------------------ (test/deftest enum-codomain (enum-valued? x0) (enum-valued? kolor) (enum-valued? primate) )
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "PI:NAME:<NAME>END_PI" :date "2016-11-10" :doc "Artificial data for unit tests." } zana.test.functions.record (:require [clojure.string :as s] [clojure.test :as test] [clojure.repl :as repl] [zana.api :as z] [zana.test.functions.kolor :as kolor] [zana.test.functions.primate :as primate]) (:import [zana.test.java Kolor])) ;; mvn -Dtest=zana.test.functions.record clojure:test ;;------------------------------------------------------------------------------ (z/define-datum Record [^double x0 ^double x1 ^double x2 ^double x3 ^double x4 ^double x5 ^zana.test.java.Kolor kolor ^clojure.lang.Keyword primate ^double true-probability ^double true-class ^double predicted-probability ^double predicted-class]) ;;------------------------------------------------------------------------------ (def attributes {:x0 x0 :x1 x1 :x2 x2 :x3 x3 :x4 x4 :x5 x5 :kolor kolor :primate primate :ground-truth true-class :prediction predicted-class}) ;;------------------------------------------------------------------------------ (defn make-diagonal-step-function [^double bias] (assert (<= 0.0 bias 1.0)) (let [l0 0.0 w0 1.0 l1 0.0 w1 1.0] (fn step ^double [^Record datum] (let [u0 (/ (- (x0 datum) l0) w0) u1 (/ (- (x1 datum) l1) w1) diagonal? (or (and (<= u0 0.5) (<= u1 0.5)) (and (>= u0 0.5) (>= u1 0.5)))] (* bias (if (kolor/primary? (kolor datum)) (if diagonal? 1.0 0.0) (if diagonal? 0.0 1.0))))))) ;;------------------------------------------------------------------------------ (defn make-pyramid-function [^double bias] (assert (<= 0.0 bias 1.0)) (let [l0 0.0 w0 1.0 l1 0.0 w1 1.0] (fn pyramid ^double [^Record datum] (let [u0 (/ (- (x0 datum) l0) w0) _(assert (<= 0.0 u0 1.0)) u1 (/ (- (x1 datum) l1) w1) _(assert (<= 0.0 u1 1.0)) u (* 0.5 (+ (Math/min u0 (- 1.0 u0)) (Math/min u1 (- 1.0 u1)))) _(assert (<= 0.0 u 1.0)) p (* bias (if (kolor/primary? (kolor datum)) u (- 1.0 u)))] (assert (<= 0.0 p 1.0)) p)))) ;;------------------------------------------------------------------------------ (defn make-spikes-function [^double bias] (assert (<= 0.0 bias 1.0)) (fn spikes ^double [^Record datum] (let [u0 (x0 datum) _ (assert (<= 0.0 u0 1.0)) u1 (x1 datum) _ (assert (<= 0.0 u1 1.0)) k (kolor datum) [^double mu0 ^double mu1] (cond (= k Kolor/RED) [0.25 0.26] (= k Kolor/GREEN) [0.51 0.27] (= k Kolor/BLUE) [0.78 0.28] (= k Kolor/CYAN) [0.29 0.79] (= k Kolor/MAGENTA) [0.52 0.74] (= k Kolor/YELLOW) [0.68 0.73]) v0 (- mu0 u0) v1 (- mu1 u1) r (Math/sqrt (+ (* v0 v0) (* v1 v1))) a 0.3 a-r (Math/max 0.0 (- a r)) p (* bias (/ (* a-r a-r) (* a a)))] (assert (<= 0.0 p 1.0)) p))) ;;------------------------------------------------------------------------------ (defn make-cone-function [^double bias] (assert (<= 0.0 bias 1.0)) (let [l0 0.0 w0 1.0 l1 0.0 w1 1.0] (fn cone ^double [^Record datum] (let [u0 (/ (- (x0 datum) l0) w0) u0 (- (* 2.0 u0) 1.0) u1 (/ (- (x1 datum) l1) w1) u1 (- (* 2.0 u1) 1.0) u (- 1.0 (* 0.5 (+ (* u0 u0) (* u1 u1))))] (if (kolor/primary? (kolor datum)) u (- 1.0 u)))))) ;;------------------------------------------------------------------------------ ;; TODO: queue? (def ^:private seed0 "7CFA49EF4DF2F09D5F58B2F9198D4211") (def ^:private seed1 "38268047490594E3278EEA0E5182D7A2") (def ^:private seed2 "7DFBA14AB78F049E5DAA711428C8CBEF") (def ^:private seed3 "0B4773B2C811374096880EA2B045E6EF") (def ^:private seed4 "087E31A05DDF780B29574B4E83D92615") (def ^:private seed5 "0751BC45236182BDE2C6E92A513CF383") (def ^:private seed6 "28EE35787E1481D72D901EF53516B3A6") (def ^:private seed7 "2D3DF75EC1459A4B26C0B29449D959CC") (def ^:private seed8 "BD504A2D507F96F63889FFA3A1EBBAC6") ;;------------------------------------------------------------------------------ (defn generator [^clojure.lang.IFn$OD prob] (let [^clojure.lang.IFn$D generate-x0 (z/continuous-uniform-generator seed0) ^clojure.lang.IFn$D generate-x1 (z/continuous-uniform-generator seed1) ;;^clojure.lang.IFn$D generate-x2 (z/continuous-uniform-generator seed2) ;;^clojure.lang.IFn$D generate-x3 (z/continuous-uniform-generator seed3) ;;^clojure.lang.IFn$D generate-x4 (z/continuous-uniform-generator seed4) ;;^clojure.lang.IFn$D generate-x5 (z/continuous-uniform-generator seed5) generate-kolor (kolor/generator seed6) generate-primate (primate/generator seed7) generate-01 (z/bernoulli-generator seed8)] (fn random-record ^Record [_] (let [x0 (.invokePrim generate-x0) x1 (.invokePrim generate-x1) x2 (Math/min x0 x1) ;;(.invokePrim generate-x2) x3 (Math/max x0 x1) ;;(.invokePrim generate-x4) x4 (+ x0 x1) ;;(.invokePrim generate-x4) x5 (- x0 x1) ;;(.invokePrim generate-x5) kolor (generate-kolor) primate (generate-primate) datum (Record. x0 x1 x2 x3 x4 x5 kolor primate Double/NaN Double/NaN Double/NaN Double/NaN) p (prob datum) _(assert (<= 0.0 p 1.0)) c (generate-01 p)] (assoc datum :true-class c :true-probability p))))) ;;------------------------------------------------------------------------------ (defn enum-valued? [f] (println) (println f) (let [[ns n] (s/split (pr-str (class f)) #"\$") s (symbol ns n) r (resolve s) m (meta r) a (first (:arglists m)) tag (:tag (meta a)) codomain (resolve tag) tf (and (instance? Class codomain) (.isEnum ^Class codomain)) ] (prn ns n) (prn (class s) s) (prn (class r) r) (prn a) (prn (class codomain) codomain) (prn tf) tf)) ;;------------------------------------------------------------------------------ (test/deftest enum-codomain (enum-valued? x0) (enum-valued? kolor) (enum-valued? primate) )
[ { "context": "h an ID\"\n (t/is (= {:data {:attributes {:name \"foo\", :id 1}, :type \"bars\", :id \"1\"}}\n (j", "end": 1668, "score": 0.8978468179702759, "start": 1665, "tag": "NAME", "value": "foo" }, { "context": " (jsonapi/decorate-request \"bars\" {:name \"foo\", :id 1} :id)))))\n\n(t/deftest strip-response-test", "end": 1760, "score": 0.7998762130737305, "start": 1757, "tag": "NAME", "value": "foo" }, { "context": "napi/strip-response response))\n {:body {:name \"foo\"}}\n {:body {:data {:attributes {:name \"foo\"}, ", "end": 1909, "score": 0.9038095474243164, "start": 1906, "tag": "NAME", "value": "foo" }, { "context": "me \"foo\"}}\n {:body {:data {:attributes {:name \"foo\"}, :type \"bars\", :id \"1\"}}}\n\n {:body [{:name \"", "end": 1955, "score": 0.8685250282287598, "start": 1952, "tag": "NAME", "value": "foo" }, { "context": "\"}, :type \"bars\", :id \"1\"}}}\n\n {:body [{:name \"foo\", :id 1}]}\n {:body {:data [{:attributes {:name", "end": 2008, "score": 0.9161735773086548, "start": 2005, "tag": "NAME", "value": "foo" }, { "context": " :id 1}]}\n {:body {:data [{:attributes {:name \"foo\", :id 1}, :type \"bars\", :id \"1\"}]}}))\n", "end": 2063, "score": 0.8526907563209534, "start": 2060, "tag": "NAME", "value": "foo" } ]
test/jsonapi/core_test.clj
scij/ring.middleware.jsonapi
0
(ns jsonapi.core-test (:require [clojure.test :as t] [jsonapi.core :as jsonapi])) (t/deftest decorate-response-test (t/testing "should work with custom options" (t/are [expected response opts] (= expected (jsonapi/decorate-response response opts)) {:body {:data {:attributes {:name "foo", :id 1}, :id "1", :type "bars"}, :jsonapi {:version "1.0"}}} {:body {:name "foo", :id 1}, ::jsonapi/id-key :id, ::jsonapi/resource-name "bars"} {} {:body {:data {:attributes {:name "foo", :id 1}, :id "1", :type "bars"} :meta {:foo "bar"}, :jsonapi {:version "1.0"}}} {:body {:name "foo", :id 1} ::jsonapi/id-key :id ::jsonapi/resource-name "bars" ::jsonapi/meta {:foo "bar"}} {} {:body {:data {:attributes {:name "foo", :id 1}, :id "1", :type "bars"} :meta {:foo "bar"}, :jsonapi {:version "1.0"}}} {:body {:name "foo", :id 1} ::jsonapi/id-key :id ::jsonapi/resource-name "bars" ::jsonapi/meta {:foo "bar"}} {})) (t/testing "should work with default options" (t/is (= {:body {:data {:attributes {:name "foo", :id 1}, :id "1", :type "bars"} :jsonapi {:version "1.0"}}} (jsonapi/decorate-response {:body {:name "foo", :id 1}, ::jsonapi/id-key :id, ::jsonapi/resource-name "bars"}))))) (t/deftest decorate-request-test (t/testing "should decorate request" (t/is (= {:data {:attributes {:name "foo"}, :type "bars"}} (jsonapi/decorate-request "bars" {:name "foo"})))) (t/testing "should decorate request with an ID" (t/is (= {:data {:attributes {:name "foo", :id 1}, :type "bars", :id "1"}} (jsonapi/decorate-request "bars" {:name "foo", :id 1} :id))))) (t/deftest strip-response-test (t/are [expected response] (= expected (jsonapi/strip-response response)) {:body {:name "foo"}} {:body {:data {:attributes {:name "foo"}, :type "bars", :id "1"}}} {:body [{:name "foo", :id 1}]} {:body {:data [{:attributes {:name "foo", :id 1}, :type "bars", :id "1"}]}}))
101693
(ns jsonapi.core-test (:require [clojure.test :as t] [jsonapi.core :as jsonapi])) (t/deftest decorate-response-test (t/testing "should work with custom options" (t/are [expected response opts] (= expected (jsonapi/decorate-response response opts)) {:body {:data {:attributes {:name "foo", :id 1}, :id "1", :type "bars"}, :jsonapi {:version "1.0"}}} {:body {:name "foo", :id 1}, ::jsonapi/id-key :id, ::jsonapi/resource-name "bars"} {} {:body {:data {:attributes {:name "foo", :id 1}, :id "1", :type "bars"} :meta {:foo "bar"}, :jsonapi {:version "1.0"}}} {:body {:name "foo", :id 1} ::jsonapi/id-key :id ::jsonapi/resource-name "bars" ::jsonapi/meta {:foo "bar"}} {} {:body {:data {:attributes {:name "foo", :id 1}, :id "1", :type "bars"} :meta {:foo "bar"}, :jsonapi {:version "1.0"}}} {:body {:name "foo", :id 1} ::jsonapi/id-key :id ::jsonapi/resource-name "bars" ::jsonapi/meta {:foo "bar"}} {})) (t/testing "should work with default options" (t/is (= {:body {:data {:attributes {:name "foo", :id 1}, :id "1", :type "bars"} :jsonapi {:version "1.0"}}} (jsonapi/decorate-response {:body {:name "foo", :id 1}, ::jsonapi/id-key :id, ::jsonapi/resource-name "bars"}))))) (t/deftest decorate-request-test (t/testing "should decorate request" (t/is (= {:data {:attributes {:name "foo"}, :type "bars"}} (jsonapi/decorate-request "bars" {:name "foo"})))) (t/testing "should decorate request with an ID" (t/is (= {:data {:attributes {:name "<NAME>", :id 1}, :type "bars", :id "1"}} (jsonapi/decorate-request "bars" {:name "<NAME>", :id 1} :id))))) (t/deftest strip-response-test (t/are [expected response] (= expected (jsonapi/strip-response response)) {:body {:name "<NAME>"}} {:body {:data {:attributes {:name "<NAME>"}, :type "bars", :id "1"}}} {:body [{:name "<NAME>", :id 1}]} {:body {:data [{:attributes {:name "<NAME>", :id 1}, :type "bars", :id "1"}]}}))
true
(ns jsonapi.core-test (:require [clojure.test :as t] [jsonapi.core :as jsonapi])) (t/deftest decorate-response-test (t/testing "should work with custom options" (t/are [expected response opts] (= expected (jsonapi/decorate-response response opts)) {:body {:data {:attributes {:name "foo", :id 1}, :id "1", :type "bars"}, :jsonapi {:version "1.0"}}} {:body {:name "foo", :id 1}, ::jsonapi/id-key :id, ::jsonapi/resource-name "bars"} {} {:body {:data {:attributes {:name "foo", :id 1}, :id "1", :type "bars"} :meta {:foo "bar"}, :jsonapi {:version "1.0"}}} {:body {:name "foo", :id 1} ::jsonapi/id-key :id ::jsonapi/resource-name "bars" ::jsonapi/meta {:foo "bar"}} {} {:body {:data {:attributes {:name "foo", :id 1}, :id "1", :type "bars"} :meta {:foo "bar"}, :jsonapi {:version "1.0"}}} {:body {:name "foo", :id 1} ::jsonapi/id-key :id ::jsonapi/resource-name "bars" ::jsonapi/meta {:foo "bar"}} {})) (t/testing "should work with default options" (t/is (= {:body {:data {:attributes {:name "foo", :id 1}, :id "1", :type "bars"} :jsonapi {:version "1.0"}}} (jsonapi/decorate-response {:body {:name "foo", :id 1}, ::jsonapi/id-key :id, ::jsonapi/resource-name "bars"}))))) (t/deftest decorate-request-test (t/testing "should decorate request" (t/is (= {:data {:attributes {:name "foo"}, :type "bars"}} (jsonapi/decorate-request "bars" {:name "foo"})))) (t/testing "should decorate request with an ID" (t/is (= {:data {:attributes {:name "PI:NAME:<NAME>END_PI", :id 1}, :type "bars", :id "1"}} (jsonapi/decorate-request "bars" {:name "PI:NAME:<NAME>END_PI", :id 1} :id))))) (t/deftest strip-response-test (t/are [expected response] (= expected (jsonapi/strip-response response)) {:body {:name "PI:NAME:<NAME>END_PI"}} {:body {:data {:attributes {:name "PI:NAME:<NAME>END_PI"}, :type "bars", :id "1"}}} {:body [{:name "PI:NAME:<NAME>END_PI", :id 1}]} {:body {:data [{:attributes {:name "PI:NAME:<NAME>END_PI", :id 1}, :type "bars", :id "1"}]}}))
[ { "context": "ment)))\n\n(defn add-default-person [seg]\n (if (#{\"praet\" \"winien\"} (:pos seg))\n (assoc seg :person \"te", "end": 3977, "score": 0.7650370001792908, "start": 3972, "tag": "NAME", "value": "praet" }, { "context": "\n(defn add-default-person [seg]\n (if (#{\"praet\" \"winien\"} (:pos seg))\n (assoc seg :person \"ter\")\n s", "end": 3986, "score": 0.9343310594558716, "start": 3980, "tag": "NAME", "value": "winien" } ]
src/clj_nkjp/polimorf.clj
nathell/clj-nkjp
3
(ns clj-nkjp.polimorf (:require [clojure.math.combinatorics :as combinatorics] [clojure.string :as string] [clojure.java.io :as io] [clj-nkjp.tags :as tags] [clj-nkjp.tagset :as tagset]) (:import [morfologik.stemming PolishStemmer WordData])) (let [stemmer (PolishStemmer.)] (defn analyze [word] (locking stemmer (let [res (map (fn [^WordData x] {:base (-> x .getStem str) :tag (-> x .getTag str)}) (.lookup stemmer word))] (when-not (empty? res) (doall res)))))) (defn expand-single [tag] (map (partial string/join ":") (apply combinatorics/cartesian-product (map #(string/split % #"\.") (string/split tag #":"))))) (defn semiexpand-tag [tag] (string/split tag #"[+|]")) (defn expand-tag [tag] (mapcat expand-single (semiexpand-tag tag))) (defn expand-interp [{:keys [base tag]}] (map (partial vector base) (expand-tag tag))) (defn extract-word-data [^WordData w] [[(str (.getWord w)) (str (.getStem w))] (semiexpand-tag (.getTag w))]) (defn all-tags-contracted [] (let [s (PolishStemmer.)] (reduce (fn [accu ^WordData wd] (conj accu (str (.getTag wd)))) #{} s))) (defn dump-dict [] (doseq [^WordData w (PolishStemmer.) t (expand-tag (str (.getTag w)))] (printf "%s\t%s\t%s\n" (str (.getWord w)) (str (.getStem w)) t))) (defn find-words-by-tag [t] (let [s (PolishStemmer.)] (filter (fn [^WordData wd] ((set (expand-tag (str (.getTag wd)))) t)) s))) (defn load-polimorf-tab [rdr] (map (fn [x] [(first (first x)) (second (first x)) (distinct (mapcat #(semiexpand-tag (nth % 2)) x))]) (partition-by (partial take 2) (map #(string/split % #"\t") (line-seq rdr))))) (defmacro with-polimorf [f & body] `(with-open [~f (io/reader "/home/nathell/projects/smyrna/other/polimorf/PoliMorf-0.6.5.tab")] ~@body)) (defn tag-frequencies-semicontracted [] (let [s (PolishStemmer.)] (frequencies (mapcat semiexpand-tag (map #(str (.getTag %)) s))))) (defn morfologik->t3 [tag] (if (= tag "num:comp") "ign" (-> tag (string/replace #"^verb:pred:pot" "pot") (string/replace #"^verb:" "") (string/replace #":(non)?refl" "") (string/replace #":n[12]" ":n") (string/replace #"p[23]" "n") (string/replace #"p1" "m1") ((fn [t] (if (.startsWith t "siebie") (string/replace t #":n?akc" "") t)))))) (def morfologik-override (into {"się" [["się" "qub"]] "bardzo" [["bardzo" "adv:pos"]] "najbardziej" [["bardzo" "adv:sup"]] "znowu" [["znowu" "adv"] ["znowu" "qub"]] "znów" [["znów" "adv"] ["znów" "qub"]]} (for [base ["by" "żeby" "aby" "gdyby" "jakby" "że" "choćby" "chociażby"] suffix ["m" "ś" "śmy" "ście"]] [(str base suffix) [[base "comp"] [base "qub"]]]))) (def morfologik-additional {"głównie" [["głównie" "qub"]] "to" [["to" "pred"]] "także" [["także" "conj"]] "zbyt" [["zbyt" "qub"]]}) (defn analyze-t3 [x] (let [lc (string/lower-case x)] (if (re-find #"^[\pP§+°=><˝`¨|×−$~]+$" x) [[x "interp"]] (if-let [override (morfologik-override lc)] override (let [an (concat (analyze x) (analyze lc))] (if (seq an) (distinct (concat (map (fn [[x y]] [x (morfologik->t3 y)]) (mapcat expand-interp an)) (morfologik-additional lc))) [[x "ign"]])))))) ;;; NKJP to T3 (def t3 (tagset/read-tagset (io/resource "tagsets/t3.tagset"))) (defn parse-tag-from-segment [seg] (assoc (tagset/parse-tag (-> seg :disamb first :interpretation first)) :orth (-> seg :orth first) :nps (-> seg :nps first))) (defn sentence->segs [sentence] (map parse-tag-from-segment (rest sentence))) (defn stringify-sentence [sentence] (apply str (map #(str (when-not (:nps %) " ") (:orth %)) (sentence->segs sentence)))) (defn sentences [document] (filter #(= (first %) :s) (tree-seq vector? rest document))) (defn add-default-person [seg] (if (#{"praet" "winien"} (:pos seg)) (assoc seg :person "ter") seg)) (defn combine-subsegments-no-verify [main aux errors] (if (seq aux) (reduce (fn [[curr errors] aux] (cond (= (:pos aux) "aglt") (if (#{"praet" "pot" "winien"} (:pos curr)) [(assoc curr :person (:person aux)) errors] [curr (conj errors {:type :aglt, :aux aux, :main main, :partial curr})]) (= (:orth aux) "by") (if (= (:pos curr) "praet") [(assoc curr :pos "pot") errors] [curr (conj errors {:type :pot, :aux aux, :main main, :partial curr})]) :otherwise [curr (conj errors {:type :unsupported, :aux aux, :main main, :partial curr})])) [(-> main (assoc :orth (apply str (:orth main) (map :orth aux))) add-default-person) errors] aux) [(add-default-person main) errors])) (defn combine-subsegments [main aux errors] (let [[res errors] (combine-subsegments-no-verify main aux errors)] (try (tagset/verify-tag t3 res) [res errors] (catch Exception e [{:orth (:orth res), :base (:base res), :nps (:nps res), :pos "ign"} (conj errors {:type :not-in-t3, :error (.getMessage e)})])))) (defn nkjp->t3 [segs] (when (seq segs) (lazy-seq (let [fst (first segs) rst (rest segs)] (if (= (:pos fst) "interp") (cons [fst nil] (nkjp->t3 rst)) (let [[aux nxt] (split-with #(and (:nps %) (not= (:pos %) "interp")) rst)] (cons (combine-subsegments fst aux []) (nkjp->t3 nxt)))))))) (defn in-morfologik? [seg] ((set (map second (analyze-t3 (:orth seg)))) (tagset/serialize-tag t3 seg))) (defn compactify-nim [x] [(:orth x) (tagset/serialize-tag t3 x) (string/join " " (analyze-t3 (:orth x)))]) (defn documents [] (map (comp read-string slurp) (rest (file-seq (io/file "/home/nathell/corpora/nkjp-clj/"))))) (defn checker "Try running nkjp->t3 on all sentences in the corpus, to see how many unsupported cases we have." [] (apply concat (for [docum (documents) sent (sentences docum)] (apply concat (map second (nkjp->t3 (sentence->segs sent))))))) (defn not-in-morfologik [document] (mapcat #(remove in-morfologik? (map first (nkjp->t3 (sentence->segs %)))) (sentences document))) (defn nim-report [] (let [nim (mapcat not-in-morfologik (documents))] (for [[k cnt] (sort-by val > (frequencies nim))] (into [cnt] (compactify-nim k)))))
83688
(ns clj-nkjp.polimorf (:require [clojure.math.combinatorics :as combinatorics] [clojure.string :as string] [clojure.java.io :as io] [clj-nkjp.tags :as tags] [clj-nkjp.tagset :as tagset]) (:import [morfologik.stemming PolishStemmer WordData])) (let [stemmer (PolishStemmer.)] (defn analyze [word] (locking stemmer (let [res (map (fn [^WordData x] {:base (-> x .getStem str) :tag (-> x .getTag str)}) (.lookup stemmer word))] (when-not (empty? res) (doall res)))))) (defn expand-single [tag] (map (partial string/join ":") (apply combinatorics/cartesian-product (map #(string/split % #"\.") (string/split tag #":"))))) (defn semiexpand-tag [tag] (string/split tag #"[+|]")) (defn expand-tag [tag] (mapcat expand-single (semiexpand-tag tag))) (defn expand-interp [{:keys [base tag]}] (map (partial vector base) (expand-tag tag))) (defn extract-word-data [^WordData w] [[(str (.getWord w)) (str (.getStem w))] (semiexpand-tag (.getTag w))]) (defn all-tags-contracted [] (let [s (PolishStemmer.)] (reduce (fn [accu ^WordData wd] (conj accu (str (.getTag wd)))) #{} s))) (defn dump-dict [] (doseq [^WordData w (PolishStemmer.) t (expand-tag (str (.getTag w)))] (printf "%s\t%s\t%s\n" (str (.getWord w)) (str (.getStem w)) t))) (defn find-words-by-tag [t] (let [s (PolishStemmer.)] (filter (fn [^WordData wd] ((set (expand-tag (str (.getTag wd)))) t)) s))) (defn load-polimorf-tab [rdr] (map (fn [x] [(first (first x)) (second (first x)) (distinct (mapcat #(semiexpand-tag (nth % 2)) x))]) (partition-by (partial take 2) (map #(string/split % #"\t") (line-seq rdr))))) (defmacro with-polimorf [f & body] `(with-open [~f (io/reader "/home/nathell/projects/smyrna/other/polimorf/PoliMorf-0.6.5.tab")] ~@body)) (defn tag-frequencies-semicontracted [] (let [s (PolishStemmer.)] (frequencies (mapcat semiexpand-tag (map #(str (.getTag %)) s))))) (defn morfologik->t3 [tag] (if (= tag "num:comp") "ign" (-> tag (string/replace #"^verb:pred:pot" "pot") (string/replace #"^verb:" "") (string/replace #":(non)?refl" "") (string/replace #":n[12]" ":n") (string/replace #"p[23]" "n") (string/replace #"p1" "m1") ((fn [t] (if (.startsWith t "siebie") (string/replace t #":n?akc" "") t)))))) (def morfologik-override (into {"się" [["się" "qub"]] "bardzo" [["bardzo" "adv:pos"]] "najbardziej" [["bardzo" "adv:sup"]] "znowu" [["znowu" "adv"] ["znowu" "qub"]] "znów" [["znów" "adv"] ["znów" "qub"]]} (for [base ["by" "żeby" "aby" "gdyby" "jakby" "że" "choćby" "chociażby"] suffix ["m" "ś" "śmy" "ście"]] [(str base suffix) [[base "comp"] [base "qub"]]]))) (def morfologik-additional {"głównie" [["głównie" "qub"]] "to" [["to" "pred"]] "także" [["także" "conj"]] "zbyt" [["zbyt" "qub"]]}) (defn analyze-t3 [x] (let [lc (string/lower-case x)] (if (re-find #"^[\pP§+°=><˝`¨|×−$~]+$" x) [[x "interp"]] (if-let [override (morfologik-override lc)] override (let [an (concat (analyze x) (analyze lc))] (if (seq an) (distinct (concat (map (fn [[x y]] [x (morfologik->t3 y)]) (mapcat expand-interp an)) (morfologik-additional lc))) [[x "ign"]])))))) ;;; NKJP to T3 (def t3 (tagset/read-tagset (io/resource "tagsets/t3.tagset"))) (defn parse-tag-from-segment [seg] (assoc (tagset/parse-tag (-> seg :disamb first :interpretation first)) :orth (-> seg :orth first) :nps (-> seg :nps first))) (defn sentence->segs [sentence] (map parse-tag-from-segment (rest sentence))) (defn stringify-sentence [sentence] (apply str (map #(str (when-not (:nps %) " ") (:orth %)) (sentence->segs sentence)))) (defn sentences [document] (filter #(= (first %) :s) (tree-seq vector? rest document))) (defn add-default-person [seg] (if (#{"<NAME>" "<NAME>"} (:pos seg)) (assoc seg :person "ter") seg)) (defn combine-subsegments-no-verify [main aux errors] (if (seq aux) (reduce (fn [[curr errors] aux] (cond (= (:pos aux) "aglt") (if (#{"praet" "pot" "winien"} (:pos curr)) [(assoc curr :person (:person aux)) errors] [curr (conj errors {:type :aglt, :aux aux, :main main, :partial curr})]) (= (:orth aux) "by") (if (= (:pos curr) "praet") [(assoc curr :pos "pot") errors] [curr (conj errors {:type :pot, :aux aux, :main main, :partial curr})]) :otherwise [curr (conj errors {:type :unsupported, :aux aux, :main main, :partial curr})])) [(-> main (assoc :orth (apply str (:orth main) (map :orth aux))) add-default-person) errors] aux) [(add-default-person main) errors])) (defn combine-subsegments [main aux errors] (let [[res errors] (combine-subsegments-no-verify main aux errors)] (try (tagset/verify-tag t3 res) [res errors] (catch Exception e [{:orth (:orth res), :base (:base res), :nps (:nps res), :pos "ign"} (conj errors {:type :not-in-t3, :error (.getMessage e)})])))) (defn nkjp->t3 [segs] (when (seq segs) (lazy-seq (let [fst (first segs) rst (rest segs)] (if (= (:pos fst) "interp") (cons [fst nil] (nkjp->t3 rst)) (let [[aux nxt] (split-with #(and (:nps %) (not= (:pos %) "interp")) rst)] (cons (combine-subsegments fst aux []) (nkjp->t3 nxt)))))))) (defn in-morfologik? [seg] ((set (map second (analyze-t3 (:orth seg)))) (tagset/serialize-tag t3 seg))) (defn compactify-nim [x] [(:orth x) (tagset/serialize-tag t3 x) (string/join " " (analyze-t3 (:orth x)))]) (defn documents [] (map (comp read-string slurp) (rest (file-seq (io/file "/home/nathell/corpora/nkjp-clj/"))))) (defn checker "Try running nkjp->t3 on all sentences in the corpus, to see how many unsupported cases we have." [] (apply concat (for [docum (documents) sent (sentences docum)] (apply concat (map second (nkjp->t3 (sentence->segs sent))))))) (defn not-in-morfologik [document] (mapcat #(remove in-morfologik? (map first (nkjp->t3 (sentence->segs %)))) (sentences document))) (defn nim-report [] (let [nim (mapcat not-in-morfologik (documents))] (for [[k cnt] (sort-by val > (frequencies nim))] (into [cnt] (compactify-nim k)))))
true
(ns clj-nkjp.polimorf (:require [clojure.math.combinatorics :as combinatorics] [clojure.string :as string] [clojure.java.io :as io] [clj-nkjp.tags :as tags] [clj-nkjp.tagset :as tagset]) (:import [morfologik.stemming PolishStemmer WordData])) (let [stemmer (PolishStemmer.)] (defn analyze [word] (locking stemmer (let [res (map (fn [^WordData x] {:base (-> x .getStem str) :tag (-> x .getTag str)}) (.lookup stemmer word))] (when-not (empty? res) (doall res)))))) (defn expand-single [tag] (map (partial string/join ":") (apply combinatorics/cartesian-product (map #(string/split % #"\.") (string/split tag #":"))))) (defn semiexpand-tag [tag] (string/split tag #"[+|]")) (defn expand-tag [tag] (mapcat expand-single (semiexpand-tag tag))) (defn expand-interp [{:keys [base tag]}] (map (partial vector base) (expand-tag tag))) (defn extract-word-data [^WordData w] [[(str (.getWord w)) (str (.getStem w))] (semiexpand-tag (.getTag w))]) (defn all-tags-contracted [] (let [s (PolishStemmer.)] (reduce (fn [accu ^WordData wd] (conj accu (str (.getTag wd)))) #{} s))) (defn dump-dict [] (doseq [^WordData w (PolishStemmer.) t (expand-tag (str (.getTag w)))] (printf "%s\t%s\t%s\n" (str (.getWord w)) (str (.getStem w)) t))) (defn find-words-by-tag [t] (let [s (PolishStemmer.)] (filter (fn [^WordData wd] ((set (expand-tag (str (.getTag wd)))) t)) s))) (defn load-polimorf-tab [rdr] (map (fn [x] [(first (first x)) (second (first x)) (distinct (mapcat #(semiexpand-tag (nth % 2)) x))]) (partition-by (partial take 2) (map #(string/split % #"\t") (line-seq rdr))))) (defmacro with-polimorf [f & body] `(with-open [~f (io/reader "/home/nathell/projects/smyrna/other/polimorf/PoliMorf-0.6.5.tab")] ~@body)) (defn tag-frequencies-semicontracted [] (let [s (PolishStemmer.)] (frequencies (mapcat semiexpand-tag (map #(str (.getTag %)) s))))) (defn morfologik->t3 [tag] (if (= tag "num:comp") "ign" (-> tag (string/replace #"^verb:pred:pot" "pot") (string/replace #"^verb:" "") (string/replace #":(non)?refl" "") (string/replace #":n[12]" ":n") (string/replace #"p[23]" "n") (string/replace #"p1" "m1") ((fn [t] (if (.startsWith t "siebie") (string/replace t #":n?akc" "") t)))))) (def morfologik-override (into {"się" [["się" "qub"]] "bardzo" [["bardzo" "adv:pos"]] "najbardziej" [["bardzo" "adv:sup"]] "znowu" [["znowu" "adv"] ["znowu" "qub"]] "znów" [["znów" "adv"] ["znów" "qub"]]} (for [base ["by" "żeby" "aby" "gdyby" "jakby" "że" "choćby" "chociażby"] suffix ["m" "ś" "śmy" "ście"]] [(str base suffix) [[base "comp"] [base "qub"]]]))) (def morfologik-additional {"głównie" [["głównie" "qub"]] "to" [["to" "pred"]] "także" [["także" "conj"]] "zbyt" [["zbyt" "qub"]]}) (defn analyze-t3 [x] (let [lc (string/lower-case x)] (if (re-find #"^[\pP§+°=><˝`¨|×−$~]+$" x) [[x "interp"]] (if-let [override (morfologik-override lc)] override (let [an (concat (analyze x) (analyze lc))] (if (seq an) (distinct (concat (map (fn [[x y]] [x (morfologik->t3 y)]) (mapcat expand-interp an)) (morfologik-additional lc))) [[x "ign"]])))))) ;;; NKJP to T3 (def t3 (tagset/read-tagset (io/resource "tagsets/t3.tagset"))) (defn parse-tag-from-segment [seg] (assoc (tagset/parse-tag (-> seg :disamb first :interpretation first)) :orth (-> seg :orth first) :nps (-> seg :nps first))) (defn sentence->segs [sentence] (map parse-tag-from-segment (rest sentence))) (defn stringify-sentence [sentence] (apply str (map #(str (when-not (:nps %) " ") (:orth %)) (sentence->segs sentence)))) (defn sentences [document] (filter #(= (first %) :s) (tree-seq vector? rest document))) (defn add-default-person [seg] (if (#{"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"} (:pos seg)) (assoc seg :person "ter") seg)) (defn combine-subsegments-no-verify [main aux errors] (if (seq aux) (reduce (fn [[curr errors] aux] (cond (= (:pos aux) "aglt") (if (#{"praet" "pot" "winien"} (:pos curr)) [(assoc curr :person (:person aux)) errors] [curr (conj errors {:type :aglt, :aux aux, :main main, :partial curr})]) (= (:orth aux) "by") (if (= (:pos curr) "praet") [(assoc curr :pos "pot") errors] [curr (conj errors {:type :pot, :aux aux, :main main, :partial curr})]) :otherwise [curr (conj errors {:type :unsupported, :aux aux, :main main, :partial curr})])) [(-> main (assoc :orth (apply str (:orth main) (map :orth aux))) add-default-person) errors] aux) [(add-default-person main) errors])) (defn combine-subsegments [main aux errors] (let [[res errors] (combine-subsegments-no-verify main aux errors)] (try (tagset/verify-tag t3 res) [res errors] (catch Exception e [{:orth (:orth res), :base (:base res), :nps (:nps res), :pos "ign"} (conj errors {:type :not-in-t3, :error (.getMessage e)})])))) (defn nkjp->t3 [segs] (when (seq segs) (lazy-seq (let [fst (first segs) rst (rest segs)] (if (= (:pos fst) "interp") (cons [fst nil] (nkjp->t3 rst)) (let [[aux nxt] (split-with #(and (:nps %) (not= (:pos %) "interp")) rst)] (cons (combine-subsegments fst aux []) (nkjp->t3 nxt)))))))) (defn in-morfologik? [seg] ((set (map second (analyze-t3 (:orth seg)))) (tagset/serialize-tag t3 seg))) (defn compactify-nim [x] [(:orth x) (tagset/serialize-tag t3 x) (string/join " " (analyze-t3 (:orth x)))]) (defn documents [] (map (comp read-string slurp) (rest (file-seq (io/file "/home/nathell/corpora/nkjp-clj/"))))) (defn checker "Try running nkjp->t3 on all sentences in the corpus, to see how many unsupported cases we have." [] (apply concat (for [docum (documents) sent (sentences docum)] (apply concat (map second (nkjp->t3 (sentence->segs sent))))))) (defn not-in-morfologik [document] (mapcat #(remove in-morfologik? (map first (nkjp->t3 (sentence->segs %)))) (sentences document))) (defn nim-report [] (let [nim (mapcat not-in-morfologik (documents))] (for [[k cnt] (sort-by val > (frequencies nim))] (into [cnt] (compactify-nim k)))))
[ { "context": "N \"/authcb/facebook\")\n :profile-fields [\"id\" \"displayName\" \"photos\" \"email\" \"name\"]\n :enableProof true}", "end": 3139, "score": 0.22734728455543518, "start": 3128, "tag": "KEY", "value": "displayName" } ]
example/common/src/common/config.cljs
daigotanaka/mern-cljs
9
(ns common.config (:require [cljs.nodejs :as nodejs] [mern-utils.backend-lib :refer [local-ip create-logger]])) (def WWW-SITE-TITLE "MERN-cljs Example") (def PROD-WWW-DOMAIN "your-domain.com") (def DEFAULT-LOGIN-PAGE "me") ; "mongodb" or "dynamodb" (def DATABASE "mongodb") (def MONGODB-DOMAIN "localhost") (def MONGODB-PORT 27017) (def MONGODB-DBNAME "merncljs_auth") (def RABBITMQ-DEFAULT-QUEUE "task_queue") (def PRIMARY-SOCIAL-AUTH "facebook") (def API-TOKEN-EXPIRES-IN (* 60 60 24 14)) ; 14 days (def LOGGER-CONFIG {:name "mern-cljs-example" :streams [{:level "info" :path "./logs/mern-cljs-example.log"} {:level "trace" :stream (.. nodejs/process -stdout)} ]}) ; Probably you can leave the configs below as they are (def IS-PRODUCTION (if (= (.. nodejs/process -env -NODE_ENV) "production" ) true false)) (def LOCAL-IP (if IS-PRODUCTION "0.0.0.0" "localhost")) (def COOKIE-SECRET (if IS-PRODUCTION (.. nodejs/process -env -COOKIE_SECRET) "very very secret")) (def DYNAMODB-DOMAIN LOCAL-IP) (def DYNAMODB-PORT 7893) (def DB-ENDPOINT (case DATABASE "mongodb" (str "mongodb://" MONGODB-DOMAIN ":" MONGODB-PORT "/" MONGODB-DBNAME) "dynamodb" (if IS-PRODUCTION nil (str "http://" DYNAMODB-DOMAIN ":" DYNAMODB-PORT)))) (def USE-RABBITMQ false) (def RABBITMQ-DOMAIN (if IS-PRODUCTION (.. nodejs/process -env -RABBITMQ_DOMAIN) LOCAL-IP)) (def RABBITMQ-PORT (if IS-PRODUCTION (.. nodejs/process -env -RABBITMQ_PORT) 5672)) (def RABBITMQ-USER (if IS-PRODUCTION (.. nodejs/process -env -RABBITMQ_USER) "")) (def RABBITMQ-PASSWORD (if IS-PRODUCTION (.. nodejs/process -env -RABBITMQ_PASSWORD) "")) (def API-DOMAIN LOCAL-IP) (def API-PORT 5000) (def WWW-DOMAIN (if IS-PRODUCTION "0.0.0.0" LOCAL-IP)) ; Cannot use 80 inside docker container. So 1337 internally and map the port to host (def WWW-PORT 1337) (def WWW-EXTERNAL-DOMAIN (if IS-PRODUCTION PROD-WWW-DOMAIN (str WWW-DOMAIN ":" WWW-PORT))) ; Enter "yourdomain.com" to limit access (def EMAIL-DOMAIN-RESTRICTION nil) ; Those social app accounts are set up for the example app (def FACEBOOK-CLIENT-ID (if IS-PRODUCTION (.. nodejs/process -env -FACEBOOK-CLIENT-ID) "825920487534725")) (def FACEBOOK-CLIENT-SECRET (if IS-PRODUCTION (.. nodejs/process -env -FACEBOOK-CLIENT-SECRET) "93bf4835a0b66422e49a480c7be711c5")) (def GOOGLE-CLIENT-ID (if IS-PRODUCTION (.. nodejs/process -env -FACEBOOK-CLIENT-ID) "1071376916361-af1hfk0b90bru0gn1esh3stksd0hb1ii.apps.googleusercontent.com")) (def GOOGLE-CLIENT-SECRET (if IS-PRODUCTION (.. nodejs/process -env -FACEBOOK-CLIENT-SECRET) "xxduCYSBUdTx7TfMoxk3hwrB")) (def config-auth {:email-domain-restriction EMAIL-DOMAIN-RESTRICTION :token-expires-in-sec API-TOKEN-EXPIRES-IN :facebook-auth {:client-id FACEBOOK-CLIENT-ID :client-secret FACEBOOK-CLIENT-SECRET :callback-url (str "http://" WWW-EXTERNAL-DOMAIN "/authcb/facebook") :profile-fields ["id" "displayName" "photos" "email" "name"] :enableProof true} :google-auth {:client-id GOOGLE-CLIENT-ID :client-secret GOOGLE-CLIENT-SECRET :callback-url (str "http://" WWW-EXTERNAL-DOMAIN "/authcb/google")}}) (def cors-options (clj->js {:origin (str "http://" WWW-EXTERNAL-DOMAIN) :credentials true :allowedHeaders "Authorization,Origin,X-Requested-With,Content-Type,Accept"})) (def AWS-ACCESS-KEY-ID (.. nodejs/process -env -AWS_ACCESS_KEY_ID)) (def AWS-SECRET-ACCESS-KEY (.. nodejs/process -env -AWS_SECRET_ACCESS_KEY)) (def AWS-REGION (.. nodejs/process -env -AWS_REGION)) (def AWS-CONFIG {:accessKeyId AWS-ACCESS-KEY-ID :secretAccessKey AWS-SECRET-ACCESS-KEY :region AWS-REGION}) (def RABBITMQ-ENDPOINT (if IS-PRODUCTION (str "amqp://" RABBITMQ-USER ":" RABBITMQ-PASSWORD "@" RABBITMQ-DOMAIN "/" RABBITMQ-USER) (str "amqp://" RABBITMQ-DOMAIN ":" RABBITMQ-PORT))) (def LOGGER (create-logger (clj->js LOGGER-CONFIG)))
87748
(ns common.config (:require [cljs.nodejs :as nodejs] [mern-utils.backend-lib :refer [local-ip create-logger]])) (def WWW-SITE-TITLE "MERN-cljs Example") (def PROD-WWW-DOMAIN "your-domain.com") (def DEFAULT-LOGIN-PAGE "me") ; "mongodb" or "dynamodb" (def DATABASE "mongodb") (def MONGODB-DOMAIN "localhost") (def MONGODB-PORT 27017) (def MONGODB-DBNAME "merncljs_auth") (def RABBITMQ-DEFAULT-QUEUE "task_queue") (def PRIMARY-SOCIAL-AUTH "facebook") (def API-TOKEN-EXPIRES-IN (* 60 60 24 14)) ; 14 days (def LOGGER-CONFIG {:name "mern-cljs-example" :streams [{:level "info" :path "./logs/mern-cljs-example.log"} {:level "trace" :stream (.. nodejs/process -stdout)} ]}) ; Probably you can leave the configs below as they are (def IS-PRODUCTION (if (= (.. nodejs/process -env -NODE_ENV) "production" ) true false)) (def LOCAL-IP (if IS-PRODUCTION "0.0.0.0" "localhost")) (def COOKIE-SECRET (if IS-PRODUCTION (.. nodejs/process -env -COOKIE_SECRET) "very very secret")) (def DYNAMODB-DOMAIN LOCAL-IP) (def DYNAMODB-PORT 7893) (def DB-ENDPOINT (case DATABASE "mongodb" (str "mongodb://" MONGODB-DOMAIN ":" MONGODB-PORT "/" MONGODB-DBNAME) "dynamodb" (if IS-PRODUCTION nil (str "http://" DYNAMODB-DOMAIN ":" DYNAMODB-PORT)))) (def USE-RABBITMQ false) (def RABBITMQ-DOMAIN (if IS-PRODUCTION (.. nodejs/process -env -RABBITMQ_DOMAIN) LOCAL-IP)) (def RABBITMQ-PORT (if IS-PRODUCTION (.. nodejs/process -env -RABBITMQ_PORT) 5672)) (def RABBITMQ-USER (if IS-PRODUCTION (.. nodejs/process -env -RABBITMQ_USER) "")) (def RABBITMQ-PASSWORD (if IS-PRODUCTION (.. nodejs/process -env -RABBITMQ_PASSWORD) "")) (def API-DOMAIN LOCAL-IP) (def API-PORT 5000) (def WWW-DOMAIN (if IS-PRODUCTION "0.0.0.0" LOCAL-IP)) ; Cannot use 80 inside docker container. So 1337 internally and map the port to host (def WWW-PORT 1337) (def WWW-EXTERNAL-DOMAIN (if IS-PRODUCTION PROD-WWW-DOMAIN (str WWW-DOMAIN ":" WWW-PORT))) ; Enter "yourdomain.com" to limit access (def EMAIL-DOMAIN-RESTRICTION nil) ; Those social app accounts are set up for the example app (def FACEBOOK-CLIENT-ID (if IS-PRODUCTION (.. nodejs/process -env -FACEBOOK-CLIENT-ID) "825920487534725")) (def FACEBOOK-CLIENT-SECRET (if IS-PRODUCTION (.. nodejs/process -env -FACEBOOK-CLIENT-SECRET) "93bf4835a0b66422e49a480c7be711c5")) (def GOOGLE-CLIENT-ID (if IS-PRODUCTION (.. nodejs/process -env -FACEBOOK-CLIENT-ID) "1071376916361-af1hfk0b90bru0gn1esh3stksd0hb1ii.apps.googleusercontent.com")) (def GOOGLE-CLIENT-SECRET (if IS-PRODUCTION (.. nodejs/process -env -FACEBOOK-CLIENT-SECRET) "xxduCYSBUdTx7TfMoxk3hwrB")) (def config-auth {:email-domain-restriction EMAIL-DOMAIN-RESTRICTION :token-expires-in-sec API-TOKEN-EXPIRES-IN :facebook-auth {:client-id FACEBOOK-CLIENT-ID :client-secret FACEBOOK-CLIENT-SECRET :callback-url (str "http://" WWW-EXTERNAL-DOMAIN "/authcb/facebook") :profile-fields ["id" "<KEY>" "photos" "email" "name"] :enableProof true} :google-auth {:client-id GOOGLE-CLIENT-ID :client-secret GOOGLE-CLIENT-SECRET :callback-url (str "http://" WWW-EXTERNAL-DOMAIN "/authcb/google")}}) (def cors-options (clj->js {:origin (str "http://" WWW-EXTERNAL-DOMAIN) :credentials true :allowedHeaders "Authorization,Origin,X-Requested-With,Content-Type,Accept"})) (def AWS-ACCESS-KEY-ID (.. nodejs/process -env -AWS_ACCESS_KEY_ID)) (def AWS-SECRET-ACCESS-KEY (.. nodejs/process -env -AWS_SECRET_ACCESS_KEY)) (def AWS-REGION (.. nodejs/process -env -AWS_REGION)) (def AWS-CONFIG {:accessKeyId AWS-ACCESS-KEY-ID :secretAccessKey AWS-SECRET-ACCESS-KEY :region AWS-REGION}) (def RABBITMQ-ENDPOINT (if IS-PRODUCTION (str "amqp://" RABBITMQ-USER ":" RABBITMQ-PASSWORD "@" RABBITMQ-DOMAIN "/" RABBITMQ-USER) (str "amqp://" RABBITMQ-DOMAIN ":" RABBITMQ-PORT))) (def LOGGER (create-logger (clj->js LOGGER-CONFIG)))
true
(ns common.config (:require [cljs.nodejs :as nodejs] [mern-utils.backend-lib :refer [local-ip create-logger]])) (def WWW-SITE-TITLE "MERN-cljs Example") (def PROD-WWW-DOMAIN "your-domain.com") (def DEFAULT-LOGIN-PAGE "me") ; "mongodb" or "dynamodb" (def DATABASE "mongodb") (def MONGODB-DOMAIN "localhost") (def MONGODB-PORT 27017) (def MONGODB-DBNAME "merncljs_auth") (def RABBITMQ-DEFAULT-QUEUE "task_queue") (def PRIMARY-SOCIAL-AUTH "facebook") (def API-TOKEN-EXPIRES-IN (* 60 60 24 14)) ; 14 days (def LOGGER-CONFIG {:name "mern-cljs-example" :streams [{:level "info" :path "./logs/mern-cljs-example.log"} {:level "trace" :stream (.. nodejs/process -stdout)} ]}) ; Probably you can leave the configs below as they are (def IS-PRODUCTION (if (= (.. nodejs/process -env -NODE_ENV) "production" ) true false)) (def LOCAL-IP (if IS-PRODUCTION "0.0.0.0" "localhost")) (def COOKIE-SECRET (if IS-PRODUCTION (.. nodejs/process -env -COOKIE_SECRET) "very very secret")) (def DYNAMODB-DOMAIN LOCAL-IP) (def DYNAMODB-PORT 7893) (def DB-ENDPOINT (case DATABASE "mongodb" (str "mongodb://" MONGODB-DOMAIN ":" MONGODB-PORT "/" MONGODB-DBNAME) "dynamodb" (if IS-PRODUCTION nil (str "http://" DYNAMODB-DOMAIN ":" DYNAMODB-PORT)))) (def USE-RABBITMQ false) (def RABBITMQ-DOMAIN (if IS-PRODUCTION (.. nodejs/process -env -RABBITMQ_DOMAIN) LOCAL-IP)) (def RABBITMQ-PORT (if IS-PRODUCTION (.. nodejs/process -env -RABBITMQ_PORT) 5672)) (def RABBITMQ-USER (if IS-PRODUCTION (.. nodejs/process -env -RABBITMQ_USER) "")) (def RABBITMQ-PASSWORD (if IS-PRODUCTION (.. nodejs/process -env -RABBITMQ_PASSWORD) "")) (def API-DOMAIN LOCAL-IP) (def API-PORT 5000) (def WWW-DOMAIN (if IS-PRODUCTION "0.0.0.0" LOCAL-IP)) ; Cannot use 80 inside docker container. So 1337 internally and map the port to host (def WWW-PORT 1337) (def WWW-EXTERNAL-DOMAIN (if IS-PRODUCTION PROD-WWW-DOMAIN (str WWW-DOMAIN ":" WWW-PORT))) ; Enter "yourdomain.com" to limit access (def EMAIL-DOMAIN-RESTRICTION nil) ; Those social app accounts are set up for the example app (def FACEBOOK-CLIENT-ID (if IS-PRODUCTION (.. nodejs/process -env -FACEBOOK-CLIENT-ID) "825920487534725")) (def FACEBOOK-CLIENT-SECRET (if IS-PRODUCTION (.. nodejs/process -env -FACEBOOK-CLIENT-SECRET) "93bf4835a0b66422e49a480c7be711c5")) (def GOOGLE-CLIENT-ID (if IS-PRODUCTION (.. nodejs/process -env -FACEBOOK-CLIENT-ID) "1071376916361-af1hfk0b90bru0gn1esh3stksd0hb1ii.apps.googleusercontent.com")) (def GOOGLE-CLIENT-SECRET (if IS-PRODUCTION (.. nodejs/process -env -FACEBOOK-CLIENT-SECRET) "xxduCYSBUdTx7TfMoxk3hwrB")) (def config-auth {:email-domain-restriction EMAIL-DOMAIN-RESTRICTION :token-expires-in-sec API-TOKEN-EXPIRES-IN :facebook-auth {:client-id FACEBOOK-CLIENT-ID :client-secret FACEBOOK-CLIENT-SECRET :callback-url (str "http://" WWW-EXTERNAL-DOMAIN "/authcb/facebook") :profile-fields ["id" "PI:KEY:<KEY>END_PI" "photos" "email" "name"] :enableProof true} :google-auth {:client-id GOOGLE-CLIENT-ID :client-secret GOOGLE-CLIENT-SECRET :callback-url (str "http://" WWW-EXTERNAL-DOMAIN "/authcb/google")}}) (def cors-options (clj->js {:origin (str "http://" WWW-EXTERNAL-DOMAIN) :credentials true :allowedHeaders "Authorization,Origin,X-Requested-With,Content-Type,Accept"})) (def AWS-ACCESS-KEY-ID (.. nodejs/process -env -AWS_ACCESS_KEY_ID)) (def AWS-SECRET-ACCESS-KEY (.. nodejs/process -env -AWS_SECRET_ACCESS_KEY)) (def AWS-REGION (.. nodejs/process -env -AWS_REGION)) (def AWS-CONFIG {:accessKeyId AWS-ACCESS-KEY-ID :secretAccessKey AWS-SECRET-ACCESS-KEY :region AWS-REGION}) (def RABBITMQ-ENDPOINT (if IS-PRODUCTION (str "amqp://" RABBITMQ-USER ":" RABBITMQ-PASSWORD "@" RABBITMQ-DOMAIN "/" RABBITMQ-USER) (str "amqp://" RABBITMQ-DOMAIN ":" RABBITMQ-PORT))) (def LOGGER (create-logger (clj->js LOGGER-CONFIG)))
[ { "context": "onDomain]))))}])\n\n(def ^:private persistence-key \"workspace-table-types\")\n(def ^:private VERSION 2)\n\n\n(defn- union-tags [", "end": 7967, "score": 0.921136736869812, "start": 7946, "tag": "KEY", "value": "workspace-table-types" } ]
src/cljs/main/broadfcui/page/workspaces_list.cljs
epam/firecloud-ui
0
(ns broadfcui.page.workspaces-list (:require [dmohs.react :as react] [clojure.string :as string] [broadfcui.common :as common] [broadfcui.common.components :as comps] [broadfcui.common.filter :as filter] [broadfcui.common.flex-utils :as flex] [broadfcui.common.icons :as icons] [broadfcui.common.links :as links] [broadfcui.common.style :as style] [broadfcui.common.table :refer [Table]] [broadfcui.common.table.style :as table-style] [broadfcui.components.buttons :as buttons] [broadfcui.components.foundation-dropdown :as dropdown] [broadfcui.components.modals :as modals] [broadfcui.config :as config] [broadfcui.endpoints :as endpoints] [broadfcui.nav :as nav] [broadfcui.net :as net] [broadfcui.page.workspace.create :as create] [broadfcui.persistence :as persistence] [broadfcui.utils :as utils] )) (def row-height-px 56) (def tcga-disabled-text (str "This workspace contains controlled access data. You can only access the contents of this workspace if you are " "dbGaP authorized for TCGA data and have linked your FireCloud account to your eRA Commons account.")) (def non-dbGap-disabled-text "Click to request access.") (react/defc- RequestAuthDomainAccessDialog {:render (fn [{:keys [state this props]}] [modals/OKCancelForm {:header "Request Access" :cancel-text "Done" :dismiss (:dismiss props) :content (let [{:keys [my-groups ws-instructions error]} @state] (cond (not (or (and my-groups ws-instructions) error)) [comps/Spinner {:text "Loading Authorization Domain..."}] error (case (:code error) (:unknown :parse-error) [:div {:style {:color (:exception-state style/colors)}} "Error:" [:div {} (:details error)]] [comps/ErrorViewer {:error (:details error)}]) :else [:div {:style {:width 750}} [:div {} "You cannot access this Workspace because it contains restricted data. You need permission from the admin(s) of all of the Groups in the Authorization Domain protecting the workspace."] (let [simple-th (fn [text] [:th {:style {:textAlign "left" :padding "0 0.5rem" :borderBottom style/standard-line}} text]) simple-td (fn [text] [:td {} [:label {:style {:display "block" :padding "1rem 0.5rem"}} text]]) instructions (reduce (fn [m ad] (assoc m (keyword (:groupName ad)) (:instructions ad))) {} ws-instructions)] [:table {:style {:width "100%" :borderCollapse "collapse" :margin "1em 0 1em 0"}} [:thead {} [:tr {} (simple-th "Group Name") (simple-th "Access")]] [:tbody {} (map-indexed (fn [i auth-domain] (let [{:keys [member? requested? requesting?]} (:data auth-domain) name (:name auth-domain) instruction ((keyword name) instructions)] [:tr {} (simple-td name) [:td {:style {:width "50%"}} (if member? "Yes" (if instruction [:div {} "Learn how to apply for this Group " (links/create-external {:href instruction} "here") "."] [:div {} [buttons/Button {:style {:width "125px"} :disabled? (or requested? requesting?) :text (if requested? "Request Sent" "Request Access") :onClick #(this :-request-access name i)}] (when requesting? [comps/Spinner]) (when requested? (dropdown/render-info-box {:text [:div {} "Your request has been submitted. When you are granted access, the " [:strong {} "Access Level"] " displayed on the Workspace list will be updated."]}))]))]])) (:ws-auth-domain-groups @state))]])]))}]) :component-did-mount (fn [{:keys [this]}] (this :-load-groups) (this :-get-access-instructions)) :-load-groups (fn [{:keys [props state]}] (endpoints/get-groups (fn [err-text groups] (if err-text (swap! state assoc :error-message err-text) (let [my-groups (map :groupName groups)] (swap! state assoc :ws-auth-domain-groups (mapv (fn [group] {:name group :data {:member? (contains? (set my-groups) group)}}) (:ws-auth-domain-groups props))) (swap! state assoc :my-groups my-groups)))))) :-get-access-instructions (fn [{:keys [props state]}] (endpoints/get-ws-access-instructions (:workspace-id props) (fn [err-text instructions] (if err-text (swap! state assoc :error-message err-text) (swap! state assoc :ws-instructions instructions))))) :-request-access (fn [{:keys [state]} group-name group-index] (swap! state update-in [:ws-auth-domain-groups group-index :data] assoc :requesting? true) (endpoints/call-ajax-orch {:endpoint (endpoints/request-group-access group-name) :on-done (fn [] (swap! state update-in [:ws-auth-domain-groups group-index :data] assoc :requesting? nil :requested? true))}))}) (defn- get-workspace-name-string [column-data] (str (get-in column-data [:workspace-id :namespace]) "/" (get-in column-data [:workspace-id :name]))) (defn- get-workspace-description [ws] (not-empty (get-in ws [:workspace :attributes :description]))) (def ^:private access-levels ["PROJECT_OWNER" "OWNER" "WRITER" "READER" "NO ACCESS"]) (def ^:private access-levels-sortorder (zipmap access-levels (range))) (def ^:private table-filters [{:title "Status" :options ["Complete" "Running" "Exception"] :render identity :predicate (fn [ws option] (= (:status ws) option))} {:title "Access" :options access-levels :render style/prettify-access-level :predicate (fn [ws option] (= (:accessLevel ws) option))} {:title "Publishing" :options [true false] :render #(if % "Published" "Un-published") :predicate (fn [ws option] (= option (boolean (get-in ws [:workspace :attributes :library:published]))))} {:title "TCGA Access" :options [:open :protected] :render #(if (= % :open) "TCGA Open Access" "TCGA Controlled Access") :predicate (fn [ws option] (and (= (config/tcga-namespace) (get-in ws [:workspace :namespace])) ((if (= option :open) empty? seq) (get-in ws [:workspace :authorizationDomain]))))}]) (def ^:private persistence-key "workspace-table-types") (def ^:private VERSION 2) (defn- union-tags [workspaces] (->> workspaces (keep #(some-> % :workspace :attributes :tag:tags :items set)) (apply clojure.set/union))) (defn- attach-table-data [featured-workspaces {:keys [accessLevel workspace status] :as ws}] (let [workspace-id (select-keys workspace [:namespace :name]) no-access? (= accessLevel "NO ACCESS") auth-domain (:authorizationDomain workspace) domain-groups (map :membersGroupName auth-domain)] (assoc ws :workspace-id workspace-id :workspace-column-sort-value (mapv string/lower-case (replace workspace-id [:namespace :name])) :access-level-index (get access-levels-sortorder accessLevel) :status status :auth-domain-groups domain-groups :no-access? no-access? :access-level accessLevel :hover-text (when no-access? (if (contains? domain-groups config/tcga-authorization-domain) tcga-disabled-text non-dbGap-disabled-text)) :restricted? (seq auth-domain) :featured? (contains? featured-workspaces workspace-id)))) (react/defc- WorkspaceTable {:get-initial-state (fn [] (persistence/try-restore {:key persistence-key :initial (fn [] {:v VERSION :filters-expanded? true :filters (into {"Tags" []} (map (fn [{:keys [title]}] [title #{}]) table-filters))}) :validator (comp (partial = VERSION) :v)})) :component-will-mount (fn [{:keys [props locals]}] (swap! locals assoc :tags (union-tags (:workspaces props)) :total-count (count (:workspaces props)))) :render (fn [{:keys [props state this locals]}] (let [{:keys [filters-expanded? request-access-modal-props]} @state] [:div {} (when request-access-modal-props [:div {:data-test-id "request-access-modal"} [RequestAuthDomainAccessDialog (assoc request-access-modal-props :dismiss #(swap! state dissoc :request-access-modal-props))]]) [Table {:data-test-id "workspace-list" :persistence-key "workspace-table" :v 3 :data (this :-filter-workspaces) :total-count (:total-count @locals) :tabs {:style {:backgroundColor (:background-light style/colors) :margin "-0.6rem -1rem 0.3rem" :paddingLeft "1rem"} :items [{:label "My Workspaces" :predicate (fn [{:keys [public accessLevel]}] (or (not public) (common/access-greater-than-equal-to? accessLevel "WRITER")))} {:label "Public Workspaces" :predicate :public} {:label "Featured Workspaces" :predicate :featured?}]} :style {:content {:paddingLeft "1rem" :paddingRight "1rem"}} :body {:columns ;; All of this margining is terrible, but since this table ;; will be redesigned soon I'm leaving it as-is. [{:id "Status" :header [:span {:style {:marginLeft 7}} "Status"] :sortable? false :resizable? false :filterable? false :initial-width row-height-px :as-text :status :render #(this :-render-status-cell %)} {:id "Workspace" :header [:span {:style {:marginLeft 24}} "Workspace"] :initial-width 300 :as-text get-workspace-name-string :sort-by :workspace-column-sort-value :render #(this :-render-workspace-cell %)} {:id "Description" :header [:span {:style {:marginLeft 14}} "Description"] :initial-width 350 :column-data get-workspace-description :render (fn [description] [:div {:style {:paddingLeft 14}} (if description (-> description string/split-lines first) [:span {:style {:fontStyle "italic"}} "No description provided"])])} {:id "Last Modified" :header [:span {:style {:marginLeft 14}} "Last Modified"] :filterable? false :initial-width 200 :column-data (comp :lastModified :workspace) :render (fn [date] [:div {:style {:paddingLeft 14}} (common/format-date date common/short-date-format)]) :as-text common/format-date} {:id "Access Level" :header [:span {:style {:marginLeft 14}} "Access Level"] :initial-width 132 :resizable? false :filterable? false :as-text (comp style/prettify-access-level :access-level) :sort-by :access-level-index :sort-initial :asc :render (fn [{:keys [access-level workspace-id auth-domain-groups]}] [:div {:style {:paddingLeft 14}} (if (= access-level "NO ACCESS") (links/create-internal {:onClick #(this :-show-request-access-modal workspace-id auth-domain-groups)} (style/prettify-access-level access-level)) (style/prettify-access-level access-level))])}] :behavior {:reorderable-columns? false} :style {:header-row {:color (:text-lighter style/colors) :fontSize "90%"} :header-cell {:padding "0.4rem 0"} :resize-tab (table-style/tab :line-default) :body {:border style/standard-line} :body-row (fn [{:keys [index]}] (merge {:alignItems "center"} (when (pos? index) {:borderTop style/standard-line}))) :cell table-style/clip-text}} :toolbar {:filter-bar {:inner {:width 300}} :style {:padding "1rem" :margin 0 :backgroundColor (:background-light style/colors)} :get-items (constantly [(links/create-internal {:onClick #(swap! state update :filters-expanded? not)} (if filters-expanded? "Collapse filters" "Expand filters")) flex/spring [create/Button (select-keys props [:nav-context :billing-projects :disabled-reason])]])} :sidebar (when filters-expanded? (this :-render-side-filters))}]])) :component-did-update (fn [{:keys [state]}] (persistence/save {:key persistence-key :state state})) :-show-request-access-modal (fn [{:keys [state]} workspace-id auth-domain-groups] (swap! state assoc :request-access-modal-props {:workspace-id workspace-id :ws-auth-domain-groups auth-domain-groups})) :-render-status-cell (fn [{:keys [this]} {:keys [status no-access? hover-text workspace-id auth-domain-groups]}] [:a {:href (if no-access? "javascript:;" (nav/get-link :workspace-summary workspace-id)) :onClick (if no-access? #(this :-show-request-access-modal workspace-id auth-domain-groups)) :style {:display "block" :position "relative" :backgroundColor (if no-access? (:disabled-state style/colors) (style/color-for-status status)) :margin "2px 0 2px 2px" :height (- row-height-px 4)} :title hover-text} [:span {:style {:position "absolute" :top 0 :right 0 :bottom 0 :left 0 :backgroundColor "rgba(0,0,0,0.2)"}}] (style/center {} (case status "Complete" [icons/CompleteIcon] "Running" [icons/RunningIcon] "Exception" [icons/ExceptionIcon]))]) :-render-workspace-cell (fn [{:keys [this]} {:keys [status restricted? no-access? hover-text workspace-id auth-domain-groups]}] (let [{:keys [namespace name]} workspace-id color (style/color-for-status status)] [:a {:data-test-id (str namespace "-" name "-workspace-link") :href (if no-access? "javascript:;" (nav/get-link :workspace-summary workspace-id)) :onClick (if no-access? #(this :-show-request-access-modal workspace-id auth-domain-groups)) :style {:display "flex" :alignItems "center" :backgroundColor (if no-access? (:disabled-state style/colors) color) :color "white" :textDecoration "none" :height (- row-height-px 4) :margin "2px 0"} :title hover-text} (when restricted? [:span {:style {:display "block" :position "relative"}} [:span {:style {:display "block" :position "absolute" :left -17 :top -9 :width (- row-height-px 4) :padding "4px 0" :backgroundColor "white" :color "#666" :fontSize "xx-small" :transform "rotate(-90deg)"} :data-test-id (str "restricted-" namespace "-" name)} "RESTRICTED"]]) [:div {:style {:paddingLeft 24}} [:div {:style {:fontSize "80%"}} namespace] [:div {:style {:fontWeight 600}} name]]])) :-render-side-filters (fn [{:keys [state refs locals]}] (let [{:keys [filters]} @state] (apply filter/area {:style {:flex "0 0 175px" :marginTop -12}} (filter/section {:title "Tags" :content (react/create-element [comps/TagAutocomplete {:ref "tag-autocomplete" :tags (filters "Tags") :data (:tags @locals) :show-counts? false :allow-new? false :on-change #(swap! state update :filters assoc "Tags" %)}]) :on-clear #((@refs "tag-autocomplete") :set-tags [])}) (map (fn [{:keys [title options render]}] (filter/section {:title title :content (filter/checkboxes {:items (map (fn [option] {:item option :render render}) options) :checked-items (get-in @state [:filters title]) :on-change (fn [item checked?] (swap! state update-in [:filters title] (if checked? conj disj) item))}) :on-clear #(swap! state update-in [:filters title] empty)})) table-filters)))) :-filter-workspaces (fn [{:keys [props state]}] (let [{:keys [workspaces]} props {:keys [filters]} @state checkbox-filters (map (fn [{:keys [title predicate]}] (let [selected (filters title)] (if (empty? selected) (constantly true) (apply some-fn (map (fn [option] (fn [ws] (predicate ws option))) selected))))) table-filters) selected-tags (filters "Tags") tag-filter (if (empty? selected-tags) (constantly true) (fn [ws] (let [ws-tags (set (get-in ws [:workspace :attributes :tag:tags :items]))] (every? (partial contains? ws-tags) selected-tags))))] (->> workspaces (filter (apply every-pred tag-filter checkbox-filters)) (map (partial attach-table-data (:featured-workspaces props))))))}) (react/defc- WorkspaceList {:get-initial-state (fn [] {:server-response {:disabled-reason :not-loaded}}) :render (fn [{:keys [props state]}] (let [{:keys [server-response]} @state workspaces (map (fn [ws] (assoc ws :status (common/compute-status ws))) (get-in server-response [:workspaces-response :parsed-response])) {:keys [billing-projects disabled-reason featured-workspaces]} server-response] (net/render-with-ajax (:workspaces-response server-response) (fn [] [WorkspaceTable (merge props (utils/restructure workspaces billing-projects disabled-reason featured-workspaces))]) {:loading-text "Loading workspaces..." :rephrase-error #(get-in % [:parsed-response :workspaces :error-message])}))) :component-did-mount (fn [{:keys [state]}] (endpoints/call-ajax-orch {:endpoint endpoints/list-workspaces :on-done (net/handle-ajax-response #(swap! state update :server-response assoc :workspaces-response %))}) (endpoints/get-billing-projects (fn [err-text projects] (if err-text (swap! state update :server-response assoc :error-message err-text :disabled-reason :error) (swap! state update :server-response assoc :billing-projects (map :projectName projects) :disabled-reason (when (empty? projects) :no-billing))))) (utils/ajax {:url (config/featured-json-url) :on-done (fn [{:keys [raw-response]}] (swap! state update :server-response assoc :featured-workspaces (set (let [[parsed _] (utils/parse-json-string raw-response true false)] parsed))))}))}) ; Simply show no featured workspaces if file is absent or contains invalid JSON (defn add-nav-paths [] (nav/defredirect {:regex #"workspaces" :make-path (fn [] "")}) (nav/defpath :workspaces {:component WorkspaceList :regex #"" :make-props (fn [] {}) :make-path (fn [] "")}))
3713
(ns broadfcui.page.workspaces-list (:require [dmohs.react :as react] [clojure.string :as string] [broadfcui.common :as common] [broadfcui.common.components :as comps] [broadfcui.common.filter :as filter] [broadfcui.common.flex-utils :as flex] [broadfcui.common.icons :as icons] [broadfcui.common.links :as links] [broadfcui.common.style :as style] [broadfcui.common.table :refer [Table]] [broadfcui.common.table.style :as table-style] [broadfcui.components.buttons :as buttons] [broadfcui.components.foundation-dropdown :as dropdown] [broadfcui.components.modals :as modals] [broadfcui.config :as config] [broadfcui.endpoints :as endpoints] [broadfcui.nav :as nav] [broadfcui.net :as net] [broadfcui.page.workspace.create :as create] [broadfcui.persistence :as persistence] [broadfcui.utils :as utils] )) (def row-height-px 56) (def tcga-disabled-text (str "This workspace contains controlled access data. You can only access the contents of this workspace if you are " "dbGaP authorized for TCGA data and have linked your FireCloud account to your eRA Commons account.")) (def non-dbGap-disabled-text "Click to request access.") (react/defc- RequestAuthDomainAccessDialog {:render (fn [{:keys [state this props]}] [modals/OKCancelForm {:header "Request Access" :cancel-text "Done" :dismiss (:dismiss props) :content (let [{:keys [my-groups ws-instructions error]} @state] (cond (not (or (and my-groups ws-instructions) error)) [comps/Spinner {:text "Loading Authorization Domain..."}] error (case (:code error) (:unknown :parse-error) [:div {:style {:color (:exception-state style/colors)}} "Error:" [:div {} (:details error)]] [comps/ErrorViewer {:error (:details error)}]) :else [:div {:style {:width 750}} [:div {} "You cannot access this Workspace because it contains restricted data. You need permission from the admin(s) of all of the Groups in the Authorization Domain protecting the workspace."] (let [simple-th (fn [text] [:th {:style {:textAlign "left" :padding "0 0.5rem" :borderBottom style/standard-line}} text]) simple-td (fn [text] [:td {} [:label {:style {:display "block" :padding "1rem 0.5rem"}} text]]) instructions (reduce (fn [m ad] (assoc m (keyword (:groupName ad)) (:instructions ad))) {} ws-instructions)] [:table {:style {:width "100%" :borderCollapse "collapse" :margin "1em 0 1em 0"}} [:thead {} [:tr {} (simple-th "Group Name") (simple-th "Access")]] [:tbody {} (map-indexed (fn [i auth-domain] (let [{:keys [member? requested? requesting?]} (:data auth-domain) name (:name auth-domain) instruction ((keyword name) instructions)] [:tr {} (simple-td name) [:td {:style {:width "50%"}} (if member? "Yes" (if instruction [:div {} "Learn how to apply for this Group " (links/create-external {:href instruction} "here") "."] [:div {} [buttons/Button {:style {:width "125px"} :disabled? (or requested? requesting?) :text (if requested? "Request Sent" "Request Access") :onClick #(this :-request-access name i)}] (when requesting? [comps/Spinner]) (when requested? (dropdown/render-info-box {:text [:div {} "Your request has been submitted. When you are granted access, the " [:strong {} "Access Level"] " displayed on the Workspace list will be updated."]}))]))]])) (:ws-auth-domain-groups @state))]])]))}]) :component-did-mount (fn [{:keys [this]}] (this :-load-groups) (this :-get-access-instructions)) :-load-groups (fn [{:keys [props state]}] (endpoints/get-groups (fn [err-text groups] (if err-text (swap! state assoc :error-message err-text) (let [my-groups (map :groupName groups)] (swap! state assoc :ws-auth-domain-groups (mapv (fn [group] {:name group :data {:member? (contains? (set my-groups) group)}}) (:ws-auth-domain-groups props))) (swap! state assoc :my-groups my-groups)))))) :-get-access-instructions (fn [{:keys [props state]}] (endpoints/get-ws-access-instructions (:workspace-id props) (fn [err-text instructions] (if err-text (swap! state assoc :error-message err-text) (swap! state assoc :ws-instructions instructions))))) :-request-access (fn [{:keys [state]} group-name group-index] (swap! state update-in [:ws-auth-domain-groups group-index :data] assoc :requesting? true) (endpoints/call-ajax-orch {:endpoint (endpoints/request-group-access group-name) :on-done (fn [] (swap! state update-in [:ws-auth-domain-groups group-index :data] assoc :requesting? nil :requested? true))}))}) (defn- get-workspace-name-string [column-data] (str (get-in column-data [:workspace-id :namespace]) "/" (get-in column-data [:workspace-id :name]))) (defn- get-workspace-description [ws] (not-empty (get-in ws [:workspace :attributes :description]))) (def ^:private access-levels ["PROJECT_OWNER" "OWNER" "WRITER" "READER" "NO ACCESS"]) (def ^:private access-levels-sortorder (zipmap access-levels (range))) (def ^:private table-filters [{:title "Status" :options ["Complete" "Running" "Exception"] :render identity :predicate (fn [ws option] (= (:status ws) option))} {:title "Access" :options access-levels :render style/prettify-access-level :predicate (fn [ws option] (= (:accessLevel ws) option))} {:title "Publishing" :options [true false] :render #(if % "Published" "Un-published") :predicate (fn [ws option] (= option (boolean (get-in ws [:workspace :attributes :library:published]))))} {:title "TCGA Access" :options [:open :protected] :render #(if (= % :open) "TCGA Open Access" "TCGA Controlled Access") :predicate (fn [ws option] (and (= (config/tcga-namespace) (get-in ws [:workspace :namespace])) ((if (= option :open) empty? seq) (get-in ws [:workspace :authorizationDomain]))))}]) (def ^:private persistence-key "<KEY>") (def ^:private VERSION 2) (defn- union-tags [workspaces] (->> workspaces (keep #(some-> % :workspace :attributes :tag:tags :items set)) (apply clojure.set/union))) (defn- attach-table-data [featured-workspaces {:keys [accessLevel workspace status] :as ws}] (let [workspace-id (select-keys workspace [:namespace :name]) no-access? (= accessLevel "NO ACCESS") auth-domain (:authorizationDomain workspace) domain-groups (map :membersGroupName auth-domain)] (assoc ws :workspace-id workspace-id :workspace-column-sort-value (mapv string/lower-case (replace workspace-id [:namespace :name])) :access-level-index (get access-levels-sortorder accessLevel) :status status :auth-domain-groups domain-groups :no-access? no-access? :access-level accessLevel :hover-text (when no-access? (if (contains? domain-groups config/tcga-authorization-domain) tcga-disabled-text non-dbGap-disabled-text)) :restricted? (seq auth-domain) :featured? (contains? featured-workspaces workspace-id)))) (react/defc- WorkspaceTable {:get-initial-state (fn [] (persistence/try-restore {:key persistence-key :initial (fn [] {:v VERSION :filters-expanded? true :filters (into {"Tags" []} (map (fn [{:keys [title]}] [title #{}]) table-filters))}) :validator (comp (partial = VERSION) :v)})) :component-will-mount (fn [{:keys [props locals]}] (swap! locals assoc :tags (union-tags (:workspaces props)) :total-count (count (:workspaces props)))) :render (fn [{:keys [props state this locals]}] (let [{:keys [filters-expanded? request-access-modal-props]} @state] [:div {} (when request-access-modal-props [:div {:data-test-id "request-access-modal"} [RequestAuthDomainAccessDialog (assoc request-access-modal-props :dismiss #(swap! state dissoc :request-access-modal-props))]]) [Table {:data-test-id "workspace-list" :persistence-key "workspace-table" :v 3 :data (this :-filter-workspaces) :total-count (:total-count @locals) :tabs {:style {:backgroundColor (:background-light style/colors) :margin "-0.6rem -1rem 0.3rem" :paddingLeft "1rem"} :items [{:label "My Workspaces" :predicate (fn [{:keys [public accessLevel]}] (or (not public) (common/access-greater-than-equal-to? accessLevel "WRITER")))} {:label "Public Workspaces" :predicate :public} {:label "Featured Workspaces" :predicate :featured?}]} :style {:content {:paddingLeft "1rem" :paddingRight "1rem"}} :body {:columns ;; All of this margining is terrible, but since this table ;; will be redesigned soon I'm leaving it as-is. [{:id "Status" :header [:span {:style {:marginLeft 7}} "Status"] :sortable? false :resizable? false :filterable? false :initial-width row-height-px :as-text :status :render #(this :-render-status-cell %)} {:id "Workspace" :header [:span {:style {:marginLeft 24}} "Workspace"] :initial-width 300 :as-text get-workspace-name-string :sort-by :workspace-column-sort-value :render #(this :-render-workspace-cell %)} {:id "Description" :header [:span {:style {:marginLeft 14}} "Description"] :initial-width 350 :column-data get-workspace-description :render (fn [description] [:div {:style {:paddingLeft 14}} (if description (-> description string/split-lines first) [:span {:style {:fontStyle "italic"}} "No description provided"])])} {:id "Last Modified" :header [:span {:style {:marginLeft 14}} "Last Modified"] :filterable? false :initial-width 200 :column-data (comp :lastModified :workspace) :render (fn [date] [:div {:style {:paddingLeft 14}} (common/format-date date common/short-date-format)]) :as-text common/format-date} {:id "Access Level" :header [:span {:style {:marginLeft 14}} "Access Level"] :initial-width 132 :resizable? false :filterable? false :as-text (comp style/prettify-access-level :access-level) :sort-by :access-level-index :sort-initial :asc :render (fn [{:keys [access-level workspace-id auth-domain-groups]}] [:div {:style {:paddingLeft 14}} (if (= access-level "NO ACCESS") (links/create-internal {:onClick #(this :-show-request-access-modal workspace-id auth-domain-groups)} (style/prettify-access-level access-level)) (style/prettify-access-level access-level))])}] :behavior {:reorderable-columns? false} :style {:header-row {:color (:text-lighter style/colors) :fontSize "90%"} :header-cell {:padding "0.4rem 0"} :resize-tab (table-style/tab :line-default) :body {:border style/standard-line} :body-row (fn [{:keys [index]}] (merge {:alignItems "center"} (when (pos? index) {:borderTop style/standard-line}))) :cell table-style/clip-text}} :toolbar {:filter-bar {:inner {:width 300}} :style {:padding "1rem" :margin 0 :backgroundColor (:background-light style/colors)} :get-items (constantly [(links/create-internal {:onClick #(swap! state update :filters-expanded? not)} (if filters-expanded? "Collapse filters" "Expand filters")) flex/spring [create/Button (select-keys props [:nav-context :billing-projects :disabled-reason])]])} :sidebar (when filters-expanded? (this :-render-side-filters))}]])) :component-did-update (fn [{:keys [state]}] (persistence/save {:key persistence-key :state state})) :-show-request-access-modal (fn [{:keys [state]} workspace-id auth-domain-groups] (swap! state assoc :request-access-modal-props {:workspace-id workspace-id :ws-auth-domain-groups auth-domain-groups})) :-render-status-cell (fn [{:keys [this]} {:keys [status no-access? hover-text workspace-id auth-domain-groups]}] [:a {:href (if no-access? "javascript:;" (nav/get-link :workspace-summary workspace-id)) :onClick (if no-access? #(this :-show-request-access-modal workspace-id auth-domain-groups)) :style {:display "block" :position "relative" :backgroundColor (if no-access? (:disabled-state style/colors) (style/color-for-status status)) :margin "2px 0 2px 2px" :height (- row-height-px 4)} :title hover-text} [:span {:style {:position "absolute" :top 0 :right 0 :bottom 0 :left 0 :backgroundColor "rgba(0,0,0,0.2)"}}] (style/center {} (case status "Complete" [icons/CompleteIcon] "Running" [icons/RunningIcon] "Exception" [icons/ExceptionIcon]))]) :-render-workspace-cell (fn [{:keys [this]} {:keys [status restricted? no-access? hover-text workspace-id auth-domain-groups]}] (let [{:keys [namespace name]} workspace-id color (style/color-for-status status)] [:a {:data-test-id (str namespace "-" name "-workspace-link") :href (if no-access? "javascript:;" (nav/get-link :workspace-summary workspace-id)) :onClick (if no-access? #(this :-show-request-access-modal workspace-id auth-domain-groups)) :style {:display "flex" :alignItems "center" :backgroundColor (if no-access? (:disabled-state style/colors) color) :color "white" :textDecoration "none" :height (- row-height-px 4) :margin "2px 0"} :title hover-text} (when restricted? [:span {:style {:display "block" :position "relative"}} [:span {:style {:display "block" :position "absolute" :left -17 :top -9 :width (- row-height-px 4) :padding "4px 0" :backgroundColor "white" :color "#666" :fontSize "xx-small" :transform "rotate(-90deg)"} :data-test-id (str "restricted-" namespace "-" name)} "RESTRICTED"]]) [:div {:style {:paddingLeft 24}} [:div {:style {:fontSize "80%"}} namespace] [:div {:style {:fontWeight 600}} name]]])) :-render-side-filters (fn [{:keys [state refs locals]}] (let [{:keys [filters]} @state] (apply filter/area {:style {:flex "0 0 175px" :marginTop -12}} (filter/section {:title "Tags" :content (react/create-element [comps/TagAutocomplete {:ref "tag-autocomplete" :tags (filters "Tags") :data (:tags @locals) :show-counts? false :allow-new? false :on-change #(swap! state update :filters assoc "Tags" %)}]) :on-clear #((@refs "tag-autocomplete") :set-tags [])}) (map (fn [{:keys [title options render]}] (filter/section {:title title :content (filter/checkboxes {:items (map (fn [option] {:item option :render render}) options) :checked-items (get-in @state [:filters title]) :on-change (fn [item checked?] (swap! state update-in [:filters title] (if checked? conj disj) item))}) :on-clear #(swap! state update-in [:filters title] empty)})) table-filters)))) :-filter-workspaces (fn [{:keys [props state]}] (let [{:keys [workspaces]} props {:keys [filters]} @state checkbox-filters (map (fn [{:keys [title predicate]}] (let [selected (filters title)] (if (empty? selected) (constantly true) (apply some-fn (map (fn [option] (fn [ws] (predicate ws option))) selected))))) table-filters) selected-tags (filters "Tags") tag-filter (if (empty? selected-tags) (constantly true) (fn [ws] (let [ws-tags (set (get-in ws [:workspace :attributes :tag:tags :items]))] (every? (partial contains? ws-tags) selected-tags))))] (->> workspaces (filter (apply every-pred tag-filter checkbox-filters)) (map (partial attach-table-data (:featured-workspaces props))))))}) (react/defc- WorkspaceList {:get-initial-state (fn [] {:server-response {:disabled-reason :not-loaded}}) :render (fn [{:keys [props state]}] (let [{:keys [server-response]} @state workspaces (map (fn [ws] (assoc ws :status (common/compute-status ws))) (get-in server-response [:workspaces-response :parsed-response])) {:keys [billing-projects disabled-reason featured-workspaces]} server-response] (net/render-with-ajax (:workspaces-response server-response) (fn [] [WorkspaceTable (merge props (utils/restructure workspaces billing-projects disabled-reason featured-workspaces))]) {:loading-text "Loading workspaces..." :rephrase-error #(get-in % [:parsed-response :workspaces :error-message])}))) :component-did-mount (fn [{:keys [state]}] (endpoints/call-ajax-orch {:endpoint endpoints/list-workspaces :on-done (net/handle-ajax-response #(swap! state update :server-response assoc :workspaces-response %))}) (endpoints/get-billing-projects (fn [err-text projects] (if err-text (swap! state update :server-response assoc :error-message err-text :disabled-reason :error) (swap! state update :server-response assoc :billing-projects (map :projectName projects) :disabled-reason (when (empty? projects) :no-billing))))) (utils/ajax {:url (config/featured-json-url) :on-done (fn [{:keys [raw-response]}] (swap! state update :server-response assoc :featured-workspaces (set (let [[parsed _] (utils/parse-json-string raw-response true false)] parsed))))}))}) ; Simply show no featured workspaces if file is absent or contains invalid JSON (defn add-nav-paths [] (nav/defredirect {:regex #"workspaces" :make-path (fn [] "")}) (nav/defpath :workspaces {:component WorkspaceList :regex #"" :make-props (fn [] {}) :make-path (fn [] "")}))
true
(ns broadfcui.page.workspaces-list (:require [dmohs.react :as react] [clojure.string :as string] [broadfcui.common :as common] [broadfcui.common.components :as comps] [broadfcui.common.filter :as filter] [broadfcui.common.flex-utils :as flex] [broadfcui.common.icons :as icons] [broadfcui.common.links :as links] [broadfcui.common.style :as style] [broadfcui.common.table :refer [Table]] [broadfcui.common.table.style :as table-style] [broadfcui.components.buttons :as buttons] [broadfcui.components.foundation-dropdown :as dropdown] [broadfcui.components.modals :as modals] [broadfcui.config :as config] [broadfcui.endpoints :as endpoints] [broadfcui.nav :as nav] [broadfcui.net :as net] [broadfcui.page.workspace.create :as create] [broadfcui.persistence :as persistence] [broadfcui.utils :as utils] )) (def row-height-px 56) (def tcga-disabled-text (str "This workspace contains controlled access data. You can only access the contents of this workspace if you are " "dbGaP authorized for TCGA data and have linked your FireCloud account to your eRA Commons account.")) (def non-dbGap-disabled-text "Click to request access.") (react/defc- RequestAuthDomainAccessDialog {:render (fn [{:keys [state this props]}] [modals/OKCancelForm {:header "Request Access" :cancel-text "Done" :dismiss (:dismiss props) :content (let [{:keys [my-groups ws-instructions error]} @state] (cond (not (or (and my-groups ws-instructions) error)) [comps/Spinner {:text "Loading Authorization Domain..."}] error (case (:code error) (:unknown :parse-error) [:div {:style {:color (:exception-state style/colors)}} "Error:" [:div {} (:details error)]] [comps/ErrorViewer {:error (:details error)}]) :else [:div {:style {:width 750}} [:div {} "You cannot access this Workspace because it contains restricted data. You need permission from the admin(s) of all of the Groups in the Authorization Domain protecting the workspace."] (let [simple-th (fn [text] [:th {:style {:textAlign "left" :padding "0 0.5rem" :borderBottom style/standard-line}} text]) simple-td (fn [text] [:td {} [:label {:style {:display "block" :padding "1rem 0.5rem"}} text]]) instructions (reduce (fn [m ad] (assoc m (keyword (:groupName ad)) (:instructions ad))) {} ws-instructions)] [:table {:style {:width "100%" :borderCollapse "collapse" :margin "1em 0 1em 0"}} [:thead {} [:tr {} (simple-th "Group Name") (simple-th "Access")]] [:tbody {} (map-indexed (fn [i auth-domain] (let [{:keys [member? requested? requesting?]} (:data auth-domain) name (:name auth-domain) instruction ((keyword name) instructions)] [:tr {} (simple-td name) [:td {:style {:width "50%"}} (if member? "Yes" (if instruction [:div {} "Learn how to apply for this Group " (links/create-external {:href instruction} "here") "."] [:div {} [buttons/Button {:style {:width "125px"} :disabled? (or requested? requesting?) :text (if requested? "Request Sent" "Request Access") :onClick #(this :-request-access name i)}] (when requesting? [comps/Spinner]) (when requested? (dropdown/render-info-box {:text [:div {} "Your request has been submitted. When you are granted access, the " [:strong {} "Access Level"] " displayed on the Workspace list will be updated."]}))]))]])) (:ws-auth-domain-groups @state))]])]))}]) :component-did-mount (fn [{:keys [this]}] (this :-load-groups) (this :-get-access-instructions)) :-load-groups (fn [{:keys [props state]}] (endpoints/get-groups (fn [err-text groups] (if err-text (swap! state assoc :error-message err-text) (let [my-groups (map :groupName groups)] (swap! state assoc :ws-auth-domain-groups (mapv (fn [group] {:name group :data {:member? (contains? (set my-groups) group)}}) (:ws-auth-domain-groups props))) (swap! state assoc :my-groups my-groups)))))) :-get-access-instructions (fn [{:keys [props state]}] (endpoints/get-ws-access-instructions (:workspace-id props) (fn [err-text instructions] (if err-text (swap! state assoc :error-message err-text) (swap! state assoc :ws-instructions instructions))))) :-request-access (fn [{:keys [state]} group-name group-index] (swap! state update-in [:ws-auth-domain-groups group-index :data] assoc :requesting? true) (endpoints/call-ajax-orch {:endpoint (endpoints/request-group-access group-name) :on-done (fn [] (swap! state update-in [:ws-auth-domain-groups group-index :data] assoc :requesting? nil :requested? true))}))}) (defn- get-workspace-name-string [column-data] (str (get-in column-data [:workspace-id :namespace]) "/" (get-in column-data [:workspace-id :name]))) (defn- get-workspace-description [ws] (not-empty (get-in ws [:workspace :attributes :description]))) (def ^:private access-levels ["PROJECT_OWNER" "OWNER" "WRITER" "READER" "NO ACCESS"]) (def ^:private access-levels-sortorder (zipmap access-levels (range))) (def ^:private table-filters [{:title "Status" :options ["Complete" "Running" "Exception"] :render identity :predicate (fn [ws option] (= (:status ws) option))} {:title "Access" :options access-levels :render style/prettify-access-level :predicate (fn [ws option] (= (:accessLevel ws) option))} {:title "Publishing" :options [true false] :render #(if % "Published" "Un-published") :predicate (fn [ws option] (= option (boolean (get-in ws [:workspace :attributes :library:published]))))} {:title "TCGA Access" :options [:open :protected] :render #(if (= % :open) "TCGA Open Access" "TCGA Controlled Access") :predicate (fn [ws option] (and (= (config/tcga-namespace) (get-in ws [:workspace :namespace])) ((if (= option :open) empty? seq) (get-in ws [:workspace :authorizationDomain]))))}]) (def ^:private persistence-key "PI:KEY:<KEY>END_PI") (def ^:private VERSION 2) (defn- union-tags [workspaces] (->> workspaces (keep #(some-> % :workspace :attributes :tag:tags :items set)) (apply clojure.set/union))) (defn- attach-table-data [featured-workspaces {:keys [accessLevel workspace status] :as ws}] (let [workspace-id (select-keys workspace [:namespace :name]) no-access? (= accessLevel "NO ACCESS") auth-domain (:authorizationDomain workspace) domain-groups (map :membersGroupName auth-domain)] (assoc ws :workspace-id workspace-id :workspace-column-sort-value (mapv string/lower-case (replace workspace-id [:namespace :name])) :access-level-index (get access-levels-sortorder accessLevel) :status status :auth-domain-groups domain-groups :no-access? no-access? :access-level accessLevel :hover-text (when no-access? (if (contains? domain-groups config/tcga-authorization-domain) tcga-disabled-text non-dbGap-disabled-text)) :restricted? (seq auth-domain) :featured? (contains? featured-workspaces workspace-id)))) (react/defc- WorkspaceTable {:get-initial-state (fn [] (persistence/try-restore {:key persistence-key :initial (fn [] {:v VERSION :filters-expanded? true :filters (into {"Tags" []} (map (fn [{:keys [title]}] [title #{}]) table-filters))}) :validator (comp (partial = VERSION) :v)})) :component-will-mount (fn [{:keys [props locals]}] (swap! locals assoc :tags (union-tags (:workspaces props)) :total-count (count (:workspaces props)))) :render (fn [{:keys [props state this locals]}] (let [{:keys [filters-expanded? request-access-modal-props]} @state] [:div {} (when request-access-modal-props [:div {:data-test-id "request-access-modal"} [RequestAuthDomainAccessDialog (assoc request-access-modal-props :dismiss #(swap! state dissoc :request-access-modal-props))]]) [Table {:data-test-id "workspace-list" :persistence-key "workspace-table" :v 3 :data (this :-filter-workspaces) :total-count (:total-count @locals) :tabs {:style {:backgroundColor (:background-light style/colors) :margin "-0.6rem -1rem 0.3rem" :paddingLeft "1rem"} :items [{:label "My Workspaces" :predicate (fn [{:keys [public accessLevel]}] (or (not public) (common/access-greater-than-equal-to? accessLevel "WRITER")))} {:label "Public Workspaces" :predicate :public} {:label "Featured Workspaces" :predicate :featured?}]} :style {:content {:paddingLeft "1rem" :paddingRight "1rem"}} :body {:columns ;; All of this margining is terrible, but since this table ;; will be redesigned soon I'm leaving it as-is. [{:id "Status" :header [:span {:style {:marginLeft 7}} "Status"] :sortable? false :resizable? false :filterable? false :initial-width row-height-px :as-text :status :render #(this :-render-status-cell %)} {:id "Workspace" :header [:span {:style {:marginLeft 24}} "Workspace"] :initial-width 300 :as-text get-workspace-name-string :sort-by :workspace-column-sort-value :render #(this :-render-workspace-cell %)} {:id "Description" :header [:span {:style {:marginLeft 14}} "Description"] :initial-width 350 :column-data get-workspace-description :render (fn [description] [:div {:style {:paddingLeft 14}} (if description (-> description string/split-lines first) [:span {:style {:fontStyle "italic"}} "No description provided"])])} {:id "Last Modified" :header [:span {:style {:marginLeft 14}} "Last Modified"] :filterable? false :initial-width 200 :column-data (comp :lastModified :workspace) :render (fn [date] [:div {:style {:paddingLeft 14}} (common/format-date date common/short-date-format)]) :as-text common/format-date} {:id "Access Level" :header [:span {:style {:marginLeft 14}} "Access Level"] :initial-width 132 :resizable? false :filterable? false :as-text (comp style/prettify-access-level :access-level) :sort-by :access-level-index :sort-initial :asc :render (fn [{:keys [access-level workspace-id auth-domain-groups]}] [:div {:style {:paddingLeft 14}} (if (= access-level "NO ACCESS") (links/create-internal {:onClick #(this :-show-request-access-modal workspace-id auth-domain-groups)} (style/prettify-access-level access-level)) (style/prettify-access-level access-level))])}] :behavior {:reorderable-columns? false} :style {:header-row {:color (:text-lighter style/colors) :fontSize "90%"} :header-cell {:padding "0.4rem 0"} :resize-tab (table-style/tab :line-default) :body {:border style/standard-line} :body-row (fn [{:keys [index]}] (merge {:alignItems "center"} (when (pos? index) {:borderTop style/standard-line}))) :cell table-style/clip-text}} :toolbar {:filter-bar {:inner {:width 300}} :style {:padding "1rem" :margin 0 :backgroundColor (:background-light style/colors)} :get-items (constantly [(links/create-internal {:onClick #(swap! state update :filters-expanded? not)} (if filters-expanded? "Collapse filters" "Expand filters")) flex/spring [create/Button (select-keys props [:nav-context :billing-projects :disabled-reason])]])} :sidebar (when filters-expanded? (this :-render-side-filters))}]])) :component-did-update (fn [{:keys [state]}] (persistence/save {:key persistence-key :state state})) :-show-request-access-modal (fn [{:keys [state]} workspace-id auth-domain-groups] (swap! state assoc :request-access-modal-props {:workspace-id workspace-id :ws-auth-domain-groups auth-domain-groups})) :-render-status-cell (fn [{:keys [this]} {:keys [status no-access? hover-text workspace-id auth-domain-groups]}] [:a {:href (if no-access? "javascript:;" (nav/get-link :workspace-summary workspace-id)) :onClick (if no-access? #(this :-show-request-access-modal workspace-id auth-domain-groups)) :style {:display "block" :position "relative" :backgroundColor (if no-access? (:disabled-state style/colors) (style/color-for-status status)) :margin "2px 0 2px 2px" :height (- row-height-px 4)} :title hover-text} [:span {:style {:position "absolute" :top 0 :right 0 :bottom 0 :left 0 :backgroundColor "rgba(0,0,0,0.2)"}}] (style/center {} (case status "Complete" [icons/CompleteIcon] "Running" [icons/RunningIcon] "Exception" [icons/ExceptionIcon]))]) :-render-workspace-cell (fn [{:keys [this]} {:keys [status restricted? no-access? hover-text workspace-id auth-domain-groups]}] (let [{:keys [namespace name]} workspace-id color (style/color-for-status status)] [:a {:data-test-id (str namespace "-" name "-workspace-link") :href (if no-access? "javascript:;" (nav/get-link :workspace-summary workspace-id)) :onClick (if no-access? #(this :-show-request-access-modal workspace-id auth-domain-groups)) :style {:display "flex" :alignItems "center" :backgroundColor (if no-access? (:disabled-state style/colors) color) :color "white" :textDecoration "none" :height (- row-height-px 4) :margin "2px 0"} :title hover-text} (when restricted? [:span {:style {:display "block" :position "relative"}} [:span {:style {:display "block" :position "absolute" :left -17 :top -9 :width (- row-height-px 4) :padding "4px 0" :backgroundColor "white" :color "#666" :fontSize "xx-small" :transform "rotate(-90deg)"} :data-test-id (str "restricted-" namespace "-" name)} "RESTRICTED"]]) [:div {:style {:paddingLeft 24}} [:div {:style {:fontSize "80%"}} namespace] [:div {:style {:fontWeight 600}} name]]])) :-render-side-filters (fn [{:keys [state refs locals]}] (let [{:keys [filters]} @state] (apply filter/area {:style {:flex "0 0 175px" :marginTop -12}} (filter/section {:title "Tags" :content (react/create-element [comps/TagAutocomplete {:ref "tag-autocomplete" :tags (filters "Tags") :data (:tags @locals) :show-counts? false :allow-new? false :on-change #(swap! state update :filters assoc "Tags" %)}]) :on-clear #((@refs "tag-autocomplete") :set-tags [])}) (map (fn [{:keys [title options render]}] (filter/section {:title title :content (filter/checkboxes {:items (map (fn [option] {:item option :render render}) options) :checked-items (get-in @state [:filters title]) :on-change (fn [item checked?] (swap! state update-in [:filters title] (if checked? conj disj) item))}) :on-clear #(swap! state update-in [:filters title] empty)})) table-filters)))) :-filter-workspaces (fn [{:keys [props state]}] (let [{:keys [workspaces]} props {:keys [filters]} @state checkbox-filters (map (fn [{:keys [title predicate]}] (let [selected (filters title)] (if (empty? selected) (constantly true) (apply some-fn (map (fn [option] (fn [ws] (predicate ws option))) selected))))) table-filters) selected-tags (filters "Tags") tag-filter (if (empty? selected-tags) (constantly true) (fn [ws] (let [ws-tags (set (get-in ws [:workspace :attributes :tag:tags :items]))] (every? (partial contains? ws-tags) selected-tags))))] (->> workspaces (filter (apply every-pred tag-filter checkbox-filters)) (map (partial attach-table-data (:featured-workspaces props))))))}) (react/defc- WorkspaceList {:get-initial-state (fn [] {:server-response {:disabled-reason :not-loaded}}) :render (fn [{:keys [props state]}] (let [{:keys [server-response]} @state workspaces (map (fn [ws] (assoc ws :status (common/compute-status ws))) (get-in server-response [:workspaces-response :parsed-response])) {:keys [billing-projects disabled-reason featured-workspaces]} server-response] (net/render-with-ajax (:workspaces-response server-response) (fn [] [WorkspaceTable (merge props (utils/restructure workspaces billing-projects disabled-reason featured-workspaces))]) {:loading-text "Loading workspaces..." :rephrase-error #(get-in % [:parsed-response :workspaces :error-message])}))) :component-did-mount (fn [{:keys [state]}] (endpoints/call-ajax-orch {:endpoint endpoints/list-workspaces :on-done (net/handle-ajax-response #(swap! state update :server-response assoc :workspaces-response %))}) (endpoints/get-billing-projects (fn [err-text projects] (if err-text (swap! state update :server-response assoc :error-message err-text :disabled-reason :error) (swap! state update :server-response assoc :billing-projects (map :projectName projects) :disabled-reason (when (empty? projects) :no-billing))))) (utils/ajax {:url (config/featured-json-url) :on-done (fn [{:keys [raw-response]}] (swap! state update :server-response assoc :featured-workspaces (set (let [[parsed _] (utils/parse-json-string raw-response true false)] parsed))))}))}) ; Simply show no featured workspaces if file is absent or contains invalid JSON (defn add-nav-paths [] (nav/defredirect {:regex #"workspaces" :make-path (fn [] "")}) (nav/defpath :workspaces {:component WorkspaceList :regex #"" :make-props (fn [] {}) :make-path (fn [] "")}))
[ { "context": "m.com/v2/feeds/80428.csv\") {:headers {\"X-ApiKey\" \"MBhfc52ZUaa-DGD3cFtgcB1bmtSSAKwwWmRPR0RjRkJnND0g\"} :body (str stream_id \",\" value) :throw-exceptio", "end": 302, "score": 0.999743640422821, "start": 254, "tag": "KEY", "value": "MBhfc52ZUaa-DGD3cFtgcB1bmtSSAKwwWmRPR0RjRkJnND0g" } ]
data/train/clojure/8f75d6ef0e45805d93f3c38468d8483265e741a7core.clj
harshp8l/deep-learning-lang-detection
84
(ns cosm-overtone.core (:use overtone.live) (:require [clj-http.client :as client])) (defn- put-cosm "Update cosm feed" [stream_id value] (if-not (empty? value) (client/put (str "http://api.cosm.com/v2/feeds/80428.csv") {:headers {"X-ApiKey" "MBhfc52ZUaa-DGD3cFtgcB1bmtSSAKwwWmRPR0RjRkJnND0g"} :body (str stream_id "," value) :throw-exceptions false}))) (defn- handle-input "Parse input and send to cosm" [msg] (let [instrument (get msg :path) args (get msg :args)] (put-cosm (clojure.string/replace (str instrument) #"/" "") (clojure.string/replace (str args) #"[()]" "")))) (defn -main "Called by lein run" [& args] (osc-listen (osc-server 44100 "osc-clj") (fn [msg] (handle-input msg))))
100777
(ns cosm-overtone.core (:use overtone.live) (:require [clj-http.client :as client])) (defn- put-cosm "Update cosm feed" [stream_id value] (if-not (empty? value) (client/put (str "http://api.cosm.com/v2/feeds/80428.csv") {:headers {"X-ApiKey" "<KEY>"} :body (str stream_id "," value) :throw-exceptions false}))) (defn- handle-input "Parse input and send to cosm" [msg] (let [instrument (get msg :path) args (get msg :args)] (put-cosm (clojure.string/replace (str instrument) #"/" "") (clojure.string/replace (str args) #"[()]" "")))) (defn -main "Called by lein run" [& args] (osc-listen (osc-server 44100 "osc-clj") (fn [msg] (handle-input msg))))
true
(ns cosm-overtone.core (:use overtone.live) (:require [clj-http.client :as client])) (defn- put-cosm "Update cosm feed" [stream_id value] (if-not (empty? value) (client/put (str "http://api.cosm.com/v2/feeds/80428.csv") {:headers {"X-ApiKey" "PI:KEY:<KEY>END_PI"} :body (str stream_id "," value) :throw-exceptions false}))) (defn- handle-input "Parse input and send to cosm" [msg] (let [instrument (get msg :path) args (get msg :args)] (put-cosm (clojure.string/replace (str instrument) #"/" "") (clojure.string/replace (str args) #"[()]" "")))) (defn -main "Called by lein run" [& args] (osc-listen (osc-server 44100 "osc-clj") (fn [msg] (handle-input msg))))
[ { "context": "ve-example\n {:disabled false\n :first-name \"John\"\n :invalid false\n :likes #{:apples :banan", "end": 156, "score": 0.9998542070388794, "start": 152, "tag": "NAME", "value": "John" } ]
packages/reagent/src/cljs/nebula_widgets/kitchen_sink/panels/form_widget/db.cljs
mt0erfztxt/nebula-widgets
0
(ns nebula-widgets.kitchen-sink.panels.form-widget.db) (def default-db {:form-widget {:interactive-example {:disabled false :first-name "John" :invalid false :likes #{:apples :bananas}}}})
2932
(ns nebula-widgets.kitchen-sink.panels.form-widget.db) (def default-db {:form-widget {:interactive-example {:disabled false :first-name "<NAME>" :invalid false :likes #{:apples :bananas}}}})
true
(ns nebula-widgets.kitchen-sink.panels.form-widget.db) (def default-db {:form-widget {:interactive-example {:disabled false :first-name "PI:NAME:<NAME>END_PI" :invalid false :likes #{:apples :bananas}}}})
[ { "context": " {:form-params {:username username\n :passwo", "end": 743, "score": 0.9948983788490295, "start": 735, "tag": "USERNAME", "value": "username" }, { "context": " :password password\n :_csrf ", "end": 804, "score": 0.9990014433860779, "start": 796, "tag": "PASSWORD", "value": "password" }, { "context": "\n\n(defn -main []\n (let [username (System/getenv \"SIMPLE_USERNAME\")\n password (System/getenv \"SIMPLE_PASSWOR", "end": 2431, "score": 0.9778175950050354, "start": 2416, "tag": "USERNAME", "value": "SIMPLE_USERNAME" }, { "context": "IMPLE_USERNAME\")\n password (System/getenv \"SIMPLE_PASSWORD\")\n cookie-store (cookies/cookie-store)\n ", "end": 2482, "score": 0.9485502243041992, "start": 2467, "tag": "PASSWORD", "value": "SIMPLE_PASSWORD" } ]
src/simple_autogoals/core.clj
bi1yeu/simple-autogoals
4
(ns simple-autogoals.core (:require [clj-http.client :as client] [clj-http.cookies :as cookies] [cheshire.core :as json] [clojure.walk :refer [keywordize-keys]]) (:gen-class)) (def ^:const ^:private auto-amount-pattern #"auto_transfer=([0-9|.]*)") (defn- sign-in [username password cookie-store] (println "Signing-in" username) (let [csrf (->> (client/get "https://bank.simple.com/signin" {:cookie-store cookie-store}) :body (re-find #"<meta name=\"_csrf\" content=\"(.*)\">") last)] (try (if (-> (client/post "https://bank.simple.com/signin" {:form-params {:username username :password password :_csrf csrf} :cookie-store cookie-store}) :body (.contains "Your username and passphrase don't match")) (throw (Exception. "Invalid username and/or passphrase")) csrf) (catch Exception e (println "Could not sign-in" e) (throw e))))) (defn- transfer-to-goal [cookie-store csrf {:keys [name id dollar-amount-to-transfer]}] (println (format "Transferring $%.2f to \"%s\"" dollar-amount-to-transfer name)) (client/post (format "https://bank.simple.com/goals/%s/transactions" id) {:form-params {:amount (int (* dollar-amount-to-transfer 10000)) :_csrf csrf} :cookie-store cookie-store})) (defn- should-transfer? [goal] (and (not (:archived goal)) (not (:paused goal)) (:description goal) (re-find auto-amount-pattern (:description goal)))) (defn- assoc-amount-to-transfer [goal] (assoc goal :dollar-amount-to-transfer (-> (re-find auto-amount-pattern (:description goal)) last read-string (* 1.0)))) (defn- get-goals-to-transfer [cookie-store] (println "Getting goals") (->> (client/get "https://bank.simple.com/goals/data" {:cookie-store cookie-store}) :body json/parse-string (map keywordize-keys) (filter should-transfer?) (map assoc-amount-to-transfer))) (defn -main [] (let [username (System/getenv "SIMPLE_USERNAME") password (System/getenv "SIMPLE_PASSWORD") cookie-store (cookies/cookie-store) csrf (sign-in username password cookie-store) goals (get-goals-to-transfer cookie-store)] (println (count goals) "goals to update") (doall (map (partial transfer-to-goal cookie-store csrf) goals)) (println "Done")))
15489
(ns simple-autogoals.core (:require [clj-http.client :as client] [clj-http.cookies :as cookies] [cheshire.core :as json] [clojure.walk :refer [keywordize-keys]]) (:gen-class)) (def ^:const ^:private auto-amount-pattern #"auto_transfer=([0-9|.]*)") (defn- sign-in [username password cookie-store] (println "Signing-in" username) (let [csrf (->> (client/get "https://bank.simple.com/signin" {:cookie-store cookie-store}) :body (re-find #"<meta name=\"_csrf\" content=\"(.*)\">") last)] (try (if (-> (client/post "https://bank.simple.com/signin" {:form-params {:username username :password <PASSWORD> :_csrf csrf} :cookie-store cookie-store}) :body (.contains "Your username and passphrase don't match")) (throw (Exception. "Invalid username and/or passphrase")) csrf) (catch Exception e (println "Could not sign-in" e) (throw e))))) (defn- transfer-to-goal [cookie-store csrf {:keys [name id dollar-amount-to-transfer]}] (println (format "Transferring $%.2f to \"%s\"" dollar-amount-to-transfer name)) (client/post (format "https://bank.simple.com/goals/%s/transactions" id) {:form-params {:amount (int (* dollar-amount-to-transfer 10000)) :_csrf csrf} :cookie-store cookie-store})) (defn- should-transfer? [goal] (and (not (:archived goal)) (not (:paused goal)) (:description goal) (re-find auto-amount-pattern (:description goal)))) (defn- assoc-amount-to-transfer [goal] (assoc goal :dollar-amount-to-transfer (-> (re-find auto-amount-pattern (:description goal)) last read-string (* 1.0)))) (defn- get-goals-to-transfer [cookie-store] (println "Getting goals") (->> (client/get "https://bank.simple.com/goals/data" {:cookie-store cookie-store}) :body json/parse-string (map keywordize-keys) (filter should-transfer?) (map assoc-amount-to-transfer))) (defn -main [] (let [username (System/getenv "SIMPLE_USERNAME") password (System/getenv "<PASSWORD>") cookie-store (cookies/cookie-store) csrf (sign-in username password cookie-store) goals (get-goals-to-transfer cookie-store)] (println (count goals) "goals to update") (doall (map (partial transfer-to-goal cookie-store csrf) goals)) (println "Done")))
true
(ns simple-autogoals.core (:require [clj-http.client :as client] [clj-http.cookies :as cookies] [cheshire.core :as json] [clojure.walk :refer [keywordize-keys]]) (:gen-class)) (def ^:const ^:private auto-amount-pattern #"auto_transfer=([0-9|.]*)") (defn- sign-in [username password cookie-store] (println "Signing-in" username) (let [csrf (->> (client/get "https://bank.simple.com/signin" {:cookie-store cookie-store}) :body (re-find #"<meta name=\"_csrf\" content=\"(.*)\">") last)] (try (if (-> (client/post "https://bank.simple.com/signin" {:form-params {:username username :password PI:PASSWORD:<PASSWORD>END_PI :_csrf csrf} :cookie-store cookie-store}) :body (.contains "Your username and passphrase don't match")) (throw (Exception. "Invalid username and/or passphrase")) csrf) (catch Exception e (println "Could not sign-in" e) (throw e))))) (defn- transfer-to-goal [cookie-store csrf {:keys [name id dollar-amount-to-transfer]}] (println (format "Transferring $%.2f to \"%s\"" dollar-amount-to-transfer name)) (client/post (format "https://bank.simple.com/goals/%s/transactions" id) {:form-params {:amount (int (* dollar-amount-to-transfer 10000)) :_csrf csrf} :cookie-store cookie-store})) (defn- should-transfer? [goal] (and (not (:archived goal)) (not (:paused goal)) (:description goal) (re-find auto-amount-pattern (:description goal)))) (defn- assoc-amount-to-transfer [goal] (assoc goal :dollar-amount-to-transfer (-> (re-find auto-amount-pattern (:description goal)) last read-string (* 1.0)))) (defn- get-goals-to-transfer [cookie-store] (println "Getting goals") (->> (client/get "https://bank.simple.com/goals/data" {:cookie-store cookie-store}) :body json/parse-string (map keywordize-keys) (filter should-transfer?) (map assoc-amount-to-transfer))) (defn -main [] (let [username (System/getenv "SIMPLE_USERNAME") password (System/getenv "PI:PASSWORD:<PASSWORD>END_PI") cookie-store (cookies/cookie-store) csrf (sign-in username password cookie-store) goals (get-goals-to-transfer cookie-store)] (println (count goals) "goals to update") (doall (map (partial transfer-to-goal cookie-store csrf) goals)) (println "Done")))
[ { "context": "omparison for Clojure\"\n :url \"https://github.com/xsc/version-clj\"\n :license {:name \"MIT\"\n ", "end": 132, "score": 0.9995870590209961, "start": 129, "tag": "USERNAME", "value": "xsc" }, { "context": "ses/mit\"\n :year 2013\n :key \"mit\"\n :comment \"MIT License\"}\n :dependenc", "end": 273, "score": 0.8922500014305115, "start": 270, "tag": "KEY", "value": "mit" } ]
project.clj
xsc/version-clj
24
(defproject version-clj "2.0.3-SNAPSHOT" :description "Version Analysis and Comparison for Clojure" :url "https://github.com/xsc/version-clj" :license {:name "MIT" :url "https://choosealicense.com/licenses/mit" :year 2013 :key "mit" :comment "MIT License"} :dependencies [[org.clojure/clojure "1.10.1" :scope "provided"] [org.clojure/clojurescript "1.10.773" :scope "provided"] [com.google.code.findbugs/jsr305 "3.0.2" :scope "provided"]] :profiles {:dev {:global-vars {*warn-on-reflection* true}} :kaocha {:dependencies [[lambdaisland/kaocha "1.0.732" :exclusions [org.clojure/spec.alpha]] [lambdaisland/kaocha-cljs "0.0-71" :exclusions [org.clojure/clojurescript com.cognitect/transit-clj com.cognitect/transit-java]] [lambdaisland/kaocha-cloverage "1.0.75"] [org.clojure/tools.namespace "0.3.1"] [org.clojure/java.classpath "1.0.0"]]} :ci [:kaocha {:global-vars {*warn-on-reflection* false}}]} :cljsbuild {:test-commands {"node" ["node" :node-runner "target/testable.js"]} :builds [{:source-paths ["target/classes" "target/test-classes"] :compiler {:output-to "target/testable.js" :optimizations :simple}}]} :aliases {"kaocha" ["with-profile" "+kaocha" "run" "-m" "kaocha.runner"] "ci" ["with-profile" "+ci" "run" "-m" "kaocha.runner" "--reporter" "documentation" "--plugin" "cloverage" "--codecov" "--no-cov-html"]} :pedantic? :abort)
71437
(defproject version-clj "2.0.3-SNAPSHOT" :description "Version Analysis and Comparison for Clojure" :url "https://github.com/xsc/version-clj" :license {:name "MIT" :url "https://choosealicense.com/licenses/mit" :year 2013 :key "<KEY>" :comment "MIT License"} :dependencies [[org.clojure/clojure "1.10.1" :scope "provided"] [org.clojure/clojurescript "1.10.773" :scope "provided"] [com.google.code.findbugs/jsr305 "3.0.2" :scope "provided"]] :profiles {:dev {:global-vars {*warn-on-reflection* true}} :kaocha {:dependencies [[lambdaisland/kaocha "1.0.732" :exclusions [org.clojure/spec.alpha]] [lambdaisland/kaocha-cljs "0.0-71" :exclusions [org.clojure/clojurescript com.cognitect/transit-clj com.cognitect/transit-java]] [lambdaisland/kaocha-cloverage "1.0.75"] [org.clojure/tools.namespace "0.3.1"] [org.clojure/java.classpath "1.0.0"]]} :ci [:kaocha {:global-vars {*warn-on-reflection* false}}]} :cljsbuild {:test-commands {"node" ["node" :node-runner "target/testable.js"]} :builds [{:source-paths ["target/classes" "target/test-classes"] :compiler {:output-to "target/testable.js" :optimizations :simple}}]} :aliases {"kaocha" ["with-profile" "+kaocha" "run" "-m" "kaocha.runner"] "ci" ["with-profile" "+ci" "run" "-m" "kaocha.runner" "--reporter" "documentation" "--plugin" "cloverage" "--codecov" "--no-cov-html"]} :pedantic? :abort)
true
(defproject version-clj "2.0.3-SNAPSHOT" :description "Version Analysis and Comparison for Clojure" :url "https://github.com/xsc/version-clj" :license {:name "MIT" :url "https://choosealicense.com/licenses/mit" :year 2013 :key "PI:KEY:<KEY>END_PI" :comment "MIT License"} :dependencies [[org.clojure/clojure "1.10.1" :scope "provided"] [org.clojure/clojurescript "1.10.773" :scope "provided"] [com.google.code.findbugs/jsr305 "3.0.2" :scope "provided"]] :profiles {:dev {:global-vars {*warn-on-reflection* true}} :kaocha {:dependencies [[lambdaisland/kaocha "1.0.732" :exclusions [org.clojure/spec.alpha]] [lambdaisland/kaocha-cljs "0.0-71" :exclusions [org.clojure/clojurescript com.cognitect/transit-clj com.cognitect/transit-java]] [lambdaisland/kaocha-cloverage "1.0.75"] [org.clojure/tools.namespace "0.3.1"] [org.clojure/java.classpath "1.0.0"]]} :ci [:kaocha {:global-vars {*warn-on-reflection* false}}]} :cljsbuild {:test-commands {"node" ["node" :node-runner "target/testable.js"]} :builds [{:source-paths ["target/classes" "target/test-classes"] :compiler {:output-to "target/testable.js" :optimizations :simple}}]} :aliases {"kaocha" ["with-profile" "+kaocha" "run" "-m" "kaocha.runner"] "ci" ["with-profile" "+ci" "run" "-m" "kaocha.runner" "--reporter" "documentation" "--plugin" "cloverage" "--codecov" "--no-cov-html"]} :pedantic? :abort)
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.9998166561126709, "start": 96, "tag": "NAME", "value": "Ragnar Svensson" }, { "context": "-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold License version 1.0 ", "end": 129, "score": 0.9998257160186768, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/src/clj/editor/hot_reload.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 editor.hot-reload (:require [clojure.java.io :as io] [clojure.string :as string] [dynamo.graph :as g] [editor.pipeline :as pipeline] [editor.workspace :as workspace] [editor.resource :as resource]) (:import [java.io FileNotFoundException] [java.net URI] [org.apache.commons.io FilenameUtils IOUtils])) (set! *warn-on-reflection* true) (def ^:const url-prefix "/build") (def ^:const verify-etags-url-prefix "/__verify_etags__") (def ^:const not-found {:code 404}) (def ^:const bad-request {:code 400}) (defn- content->bytes [content] (-> content io/input-stream IOUtils/toByteArray)) (defn- handler [workspace project {:keys [url method headers]}] (let [build-path (FilenameUtils/normalize (str (workspace/build-path workspace))) path (subs url (count url-prefix)) full-path (format "%s%s" build-path path)] ;; Avoid going outside the build path with '..' (if (string/starts-with? full-path build-path) (let [etag (workspace/etag workspace path) remote-etag (first (get headers "If-none-match")) cached? (when remote-etag (= etag remote-etag)) content (when (not cached?) (try (with-open [is (io/input-stream full-path)] (IOUtils/toByteArray is)) (catch FileNotFoundException _ :not-found)))] (if (= content :not-found) not-found (let [response-headers (cond-> {"ETag" etag} (= method "GET") (assoc "Content-Length" (if content (str (count content)) "-1")))] (cond-> {:code (if cached? 304 200) :headers response-headers} (and (= method "GET") (not cached?)) (assoc :body content))))) not-found))) (defn build-handler [workspace project request] (handler workspace project request)) (defn- string->url ^URI [^String str] (when (some? str) (try (URI. str) (catch java.net.URISyntaxException _ nil)))) (defn- body->valid-entries [workspace ^bytes body] (into [] (comp (keep (fn [line] (let [[url-string etag] (string/split line #" ")] (when-some [url (some-> url-string string->url)] [url etag])))) (keep (fn [[^URI url etag]] (let [path (.. url normalize getPath)] (when (string/starts-with? path url-prefix) (let [proj-path (subs path (count url-prefix))] (when (= etag (workspace/etag workspace proj-path)) path))))))) (string/split-lines (String. body)))) (defn- v-e-handler [workspace project {:keys [url method headers ^bytes body]}] (if (not= method "POST") bad-request (let [body-str (string/join "\n" (body->valid-entries workspace body)) body (.getBytes body-str "UTF-8")] {:code 200 :headers {"Content-Length" (str (count body))} :body body}))) (defn verify-etags-handler [workspace project request] (v-e-handler workspace project request))
67705
;; 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 editor.hot-reload (:require [clojure.java.io :as io] [clojure.string :as string] [dynamo.graph :as g] [editor.pipeline :as pipeline] [editor.workspace :as workspace] [editor.resource :as resource]) (:import [java.io FileNotFoundException] [java.net URI] [org.apache.commons.io FilenameUtils IOUtils])) (set! *warn-on-reflection* true) (def ^:const url-prefix "/build") (def ^:const verify-etags-url-prefix "/__verify_etags__") (def ^:const not-found {:code 404}) (def ^:const bad-request {:code 400}) (defn- content->bytes [content] (-> content io/input-stream IOUtils/toByteArray)) (defn- handler [workspace project {:keys [url method headers]}] (let [build-path (FilenameUtils/normalize (str (workspace/build-path workspace))) path (subs url (count url-prefix)) full-path (format "%s%s" build-path path)] ;; Avoid going outside the build path with '..' (if (string/starts-with? full-path build-path) (let [etag (workspace/etag workspace path) remote-etag (first (get headers "If-none-match")) cached? (when remote-etag (= etag remote-etag)) content (when (not cached?) (try (with-open [is (io/input-stream full-path)] (IOUtils/toByteArray is)) (catch FileNotFoundException _ :not-found)))] (if (= content :not-found) not-found (let [response-headers (cond-> {"ETag" etag} (= method "GET") (assoc "Content-Length" (if content (str (count content)) "-1")))] (cond-> {:code (if cached? 304 200) :headers response-headers} (and (= method "GET") (not cached?)) (assoc :body content))))) not-found))) (defn build-handler [workspace project request] (handler workspace project request)) (defn- string->url ^URI [^String str] (when (some? str) (try (URI. str) (catch java.net.URISyntaxException _ nil)))) (defn- body->valid-entries [workspace ^bytes body] (into [] (comp (keep (fn [line] (let [[url-string etag] (string/split line #" ")] (when-some [url (some-> url-string string->url)] [url etag])))) (keep (fn [[^URI url etag]] (let [path (.. url normalize getPath)] (when (string/starts-with? path url-prefix) (let [proj-path (subs path (count url-prefix))] (when (= etag (workspace/etag workspace proj-path)) path))))))) (string/split-lines (String. body)))) (defn- v-e-handler [workspace project {:keys [url method headers ^bytes body]}] (if (not= method "POST") bad-request (let [body-str (string/join "\n" (body->valid-entries workspace body)) body (.getBytes body-str "UTF-8")] {:code 200 :headers {"Content-Length" (str (count body))} :body body}))) (defn verify-etags-handler [workspace project request] (v-e-handler workspace project request))
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 editor.hot-reload (:require [clojure.java.io :as io] [clojure.string :as string] [dynamo.graph :as g] [editor.pipeline :as pipeline] [editor.workspace :as workspace] [editor.resource :as resource]) (:import [java.io FileNotFoundException] [java.net URI] [org.apache.commons.io FilenameUtils IOUtils])) (set! *warn-on-reflection* true) (def ^:const url-prefix "/build") (def ^:const verify-etags-url-prefix "/__verify_etags__") (def ^:const not-found {:code 404}) (def ^:const bad-request {:code 400}) (defn- content->bytes [content] (-> content io/input-stream IOUtils/toByteArray)) (defn- handler [workspace project {:keys [url method headers]}] (let [build-path (FilenameUtils/normalize (str (workspace/build-path workspace))) path (subs url (count url-prefix)) full-path (format "%s%s" build-path path)] ;; Avoid going outside the build path with '..' (if (string/starts-with? full-path build-path) (let [etag (workspace/etag workspace path) remote-etag (first (get headers "If-none-match")) cached? (when remote-etag (= etag remote-etag)) content (when (not cached?) (try (with-open [is (io/input-stream full-path)] (IOUtils/toByteArray is)) (catch FileNotFoundException _ :not-found)))] (if (= content :not-found) not-found (let [response-headers (cond-> {"ETag" etag} (= method "GET") (assoc "Content-Length" (if content (str (count content)) "-1")))] (cond-> {:code (if cached? 304 200) :headers response-headers} (and (= method "GET") (not cached?)) (assoc :body content))))) not-found))) (defn build-handler [workspace project request] (handler workspace project request)) (defn- string->url ^URI [^String str] (when (some? str) (try (URI. str) (catch java.net.URISyntaxException _ nil)))) (defn- body->valid-entries [workspace ^bytes body] (into [] (comp (keep (fn [line] (let [[url-string etag] (string/split line #" ")] (when-some [url (some-> url-string string->url)] [url etag])))) (keep (fn [[^URI url etag]] (let [path (.. url normalize getPath)] (when (string/starts-with? path url-prefix) (let [proj-path (subs path (count url-prefix))] (when (= etag (workspace/etag workspace proj-path)) path))))))) (string/split-lines (String. body)))) (defn- v-e-handler [workspace project {:keys [url method headers ^bytes body]}] (if (not= method "POST") bad-request (let [body-str (string/join "\n" (body->valid-entries workspace body)) body (.getBytes body-str "UTF-8")] {:code 200 :headers {"Content-Length" (str (count body))} :body body}))) (defn verify-etags-handler [workspace project request] (v-e-handler workspace project request))
[ { "context": "e {:id \"2000\"\n :given_name \"Louis\"\n :family_name \"Wu\"\n ", "end": 1009, "score": 0.9996280670166016, "start": 1004, "tag": "NAME", "value": "Louis" }, { "context": "name \"Louis\"\n :family_name \"Wu\"\n :employer example-busines", "end": 1050, "score": 0.9855433702468872, "start": 1048, "tag": "NAME", "value": "Wu" } ]
test/com/walmartlabs/lacinia/unions_test.clj
gusbicalho/lacinia
0
(ns com.walmartlabs.lacinia.unions-test (:refer-clojure :exclude [compile]) (:require [clojure.test :refer [deftest is testing]] [com.walmartlabs.lacinia.schema :refer [compile tag-with-type]] [com.walmartlabs.lacinia :as ql] [com.walmartlabs.test-utils :refer [is-thrown]] [com.walmartlabs.test-reporting :refer [report]])) (def base-schema {:objects {:business {:fields {:id {:type :ID} :name {:type :String}}} :employee {:fields {:id {:type :ID} :employer {:type :business} :given_name {:type :String} :family_name {:type :String}}}} :unions {:searchable {:members [:business :employee]}} :queries {:businesses {:type '(list :business) :resolve identity} :search {:type '(list :searchable) :resolve identity}}}) (def example-business {:id "1000" :name "General Products"}) (def example-employee {:id "2000" :given_name "Louis" :family_name "Wu" :employer example-business}) (defn resolve-search "Simple version, doesn't apply type metadata." [_ _ _] [example-business example-employee]) (defn resolve-search+ [_ _ _] [(tag-with-type example-business :business) (tag-with-type example-employee :employee)]) (defn execute [compiled-schema q] (ql/execute compiled-schema q nil nil)) (deftest union-references-unknown ;; This covers everything: listing either completely unknown object types, ;; to listing unions, enums, or interface types. (let [schema (merge base-schema {:unions {:searchable {:members [:business :account]}}})] (is-thrown [t (compile schema)] (is (= "Union `searchable' references unknown type `account'." (.getMessage t))) (is (= :searchable (-> t ex-data :union :type-name)))))) (deftest requires-type-metadata-be-added-for-union-resolves (let [schema (-> base-schema (assoc-in [:queries :search :resolve] resolve-search) compile) q "{ search { ... on business { id name } ... on employee { id family_name }}}" result (execute schema q)] (report result (is (= "Field resolver returned an instance not tagged with a schema type." (-> result :errors first :message)))))) (deftest resolves-using-concrete-type-in-spread (let [schema (-> base-schema (assoc-in [:queries :search :resolve] resolve-search+) compile) q "{ search { ... on searchable { ... on business { id name } ... on employee { id family_name }}}}" result (execute schema q)] (is (= {:data {:search [{:id "1000" :name "General Products"} {:id "2000" :family_name "Wu"}]}} result))))
54487
(ns com.walmartlabs.lacinia.unions-test (:refer-clojure :exclude [compile]) (:require [clojure.test :refer [deftest is testing]] [com.walmartlabs.lacinia.schema :refer [compile tag-with-type]] [com.walmartlabs.lacinia :as ql] [com.walmartlabs.test-utils :refer [is-thrown]] [com.walmartlabs.test-reporting :refer [report]])) (def base-schema {:objects {:business {:fields {:id {:type :ID} :name {:type :String}}} :employee {:fields {:id {:type :ID} :employer {:type :business} :given_name {:type :String} :family_name {:type :String}}}} :unions {:searchable {:members [:business :employee]}} :queries {:businesses {:type '(list :business) :resolve identity} :search {:type '(list :searchable) :resolve identity}}}) (def example-business {:id "1000" :name "General Products"}) (def example-employee {:id "2000" :given_name "<NAME>" :family_name "<NAME>" :employer example-business}) (defn resolve-search "Simple version, doesn't apply type metadata." [_ _ _] [example-business example-employee]) (defn resolve-search+ [_ _ _] [(tag-with-type example-business :business) (tag-with-type example-employee :employee)]) (defn execute [compiled-schema q] (ql/execute compiled-schema q nil nil)) (deftest union-references-unknown ;; This covers everything: listing either completely unknown object types, ;; to listing unions, enums, or interface types. (let [schema (merge base-schema {:unions {:searchable {:members [:business :account]}}})] (is-thrown [t (compile schema)] (is (= "Union `searchable' references unknown type `account'." (.getMessage t))) (is (= :searchable (-> t ex-data :union :type-name)))))) (deftest requires-type-metadata-be-added-for-union-resolves (let [schema (-> base-schema (assoc-in [:queries :search :resolve] resolve-search) compile) q "{ search { ... on business { id name } ... on employee { id family_name }}}" result (execute schema q)] (report result (is (= "Field resolver returned an instance not tagged with a schema type." (-> result :errors first :message)))))) (deftest resolves-using-concrete-type-in-spread (let [schema (-> base-schema (assoc-in [:queries :search :resolve] resolve-search+) compile) q "{ search { ... on searchable { ... on business { id name } ... on employee { id family_name }}}}" result (execute schema q)] (is (= {:data {:search [{:id "1000" :name "General Products"} {:id "2000" :family_name "Wu"}]}} result))))
true
(ns com.walmartlabs.lacinia.unions-test (:refer-clojure :exclude [compile]) (:require [clojure.test :refer [deftest is testing]] [com.walmartlabs.lacinia.schema :refer [compile tag-with-type]] [com.walmartlabs.lacinia :as ql] [com.walmartlabs.test-utils :refer [is-thrown]] [com.walmartlabs.test-reporting :refer [report]])) (def base-schema {:objects {:business {:fields {:id {:type :ID} :name {:type :String}}} :employee {:fields {:id {:type :ID} :employer {:type :business} :given_name {:type :String} :family_name {:type :String}}}} :unions {:searchable {:members [:business :employee]}} :queries {:businesses {:type '(list :business) :resolve identity} :search {:type '(list :searchable) :resolve identity}}}) (def example-business {:id "1000" :name "General Products"}) (def example-employee {:id "2000" :given_name "PI:NAME:<NAME>END_PI" :family_name "PI:NAME:<NAME>END_PI" :employer example-business}) (defn resolve-search "Simple version, doesn't apply type metadata." [_ _ _] [example-business example-employee]) (defn resolve-search+ [_ _ _] [(tag-with-type example-business :business) (tag-with-type example-employee :employee)]) (defn execute [compiled-schema q] (ql/execute compiled-schema q nil nil)) (deftest union-references-unknown ;; This covers everything: listing either completely unknown object types, ;; to listing unions, enums, or interface types. (let [schema (merge base-schema {:unions {:searchable {:members [:business :account]}}})] (is-thrown [t (compile schema)] (is (= "Union `searchable' references unknown type `account'." (.getMessage t))) (is (= :searchable (-> t ex-data :union :type-name)))))) (deftest requires-type-metadata-be-added-for-union-resolves (let [schema (-> base-schema (assoc-in [:queries :search :resolve] resolve-search) compile) q "{ search { ... on business { id name } ... on employee { id family_name }}}" result (execute schema q)] (report result (is (= "Field resolver returned an instance not tagged with a schema type." (-> result :errors first :message)))))) (deftest resolves-using-concrete-type-in-spread (let [schema (-> base-schema (assoc-in [:queries :search :resolve] resolve-search+) compile) q "{ search { ... on searchable { ... on business { id name } ... on employee { id family_name }}}}" result (execute schema q)] (is (= {:data {:search [{:id "1000" :name "General Products"} {:id "2000" :family_name "Wu"}]}} result))))
[ { "context": " (= (:text token) (:val token))))\n \n \"alex@wit.ai\"\n \"alex.lebrun@mail.wit.com\"\n (fn [token _] (and ", "end": 622, "score": 0.9999312162399292, "start": 611, "tag": "EMAIL", "value": "alex@wit.ai" }, { "context": " (:text token) (:val token))))\n \n \"alex@wit.ai\"\n \"alex.lebrun@mail.wit.com\"\n (fn [token _] (and (= :email (:dim token))\n ", "end": 650, "score": 0.9999336004257202, "start": 626, "tag": "EMAIL", "value": "alex.lebrun@mail.wit.com" } ]
resources/languages/ro/corpus/communication.clj
guivn/duckling
922
( {} "0743115099" "0743 115 099" "074 31 15 099" "0743 11 50 99" "+4 0743115099" "004 0743115099" "0743115099 int 897" "650-283-4757" "+1 6502834757" "+33 4 76095663" "06 2070 2220" "(650)-283-4757 ext 897" (fn [token _] (and (= :phone-number (:dim token)) (= (:text token) (:val token)))) "http://www.bla.com" "www.bla.com:8080/path" "https://myserver?foo=bar" "cnn.com/info" "bla.com/path/path?ext=%23&foo=bla" "localhost" "localhost:8000" "http://kimchi" ; local url (fn [token _] (and (= :url (:dim token)) (= (:text token) (:val token)))) "alex@wit.ai" "alex.lebrun@mail.wit.com" (fn [token _] (and (= :email (:dim token)) (= (:text token) (:val token)))) )
124209
( {} "0743115099" "0743 115 099" "074 31 15 099" "0743 11 50 99" "+4 0743115099" "004 0743115099" "0743115099 int 897" "650-283-4757" "+1 6502834757" "+33 4 76095663" "06 2070 2220" "(650)-283-4757 ext 897" (fn [token _] (and (= :phone-number (:dim token)) (= (:text token) (:val token)))) "http://www.bla.com" "www.bla.com:8080/path" "https://myserver?foo=bar" "cnn.com/info" "bla.com/path/path?ext=%23&foo=bla" "localhost" "localhost:8000" "http://kimchi" ; local url (fn [token _] (and (= :url (:dim token)) (= (:text token) (:val token)))) "<EMAIL>" "<EMAIL>" (fn [token _] (and (= :email (:dim token)) (= (:text token) (:val token)))) )
true
( {} "0743115099" "0743 115 099" "074 31 15 099" "0743 11 50 99" "+4 0743115099" "004 0743115099" "0743115099 int 897" "650-283-4757" "+1 6502834757" "+33 4 76095663" "06 2070 2220" "(650)-283-4757 ext 897" (fn [token _] (and (= :phone-number (:dim token)) (= (:text token) (:val token)))) "http://www.bla.com" "www.bla.com:8080/path" "https://myserver?foo=bar" "cnn.com/info" "bla.com/path/path?ext=%23&foo=bla" "localhost" "localhost:8000" "http://kimchi" ; local url (fn [token _] (and (= :url (:dim token)) (= (:text token) (:val token)))) "PI:EMAIL:<EMAIL>END_PI" "PI:EMAIL:<EMAIL>END_PI" (fn [token _] (and (= :email (:dim token)) (= (:text token) (:val token)))) )
[ { "context": "ual, well, corpora.\r\n(def my-corpora \r\n [{:name \"Shakespeare's Sonnets\", :location \"res/corpora/sonnets/\"} \r\n ", "end": 250, "score": 0.7502783536911011, "start": 237, "tag": "NAME", "value": "Shakespeare's" } ]
wysitutwyg/src-clj/wysitutwyg/routes/landing.clj
MoyTW/clojure-toys
1
(ns wysitutwyg.routes.landing (:require [net.cgrand.enlive-html :as html] [compojure.core :as compojure]) (:use ring.util.response)) ;; This should correspond to actual, well, corpora. (def my-corpora [{:name "Shakespeare's Sonnets", :location "res/corpora/sonnets/"} {:name "Translation of Lorem Ipsum", :location "res/corpora/loremipsum/"}]) (html/deftemplate landing "pages/landing.html" [corpora] [:head] (html/append (first (html/html [:script {:src "res/js/main.js"}]))) [:select#corpus-selection :option] (html/clone-for [corpus corpora] [:option] (html/content (corpus :name)) [:option] (html/set-attr :value (corpus :location))) [:select#corpus-selection [:option html/first-of-type]] (html/set-attr :selected "selected")) (compojure/defroutes routes (compojure/GET "/" [] (landing my-corpora)))
65149
(ns wysitutwyg.routes.landing (:require [net.cgrand.enlive-html :as html] [compojure.core :as compojure]) (:use ring.util.response)) ;; This should correspond to actual, well, corpora. (def my-corpora [{:name "<NAME> Sonnets", :location "res/corpora/sonnets/"} {:name "Translation of Lorem Ipsum", :location "res/corpora/loremipsum/"}]) (html/deftemplate landing "pages/landing.html" [corpora] [:head] (html/append (first (html/html [:script {:src "res/js/main.js"}]))) [:select#corpus-selection :option] (html/clone-for [corpus corpora] [:option] (html/content (corpus :name)) [:option] (html/set-attr :value (corpus :location))) [:select#corpus-selection [:option html/first-of-type]] (html/set-attr :selected "selected")) (compojure/defroutes routes (compojure/GET "/" [] (landing my-corpora)))
true
(ns wysitutwyg.routes.landing (:require [net.cgrand.enlive-html :as html] [compojure.core :as compojure]) (:use ring.util.response)) ;; This should correspond to actual, well, corpora. (def my-corpora [{:name "PI:NAME:<NAME>END_PI Sonnets", :location "res/corpora/sonnets/"} {:name "Translation of Lorem Ipsum", :location "res/corpora/loremipsum/"}]) (html/deftemplate landing "pages/landing.html" [corpora] [:head] (html/append (first (html/html [:script {:src "res/js/main.js"}]))) [:select#corpus-selection :option] (html/clone-for [corpus corpora] [:option] (html/content (corpus :name)) [:option] (html/set-attr :value (corpus :location))) [:select#corpus-selection [:option html/first-of-type]] (html/set-attr :selected "selected")) (compojure/defroutes routes (compojure/GET "/" [] (landing my-corpora)))
[ { "context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li", "end": 111, "score": 0.9998183250427246, "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.9998221397399902, "start": 113, "tag": "NAME", "value": "Christian Murray" } ]
editor/test/editor/script_api_test.clj
cmarincia/defold
0
;; Copyright 2020-2022 The Defold Foundation ;; Copyright 2014-2020 King ;; Copyright 2009-2014 Ragnar Svensson, Christian Murray ;; Licensed under the Defold License version 1.0 (the "License"); you may not use ;; this file except in compliance with the License. ;; ;; You may obtain a copy of the License, together with FAQs at ;; https://www.defold.com/license ;; ;; Unless required by applicable law or agreed to in writing, software distributed ;; under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR ;; CONDITIONS OF ANY KIND, either express or implied. See the License for the ;; specific language governing permissions and limitations under the License. (ns editor.script-api-test (:require [clojure.string :as string] [clojure.test :refer :all] [editor.script-api :as sapi])) (defn std ([name type] (std name type nil)) ([name type doc] {:type type :name name :doc doc :display-string name :insert-string name})) (def just-a-variable " - name: other type: number") (def just-a-variable-expected-result {"" [(std "other" :variable)]}) (def empty-table " - name: table type: table") (def empty-table-expected-result {"" [(std "table" :namespace)] "table" []}) (def table-with-members " - name: other type: table desc: 'Another table' members: - name: Hello type: number") (def table-with-members-expected-result {"" [(std "other" :namespace "Another table")] "other" [(std "other.Hello" :variable)]}) (def function-with-one-parameter " - name: fun type: function desc: This is super great function! parameters: - name: plopp type: plupp") (def function-with-one-parameter-expected-result {"" [{:type :function :name "fun" :doc "This is super great function!" :display-string "fun(plopp)" :insert-string "fun(plopp)" :tab-triggers {:select ["plopp"] :exit ")"}}]}) (def empty-top-level-definition "- ") (def empty-top-level-definition-expected-result {"" []}) (def broken-table-member-list " - name: other type: table desc: 'Another table' members: - nam") (def broken-table-member-list-expected-result {"" [(std "other" :namespace "Another table")] "other" []}) (def no-type-means-variable " - name: hej") (def no-type-means-variable-expected-result {"" [(std "hej" :variable)]}) (def function-with-optional-parameter " - name: fun type: function parameters: - name: optopt type: integer optional: true") (def function-with-optional-parameter-expected-result {"" [{:type :function :name "fun" :doc nil :display-string "fun([optopt])" :insert-string "fun()" :tab-triggers {:select [] :exit ")"}}]}) (defn convert [source] (sapi/combine-conversions (sapi/convert-lines (string/split-lines source)))) (deftest conversions (are [x y] (= x (convert y)) just-a-variable-expected-result just-a-variable empty-table-expected-result empty-table table-with-members-expected-result table-with-members function-with-one-parameter-expected-result function-with-one-parameter empty-top-level-definition-expected-result empty-top-level-definition broken-table-member-list-expected-result broken-table-member-list function-with-optional-parameter-expected-result function-with-optional-parameter no-type-means-variable-expected-result no-type-means-variable))
26703
;; 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 editor.script-api-test (:require [clojure.string :as string] [clojure.test :refer :all] [editor.script-api :as sapi])) (defn std ([name type] (std name type nil)) ([name type doc] {:type type :name name :doc doc :display-string name :insert-string name})) (def just-a-variable " - name: other type: number") (def just-a-variable-expected-result {"" [(std "other" :variable)]}) (def empty-table " - name: table type: table") (def empty-table-expected-result {"" [(std "table" :namespace)] "table" []}) (def table-with-members " - name: other type: table desc: 'Another table' members: - name: Hello type: number") (def table-with-members-expected-result {"" [(std "other" :namespace "Another table")] "other" [(std "other.Hello" :variable)]}) (def function-with-one-parameter " - name: fun type: function desc: This is super great function! parameters: - name: plopp type: plupp") (def function-with-one-parameter-expected-result {"" [{:type :function :name "fun" :doc "This is super great function!" :display-string "fun(plopp)" :insert-string "fun(plopp)" :tab-triggers {:select ["plopp"] :exit ")"}}]}) (def empty-top-level-definition "- ") (def empty-top-level-definition-expected-result {"" []}) (def broken-table-member-list " - name: other type: table desc: 'Another table' members: - nam") (def broken-table-member-list-expected-result {"" [(std "other" :namespace "Another table")] "other" []}) (def no-type-means-variable " - name: hej") (def no-type-means-variable-expected-result {"" [(std "hej" :variable)]}) (def function-with-optional-parameter " - name: fun type: function parameters: - name: optopt type: integer optional: true") (def function-with-optional-parameter-expected-result {"" [{:type :function :name "fun" :doc nil :display-string "fun([optopt])" :insert-string "fun()" :tab-triggers {:select [] :exit ")"}}]}) (defn convert [source] (sapi/combine-conversions (sapi/convert-lines (string/split-lines source)))) (deftest conversions (are [x y] (= x (convert y)) just-a-variable-expected-result just-a-variable empty-table-expected-result empty-table table-with-members-expected-result table-with-members function-with-one-parameter-expected-result function-with-one-parameter empty-top-level-definition-expected-result empty-top-level-definition broken-table-member-list-expected-result broken-table-member-list function-with-optional-parameter-expected-result function-with-optional-parameter no-type-means-variable-expected-result no-type-means-variable))
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 editor.script-api-test (:require [clojure.string :as string] [clojure.test :refer :all] [editor.script-api :as sapi])) (defn std ([name type] (std name type nil)) ([name type doc] {:type type :name name :doc doc :display-string name :insert-string name})) (def just-a-variable " - name: other type: number") (def just-a-variable-expected-result {"" [(std "other" :variable)]}) (def empty-table " - name: table type: table") (def empty-table-expected-result {"" [(std "table" :namespace)] "table" []}) (def table-with-members " - name: other type: table desc: 'Another table' members: - name: Hello type: number") (def table-with-members-expected-result {"" [(std "other" :namespace "Another table")] "other" [(std "other.Hello" :variable)]}) (def function-with-one-parameter " - name: fun type: function desc: This is super great function! parameters: - name: plopp type: plupp") (def function-with-one-parameter-expected-result {"" [{:type :function :name "fun" :doc "This is super great function!" :display-string "fun(plopp)" :insert-string "fun(plopp)" :tab-triggers {:select ["plopp"] :exit ")"}}]}) (def empty-top-level-definition "- ") (def empty-top-level-definition-expected-result {"" []}) (def broken-table-member-list " - name: other type: table desc: 'Another table' members: - nam") (def broken-table-member-list-expected-result {"" [(std "other" :namespace "Another table")] "other" []}) (def no-type-means-variable " - name: hej") (def no-type-means-variable-expected-result {"" [(std "hej" :variable)]}) (def function-with-optional-parameter " - name: fun type: function parameters: - name: optopt type: integer optional: true") (def function-with-optional-parameter-expected-result {"" [{:type :function :name "fun" :doc nil :display-string "fun([optopt])" :insert-string "fun()" :tab-triggers {:select [] :exit ")"}}]}) (defn convert [source] (sapi/combine-conversions (sapi/convert-lines (string/split-lines source)))) (deftest conversions (are [x y] (= x (convert y)) just-a-variable-expected-result just-a-variable empty-table-expected-result empty-table table-with-members-expected-result table-with-members function-with-one-parameter-expected-result function-with-one-parameter empty-top-level-definition-expected-result empty-top-level-definition broken-table-member-list-expected-result broken-table-member-list function-with-optional-parameter-expected-result function-with-optional-parameter no-type-means-variable-expected-result no-type-means-variable))
[ { "context": "bmitTx n [[:crux.tx/put {:crux.db/id :ivan :name \"Ivan\"} valid-time]])]\n (t/is (= submitted-tx (.", "end": 3835, "score": 0.9895452260971069, "start": 3831, "tag": "NAME", "value": "Ivan" }, { "context": " :where [[e :name \"Ivan\"]]}))))\n\n (t/is (= #{[:ivan]} (.query (.db n", "end": 4067, "score": 0.9938799142837524, "start": 4063, "tag": "NAME", "value": "Ivan" }, { "context": " :where [[e :name \"Ivan\"]]})))\n\n (with-open [n2 (n/start {:crux.node", "end": 4223, "score": 0.9940457344055176, "start": 4219, "tag": "NAME", "value": "Ivan" }, { "context": "\n :where [[e :name \"Ivan\"]]})))\n\n (let [valid-time (Date.)\n ", "end": 4659, "score": 0.994707465171814, "start": 4655, "tag": "NAME", "value": "Ivan" }, { "context": "mitTx n2 [[:crux.tx/put {:crux.db/id :ivan :name \"Iva\"} valid-time]])]\n (t/is (= submitted-tx ", "end": 4786, "score": 0.9891979694366455, "start": 4783, "tag": "NAME", "value": "Iva" }, { "context": " :where [[e :name \"Iva\"]]}))))\n\n (t/is n2))\n\n (t/is (= #{[:i", "end": 5027, "score": 0.9987375736236572, "start": 5024, "tag": "NAME", "value": "Iva" }, { "context": " :where [[e :name \"Ivan\"]]}))))))\n\n(defmacro with-latest-tx [latest-tx & ", "end": 5203, "score": 0.9994038343429565, "start": 5199, "tag": "NAME", "value": "Ivan" } ]
crux-test/test/crux/node_test.clj
tolitius/crux
0
(ns crux.node-test (:require [clojure.test :as t] [crux.config :as cc] [crux.io :as cio] crux.jdbc crux.kv.memdb crux.kv.rocksdb [crux.node :as n] [clojure.spec.alpha :as s] [crux.fixtures :as f] [clojure.java.io :as io] crux.standalone [crux.tx :as tx] [crux.tx.event :as txe] [crux.api :as api] [crux.bus :as bus]) (:import java.util.Date crux.api.Crux (java.util HashMap) (clojure.lang Keyword) (java.time Duration) (java.util.concurrent TimeoutException))) (t/deftest test-calling-shutdown-node-fails-gracefully (f/with-tmp-dir "data" [data-dir] (try (let [n (n/start {:crux.node/topology ['crux.standalone/topology] :crux.kv/db-dir (str (io/file data-dir "db"))})] (t/is (.status n)) (.close n) (.status n) (t/is false)) (catch IllegalStateException e (t/is (= "Crux node is closed" (.getMessage e))))))) (t/deftest test-start-node-complain-if-no-topology (try (with-open [n (n/start {})] (t/is false)) (catch IllegalArgumentException e (t/is (re-find #"Please specify :crux.node/topology" (.getMessage e)))))) (t/deftest test-start-node-should-throw-missing-argument-exception (f/with-tmp-dir "data" [data-dir] (try (with-open [n (n/start {:crux.node/topology '[crux.jdbc/topology] :crux.kv/db-dir (str (io/file data-dir "db"))})] (t/is false)) (catch Throwable e (t/is (re-find #"Arg :crux.jdbc/dbtype required" (.getMessage e)))) (finally (cio/delete-dir data-dir))))) (t/deftest test-can-start-JDBC-node (f/with-tmp-dir "data" [data-dir] (with-open [n (n/start {:crux.node/topology ['crux.jdbc/topology] :crux.kv/db-dir (str (io/file data-dir "kv-store")) :crux.jdbc/dbtype "h2" :crux.jdbc/dbname (str (io/file data-dir "cruxtest"))})] (t/is n)))) (t/deftest test-can-set-standalone-kv-store (f/with-tmp-dir "data" [data-dir] (with-open [n (n/start {:crux.node/topology ['crux.standalone/topology] :crux.kv/kv-store :crux.kv.memdb/kv :crux.kv/db-dir (str (io/file data-dir "db"))})] (t/is n)))) (t/deftest test-properties-file-to-node (f/with-tmp-dir "data" [data-dir] (with-open [n (n/start (assoc (cc/load-properties (clojure.java.io/resource "sample.properties")) :crux.db/db-dir (str (io/file data-dir "db"))))] (t/is (instance? crux.standalone.StandaloneTxLog (-> n :tx-log))) (t/is (= (Duration/ofSeconds 20) (-> n :options :crux.tx-log/await-tx-timeout)))))) (t/deftest topology-resolution-from-java (f/with-tmp-dir "data" [data-dir] (let [mem-db-node-options (doto (HashMap.) (.put :crux.node/topology 'crux.standalone/topology) (.put :crux.node/kv-store 'crux.kv.memdb/kv) (.put :crux.kv/db-dir (str (io/file data-dir "db-dir")))) memdb-node (Crux/startNode mem-db-node-options)] (t/is memdb-node) (t/is (not (.close memdb-node)))))) (t/deftest test-start-up-2-nodes (f/with-tmp-dir "data" [data-dir] (with-open [n (n/start {:crux.node/topology ['crux.jdbc/topology] :crux.kv/db-dir (str (io/file data-dir "kv1")) :crux.jdbc/dbtype "h2" :crux.jdbc/dbname (str (io/file data-dir "cruxtest1"))})] (t/is n) (let [valid-time (Date.) submitted-tx (.submitTx n [[:crux.tx/put {:crux.db/id :ivan :name "Ivan"} valid-time]])] (t/is (= submitted-tx (.awaitTx n submitted-tx nil))) (t/is (= #{[:ivan]} (.query (.db n) '{:find [e] :where [[e :name "Ivan"]]})))) (t/is (= #{[:ivan]} (.query (.db n) '{:find [e] :where [[e :name "Ivan"]]}))) (with-open [n2 (n/start {:crux.node/topology ['crux.jdbc/topology] :crux.kv/db-dir (str (io/file data-dir "kv2")) :crux.jdbc/dbtype "h2" :crux.jdbc/dbname (str (io/file data-dir "cruxtest2"))})] (t/is (= #{} (.query (.db n2) '{:find [e] :where [[e :name "Ivan"]]}))) (let [valid-time (Date.) submitted-tx (.submitTx n2 [[:crux.tx/put {:crux.db/id :ivan :name "Iva"} valid-time]])] (t/is (= submitted-tx (.awaitTx n2 submitted-tx nil))) (t/is (= #{[:ivan]} (.query (.db n2) '{:find [e] :where [[e :name "Iva"]]})))) (t/is n2)) (t/is (= #{[:ivan]} (.query (.db n) '{:find [e] :where [[e :name "Ivan"]]})))))) (defmacro with-latest-tx [latest-tx & body] `(with-redefs [api/latest-completed-tx (fn [node#] ~latest-tx)] ~@body)) (t/deftest test-await-tx (let [bus (bus/->bus {}) await-tx (fn [tx timeout] (#'n/await-tx {:bus bus} ::tx/tx-id tx timeout)) tx1 {::tx/tx-id 1 ::tx/tx-time (Date.)} tx-evt {:crux/event-type ::tx/indexed-tx ::tx/submitted-tx tx1 ::txe/tx-events [] :committed? true}] (t/testing "ready already" (with-latest-tx tx1 (t/is (= tx1 (await-tx tx1 nil))))) (t/testing "times out" (with-latest-tx nil (t/is (thrown? TimeoutException (await-tx tx1 (Duration/ofMillis 10)))))) (t/testing "eventually works" (future (Thread/sleep 100) (bus/send bus tx-evt)) (with-latest-tx nil (t/is (= tx1 (await-tx tx1 nil))))) (t/testing "times out if it's not quite ready" (let [!latch (promise)] (future (Thread/sleep 100) (bus/send bus (assoc-in tx-evt [::tx/submitted-tx ::tx/tx-id] 0))) (with-latest-tx nil (t/is (thrown? TimeoutException (await-tx tx1 (Duration/ofMillis 500))))))) (t/testing "throws on ingester error" (future (Thread/sleep 100) (bus/send bus {:crux/event-type ::tx/ingester-error ::tx/ingester-error (ex-info "Ingester error" {})})) (with-latest-tx nil (t/is (thrown-with-msg? Exception #"Transaction ingester aborted." (await-tx tx1 nil))))) (t/testing "throws if node closed" (future (Thread/sleep 100) (bus/send bus {:crux/event-type ::n/node-closed})) (with-latest-tx nil (t/is (thrown? InterruptedException (await-tx tx1 nil)))))))
63621
(ns crux.node-test (:require [clojure.test :as t] [crux.config :as cc] [crux.io :as cio] crux.jdbc crux.kv.memdb crux.kv.rocksdb [crux.node :as n] [clojure.spec.alpha :as s] [crux.fixtures :as f] [clojure.java.io :as io] crux.standalone [crux.tx :as tx] [crux.tx.event :as txe] [crux.api :as api] [crux.bus :as bus]) (:import java.util.Date crux.api.Crux (java.util HashMap) (clojure.lang Keyword) (java.time Duration) (java.util.concurrent TimeoutException))) (t/deftest test-calling-shutdown-node-fails-gracefully (f/with-tmp-dir "data" [data-dir] (try (let [n (n/start {:crux.node/topology ['crux.standalone/topology] :crux.kv/db-dir (str (io/file data-dir "db"))})] (t/is (.status n)) (.close n) (.status n) (t/is false)) (catch IllegalStateException e (t/is (= "Crux node is closed" (.getMessage e))))))) (t/deftest test-start-node-complain-if-no-topology (try (with-open [n (n/start {})] (t/is false)) (catch IllegalArgumentException e (t/is (re-find #"Please specify :crux.node/topology" (.getMessage e)))))) (t/deftest test-start-node-should-throw-missing-argument-exception (f/with-tmp-dir "data" [data-dir] (try (with-open [n (n/start {:crux.node/topology '[crux.jdbc/topology] :crux.kv/db-dir (str (io/file data-dir "db"))})] (t/is false)) (catch Throwable e (t/is (re-find #"Arg :crux.jdbc/dbtype required" (.getMessage e)))) (finally (cio/delete-dir data-dir))))) (t/deftest test-can-start-JDBC-node (f/with-tmp-dir "data" [data-dir] (with-open [n (n/start {:crux.node/topology ['crux.jdbc/topology] :crux.kv/db-dir (str (io/file data-dir "kv-store")) :crux.jdbc/dbtype "h2" :crux.jdbc/dbname (str (io/file data-dir "cruxtest"))})] (t/is n)))) (t/deftest test-can-set-standalone-kv-store (f/with-tmp-dir "data" [data-dir] (with-open [n (n/start {:crux.node/topology ['crux.standalone/topology] :crux.kv/kv-store :crux.kv.memdb/kv :crux.kv/db-dir (str (io/file data-dir "db"))})] (t/is n)))) (t/deftest test-properties-file-to-node (f/with-tmp-dir "data" [data-dir] (with-open [n (n/start (assoc (cc/load-properties (clojure.java.io/resource "sample.properties")) :crux.db/db-dir (str (io/file data-dir "db"))))] (t/is (instance? crux.standalone.StandaloneTxLog (-> n :tx-log))) (t/is (= (Duration/ofSeconds 20) (-> n :options :crux.tx-log/await-tx-timeout)))))) (t/deftest topology-resolution-from-java (f/with-tmp-dir "data" [data-dir] (let [mem-db-node-options (doto (HashMap.) (.put :crux.node/topology 'crux.standalone/topology) (.put :crux.node/kv-store 'crux.kv.memdb/kv) (.put :crux.kv/db-dir (str (io/file data-dir "db-dir")))) memdb-node (Crux/startNode mem-db-node-options)] (t/is memdb-node) (t/is (not (.close memdb-node)))))) (t/deftest test-start-up-2-nodes (f/with-tmp-dir "data" [data-dir] (with-open [n (n/start {:crux.node/topology ['crux.jdbc/topology] :crux.kv/db-dir (str (io/file data-dir "kv1")) :crux.jdbc/dbtype "h2" :crux.jdbc/dbname (str (io/file data-dir "cruxtest1"))})] (t/is n) (let [valid-time (Date.) submitted-tx (.submitTx n [[:crux.tx/put {:crux.db/id :ivan :name "<NAME>"} valid-time]])] (t/is (= submitted-tx (.awaitTx n submitted-tx nil))) (t/is (= #{[:ivan]} (.query (.db n) '{:find [e] :where [[e :name "<NAME>"]]})))) (t/is (= #{[:ivan]} (.query (.db n) '{:find [e] :where [[e :name "<NAME>"]]}))) (with-open [n2 (n/start {:crux.node/topology ['crux.jdbc/topology] :crux.kv/db-dir (str (io/file data-dir "kv2")) :crux.jdbc/dbtype "h2" :crux.jdbc/dbname (str (io/file data-dir "cruxtest2"))})] (t/is (= #{} (.query (.db n2) '{:find [e] :where [[e :name "<NAME>"]]}))) (let [valid-time (Date.) submitted-tx (.submitTx n2 [[:crux.tx/put {:crux.db/id :ivan :name "<NAME>"} valid-time]])] (t/is (= submitted-tx (.awaitTx n2 submitted-tx nil))) (t/is (= #{[:ivan]} (.query (.db n2) '{:find [e] :where [[e :name "<NAME>"]]})))) (t/is n2)) (t/is (= #{[:ivan]} (.query (.db n) '{:find [e] :where [[e :name "<NAME>"]]})))))) (defmacro with-latest-tx [latest-tx & body] `(with-redefs [api/latest-completed-tx (fn [node#] ~latest-tx)] ~@body)) (t/deftest test-await-tx (let [bus (bus/->bus {}) await-tx (fn [tx timeout] (#'n/await-tx {:bus bus} ::tx/tx-id tx timeout)) tx1 {::tx/tx-id 1 ::tx/tx-time (Date.)} tx-evt {:crux/event-type ::tx/indexed-tx ::tx/submitted-tx tx1 ::txe/tx-events [] :committed? true}] (t/testing "ready already" (with-latest-tx tx1 (t/is (= tx1 (await-tx tx1 nil))))) (t/testing "times out" (with-latest-tx nil (t/is (thrown? TimeoutException (await-tx tx1 (Duration/ofMillis 10)))))) (t/testing "eventually works" (future (Thread/sleep 100) (bus/send bus tx-evt)) (with-latest-tx nil (t/is (= tx1 (await-tx tx1 nil))))) (t/testing "times out if it's not quite ready" (let [!latch (promise)] (future (Thread/sleep 100) (bus/send bus (assoc-in tx-evt [::tx/submitted-tx ::tx/tx-id] 0))) (with-latest-tx nil (t/is (thrown? TimeoutException (await-tx tx1 (Duration/ofMillis 500))))))) (t/testing "throws on ingester error" (future (Thread/sleep 100) (bus/send bus {:crux/event-type ::tx/ingester-error ::tx/ingester-error (ex-info "Ingester error" {})})) (with-latest-tx nil (t/is (thrown-with-msg? Exception #"Transaction ingester aborted." (await-tx tx1 nil))))) (t/testing "throws if node closed" (future (Thread/sleep 100) (bus/send bus {:crux/event-type ::n/node-closed})) (with-latest-tx nil (t/is (thrown? InterruptedException (await-tx tx1 nil)))))))
true
(ns crux.node-test (:require [clojure.test :as t] [crux.config :as cc] [crux.io :as cio] crux.jdbc crux.kv.memdb crux.kv.rocksdb [crux.node :as n] [clojure.spec.alpha :as s] [crux.fixtures :as f] [clojure.java.io :as io] crux.standalone [crux.tx :as tx] [crux.tx.event :as txe] [crux.api :as api] [crux.bus :as bus]) (:import java.util.Date crux.api.Crux (java.util HashMap) (clojure.lang Keyword) (java.time Duration) (java.util.concurrent TimeoutException))) (t/deftest test-calling-shutdown-node-fails-gracefully (f/with-tmp-dir "data" [data-dir] (try (let [n (n/start {:crux.node/topology ['crux.standalone/topology] :crux.kv/db-dir (str (io/file data-dir "db"))})] (t/is (.status n)) (.close n) (.status n) (t/is false)) (catch IllegalStateException e (t/is (= "Crux node is closed" (.getMessage e))))))) (t/deftest test-start-node-complain-if-no-topology (try (with-open [n (n/start {})] (t/is false)) (catch IllegalArgumentException e (t/is (re-find #"Please specify :crux.node/topology" (.getMessage e)))))) (t/deftest test-start-node-should-throw-missing-argument-exception (f/with-tmp-dir "data" [data-dir] (try (with-open [n (n/start {:crux.node/topology '[crux.jdbc/topology] :crux.kv/db-dir (str (io/file data-dir "db"))})] (t/is false)) (catch Throwable e (t/is (re-find #"Arg :crux.jdbc/dbtype required" (.getMessage e)))) (finally (cio/delete-dir data-dir))))) (t/deftest test-can-start-JDBC-node (f/with-tmp-dir "data" [data-dir] (with-open [n (n/start {:crux.node/topology ['crux.jdbc/topology] :crux.kv/db-dir (str (io/file data-dir "kv-store")) :crux.jdbc/dbtype "h2" :crux.jdbc/dbname (str (io/file data-dir "cruxtest"))})] (t/is n)))) (t/deftest test-can-set-standalone-kv-store (f/with-tmp-dir "data" [data-dir] (with-open [n (n/start {:crux.node/topology ['crux.standalone/topology] :crux.kv/kv-store :crux.kv.memdb/kv :crux.kv/db-dir (str (io/file data-dir "db"))})] (t/is n)))) (t/deftest test-properties-file-to-node (f/with-tmp-dir "data" [data-dir] (with-open [n (n/start (assoc (cc/load-properties (clojure.java.io/resource "sample.properties")) :crux.db/db-dir (str (io/file data-dir "db"))))] (t/is (instance? crux.standalone.StandaloneTxLog (-> n :tx-log))) (t/is (= (Duration/ofSeconds 20) (-> n :options :crux.tx-log/await-tx-timeout)))))) (t/deftest topology-resolution-from-java (f/with-tmp-dir "data" [data-dir] (let [mem-db-node-options (doto (HashMap.) (.put :crux.node/topology 'crux.standalone/topology) (.put :crux.node/kv-store 'crux.kv.memdb/kv) (.put :crux.kv/db-dir (str (io/file data-dir "db-dir")))) memdb-node (Crux/startNode mem-db-node-options)] (t/is memdb-node) (t/is (not (.close memdb-node)))))) (t/deftest test-start-up-2-nodes (f/with-tmp-dir "data" [data-dir] (with-open [n (n/start {:crux.node/topology ['crux.jdbc/topology] :crux.kv/db-dir (str (io/file data-dir "kv1")) :crux.jdbc/dbtype "h2" :crux.jdbc/dbname (str (io/file data-dir "cruxtest1"))})] (t/is n) (let [valid-time (Date.) submitted-tx (.submitTx n [[:crux.tx/put {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI"} valid-time]])] (t/is (= submitted-tx (.awaitTx n submitted-tx nil))) (t/is (= #{[:ivan]} (.query (.db n) '{:find [e] :where [[e :name "PI:NAME:<NAME>END_PI"]]})))) (t/is (= #{[:ivan]} (.query (.db n) '{:find [e] :where [[e :name "PI:NAME:<NAME>END_PI"]]}))) (with-open [n2 (n/start {:crux.node/topology ['crux.jdbc/topology] :crux.kv/db-dir (str (io/file data-dir "kv2")) :crux.jdbc/dbtype "h2" :crux.jdbc/dbname (str (io/file data-dir "cruxtest2"))})] (t/is (= #{} (.query (.db n2) '{:find [e] :where [[e :name "PI:NAME:<NAME>END_PI"]]}))) (let [valid-time (Date.) submitted-tx (.submitTx n2 [[:crux.tx/put {:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI"} valid-time]])] (t/is (= submitted-tx (.awaitTx n2 submitted-tx nil))) (t/is (= #{[:ivan]} (.query (.db n2) '{:find [e] :where [[e :name "PI:NAME:<NAME>END_PI"]]})))) (t/is n2)) (t/is (= #{[:ivan]} (.query (.db n) '{:find [e] :where [[e :name "PI:NAME:<NAME>END_PI"]]})))))) (defmacro with-latest-tx [latest-tx & body] `(with-redefs [api/latest-completed-tx (fn [node#] ~latest-tx)] ~@body)) (t/deftest test-await-tx (let [bus (bus/->bus {}) await-tx (fn [tx timeout] (#'n/await-tx {:bus bus} ::tx/tx-id tx timeout)) tx1 {::tx/tx-id 1 ::tx/tx-time (Date.)} tx-evt {:crux/event-type ::tx/indexed-tx ::tx/submitted-tx tx1 ::txe/tx-events [] :committed? true}] (t/testing "ready already" (with-latest-tx tx1 (t/is (= tx1 (await-tx tx1 nil))))) (t/testing "times out" (with-latest-tx nil (t/is (thrown? TimeoutException (await-tx tx1 (Duration/ofMillis 10)))))) (t/testing "eventually works" (future (Thread/sleep 100) (bus/send bus tx-evt)) (with-latest-tx nil (t/is (= tx1 (await-tx tx1 nil))))) (t/testing "times out if it's not quite ready" (let [!latch (promise)] (future (Thread/sleep 100) (bus/send bus (assoc-in tx-evt [::tx/submitted-tx ::tx/tx-id] 0))) (with-latest-tx nil (t/is (thrown? TimeoutException (await-tx tx1 (Duration/ofMillis 500))))))) (t/testing "throws on ingester error" (future (Thread/sleep 100) (bus/send bus {:crux/event-type ::tx/ingester-error ::tx/ingester-error (ex-info "Ingester error" {})})) (with-latest-tx nil (t/is (thrown-with-msg? Exception #"Transaction ingester aborted." (await-tx tx1 nil))))) (t/testing "throws if node closed" (future (Thread/sleep 100) (bus/send bus {:crux/event-type ::n/node-closed})) (with-latest-tx nil (t/is (thrown? InterruptedException (await-tx tx1 nil)))))))
[ { "context": "rn \"SET\" (sph/set-value! env \"accounts\" \"user1\" \"John\"))\n (prn \"GET\" (sph/get-value env \"accounts\"", "end": 388, "score": 0.997865617275238, "start": 384, "tag": "NAME", "value": "John" } ]
clj-sophia/src/simple/main.clj
piotr-yuxuan/graalvm-clojure2
361
(ns simple.main (:require [com.brunobonacci.sophia :as sph]) (:gen-class)) (defn -main [] (let [env (sph/sophia {;; where to store the files on disk :sophia.path "/tmp/sophia-test" ;; which logical databases to create :dbs ["accounts", {:name "transactions"}]})] (prn "SET" (sph/set-value! env "accounts" "user1" "John")) (prn "GET" (sph/get-value env "accounts" "user1"))))
119777
(ns simple.main (:require [com.brunobonacci.sophia :as sph]) (:gen-class)) (defn -main [] (let [env (sph/sophia {;; where to store the files on disk :sophia.path "/tmp/sophia-test" ;; which logical databases to create :dbs ["accounts", {:name "transactions"}]})] (prn "SET" (sph/set-value! env "accounts" "user1" "<NAME>")) (prn "GET" (sph/get-value env "accounts" "user1"))))
true
(ns simple.main (:require [com.brunobonacci.sophia :as sph]) (:gen-class)) (defn -main [] (let [env (sph/sophia {;; where to store the files on disk :sophia.path "/tmp/sophia-test" ;; which logical databases to create :dbs ["accounts", {:name "transactions"}]})] (prn "SET" (sph/set-value! env "accounts" "user1" "PI:NAME:<NAME>END_PI")) (prn "GET" (sph/get-value env "accounts" "user1"))))
[ { "context": "; Copyright 2020 Mark Wardle and Eldrix Ltd\n;\n; Licensed under the Apache Li", "end": 28, "score": 0.9998583793640137, "start": 17, "tag": "NAME", "value": "Mark Wardle" }, { "context": "pe :jetty\n ::http/port 8081\n ::http/host \"0.0.0.0\"\n })\n\n(defn start-server\n ([svc port] (start-s", "end": 8334, "score": 0.9993458986282349, "start": 8327, "tag": "IP_ADDRESS", "value": "0.0.0.0" } ]
src/com/eldrix/hermes/server.clj
sidharthramesh/hermes
0
; Copyright 2020 Mark Wardle and Eldrix Ltd ; ; 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.eldrix.hermes.server (:require [cheshire.core :as json] [cheshire.generate :as json-gen] [clojure.string :as str] [clojure.tools.logging.readable :as log] [com.eldrix.hermes.service :as svc] [com.eldrix.hermes.snomed :as snomed] [io.pedestal.http :as http] [io.pedestal.http.content-negotiation :as conneg] [io.pedestal.http.route :as route] [io.pedestal.interceptor :as intc] [io.pedestal.interceptor.error :as intc-err]) (:import (java.time.format DateTimeFormatter) (java.time LocalDate) (com.fasterxml.jackson.core JsonGenerator))) (set! *warn-on-reflection* true) (def supported-types ["text/html" "application/edn" "application/json" "text/plain"]) (def content-neg-intc (conneg/negotiate-content supported-types)) (defn response [status body & {:as headers}] {:status status :body body :headers headers}) (def ok (partial response 200)) (def not-found (partial response 404)) (defn accepted-type [context] (get-in context [:request :accept :field] "application/json")) (json-gen/add-encoder LocalDate (fn [^LocalDate o ^JsonGenerator out] (.writeString out (.format (DateTimeFormatter/ISO_DATE) o)))) (defn transform-content [body content-type] (case content-type "text/html" body "text/plain" body "application/edn" (pr-str body) "application/json" (json/generate-string body))) (defn coerce-to [response content-type] (-> response (update :body transform-content content-type) (assoc-in [:headers "Content-Type"] content-type))) (def coerce-body {:name ::coerce-body :leave (fn [context] (if (get-in context [:response :headers "Content-Type"]) context (update-in context [:response] coerce-to (accepted-type context))))}) (defn inject-svc "A simple interceptor to inject terminology service 'svc' into the context." [svc] {:name ::inject-svc :enter (fn [context] (update context :request assoc ::service svc))}) (def entity-render "Interceptor to render an entity '(:result context)' into the response." {:name :entity-render :leave (fn [context] (if-let [item (:result context)] (assoc context :response (ok item)) context))}) (def service-error-handler (intc-err/error-dispatch [context err] [{:exception-type :java.lang.NumberFormatException :interceptor ::get-search}] (assoc context :response {:status 400 :body (str "Invalid search parameters; invalid number: " (ex-message (:exception (ex-data err))))}) [{:exception-type :java.lang.IllegalArgumentException :interceptor ::get-search}] (assoc context :response {:status 400 :body (str "invalid search parameters: " (ex-message (:exception (ex-data err))))}) [{:exception-type :clojure.lang.ExceptionInfo :interceptor ::get-search}] (assoc context :response {:status 400 :body (str "invalid search parameters: " (ex-message (:exception (ex-data err))))}) :else (assoc context :io.pedestal.interceptor.chain/error err))) (def get-concept {:name ::get-concept :enter (fn [context] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (when-let [concept (svc/getConcept (get-in context [:request ::service]) concept-id)] (assoc context :result concept))))}) (def get-extended-concept {:name ::get-extended-concept :enter (fn [context] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (when-let [concept (svc/getExtendedConcept (get-in context [:request ::service]) concept-id)] (assoc context :result concept))))}) (def get-concept-descriptions {:name ::get-concept-descriptions :enter (fn [context] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (when-let [ds (svc/getDescriptions (get-in context [:request ::service]) concept-id)] (assoc context :result ds))))}) (def get-map-to {:name ::get-map-to :enter (fn [context] (let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id])) refset-id (Long/parseLong (get-in context [:request :path-params :refset-id]))] (when (and concept-id refset-id) (when-let [rfs (svc/getComponentRefsetItems (get-in context [:request ::service]) concept-id refset-id)] (assoc context :result rfs)))))}) (def get-map-from {:name ::get-map-from :enter (fn [context] (let [refset-id (Long/parseLong (get-in context [:request :path-params :refset-id])) code (get-in context [:request :path-params :code])] (when (and refset-id code) (when-let [rfs (svc/reverseMap (get-in context [:request ::service]) refset-id (str/upper-case code))] (assoc context :result rfs)))))}) (def subsumed-by? {:name ::subsumed-by :enter (fn [context] (let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id])) subsumer-id (Long/parseLong (get-in context [:request :path-params :subsumer-id])) svc (get-in context [:request ::service])] (log/info "subsumed by request: is " concept-id "subsumed by" subsumer-id ", using svc:" svc "?") (assoc context :result {:subsumedBy (svc/subsumedBy? svc concept-id subsumer-id)})))}) (defn parse-search-params [context] (let [{:keys [s maxHits isA refset constraint]} (get-in context [:request :params])] (cond-> {} s (assoc :s s) constraint (assoc :constraint constraint) maxHits (assoc :max-hits (Integer/parseInt maxHits)) (string? isA) (assoc :properties {snomed/IsA (Long/parseLong isA)}) (vector? isA) (assoc :properties {snomed/IsA (into [] (map #(Long/parseLong %) isA))}) (string? refset) (assoc :concept-refsets [(Long/parseLong refset)]) (vector? refset) (assoc :concept-refsets (into [] (map #(Long/parseLong %) refset)))))) (def get-search {:name ::get-search :enter (fn [context] (let [params (parse-search-params context) svc (get-in context [:request ::service])] (when (= (:max-hits params) 0) (throw (IllegalArgumentException. "invalid parameter: 0 maxHits"))) (assoc context :result (svc/search svc params))))}) (def common-routes [coerce-body content-neg-intc entity-render]) (def routes (route/expand-routes #{["/v1/snomed/concepts/:concept-id" :get (conj common-routes get-concept)] ["/v1/snomed/concepts/:concept-id/descriptions" :get (conj common-routes get-concept-descriptions)] ["/v1/snomed/concepts/:concept-id/extended" :get [coerce-body content-neg-intc entity-render get-extended-concept]] ["/v1/snomed/concepts/:concept-id/map/:refset-id" :get [coerce-body content-neg-intc entity-render get-map-to]] ["/v1/snomed/concepts/:concept-id/subsumed-by/:subsumer-id" :get [coerce-body content-neg-intc entity-render subsumed-by?]] ["/v1/snomed/crossmap/:refset-id/:code" :get [coerce-body content-neg-intc entity-render get-map-from]] ["/v1/snomed/search" :get [service-error-handler coerce-body content-neg-intc entity-render get-search]]})) (def service-map {::http/routes routes ::http/type :jetty ::http/port 8081 ::http/host "0.0.0.0" }) (defn start-server ([svc port] (start-server svc port true)) ([svc port join?] (log/info "starting server on port " port) (http/start (http/create-server (-> service-map (assoc ::http/port port) (assoc ::http/join? join?) (http/default-interceptors) (update ::http/interceptors conj (intc/interceptor (inject-svc svc)))))))) (defn stop-server [server] (http/stop server)) (comment )
62655
; Copyright 2020 <NAME> and Eldrix Ltd ; ; 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.eldrix.hermes.server (:require [cheshire.core :as json] [cheshire.generate :as json-gen] [clojure.string :as str] [clojure.tools.logging.readable :as log] [com.eldrix.hermes.service :as svc] [com.eldrix.hermes.snomed :as snomed] [io.pedestal.http :as http] [io.pedestal.http.content-negotiation :as conneg] [io.pedestal.http.route :as route] [io.pedestal.interceptor :as intc] [io.pedestal.interceptor.error :as intc-err]) (:import (java.time.format DateTimeFormatter) (java.time LocalDate) (com.fasterxml.jackson.core JsonGenerator))) (set! *warn-on-reflection* true) (def supported-types ["text/html" "application/edn" "application/json" "text/plain"]) (def content-neg-intc (conneg/negotiate-content supported-types)) (defn response [status body & {:as headers}] {:status status :body body :headers headers}) (def ok (partial response 200)) (def not-found (partial response 404)) (defn accepted-type [context] (get-in context [:request :accept :field] "application/json")) (json-gen/add-encoder LocalDate (fn [^LocalDate o ^JsonGenerator out] (.writeString out (.format (DateTimeFormatter/ISO_DATE) o)))) (defn transform-content [body content-type] (case content-type "text/html" body "text/plain" body "application/edn" (pr-str body) "application/json" (json/generate-string body))) (defn coerce-to [response content-type] (-> response (update :body transform-content content-type) (assoc-in [:headers "Content-Type"] content-type))) (def coerce-body {:name ::coerce-body :leave (fn [context] (if (get-in context [:response :headers "Content-Type"]) context (update-in context [:response] coerce-to (accepted-type context))))}) (defn inject-svc "A simple interceptor to inject terminology service 'svc' into the context." [svc] {:name ::inject-svc :enter (fn [context] (update context :request assoc ::service svc))}) (def entity-render "Interceptor to render an entity '(:result context)' into the response." {:name :entity-render :leave (fn [context] (if-let [item (:result context)] (assoc context :response (ok item)) context))}) (def service-error-handler (intc-err/error-dispatch [context err] [{:exception-type :java.lang.NumberFormatException :interceptor ::get-search}] (assoc context :response {:status 400 :body (str "Invalid search parameters; invalid number: " (ex-message (:exception (ex-data err))))}) [{:exception-type :java.lang.IllegalArgumentException :interceptor ::get-search}] (assoc context :response {:status 400 :body (str "invalid search parameters: " (ex-message (:exception (ex-data err))))}) [{:exception-type :clojure.lang.ExceptionInfo :interceptor ::get-search}] (assoc context :response {:status 400 :body (str "invalid search parameters: " (ex-message (:exception (ex-data err))))}) :else (assoc context :io.pedestal.interceptor.chain/error err))) (def get-concept {:name ::get-concept :enter (fn [context] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (when-let [concept (svc/getConcept (get-in context [:request ::service]) concept-id)] (assoc context :result concept))))}) (def get-extended-concept {:name ::get-extended-concept :enter (fn [context] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (when-let [concept (svc/getExtendedConcept (get-in context [:request ::service]) concept-id)] (assoc context :result concept))))}) (def get-concept-descriptions {:name ::get-concept-descriptions :enter (fn [context] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (when-let [ds (svc/getDescriptions (get-in context [:request ::service]) concept-id)] (assoc context :result ds))))}) (def get-map-to {:name ::get-map-to :enter (fn [context] (let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id])) refset-id (Long/parseLong (get-in context [:request :path-params :refset-id]))] (when (and concept-id refset-id) (when-let [rfs (svc/getComponentRefsetItems (get-in context [:request ::service]) concept-id refset-id)] (assoc context :result rfs)))))}) (def get-map-from {:name ::get-map-from :enter (fn [context] (let [refset-id (Long/parseLong (get-in context [:request :path-params :refset-id])) code (get-in context [:request :path-params :code])] (when (and refset-id code) (when-let [rfs (svc/reverseMap (get-in context [:request ::service]) refset-id (str/upper-case code))] (assoc context :result rfs)))))}) (def subsumed-by? {:name ::subsumed-by :enter (fn [context] (let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id])) subsumer-id (Long/parseLong (get-in context [:request :path-params :subsumer-id])) svc (get-in context [:request ::service])] (log/info "subsumed by request: is " concept-id "subsumed by" subsumer-id ", using svc:" svc "?") (assoc context :result {:subsumedBy (svc/subsumedBy? svc concept-id subsumer-id)})))}) (defn parse-search-params [context] (let [{:keys [s maxHits isA refset constraint]} (get-in context [:request :params])] (cond-> {} s (assoc :s s) constraint (assoc :constraint constraint) maxHits (assoc :max-hits (Integer/parseInt maxHits)) (string? isA) (assoc :properties {snomed/IsA (Long/parseLong isA)}) (vector? isA) (assoc :properties {snomed/IsA (into [] (map #(Long/parseLong %) isA))}) (string? refset) (assoc :concept-refsets [(Long/parseLong refset)]) (vector? refset) (assoc :concept-refsets (into [] (map #(Long/parseLong %) refset)))))) (def get-search {:name ::get-search :enter (fn [context] (let [params (parse-search-params context) svc (get-in context [:request ::service])] (when (= (:max-hits params) 0) (throw (IllegalArgumentException. "invalid parameter: 0 maxHits"))) (assoc context :result (svc/search svc params))))}) (def common-routes [coerce-body content-neg-intc entity-render]) (def routes (route/expand-routes #{["/v1/snomed/concepts/:concept-id" :get (conj common-routes get-concept)] ["/v1/snomed/concepts/:concept-id/descriptions" :get (conj common-routes get-concept-descriptions)] ["/v1/snomed/concepts/:concept-id/extended" :get [coerce-body content-neg-intc entity-render get-extended-concept]] ["/v1/snomed/concepts/:concept-id/map/:refset-id" :get [coerce-body content-neg-intc entity-render get-map-to]] ["/v1/snomed/concepts/:concept-id/subsumed-by/:subsumer-id" :get [coerce-body content-neg-intc entity-render subsumed-by?]] ["/v1/snomed/crossmap/:refset-id/:code" :get [coerce-body content-neg-intc entity-render get-map-from]] ["/v1/snomed/search" :get [service-error-handler coerce-body content-neg-intc entity-render get-search]]})) (def service-map {::http/routes routes ::http/type :jetty ::http/port 8081 ::http/host "0.0.0.0" }) (defn start-server ([svc port] (start-server svc port true)) ([svc port join?] (log/info "starting server on port " port) (http/start (http/create-server (-> service-map (assoc ::http/port port) (assoc ::http/join? join?) (http/default-interceptors) (update ::http/interceptors conj (intc/interceptor (inject-svc svc)))))))) (defn stop-server [server] (http/stop server)) (comment )
true
; Copyright 2020 PI:NAME:<NAME>END_PI and Eldrix Ltd ; ; 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.eldrix.hermes.server (:require [cheshire.core :as json] [cheshire.generate :as json-gen] [clojure.string :as str] [clojure.tools.logging.readable :as log] [com.eldrix.hermes.service :as svc] [com.eldrix.hermes.snomed :as snomed] [io.pedestal.http :as http] [io.pedestal.http.content-negotiation :as conneg] [io.pedestal.http.route :as route] [io.pedestal.interceptor :as intc] [io.pedestal.interceptor.error :as intc-err]) (:import (java.time.format DateTimeFormatter) (java.time LocalDate) (com.fasterxml.jackson.core JsonGenerator))) (set! *warn-on-reflection* true) (def supported-types ["text/html" "application/edn" "application/json" "text/plain"]) (def content-neg-intc (conneg/negotiate-content supported-types)) (defn response [status body & {:as headers}] {:status status :body body :headers headers}) (def ok (partial response 200)) (def not-found (partial response 404)) (defn accepted-type [context] (get-in context [:request :accept :field] "application/json")) (json-gen/add-encoder LocalDate (fn [^LocalDate o ^JsonGenerator out] (.writeString out (.format (DateTimeFormatter/ISO_DATE) o)))) (defn transform-content [body content-type] (case content-type "text/html" body "text/plain" body "application/edn" (pr-str body) "application/json" (json/generate-string body))) (defn coerce-to [response content-type] (-> response (update :body transform-content content-type) (assoc-in [:headers "Content-Type"] content-type))) (def coerce-body {:name ::coerce-body :leave (fn [context] (if (get-in context [:response :headers "Content-Type"]) context (update-in context [:response] coerce-to (accepted-type context))))}) (defn inject-svc "A simple interceptor to inject terminology service 'svc' into the context." [svc] {:name ::inject-svc :enter (fn [context] (update context :request assoc ::service svc))}) (def entity-render "Interceptor to render an entity '(:result context)' into the response." {:name :entity-render :leave (fn [context] (if-let [item (:result context)] (assoc context :response (ok item)) context))}) (def service-error-handler (intc-err/error-dispatch [context err] [{:exception-type :java.lang.NumberFormatException :interceptor ::get-search}] (assoc context :response {:status 400 :body (str "Invalid search parameters; invalid number: " (ex-message (:exception (ex-data err))))}) [{:exception-type :java.lang.IllegalArgumentException :interceptor ::get-search}] (assoc context :response {:status 400 :body (str "invalid search parameters: " (ex-message (:exception (ex-data err))))}) [{:exception-type :clojure.lang.ExceptionInfo :interceptor ::get-search}] (assoc context :response {:status 400 :body (str "invalid search parameters: " (ex-message (:exception (ex-data err))))}) :else (assoc context :io.pedestal.interceptor.chain/error err))) (def get-concept {:name ::get-concept :enter (fn [context] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (when-let [concept (svc/getConcept (get-in context [:request ::service]) concept-id)] (assoc context :result concept))))}) (def get-extended-concept {:name ::get-extended-concept :enter (fn [context] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (when-let [concept (svc/getExtendedConcept (get-in context [:request ::service]) concept-id)] (assoc context :result concept))))}) (def get-concept-descriptions {:name ::get-concept-descriptions :enter (fn [context] (when-let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id]))] (when-let [ds (svc/getDescriptions (get-in context [:request ::service]) concept-id)] (assoc context :result ds))))}) (def get-map-to {:name ::get-map-to :enter (fn [context] (let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id])) refset-id (Long/parseLong (get-in context [:request :path-params :refset-id]))] (when (and concept-id refset-id) (when-let [rfs (svc/getComponentRefsetItems (get-in context [:request ::service]) concept-id refset-id)] (assoc context :result rfs)))))}) (def get-map-from {:name ::get-map-from :enter (fn [context] (let [refset-id (Long/parseLong (get-in context [:request :path-params :refset-id])) code (get-in context [:request :path-params :code])] (when (and refset-id code) (when-let [rfs (svc/reverseMap (get-in context [:request ::service]) refset-id (str/upper-case code))] (assoc context :result rfs)))))}) (def subsumed-by? {:name ::subsumed-by :enter (fn [context] (let [concept-id (Long/parseLong (get-in context [:request :path-params :concept-id])) subsumer-id (Long/parseLong (get-in context [:request :path-params :subsumer-id])) svc (get-in context [:request ::service])] (log/info "subsumed by request: is " concept-id "subsumed by" subsumer-id ", using svc:" svc "?") (assoc context :result {:subsumedBy (svc/subsumedBy? svc concept-id subsumer-id)})))}) (defn parse-search-params [context] (let [{:keys [s maxHits isA refset constraint]} (get-in context [:request :params])] (cond-> {} s (assoc :s s) constraint (assoc :constraint constraint) maxHits (assoc :max-hits (Integer/parseInt maxHits)) (string? isA) (assoc :properties {snomed/IsA (Long/parseLong isA)}) (vector? isA) (assoc :properties {snomed/IsA (into [] (map #(Long/parseLong %) isA))}) (string? refset) (assoc :concept-refsets [(Long/parseLong refset)]) (vector? refset) (assoc :concept-refsets (into [] (map #(Long/parseLong %) refset)))))) (def get-search {:name ::get-search :enter (fn [context] (let [params (parse-search-params context) svc (get-in context [:request ::service])] (when (= (:max-hits params) 0) (throw (IllegalArgumentException. "invalid parameter: 0 maxHits"))) (assoc context :result (svc/search svc params))))}) (def common-routes [coerce-body content-neg-intc entity-render]) (def routes (route/expand-routes #{["/v1/snomed/concepts/:concept-id" :get (conj common-routes get-concept)] ["/v1/snomed/concepts/:concept-id/descriptions" :get (conj common-routes get-concept-descriptions)] ["/v1/snomed/concepts/:concept-id/extended" :get [coerce-body content-neg-intc entity-render get-extended-concept]] ["/v1/snomed/concepts/:concept-id/map/:refset-id" :get [coerce-body content-neg-intc entity-render get-map-to]] ["/v1/snomed/concepts/:concept-id/subsumed-by/:subsumer-id" :get [coerce-body content-neg-intc entity-render subsumed-by?]] ["/v1/snomed/crossmap/:refset-id/:code" :get [coerce-body content-neg-intc entity-render get-map-from]] ["/v1/snomed/search" :get [service-error-handler coerce-body content-neg-intc entity-render get-search]]})) (def service-map {::http/routes routes ::http/type :jetty ::http/port 8081 ::http/host "0.0.0.0" }) (defn start-server ([svc port] (start-server svc port true)) ([svc port join?] (log/info "starting server on port " port) (http/start (http/create-server (-> service-map (assoc ::http/port port) (assoc ::http/join? join?) (http/default-interceptors) (update ::http/interceptors conj (intc/interceptor (inject-svc svc)))))))) (defn stop-server [server] (http/stop server)) (comment )
[ { "context": "; Copyright (c) Chris Houser, Jan 2009. All rights reserved.\n; The use and d", "end": 30, "score": 0.9998304843902588, "start": 18, "tag": "NAME", "value": "Chris Houser" }, { "context": "; Copyright (c) Chris Houser, Jan 2009. All rights reserved.\n; The use and distri", "end": 35, "score": 0.9873799085617065, "start": 32, "tag": "NAME", "value": "Jan" } ]
ThirdParty/clojure-contrib-1.1.0/clojurescript/src/clojure/contrib/clojurescript/applet.clj
allertonm/Couverjure
3
; Copyright (c) Chris Houser, Jan 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. ; Applet that provides Clojure-to-JavaScript functionality to a browser (ns clojure.contrib.clojurescript.applet (:import (java.io PrintWriter StringReader)) (:gen-class :extends java.applet.Applet :methods [[tojs [String] Object]]) (:use [clojure.contrib.clojurescript :only (formtojs filetojs)]) (:require [clojure.contrib.duck-streams :as ds])) (defn -tojs [this cljstr] (try ["js" (with-out-str (filetojs (StringReader. cljstr) :debug-fn-names false :debug-comments false :eval-defmacro true))] (catch Throwable e (if (= (.getMessage e) "EOF while reading") ["incomplete"] ["err" (with-out-str (.printStackTrace e (PrintWriter. *out*)))]))))
55020
; Copyright (c) <NAME>, <NAME> 2009. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ; Applet that provides Clojure-to-JavaScript functionality to a browser (ns clojure.contrib.clojurescript.applet (:import (java.io PrintWriter StringReader)) (:gen-class :extends java.applet.Applet :methods [[tojs [String] Object]]) (:use [clojure.contrib.clojurescript :only (formtojs filetojs)]) (:require [clojure.contrib.duck-streams :as ds])) (defn -tojs [this cljstr] (try ["js" (with-out-str (filetojs (StringReader. cljstr) :debug-fn-names false :debug-comments false :eval-defmacro true))] (catch Throwable e (if (= (.getMessage e) "EOF while reading") ["incomplete"] ["err" (with-out-str (.printStackTrace e (PrintWriter. *out*)))]))))
true
; Copyright (c) PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI 2009. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. ; Applet that provides Clojure-to-JavaScript functionality to a browser (ns clojure.contrib.clojurescript.applet (:import (java.io PrintWriter StringReader)) (:gen-class :extends java.applet.Applet :methods [[tojs [String] Object]]) (:use [clojure.contrib.clojurescript :only (formtojs filetojs)]) (:require [clojure.contrib.duck-streams :as ds])) (defn -tojs [this cljstr] (try ["js" (with-out-str (filetojs (StringReader. cljstr) :debug-fn-names false :debug-comments false :eval-defmacro true))] (catch Throwable e (if (= (.getMessage e) "EOF while reading") ["incomplete"] ["err" (with-out-str (.printStackTrace e (PrintWriter. *out*)))]))))
[ { "context": "-09\" :to #inst \"2014-09\" :type :talk}\n {:title \"Bezalel\" :from #inst \"2011-04\" :to #inst \"2011", "end": 2800, "score": 0.9982798099517822, "start": 2793, "tag": "NAME", "value": "Bezalel" } ]
examples/viz/timeline.clj
gaybro8777/geom
803
(require '[thi.ng.geom.viz.core :as viz] :reload) (require '[thi.ng.geom.svg.core :as svg]) (require '[thi.ng.geom.vector :as v]) (require '[thi.ng.color.core :as col]) (require '[thi.ng.math.core :as m :refer [PI TWO_PI]]) (require '[thi.ng.color.core :as col]) (import '[java.util Calendar GregorianCalendar]) (def items [{:title "toxiclibs" :from #inst "2006-03" :to #inst "2013-06" :type :oss} {:title "thi.ng/geom" :from #inst "2011-08" :to #inst "2015-10" :type :oss} {:title "thi.ng/trio" :from #inst "2012-12" :to #inst "2015-06" :type :oss} {:title "thi.ng/fabric" :from #inst "2014-12" :to #inst "2015-09" :type :oss} {:title "thi.ng/simplecl" :from #inst "2012-10" :to #inst "2013-06" :type :oss} {:title "thi.ng/raymarchcl" :from #inst "2013-02" :to #inst "2013-05" :type :oss} {:title "thi.ng/structgen" :from #inst "2012-10" :to #inst "2013-02" :type :oss} {:title "thi.ng/luxor" :from #inst "2013-10" :to #inst "2015-06" :type :oss} {:title "thi.ng/morphogen" :from #inst "2014-03" :to #inst "2015-06" :type :oss} {:title "thi.ng/color" :from #inst "2014-09" :to #inst "2015-10" :type :oss} {:title "thi.ng/validate" :from #inst "2014-05" :to #inst "2015-06" :type :oss} {:title "thi.ng/ndarray" :from #inst "2015-05" :to #inst "2015-06" :type :oss} {:title "thi.ng/tweeny" :from #inst "2013-10" :to #inst "2015-01" :type :oss} {:title "Co(De)Factory" :from #inst "2013-12" :to #inst "2014-08" :type :project} {:title "Chrome WebLab" :from #inst "2011-05" :to #inst "2012-11" :type :project} {:title "ODI" :from #inst "2013-07" :to #inst "2013-10" :type :project} {:title "LCOM" :from #inst "2012-06" :to #inst "2013-05" :type :project} {:title "V&amp;A Ornamental" :from #inst "2010-12" :to #inst "2011-05" :type :project} {:title "Engine26" :from #inst "2010-08" :to #inst "2010-12" :type :project} {:title "Resonate" :from #inst "2012-04" :to #inst "2012-04" :type :workshop} {:title "Resonate" :from #inst "2013-03" :to #inst "2013-03" :type :workshop} {:title "Resonate" :from #inst "2014-04" :to #inst "2014-04" :type :workshop} {:title "Resonate" :from #inst "2015-04" :to #inst "2015-04" :type :workshop} {:title "Resonate" :from #inst "2012-04" :to #inst "2012-04" :type :talk} {:title "Resonate" :from #inst "2013-03" :to #inst "2013-03" :type :talk} {:title "Resonate" :from #inst "2014-04" :to #inst "2014-04" :type :talk} {:title "Resonate" :from #inst "2015-04" :to #inst "2015-04" :type :talk} {:title "Retune" :from #inst "2014-09" :to #inst "2014-09" :type :talk} {:title "Bezalel" :from #inst "2011-04" :to #inst "2011-04" :type :workshop} {:title "V&amp;A" :from #inst "2011-01" :to #inst "2011-03" :type :workshop} {:title "HEAD" :from #inst "2010-10" :to #inst "2010-10" :type :workshop} {:title "ETH" :from #inst "2010-11" :to #inst "2010-11" :type :workshop} {:title "SAC" :from #inst "2012-11" :to #inst "2012-11" :type :workshop} {:title "SAC" :from #inst "2014-12" :to #inst "2014-12" :type :workshop} {:title "MSA" :from #inst "2013-04" :to #inst "2013-04" :type :workshop} {:title "Young Creators" :from #inst "2014-06" :to #inst "2014-06" :type :workshop} {:title "EYEO" :from #inst "2013-06" :to #inst "2013-06" :type :talk} {:title "Reasons" :from #inst "2014-02" :to #inst "2014-02" :type :talk} {:title "Reasons" :from #inst "2014-09" :to #inst "2014-09" :type :talk}]) (def item-type-colors {:project "#0af" :oss "#63f" :workshop "#9f0" :talk "#f9f"}) (def month (* (/ (+ (* 3 365) 366) 4.0 12.0) 24 60 60 1000)) (def year (* month 12)) (defn ->epoch [^java.util.Date d] (.getTime d)) ;; http://stackoverflow.com/questions/9001384/java-date-rounding (defn round-to-year [epoch] (let [cal (GregorianCalendar.)] (doto cal (.setTimeInMillis (long epoch)) (.add Calendar/MONTH 6) (.set Calendar/MONTH 0) (.set Calendar/DAY_OF_MONTH 1) (.set Calendar/HOUR 0) (.set Calendar/MINUTE 0) (.set Calendar/SECOND 0) (.set Calendar/MILLISECOND 0)) (.get cal Calendar/YEAR))) (defn make-gradient [[id base]] (let [base (col/as-hsva (col/css base))] (svg/linear-gradient id {} [0 base] [1 (col/adjust-saturation base -0.66)]))) (defn item-range [i] [(->epoch (:from i)) (->epoch (:to i))]) (defn timeline-spec [type offset] {:values (if type (filter #(= type (:type %)) items) items) :offset offset :item-range item-range :attribs {:fill "white" :stroke "none" :font-family "Arial" :font-size 10} :shape (viz/labeled-rect-horizontal {:h 14 :r 7 :min-width 30 :base-line 3 :label :title :fill #(str "url(#" (name (:type %)) ")")}) :layout viz/svg-stacked-interval-plot}) ;; Create stacked timeline with *all* items (->> {:x-axis (viz/linear-axis {:domain [(->epoch #inst "2010-09") (->epoch #inst "2015-06")] :range [10 950] :pos 160 :major year :minor month :label (viz/default-svg-label round-to-year)}) :y-axis (viz/linear-axis {:domain [0 9] :range [10 160] :visible false}) :grid {:minor-x true} :data [(timeline-spec nil 0)]} (viz/svg-plot2d-cartesian) (svg/svg {:width 960 :height 200} (apply svg/defs (map make-gradient item-type-colors))) (svg/serialize) (spit "out/timeline.svg")) ;; Create stacked timeline vertically grouped by item type (->> {:x-axis (viz/linear-axis {:domain [(->epoch #inst "2010-09") (->epoch #inst "2015-06")] :range [10 950] :pos 220 :major year :minor month :label (viz/default-svg-label round-to-year)}) :y-axis (viz/linear-axis {:domain [0 13] :range [10 220] :visible false}) :grid {:minor-x true} :data [(timeline-spec :project 0) (timeline-spec :oss 2) (timeline-spec :workshop 10) (timeline-spec :talk 11)]} (viz/svg-plot2d-cartesian) (svg/svg {:width 960 :height 245} (apply svg/defs (map make-gradient item-type-colors))) (svg/serialize) (spit "out/timeline-separate.svg"))
65996
(require '[thi.ng.geom.viz.core :as viz] :reload) (require '[thi.ng.geom.svg.core :as svg]) (require '[thi.ng.geom.vector :as v]) (require '[thi.ng.color.core :as col]) (require '[thi.ng.math.core :as m :refer [PI TWO_PI]]) (require '[thi.ng.color.core :as col]) (import '[java.util Calendar GregorianCalendar]) (def items [{:title "toxiclibs" :from #inst "2006-03" :to #inst "2013-06" :type :oss} {:title "thi.ng/geom" :from #inst "2011-08" :to #inst "2015-10" :type :oss} {:title "thi.ng/trio" :from #inst "2012-12" :to #inst "2015-06" :type :oss} {:title "thi.ng/fabric" :from #inst "2014-12" :to #inst "2015-09" :type :oss} {:title "thi.ng/simplecl" :from #inst "2012-10" :to #inst "2013-06" :type :oss} {:title "thi.ng/raymarchcl" :from #inst "2013-02" :to #inst "2013-05" :type :oss} {:title "thi.ng/structgen" :from #inst "2012-10" :to #inst "2013-02" :type :oss} {:title "thi.ng/luxor" :from #inst "2013-10" :to #inst "2015-06" :type :oss} {:title "thi.ng/morphogen" :from #inst "2014-03" :to #inst "2015-06" :type :oss} {:title "thi.ng/color" :from #inst "2014-09" :to #inst "2015-10" :type :oss} {:title "thi.ng/validate" :from #inst "2014-05" :to #inst "2015-06" :type :oss} {:title "thi.ng/ndarray" :from #inst "2015-05" :to #inst "2015-06" :type :oss} {:title "thi.ng/tweeny" :from #inst "2013-10" :to #inst "2015-01" :type :oss} {:title "Co(De)Factory" :from #inst "2013-12" :to #inst "2014-08" :type :project} {:title "Chrome WebLab" :from #inst "2011-05" :to #inst "2012-11" :type :project} {:title "ODI" :from #inst "2013-07" :to #inst "2013-10" :type :project} {:title "LCOM" :from #inst "2012-06" :to #inst "2013-05" :type :project} {:title "V&amp;A Ornamental" :from #inst "2010-12" :to #inst "2011-05" :type :project} {:title "Engine26" :from #inst "2010-08" :to #inst "2010-12" :type :project} {:title "Resonate" :from #inst "2012-04" :to #inst "2012-04" :type :workshop} {:title "Resonate" :from #inst "2013-03" :to #inst "2013-03" :type :workshop} {:title "Resonate" :from #inst "2014-04" :to #inst "2014-04" :type :workshop} {:title "Resonate" :from #inst "2015-04" :to #inst "2015-04" :type :workshop} {:title "Resonate" :from #inst "2012-04" :to #inst "2012-04" :type :talk} {:title "Resonate" :from #inst "2013-03" :to #inst "2013-03" :type :talk} {:title "Resonate" :from #inst "2014-04" :to #inst "2014-04" :type :talk} {:title "Resonate" :from #inst "2015-04" :to #inst "2015-04" :type :talk} {:title "Retune" :from #inst "2014-09" :to #inst "2014-09" :type :talk} {:title "<NAME>" :from #inst "2011-04" :to #inst "2011-04" :type :workshop} {:title "V&amp;A" :from #inst "2011-01" :to #inst "2011-03" :type :workshop} {:title "HEAD" :from #inst "2010-10" :to #inst "2010-10" :type :workshop} {:title "ETH" :from #inst "2010-11" :to #inst "2010-11" :type :workshop} {:title "SAC" :from #inst "2012-11" :to #inst "2012-11" :type :workshop} {:title "SAC" :from #inst "2014-12" :to #inst "2014-12" :type :workshop} {:title "MSA" :from #inst "2013-04" :to #inst "2013-04" :type :workshop} {:title "Young Creators" :from #inst "2014-06" :to #inst "2014-06" :type :workshop} {:title "EYEO" :from #inst "2013-06" :to #inst "2013-06" :type :talk} {:title "Reasons" :from #inst "2014-02" :to #inst "2014-02" :type :talk} {:title "Reasons" :from #inst "2014-09" :to #inst "2014-09" :type :talk}]) (def item-type-colors {:project "#0af" :oss "#63f" :workshop "#9f0" :talk "#f9f"}) (def month (* (/ (+ (* 3 365) 366) 4.0 12.0) 24 60 60 1000)) (def year (* month 12)) (defn ->epoch [^java.util.Date d] (.getTime d)) ;; http://stackoverflow.com/questions/9001384/java-date-rounding (defn round-to-year [epoch] (let [cal (GregorianCalendar.)] (doto cal (.setTimeInMillis (long epoch)) (.add Calendar/MONTH 6) (.set Calendar/MONTH 0) (.set Calendar/DAY_OF_MONTH 1) (.set Calendar/HOUR 0) (.set Calendar/MINUTE 0) (.set Calendar/SECOND 0) (.set Calendar/MILLISECOND 0)) (.get cal Calendar/YEAR))) (defn make-gradient [[id base]] (let [base (col/as-hsva (col/css base))] (svg/linear-gradient id {} [0 base] [1 (col/adjust-saturation base -0.66)]))) (defn item-range [i] [(->epoch (:from i)) (->epoch (:to i))]) (defn timeline-spec [type offset] {:values (if type (filter #(= type (:type %)) items) items) :offset offset :item-range item-range :attribs {:fill "white" :stroke "none" :font-family "Arial" :font-size 10} :shape (viz/labeled-rect-horizontal {:h 14 :r 7 :min-width 30 :base-line 3 :label :title :fill #(str "url(#" (name (:type %)) ")")}) :layout viz/svg-stacked-interval-plot}) ;; Create stacked timeline with *all* items (->> {:x-axis (viz/linear-axis {:domain [(->epoch #inst "2010-09") (->epoch #inst "2015-06")] :range [10 950] :pos 160 :major year :minor month :label (viz/default-svg-label round-to-year)}) :y-axis (viz/linear-axis {:domain [0 9] :range [10 160] :visible false}) :grid {:minor-x true} :data [(timeline-spec nil 0)]} (viz/svg-plot2d-cartesian) (svg/svg {:width 960 :height 200} (apply svg/defs (map make-gradient item-type-colors))) (svg/serialize) (spit "out/timeline.svg")) ;; Create stacked timeline vertically grouped by item type (->> {:x-axis (viz/linear-axis {:domain [(->epoch #inst "2010-09") (->epoch #inst "2015-06")] :range [10 950] :pos 220 :major year :minor month :label (viz/default-svg-label round-to-year)}) :y-axis (viz/linear-axis {:domain [0 13] :range [10 220] :visible false}) :grid {:minor-x true} :data [(timeline-spec :project 0) (timeline-spec :oss 2) (timeline-spec :workshop 10) (timeline-spec :talk 11)]} (viz/svg-plot2d-cartesian) (svg/svg {:width 960 :height 245} (apply svg/defs (map make-gradient item-type-colors))) (svg/serialize) (spit "out/timeline-separate.svg"))
true
(require '[thi.ng.geom.viz.core :as viz] :reload) (require '[thi.ng.geom.svg.core :as svg]) (require '[thi.ng.geom.vector :as v]) (require '[thi.ng.color.core :as col]) (require '[thi.ng.math.core :as m :refer [PI TWO_PI]]) (require '[thi.ng.color.core :as col]) (import '[java.util Calendar GregorianCalendar]) (def items [{:title "toxiclibs" :from #inst "2006-03" :to #inst "2013-06" :type :oss} {:title "thi.ng/geom" :from #inst "2011-08" :to #inst "2015-10" :type :oss} {:title "thi.ng/trio" :from #inst "2012-12" :to #inst "2015-06" :type :oss} {:title "thi.ng/fabric" :from #inst "2014-12" :to #inst "2015-09" :type :oss} {:title "thi.ng/simplecl" :from #inst "2012-10" :to #inst "2013-06" :type :oss} {:title "thi.ng/raymarchcl" :from #inst "2013-02" :to #inst "2013-05" :type :oss} {:title "thi.ng/structgen" :from #inst "2012-10" :to #inst "2013-02" :type :oss} {:title "thi.ng/luxor" :from #inst "2013-10" :to #inst "2015-06" :type :oss} {:title "thi.ng/morphogen" :from #inst "2014-03" :to #inst "2015-06" :type :oss} {:title "thi.ng/color" :from #inst "2014-09" :to #inst "2015-10" :type :oss} {:title "thi.ng/validate" :from #inst "2014-05" :to #inst "2015-06" :type :oss} {:title "thi.ng/ndarray" :from #inst "2015-05" :to #inst "2015-06" :type :oss} {:title "thi.ng/tweeny" :from #inst "2013-10" :to #inst "2015-01" :type :oss} {:title "Co(De)Factory" :from #inst "2013-12" :to #inst "2014-08" :type :project} {:title "Chrome WebLab" :from #inst "2011-05" :to #inst "2012-11" :type :project} {:title "ODI" :from #inst "2013-07" :to #inst "2013-10" :type :project} {:title "LCOM" :from #inst "2012-06" :to #inst "2013-05" :type :project} {:title "V&amp;A Ornamental" :from #inst "2010-12" :to #inst "2011-05" :type :project} {:title "Engine26" :from #inst "2010-08" :to #inst "2010-12" :type :project} {:title "Resonate" :from #inst "2012-04" :to #inst "2012-04" :type :workshop} {:title "Resonate" :from #inst "2013-03" :to #inst "2013-03" :type :workshop} {:title "Resonate" :from #inst "2014-04" :to #inst "2014-04" :type :workshop} {:title "Resonate" :from #inst "2015-04" :to #inst "2015-04" :type :workshop} {:title "Resonate" :from #inst "2012-04" :to #inst "2012-04" :type :talk} {:title "Resonate" :from #inst "2013-03" :to #inst "2013-03" :type :talk} {:title "Resonate" :from #inst "2014-04" :to #inst "2014-04" :type :talk} {:title "Resonate" :from #inst "2015-04" :to #inst "2015-04" :type :talk} {:title "Retune" :from #inst "2014-09" :to #inst "2014-09" :type :talk} {:title "PI:NAME:<NAME>END_PI" :from #inst "2011-04" :to #inst "2011-04" :type :workshop} {:title "V&amp;A" :from #inst "2011-01" :to #inst "2011-03" :type :workshop} {:title "HEAD" :from #inst "2010-10" :to #inst "2010-10" :type :workshop} {:title "ETH" :from #inst "2010-11" :to #inst "2010-11" :type :workshop} {:title "SAC" :from #inst "2012-11" :to #inst "2012-11" :type :workshop} {:title "SAC" :from #inst "2014-12" :to #inst "2014-12" :type :workshop} {:title "MSA" :from #inst "2013-04" :to #inst "2013-04" :type :workshop} {:title "Young Creators" :from #inst "2014-06" :to #inst "2014-06" :type :workshop} {:title "EYEO" :from #inst "2013-06" :to #inst "2013-06" :type :talk} {:title "Reasons" :from #inst "2014-02" :to #inst "2014-02" :type :talk} {:title "Reasons" :from #inst "2014-09" :to #inst "2014-09" :type :talk}]) (def item-type-colors {:project "#0af" :oss "#63f" :workshop "#9f0" :talk "#f9f"}) (def month (* (/ (+ (* 3 365) 366) 4.0 12.0) 24 60 60 1000)) (def year (* month 12)) (defn ->epoch [^java.util.Date d] (.getTime d)) ;; http://stackoverflow.com/questions/9001384/java-date-rounding (defn round-to-year [epoch] (let [cal (GregorianCalendar.)] (doto cal (.setTimeInMillis (long epoch)) (.add Calendar/MONTH 6) (.set Calendar/MONTH 0) (.set Calendar/DAY_OF_MONTH 1) (.set Calendar/HOUR 0) (.set Calendar/MINUTE 0) (.set Calendar/SECOND 0) (.set Calendar/MILLISECOND 0)) (.get cal Calendar/YEAR))) (defn make-gradient [[id base]] (let [base (col/as-hsva (col/css base))] (svg/linear-gradient id {} [0 base] [1 (col/adjust-saturation base -0.66)]))) (defn item-range [i] [(->epoch (:from i)) (->epoch (:to i))]) (defn timeline-spec [type offset] {:values (if type (filter #(= type (:type %)) items) items) :offset offset :item-range item-range :attribs {:fill "white" :stroke "none" :font-family "Arial" :font-size 10} :shape (viz/labeled-rect-horizontal {:h 14 :r 7 :min-width 30 :base-line 3 :label :title :fill #(str "url(#" (name (:type %)) ")")}) :layout viz/svg-stacked-interval-plot}) ;; Create stacked timeline with *all* items (->> {:x-axis (viz/linear-axis {:domain [(->epoch #inst "2010-09") (->epoch #inst "2015-06")] :range [10 950] :pos 160 :major year :minor month :label (viz/default-svg-label round-to-year)}) :y-axis (viz/linear-axis {:domain [0 9] :range [10 160] :visible false}) :grid {:minor-x true} :data [(timeline-spec nil 0)]} (viz/svg-plot2d-cartesian) (svg/svg {:width 960 :height 200} (apply svg/defs (map make-gradient item-type-colors))) (svg/serialize) (spit "out/timeline.svg")) ;; Create stacked timeline vertically grouped by item type (->> {:x-axis (viz/linear-axis {:domain [(->epoch #inst "2010-09") (->epoch #inst "2015-06")] :range [10 950] :pos 220 :major year :minor month :label (viz/default-svg-label round-to-year)}) :y-axis (viz/linear-axis {:domain [0 13] :range [10 220] :visible false}) :grid {:minor-x true} :data [(timeline-spec :project 0) (timeline-spec :oss 2) (timeline-spec :workshop 10) (timeline-spec :talk 11)]} (viz/svg-plot2d-cartesian) (svg/svg {:width 960 :height 245} (apply svg/defs (map make-gradient item-type-colors))) (svg/serialize) (spit "out/timeline-separate.svg"))
[ { "context": "ng utility functions.\"\n :url \"https://github.com/chartbeat-labs/cljbeat-options\"\n :license {:name \"Apache Licens", "end": 161, "score": 0.9976116418838501, "start": 147, "tag": "USERNAME", "value": "chartbeat-labs" }, { "context": "ies [[\"releases\" :clojars]]\n :signing {:gpg-key \"F0903068\"}\n\n :aot :all\n :vcs :git)\n", "end": 558, "score": 0.9990371465682983, "start": 550, "tag": "KEY", "value": "F0903068" } ]
project.clj
chartbeat-labs/cljbeat-options
1
(defproject com.chartbeat.cljbeat/options "1.0.0" :description "Chartbeat specific option parsing utility functions." :url "https://github.com/chartbeat-labs/cljbeat-options" :license {:name "Apache License, Version 2.0" :url "http://www.apache.org/license/LICENSE-2.0.html"} :dependencies [[org.clojure/clojure "1.6.0"] [org.clojure/tools.cli "0.3.1"] [org.clojure/tools.logging "0.3.1"] [clj-yaml "0.4.0"]] :deploy-repositories [["releases" :clojars]] :signing {:gpg-key "F0903068"} :aot :all :vcs :git)
78870
(defproject com.chartbeat.cljbeat/options "1.0.0" :description "Chartbeat specific option parsing utility functions." :url "https://github.com/chartbeat-labs/cljbeat-options" :license {:name "Apache License, Version 2.0" :url "http://www.apache.org/license/LICENSE-2.0.html"} :dependencies [[org.clojure/clojure "1.6.0"] [org.clojure/tools.cli "0.3.1"] [org.clojure/tools.logging "0.3.1"] [clj-yaml "0.4.0"]] :deploy-repositories [["releases" :clojars]] :signing {:gpg-key "<KEY>"} :aot :all :vcs :git)
true
(defproject com.chartbeat.cljbeat/options "1.0.0" :description "Chartbeat specific option parsing utility functions." :url "https://github.com/chartbeat-labs/cljbeat-options" :license {:name "Apache License, Version 2.0" :url "http://www.apache.org/license/LICENSE-2.0.html"} :dependencies [[org.clojure/clojure "1.6.0"] [org.clojure/tools.cli "0.3.1"] [org.clojure/tools.logging "0.3.1"] [clj-yaml "0.4.0"]] :deploy-repositories [["releases" :clojars]] :signing {:gpg-key "PI:KEY:<KEY>END_PI"} :aot :all :vcs :git)
[ { "context": "n test-add-patients []\n (let [patients {}\n victor {:id 1 :name \"Victor\"}\n leo {:id 1 :n", "end": 361, "score": 0.833908200263977, "start": 360, "tag": "NAME", "value": "v" }, { "context": "test-add-patients []\n (let [patients {}\n victor {:id 1 :name \"Victor\"}\n leo {:id 1 :name \"", "end": 366, "score": 0.7186668515205383, "start": 361, "tag": "NAME", "value": "ictor" }, { "context": "\n (let [patients {}\n victor {:id 1 :name \"Victor\"}\n leo {:id 1 :name \"Leo\"}\n billy {", "end": 387, "score": 0.9994335770606995, "start": 381, "tag": "NAME", "value": "Victor" }, { "context": "s {}\n victor {:id 1 :name \"Victor\"}\n leo {:id 1 :name \"Leo\"}\n billy {:name \"Billy\"}", "end": 401, "score": 0.8266732096672058, "start": 398, "tag": "NAME", "value": "leo" }, { "context": " {:id 1 :name \"Victor\"}\n leo {:id 1 :name \"Leo\"}\n billy {:name \"Billy\"}]\n\n (pprint (ad", "end": 419, "score": 0.9994515180587769, "start": 416, "tag": "NAME", "value": "Leo" }, { "context": " \"Victor\"}\n leo {:id 1 :name \"Leo\"}\n billy {:name \"Billy\"}]\n\n (pprint (add-patient patien", "end": 435, "score": 0.6882025003433228, "start": 430, "tag": "NAME", "value": "billy" }, { "context": " leo {:id 1 :name \"Leo\"}\n billy {:name \"Billy\"}]\n\n (pprint (add-patient patients victor))\n ", "end": 449, "score": 0.999644935131073, "start": 444, "tag": "NAME", "value": "Billy" }, { "context": ":name \"Billy\"}]\n\n (pprint (add-patient patients victor))\n (pprint (add-patient patients leo))\n ", "end": 489, "score": 0.8209129571914673, "start": 488, "tag": "NAME", "value": "v" }, { "context": "ame \"Billy\"}]\n\n (pprint (add-patient patients victor))\n (pprint (add-patient patients leo))\n (pp", "end": 494, "score": 0.7067751884460449, "start": 489, "tag": "NAME", "value": "ictor" }, { "context": "atients victor))\n (pprint (add-patient patients leo))\n (pprint (add-patient patients billy))))\n\n; ", "end": 534, "score": 0.912771463394165, "start": 531, "tag": "NAME", "value": "leo" }, { "context": "record Patient [id, name])\n\n(pprint (->Patient 1 \"Fred\"))\n(pprint (Patient. 1 \"Fred\"))\n(pprint (map->Pat", "end": 716, "score": 0.9995927810668945, "start": 712, "tag": "NAME", "value": "Fred" }, { "context": "pprint (->Patient 1 \"Fred\"))\n(pprint (Patient. 1 \"Fred\"))\n(pprint (map->Patient {:id 1 :name \"Fred\"}))\n\n", "end": 745, "score": 0.9995229244232178, "start": 741, "tag": "NAME", "value": "Fred" }, { "context": "t. 1 \"Fred\"))\n(pprint (map->Patient {:id 1 :name \"Fred\"}))\n\n(let [fred (->Patient 1 \"Fred\")\n ; Can ", "end": 789, "score": 0.9996026158332825, "start": 785, "tag": "NAME", "value": "Fred" }, { "context": "rint (map->Patient {:id 1 :name \"Fred\"}))\n\n(let [fred (->Patient 1 \"Fred\")\n ; Can define extra/les", "end": 805, "score": 0.5492523908615112, "start": 802, "tag": "NAME", "value": "red" }, { "context": " {:id 1 :name \"Fred\"}))\n\n(let [fred (->Patient 1 \"Fred\")\n ; Can define extra/less arguments\n p", "end": 824, "score": 0.9989393949508667, "start": 820, "tag": "NAME", "value": "Fred" }, { "context": "arguments\n peter (map->Patient {:id 1 :name \"Peter\" :document \"123456\"})]\n\n ; Can be used like a ma", "end": 912, "score": 0.9988933801651001, "start": 907, "tag": "NAME", "value": "Peter" }, { "context": "456\"})]\n\n ; Can be used like a map\n (pprint (:id fred))\n (pprint (vals fred))\n (println \"Is record", "end": 980, "score": 0.5457991361618042, "start": 979, "tag": "NAME", "value": "f" }, { "context": "6\"})]\n\n ; Can be used like a map\n (pprint (:id fred))\n (pprint (vals fred))\n (println \"Is record? \"", "end": 983, "score": 0.5288623571395874, "start": 980, "tag": "NAME", "value": "red" }, { "context": " (println \"Compare Fred: \" (= fred (->Patient 1 \"Fred\")))\n (println \"Compare different: \" (= fred (->P", "end": 1315, "score": 0.9963430166244507, "start": 1311, "tag": "NAME", "value": "Fred" }, { "context": "intln \"Compare different: \" (= fred (->Patient 1 \"Peter\"))))", "end": 1380, "score": 0.992455005645752, "start": 1375, "tag": "NAME", "value": "Peter" } ]
hospital_patient/src/hospital_patient/class1.clj
vgeorgo/courses-alura-clojure
0
(ns hospital-patient.class1 (:use clojure.pprint)) (defn add-patient "Add a patient to a list of patients. Throw exception if :id id not provided" [patients patient] (if-let [id (:id patient)] (assoc patients id patient) (throw (ex-info "Patient :id not provided" {:patient patient})))) (defn test-add-patients [] (let [patients {} victor {:id 1 :name "Victor"} leo {:id 1 :name "Leo"} billy {:name "Billy"}] (pprint (add-patient patients victor)) (pprint (add-patient patients leo)) (pprint (add-patient patients billy)))) ; (test-add-patients) ; Behind the scenes Patient becomes a class in Java (defrecord Patient [id, name]) (pprint (->Patient 1 "Fred")) (pprint (Patient. 1 "Fred")) (pprint (map->Patient {:id 1 :name "Fred"})) (let [fred (->Patient 1 "Fred") ; Can define extra/less arguments peter (map->Patient {:id 1 :name "Peter" :document "123456"})] ; Can be used like a map (pprint (:id fred)) (pprint (vals fred)) (println "Is record? " (record? fred)) ; Used as a property (faster accessing directly) (println "Name: " (.name fred)) (pprint peter) ; Still immutable, return a new Record with updated values (pprint (assoc fred :id 20)) ; Comparison (println "Compare Fred: " (= fred (->Patient 1 "Fred"))) (println "Compare different: " (= fred (->Patient 1 "Peter"))))
79236
(ns hospital-patient.class1 (:use clojure.pprint)) (defn add-patient "Add a patient to a list of patients. Throw exception if :id id not provided" [patients patient] (if-let [id (:id patient)] (assoc patients id patient) (throw (ex-info "Patient :id not provided" {:patient patient})))) (defn test-add-patients [] (let [patients {} <NAME> <NAME> {:id 1 :name "<NAME>"} <NAME> {:id 1 :name "<NAME>"} <NAME> {:name "<NAME>"}] (pprint (add-patient patients <NAME> <NAME>)) (pprint (add-patient patients <NAME>)) (pprint (add-patient patients billy)))) ; (test-add-patients) ; Behind the scenes Patient becomes a class in Java (defrecord Patient [id, name]) (pprint (->Patient 1 "<NAME>")) (pprint (Patient. 1 "<NAME>")) (pprint (map->Patient {:id 1 :name "<NAME>"})) (let [f<NAME> (->Patient 1 "<NAME>") ; Can define extra/less arguments peter (map->Patient {:id 1 :name "<NAME>" :document "123456"})] ; Can be used like a map (pprint (:id <NAME> <NAME>)) (pprint (vals fred)) (println "Is record? " (record? fred)) ; Used as a property (faster accessing directly) (println "Name: " (.name fred)) (pprint peter) ; Still immutable, return a new Record with updated values (pprint (assoc fred :id 20)) ; Comparison (println "Compare Fred: " (= fred (->Patient 1 "<NAME>"))) (println "Compare different: " (= fred (->Patient 1 "<NAME>"))))
true
(ns hospital-patient.class1 (:use clojure.pprint)) (defn add-patient "Add a patient to a list of patients. Throw exception if :id id not provided" [patients patient] (if-let [id (:id patient)] (assoc patients id patient) (throw (ex-info "Patient :id not provided" {:patient patient})))) (defn test-add-patients [] (let [patients {} PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI {:id 1 :name "PI:NAME:<NAME>END_PI"} PI:NAME:<NAME>END_PI {:id 1 :name "PI:NAME:<NAME>END_PI"} PI:NAME:<NAME>END_PI {:name "PI:NAME:<NAME>END_PI"}] (pprint (add-patient patients PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI)) (pprint (add-patient patients PI:NAME:<NAME>END_PI)) (pprint (add-patient patients billy)))) ; (test-add-patients) ; Behind the scenes Patient becomes a class in Java (defrecord Patient [id, name]) (pprint (->Patient 1 "PI:NAME:<NAME>END_PI")) (pprint (Patient. 1 "PI:NAME:<NAME>END_PI")) (pprint (map->Patient {:id 1 :name "PI:NAME:<NAME>END_PI"})) (let [fPI:NAME:<NAME>END_PI (->Patient 1 "PI:NAME:<NAME>END_PI") ; Can define extra/less arguments peter (map->Patient {:id 1 :name "PI:NAME:<NAME>END_PI" :document "123456"})] ; Can be used like a map (pprint (:id PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI)) (pprint (vals fred)) (println "Is record? " (record? fred)) ; Used as a property (faster accessing directly) (println "Name: " (.name fred)) (pprint peter) ; Still immutable, return a new Record with updated values (pprint (assoc fred :id 20)) ; Comparison (println "Compare Fred: " (= fred (->Patient 1 "PI:NAME:<NAME>END_PI"))) (println "Compare different: " (= fred (->Patient 1 "PI:NAME:<NAME>END_PI"))))
[ { "context": " \"I'm Daniel\"\n ", "end": 1100, "score": 0.9994242191314697, "start": 1094, "tag": "NAME", "value": "Daniel" }, { "context": " \"I'm Daniel, and..\"\n ", "end": 1163, "score": 0.9992483258247375, "start": 1157, "tag": "NAME", "value": "Daniel" } ]
src/cljs/portfolio/home.cljs
DanielRS/portfolio-clojure
0
(ns portfolio.home (:require [cljs.core.async :refer [<! chan close!]] [goog.dom :as dom] [goog.dom.classes :as classes] [goog.events :as events] [garden.color :refer [as-hex]] [portfolio.util :refer [event->chan]] [portfolio.settings :as settings]) (:require-macros [cljs.core.async.macros :refer [go go-loop]])) (defn timeout [ms] (let [c (chan)] (js/setTimeout (fn [] (close! c)) ms) c)) (def nav (dom/getElement "navbar")) (def text-bg (dom/getElementByClass "mega-brand__text")) (defn background-change! [] (let [scroll-y (.-y (dom/getDocumentScroll))] (if (> scroll-y 0) (classes/remove nav "navbar--home") (classes/add nav "navbar--home")))) (defn scroll-handler! [] (let [c (event->chan js/window "scroll")] (go-loop [] (let [_ (<! c)] (background-change!)) (recur)))) (defn ^:export init! [] (background-change!) (scroll-handler!) (.typing (js/$ "#tagline") (clj->js {:sentences ["Hello!" "I'm Daniel" "I'm Daniel, and.." "I'm a programmer"]})))
7293
(ns portfolio.home (:require [cljs.core.async :refer [<! chan close!]] [goog.dom :as dom] [goog.dom.classes :as classes] [goog.events :as events] [garden.color :refer [as-hex]] [portfolio.util :refer [event->chan]] [portfolio.settings :as settings]) (:require-macros [cljs.core.async.macros :refer [go go-loop]])) (defn timeout [ms] (let [c (chan)] (js/setTimeout (fn [] (close! c)) ms) c)) (def nav (dom/getElement "navbar")) (def text-bg (dom/getElementByClass "mega-brand__text")) (defn background-change! [] (let [scroll-y (.-y (dom/getDocumentScroll))] (if (> scroll-y 0) (classes/remove nav "navbar--home") (classes/add nav "navbar--home")))) (defn scroll-handler! [] (let [c (event->chan js/window "scroll")] (go-loop [] (let [_ (<! c)] (background-change!)) (recur)))) (defn ^:export init! [] (background-change!) (scroll-handler!) (.typing (js/$ "#tagline") (clj->js {:sentences ["Hello!" "I'm <NAME>" "I'm <NAME>, and.." "I'm a programmer"]})))
true
(ns portfolio.home (:require [cljs.core.async :refer [<! chan close!]] [goog.dom :as dom] [goog.dom.classes :as classes] [goog.events :as events] [garden.color :refer [as-hex]] [portfolio.util :refer [event->chan]] [portfolio.settings :as settings]) (:require-macros [cljs.core.async.macros :refer [go go-loop]])) (defn timeout [ms] (let [c (chan)] (js/setTimeout (fn [] (close! c)) ms) c)) (def nav (dom/getElement "navbar")) (def text-bg (dom/getElementByClass "mega-brand__text")) (defn background-change! [] (let [scroll-y (.-y (dom/getDocumentScroll))] (if (> scroll-y 0) (classes/remove nav "navbar--home") (classes/add nav "navbar--home")))) (defn scroll-handler! [] (let [c (event->chan js/window "scroll")] (go-loop [] (let [_ (<! c)] (background-change!)) (recur)))) (defn ^:export init! [] (background-change!) (scroll-handler!) (.typing (js/$ "#tagline") (clj->js {:sentences ["Hello!" "I'm PI:NAME:<NAME>END_PI" "I'm PI:NAME:<NAME>END_PI, and.." "I'm a programmer"]})))
[ { "context": "le \"Documentation\"}\n {:href \"https://github.com/zetawar/zetawar/issues\" :title \"Roadmap\"}\n {:href (sit", "end": 2241, "score": 0.999409019947052, "start": 2234, "tag": "USERNAME", "value": "zetawar" }, { "context": " \"Follow \"\n [:a {:href \"https://twitter.com/ZetawarGame\"} \"@ZetawarGame\"]\n \" for updates. \"\n \"Que", "end": 4101, "score": 0.9995603561401367, "start": 4090, "tag": "USERNAME", "value": "ZetawarGame" }, { "context": " [:a {:href \"https://twitter.com/ZetawarGame\"} \"@ZetawarGame\"]\n \" for updates. \"\n \"Questions or commen", "end": 4117, "score": 0.9996688961982727, "start": 4104, "tag": "USERNAME", "value": "\"@ZetawarGame" }, { "context": "rtwork from \"\n [:a {:href \"https://github.com/cvincent/elite-command\"} \"Elite Command\"]\n \" Copyright", "end": 4484, "score": 0.999718964099884, "start": 4476, "tag": "USERNAME", "value": "cvincent" }, { "context": "e-command\"} \"Elite Command\"]\n \" Copyright 2015 Chris Vincent under \"\n [:a {:href \"http://creativecommons.o", "end": 4553, "score": 0.9998613595962524, "start": 4540, "tag": "NAME", "value": "Chris Vincent" } ]
src/cljc/zetawar/views/common.cljc
Zetawar/zetawar
164
(ns zetawar.views.common #?@(:clj [(:require [clojure.java.io :as io] [hiccup.page :refer [html5 include-css include-js]] [zetawar.site :as site])] :cljs [(:require [cljsjs.react-bootstrap] [zetawar.site :as site])])) #?(:clj (do (defn ga [tracking-id] [:script (str "(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){" "(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o)," "m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)" "})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');" "ga('create', '" tracking-id "', 'auto');" "ga('send', 'pageview');")]) (defn sentry [sentry-url environment] [[:script {:src "https://cdn.ravenjs.com/3.9.1/raven.min.js"}] [:script (str "Raven.config('" sentry-url "', {" "release: '" site/build "'," "environment: '" environment "'," "tags: {git_commit: '" site/build "'}" "}).install();")]]) (defn head [{global-meta :meta :as data} title] (into [:head [:meta {:charset "utf-8"}] [:meta {:http-equiv "X-UA-Compatible" :content "IE=edge"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1"}] [:title title] (include-css (site/prefix "/css/main.css")) (include-css (site/prefix "/css/highlight/default.css")) (include-js (site/prefix "/js/highlight.pack.js")) [:script "hljs.initHighlightingOnLoad();"] (some-> (:google-analytics-tracking-id global-meta) ga)] (some-> (:sentry-url global-meta) (sentry (:sentry-environment global-meta))))) )) (def nav-links [{:href (site/prefix "/") :title "Game"} {:href (site/prefix "/blog") :title "Blog"} {:href (site/prefix "/docs") :title "Documentation"} {:href "https://github.com/zetawar/zetawar/issues" :title "Roadmap"} {:href (site/prefix "/backers") :title "Backers"}]) (defn navbar ([] (navbar nil)) ([active-title] #?( :clj [:div#navbar-wrapper {:data-active-title active-title} [:nav.navbar.navbar-inverse.navbar-fixed-top [:div.container [:div.navbar-header [:a.navbar-brand {:href "/"} [:img {:src (site/prefix "/images/navbar-logo.svg")}] "Zetawar"]] [:div#navbar-collapse.collapse.navbar-collapse (into [:ul.nav.navbar-nav ] (for [{:keys [href title]} nav-links] (if (= title active-title) [:li {:class "active"} [:a {:href href} title]] [:li [:a {:href href} title]])))]]]] :cljs [:> js/ReactBootstrap.Navbar {:fixed-top true :inverse true} [:> js/ReactBootstrap.Navbar.Header [:> js/ReactBootstrap.Navbar.Brand [:a {:href "/"} [:img {:src (site/prefix "/images/navbar-logo.svg")}] "Zetawar"]] [:> js/ReactBootstrap.Navbar.Toggle]] [:> js/ReactBootstrap.Navbar.Collapse (into [:> js/ReactBootstrap.Nav] (map-indexed (fn [idx {:keys [href title]}] (let [active (= title active-title)] [:> js/ReactBootstrap.NavItem {:event-key idx :active active :href href} title])) nav-links))]] ) )) (defn footer [] [:div.container [:div#footer [:p "Build: " (if (not-empty site/build) [:a {:href (str "/builds/" site/build)} site/build] "DEV") (when (not-empty site/build-timestamp) (str " • " site/build-timestamp))] [:p "Follow " [:a {:href "https://twitter.com/ZetawarGame"} "@ZetawarGame"] " for updates. " "Questions or comments? Send us some " [:a {:href "http://goo.gl/forms/RgTpkCYDBk"} "feedback"] "."] [:p "Copyright 2016 Arugaba LLC under the " [:a {:href "https://github.com/Zetawar/zetawar/blob/master/LICENSE.txt"} "MIT license"]] [:p "Artwork from " [:a {:href "https://github.com/cvincent/elite-command"} "Elite Command"] " Copyright 2015 Chris Vincent under " [:a {:href "http://creativecommons.org/licenses/by/4.0/"} "Creative Commons Attribution 4.0 International License"]]]])
117179
(ns zetawar.views.common #?@(:clj [(:require [clojure.java.io :as io] [hiccup.page :refer [html5 include-css include-js]] [zetawar.site :as site])] :cljs [(:require [cljsjs.react-bootstrap] [zetawar.site :as site])])) #?(:clj (do (defn ga [tracking-id] [:script (str "(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){" "(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o)," "m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)" "})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');" "ga('create', '" tracking-id "', 'auto');" "ga('send', 'pageview');")]) (defn sentry [sentry-url environment] [[:script {:src "https://cdn.ravenjs.com/3.9.1/raven.min.js"}] [:script (str "Raven.config('" sentry-url "', {" "release: '" site/build "'," "environment: '" environment "'," "tags: {git_commit: '" site/build "'}" "}).install();")]]) (defn head [{global-meta :meta :as data} title] (into [:head [:meta {:charset "utf-8"}] [:meta {:http-equiv "X-UA-Compatible" :content "IE=edge"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1"}] [:title title] (include-css (site/prefix "/css/main.css")) (include-css (site/prefix "/css/highlight/default.css")) (include-js (site/prefix "/js/highlight.pack.js")) [:script "hljs.initHighlightingOnLoad();"] (some-> (:google-analytics-tracking-id global-meta) ga)] (some-> (:sentry-url global-meta) (sentry (:sentry-environment global-meta))))) )) (def nav-links [{:href (site/prefix "/") :title "Game"} {:href (site/prefix "/blog") :title "Blog"} {:href (site/prefix "/docs") :title "Documentation"} {:href "https://github.com/zetawar/zetawar/issues" :title "Roadmap"} {:href (site/prefix "/backers") :title "Backers"}]) (defn navbar ([] (navbar nil)) ([active-title] #?( :clj [:div#navbar-wrapper {:data-active-title active-title} [:nav.navbar.navbar-inverse.navbar-fixed-top [:div.container [:div.navbar-header [:a.navbar-brand {:href "/"} [:img {:src (site/prefix "/images/navbar-logo.svg")}] "Zetawar"]] [:div#navbar-collapse.collapse.navbar-collapse (into [:ul.nav.navbar-nav ] (for [{:keys [href title]} nav-links] (if (= title active-title) [:li {:class "active"} [:a {:href href} title]] [:li [:a {:href href} title]])))]]]] :cljs [:> js/ReactBootstrap.Navbar {:fixed-top true :inverse true} [:> js/ReactBootstrap.Navbar.Header [:> js/ReactBootstrap.Navbar.Brand [:a {:href "/"} [:img {:src (site/prefix "/images/navbar-logo.svg")}] "Zetawar"]] [:> js/ReactBootstrap.Navbar.Toggle]] [:> js/ReactBootstrap.Navbar.Collapse (into [:> js/ReactBootstrap.Nav] (map-indexed (fn [idx {:keys [href title]}] (let [active (= title active-title)] [:> js/ReactBootstrap.NavItem {:event-key idx :active active :href href} title])) nav-links))]] ) )) (defn footer [] [:div.container [:div#footer [:p "Build: " (if (not-empty site/build) [:a {:href (str "/builds/" site/build)} site/build] "DEV") (when (not-empty site/build-timestamp) (str " • " site/build-timestamp))] [:p "Follow " [:a {:href "https://twitter.com/ZetawarGame"} "@ZetawarGame"] " for updates. " "Questions or comments? Send us some " [:a {:href "http://goo.gl/forms/RgTpkCYDBk"} "feedback"] "."] [:p "Copyright 2016 Arugaba LLC under the " [:a {:href "https://github.com/Zetawar/zetawar/blob/master/LICENSE.txt"} "MIT license"]] [:p "Artwork from " [:a {:href "https://github.com/cvincent/elite-command"} "Elite Command"] " Copyright 2015 <NAME> under " [:a {:href "http://creativecommons.org/licenses/by/4.0/"} "Creative Commons Attribution 4.0 International License"]]]])
true
(ns zetawar.views.common #?@(:clj [(:require [clojure.java.io :as io] [hiccup.page :refer [html5 include-css include-js]] [zetawar.site :as site])] :cljs [(:require [cljsjs.react-bootstrap] [zetawar.site :as site])])) #?(:clj (do (defn ga [tracking-id] [:script (str "(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){" "(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o)," "m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)" "})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');" "ga('create', '" tracking-id "', 'auto');" "ga('send', 'pageview');")]) (defn sentry [sentry-url environment] [[:script {:src "https://cdn.ravenjs.com/3.9.1/raven.min.js"}] [:script (str "Raven.config('" sentry-url "', {" "release: '" site/build "'," "environment: '" environment "'," "tags: {git_commit: '" site/build "'}" "}).install();")]]) (defn head [{global-meta :meta :as data} title] (into [:head [:meta {:charset "utf-8"}] [:meta {:http-equiv "X-UA-Compatible" :content "IE=edge"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1"}] [:title title] (include-css (site/prefix "/css/main.css")) (include-css (site/prefix "/css/highlight/default.css")) (include-js (site/prefix "/js/highlight.pack.js")) [:script "hljs.initHighlightingOnLoad();"] (some-> (:google-analytics-tracking-id global-meta) ga)] (some-> (:sentry-url global-meta) (sentry (:sentry-environment global-meta))))) )) (def nav-links [{:href (site/prefix "/") :title "Game"} {:href (site/prefix "/blog") :title "Blog"} {:href (site/prefix "/docs") :title "Documentation"} {:href "https://github.com/zetawar/zetawar/issues" :title "Roadmap"} {:href (site/prefix "/backers") :title "Backers"}]) (defn navbar ([] (navbar nil)) ([active-title] #?( :clj [:div#navbar-wrapper {:data-active-title active-title} [:nav.navbar.navbar-inverse.navbar-fixed-top [:div.container [:div.navbar-header [:a.navbar-brand {:href "/"} [:img {:src (site/prefix "/images/navbar-logo.svg")}] "Zetawar"]] [:div#navbar-collapse.collapse.navbar-collapse (into [:ul.nav.navbar-nav ] (for [{:keys [href title]} nav-links] (if (= title active-title) [:li {:class "active"} [:a {:href href} title]] [:li [:a {:href href} title]])))]]]] :cljs [:> js/ReactBootstrap.Navbar {:fixed-top true :inverse true} [:> js/ReactBootstrap.Navbar.Header [:> js/ReactBootstrap.Navbar.Brand [:a {:href "/"} [:img {:src (site/prefix "/images/navbar-logo.svg")}] "Zetawar"]] [:> js/ReactBootstrap.Navbar.Toggle]] [:> js/ReactBootstrap.Navbar.Collapse (into [:> js/ReactBootstrap.Nav] (map-indexed (fn [idx {:keys [href title]}] (let [active (= title active-title)] [:> js/ReactBootstrap.NavItem {:event-key idx :active active :href href} title])) nav-links))]] ) )) (defn footer [] [:div.container [:div#footer [:p "Build: " (if (not-empty site/build) [:a {:href (str "/builds/" site/build)} site/build] "DEV") (when (not-empty site/build-timestamp) (str " • " site/build-timestamp))] [:p "Follow " [:a {:href "https://twitter.com/ZetawarGame"} "@ZetawarGame"] " for updates. " "Questions or comments? Send us some " [:a {:href "http://goo.gl/forms/RgTpkCYDBk"} "feedback"] "."] [:p "Copyright 2016 Arugaba LLC under the " [:a {:href "https://github.com/Zetawar/zetawar/blob/master/LICENSE.txt"} "MIT license"]] [:p "Artwork from " [:a {:href "https://github.com/cvincent/elite-command"} "Elite Command"] " Copyright 2015 PI:NAME:<NAME>END_PI under " [:a {:href "http://creativecommons.org/licenses/by/4.0/"} "Creative Commons Attribution 4.0 International License"]]]])
[ { "context": " ((get roots' target))))\n (let [watch-key (gensym)\n state (if (satisfies? IAtom value)\n ", "end": 34917, "score": 0.9402400255203247, "start": 34911, "tag": "KEY", "value": "gensym" } ]
resources/public/js/compiled/out/om/core.cljs
imaximix/om-tutorials
1
(ns om.core (:require-macros om.core) (:require [cljsjs.react] [om.dom :as dom :include-macros true] [goog.object :as gobj] [goog.dom :as gdom] [goog.dom.dataset :as gdomdata]) (:import [goog.ui IdGenerator])) (def ^{:dynamic true :private true} *parent* nil) (def ^{:dynamic true :private true} *instrument* nil) (def ^{:dynamic true :private true} *descriptor* nil) (def ^{:dynamic true :private true} *state* nil) (def ^{:dynamic true :private true} *root-key* nil) ;; ============================================================================= ;; React Life Cycle Protocols ;; ;; http://facebook.github.io/react/docs/component-specs.html (defprotocol IDisplayName (display-name [this])) (defprotocol IInitState (init-state [this])) (defprotocol IShouldUpdate (should-update [this next-props next-state])) (defprotocol IWillMount (will-mount [this])) (defprotocol IDidMount (did-mount [this])) (defprotocol IWillUnmount (will-unmount [this])) (defprotocol IWillUpdate (will-update [this next-props next-state])) (defprotocol IDidUpdate (did-update [this prev-props prev-state])) (defprotocol IWillReceiveProps (will-receive-props [this next-props])) (defprotocol IRender (render [this])) (defprotocol IRenderProps (render-props [this props state])) (defprotocol IRenderState (render-state [this state])) ;; marker protocol, if set component will check equality of current ;; and render state (defprotocol ICheckState) ;; ============================================================================= ;; Om Protocols (defprotocol IOmSwap (-om-swap! [this cursor korks f tag])) (defprotocol IGetState (-get-state [this] [this ks])) (defprotocol IGetRenderState (-get-render-state [this] [this ks])) (defprotocol ISetState (-set-state! [this val render] [this ks val render])) ;; PRIVATE render queue, for components that use local state ;; and independently addressable components (defprotocol IRenderQueue (-get-queue [this]) (-queue-render! [this c]) (-empty-queue! [this])) (defprotocol IValue (-value [x])) (extend-type default IValue (-value [x] x)) (defprotocol ICursor (-path [cursor]) (-state [cursor])) (defprotocol IToCursor (-to-cursor [value state] [value state path])) (defprotocol ICursorDerive (-derive [cursor derived state path])) (declare to-cursor) (extend-type default ICursorDerive (-derive [this derived state path] (to-cursor derived state path))) (defn path [cursor] (-path cursor)) (defn value [cursor] (-value cursor)) (defn state [cursor] (-state cursor)) (defprotocol ITransact (-transact! [cursor korks f tag])) ;; PRIVATE (defprotocol INotify (-listen! [x key tx-listen]) (-unlisten! [x key]) (-notify! [x tx-data root-cursor])) ;; PRIVATE (defprotocol IRootProperties (-set-property! [this id p val]) (-remove-property! [this id p]) (-remove-properties! [this id]) (-get-property [this id p])) ;; PRIVATE (defprotocol IRootKey (-root-key [cursor])) (defprotocol IAdapt (-adapt [this other])) (extend-type default IAdapt (-adapt [_ other] other)) (defn adapt [x other] (-adapt x other)) (defprotocol IOmRef (-add-dep! [this c]) (-remove-dep! [this c]) (-refresh-deps! [this]) (-get-deps [this])) (declare notify*) (defn transact* ([state cursor korks f tag] (let [old-state @state path (into (om.core/path cursor) korks) ret (cond (satisfies? IOmSwap state) (-om-swap! state cursor korks f tag) (empty? path) (swap! state f) :else (swap! state update-in path f))] (when-not (= ret ::defer) (let [tx-data {:path path :old-value (get-in old-state path) :new-value (get-in @state path) :old-state old-state :new-state @state}] (if-not (nil? tag) (notify* cursor (assoc tx-data :tag tag)) (notify* cursor tx-data))))))) (defn cursor? [x] (satisfies? ICursor x)) (defn component? [x] (aget x "isOmComponent")) (defn ^:private children [node] (let [c (.. node -props -children)] (if (ifn? c) (set! (.. node -props -children) (c node)) c))) (defn get-props "Given an owning Pure node return the Om props. Analogous to React component props." ([x] {:pre [(component? x)]} (aget (.-props x) "__om_cursor")) ([x korks] {:pre [(component? x)]} (let [korks (if (sequential? korks) korks [korks])] (cond-> (aget (.-props x) "__om_cursor") (seq korks) (get-in korks))))) (defn get-state "Returns the component local state of an owning component. owner is the component. An optional key or sequence of keys may be given to extract a specific value. Always returns pending state." ([owner] {:pre [(component? owner)]} (-get-state owner)) ([owner korks] {:pre [(component? owner)]} (let [ks (if (sequential? korks) korks [korks])] (-get-state owner ks)))) (defn get-shared "Takes an owner and returns a map of global shared values for a render loop. An optional key or sequence of keys may be given to extract a specific value." ([owner] (when-not (nil? owner) (aget (.-props owner) "__om_shared"))) ([owner korks] (cond (not (sequential? korks)) (get (get-shared owner) korks) (empty? korks) (get-shared owner) :else (get-in (get-shared owner) korks)))) (defn ^:private merge-pending-state [owner] (let [state (.-state owner)] (when-let [pending-state (aget state "__om_pending_state")] (doto state (aset "__om_prev_state" (aget state "__om_state")) (aset "__om_state" pending-state) (aset "__om_pending_state" nil))))) (defn ^:private merge-props-state ([owner] (merge-props-state owner nil)) ([owner props] (let [props (or props (.-props owner))] (when-let [props-state (aget props "__om_state")] (let [state (.-state owner)] (aset state "__om_pending_state" (merge (or (aget state "__om_pending_state") (aget state "__om_state")) props-state)) (aset props "__om_state" nil)))))) (defn ref-changed? [ref] (let [val (value ref) val' (get-in @(state ref) (path ref) ::not-found)] (not= val val'))) (defn update-refs [c] (let [cstate (.-state c) refs (aget cstate "__om_refs")] (when-not (zero? (count refs)) (aset cstate "__om_refs" (into #{} (filter nil? (map (fn [ref] (let [ref-val (value ref) ref-state (state ref) ref-path (path ref) ref-val' (get-in @ref-state ref-path ::not-found)] (when (not= ref-val ::not-found) (if (not= ref-val ref-val') (adapt ref (to-cursor ref-val' ref-state ref-path)) ref)))) refs))))))) (declare unobserve) (def pure-methods {:isOmComponent true :getDisplayName (fn [] (this-as this (let [c (children this)] (when (satisfies? IDisplayName c) (display-name c))))) :getInitialState (fn [] (this-as this (let [c (children this) props (.-props this) istate (or (aget props "__om_init_state") {}) id (::id istate) ret #js {:__om_id (or id (.getNextUniqueId (.getInstance IdGenerator))) :__om_state (merge (when (satisfies? IInitState c) (init-state c)) (dissoc istate ::id))}] (aset props "__om_init_state" nil) ret))) :shouldComponentUpdate (fn [next-props next-state] (this-as this (let [props (.-props this) state (.-state this) c (children this)] ;; need to merge in props state first (merge-props-state this next-props) (if (satisfies? IShouldUpdate c) (should-update c (get-props #js {:props next-props :isOmComponent true}) (-get-state this)) (let [cursor (aget props "__om_cursor") next-cursor (aget next-props "__om_cursor")] (cond (not= (-value cursor) (-value next-cursor)) true (and (cursor? cursor) (cursor? next-cursor) (not= (-path cursor) (-path next-cursor ))) true (not= (-get-state this) (-get-render-state this)) true (and (not (zero? (count (aget state "__om_refs")))) (some #(ref-changed? %) (aget state "__om_refs"))) true (not (== (aget props "__om_index") (aget next-props "__om_index"))) true :else false)))))) :componentWillMount (fn [] (this-as this (merge-props-state this) (let [c (children this)] (when (satisfies? IWillMount c) (will-mount c))) (merge-pending-state this))) :componentDidMount (fn [] (this-as this (let [c (children this) cursor (aget (.-props this) "__om_cursor")] (when (satisfies? IDidMount c) (did-mount c))))) :componentWillUnmount (fn [] (this-as this (let [c (children this) cursor (aget (.-props this) "__om_cursor")] (when (satisfies? IWillUnmount c) (will-unmount c)) (when-let [refs (seq (aget (.-state this) "__om_refs"))] (doseq [ref refs] (unobserve this ref)))))) :componentWillUpdate (fn [next-props next-state] (this-as this (let [c (children this)] (when (satisfies? IWillUpdate c) (let [state (.-state this)] (will-update c (get-props #js {:props next-props :isOmComponent true}) (-get-state this))))) (merge-pending-state this) (update-refs this))) :componentDidUpdate (fn [prev-props prev-state] (this-as this (let [c (children this)] (when (satisfies? IDidUpdate c) (let [state (.-state this)] (did-update c (get-props #js {:props prev-props :isOmComponent true}) (or (aget state "__om_prev_state") (aget state "__om_state"))))) (aset (.-state this) "__om_prev_state" nil)))) :componentWillReceiveProps (fn [next-props] (this-as this (let [c (children this)] (when (satisfies? IWillReceiveProps c) (will-receive-props c (get-props #js {:props next-props :isOmComponent true})))))) :render (fn [] (this-as this (let [c (children this) props (.-props this)] (binding [*parent* this *state* (aget props "__om_app_state") *instrument* (aget props "__om_instrument") *descriptor* (aget props "__om_descriptor") *root-key* (aget props "__om_root_key")] (cond (satisfies? IRender c) (render c) (satisfies? IRenderProps c) (render-props c (aget props "__om_cursor") (get-state this)) (satisfies? IRenderState c) (render-state c (get-state this)) :else c)))))}) (defn specify-state-methods! [obj] (specify! obj ISetState (-set-state! ([this val render] (let [props (.-props this) app-state (aget props "__om_app_state")] (aset (.-state this) "__om_pending_state" val) (when (and (not (nil? app-state)) render) (-queue-render! app-state this)))) ([this ks val render] (let [props (.-props this) state (.-state this) pstate (-get-state this) app-state (aget props "__om_app_state")] (aset state "__om_pending_state" (assoc-in pstate ks val)) (when (and (not (nil? app-state)) render) (-queue-render! app-state this))))) IGetRenderState (-get-render-state ([this] (aget (.-state this) "__om_state")) ([this ks] (get-in (-get-render-state this) ks))) IGetState (-get-state ([this] (let [state (.-state this)] (or (aget state "__om_pending_state") (aget state "__om_state")))) ([this ks] (get-in (-get-state this) ks))))) (def pure-descriptor (specify-state-methods! (clj->js pure-methods))) ;; ============================================================================= ;; EXPERIMENTAL: No Local State (declare get-node) (defn react-id [x] (let [id (gdomdata/get (get-node x) "reactid")] (assert id) id)) (defn get-gstate [owner] (aget (.-props owner) "__om_app_state")) (defn no-local-merge-pending-state [owner] (let [gstate (get-gstate owner) spath [:state-map (react-id owner)] states (get-in @gstate spath)] (when (:pending-state states) (swap! gstate update-in spath (fn [states] (-> states (assoc :previous-state (:render-state states)) (assoc :render-state (merge (:render-state states) (:pending-state states))) (dissoc :pending-state))))))) (declare mounted?) (def no-local-state-methods (assoc pure-methods :getInitialState (fn [] (this-as this (let [c (children this) props (.-props this) istate (or (aget props "__om_init_state") {}) om-id (or (:om.core/id istate) (.getNextUniqueId (.getInstance IdGenerator))) state (merge (dissoc istate ::id) (when (satisfies? IInitState c) (init-state c)))] (aset props "__om_init_state" nil) #js {:__om_id om-id}))) :componentDidMount (fn [] (this-as this (let [c (children this) cursor (aget (.-props this) "__om_cursor") spath [:state-map (react-id this) :render-state]] (swap! (get-gstate this) assoc-in spath state) (when (satisfies? IDidMount c) (did-mount c))))) :componentWillMount (fn [] (this-as this (merge-props-state this) (let [c (children this)] (when (satisfies? IWillMount c) (will-mount c))) ;; TODO: cannot merge state until mounted? (when (mounted? this) (no-local-merge-pending-state this)))) :componentWillUnmount (fn [] (this-as this (let [c (children this)] (when (satisfies? IWillUnmount c) (will-unmount c)) (swap! (get-gstate this) update-in [:state-map] dissoc (react-id this)) (when-let [refs (seq (aget (.-state this) "__om_refs"))] (doseq [ref refs] (unobserve this ref)))))) :componentWillUpdate (fn [next-props next-state] (this-as this (let [props (.-props this) c (children this)] (when (satisfies? IWillUpdate c) (let [state (.-state this)] (will-update c (get-props #js {:props next-props :isOmComponent true}) (-get-state this))))) (no-local-merge-pending-state this) (update-refs this))) :componentDidUpdate (fn [prev-props prev-state] (this-as this (let [c (children this) gstate (get-gstate this) states (get-in @gstate [:state-map (react-id this)]) spath [:state-map (react-id this)]] (when (satisfies? IDidUpdate c) (let [state (.-state this)] (did-update c (get-props #js {:props prev-props :isOmComponent true}) (or (:previous-state states) (:render-state states))))) (when (:previous-state states) (swap! gstate update-in spath dissoc :previous-state))))))) (defn no-local-descriptor [methods] (specify! (clj->js methods) ISetState (-set-state! ([this val render] (let [gstate (get-gstate this) spath [:state-map (react-id this) :pending-state]] (swap! (get-gstate this) assoc-in spath val) (when (and (not (nil? gstate)) render) (-queue-render! gstate this)))) ([this ks val render] (-set-state! this (assoc-in (-get-state this) ks val) render))) IGetRenderState (-get-render-state ([this] (let [spath [:state-map (react-id this) :render-state]] (get-in @(get-gstate this) spath))) ([this ks] (get-in (-get-render-state this) ks))) IGetState (-get-state ([this] (if (mounted? this) (let [spath [:state-map (react-id this)] states (get-in @(get-gstate this) spath)] (or (:pending-state states) (:render-state states))) ;; TODO: means state cannot be written to until mounted - David (aget (.-props this) "__om_init_state"))) ([this ks] (get-in (-get-state this) ks))))) ;; ============================================================================= ;; Cursors (defn valid? [x] (if (satisfies? ICursor x) (not (keyword-identical? @x ::invalid)) true)) (deftype MapCursor [value state path] IWithMeta (-with-meta [_ new-meta] (MapCursor. (with-meta value new-meta) state path)) IMeta (-meta [_] (meta value)) IDeref (-deref [this] (get-in @state path ::invalid)) IValue (-value [_] value) ICursor (-path [_] path) (-state [_] state) ITransact (-transact! [this korks f tag] (transact* state this korks f tag)) ICloneable (-clone [_] (MapCursor. value state path)) ICounted (-count [_] (-count value)) ICollection (-conj [_ o] (MapCursor. (-conj value o) state path)) ;; EXPERIMENTAL IEmptyableCollection (-empty [_] (MapCursor. (empty value) state path)) ILookup (-lookup [this k] (-lookup this k nil)) (-lookup [this k not-found] (let [v (-lookup value k ::not-found)] (if-not (= v ::not-found) (-derive this v state (conj path k)) not-found))) IFn (-invoke [this k] (-lookup this k)) (-invoke [this k not-found] (-lookup this k not-found)) ISeqable (-seq [this] (when (pos? (count value)) (map (fn [[k v]] [k (-derive this v state (conj path k))]) value))) IAssociative (-contains-key? [_ k] (-contains-key? value k)) (-assoc [_ k v] (MapCursor. (-assoc value k v) state path)) IMap (-dissoc [_ k] (MapCursor. (-dissoc value k) state path)) IEquiv (-equiv [_ other] (if (cursor? other) (= value (-value other)) (= value other))) IHash (-hash [_] (hash value)) IKVReduce (-kv-reduce [_ f init] (-kv-reduce value f init)) IPrintWithWriter (-pr-writer [_ writer opts] (-pr-writer value writer opts))) (deftype IndexedCursor [value state path] ISequential IDeref (-deref [this] (get-in @state path ::invalid)) IWithMeta (-with-meta [_ new-meta] (IndexedCursor. (with-meta value new-meta) state path)) IMeta (-meta [_] (meta value)) IValue (-value [_] value) ICursor (-path [_] path) (-state [_] state) ITransact (-transact! [this korks f tag] (transact* state this korks f tag)) ICloneable (-clone [_] (IndexedCursor. value state path)) ICounted (-count [_] (-count value)) ICollection (-conj [_ o] (IndexedCursor. (-conj value o) state path)) ;; EXPERIMENTAL IEmptyableCollection (-empty [_] (IndexedCursor. (empty value) state path)) ILookup (-lookup [this n] (-nth this n nil)) (-lookup [this n not-found] (-nth this n not-found)) IFn (-invoke [this k] (-lookup this k)) (-invoke [this k not-found] (-lookup this k not-found)) IIndexed (-nth [this n] (-derive this (-nth value n) state (conj path n))) (-nth [this n not-found] (if (< n (-count value)) (-derive this (-nth value n not-found) state (conj path n)) not-found)) ISeqable (-seq [this] (when (pos? (count value)) (map (fn [v i] (-derive this v state (conj path i))) value (range)))) IAssociative (-contains-key? [_ k] (-contains-key? value k)) (-assoc [this n v] (-derive this (-assoc-n value n v) state path)) IStack (-peek [this] (-derive this (-peek value) state path)) (-pop [this] (-derive this (-pop value) state path)) IEquiv (-equiv [_ other] (if (cursor? other) (= value (-value other)) (= value other))) IHash (-hash [_] (hash value)) IKVReduce (-kv-reduce [_ f init] (-kv-reduce value f init)) IPrintWithWriter (-pr-writer [_ writer opts] (-pr-writer value writer opts))) (defn ^:private to-cursor* [val state path] (specify val IDeref (-deref [this] (get-in @state path ::invalid)) ICursor (-path [_] path) (-state [_] state) ITransact (-transact! [this korks f tag] (transact* state this korks f tag)) IEquiv (-equiv [_ other] (if (cursor? other) (= val (-value other)) (= val other))))) (defn ^:private to-cursor ([val] (to-cursor val nil [])) ([val state] (to-cursor val state [])) ([val state path] (cond (cursor? val) val (satisfies? IToCursor val) (-to-cursor val state path) (indexed? val) (IndexedCursor. val state path) (map? val) (MapCursor. val state path) (satisfies? ICloneable val) (to-cursor* val state path) :else val))) (defn notify* [cursor tx-data] (let [state (-state cursor)] (-notify! state tx-data (to-cursor @state state)))) ;; ============================================================================= ;; Ref Cursors (declare commit! id refresh-props!) (defn root-cursor "Given an application state atom return a root cursor for it." [atom] {:pre [(satisfies? IDeref atom)]} (to-cursor @atom atom [])) (def _refs (atom {})) (defn ref-sub-cursor [x parent] (specify x ICloneable (-clone [this] (ref-sub-cursor (clone x) parent)) IAdapt (-adapt [this other] (ref-sub-cursor (adapt x other) parent)) ICursorDerive (-derive [this derived state path] (let [cursor' (to-cursor derived state path)] (if (cursor? cursor') (adapt this cursor') cursor'))) ITransact (-transact! [cursor korks f tag] (commit! cursor korks f) (-refresh-deps! parent)))) (defn ref-cursor? [x] (satisfies? IOmRef x)) (defn ref-cursor "Given a cursor return a reference cursor that inherits all of the properties and methods of the cursor. Reference cursors may be observed via om.core/observe." [cursor] {:pre [(cursor? cursor)]} (if (ref-cursor? cursor) cursor (let [path (path cursor) storage (get (swap! _refs update-in [path] (fnil identity (atom {}))) path)] (specify cursor ICursorDerive (-derive [this derived state path] (let [cursor' (to-cursor derived state path)] (if (cursor? cursor') (ref-sub-cursor cursor' this) cursor'))) IOmRef (-add-dep! [_ c] (swap! storage assoc (id c) c)) (-remove-dep! [_ c] (let [m (swap! storage dissoc (id c))] (when (zero? (count m)) (swap! _refs dissoc path)))) (-refresh-deps! [_] (doseq [c (vals @storage)] (-queue-render! (state cursor) c))) (-get-deps [_] @storage) ITransact (-transact! [cursor korks f tag] (commit! cursor korks f) (-refresh-deps! cursor)))))) (defn add-ref-to-component! [c ref] (let [state (.-state c) refs (or (aget state "__om_refs") #{})] (when-not (contains? refs ref) (aset state "__om_refs" (conj refs ref))))) (defn remove-ref-from-component! [c ref] (let [state (.-state c) refs (aget state "__om_refs")] (when (contains? refs ref) (aset state "__om_refs" (disj refs ref))))) (defn observe "Given a component and a reference cursor have the component observe the reference cursor for any data changes." [c ref] {:pre [(component? c) (cursor? ref) (ref-cursor? ref)]} (add-ref-to-component! c ref) (-add-dep! ref c) ref) (defn unobserve [c ref] (remove-ref-from-component! c ref) (-remove-dep! ref c) ref) ;; ============================================================================= ;; API (def ^:private refresh-queued false) (def ^:private refresh-set (atom #{})) (defn ^:private get-renderT [state] (or (.-om$render$T state) 0)) (defn render-all "Force a render of *all* roots. Usage of this function is almost never recommended." ([] (render-all nil)) ([state] (set! refresh-queued false) (doseq [f @refresh-set] (f)) (when-not (nil? state) (set! (.-om$render$T state) (inc (get-renderT state)))))) (def ^:private roots (atom {})) (defn ^:private valid-component? [x f] (assert (or (satisfies? IRender x) (satisfies? IRenderProps x) (satisfies? IRenderState x)) (str "Invalid Om component fn, " (.-name f) " does not return valid instance"))) (defn ^:private valid-opts? [m] (every? #{:key :react-key :key-fn :fn :init-state :state :opts :shared ::index :instrument :descriptor} (keys m))) (defn id [owner] (aget (.-state owner) "__om_id")) (defn get-descriptor ([f] (get-descriptor f nil)) ([f descriptor] (let [rdesc (or descriptor *descriptor* pure-descriptor)] (when (or (nil? (gobj/get f "om$descriptor")) (not (identical? rdesc (gobj/get f "om$tag")))) (let [factory (js/React.createFactory (js/React.createClass rdesc))] (gobj/set f "om$descriptor" factory) (gobj/set f "om$tag" rdesc)))) (gobj/get f "om$descriptor"))) (defn getf ([f cursor] (if (instance? MultiFn f) (let [dv ((.-dispatch-fn f) cursor nil)] (get-method f dv)) f)) ([f cursor opts] (if (instance? MultiFn f) (let [dv ((.-dispatch-fn f) cursor nil opts)] (get-method f dv)) f))) (defn build* ([f cursor] (build* f cursor nil)) ([f cursor m] {:pre [(ifn? f) (or (nil? m) (map? m))]} (assert (valid-opts? m) (apply str "build options contains invalid keys, only :key, :key-fn :react-key, " ":fn, :init-state, :state, and :opts allowed, given " (interpose ", " (keys m)))) (cond (nil? m) (let [shared (get-shared *parent*) ctor (get-descriptor (getf f cursor))] (ctor #js {:__om_cursor cursor :__om_shared shared :__om_root_key *root-key* :__om_app_state *state* :__om_descriptor *descriptor* :__om_instrument *instrument* :children (fn [this] (let [ret (f cursor this)] (valid-component? ret f) ret))})) :else (let [{:keys [key key-fn state init-state opts]} m dataf (get m :fn) cursor' (if-not (nil? dataf) (if-let [i (::index m)] (dataf cursor i) (dataf cursor)) cursor) rkey (cond (not (nil? key)) (get cursor' key) (not (nil? key-fn)) (key-fn cursor') :else (get m :react-key)) shared (or (:shared m) (get-shared *parent*)) ctor (get-descriptor (getf f cursor' opts) (:descriptor m))] (ctor #js {:__om_cursor cursor' :__om_index (::index m) :__om_init_state init-state :__om_state state :__om_shared shared :__om_root_key *root-key* :__om_app_state *state* :__om_descriptor *descriptor* :__om_instrument *instrument* :key (or rkey js/undefined) ;; annoying :children (if (nil? opts) (fn [this] (let [ret (f cursor' this)] (valid-component? ret f) ret)) (fn [this] (let [ret (f cursor' this opts)] (valid-component? ret f) ret)))}))))) (defn build "Builds an Om component. Takes an IRender/IRenderState instance returning function f, a value, and an optional third argument which may be a map of build specifications. f - is a function of 2 or 3 arguments. The first argument can be any value and the second argument will be the owning pure node. If a map of options m is passed in this will be the third argument. f must return at a minimum an IRender or IRenderState instance, this instance may implement other React life cycle protocols. x - any value m - a map the following keys are allowed: :key - a keyword that should be used to look up the key used by React itself when rendering sequential things. :react-key - an explicit react key :fn - a function to apply to the data before invoking f. :init-state - a map of initial state to pass to the component. :state - a map of state to pass to the component, will be merged in. :opts - a map of values. Can be used to pass side information down the render tree. :descriptor - a JS object of React methods, will be used to construct a React class per Om component function encountered. defaults to pure-descriptor. Example: (build list-of-gadgets x {:init-state {:event-chan ... :narble ...}}) " ([f x] (build f x nil)) ([f x m] {:pre [(ifn? f) (or (nil? m) (map? m))]} (if-not (nil? *instrument*) (let [ret (*instrument* f x m)] (if (= ret ::pass) (build* f x m) ret)) (build* f x m)))) (defn build-all "Build a sequence of components. f is the component constructor function, xs a sequence of values, and m a map of options the same as provided to om.core/build." ([f xs] (build-all f xs nil)) ([f xs m] {:pre [(ifn? f) (or (nil? m) (map? m))]} (map (fn [x i] (build f x (assoc m ::index i))) xs (range)))) (defn ^:private setup [state key tx-listen] (when-not (satisfies? INotify state) (let [properties (atom {}) listeners (atom {}) render-queue (atom #{})] (specify! state IRootProperties (-set-property! [_ id k v] (swap! properties assoc-in [id k] v)) (-remove-property! [_ id k] (swap! properties dissoc id k)) (-remove-properties! [_ id] (swap! properties dissoc id)) (-get-property [_ id k] (get-in @properties [id k])) INotify (-listen! [this key tx-listen] (when-not (nil? tx-listen) (swap! listeners assoc key tx-listen)) this) (-unlisten! [this key] (swap! listeners dissoc key) this) (-notify! [this tx-data root-cursor] (doseq [[_ f] @listeners] (f tx-data root-cursor)) this) IRenderQueue (-get-queue [this] @render-queue) (-queue-render! [this c] (when-not (contains? @render-queue c) (swap! render-queue conj c) (swap! this identity))) (-empty-queue! [this] (swap! render-queue empty))))) (-listen! state key tx-listen)) (defn ^:private tear-down [state key] (-unlisten! state key)) (defn tag-root-key [cursor root-key] (if (cursor? cursor) (specify cursor ICloneable (-clone [this] (tag-root-key (clone cursor) root-key)) IAdapt (-adapt [this other] (tag-root-key (adapt cursor other) root-key)) IRootKey (-root-key [this] root-key)) cursor)) (defn root "Take a component constructor function f, value an immutable tree of associative data structures optionally an wrapped in an IAtom instance, and a map of options and installs an Om/React render loop. f must return an instance that at a minimum implements IRender or IRenderState (it may implement other React life cycle protocols). f must take at least two arguments, the root cursor and the owning pure node. A cursor is just the original data wrapped in an ICursor instance which maintains path information. Only one root render loop allowed per target element. om.core/root is idempotent, if called again on the same target element the previous render loop will be replaced. Options may also include any key allowed by om.core/build to customize f. In addition om.core/root supports the following special options: :target - (required) a DOM element. :shared - data to be shared by all components, see om.core/get-shared :tx-listen - a function that will listen in in transactions, should take 2 arguments - the first a map containing the path, old and new state at path, old and new global state, and transaction tag if provided. :instrument - a function of three arguments that if provided will intercept all calls to om.core/build. This function should correspond to the three arity version of om.core/build. :adapt - a function to adapt the root cursor :raf - override requestAnimationFrame based rendering. If false setTimeout will be use. If given a function will be invoked instead. Example: (root (fn [data owner] ...) {:message :hello} {:target js/document.body})" ([f value {:keys [target tx-listen path instrument descriptor adapt raf] :as options}] (assert (ifn? f) "First argument must be a function") (assert (not (nil? target)) "No target specified to om.core/root") ;; only one root render loop per target (let [roots' @roots] (when (contains? roots' target) ((get roots' target)))) (let [watch-key (gensym) state (if (satisfies? IAtom value) value (atom value)) state (setup state watch-key tx-listen) adapt (or adapt identity) m (dissoc options :target :tx-listen :path :adapt :raf) ret (atom nil) rootf (fn rootf [] (swap! refresh-set disj rootf) (let [value @state cursor (adapt (tag-root-key (if (nil? path) (to-cursor value state []) (to-cursor (get-in value path) state path)) watch-key))] (when-not (-get-property state watch-key :skip-render-root) (-set-property! state watch-key :skip-render-root true) (let [c (dom/render (binding [*descriptor* descriptor *instrument* instrument *state* state *root-key* watch-key] (build f cursor m)) target)] (when (nil? @ret) (reset! ret c)))) ;; update state pass (let [queue (-get-queue state)] (-empty-queue! state) (when-not (empty? queue) (doseq [c queue] (when (.isMounted c) (when-let [next-props (aget (.-state c) "__om_next_cursor")] (aset (.-props c) "__om_cursor" next-props) (aset (.-state c) "__om_next_cursor" nil)) (when (or (not (satisfies? ICheckState (children c))) (.shouldComponentUpdate c (.-props c) (.-state c))) (.forceUpdate c)))))) ;; ref cursor pass (let [_refs @_refs] (when-not (empty? _refs) (doseq [[path cs] _refs] (let [cs @cs] (doseq [[id c] cs] (when (.shouldComponentUpdate c (.-props c) (.-state c)) (.forceUpdate c))))))) @ret))] (add-watch state watch-key (fn [_ _ o n] (when (and (not (-get-property state watch-key :ignore)) (not (identical? o n))) (-set-property! state watch-key :skip-render-root false)) (-set-property! state watch-key :ignore false) (when-not (contains? @refresh-set rootf) (swap! refresh-set conj rootf)) (when-not refresh-queued (set! refresh-queued true) (cond (fn? raf) (raf) (or (false? raf) (not (exists? js/requestAnimationFrame))) (js/setTimeout #(render-all state) 16) :else (js/requestAnimationFrame #(render-all state)))))) ;; store fn to remove previous root render loop (swap! roots assoc target (fn [] (-remove-properties! state watch-key) (remove-watch state watch-key) (tear-down state watch-key) (swap! refresh-set disj rootf) (swap! roots dissoc target) (js/React.unmountComponentAtNode target))) (rootf)))) (defn detach-root "Given a DOM target remove its render loop if one exists." [target] {:pre [(gdom/isElement target)]} (when-let [f (get @roots target)] (f))) (defn transactable? [x] (satisfies? ITransact x)) (defn transact! "Given a tag, a cursor, an optional list of keys ks, mutate the tree at the path specified by the cursor + the optional keys by applying f to the specified value in the tree. An Om re-render will be triggered." ([cursor f] (transact! cursor [] f nil)) ([cursor korks f] (transact! cursor korks f nil)) ([cursor korks f tag] {:pre [(transactable? cursor) (ifn? f)]} (let [korks (cond (nil? korks) [] (sequential? korks) korks :else [korks])] (-transact! cursor korks f tag)))) (defn update! "Like transact! but no function provided, instead a replacement value is given." ([cursor v] {:pre [(cursor? cursor)]} (transact! cursor [] (fn [_] v) nil)) ([cursor korks v] {:pre [(cursor? cursor)]} (transact! cursor korks (fn [_] v) nil)) ([cursor korks v tag] {:pre [(cursor? cursor)]} (transact! cursor korks (fn [_] v) tag))) (defn commit! "EXPERIMENTAL: Like transact! but does not schedule a re-render or create a transact event." [cursor korks f] {:pre [(cursor? cursor) (ifn? f)]} (let [key (when (satisfies? IRootKey cursor) (-root-key cursor)) app-state (state cursor) korks (cond (nil? korks) [] (sequential? korks) korks :else [korks]) cpath (path cursor) rpath (into cpath korks)] (when key (-set-property! app-state key :ignore true)) (if (empty? rpath) (swap! app-state f) (swap! app-state update-in rpath f)))) (defn get-node "A helper function to get at React DOM refs. Given a owning pure node extract the DOM ref specified by name." ([owner] (.getDOMNode owner)) ([owner name] {:pre [(string? name)]} (some-> (.-refs owner) (aget name) (.getDOMNode)))) (defn get-ref "A helper function to get at React refs. Given an owning pure node extract the ref specified by name." [owner name] {:pre [(component? owner) (string? name)]} (some-> (.-refs owner) (gobj/get name))) (defn mounted? "Return true if the backing React component is mounted into the DOM." [owner] (.isMounted owner)) (defn set-state! "Takes a pure owning component, a sequential list of keys and value and sets the state of the component. Conceptually analagous to React setState. Will schedule an Om re-render." ([owner v] {:pre [(component? owner)]} (-set-state! owner v true)) ([owner korks v] {:pre [(component? owner)]} (let [ks (if (sequential? korks) korks [korks])] (-set-state! owner ks v true)))) (defn set-state-nr! "EXPERIMENTAL: Same as set-state! but does not trigger re-render." ([owner v] {:pre [(component? owner)]} (-set-state! owner v false)) ([owner korks v] {:pre [(component? owner)]} (let [ks (if (sequential? korks) korks [korks])] (-set-state! owner ks v false)))) (defn update-state! "Takes a pure owning component, a sequential list of keys and a function to transition the state of the component. Conceptually analagous to React setState. Will schedule an Om re-render." ([owner f] {:pre [(component? owner) (ifn? f)]} (set-state! owner (f (get-state owner)))) ([owner korks f] {:pre [(component? owner) (ifn? f)]} (set-state! owner korks (f (get-state owner korks))))) (defn update-state-nr! "EXPERIMENTAL: Same as update-state! but does not trigger re-render." ([owner f] {:pre [(component? owner) (ifn? f)]} (set-state-nr! owner (f (get-state owner)))) ([owner korks f] {:pre [(component? owner) (ifn? f)]} (set-state-nr! owner korks (f (get-state owner korks))))) (defn refresh! "Utility to re-render an owner." [owner] {:pre [(component? owner)]} (update-state! owner identity)) (defn get-render-state "Takes a pure owning component and an optional key or sequential list of keys and returns a property in the component local state if it exists. Always returns the rendered state, not the pending state." ([owner] {:pre [(component? owner)]} (-get-render-state owner)) ([owner korks] {:pre [(component? owner)]} (let [ks (if (sequential? korks) korks [korks])] (-get-render-state owner ks))))
108217
(ns om.core (:require-macros om.core) (:require [cljsjs.react] [om.dom :as dom :include-macros true] [goog.object :as gobj] [goog.dom :as gdom] [goog.dom.dataset :as gdomdata]) (:import [goog.ui IdGenerator])) (def ^{:dynamic true :private true} *parent* nil) (def ^{:dynamic true :private true} *instrument* nil) (def ^{:dynamic true :private true} *descriptor* nil) (def ^{:dynamic true :private true} *state* nil) (def ^{:dynamic true :private true} *root-key* nil) ;; ============================================================================= ;; React Life Cycle Protocols ;; ;; http://facebook.github.io/react/docs/component-specs.html (defprotocol IDisplayName (display-name [this])) (defprotocol IInitState (init-state [this])) (defprotocol IShouldUpdate (should-update [this next-props next-state])) (defprotocol IWillMount (will-mount [this])) (defprotocol IDidMount (did-mount [this])) (defprotocol IWillUnmount (will-unmount [this])) (defprotocol IWillUpdate (will-update [this next-props next-state])) (defprotocol IDidUpdate (did-update [this prev-props prev-state])) (defprotocol IWillReceiveProps (will-receive-props [this next-props])) (defprotocol IRender (render [this])) (defprotocol IRenderProps (render-props [this props state])) (defprotocol IRenderState (render-state [this state])) ;; marker protocol, if set component will check equality of current ;; and render state (defprotocol ICheckState) ;; ============================================================================= ;; Om Protocols (defprotocol IOmSwap (-om-swap! [this cursor korks f tag])) (defprotocol IGetState (-get-state [this] [this ks])) (defprotocol IGetRenderState (-get-render-state [this] [this ks])) (defprotocol ISetState (-set-state! [this val render] [this ks val render])) ;; PRIVATE render queue, for components that use local state ;; and independently addressable components (defprotocol IRenderQueue (-get-queue [this]) (-queue-render! [this c]) (-empty-queue! [this])) (defprotocol IValue (-value [x])) (extend-type default IValue (-value [x] x)) (defprotocol ICursor (-path [cursor]) (-state [cursor])) (defprotocol IToCursor (-to-cursor [value state] [value state path])) (defprotocol ICursorDerive (-derive [cursor derived state path])) (declare to-cursor) (extend-type default ICursorDerive (-derive [this derived state path] (to-cursor derived state path))) (defn path [cursor] (-path cursor)) (defn value [cursor] (-value cursor)) (defn state [cursor] (-state cursor)) (defprotocol ITransact (-transact! [cursor korks f tag])) ;; PRIVATE (defprotocol INotify (-listen! [x key tx-listen]) (-unlisten! [x key]) (-notify! [x tx-data root-cursor])) ;; PRIVATE (defprotocol IRootProperties (-set-property! [this id p val]) (-remove-property! [this id p]) (-remove-properties! [this id]) (-get-property [this id p])) ;; PRIVATE (defprotocol IRootKey (-root-key [cursor])) (defprotocol IAdapt (-adapt [this other])) (extend-type default IAdapt (-adapt [_ other] other)) (defn adapt [x other] (-adapt x other)) (defprotocol IOmRef (-add-dep! [this c]) (-remove-dep! [this c]) (-refresh-deps! [this]) (-get-deps [this])) (declare notify*) (defn transact* ([state cursor korks f tag] (let [old-state @state path (into (om.core/path cursor) korks) ret (cond (satisfies? IOmSwap state) (-om-swap! state cursor korks f tag) (empty? path) (swap! state f) :else (swap! state update-in path f))] (when-not (= ret ::defer) (let [tx-data {:path path :old-value (get-in old-state path) :new-value (get-in @state path) :old-state old-state :new-state @state}] (if-not (nil? tag) (notify* cursor (assoc tx-data :tag tag)) (notify* cursor tx-data))))))) (defn cursor? [x] (satisfies? ICursor x)) (defn component? [x] (aget x "isOmComponent")) (defn ^:private children [node] (let [c (.. node -props -children)] (if (ifn? c) (set! (.. node -props -children) (c node)) c))) (defn get-props "Given an owning Pure node return the Om props. Analogous to React component props." ([x] {:pre [(component? x)]} (aget (.-props x) "__om_cursor")) ([x korks] {:pre [(component? x)]} (let [korks (if (sequential? korks) korks [korks])] (cond-> (aget (.-props x) "__om_cursor") (seq korks) (get-in korks))))) (defn get-state "Returns the component local state of an owning component. owner is the component. An optional key or sequence of keys may be given to extract a specific value. Always returns pending state." ([owner] {:pre [(component? owner)]} (-get-state owner)) ([owner korks] {:pre [(component? owner)]} (let [ks (if (sequential? korks) korks [korks])] (-get-state owner ks)))) (defn get-shared "Takes an owner and returns a map of global shared values for a render loop. An optional key or sequence of keys may be given to extract a specific value." ([owner] (when-not (nil? owner) (aget (.-props owner) "__om_shared"))) ([owner korks] (cond (not (sequential? korks)) (get (get-shared owner) korks) (empty? korks) (get-shared owner) :else (get-in (get-shared owner) korks)))) (defn ^:private merge-pending-state [owner] (let [state (.-state owner)] (when-let [pending-state (aget state "__om_pending_state")] (doto state (aset "__om_prev_state" (aget state "__om_state")) (aset "__om_state" pending-state) (aset "__om_pending_state" nil))))) (defn ^:private merge-props-state ([owner] (merge-props-state owner nil)) ([owner props] (let [props (or props (.-props owner))] (when-let [props-state (aget props "__om_state")] (let [state (.-state owner)] (aset state "__om_pending_state" (merge (or (aget state "__om_pending_state") (aget state "__om_state")) props-state)) (aset props "__om_state" nil)))))) (defn ref-changed? [ref] (let [val (value ref) val' (get-in @(state ref) (path ref) ::not-found)] (not= val val'))) (defn update-refs [c] (let [cstate (.-state c) refs (aget cstate "__om_refs")] (when-not (zero? (count refs)) (aset cstate "__om_refs" (into #{} (filter nil? (map (fn [ref] (let [ref-val (value ref) ref-state (state ref) ref-path (path ref) ref-val' (get-in @ref-state ref-path ::not-found)] (when (not= ref-val ::not-found) (if (not= ref-val ref-val') (adapt ref (to-cursor ref-val' ref-state ref-path)) ref)))) refs))))))) (declare unobserve) (def pure-methods {:isOmComponent true :getDisplayName (fn [] (this-as this (let [c (children this)] (when (satisfies? IDisplayName c) (display-name c))))) :getInitialState (fn [] (this-as this (let [c (children this) props (.-props this) istate (or (aget props "__om_init_state") {}) id (::id istate) ret #js {:__om_id (or id (.getNextUniqueId (.getInstance IdGenerator))) :__om_state (merge (when (satisfies? IInitState c) (init-state c)) (dissoc istate ::id))}] (aset props "__om_init_state" nil) ret))) :shouldComponentUpdate (fn [next-props next-state] (this-as this (let [props (.-props this) state (.-state this) c (children this)] ;; need to merge in props state first (merge-props-state this next-props) (if (satisfies? IShouldUpdate c) (should-update c (get-props #js {:props next-props :isOmComponent true}) (-get-state this)) (let [cursor (aget props "__om_cursor") next-cursor (aget next-props "__om_cursor")] (cond (not= (-value cursor) (-value next-cursor)) true (and (cursor? cursor) (cursor? next-cursor) (not= (-path cursor) (-path next-cursor ))) true (not= (-get-state this) (-get-render-state this)) true (and (not (zero? (count (aget state "__om_refs")))) (some #(ref-changed? %) (aget state "__om_refs"))) true (not (== (aget props "__om_index") (aget next-props "__om_index"))) true :else false)))))) :componentWillMount (fn [] (this-as this (merge-props-state this) (let [c (children this)] (when (satisfies? IWillMount c) (will-mount c))) (merge-pending-state this))) :componentDidMount (fn [] (this-as this (let [c (children this) cursor (aget (.-props this) "__om_cursor")] (when (satisfies? IDidMount c) (did-mount c))))) :componentWillUnmount (fn [] (this-as this (let [c (children this) cursor (aget (.-props this) "__om_cursor")] (when (satisfies? IWillUnmount c) (will-unmount c)) (when-let [refs (seq (aget (.-state this) "__om_refs"))] (doseq [ref refs] (unobserve this ref)))))) :componentWillUpdate (fn [next-props next-state] (this-as this (let [c (children this)] (when (satisfies? IWillUpdate c) (let [state (.-state this)] (will-update c (get-props #js {:props next-props :isOmComponent true}) (-get-state this))))) (merge-pending-state this) (update-refs this))) :componentDidUpdate (fn [prev-props prev-state] (this-as this (let [c (children this)] (when (satisfies? IDidUpdate c) (let [state (.-state this)] (did-update c (get-props #js {:props prev-props :isOmComponent true}) (or (aget state "__om_prev_state") (aget state "__om_state"))))) (aset (.-state this) "__om_prev_state" nil)))) :componentWillReceiveProps (fn [next-props] (this-as this (let [c (children this)] (when (satisfies? IWillReceiveProps c) (will-receive-props c (get-props #js {:props next-props :isOmComponent true})))))) :render (fn [] (this-as this (let [c (children this) props (.-props this)] (binding [*parent* this *state* (aget props "__om_app_state") *instrument* (aget props "__om_instrument") *descriptor* (aget props "__om_descriptor") *root-key* (aget props "__om_root_key")] (cond (satisfies? IRender c) (render c) (satisfies? IRenderProps c) (render-props c (aget props "__om_cursor") (get-state this)) (satisfies? IRenderState c) (render-state c (get-state this)) :else c)))))}) (defn specify-state-methods! [obj] (specify! obj ISetState (-set-state! ([this val render] (let [props (.-props this) app-state (aget props "__om_app_state")] (aset (.-state this) "__om_pending_state" val) (when (and (not (nil? app-state)) render) (-queue-render! app-state this)))) ([this ks val render] (let [props (.-props this) state (.-state this) pstate (-get-state this) app-state (aget props "__om_app_state")] (aset state "__om_pending_state" (assoc-in pstate ks val)) (when (and (not (nil? app-state)) render) (-queue-render! app-state this))))) IGetRenderState (-get-render-state ([this] (aget (.-state this) "__om_state")) ([this ks] (get-in (-get-render-state this) ks))) IGetState (-get-state ([this] (let [state (.-state this)] (or (aget state "__om_pending_state") (aget state "__om_state")))) ([this ks] (get-in (-get-state this) ks))))) (def pure-descriptor (specify-state-methods! (clj->js pure-methods))) ;; ============================================================================= ;; EXPERIMENTAL: No Local State (declare get-node) (defn react-id [x] (let [id (gdomdata/get (get-node x) "reactid")] (assert id) id)) (defn get-gstate [owner] (aget (.-props owner) "__om_app_state")) (defn no-local-merge-pending-state [owner] (let [gstate (get-gstate owner) spath [:state-map (react-id owner)] states (get-in @gstate spath)] (when (:pending-state states) (swap! gstate update-in spath (fn [states] (-> states (assoc :previous-state (:render-state states)) (assoc :render-state (merge (:render-state states) (:pending-state states))) (dissoc :pending-state))))))) (declare mounted?) (def no-local-state-methods (assoc pure-methods :getInitialState (fn [] (this-as this (let [c (children this) props (.-props this) istate (or (aget props "__om_init_state") {}) om-id (or (:om.core/id istate) (.getNextUniqueId (.getInstance IdGenerator))) state (merge (dissoc istate ::id) (when (satisfies? IInitState c) (init-state c)))] (aset props "__om_init_state" nil) #js {:__om_id om-id}))) :componentDidMount (fn [] (this-as this (let [c (children this) cursor (aget (.-props this) "__om_cursor") spath [:state-map (react-id this) :render-state]] (swap! (get-gstate this) assoc-in spath state) (when (satisfies? IDidMount c) (did-mount c))))) :componentWillMount (fn [] (this-as this (merge-props-state this) (let [c (children this)] (when (satisfies? IWillMount c) (will-mount c))) ;; TODO: cannot merge state until mounted? (when (mounted? this) (no-local-merge-pending-state this)))) :componentWillUnmount (fn [] (this-as this (let [c (children this)] (when (satisfies? IWillUnmount c) (will-unmount c)) (swap! (get-gstate this) update-in [:state-map] dissoc (react-id this)) (when-let [refs (seq (aget (.-state this) "__om_refs"))] (doseq [ref refs] (unobserve this ref)))))) :componentWillUpdate (fn [next-props next-state] (this-as this (let [props (.-props this) c (children this)] (when (satisfies? IWillUpdate c) (let [state (.-state this)] (will-update c (get-props #js {:props next-props :isOmComponent true}) (-get-state this))))) (no-local-merge-pending-state this) (update-refs this))) :componentDidUpdate (fn [prev-props prev-state] (this-as this (let [c (children this) gstate (get-gstate this) states (get-in @gstate [:state-map (react-id this)]) spath [:state-map (react-id this)]] (when (satisfies? IDidUpdate c) (let [state (.-state this)] (did-update c (get-props #js {:props prev-props :isOmComponent true}) (or (:previous-state states) (:render-state states))))) (when (:previous-state states) (swap! gstate update-in spath dissoc :previous-state))))))) (defn no-local-descriptor [methods] (specify! (clj->js methods) ISetState (-set-state! ([this val render] (let [gstate (get-gstate this) spath [:state-map (react-id this) :pending-state]] (swap! (get-gstate this) assoc-in spath val) (when (and (not (nil? gstate)) render) (-queue-render! gstate this)))) ([this ks val render] (-set-state! this (assoc-in (-get-state this) ks val) render))) IGetRenderState (-get-render-state ([this] (let [spath [:state-map (react-id this) :render-state]] (get-in @(get-gstate this) spath))) ([this ks] (get-in (-get-render-state this) ks))) IGetState (-get-state ([this] (if (mounted? this) (let [spath [:state-map (react-id this)] states (get-in @(get-gstate this) spath)] (or (:pending-state states) (:render-state states))) ;; TODO: means state cannot be written to until mounted - David (aget (.-props this) "__om_init_state"))) ([this ks] (get-in (-get-state this) ks))))) ;; ============================================================================= ;; Cursors (defn valid? [x] (if (satisfies? ICursor x) (not (keyword-identical? @x ::invalid)) true)) (deftype MapCursor [value state path] IWithMeta (-with-meta [_ new-meta] (MapCursor. (with-meta value new-meta) state path)) IMeta (-meta [_] (meta value)) IDeref (-deref [this] (get-in @state path ::invalid)) IValue (-value [_] value) ICursor (-path [_] path) (-state [_] state) ITransact (-transact! [this korks f tag] (transact* state this korks f tag)) ICloneable (-clone [_] (MapCursor. value state path)) ICounted (-count [_] (-count value)) ICollection (-conj [_ o] (MapCursor. (-conj value o) state path)) ;; EXPERIMENTAL IEmptyableCollection (-empty [_] (MapCursor. (empty value) state path)) ILookup (-lookup [this k] (-lookup this k nil)) (-lookup [this k not-found] (let [v (-lookup value k ::not-found)] (if-not (= v ::not-found) (-derive this v state (conj path k)) not-found))) IFn (-invoke [this k] (-lookup this k)) (-invoke [this k not-found] (-lookup this k not-found)) ISeqable (-seq [this] (when (pos? (count value)) (map (fn [[k v]] [k (-derive this v state (conj path k))]) value))) IAssociative (-contains-key? [_ k] (-contains-key? value k)) (-assoc [_ k v] (MapCursor. (-assoc value k v) state path)) IMap (-dissoc [_ k] (MapCursor. (-dissoc value k) state path)) IEquiv (-equiv [_ other] (if (cursor? other) (= value (-value other)) (= value other))) IHash (-hash [_] (hash value)) IKVReduce (-kv-reduce [_ f init] (-kv-reduce value f init)) IPrintWithWriter (-pr-writer [_ writer opts] (-pr-writer value writer opts))) (deftype IndexedCursor [value state path] ISequential IDeref (-deref [this] (get-in @state path ::invalid)) IWithMeta (-with-meta [_ new-meta] (IndexedCursor. (with-meta value new-meta) state path)) IMeta (-meta [_] (meta value)) IValue (-value [_] value) ICursor (-path [_] path) (-state [_] state) ITransact (-transact! [this korks f tag] (transact* state this korks f tag)) ICloneable (-clone [_] (IndexedCursor. value state path)) ICounted (-count [_] (-count value)) ICollection (-conj [_ o] (IndexedCursor. (-conj value o) state path)) ;; EXPERIMENTAL IEmptyableCollection (-empty [_] (IndexedCursor. (empty value) state path)) ILookup (-lookup [this n] (-nth this n nil)) (-lookup [this n not-found] (-nth this n not-found)) IFn (-invoke [this k] (-lookup this k)) (-invoke [this k not-found] (-lookup this k not-found)) IIndexed (-nth [this n] (-derive this (-nth value n) state (conj path n))) (-nth [this n not-found] (if (< n (-count value)) (-derive this (-nth value n not-found) state (conj path n)) not-found)) ISeqable (-seq [this] (when (pos? (count value)) (map (fn [v i] (-derive this v state (conj path i))) value (range)))) IAssociative (-contains-key? [_ k] (-contains-key? value k)) (-assoc [this n v] (-derive this (-assoc-n value n v) state path)) IStack (-peek [this] (-derive this (-peek value) state path)) (-pop [this] (-derive this (-pop value) state path)) IEquiv (-equiv [_ other] (if (cursor? other) (= value (-value other)) (= value other))) IHash (-hash [_] (hash value)) IKVReduce (-kv-reduce [_ f init] (-kv-reduce value f init)) IPrintWithWriter (-pr-writer [_ writer opts] (-pr-writer value writer opts))) (defn ^:private to-cursor* [val state path] (specify val IDeref (-deref [this] (get-in @state path ::invalid)) ICursor (-path [_] path) (-state [_] state) ITransact (-transact! [this korks f tag] (transact* state this korks f tag)) IEquiv (-equiv [_ other] (if (cursor? other) (= val (-value other)) (= val other))))) (defn ^:private to-cursor ([val] (to-cursor val nil [])) ([val state] (to-cursor val state [])) ([val state path] (cond (cursor? val) val (satisfies? IToCursor val) (-to-cursor val state path) (indexed? val) (IndexedCursor. val state path) (map? val) (MapCursor. val state path) (satisfies? ICloneable val) (to-cursor* val state path) :else val))) (defn notify* [cursor tx-data] (let [state (-state cursor)] (-notify! state tx-data (to-cursor @state state)))) ;; ============================================================================= ;; Ref Cursors (declare commit! id refresh-props!) (defn root-cursor "Given an application state atom return a root cursor for it." [atom] {:pre [(satisfies? IDeref atom)]} (to-cursor @atom atom [])) (def _refs (atom {})) (defn ref-sub-cursor [x parent] (specify x ICloneable (-clone [this] (ref-sub-cursor (clone x) parent)) IAdapt (-adapt [this other] (ref-sub-cursor (adapt x other) parent)) ICursorDerive (-derive [this derived state path] (let [cursor' (to-cursor derived state path)] (if (cursor? cursor') (adapt this cursor') cursor'))) ITransact (-transact! [cursor korks f tag] (commit! cursor korks f) (-refresh-deps! parent)))) (defn ref-cursor? [x] (satisfies? IOmRef x)) (defn ref-cursor "Given a cursor return a reference cursor that inherits all of the properties and methods of the cursor. Reference cursors may be observed via om.core/observe." [cursor] {:pre [(cursor? cursor)]} (if (ref-cursor? cursor) cursor (let [path (path cursor) storage (get (swap! _refs update-in [path] (fnil identity (atom {}))) path)] (specify cursor ICursorDerive (-derive [this derived state path] (let [cursor' (to-cursor derived state path)] (if (cursor? cursor') (ref-sub-cursor cursor' this) cursor'))) IOmRef (-add-dep! [_ c] (swap! storage assoc (id c) c)) (-remove-dep! [_ c] (let [m (swap! storage dissoc (id c))] (when (zero? (count m)) (swap! _refs dissoc path)))) (-refresh-deps! [_] (doseq [c (vals @storage)] (-queue-render! (state cursor) c))) (-get-deps [_] @storage) ITransact (-transact! [cursor korks f tag] (commit! cursor korks f) (-refresh-deps! cursor)))))) (defn add-ref-to-component! [c ref] (let [state (.-state c) refs (or (aget state "__om_refs") #{})] (when-not (contains? refs ref) (aset state "__om_refs" (conj refs ref))))) (defn remove-ref-from-component! [c ref] (let [state (.-state c) refs (aget state "__om_refs")] (when (contains? refs ref) (aset state "__om_refs" (disj refs ref))))) (defn observe "Given a component and a reference cursor have the component observe the reference cursor for any data changes." [c ref] {:pre [(component? c) (cursor? ref) (ref-cursor? ref)]} (add-ref-to-component! c ref) (-add-dep! ref c) ref) (defn unobserve [c ref] (remove-ref-from-component! c ref) (-remove-dep! ref c) ref) ;; ============================================================================= ;; API (def ^:private refresh-queued false) (def ^:private refresh-set (atom #{})) (defn ^:private get-renderT [state] (or (.-om$render$T state) 0)) (defn render-all "Force a render of *all* roots. Usage of this function is almost never recommended." ([] (render-all nil)) ([state] (set! refresh-queued false) (doseq [f @refresh-set] (f)) (when-not (nil? state) (set! (.-om$render$T state) (inc (get-renderT state)))))) (def ^:private roots (atom {})) (defn ^:private valid-component? [x f] (assert (or (satisfies? IRender x) (satisfies? IRenderProps x) (satisfies? IRenderState x)) (str "Invalid Om component fn, " (.-name f) " does not return valid instance"))) (defn ^:private valid-opts? [m] (every? #{:key :react-key :key-fn :fn :init-state :state :opts :shared ::index :instrument :descriptor} (keys m))) (defn id [owner] (aget (.-state owner) "__om_id")) (defn get-descriptor ([f] (get-descriptor f nil)) ([f descriptor] (let [rdesc (or descriptor *descriptor* pure-descriptor)] (when (or (nil? (gobj/get f "om$descriptor")) (not (identical? rdesc (gobj/get f "om$tag")))) (let [factory (js/React.createFactory (js/React.createClass rdesc))] (gobj/set f "om$descriptor" factory) (gobj/set f "om$tag" rdesc)))) (gobj/get f "om$descriptor"))) (defn getf ([f cursor] (if (instance? MultiFn f) (let [dv ((.-dispatch-fn f) cursor nil)] (get-method f dv)) f)) ([f cursor opts] (if (instance? MultiFn f) (let [dv ((.-dispatch-fn f) cursor nil opts)] (get-method f dv)) f))) (defn build* ([f cursor] (build* f cursor nil)) ([f cursor m] {:pre [(ifn? f) (or (nil? m) (map? m))]} (assert (valid-opts? m) (apply str "build options contains invalid keys, only :key, :key-fn :react-key, " ":fn, :init-state, :state, and :opts allowed, given " (interpose ", " (keys m)))) (cond (nil? m) (let [shared (get-shared *parent*) ctor (get-descriptor (getf f cursor))] (ctor #js {:__om_cursor cursor :__om_shared shared :__om_root_key *root-key* :__om_app_state *state* :__om_descriptor *descriptor* :__om_instrument *instrument* :children (fn [this] (let [ret (f cursor this)] (valid-component? ret f) ret))})) :else (let [{:keys [key key-fn state init-state opts]} m dataf (get m :fn) cursor' (if-not (nil? dataf) (if-let [i (::index m)] (dataf cursor i) (dataf cursor)) cursor) rkey (cond (not (nil? key)) (get cursor' key) (not (nil? key-fn)) (key-fn cursor') :else (get m :react-key)) shared (or (:shared m) (get-shared *parent*)) ctor (get-descriptor (getf f cursor' opts) (:descriptor m))] (ctor #js {:__om_cursor cursor' :__om_index (::index m) :__om_init_state init-state :__om_state state :__om_shared shared :__om_root_key *root-key* :__om_app_state *state* :__om_descriptor *descriptor* :__om_instrument *instrument* :key (or rkey js/undefined) ;; annoying :children (if (nil? opts) (fn [this] (let [ret (f cursor' this)] (valid-component? ret f) ret)) (fn [this] (let [ret (f cursor' this opts)] (valid-component? ret f) ret)))}))))) (defn build "Builds an Om component. Takes an IRender/IRenderState instance returning function f, a value, and an optional third argument which may be a map of build specifications. f - is a function of 2 or 3 arguments. The first argument can be any value and the second argument will be the owning pure node. If a map of options m is passed in this will be the third argument. f must return at a minimum an IRender or IRenderState instance, this instance may implement other React life cycle protocols. x - any value m - a map the following keys are allowed: :key - a keyword that should be used to look up the key used by React itself when rendering sequential things. :react-key - an explicit react key :fn - a function to apply to the data before invoking f. :init-state - a map of initial state to pass to the component. :state - a map of state to pass to the component, will be merged in. :opts - a map of values. Can be used to pass side information down the render tree. :descriptor - a JS object of React methods, will be used to construct a React class per Om component function encountered. defaults to pure-descriptor. Example: (build list-of-gadgets x {:init-state {:event-chan ... :narble ...}}) " ([f x] (build f x nil)) ([f x m] {:pre [(ifn? f) (or (nil? m) (map? m))]} (if-not (nil? *instrument*) (let [ret (*instrument* f x m)] (if (= ret ::pass) (build* f x m) ret)) (build* f x m)))) (defn build-all "Build a sequence of components. f is the component constructor function, xs a sequence of values, and m a map of options the same as provided to om.core/build." ([f xs] (build-all f xs nil)) ([f xs m] {:pre [(ifn? f) (or (nil? m) (map? m))]} (map (fn [x i] (build f x (assoc m ::index i))) xs (range)))) (defn ^:private setup [state key tx-listen] (when-not (satisfies? INotify state) (let [properties (atom {}) listeners (atom {}) render-queue (atom #{})] (specify! state IRootProperties (-set-property! [_ id k v] (swap! properties assoc-in [id k] v)) (-remove-property! [_ id k] (swap! properties dissoc id k)) (-remove-properties! [_ id] (swap! properties dissoc id)) (-get-property [_ id k] (get-in @properties [id k])) INotify (-listen! [this key tx-listen] (when-not (nil? tx-listen) (swap! listeners assoc key tx-listen)) this) (-unlisten! [this key] (swap! listeners dissoc key) this) (-notify! [this tx-data root-cursor] (doseq [[_ f] @listeners] (f tx-data root-cursor)) this) IRenderQueue (-get-queue [this] @render-queue) (-queue-render! [this c] (when-not (contains? @render-queue c) (swap! render-queue conj c) (swap! this identity))) (-empty-queue! [this] (swap! render-queue empty))))) (-listen! state key tx-listen)) (defn ^:private tear-down [state key] (-unlisten! state key)) (defn tag-root-key [cursor root-key] (if (cursor? cursor) (specify cursor ICloneable (-clone [this] (tag-root-key (clone cursor) root-key)) IAdapt (-adapt [this other] (tag-root-key (adapt cursor other) root-key)) IRootKey (-root-key [this] root-key)) cursor)) (defn root "Take a component constructor function f, value an immutable tree of associative data structures optionally an wrapped in an IAtom instance, and a map of options and installs an Om/React render loop. f must return an instance that at a minimum implements IRender or IRenderState (it may implement other React life cycle protocols). f must take at least two arguments, the root cursor and the owning pure node. A cursor is just the original data wrapped in an ICursor instance which maintains path information. Only one root render loop allowed per target element. om.core/root is idempotent, if called again on the same target element the previous render loop will be replaced. Options may also include any key allowed by om.core/build to customize f. In addition om.core/root supports the following special options: :target - (required) a DOM element. :shared - data to be shared by all components, see om.core/get-shared :tx-listen - a function that will listen in in transactions, should take 2 arguments - the first a map containing the path, old and new state at path, old and new global state, and transaction tag if provided. :instrument - a function of three arguments that if provided will intercept all calls to om.core/build. This function should correspond to the three arity version of om.core/build. :adapt - a function to adapt the root cursor :raf - override requestAnimationFrame based rendering. If false setTimeout will be use. If given a function will be invoked instead. Example: (root (fn [data owner] ...) {:message :hello} {:target js/document.body})" ([f value {:keys [target tx-listen path instrument descriptor adapt raf] :as options}] (assert (ifn? f) "First argument must be a function") (assert (not (nil? target)) "No target specified to om.core/root") ;; only one root render loop per target (let [roots' @roots] (when (contains? roots' target) ((get roots' target)))) (let [watch-key (<KEY>) state (if (satisfies? IAtom value) value (atom value)) state (setup state watch-key tx-listen) adapt (or adapt identity) m (dissoc options :target :tx-listen :path :adapt :raf) ret (atom nil) rootf (fn rootf [] (swap! refresh-set disj rootf) (let [value @state cursor (adapt (tag-root-key (if (nil? path) (to-cursor value state []) (to-cursor (get-in value path) state path)) watch-key))] (when-not (-get-property state watch-key :skip-render-root) (-set-property! state watch-key :skip-render-root true) (let [c (dom/render (binding [*descriptor* descriptor *instrument* instrument *state* state *root-key* watch-key] (build f cursor m)) target)] (when (nil? @ret) (reset! ret c)))) ;; update state pass (let [queue (-get-queue state)] (-empty-queue! state) (when-not (empty? queue) (doseq [c queue] (when (.isMounted c) (when-let [next-props (aget (.-state c) "__om_next_cursor")] (aset (.-props c) "__om_cursor" next-props) (aset (.-state c) "__om_next_cursor" nil)) (when (or (not (satisfies? ICheckState (children c))) (.shouldComponentUpdate c (.-props c) (.-state c))) (.forceUpdate c)))))) ;; ref cursor pass (let [_refs @_refs] (when-not (empty? _refs) (doseq [[path cs] _refs] (let [cs @cs] (doseq [[id c] cs] (when (.shouldComponentUpdate c (.-props c) (.-state c)) (.forceUpdate c))))))) @ret))] (add-watch state watch-key (fn [_ _ o n] (when (and (not (-get-property state watch-key :ignore)) (not (identical? o n))) (-set-property! state watch-key :skip-render-root false)) (-set-property! state watch-key :ignore false) (when-not (contains? @refresh-set rootf) (swap! refresh-set conj rootf)) (when-not refresh-queued (set! refresh-queued true) (cond (fn? raf) (raf) (or (false? raf) (not (exists? js/requestAnimationFrame))) (js/setTimeout #(render-all state) 16) :else (js/requestAnimationFrame #(render-all state)))))) ;; store fn to remove previous root render loop (swap! roots assoc target (fn [] (-remove-properties! state watch-key) (remove-watch state watch-key) (tear-down state watch-key) (swap! refresh-set disj rootf) (swap! roots dissoc target) (js/React.unmountComponentAtNode target))) (rootf)))) (defn detach-root "Given a DOM target remove its render loop if one exists." [target] {:pre [(gdom/isElement target)]} (when-let [f (get @roots target)] (f))) (defn transactable? [x] (satisfies? ITransact x)) (defn transact! "Given a tag, a cursor, an optional list of keys ks, mutate the tree at the path specified by the cursor + the optional keys by applying f to the specified value in the tree. An Om re-render will be triggered." ([cursor f] (transact! cursor [] f nil)) ([cursor korks f] (transact! cursor korks f nil)) ([cursor korks f tag] {:pre [(transactable? cursor) (ifn? f)]} (let [korks (cond (nil? korks) [] (sequential? korks) korks :else [korks])] (-transact! cursor korks f tag)))) (defn update! "Like transact! but no function provided, instead a replacement value is given." ([cursor v] {:pre [(cursor? cursor)]} (transact! cursor [] (fn [_] v) nil)) ([cursor korks v] {:pre [(cursor? cursor)]} (transact! cursor korks (fn [_] v) nil)) ([cursor korks v tag] {:pre [(cursor? cursor)]} (transact! cursor korks (fn [_] v) tag))) (defn commit! "EXPERIMENTAL: Like transact! but does not schedule a re-render or create a transact event." [cursor korks f] {:pre [(cursor? cursor) (ifn? f)]} (let [key (when (satisfies? IRootKey cursor) (-root-key cursor)) app-state (state cursor) korks (cond (nil? korks) [] (sequential? korks) korks :else [korks]) cpath (path cursor) rpath (into cpath korks)] (when key (-set-property! app-state key :ignore true)) (if (empty? rpath) (swap! app-state f) (swap! app-state update-in rpath f)))) (defn get-node "A helper function to get at React DOM refs. Given a owning pure node extract the DOM ref specified by name." ([owner] (.getDOMNode owner)) ([owner name] {:pre [(string? name)]} (some-> (.-refs owner) (aget name) (.getDOMNode)))) (defn get-ref "A helper function to get at React refs. Given an owning pure node extract the ref specified by name." [owner name] {:pre [(component? owner) (string? name)]} (some-> (.-refs owner) (gobj/get name))) (defn mounted? "Return true if the backing React component is mounted into the DOM." [owner] (.isMounted owner)) (defn set-state! "Takes a pure owning component, a sequential list of keys and value and sets the state of the component. Conceptually analagous to React setState. Will schedule an Om re-render." ([owner v] {:pre [(component? owner)]} (-set-state! owner v true)) ([owner korks v] {:pre [(component? owner)]} (let [ks (if (sequential? korks) korks [korks])] (-set-state! owner ks v true)))) (defn set-state-nr! "EXPERIMENTAL: Same as set-state! but does not trigger re-render." ([owner v] {:pre [(component? owner)]} (-set-state! owner v false)) ([owner korks v] {:pre [(component? owner)]} (let [ks (if (sequential? korks) korks [korks])] (-set-state! owner ks v false)))) (defn update-state! "Takes a pure owning component, a sequential list of keys and a function to transition the state of the component. Conceptually analagous to React setState. Will schedule an Om re-render." ([owner f] {:pre [(component? owner) (ifn? f)]} (set-state! owner (f (get-state owner)))) ([owner korks f] {:pre [(component? owner) (ifn? f)]} (set-state! owner korks (f (get-state owner korks))))) (defn update-state-nr! "EXPERIMENTAL: Same as update-state! but does not trigger re-render." ([owner f] {:pre [(component? owner) (ifn? f)]} (set-state-nr! owner (f (get-state owner)))) ([owner korks f] {:pre [(component? owner) (ifn? f)]} (set-state-nr! owner korks (f (get-state owner korks))))) (defn refresh! "Utility to re-render an owner." [owner] {:pre [(component? owner)]} (update-state! owner identity)) (defn get-render-state "Takes a pure owning component and an optional key or sequential list of keys and returns a property in the component local state if it exists. Always returns the rendered state, not the pending state." ([owner] {:pre [(component? owner)]} (-get-render-state owner)) ([owner korks] {:pre [(component? owner)]} (let [ks (if (sequential? korks) korks [korks])] (-get-render-state owner ks))))
true
(ns om.core (:require-macros om.core) (:require [cljsjs.react] [om.dom :as dom :include-macros true] [goog.object :as gobj] [goog.dom :as gdom] [goog.dom.dataset :as gdomdata]) (:import [goog.ui IdGenerator])) (def ^{:dynamic true :private true} *parent* nil) (def ^{:dynamic true :private true} *instrument* nil) (def ^{:dynamic true :private true} *descriptor* nil) (def ^{:dynamic true :private true} *state* nil) (def ^{:dynamic true :private true} *root-key* nil) ;; ============================================================================= ;; React Life Cycle Protocols ;; ;; http://facebook.github.io/react/docs/component-specs.html (defprotocol IDisplayName (display-name [this])) (defprotocol IInitState (init-state [this])) (defprotocol IShouldUpdate (should-update [this next-props next-state])) (defprotocol IWillMount (will-mount [this])) (defprotocol IDidMount (did-mount [this])) (defprotocol IWillUnmount (will-unmount [this])) (defprotocol IWillUpdate (will-update [this next-props next-state])) (defprotocol IDidUpdate (did-update [this prev-props prev-state])) (defprotocol IWillReceiveProps (will-receive-props [this next-props])) (defprotocol IRender (render [this])) (defprotocol IRenderProps (render-props [this props state])) (defprotocol IRenderState (render-state [this state])) ;; marker protocol, if set component will check equality of current ;; and render state (defprotocol ICheckState) ;; ============================================================================= ;; Om Protocols (defprotocol IOmSwap (-om-swap! [this cursor korks f tag])) (defprotocol IGetState (-get-state [this] [this ks])) (defprotocol IGetRenderState (-get-render-state [this] [this ks])) (defprotocol ISetState (-set-state! [this val render] [this ks val render])) ;; PRIVATE render queue, for components that use local state ;; and independently addressable components (defprotocol IRenderQueue (-get-queue [this]) (-queue-render! [this c]) (-empty-queue! [this])) (defprotocol IValue (-value [x])) (extend-type default IValue (-value [x] x)) (defprotocol ICursor (-path [cursor]) (-state [cursor])) (defprotocol IToCursor (-to-cursor [value state] [value state path])) (defprotocol ICursorDerive (-derive [cursor derived state path])) (declare to-cursor) (extend-type default ICursorDerive (-derive [this derived state path] (to-cursor derived state path))) (defn path [cursor] (-path cursor)) (defn value [cursor] (-value cursor)) (defn state [cursor] (-state cursor)) (defprotocol ITransact (-transact! [cursor korks f tag])) ;; PRIVATE (defprotocol INotify (-listen! [x key tx-listen]) (-unlisten! [x key]) (-notify! [x tx-data root-cursor])) ;; PRIVATE (defprotocol IRootProperties (-set-property! [this id p val]) (-remove-property! [this id p]) (-remove-properties! [this id]) (-get-property [this id p])) ;; PRIVATE (defprotocol IRootKey (-root-key [cursor])) (defprotocol IAdapt (-adapt [this other])) (extend-type default IAdapt (-adapt [_ other] other)) (defn adapt [x other] (-adapt x other)) (defprotocol IOmRef (-add-dep! [this c]) (-remove-dep! [this c]) (-refresh-deps! [this]) (-get-deps [this])) (declare notify*) (defn transact* ([state cursor korks f tag] (let [old-state @state path (into (om.core/path cursor) korks) ret (cond (satisfies? IOmSwap state) (-om-swap! state cursor korks f tag) (empty? path) (swap! state f) :else (swap! state update-in path f))] (when-not (= ret ::defer) (let [tx-data {:path path :old-value (get-in old-state path) :new-value (get-in @state path) :old-state old-state :new-state @state}] (if-not (nil? tag) (notify* cursor (assoc tx-data :tag tag)) (notify* cursor tx-data))))))) (defn cursor? [x] (satisfies? ICursor x)) (defn component? [x] (aget x "isOmComponent")) (defn ^:private children [node] (let [c (.. node -props -children)] (if (ifn? c) (set! (.. node -props -children) (c node)) c))) (defn get-props "Given an owning Pure node return the Om props. Analogous to React component props." ([x] {:pre [(component? x)]} (aget (.-props x) "__om_cursor")) ([x korks] {:pre [(component? x)]} (let [korks (if (sequential? korks) korks [korks])] (cond-> (aget (.-props x) "__om_cursor") (seq korks) (get-in korks))))) (defn get-state "Returns the component local state of an owning component. owner is the component. An optional key or sequence of keys may be given to extract a specific value. Always returns pending state." ([owner] {:pre [(component? owner)]} (-get-state owner)) ([owner korks] {:pre [(component? owner)]} (let [ks (if (sequential? korks) korks [korks])] (-get-state owner ks)))) (defn get-shared "Takes an owner and returns a map of global shared values for a render loop. An optional key or sequence of keys may be given to extract a specific value." ([owner] (when-not (nil? owner) (aget (.-props owner) "__om_shared"))) ([owner korks] (cond (not (sequential? korks)) (get (get-shared owner) korks) (empty? korks) (get-shared owner) :else (get-in (get-shared owner) korks)))) (defn ^:private merge-pending-state [owner] (let [state (.-state owner)] (when-let [pending-state (aget state "__om_pending_state")] (doto state (aset "__om_prev_state" (aget state "__om_state")) (aset "__om_state" pending-state) (aset "__om_pending_state" nil))))) (defn ^:private merge-props-state ([owner] (merge-props-state owner nil)) ([owner props] (let [props (or props (.-props owner))] (when-let [props-state (aget props "__om_state")] (let [state (.-state owner)] (aset state "__om_pending_state" (merge (or (aget state "__om_pending_state") (aget state "__om_state")) props-state)) (aset props "__om_state" nil)))))) (defn ref-changed? [ref] (let [val (value ref) val' (get-in @(state ref) (path ref) ::not-found)] (not= val val'))) (defn update-refs [c] (let [cstate (.-state c) refs (aget cstate "__om_refs")] (when-not (zero? (count refs)) (aset cstate "__om_refs" (into #{} (filter nil? (map (fn [ref] (let [ref-val (value ref) ref-state (state ref) ref-path (path ref) ref-val' (get-in @ref-state ref-path ::not-found)] (when (not= ref-val ::not-found) (if (not= ref-val ref-val') (adapt ref (to-cursor ref-val' ref-state ref-path)) ref)))) refs))))))) (declare unobserve) (def pure-methods {:isOmComponent true :getDisplayName (fn [] (this-as this (let [c (children this)] (when (satisfies? IDisplayName c) (display-name c))))) :getInitialState (fn [] (this-as this (let [c (children this) props (.-props this) istate (or (aget props "__om_init_state") {}) id (::id istate) ret #js {:__om_id (or id (.getNextUniqueId (.getInstance IdGenerator))) :__om_state (merge (when (satisfies? IInitState c) (init-state c)) (dissoc istate ::id))}] (aset props "__om_init_state" nil) ret))) :shouldComponentUpdate (fn [next-props next-state] (this-as this (let [props (.-props this) state (.-state this) c (children this)] ;; need to merge in props state first (merge-props-state this next-props) (if (satisfies? IShouldUpdate c) (should-update c (get-props #js {:props next-props :isOmComponent true}) (-get-state this)) (let [cursor (aget props "__om_cursor") next-cursor (aget next-props "__om_cursor")] (cond (not= (-value cursor) (-value next-cursor)) true (and (cursor? cursor) (cursor? next-cursor) (not= (-path cursor) (-path next-cursor ))) true (not= (-get-state this) (-get-render-state this)) true (and (not (zero? (count (aget state "__om_refs")))) (some #(ref-changed? %) (aget state "__om_refs"))) true (not (== (aget props "__om_index") (aget next-props "__om_index"))) true :else false)))))) :componentWillMount (fn [] (this-as this (merge-props-state this) (let [c (children this)] (when (satisfies? IWillMount c) (will-mount c))) (merge-pending-state this))) :componentDidMount (fn [] (this-as this (let [c (children this) cursor (aget (.-props this) "__om_cursor")] (when (satisfies? IDidMount c) (did-mount c))))) :componentWillUnmount (fn [] (this-as this (let [c (children this) cursor (aget (.-props this) "__om_cursor")] (when (satisfies? IWillUnmount c) (will-unmount c)) (when-let [refs (seq (aget (.-state this) "__om_refs"))] (doseq [ref refs] (unobserve this ref)))))) :componentWillUpdate (fn [next-props next-state] (this-as this (let [c (children this)] (when (satisfies? IWillUpdate c) (let [state (.-state this)] (will-update c (get-props #js {:props next-props :isOmComponent true}) (-get-state this))))) (merge-pending-state this) (update-refs this))) :componentDidUpdate (fn [prev-props prev-state] (this-as this (let [c (children this)] (when (satisfies? IDidUpdate c) (let [state (.-state this)] (did-update c (get-props #js {:props prev-props :isOmComponent true}) (or (aget state "__om_prev_state") (aget state "__om_state"))))) (aset (.-state this) "__om_prev_state" nil)))) :componentWillReceiveProps (fn [next-props] (this-as this (let [c (children this)] (when (satisfies? IWillReceiveProps c) (will-receive-props c (get-props #js {:props next-props :isOmComponent true})))))) :render (fn [] (this-as this (let [c (children this) props (.-props this)] (binding [*parent* this *state* (aget props "__om_app_state") *instrument* (aget props "__om_instrument") *descriptor* (aget props "__om_descriptor") *root-key* (aget props "__om_root_key")] (cond (satisfies? IRender c) (render c) (satisfies? IRenderProps c) (render-props c (aget props "__om_cursor") (get-state this)) (satisfies? IRenderState c) (render-state c (get-state this)) :else c)))))}) (defn specify-state-methods! [obj] (specify! obj ISetState (-set-state! ([this val render] (let [props (.-props this) app-state (aget props "__om_app_state")] (aset (.-state this) "__om_pending_state" val) (when (and (not (nil? app-state)) render) (-queue-render! app-state this)))) ([this ks val render] (let [props (.-props this) state (.-state this) pstate (-get-state this) app-state (aget props "__om_app_state")] (aset state "__om_pending_state" (assoc-in pstate ks val)) (when (and (not (nil? app-state)) render) (-queue-render! app-state this))))) IGetRenderState (-get-render-state ([this] (aget (.-state this) "__om_state")) ([this ks] (get-in (-get-render-state this) ks))) IGetState (-get-state ([this] (let [state (.-state this)] (or (aget state "__om_pending_state") (aget state "__om_state")))) ([this ks] (get-in (-get-state this) ks))))) (def pure-descriptor (specify-state-methods! (clj->js pure-methods))) ;; ============================================================================= ;; EXPERIMENTAL: No Local State (declare get-node) (defn react-id [x] (let [id (gdomdata/get (get-node x) "reactid")] (assert id) id)) (defn get-gstate [owner] (aget (.-props owner) "__om_app_state")) (defn no-local-merge-pending-state [owner] (let [gstate (get-gstate owner) spath [:state-map (react-id owner)] states (get-in @gstate spath)] (when (:pending-state states) (swap! gstate update-in spath (fn [states] (-> states (assoc :previous-state (:render-state states)) (assoc :render-state (merge (:render-state states) (:pending-state states))) (dissoc :pending-state))))))) (declare mounted?) (def no-local-state-methods (assoc pure-methods :getInitialState (fn [] (this-as this (let [c (children this) props (.-props this) istate (or (aget props "__om_init_state") {}) om-id (or (:om.core/id istate) (.getNextUniqueId (.getInstance IdGenerator))) state (merge (dissoc istate ::id) (when (satisfies? IInitState c) (init-state c)))] (aset props "__om_init_state" nil) #js {:__om_id om-id}))) :componentDidMount (fn [] (this-as this (let [c (children this) cursor (aget (.-props this) "__om_cursor") spath [:state-map (react-id this) :render-state]] (swap! (get-gstate this) assoc-in spath state) (when (satisfies? IDidMount c) (did-mount c))))) :componentWillMount (fn [] (this-as this (merge-props-state this) (let [c (children this)] (when (satisfies? IWillMount c) (will-mount c))) ;; TODO: cannot merge state until mounted? (when (mounted? this) (no-local-merge-pending-state this)))) :componentWillUnmount (fn [] (this-as this (let [c (children this)] (when (satisfies? IWillUnmount c) (will-unmount c)) (swap! (get-gstate this) update-in [:state-map] dissoc (react-id this)) (when-let [refs (seq (aget (.-state this) "__om_refs"))] (doseq [ref refs] (unobserve this ref)))))) :componentWillUpdate (fn [next-props next-state] (this-as this (let [props (.-props this) c (children this)] (when (satisfies? IWillUpdate c) (let [state (.-state this)] (will-update c (get-props #js {:props next-props :isOmComponent true}) (-get-state this))))) (no-local-merge-pending-state this) (update-refs this))) :componentDidUpdate (fn [prev-props prev-state] (this-as this (let [c (children this) gstate (get-gstate this) states (get-in @gstate [:state-map (react-id this)]) spath [:state-map (react-id this)]] (when (satisfies? IDidUpdate c) (let [state (.-state this)] (did-update c (get-props #js {:props prev-props :isOmComponent true}) (or (:previous-state states) (:render-state states))))) (when (:previous-state states) (swap! gstate update-in spath dissoc :previous-state))))))) (defn no-local-descriptor [methods] (specify! (clj->js methods) ISetState (-set-state! ([this val render] (let [gstate (get-gstate this) spath [:state-map (react-id this) :pending-state]] (swap! (get-gstate this) assoc-in spath val) (when (and (not (nil? gstate)) render) (-queue-render! gstate this)))) ([this ks val render] (-set-state! this (assoc-in (-get-state this) ks val) render))) IGetRenderState (-get-render-state ([this] (let [spath [:state-map (react-id this) :render-state]] (get-in @(get-gstate this) spath))) ([this ks] (get-in (-get-render-state this) ks))) IGetState (-get-state ([this] (if (mounted? this) (let [spath [:state-map (react-id this)] states (get-in @(get-gstate this) spath)] (or (:pending-state states) (:render-state states))) ;; TODO: means state cannot be written to until mounted - David (aget (.-props this) "__om_init_state"))) ([this ks] (get-in (-get-state this) ks))))) ;; ============================================================================= ;; Cursors (defn valid? [x] (if (satisfies? ICursor x) (not (keyword-identical? @x ::invalid)) true)) (deftype MapCursor [value state path] IWithMeta (-with-meta [_ new-meta] (MapCursor. (with-meta value new-meta) state path)) IMeta (-meta [_] (meta value)) IDeref (-deref [this] (get-in @state path ::invalid)) IValue (-value [_] value) ICursor (-path [_] path) (-state [_] state) ITransact (-transact! [this korks f tag] (transact* state this korks f tag)) ICloneable (-clone [_] (MapCursor. value state path)) ICounted (-count [_] (-count value)) ICollection (-conj [_ o] (MapCursor. (-conj value o) state path)) ;; EXPERIMENTAL IEmptyableCollection (-empty [_] (MapCursor. (empty value) state path)) ILookup (-lookup [this k] (-lookup this k nil)) (-lookup [this k not-found] (let [v (-lookup value k ::not-found)] (if-not (= v ::not-found) (-derive this v state (conj path k)) not-found))) IFn (-invoke [this k] (-lookup this k)) (-invoke [this k not-found] (-lookup this k not-found)) ISeqable (-seq [this] (when (pos? (count value)) (map (fn [[k v]] [k (-derive this v state (conj path k))]) value))) IAssociative (-contains-key? [_ k] (-contains-key? value k)) (-assoc [_ k v] (MapCursor. (-assoc value k v) state path)) IMap (-dissoc [_ k] (MapCursor. (-dissoc value k) state path)) IEquiv (-equiv [_ other] (if (cursor? other) (= value (-value other)) (= value other))) IHash (-hash [_] (hash value)) IKVReduce (-kv-reduce [_ f init] (-kv-reduce value f init)) IPrintWithWriter (-pr-writer [_ writer opts] (-pr-writer value writer opts))) (deftype IndexedCursor [value state path] ISequential IDeref (-deref [this] (get-in @state path ::invalid)) IWithMeta (-with-meta [_ new-meta] (IndexedCursor. (with-meta value new-meta) state path)) IMeta (-meta [_] (meta value)) IValue (-value [_] value) ICursor (-path [_] path) (-state [_] state) ITransact (-transact! [this korks f tag] (transact* state this korks f tag)) ICloneable (-clone [_] (IndexedCursor. value state path)) ICounted (-count [_] (-count value)) ICollection (-conj [_ o] (IndexedCursor. (-conj value o) state path)) ;; EXPERIMENTAL IEmptyableCollection (-empty [_] (IndexedCursor. (empty value) state path)) ILookup (-lookup [this n] (-nth this n nil)) (-lookup [this n not-found] (-nth this n not-found)) IFn (-invoke [this k] (-lookup this k)) (-invoke [this k not-found] (-lookup this k not-found)) IIndexed (-nth [this n] (-derive this (-nth value n) state (conj path n))) (-nth [this n not-found] (if (< n (-count value)) (-derive this (-nth value n not-found) state (conj path n)) not-found)) ISeqable (-seq [this] (when (pos? (count value)) (map (fn [v i] (-derive this v state (conj path i))) value (range)))) IAssociative (-contains-key? [_ k] (-contains-key? value k)) (-assoc [this n v] (-derive this (-assoc-n value n v) state path)) IStack (-peek [this] (-derive this (-peek value) state path)) (-pop [this] (-derive this (-pop value) state path)) IEquiv (-equiv [_ other] (if (cursor? other) (= value (-value other)) (= value other))) IHash (-hash [_] (hash value)) IKVReduce (-kv-reduce [_ f init] (-kv-reduce value f init)) IPrintWithWriter (-pr-writer [_ writer opts] (-pr-writer value writer opts))) (defn ^:private to-cursor* [val state path] (specify val IDeref (-deref [this] (get-in @state path ::invalid)) ICursor (-path [_] path) (-state [_] state) ITransact (-transact! [this korks f tag] (transact* state this korks f tag)) IEquiv (-equiv [_ other] (if (cursor? other) (= val (-value other)) (= val other))))) (defn ^:private to-cursor ([val] (to-cursor val nil [])) ([val state] (to-cursor val state [])) ([val state path] (cond (cursor? val) val (satisfies? IToCursor val) (-to-cursor val state path) (indexed? val) (IndexedCursor. val state path) (map? val) (MapCursor. val state path) (satisfies? ICloneable val) (to-cursor* val state path) :else val))) (defn notify* [cursor tx-data] (let [state (-state cursor)] (-notify! state tx-data (to-cursor @state state)))) ;; ============================================================================= ;; Ref Cursors (declare commit! id refresh-props!) (defn root-cursor "Given an application state atom return a root cursor for it." [atom] {:pre [(satisfies? IDeref atom)]} (to-cursor @atom atom [])) (def _refs (atom {})) (defn ref-sub-cursor [x parent] (specify x ICloneable (-clone [this] (ref-sub-cursor (clone x) parent)) IAdapt (-adapt [this other] (ref-sub-cursor (adapt x other) parent)) ICursorDerive (-derive [this derived state path] (let [cursor' (to-cursor derived state path)] (if (cursor? cursor') (adapt this cursor') cursor'))) ITransact (-transact! [cursor korks f tag] (commit! cursor korks f) (-refresh-deps! parent)))) (defn ref-cursor? [x] (satisfies? IOmRef x)) (defn ref-cursor "Given a cursor return a reference cursor that inherits all of the properties and methods of the cursor. Reference cursors may be observed via om.core/observe." [cursor] {:pre [(cursor? cursor)]} (if (ref-cursor? cursor) cursor (let [path (path cursor) storage (get (swap! _refs update-in [path] (fnil identity (atom {}))) path)] (specify cursor ICursorDerive (-derive [this derived state path] (let [cursor' (to-cursor derived state path)] (if (cursor? cursor') (ref-sub-cursor cursor' this) cursor'))) IOmRef (-add-dep! [_ c] (swap! storage assoc (id c) c)) (-remove-dep! [_ c] (let [m (swap! storage dissoc (id c))] (when (zero? (count m)) (swap! _refs dissoc path)))) (-refresh-deps! [_] (doseq [c (vals @storage)] (-queue-render! (state cursor) c))) (-get-deps [_] @storage) ITransact (-transact! [cursor korks f tag] (commit! cursor korks f) (-refresh-deps! cursor)))))) (defn add-ref-to-component! [c ref] (let [state (.-state c) refs (or (aget state "__om_refs") #{})] (when-not (contains? refs ref) (aset state "__om_refs" (conj refs ref))))) (defn remove-ref-from-component! [c ref] (let [state (.-state c) refs (aget state "__om_refs")] (when (contains? refs ref) (aset state "__om_refs" (disj refs ref))))) (defn observe "Given a component and a reference cursor have the component observe the reference cursor for any data changes." [c ref] {:pre [(component? c) (cursor? ref) (ref-cursor? ref)]} (add-ref-to-component! c ref) (-add-dep! ref c) ref) (defn unobserve [c ref] (remove-ref-from-component! c ref) (-remove-dep! ref c) ref) ;; ============================================================================= ;; API (def ^:private refresh-queued false) (def ^:private refresh-set (atom #{})) (defn ^:private get-renderT [state] (or (.-om$render$T state) 0)) (defn render-all "Force a render of *all* roots. Usage of this function is almost never recommended." ([] (render-all nil)) ([state] (set! refresh-queued false) (doseq [f @refresh-set] (f)) (when-not (nil? state) (set! (.-om$render$T state) (inc (get-renderT state)))))) (def ^:private roots (atom {})) (defn ^:private valid-component? [x f] (assert (or (satisfies? IRender x) (satisfies? IRenderProps x) (satisfies? IRenderState x)) (str "Invalid Om component fn, " (.-name f) " does not return valid instance"))) (defn ^:private valid-opts? [m] (every? #{:key :react-key :key-fn :fn :init-state :state :opts :shared ::index :instrument :descriptor} (keys m))) (defn id [owner] (aget (.-state owner) "__om_id")) (defn get-descriptor ([f] (get-descriptor f nil)) ([f descriptor] (let [rdesc (or descriptor *descriptor* pure-descriptor)] (when (or (nil? (gobj/get f "om$descriptor")) (not (identical? rdesc (gobj/get f "om$tag")))) (let [factory (js/React.createFactory (js/React.createClass rdesc))] (gobj/set f "om$descriptor" factory) (gobj/set f "om$tag" rdesc)))) (gobj/get f "om$descriptor"))) (defn getf ([f cursor] (if (instance? MultiFn f) (let [dv ((.-dispatch-fn f) cursor nil)] (get-method f dv)) f)) ([f cursor opts] (if (instance? MultiFn f) (let [dv ((.-dispatch-fn f) cursor nil opts)] (get-method f dv)) f))) (defn build* ([f cursor] (build* f cursor nil)) ([f cursor m] {:pre [(ifn? f) (or (nil? m) (map? m))]} (assert (valid-opts? m) (apply str "build options contains invalid keys, only :key, :key-fn :react-key, " ":fn, :init-state, :state, and :opts allowed, given " (interpose ", " (keys m)))) (cond (nil? m) (let [shared (get-shared *parent*) ctor (get-descriptor (getf f cursor))] (ctor #js {:__om_cursor cursor :__om_shared shared :__om_root_key *root-key* :__om_app_state *state* :__om_descriptor *descriptor* :__om_instrument *instrument* :children (fn [this] (let [ret (f cursor this)] (valid-component? ret f) ret))})) :else (let [{:keys [key key-fn state init-state opts]} m dataf (get m :fn) cursor' (if-not (nil? dataf) (if-let [i (::index m)] (dataf cursor i) (dataf cursor)) cursor) rkey (cond (not (nil? key)) (get cursor' key) (not (nil? key-fn)) (key-fn cursor') :else (get m :react-key)) shared (or (:shared m) (get-shared *parent*)) ctor (get-descriptor (getf f cursor' opts) (:descriptor m))] (ctor #js {:__om_cursor cursor' :__om_index (::index m) :__om_init_state init-state :__om_state state :__om_shared shared :__om_root_key *root-key* :__om_app_state *state* :__om_descriptor *descriptor* :__om_instrument *instrument* :key (or rkey js/undefined) ;; annoying :children (if (nil? opts) (fn [this] (let [ret (f cursor' this)] (valid-component? ret f) ret)) (fn [this] (let [ret (f cursor' this opts)] (valid-component? ret f) ret)))}))))) (defn build "Builds an Om component. Takes an IRender/IRenderState instance returning function f, a value, and an optional third argument which may be a map of build specifications. f - is a function of 2 or 3 arguments. The first argument can be any value and the second argument will be the owning pure node. If a map of options m is passed in this will be the third argument. f must return at a minimum an IRender or IRenderState instance, this instance may implement other React life cycle protocols. x - any value m - a map the following keys are allowed: :key - a keyword that should be used to look up the key used by React itself when rendering sequential things. :react-key - an explicit react key :fn - a function to apply to the data before invoking f. :init-state - a map of initial state to pass to the component. :state - a map of state to pass to the component, will be merged in. :opts - a map of values. Can be used to pass side information down the render tree. :descriptor - a JS object of React methods, will be used to construct a React class per Om component function encountered. defaults to pure-descriptor. Example: (build list-of-gadgets x {:init-state {:event-chan ... :narble ...}}) " ([f x] (build f x nil)) ([f x m] {:pre [(ifn? f) (or (nil? m) (map? m))]} (if-not (nil? *instrument*) (let [ret (*instrument* f x m)] (if (= ret ::pass) (build* f x m) ret)) (build* f x m)))) (defn build-all "Build a sequence of components. f is the component constructor function, xs a sequence of values, and m a map of options the same as provided to om.core/build." ([f xs] (build-all f xs nil)) ([f xs m] {:pre [(ifn? f) (or (nil? m) (map? m))]} (map (fn [x i] (build f x (assoc m ::index i))) xs (range)))) (defn ^:private setup [state key tx-listen] (when-not (satisfies? INotify state) (let [properties (atom {}) listeners (atom {}) render-queue (atom #{})] (specify! state IRootProperties (-set-property! [_ id k v] (swap! properties assoc-in [id k] v)) (-remove-property! [_ id k] (swap! properties dissoc id k)) (-remove-properties! [_ id] (swap! properties dissoc id)) (-get-property [_ id k] (get-in @properties [id k])) INotify (-listen! [this key tx-listen] (when-not (nil? tx-listen) (swap! listeners assoc key tx-listen)) this) (-unlisten! [this key] (swap! listeners dissoc key) this) (-notify! [this tx-data root-cursor] (doseq [[_ f] @listeners] (f tx-data root-cursor)) this) IRenderQueue (-get-queue [this] @render-queue) (-queue-render! [this c] (when-not (contains? @render-queue c) (swap! render-queue conj c) (swap! this identity))) (-empty-queue! [this] (swap! render-queue empty))))) (-listen! state key tx-listen)) (defn ^:private tear-down [state key] (-unlisten! state key)) (defn tag-root-key [cursor root-key] (if (cursor? cursor) (specify cursor ICloneable (-clone [this] (tag-root-key (clone cursor) root-key)) IAdapt (-adapt [this other] (tag-root-key (adapt cursor other) root-key)) IRootKey (-root-key [this] root-key)) cursor)) (defn root "Take a component constructor function f, value an immutable tree of associative data structures optionally an wrapped in an IAtom instance, and a map of options and installs an Om/React render loop. f must return an instance that at a minimum implements IRender or IRenderState (it may implement other React life cycle protocols). f must take at least two arguments, the root cursor and the owning pure node. A cursor is just the original data wrapped in an ICursor instance which maintains path information. Only one root render loop allowed per target element. om.core/root is idempotent, if called again on the same target element the previous render loop will be replaced. Options may also include any key allowed by om.core/build to customize f. In addition om.core/root supports the following special options: :target - (required) a DOM element. :shared - data to be shared by all components, see om.core/get-shared :tx-listen - a function that will listen in in transactions, should take 2 arguments - the first a map containing the path, old and new state at path, old and new global state, and transaction tag if provided. :instrument - a function of three arguments that if provided will intercept all calls to om.core/build. This function should correspond to the three arity version of om.core/build. :adapt - a function to adapt the root cursor :raf - override requestAnimationFrame based rendering. If false setTimeout will be use. If given a function will be invoked instead. Example: (root (fn [data owner] ...) {:message :hello} {:target js/document.body})" ([f value {:keys [target tx-listen path instrument descriptor adapt raf] :as options}] (assert (ifn? f) "First argument must be a function") (assert (not (nil? target)) "No target specified to om.core/root") ;; only one root render loop per target (let [roots' @roots] (when (contains? roots' target) ((get roots' target)))) (let [watch-key (PI:KEY:<KEY>END_PI) state (if (satisfies? IAtom value) value (atom value)) state (setup state watch-key tx-listen) adapt (or adapt identity) m (dissoc options :target :tx-listen :path :adapt :raf) ret (atom nil) rootf (fn rootf [] (swap! refresh-set disj rootf) (let [value @state cursor (adapt (tag-root-key (if (nil? path) (to-cursor value state []) (to-cursor (get-in value path) state path)) watch-key))] (when-not (-get-property state watch-key :skip-render-root) (-set-property! state watch-key :skip-render-root true) (let [c (dom/render (binding [*descriptor* descriptor *instrument* instrument *state* state *root-key* watch-key] (build f cursor m)) target)] (when (nil? @ret) (reset! ret c)))) ;; update state pass (let [queue (-get-queue state)] (-empty-queue! state) (when-not (empty? queue) (doseq [c queue] (when (.isMounted c) (when-let [next-props (aget (.-state c) "__om_next_cursor")] (aset (.-props c) "__om_cursor" next-props) (aset (.-state c) "__om_next_cursor" nil)) (when (or (not (satisfies? ICheckState (children c))) (.shouldComponentUpdate c (.-props c) (.-state c))) (.forceUpdate c)))))) ;; ref cursor pass (let [_refs @_refs] (when-not (empty? _refs) (doseq [[path cs] _refs] (let [cs @cs] (doseq [[id c] cs] (when (.shouldComponentUpdate c (.-props c) (.-state c)) (.forceUpdate c))))))) @ret))] (add-watch state watch-key (fn [_ _ o n] (when (and (not (-get-property state watch-key :ignore)) (not (identical? o n))) (-set-property! state watch-key :skip-render-root false)) (-set-property! state watch-key :ignore false) (when-not (contains? @refresh-set rootf) (swap! refresh-set conj rootf)) (when-not refresh-queued (set! refresh-queued true) (cond (fn? raf) (raf) (or (false? raf) (not (exists? js/requestAnimationFrame))) (js/setTimeout #(render-all state) 16) :else (js/requestAnimationFrame #(render-all state)))))) ;; store fn to remove previous root render loop (swap! roots assoc target (fn [] (-remove-properties! state watch-key) (remove-watch state watch-key) (tear-down state watch-key) (swap! refresh-set disj rootf) (swap! roots dissoc target) (js/React.unmountComponentAtNode target))) (rootf)))) (defn detach-root "Given a DOM target remove its render loop if one exists." [target] {:pre [(gdom/isElement target)]} (when-let [f (get @roots target)] (f))) (defn transactable? [x] (satisfies? ITransact x)) (defn transact! "Given a tag, a cursor, an optional list of keys ks, mutate the tree at the path specified by the cursor + the optional keys by applying f to the specified value in the tree. An Om re-render will be triggered." ([cursor f] (transact! cursor [] f nil)) ([cursor korks f] (transact! cursor korks f nil)) ([cursor korks f tag] {:pre [(transactable? cursor) (ifn? f)]} (let [korks (cond (nil? korks) [] (sequential? korks) korks :else [korks])] (-transact! cursor korks f tag)))) (defn update! "Like transact! but no function provided, instead a replacement value is given." ([cursor v] {:pre [(cursor? cursor)]} (transact! cursor [] (fn [_] v) nil)) ([cursor korks v] {:pre [(cursor? cursor)]} (transact! cursor korks (fn [_] v) nil)) ([cursor korks v tag] {:pre [(cursor? cursor)]} (transact! cursor korks (fn [_] v) tag))) (defn commit! "EXPERIMENTAL: Like transact! but does not schedule a re-render or create a transact event." [cursor korks f] {:pre [(cursor? cursor) (ifn? f)]} (let [key (when (satisfies? IRootKey cursor) (-root-key cursor)) app-state (state cursor) korks (cond (nil? korks) [] (sequential? korks) korks :else [korks]) cpath (path cursor) rpath (into cpath korks)] (when key (-set-property! app-state key :ignore true)) (if (empty? rpath) (swap! app-state f) (swap! app-state update-in rpath f)))) (defn get-node "A helper function to get at React DOM refs. Given a owning pure node extract the DOM ref specified by name." ([owner] (.getDOMNode owner)) ([owner name] {:pre [(string? name)]} (some-> (.-refs owner) (aget name) (.getDOMNode)))) (defn get-ref "A helper function to get at React refs. Given an owning pure node extract the ref specified by name." [owner name] {:pre [(component? owner) (string? name)]} (some-> (.-refs owner) (gobj/get name))) (defn mounted? "Return true if the backing React component is mounted into the DOM." [owner] (.isMounted owner)) (defn set-state! "Takes a pure owning component, a sequential list of keys and value and sets the state of the component. Conceptually analagous to React setState. Will schedule an Om re-render." ([owner v] {:pre [(component? owner)]} (-set-state! owner v true)) ([owner korks v] {:pre [(component? owner)]} (let [ks (if (sequential? korks) korks [korks])] (-set-state! owner ks v true)))) (defn set-state-nr! "EXPERIMENTAL: Same as set-state! but does not trigger re-render." ([owner v] {:pre [(component? owner)]} (-set-state! owner v false)) ([owner korks v] {:pre [(component? owner)]} (let [ks (if (sequential? korks) korks [korks])] (-set-state! owner ks v false)))) (defn update-state! "Takes a pure owning component, a sequential list of keys and a function to transition the state of the component. Conceptually analagous to React setState. Will schedule an Om re-render." ([owner f] {:pre [(component? owner) (ifn? f)]} (set-state! owner (f (get-state owner)))) ([owner korks f] {:pre [(component? owner) (ifn? f)]} (set-state! owner korks (f (get-state owner korks))))) (defn update-state-nr! "EXPERIMENTAL: Same as update-state! but does not trigger re-render." ([owner f] {:pre [(component? owner) (ifn? f)]} (set-state-nr! owner (f (get-state owner)))) ([owner korks f] {:pre [(component? owner) (ifn? f)]} (set-state-nr! owner korks (f (get-state owner korks))))) (defn refresh! "Utility to re-render an owner." [owner] {:pre [(component? owner)]} (update-state! owner identity)) (defn get-render-state "Takes a pure owning component and an optional key or sequential list of keys and returns a property in the component local state if it exists. Always returns the rendered state, not the pending state." ([owner] {:pre [(component? owner)]} (-get-render-state owner)) ([owner korks] {:pre [(component? owner)]} (let [ks (if (sequential? korks) korks [korks])] (-get-render-state owner ks))))
[ { "context": "(is (= 7 (count users)))\n (is (= {:id 1 :name \"Albin Jaye\"}\n (first users))))\n (let [playlists (", "end": 295, "score": 0.9998838305473328, "start": 285, "tag": "NAME", "value": "Albin Jaye" }, { "context": " songs)))\n (is (= {:id 15\n :artist \"Kendrick Lamar\"\n :title \"All The Stars\"}\n a", "end": 759, "score": 0.9998273849487305, "start": 745, "tag": "NAME", "value": "Kendrick Lamar" } ]
test/scaudill/mixtape/parse_test.clj
voxdolo/mixtape
0
(ns scaudill.mixtape.parse-test (:require [clojure.test :refer :all] [scaudill.mixtape.parse :as parse])) (def json (parse/parse "resources/mixtape.json")) (deftest general-parsing-test (let [users (:users json)] (is (= 7 (count users))) (is (= {:id 1 :name "Albin Jaye"} (first users)))) (let [playlists (get json :playlists) playlist {:user_id 3 :song_ids [3 12 15]}] (is (= 3 (count playlists))) (is (= {:id 1 :user_id 2 :song_ids [8 32]} (first playlists)))) (let [songs (:songs json) all-the-stars (first (filter (fn [{:keys [id]}] (= id 15)) songs))] (is (= 40 (count songs))) (is (= {:id 15 :artist "Kendrick Lamar" :title "All The Stars"} all-the-stars))))
98138
(ns scaudill.mixtape.parse-test (:require [clojure.test :refer :all] [scaudill.mixtape.parse :as parse])) (def json (parse/parse "resources/mixtape.json")) (deftest general-parsing-test (let [users (:users json)] (is (= 7 (count users))) (is (= {:id 1 :name "<NAME>"} (first users)))) (let [playlists (get json :playlists) playlist {:user_id 3 :song_ids [3 12 15]}] (is (= 3 (count playlists))) (is (= {:id 1 :user_id 2 :song_ids [8 32]} (first playlists)))) (let [songs (:songs json) all-the-stars (first (filter (fn [{:keys [id]}] (= id 15)) songs))] (is (= 40 (count songs))) (is (= {:id 15 :artist "<NAME>" :title "All The Stars"} all-the-stars))))
true
(ns scaudill.mixtape.parse-test (:require [clojure.test :refer :all] [scaudill.mixtape.parse :as parse])) (def json (parse/parse "resources/mixtape.json")) (deftest general-parsing-test (let [users (:users json)] (is (= 7 (count users))) (is (= {:id 1 :name "PI:NAME:<NAME>END_PI"} (first users)))) (let [playlists (get json :playlists) playlist {:user_id 3 :song_ids [3 12 15]}] (is (= 3 (count playlists))) (is (= {:id 1 :user_id 2 :song_ids [8 32]} (first playlists)))) (let [songs (:songs json) all-the-stars (first (filter (fn [{:keys [id]}] (= id 15)) songs))] (is (= 40 (count songs))) (is (= {:id 15 :artist "PI:NAME:<NAME>END_PI" :title "All The Stars"} all-the-stars))))
[ { "context": "odified from potemkin, v0.4.3 (https://github.com/ztellman/potemkin), MIT licnensed, Copyright Zachary Tellm", "end": 73, "score": 0.9958565831184387, "start": 65, "tag": "USERNAME", "value": "ztellman" }, { "context": "b.com/ztellman/potemkin), MIT licnensed, Copyright Zachary Tellman\n;; Changes:\n;; - fast-memoize removed\n\n(ns ^:no-d", "end": 125, "score": 0.9998863935470581, "start": 110, "tag": "NAME", "value": "Zachary Tellman" } ]
web/src/from/potemkin.clj
Elknar/immutant
275
;; Copied and modified from potemkin, v0.4.3 (https://github.com/ztellman/potemkin), MIT licnensed, Copyright Zachary Tellman ;; Changes: ;; - fast-memoize removed (ns ^:no-doc from.potemkin (:require [from.potemkin namespaces types collections macros utils])) (from.potemkin.namespaces/import-vars from.potemkin.namespaces/import-vars) ;; totally meta (import-vars [from.potemkin.namespaces import-fn import-macro import-def] [from.potemkin.macros unify-gensyms normalize-gensyms equivalent?] [from.potemkin.utils condp-case try* fast-bound-fn fast-bound-fn* doit doary] [from.potemkin.types def-abstract-type reify+ defprotocol+ deftype+ defrecord+ definterface+ extend-protocol+] [from.potemkin.collections reify-map-type def-derived-map def-map-type])
3885
;; Copied and modified from potemkin, v0.4.3 (https://github.com/ztellman/potemkin), MIT licnensed, Copyright <NAME> ;; Changes: ;; - fast-memoize removed (ns ^:no-doc from.potemkin (:require [from.potemkin namespaces types collections macros utils])) (from.potemkin.namespaces/import-vars from.potemkin.namespaces/import-vars) ;; totally meta (import-vars [from.potemkin.namespaces import-fn import-macro import-def] [from.potemkin.macros unify-gensyms normalize-gensyms equivalent?] [from.potemkin.utils condp-case try* fast-bound-fn fast-bound-fn* doit doary] [from.potemkin.types def-abstract-type reify+ defprotocol+ deftype+ defrecord+ definterface+ extend-protocol+] [from.potemkin.collections reify-map-type def-derived-map def-map-type])
true
;; Copied and modified from potemkin, v0.4.3 (https://github.com/ztellman/potemkin), MIT licnensed, Copyright PI:NAME:<NAME>END_PI ;; Changes: ;; - fast-memoize removed (ns ^:no-doc from.potemkin (:require [from.potemkin namespaces types collections macros utils])) (from.potemkin.namespaces/import-vars from.potemkin.namespaces/import-vars) ;; totally meta (import-vars [from.potemkin.namespaces import-fn import-macro import-def] [from.potemkin.macros unify-gensyms normalize-gensyms equivalent?] [from.potemkin.utils condp-case try* fast-bound-fn fast-bound-fn* doit doary] [from.potemkin.types def-abstract-type reify+ defprotocol+ deftype+ defrecord+ definterface+ extend-protocol+] [from.potemkin.collections reify-map-type def-derived-map def-map-type])
[ { "context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"Kristina Lisa Klinkner, John Alan McDonald\" :date \"2016-12-22\"\n :do", "end": 109, "score": 0.9998852014541626, "start": 87, "tag": "NAME", "value": "Kristina Lisa Klinkner" }, { "context": "n-on-boxed)\n(ns ^{:author \"Kristina Lisa Klinkner, John Alan McDonald\" :date \"2016-12-22\"\n :doc \"Iris data classif", "end": 129, "score": 0.9998775124549866, "start": 111, "tag": "NAME", "value": "John Alan McDonald" } ]
src/test/clojure/taiga/test/classify/iris/tree.clj
wahpenayo/taiga
4
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "Kristina Lisa Klinkner, John Alan McDonald" :date "2016-12-22" :doc "Iris data classification 1-tree forest example." } taiga.test.classify.iris.tree (:require [clojure.test :as test] [zana.api :as z] [taiga.api :as taiga] [taiga.test.tree :as tree] [taiga.test.classify.data.defs :as defs] [taiga.test.classify.iris.record :as record] [taiga.test.classify.iris.iris :as iris])) ;; mvn -Dtest=taiga.test.classify.iris.tree clojure:test ;;------------------------------------------------------------------------------ (def nss (str *ns*)) (test/deftest iris-classification-tree (z/reset-mersenne-twister-seeds) (let [options (iris/options) options (assoc options :nterms 1) forest (taiga/majority-vote-classifier options) _ (z/mapc #(tree/check-mincount options %) (taiga/terms forest)) y (:ground-truth record/attributes) predictors (into (sorted-map) (dissoc record/attributes :ground-truth :prediction)) yhat (fn yhat ^double [datum] (forest predictors datum))] (defs/serialization-test nss options forest) (test/is (= (mapv taiga/node-height (taiga/terms forest)) [6])) (test/is (= (mapv taiga/count-children (taiga/terms forest)) [15])) (test/is (= (mapv taiga/count-leaves (taiga/terms forest)) [8])) (test/is (= [50 1 0 49] (defs/print-confusion y yhat (:data options)))))) ;------------------------------------------------------------------------------
70089
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "<NAME>, <NAME>" :date "2016-12-22" :doc "Iris data classification 1-tree forest example." } taiga.test.classify.iris.tree (:require [clojure.test :as test] [zana.api :as z] [taiga.api :as taiga] [taiga.test.tree :as tree] [taiga.test.classify.data.defs :as defs] [taiga.test.classify.iris.record :as record] [taiga.test.classify.iris.iris :as iris])) ;; mvn -Dtest=taiga.test.classify.iris.tree clojure:test ;;------------------------------------------------------------------------------ (def nss (str *ns*)) (test/deftest iris-classification-tree (z/reset-mersenne-twister-seeds) (let [options (iris/options) options (assoc options :nterms 1) forest (taiga/majority-vote-classifier options) _ (z/mapc #(tree/check-mincount options %) (taiga/terms forest)) y (:ground-truth record/attributes) predictors (into (sorted-map) (dissoc record/attributes :ground-truth :prediction)) yhat (fn yhat ^double [datum] (forest predictors datum))] (defs/serialization-test nss options forest) (test/is (= (mapv taiga/node-height (taiga/terms forest)) [6])) (test/is (= (mapv taiga/count-children (taiga/terms forest)) [15])) (test/is (= (mapv taiga/count-leaves (taiga/terms forest)) [8])) (test/is (= [50 1 0 49] (defs/print-confusion y yhat (:data options)))))) ;------------------------------------------------------------------------------
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 "2016-12-22" :doc "Iris data classification 1-tree forest example." } taiga.test.classify.iris.tree (:require [clojure.test :as test] [zana.api :as z] [taiga.api :as taiga] [taiga.test.tree :as tree] [taiga.test.classify.data.defs :as defs] [taiga.test.classify.iris.record :as record] [taiga.test.classify.iris.iris :as iris])) ;; mvn -Dtest=taiga.test.classify.iris.tree clojure:test ;;------------------------------------------------------------------------------ (def nss (str *ns*)) (test/deftest iris-classification-tree (z/reset-mersenne-twister-seeds) (let [options (iris/options) options (assoc options :nterms 1) forest (taiga/majority-vote-classifier options) _ (z/mapc #(tree/check-mincount options %) (taiga/terms forest)) y (:ground-truth record/attributes) predictors (into (sorted-map) (dissoc record/attributes :ground-truth :prediction)) yhat (fn yhat ^double [datum] (forest predictors datum))] (defs/serialization-test nss options forest) (test/is (= (mapv taiga/node-height (taiga/terms forest)) [6])) (test/is (= (mapv taiga/count-children (taiga/terms forest)) [15])) (test/is (= (mapv taiga/count-leaves (taiga/terms forest)) [8])) (test/is (= [50 1 0 49] (defs/print-confusion y yhat (:data options)))))) ;------------------------------------------------------------------------------
[ { "context": "il was actually sent\"))]\n (let [manager-email \"manager@bar.com\"\n manager-password \"manager\"\n m", "end": 5495, "score": 0.9999130964279175, "start": 5480, "tag": "EMAIL", "value": "manager@bar.com" }, { "context": "ail \"manager@bar.com\"\n manager-password \"manager\"\n manager-name \"Manager\"\n ;; re", "end": 5532, "score": 0.9995930790901184, "start": 5525, "tag": "PASSWORD", "value": "manager" }, { "context": "anager-password \"manager\"\n manager-name \"Manager\"\n ;; register a manager\n _ (log", "end": 5565, "score": 0.8961118459701538, "start": 5558, "tag": "NAME", "value": "Manager" }, { "context": "\n :password manager-password\n :name man", "end": 5732, "score": 0.9087297916412354, "start": 5716, "tag": "PASSWORD", "value": "manager-password" }, { "context": " :password manager-password}})\n manager-user-id (cookies/ge", "end": 6465, "score": 0.8686145544052124, "start": 6458, "tag": "PASSWORD", "value": "manager" }, { "context": " ;; child account\n child-email \"james@purpleapp.com\"\n child-password \"child\"\n child", "end": 6700, "score": 0.9999076724052429, "start": 6681, "tag": "EMAIL", "value": "james@purpleapp.com" }, { "context": "l \"james@purpleapp.com\"\n child-password \"child\"\n child-name \"Foo Bar\"\n _ (logi", "end": 6733, "score": 0.9986514449119568, "start": 6728, "tag": "PASSWORD", "value": "child" }, { "context": "-name \"BaxQux.com\")\n second-child-email \"baz@bar.com\"\n second-child-name \"Baz Bar\"\n ", "end": 7809, "score": 0.9999133944511414, "start": 7798, "tag": "EMAIL", "value": "baz@bar.com" }, { "context": " ;; A regular user\n user-email \"baz@qux.com\"\n user-password \"bazqux\"\n user-", "end": 7910, "score": 0.9999182820320129, "start": 7899, "tag": "EMAIL", "value": "baz@qux.com" }, { "context": "user-email \"baz@qux.com\"\n user-password \"bazqux\"\n user-name \"Baz Qux\"\n _ (login", "end": 7943, "score": 0.9995226860046387, "start": 7937, "tag": "PASSWORD", "value": "bazqux" }, { "context": " user-password \"bazqux\"\n user-name \"Baz Qux\"\n _ (login-test/register-user! {:platfor", "end": 7973, "score": 0.9938468933105469, "start": 7966, "tag": "NAME", "value": "Baz Qux" }, { "context": "\n :password user-password\n :name use", "end": 8102, "score": 0.8548244833946228, "start": 8089, "tag": "PASSWORD", "value": "user-password" }, { "context": "l\n :password user-password}})\n user-auth-cookie (cookies/auth-cooki", "end": 8493, "score": 0.5295984745025635, "start": 8485, "tag": "PASSWORD", "value": "password" }, { "context": "test selenium-account-user\n (let [manager-email \"manager@bar.com\"\n manager-password \"manager\"\n manag", "end": 43254, "score": 0.9999102354049683, "start": 43239, "tag": "EMAIL", "value": "manager@bar.com" }, { "context": "email \"manager@bar.com\"\n manager-password \"manager\"\n manager-name \"Manager\"\n ;; regist", "end": 43289, "score": 0.9994673132896423, "start": 43282, "tag": "PASSWORD", "value": "manager" }, { "context": " manager-password \"manager\"\n manager-name \"Manager\"\n ;; register a manager\n _ (login-t", "end": 43320, "score": 0.5575370788574219, "start": 43313, "tag": "NAME", "value": "Manager" }, { "context": "il\n :password manager-password\n :na", "end": 43472, "score": 0.7024301290512085, "start": 43465, "tag": "PASSWORD", "value": "manager" }, { "context": "t))\n ;; child account\n child-email \"james@purpleapp.com\"\n child-password \"child\"\n child-nam", "end": 44020, "score": 0.9999169111251831, "start": 44001, "tag": "EMAIL", "value": "james@purpleapp.com" }, { "context": "ail \"james@purpleapp.com\"\n child-password \"child\"\n child-name \"Foo Bar\"\n ;; child ac", "end": 44051, "score": 0.9994625449180603, "start": 44046, "tag": "PASSWORD", "value": "child" }, { "context": " ;; child account 2\n second-child-email \"baz@bar.com\"\n second-child-name \"Baz Bar\"\n ;; c", "end": 44148, "score": 0.9999102354049683, "start": 44137, "tag": "EMAIL", "value": "baz@bar.com" }, { "context": " ;; child account 3\n third-child-email \"qux@quux.com\"\n third-child-name \"Qux Quux\"\n thir", "end": 44252, "score": 0.9959576725959778, "start": 44240, "tag": "EMAIL", "value": "qux@quux.com" }, { "context": "ld-email \"qux@quux.com\"\n third-child-name \"Qux Quux\"\n third-child-number \"800-555-1212\"\n ", "end": 44288, "score": 0.9424594640731812, "start": 44280, "tag": "NAME", "value": "Qux Quux" }, { "context": "m\")\n ;; A regular user\n user-email \"baz@qux.com\"\n user-password \"bazqux\"\n user-name", "end": 44475, "score": 0.9999266266822815, "start": 44464, "tag": "EMAIL", "value": "baz@qux.com" }, { "context": " user-email \"baz@qux.com\"\n user-password \"bazqux\"\n user-name \"Baz Qux\"\n ;; vehicles\n", "end": 44506, "score": 0.9993260502815247, "start": 44500, "tag": "PASSWORD", "value": "bazqux" }, { "context": " user-password \"bazqux\"\n user-name \"Baz Qux\"\n ;; vehicles\n manager-vehicle {:ma", "end": 44534, "score": 0.9859026670455933, "start": 44527, "tag": "NAME", "value": "Baz Qux" }, { "context": " (is (= (user-map->user-str\n {:name manager-name\n :email manager-email\n ", "end": 46215, "score": 0.4844333827495575, "start": 46208, "tag": "NAME", "value": "manager" }, { "context": "cle\n :user \"Foo Bar\"))\n (click portal/vehicle-form-save)\n (", "end": 51745, "score": 0.64190673828125, "start": 51738, "tag": "NAME", "value": "Foo Bar" }, { "context": " second-child-vehicle\n :user \"Foo Bar\"))\n (portal/vehicle-table-row->vehicl", "end": 52075, "score": 0.6705133318901062, "start": 52068, "tag": "NAME", "value": "Foo Bar" }, { "context": "eset_key \"\"\n :password_hash (bcrypt/encrypt child-password)}\n {:i", "end": 52499, "score": 0.8215703368186951, "start": 52493, "tag": "PASSWORD", "value": "bcrypt" }, { "context": " :password_hash (bcrypt/encrypt child-password)}\n {:id (:id (login/", "end": 52513, "score": 0.9695160984992981, "start": 52508, "tag": "PASSWORD", "value": "child" }, { "context": " :password_hash (bcrypt/encrypt child-password)}\n {:id (:id (login/get-user-", "end": 52522, "score": 0.699668288230896, "start": 52514, "tag": "PASSWORD", "value": "password" }, { "context": "eset_key \"\"\n :password_hash (bcrypt/encrypt child-password)}\n {:i", "end": 55436, "score": 0.9240418076515198, "start": 55430, "tag": "PASSWORD", "value": "bcrypt" }, { "context": " :password_hash (bcrypt/encrypt child-password)}\n {:id (:id (login/get-user-", "end": 55459, "score": 0.7467665076255798, "start": 55445, "tag": "PASSWORD", "value": "child-password" }, { "context": "eset_key \"\"\n :password_hash (bcrypt/encrypt child-password)}\n {:i", "end": 56023, "score": 0.9037621021270752, "start": 56017, "tag": "PASSWORD", "value": "bcrypt" }, { "context": " :password_hash (bcrypt/encrypt child-password)}\n {:id (:id (login/get-user-", "end": 56046, "score": 0.7760267853736877, "start": 56032, "tag": "PASSWORD", "value": "child-password" }, { "context": "ull-name)\n (input-text users-form-full-name \"Qux Quxxer\")\n (click users-form-save)\n (wait-until", "end": 57845, "score": 0.9998197555541992, "start": 57835, "tag": "NAME", "value": "Qux Quxxer" }, { "context": "ild-email\n {:name \"Qux Quxxer\"\n :email third-ch", "end": 58099, "score": 0.9996792674064636, "start": 58089, "tag": "NAME", "value": "Qux Quxxer" }, { "context": "ompare-user-row-and-map third-child-email {:name \"Qux Quxxer\"\n ", "end": 58734, "score": 0.998702883720398, "start": 58724, "tag": "NAME", "value": "Qux Quxxer" }, { "context": "ull-name)\n (input-text users-form-full-name \"Qux Quxx\")\n (clear users-form-phone-number)\n (in", "end": 59196, "score": 0.9971563816070557, "start": 59188, "tag": "NAME", "value": "Qux Quxx" }, { "context": "ompare-user-row-and-map third-child-email {:name \"Qux Quxx\"\n ", "end": 59512, "score": 0.9986624121665955, "start": 59504, "tag": "NAME", "value": "Qux Quxx" }, { "context": "ompare-user-row-and-map third-child-email {:name \"Qux Quxx\"\n ", "end": 60715, "score": 0.99227374792099, "start": 60707, "tag": "NAME", "value": "Qux Quxx" } ]
test/portal/functional/test/accounts.clj
Purple-Services/portal-service
4
(ns portal.functional.test.accounts (:require [crypto.password.bcrypt :as bcrypt] [clj-time.format :as t] [clj-webdriver.taxi :refer :all] [clojure.edn :as edn] [clojure.string :as string] [clojure.test :refer [deftest is testing use-fixtures]] [common.db :as db] [common.util :as util] [portal.accounts :as accounts] [portal.functional.test.cookies :as cookies] [portal.functional.test.orders :as test-orders] [portal.functional.test.portal :as portal] [portal.functional.test.selenium :as selenium] [portal.functional.test.vehicles :as test-vehicles] [portal.test.db-tools :refer [setup-ebdb-test-pool! setup-ebdb-test-for-conn-fixture clear-and-populate-test-database clear-and-populate-test-database-fixture reset-db!]] [portal.login :as login] [portal.test.login-test :as login-test] [portal.test.utils :as test-utils] [portal.users :as users] [portal.vehicles :as vehicles])) ;; for manual testing: ;; (selenium/startup-test-env!) ; make sure profiles.clj was loaded with ;; ; :base-url "http:localhost:5744/" ;; or if you are going to be doing ring mock tests ;; (setup-ebdb-test-pool!) ;; -- run tests -- ;; (reset-db!) ; note: most tests will need this run between them anyhow ;; -- run more tests ;; (selenium/shutdown-test-env! (use-fixtures :once selenium/with-server selenium/with-browser selenium/with-redefs-fixture setup-ebdb-test-for-conn-fixture) (use-fixtures :each clear-and-populate-test-database-fixture) ;; simplified routes (defn account-manager-context-uri [account-id manager-id] (str "/account/" account-id "/manager/" manager-id)) (defn add-user-uri [account-id manager-id] (str (account-manager-context-uri account-id manager-id) "/add-user")) (defn account-users-uri [account-id manager-id] (str (account-manager-context-uri account-id manager-id) "/users")) (defn manager-get-user-uri [account-id manager-id user-id] (str (account-manager-context-uri account-id manager-id) "/user/" user-id)) (defn manager-get-vehicle-uri [account-id manager-id vehicle-id] (str (account-manager-context-uri account-id manager-id) "/vehicle/" vehicle-id)) (defn user-vehicle-uri [user-id vehicle-id] (str "/user/" user-id "/vehicle/" vehicle-id)) (defn user-vehicles-uri [user-id] (str "/user/" user-id "/vehicles")) (defn user-orders-uri [user-id] (str "/user/" user-id "/orders")) (defn user-add-vehicle-uri [user-id] (str "/user/" user-id "/add-vehicle")) (defn user-edit-vehicle-uri [user-id] (str "/user/" user-id "/edit-vehicle")) (defn manager-vehicle-uri [account-id manager-id vehicle-id] (str (account-manager-context-uri account-id manager-id) "/vehicle/" vehicle-id)) (defn manager-add-vehicle-uri [account-id manager-id] (str (account-manager-context-uri account-id manager-id) "/add-vehicle")) (defn manager-edit-vehicle-uri [account-id manager-id] (str (account-manager-context-uri account-id manager-id) "/edit-vehicle")) (defn manager-edit-user-uri [account-id manager-id] (str (account-manager-context-uri account-id manager-id) "/edit-user")) (defn manager-vehicles-uri [account-id manager-id] (str (account-manager-context-uri account-id manager-id) "/vehicles")) (defn manager-orders-uri [account-id manager-id] (str (account-manager-context-uri account-id manager-id) "/orders")) ;; common elements (def users-link {:xpath "//li/a/div[text()='USERS']"}) (def add-users-button {:xpath "//div[@id='users']//button[text()=' Add']"}) (def users-form-email-address {:xpath "//div[@id='users']//form//input[@placeholder='Email Address']"}) (def users-form-full-name {:xpath "//div[@id='users']//form//input[contains(@placeholder,'Full Name')]"}) (def users-form-phone-number {:xpath "//div[@id='users']//form//input[contains(@placeholder,'Phone Number')]"}) (def users-form-save {:xpath "//div[@id='users']//form//button[text()='Save']"}) (def users-form-dismiss {:xpath "//div[@id='users']//form//button[text()='Dismiss']"}) (def users-form-yes {:xpath "//div[@id='users']//form//button[text()='Yes']"}) (def users-form-no {:xpath "//div[@id='users']//form//button[text()='No']"}) (def users-pending-tab {:xpath "//div[@id='users']//button[contains(text(),'Pending')]"}) (def users-active-tab {:xpath "//div[@id='users']//button[contains(text(),'Active')]"}) (def users-table {:xpath "//div[@id='users']//table"}) (def active-users-filter {:xpath "//div[@id='users']//button[contains(text(),'Active')]"}) (def deactivated-users-filter {:xpath "//div[@id='users']//button[contains(text(),'Deactivated')]"}) (def pending-users-filter {:xpath "//div[@id='users']//button[contains(text(),'Pending')]"}) (def users-refresh-button {:xpath "//div[@id='users']//button/i[contains(@class,'fa-refresh')]"}) (deftest ok-route (is (-> (test-utils/get-uri-json :get "/ok") (get-in [:body :success])))) (deftest account-managers-security (with-redefs [common.sendgrid/send-template-email (fn [to subject message & {:keys [from template-id substitutions]}] (println "No reset password email was actually sent"))] (let [manager-email "manager@bar.com" manager-password "manager" manager-name "Manager" ;; register a manager _ (login-test/register-user! {:platform-id manager-email :password manager-password :name manager-name}) manager (login/get-user-by-email manager-email) account-name "FooBar.com" ;; register an account _ (accounts/create-account! account-name) ;; retrieve the account account (accounts/get-account-by-name account-name) account-id (:id account) ;; associate manager with account _ (accounts/associate-account-manager! (:id manager) (:id account)) manager-login-response (test-utils/get-uri-json :post "/login" {:json-body {:email manager-email :password manager-password}}) manager-user-id (cookies/get-cookie-user-id manager-login-response) manager-auth-cookie (cookies/auth-cookie manager-login-response) ;; child account child-email "james@purpleapp.com" child-password "child" child-name "Foo Bar" _ (login-test/register-user! {:platform-id child-email :password child-password :name child-name}) child (login/get-user-by-email child-email) ;; associate child-account with account _ (accounts/associate-child-account! (:id child) (:id account)) ;; generate auth-cokkie child-login-response (test-utils/get-uri-json :post "/login" {:json-body {:email child-email :password child-password}}) child-user-id (cookies/get-cookie-user-id child-login-response) child-auth-cookie (cookies/auth-cookie child-login-response) ;; register another account _ (accounts/create-account! "BazQux.com") ;; retrieve the account another-account (accounts/get-account-by-name "BaxQux.com") second-child-email "baz@bar.com" second-child-name "Baz Bar" ;; A regular user user-email "baz@qux.com" user-password "bazqux" user-name "Baz Qux" _ (login-test/register-user! {:platform-id user-email :password user-password :name user-name}) user (login/get-user-by-email user-email) user-id (:id user) user-login-response (test-utils/get-uri-json :post "/login" {:json-body {:email user-email :password user-password}}) user-auth-cookie (cookies/auth-cookie user-login-response)] (testing "Only account managers can add and edit users" ;; child user can't add a user (is (= 403 (-> (test-utils/get-uri-json :post (add-user-uri account-id child-user-id) {:json-body {:email second-child-email :name second-child-name} :headers child-auth-cookie}) (get-in [:status])))) ;; a child user can't edit a user (is (= 403 (-> (test-utils/get-uri-json :put (manager-edit-user-uri account-id child-user-id) {:json-body {:email second-child-email :name second-child-name :id child-user-id} :headers child-auth-cookie}) (get-in [:status])))) ;; a regular user can't add a user to another account (is (= 403 (-> (test-utils/get-uri-json :post (add-user-uri account-id user-id) {:json-body {:email second-child-email :name second-child-name} :headers user-auth-cookie}) (get-in [:status])))) ;; a regular user can't edit a user of an account (is (= 403 (-> (test-utils/get-uri-json :put (manager-edit-user-uri account-id user-id) {:json-body {:email second-child-email :name second-child-name :id child-user-id} :headers user-auth-cookie}) (get-in [:status])))) ;; account manager can add a user (is (-> (test-utils/get-uri-json :post (add-user-uri account-id manager-user-id) {:json-body {:email second-child-email :name second-child-name} :headers manager-auth-cookie}) (get-in [:body :success]))) ;; account manager can edit a user (is (-> (test-utils/get-uri-json :put (manager-edit-user-uri account-id manager-user-id) {:json-body {:email child-email :name child-name :id child-user-id :active true} :headers manager-auth-cookie}) (get-in [:body :success]))) (testing "Users can't see other users" ;; can't see their parent account's users (is (= 403 (-> (test-utils/get-uri-json :get (account-users-uri account-id child-user-id) {:headers child-auth-cookie}) (get-in [:status])))) ;; can't see another child account user (is (= 403 (-> (test-utils/get-uri-json :get (manager-get-user-uri account-id child-user-id (:id (login/get-user-by-email second-child-email))) {:headers child-auth-cookie}) (get-in [:status])))) ;; can't see manager account user (is (= 403 (-> (test-utils/get-uri-json :get (manager-get-user-uri account-id child-user-id manager-user-id) {:headers child-auth-cookie}) (get-in [:status])))) ;; ...but the manager can see the child account user (is (= child-user-id (-> (test-utils/get-uri-json :get (manager-get-user-uri account-id manager-user-id child-user-id) {:headers manager-auth-cookie}) (get-in [:body :id])))) ;; manager can't see a user not associated with their account (is (= 403 (-> (test-utils/get-uri-json :get (manager-get-user-uri account-id manager-user-id user-id) {:headers manager-auth-cookie}) (get-in [:status]))))) (let [;; manager vehicles _ (test-vehicles/create-vehicle! (test-vehicles/vehicle-map {}) {:id manager-user-id}) manager-vehicles (vehicles/user-vehicles manager-user-id) manager-vehicle (first manager-vehicles) manager-vehicle-id (:id manager-vehicle) _ (test-vehicles/create-vehicle! (test-vehicles/vehicle-map {:color "red" :year "2006"}) {:id manager-user-id}) ;; child vehicle _ (test-vehicles/create-vehicle! (test-vehicles/vehicle-map {:make "Honda" :model "Accord" :color "Silver"}) {:id child-user-id}) child-vehicles (vehicles/user-vehicles child-user-id) child-vehicle (first child-vehicles) child-vehicle-id (:id child-vehicle) ;; second child vehicle second-child-user-id (:id (login/get-user-by-email second-child-email)) _ (test-vehicles/create-vehicle! (test-vehicles/vehicle-map {:make "Hyundai" :model "Sonota" :color "Orange"}) {:id second-child-user-id}) second-child-vehicles (vehicles/user-vehicles second-child-user-id) second-child-vehicle (first second-child-vehicles) second-child-vehicle-id (:id second-child-vehicle) ;; user-vehicle _ (test-vehicles/create-vehicle! (test-vehicles/vehicle-map {:make "BMW" :model "i8" :color "Blue"}) {:id user-id}) user-vehicles (vehicles/user-vehicles user-id) user-vehicle (first user-vehicles) user-vehicle-id (:id user-vehicle)] (testing "Only account managers can see all vehicles" ;; manager sees all vehicles (is (= 4 (-> (test-utils/get-uri-json :get (manager-vehicles-uri account-id manager-user-id) {:headers manager-auth-cookie}) (get-in [:body]) (count)))) ;; child can not (is (= 403 (-> (test-utils/get-uri-json :get (manager-vehicles-uri account-id child-user-id) {:headers child-auth-cookie}) (get-in [:status]))))) (testing "Child accounts can only see their own vehicles" ;; child account only sees their own vehicle (is (= 1 (-> (test-utils/get-uri-json :get (user-vehicles-uri child-user-id) {:headers child-auth-cookie}) (get-in [:body]) (count)))) ;; child can't see account vehicles (is (= 403 (-> (test-utils/get-uri-json :get (manager-vehicles-uri account-id child-user-id) {:headers child-auth-cookie}) (get-in [:status])))) ;; user can retrieve their own vehicle (is (= user-vehicle-id (-> (test-utils/get-uri-json :get (user-vehicle-uri user-id user-vehicle-id) {:headers user-auth-cookie}) (get-in [:body :id])))) ;; manager can see another vehicle associated with account (is (= child-vehicle-id) (-> (test-utils/get-uri-json :get (manager-vehicle-uri account-id manager-user-id child-vehicle-id) {:headers manager-auth-cookie}) (get-in [:body :id])))) (testing "Users can't see other user's vehicles" ;; a child user can't view another child user's vehicles (is (= 403 (-> (test-utils/get-uri-json :get (user-vehicle-uri child-user-id second-child-vehicle-id) {:headers child-auth-cookie}) (get-in [:status])))) ;; child user can't view a regular user's vehicles (is (= 403 (-> (test-utils/get-uri-json :get (user-vehicle-uri child-user-id user-vehicle-id) {:headers child-auth-cookie}) (get-in [:status])))) ;; regular user not associated with account can't view another ;; user's vehicle (is (= 403 (-> (test-utils/get-uri-json :get (user-vehicle-uri user-id child-vehicle-id) {:headers user-auth-cookie}) (get-in [:status])))) ;; account managers can't view vehicles that aren't associated ;; with their account (is (= 403 (-> (test-utils/get-uri-json :get (manager-vehicle-uri account-id manager-user-id user-vehicle-id) {:headers manager-auth-cookie}) (get-in [:status])))) (testing "Adding and editing vehicles test" ;; a regular user can add a vehicle (is (-> (test-utils/get-uri-json :post (user-add-vehicle-uri user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "BMW" :model "i8" :color "Red" :user_id user-id}) :id) :headers user-auth-cookie}) (get-in [:body :success]))) ;; a regular user can edit their own vehicle (is (-> (test-utils/get-uri-json :put (user-edit-vehicle-uri user-id) {:json-body (assoc user-vehicle :color "Black") :headers user-auth-cookie}) (get-in [:body :success]))) ;; a regular user can't add a vehicle to ;; another user-id (is (= 403 (-> (test-utils/get-uri-json :post (user-add-vehicle-uri user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "BMW" :model "i8" :color "Red" :user_id child-user-id}) :id) :headers user-auth-cookie}) (get-in [:status])))) ;; a regular user can't edit a vehicle of ;; another user-id (is (= 403 (-> (test-utils/get-uri-json :put (user-edit-vehicle-uri user-id) {:json-body (assoc child-vehicle :color "Green") :headers user-auth-cookie}) (get-in [:status])))) ;; a regular user can't change the user_id to ;; another user (is (= 403 (-> (test-utils/get-uri-json :put (user-edit-vehicle-uri user-id) {:json-body (assoc user-vehicle :user_id manager-user-id) :headers user-auth-cookie}) (get-in [:status])))) ;; a regular user can't add a vehicle to ;; an account (is (= 403 (-> (test-utils/get-uri-json :post (manager-add-vehicle-uri account-id user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "BMW" :model "i8" :color "Red" :user_id user-id}) :id) :headers user-auth-cookie}) (get-in [:status])))) ;; a manager can add a vehicle to an account ;; with their own user-id (is (-> (test-utils/get-uri-json :post (manager-add-vehicle-uri account-id manager-user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "Honda" :model "Civic" :color "Red" :user_id manager-user-id}) :id) :headers manager-auth-cookie}) (get-in [:body :success]))) ;; manager can view their own vehicle (is (= manager-vehicle-id (-> (test-utils/get-uri-json :get (manager-get-vehicle-uri account-id manager-user-id manager-vehicle-id) {:headers manager-auth-cookie}) (get-in [:body :id])))) ;; manager can view child vehicle (is (= child-vehicle-id (-> (test-utils/get-uri-json :get (manager-get-vehicle-uri account-id manager-user-id child-vehicle-id) {:headers manager-auth-cookie}) (get-in [:body :id])))) ;; a manager can add a vehicle to an account ;; with a child-user-id (is (-> (test-utils/get-uri-json :post (manager-add-vehicle-uri account-id manager-user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "Ford" :model "F150" :color "White" :user_id child-user-id}) :id) :headers manager-auth-cookie}) (get-in [:body :success]))) ;; a manager can edit a vehicle associated with an account (is (-> (test-utils/get-uri-json :put (manager-edit-vehicle-uri account-id manager-user-id) {:json-body (assoc child-vehicle :color "White") :headers manager-auth-cookie}) (get-in [:body :success]))) ;; a manager can change the user to themselves (is (-> (test-utils/get-uri-json :put (manager-edit-vehicle-uri account-id manager-user-id) {:json-body (assoc child-vehicle :user_id manager-user-id) :headers manager-auth-cookie}) (get-in [:body :success]))) ;; a manager can change the user to that of a child user (is (-> (test-utils/get-uri-json :put (manager-edit-vehicle-uri account-id manager-user-id) {:json-body (assoc manager-vehicle :user_id child-user-id) :headers manager-auth-cookie}) (get-in [:body :success]))) ;; manager can't change a vehicle user-id to one they ;; don't manage (is (= 403 (-> (test-utils/get-uri-json :put (manager-edit-vehicle-uri account-id manager-user-id) {:json-body (assoc manager-vehicle :user_id user-id) :headers manager-auth-cookie}) (get-in [:status])))) ;; a manager can't add a vehicle to an account ;; for a regular user (is (= 403 (-> (test-utils/get-uri-json :post (manager-add-vehicle-uri account-id manager-user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "BMW" :model "i8" :color "Red" :user_id user-id}) :id) :headers manager-auth-cookie}) (get-in [:status])))) ;; a child user can't add a vehicle to the account (is (= 403 (-> (test-utils/get-uri-json :post (manager-add-vehicle-uri account-id child-user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "Honda" :model "CRV" :color "Beige" :user_id child-vehicle-id}) :id) :headers child-auth-cookie}) (get-in [:status])))) ;; temporary, users should still be allowed to add vehicles ;; a child user can't add a vehicle, period (is (= 403 (-> (test-utils/get-uri-json :post (user-add-vehicle-uri child-user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "BMW" :model "i8" :color "Red" :user_id child-user-id}) :id) :headers child-auth-cookie}) (get-in [:status])))) ;; a child user can't edit a vehicle associated with the account (is (= 403 (-> (test-utils/get-uri-json :put (manager-edit-vehicle-uri account-id child-user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "Honda" :model "CRV" :color "Beige" :user_id child-vehicle-id}) :id) :headers child-auth-cookie}) (get-in [:status])))) ;; temporary, users should still be allowed to edit vehicles ;; a child user can't edit a vehicle, period (is (= 403 (-> (test-utils/get-uri-json :put (user-edit-vehicle-uri child-user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "BMW" :model "i8" :color "Red" :user_id child-user-id}) :id) :headers child-auth-cookie}) (get-in [:status])))))) (let [child-order-1 (test-orders/order-map {:user_id child-user-id :vehicle_id child-vehicle-id}) _ (test-orders/create-order! child-order-1) child-order-2 (test-orders/order-map {:user_id child-user-id :vehicle_id child-vehicle-id}) _ (test-orders/create-order! child-order-2) manager-order-1 (test-orders/order-map {:user_id manager-user-id :vehicle_id manager-vehicle-id}) _ (test-orders/create-order! manager-order-1) manager-order-2 (test-orders/order-map {:user_id manager-user-id :vehicle_id manager-vehicle-id}) _ (test-orders/create-order! manager-order-2) user-order-1 (test-orders/order-map {:user_id user-id :vehicle_id user-vehicle-id}) _ (test-orders/create-order! user-order-1) user-order-2 (test-orders/order-map {:user_id user-id :vehicle_id user-vehicle-id}) _ (test-orders/create-order! user-order-2) user-order-3 (test-orders/order-map {:user_id user-id :vehicle_id user-vehicle-id}) _ (test-orders/create-order! user-order-3)] (testing "Account managers can see all orders" (is (= 4 (-> (test-utils/get-uri-json :get (manager-orders-uri account-id manager-user-id) {:headers manager-auth-cookie}) (get-in [:body]) (count))))) (testing "Regular users can see their own orders" (is (= 3 (-> (test-utils/get-uri-json :get (user-orders-uri user-id) {:headers user-auth-cookie}) (get-in [:body]) (count))))) (testing "Child users can see their own orders" (is (= 2 (-> (test-utils/get-uri-json :get (user-orders-uri child-user-id) {:headers child-auth-cookie}) (get-in [:body]) (count))))) (testing ".. but child users can't see the account orders" (is (= 403 (-> (test-utils/get-uri-json :get (manager-orders-uri account-id child-user-id) {:headers child-auth-cookie}) (get-in [:status]))))) (testing "Regular users can't see orders of other accounts" (is (= 403 (-> (test-utils/get-uri-json :get (manager-orders-uri account-id manager-user-id) {:headers user-auth-cookie}) (get-in [:status]))))))))))) (defn user-creation-date [email] (-> email (login/get-user-by-email) :id (users/get-user) :timestamp_created (util/unix->format (t/formatter "M/d/yyyy")))) (defn user-map->user-str [{:keys [name email phone-number manager? created] :or {created (util/unix->format (util/now-unix) (t/formatter "M/d/yyyy"))}}] (string/join " " (filterv (comp not string/blank?) [name email phone-number (if manager? "Yes" "No") created]))) (defn user-table-row->user-str [email] (let [row-col (fn [col] (str "//div[@id='users']//table/tbody/tr/td[text()='" email "']/parent::tr" "/td[position()=" col "]")) _ (wait-until #(exists? {:xpath (row-col 2)})) _ (wait-until #(= (text {:xpath (row-col 2)}) email)) name (text {:xpath (row-col 1)}) email (text {:xpath (row-col 2)}) phone-number (text {:xpath (row-col 3)}) manager (text {:xpath (row-col 4)}) created (text {:xpath (row-col 5)})] (string/join " " (filterv (comp not string/blank?) [name email phone-number manager created])))) (defn active-users-filter-count [] (edn/read-string (second (re-matches #".*\(([0-9]*)\)" (text active-users-filter))))) (defn deactivated-users-filter-count [] (edn/read-string (second (re-matches #".*\(([0-9]*)\)" (text deactivated-users-filter))))) (defn pending-users-filter-count [] (edn/read-string (second (re-matches #".*\(([0-9]*)\)" (text pending-users-filter))))) (defn users-table-count [] (count (find-elements {:xpath "//div[@id='users']//table/tbody/tr"}))) (defn deactivate-user-at-position [position] (let [deactivate-link {:xpath (str "//div[@id='users']//table/tbody/tr[position()" "=" position "]/td[last()]/div/a[position()=2]")}] (click active-users-filter) (wait-until #(= (active-users-filter-count) (users-table-count))) (wait-until #(exists? deactivate-link)) (click deactivate-link))) (defn activate-user-at-position [position] (let [activate-link {:xpath (str "//div[@id='users']//table/tbody/tr[position()" "=" position "]/td[last()]/div/a[position()=2]")}] (click deactivated-users-filter) (wait-until #(= (deactivated-users-filter-count) (users-table-count))) (wait-until #(exists? activate-link)) (click activate-link))) (defn compare-active-users-table-and-filter-buttons [] (wait-until #(exists? active-users-filter)) (click active-users-filter) (wait-until #(= (active-users-filter-count) (users-table-count))) (is (= (active-users-filter-count) (users-table-count)))) (defn compare-deactivated-users-table-and-filter-buttons [] (wait-until #(exists? deactivated-users-filter)) (click deactivated-users-filter) (wait-until #(= (deactivated-users-filter-count) (users-table-count))) (is (= (deactivated-users-filter-count) (users-table-count)))) (defn count-in-active-users-filter-correct? [n] (wait-until #(= (active-users-filter-count) n)) (is (= n (active-users-filter-count)))) (defn count-in-deactivated-users-filter-correct? [n] (wait-until #(= (deactivated-users-filter-count) n)) (is (= n (deactivated-users-filter-count)))) (defn count-in-pending-users-filter-correct? [n] (wait-until #(= (pending-users-filter-count) n)) (is (= n (pending-users-filter-count)))) (defn deactivate-user-and-check [position new-count] (deactivate-user-at-position position) ;; check that the counts are correct (count-in-active-users-filter-correct? new-count) (compare-active-users-table-and-filter-buttons) (compare-deactivated-users-table-and-filter-buttons)) (defn activate-user-and-check [position new-count] (activate-user-at-position position) ;; check that the counts are correct (count-in-deactivated-users-filter-correct? new-count) (compare-active-users-table-and-filter-buttons) (compare-deactivated-users-table-and-filter-buttons)) (defn create-user [{:keys [email name phone-number]}] (wait-until #(exists? add-users-button)) (click add-users-button) (wait-until #(exists? users-form-email-address)) (clear users-form-email-address) (input-text users-form-email-address email) (clear users-form-full-name) (input-text users-form-full-name name) (clear users-form-phone-number) (input-text users-form-phone-number phone-number) (click users-form-save) (wait-until #(exists? users-form-yes)) (click users-form-yes)) (defn edit-user [email] (wait-until #(exists? {:xpath (str "//div[@id='users']//table/tbody/tr/td[text()='" email "']/parent::tr/td[last()]/div/a[position()=1]")})) (click {:xpath (str "//div[@id='users']//table/tbody/tr/td[text()='" email "']/parent::tr/td[last()]/div/a[position()=1]")})) (defn compare-user-row-and-map [email user-map] (wait-until #(not (exists? users-form-yes))) (wait-until #(exists? {:xpath (str "//div[@id='users']//table/tbody/tr/td[text()='" email "']/parent::tr")})) (wait-until #(= (user-map->user-str (assoc user-map :created (user-creation-date (:email user-map)))) (user-table-row->user-str email))) (is (= (user-map->user-str (assoc user-map :created (user-creation-date (:email user-map)))) (user-table-row->user-str email)))) (deftest selenium-account-user (let [manager-email "manager@bar.com" manager-password "manager" manager-name "Manager" ;; register a manager _ (login-test/register-user! {:platform-id manager-email :password manager-password :name manager-name}) manager (login/get-user-by-email manager-email) account-name "FooBar.com" ;; register an account _ (accounts/create-account! account-name) ;; retrieve the account account (accounts/get-account-by-name account-name) account-id (:id account) ;; associate manager with account _ (accounts/associate-account-manager! (:id manager) (:id account)) ;; child account child-email "james@purpleapp.com" child-password "child" child-name "Foo Bar" ;; child account 2 second-child-email "baz@bar.com" second-child-name "Baz Bar" ;; child account 3 third-child-email "qux@quux.com" third-child-name "Qux Quux" third-child-number "800-555-1212" ;; register another account _ (accounts/create-account! "BazQux.com") ;; A regular user user-email "baz@qux.com" user-password "bazqux" user-name "Baz Qux" ;; vehicles manager-vehicle {:make "Nissan" :model "Altima" :year "2006" :color "Blue" :license-plate "FOOBAR" :fuel-type "91 Octane" :only-top-tier-gas? false :user manager-name} first-child-vehicle {:make "Honda" :model "Accord" :year "2009" :color "Black" :license-plate "BAZQUX" :fuel-type "87 Octane" :only-top-tier-gas? true :user child-name} second-child-vehicle {:make "Ford" :model "F150" :year "1995" :color "White" :license-plate "QUUXCORGE" :fuel-type "91 Octane" :only-top-tier-gas? true :user second-child-name}] (testing "Users can be added" (selenium/go-to-uri "login") (selenium/login-portal manager-email manager-password) (wait-until #(exists? selenium/logout)) (is (exists? (find-element selenium/logout))) (wait-until #(exists? users-link)) (is (exists? (find-element users-link))) (click users-link) ;; check that the manager exists in the table (wait-until #(exists? users-active-tab)) (click users-active-tab) (is (= (user-map->user-str {:name manager-name :email manager-email :manager? true :created (user-creation-date manager-email)}) (user-table-row->user-str manager-email))) ;; check to see that a blank username is invalid (wait-until #(exists? add-users-button)) (click add-users-button) (wait-until #(exists? users-form-email-address)) (clear users-form-email-address) (input-text users-form-email-address child-email) (clear users-form-full-name) (click users-form-save) (wait-until #(exists? users-form-yes)) (click users-form-yes) (wait-until #(exists? users-form-save)) (is (= "Name can not be blank!" (selenium/get-error-alert))) (wait-until #(exists? users-form-dismiss)) (click users-form-dismiss) ;; create a user (create-user {:email child-email :name child-name :phone-number ""}) ;; check that the user shows up in the pending table (wait-until #(exists? users-pending-tab)) (click users-pending-tab) (compare-user-row-and-map child-email {:name child-name :email child-email :manager? false}) ;; add a second child user (create-user {:email second-child-email :name second-child-name :phone-number ""}) ;; check that the user shows up in the pending table (wait-until #(exists? users-pending-tab)) (click users-pending-tab) (compare-user-row-and-map second-child-email {:name second-child-name :email second-child-email :manager? false}) ;; add a third child user (create-user {:email third-child-email :name third-child-name :phone-number third-child-number}) ;; check that the user shows up in the pending table (wait-until #(exists? users-pending-tab)) (click users-pending-tab) (compare-user-row-and-map third-child-email {:name third-child-name :email third-child-email :phone-number third-child-number :manager? false})) (testing "Manager adds vehicles" (click portal/vehicles-link) (wait-until #(exists? portal/no-vehicles-message)) ;; account managers can add vehicles (portal/create-vehicle manager-vehicle) (wait-until #(exists? {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=1]"})) (is (= (portal/vehicle-map->vehicle-str manager-vehicle) (portal/vehicle-table-row->vehicle-str 1))) ;; add another vehicle (portal/create-vehicle first-child-vehicle) (wait-until #(exists? {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=2]"})) (is (= (portal/vehicle-map->vehicle-str first-child-vehicle) (portal/vehicle-table-row->vehicle-str 2))) ;; add the third vehicle (portal/create-vehicle second-child-vehicle) (wait-until #(exists? {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=3]"})) (is (= (portal/vehicle-map->vehicle-str second-child-vehicle) (portal/vehicle-table-row->vehicle-str 3)))) (testing "Manager can edit vehicle" ;; account managers edit vehicles error check (wait-until #(exists? {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=3]/td[last()]/div/a[position()=1]"})) (click {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=3]/td[last()]/div/a[position()=1]"}) (wait-until #(exists? portal/vehicle-form-make)) (portal/fill-vehicle-form (assoc second-child-vehicle :make " " :model " ")) (click portal/vehicle-form-save) (wait-until #(exists? portal/vehicle-form-yes)) (click portal/vehicle-form-yes) (wait-until #(exists? portal/vehicle-form-save)) (is (= "You must assign a make to this vehicle!" (selenium/get-error-alert))) ;; corectly fill in the form, should be updated (wait-until #(exists? portal/vehicle-form-save)) (portal/fill-vehicle-form (assoc second-child-vehicle :model "Escort")) (click portal/vehicle-form-save) (wait-until #(exists? portal/vehicle-form-yes)) (click portal/vehicle-form-yes) (wait-until #(exists? portal/add-vehicle-button)) (is (= (portal/vehicle-map->vehicle-str (assoc second-child-vehicle :model "Escort")) (portal/vehicle-table-row->vehicle-str 3))) ;; account managers can assign users to vehicles (wait-until #(exists? {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=3]/td[last()]/div/a[position()=1]"})) (click {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=3]/td[last()]/div/a[position()=1]"}) (wait-until #(exists? portal/vehicle-form-save)) (portal/fill-vehicle-form (assoc second-child-vehicle :user "Foo Bar")) (click portal/vehicle-form-save) (wait-until #(exists? portal/vehicle-form-yes)) (click portal/vehicle-form-yes) (wait-until #(exists? portal/add-vehicle-button)) (is (= (portal/vehicle-map->vehicle-str (assoc second-child-vehicle :user "Foo Bar")) (portal/vehicle-table-row->vehicle-str 3)))) (testing "Child account can't add or edit vehicles" ;; users not shown for account-children (portal/logout-portal) (selenium/go-to-uri "login") ;; set the password for the child user (is (:success (db/!update (db/conn) "users" {:reset_key "" :password_hash (bcrypt/encrypt child-password)} {:id (:id (login/get-user-by-email child-email))}))) (selenium/login-portal child-email child-password) (wait-until #(exists? selenium/logout)) ;; child users don't have an add vehicles button (click portal/vehicles-link) (wait-until #(exists? portal/vehicles-table)) (is (not (exists? portal/add-vehicle-button))) ;; child user don't have an edit vehicle button (is (not (exists? {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=3]/td[last()]/div/a[position()=1]"}))) ;; child users can see the vehicle they are assigned to (wait-until #(exists? {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=1]"})) (is (= (portal/vehicle-map->vehicle-str (dissoc first-child-vehicle :user)) (portal/vehicle-table-row->vehicle-str 1)))) (testing "Account managers can activate and reactivate vehicles" ;; login manager (selenium/go-to-uri "login") (selenium/login-portal manager-email manager-password) (wait-until #(exists? portal/vehicles-link)) ;; click on the vehicle tab (click portal/vehicles-link) (wait-until #(exists? portal/add-vehicle-button)) ;; check that row count of the active table matches the count in the ;; active filter (portal/compare-active-vehicles-table-and-filter-buttons) ;; check that row count of the deactivated table matches count in the ;; deactivated filter (portal/compare-deactivated-vehicles-table-and-filter-buttons) ;; deactivate the first vehicle (portal/deactivate-vehicle-and-check 1 2) ;; deactivate the second vehicle (portal/deactivate-vehicle-and-check 1 1) ;; deactivate the third vehicle (portal/deactivate-vehicle-and-check 1 0) ;; reactivate the first vehicle (portal/activate-vehicle-and-check 1 2) ;; reactivate the second vehicle (portal/activate-vehicle-and-check 1 1) ;; reactive the third vehicle (portal/activate-vehicle-and-check 1 0)) (testing "Account managers can activate and reactivate users" ;; login manager (selenium/go-to-uri "login") (selenium/login-portal manager-email manager-password) (wait-until #(exists? users-link)) ;; click on the user tab (click users-link) (wait-until #(exists? add-users-button)) ;; check that there are two pending users (count-in-pending-users-filter-correct? 2) (count-in-active-users-filter-correct? 2) (count-in-deactivated-users-filter-correct? 0) ;; set the password for the second child user (is (:success (db/!update (db/conn) "users" {:reset_key "" :password_hash (bcrypt/encrypt child-password)} {:id (:id (login/get-user-by-email second-child-email))}))) ;; click the user refresh button (click users-refresh-button) ;; check that the filter counts are now correct (count-in-pending-users-filter-correct? 1) (count-in-active-users-filter-correct? 3) (count-in-deactivated-users-filter-correct? 0) ;; set the password for the third child user (is (:success (db/!update (db/conn) "users" {:reset_key "" :password_hash (bcrypt/encrypt child-password)} {:id (:id (login/get-user-by-email third-child-email))}))) ;; click the user refresh button (click users-refresh-button) ;; check that the filter counts are now correct (count-in-pending-users-filter-correct? 0) (count-in-active-users-filter-correct? 4) (count-in-deactivated-users-filter-correct? 0) ;; check that row count of the active table matches the count in the ;; active filter (compare-active-users-table-and-filter-buttons) ;; check that row count of the deactivated table matches count in the ;; deactivated filter (compare-deactivated-users-table-and-filter-buttons) ;; deactivate the first user (deactivate-user-and-check 2 3) ;; deactivate the second user (deactivate-user-and-check 2 2) ;; deactivate the third user (deactivate-user-and-check 2 1) ;; reactivate the first user (activate-user-and-check 1 2) ;; reactivate the second user (activate-user-and-check 1 1) ;; reactive the third user (activate-user-and-check 1 0) ;; check that the account managers can't deactivate manager accounts (click active-users-filter) (wait-until #(= (active-users-filter-count) (users-table-count))) (is (not (re-find #"Deactivate" (text {:xpath (str "//div[@id='users']//table/tbody/tr[position()" "=" 1 "]")}))))) (testing "An account manager can edit users" ;; check that only the name be edited (edit-user third-child-email) (wait-until #(exists? users-form-full-name)) (clear users-form-full-name) (input-text users-form-full-name "Qux Quxxer") (click users-form-save) (wait-until #(exists? users-form-yes)) (click users-form-yes) (wait-until #(exists? add-users-button)) (compare-user-row-and-map third-child-email {:name "Qux Quxxer" :email third-child-email :phone-number third-child-number :manager? false}) ;; check that only the phone number can be edited (edit-user third-child-email) (wait-until #(exists? users-form-full-name)) (clear users-form-phone-number) (input-text users-form-phone-number "800-555-1111") (click users-form-save) (wait-until #(exists? users-form-yes)) (click users-form-yes) (wait-until #(exists? add-users-button)) (compare-user-row-and-map third-child-email {:name "Qux Quxxer" :email third-child-email :phone-number "800-555-1111" :manager? false}) ;; check that name and phone number can be edited together (edit-user third-child-email) (wait-until #(exists? users-form-full-name)) (clear users-form-full-name) (input-text users-form-full-name "Qux Quxx") (clear users-form-phone-number) (input-text users-form-phone-number "800-555-5555") (click users-form-save) (wait-until #(exists? users-form-yes)) (click users-form-yes) (wait-until #(exists? add-users-button)) (compare-user-row-and-map third-child-email {:name "Qux Quxx" :email third-child-email :phone-number "800-555-5555" :manager? false}) ;; check that a blank name results in an error message (edit-user third-child-email) (wait-until #(exists? users-form-full-name)) (clear users-form-full-name) (input-text users-form-full-name " ") (click users-form-save) (wait-until #(exists? users-form-yes)) (click users-form-yes) (wait-until #(exists? users-form-save)) (is (= "Name can not be blank!") (selenium/get-error-alert)) (click users-form-dismiss) (wait-until #(exists? add-users-button)) ;; check that a blank phone number can be used (edit-user third-child-email) (wait-until #(exists? users-form-full-name)) (clear users-form-phone-number) (input-text users-form-phone-number " ") (click users-form-save) (wait-until #(exists? users-form-yes)) (click users-form-yes) (wait-until #(exists? add-users-button)) (compare-user-row-and-map third-child-email {:name "Qux Quxx" :email third-child-email :phone-number "" :manager? false}))))
114449
(ns portal.functional.test.accounts (:require [crypto.password.bcrypt :as bcrypt] [clj-time.format :as t] [clj-webdriver.taxi :refer :all] [clojure.edn :as edn] [clojure.string :as string] [clojure.test :refer [deftest is testing use-fixtures]] [common.db :as db] [common.util :as util] [portal.accounts :as accounts] [portal.functional.test.cookies :as cookies] [portal.functional.test.orders :as test-orders] [portal.functional.test.portal :as portal] [portal.functional.test.selenium :as selenium] [portal.functional.test.vehicles :as test-vehicles] [portal.test.db-tools :refer [setup-ebdb-test-pool! setup-ebdb-test-for-conn-fixture clear-and-populate-test-database clear-and-populate-test-database-fixture reset-db!]] [portal.login :as login] [portal.test.login-test :as login-test] [portal.test.utils :as test-utils] [portal.users :as users] [portal.vehicles :as vehicles])) ;; for manual testing: ;; (selenium/startup-test-env!) ; make sure profiles.clj was loaded with ;; ; :base-url "http:localhost:5744/" ;; or if you are going to be doing ring mock tests ;; (setup-ebdb-test-pool!) ;; -- run tests -- ;; (reset-db!) ; note: most tests will need this run between them anyhow ;; -- run more tests ;; (selenium/shutdown-test-env! (use-fixtures :once selenium/with-server selenium/with-browser selenium/with-redefs-fixture setup-ebdb-test-for-conn-fixture) (use-fixtures :each clear-and-populate-test-database-fixture) ;; simplified routes (defn account-manager-context-uri [account-id manager-id] (str "/account/" account-id "/manager/" manager-id)) (defn add-user-uri [account-id manager-id] (str (account-manager-context-uri account-id manager-id) "/add-user")) (defn account-users-uri [account-id manager-id] (str (account-manager-context-uri account-id manager-id) "/users")) (defn manager-get-user-uri [account-id manager-id user-id] (str (account-manager-context-uri account-id manager-id) "/user/" user-id)) (defn manager-get-vehicle-uri [account-id manager-id vehicle-id] (str (account-manager-context-uri account-id manager-id) "/vehicle/" vehicle-id)) (defn user-vehicle-uri [user-id vehicle-id] (str "/user/" user-id "/vehicle/" vehicle-id)) (defn user-vehicles-uri [user-id] (str "/user/" user-id "/vehicles")) (defn user-orders-uri [user-id] (str "/user/" user-id "/orders")) (defn user-add-vehicle-uri [user-id] (str "/user/" user-id "/add-vehicle")) (defn user-edit-vehicle-uri [user-id] (str "/user/" user-id "/edit-vehicle")) (defn manager-vehicle-uri [account-id manager-id vehicle-id] (str (account-manager-context-uri account-id manager-id) "/vehicle/" vehicle-id)) (defn manager-add-vehicle-uri [account-id manager-id] (str (account-manager-context-uri account-id manager-id) "/add-vehicle")) (defn manager-edit-vehicle-uri [account-id manager-id] (str (account-manager-context-uri account-id manager-id) "/edit-vehicle")) (defn manager-edit-user-uri [account-id manager-id] (str (account-manager-context-uri account-id manager-id) "/edit-user")) (defn manager-vehicles-uri [account-id manager-id] (str (account-manager-context-uri account-id manager-id) "/vehicles")) (defn manager-orders-uri [account-id manager-id] (str (account-manager-context-uri account-id manager-id) "/orders")) ;; common elements (def users-link {:xpath "//li/a/div[text()='USERS']"}) (def add-users-button {:xpath "//div[@id='users']//button[text()=' Add']"}) (def users-form-email-address {:xpath "//div[@id='users']//form//input[@placeholder='Email Address']"}) (def users-form-full-name {:xpath "//div[@id='users']//form//input[contains(@placeholder,'Full Name')]"}) (def users-form-phone-number {:xpath "//div[@id='users']//form//input[contains(@placeholder,'Phone Number')]"}) (def users-form-save {:xpath "//div[@id='users']//form//button[text()='Save']"}) (def users-form-dismiss {:xpath "//div[@id='users']//form//button[text()='Dismiss']"}) (def users-form-yes {:xpath "//div[@id='users']//form//button[text()='Yes']"}) (def users-form-no {:xpath "//div[@id='users']//form//button[text()='No']"}) (def users-pending-tab {:xpath "//div[@id='users']//button[contains(text(),'Pending')]"}) (def users-active-tab {:xpath "//div[@id='users']//button[contains(text(),'Active')]"}) (def users-table {:xpath "//div[@id='users']//table"}) (def active-users-filter {:xpath "//div[@id='users']//button[contains(text(),'Active')]"}) (def deactivated-users-filter {:xpath "//div[@id='users']//button[contains(text(),'Deactivated')]"}) (def pending-users-filter {:xpath "//div[@id='users']//button[contains(text(),'Pending')]"}) (def users-refresh-button {:xpath "//div[@id='users']//button/i[contains(@class,'fa-refresh')]"}) (deftest ok-route (is (-> (test-utils/get-uri-json :get "/ok") (get-in [:body :success])))) (deftest account-managers-security (with-redefs [common.sendgrid/send-template-email (fn [to subject message & {:keys [from template-id substitutions]}] (println "No reset password email was actually sent"))] (let [manager-email "<EMAIL>" manager-password "<PASSWORD>" manager-name "<NAME>" ;; register a manager _ (login-test/register-user! {:platform-id manager-email :password <PASSWORD> :name manager-name}) manager (login/get-user-by-email manager-email) account-name "FooBar.com" ;; register an account _ (accounts/create-account! account-name) ;; retrieve the account account (accounts/get-account-by-name account-name) account-id (:id account) ;; associate manager with account _ (accounts/associate-account-manager! (:id manager) (:id account)) manager-login-response (test-utils/get-uri-json :post "/login" {:json-body {:email manager-email :password <PASSWORD>-password}}) manager-user-id (cookies/get-cookie-user-id manager-login-response) manager-auth-cookie (cookies/auth-cookie manager-login-response) ;; child account child-email "<EMAIL>" child-password "<PASSWORD>" child-name "Foo Bar" _ (login-test/register-user! {:platform-id child-email :password child-password :name child-name}) child (login/get-user-by-email child-email) ;; associate child-account with account _ (accounts/associate-child-account! (:id child) (:id account)) ;; generate auth-cokkie child-login-response (test-utils/get-uri-json :post "/login" {:json-body {:email child-email :password child-password}}) child-user-id (cookies/get-cookie-user-id child-login-response) child-auth-cookie (cookies/auth-cookie child-login-response) ;; register another account _ (accounts/create-account! "BazQux.com") ;; retrieve the account another-account (accounts/get-account-by-name "BaxQux.com") second-child-email "<EMAIL>" second-child-name "Baz Bar" ;; A regular user user-email "<EMAIL>" user-password "<PASSWORD>" user-name "<NAME>" _ (login-test/register-user! {:platform-id user-email :password <PASSWORD> :name user-name}) user (login/get-user-by-email user-email) user-id (:id user) user-login-response (test-utils/get-uri-json :post "/login" {:json-body {:email user-email :password user-<PASSWORD>}}) user-auth-cookie (cookies/auth-cookie user-login-response)] (testing "Only account managers can add and edit users" ;; child user can't add a user (is (= 403 (-> (test-utils/get-uri-json :post (add-user-uri account-id child-user-id) {:json-body {:email second-child-email :name second-child-name} :headers child-auth-cookie}) (get-in [:status])))) ;; a child user can't edit a user (is (= 403 (-> (test-utils/get-uri-json :put (manager-edit-user-uri account-id child-user-id) {:json-body {:email second-child-email :name second-child-name :id child-user-id} :headers child-auth-cookie}) (get-in [:status])))) ;; a regular user can't add a user to another account (is (= 403 (-> (test-utils/get-uri-json :post (add-user-uri account-id user-id) {:json-body {:email second-child-email :name second-child-name} :headers user-auth-cookie}) (get-in [:status])))) ;; a regular user can't edit a user of an account (is (= 403 (-> (test-utils/get-uri-json :put (manager-edit-user-uri account-id user-id) {:json-body {:email second-child-email :name second-child-name :id child-user-id} :headers user-auth-cookie}) (get-in [:status])))) ;; account manager can add a user (is (-> (test-utils/get-uri-json :post (add-user-uri account-id manager-user-id) {:json-body {:email second-child-email :name second-child-name} :headers manager-auth-cookie}) (get-in [:body :success]))) ;; account manager can edit a user (is (-> (test-utils/get-uri-json :put (manager-edit-user-uri account-id manager-user-id) {:json-body {:email child-email :name child-name :id child-user-id :active true} :headers manager-auth-cookie}) (get-in [:body :success]))) (testing "Users can't see other users" ;; can't see their parent account's users (is (= 403 (-> (test-utils/get-uri-json :get (account-users-uri account-id child-user-id) {:headers child-auth-cookie}) (get-in [:status])))) ;; can't see another child account user (is (= 403 (-> (test-utils/get-uri-json :get (manager-get-user-uri account-id child-user-id (:id (login/get-user-by-email second-child-email))) {:headers child-auth-cookie}) (get-in [:status])))) ;; can't see manager account user (is (= 403 (-> (test-utils/get-uri-json :get (manager-get-user-uri account-id child-user-id manager-user-id) {:headers child-auth-cookie}) (get-in [:status])))) ;; ...but the manager can see the child account user (is (= child-user-id (-> (test-utils/get-uri-json :get (manager-get-user-uri account-id manager-user-id child-user-id) {:headers manager-auth-cookie}) (get-in [:body :id])))) ;; manager can't see a user not associated with their account (is (= 403 (-> (test-utils/get-uri-json :get (manager-get-user-uri account-id manager-user-id user-id) {:headers manager-auth-cookie}) (get-in [:status]))))) (let [;; manager vehicles _ (test-vehicles/create-vehicle! (test-vehicles/vehicle-map {}) {:id manager-user-id}) manager-vehicles (vehicles/user-vehicles manager-user-id) manager-vehicle (first manager-vehicles) manager-vehicle-id (:id manager-vehicle) _ (test-vehicles/create-vehicle! (test-vehicles/vehicle-map {:color "red" :year "2006"}) {:id manager-user-id}) ;; child vehicle _ (test-vehicles/create-vehicle! (test-vehicles/vehicle-map {:make "Honda" :model "Accord" :color "Silver"}) {:id child-user-id}) child-vehicles (vehicles/user-vehicles child-user-id) child-vehicle (first child-vehicles) child-vehicle-id (:id child-vehicle) ;; second child vehicle second-child-user-id (:id (login/get-user-by-email second-child-email)) _ (test-vehicles/create-vehicle! (test-vehicles/vehicle-map {:make "Hyundai" :model "Sonota" :color "Orange"}) {:id second-child-user-id}) second-child-vehicles (vehicles/user-vehicles second-child-user-id) second-child-vehicle (first second-child-vehicles) second-child-vehicle-id (:id second-child-vehicle) ;; user-vehicle _ (test-vehicles/create-vehicle! (test-vehicles/vehicle-map {:make "BMW" :model "i8" :color "Blue"}) {:id user-id}) user-vehicles (vehicles/user-vehicles user-id) user-vehicle (first user-vehicles) user-vehicle-id (:id user-vehicle)] (testing "Only account managers can see all vehicles" ;; manager sees all vehicles (is (= 4 (-> (test-utils/get-uri-json :get (manager-vehicles-uri account-id manager-user-id) {:headers manager-auth-cookie}) (get-in [:body]) (count)))) ;; child can not (is (= 403 (-> (test-utils/get-uri-json :get (manager-vehicles-uri account-id child-user-id) {:headers child-auth-cookie}) (get-in [:status]))))) (testing "Child accounts can only see their own vehicles" ;; child account only sees their own vehicle (is (= 1 (-> (test-utils/get-uri-json :get (user-vehicles-uri child-user-id) {:headers child-auth-cookie}) (get-in [:body]) (count)))) ;; child can't see account vehicles (is (= 403 (-> (test-utils/get-uri-json :get (manager-vehicles-uri account-id child-user-id) {:headers child-auth-cookie}) (get-in [:status])))) ;; user can retrieve their own vehicle (is (= user-vehicle-id (-> (test-utils/get-uri-json :get (user-vehicle-uri user-id user-vehicle-id) {:headers user-auth-cookie}) (get-in [:body :id])))) ;; manager can see another vehicle associated with account (is (= child-vehicle-id) (-> (test-utils/get-uri-json :get (manager-vehicle-uri account-id manager-user-id child-vehicle-id) {:headers manager-auth-cookie}) (get-in [:body :id])))) (testing "Users can't see other user's vehicles" ;; a child user can't view another child user's vehicles (is (= 403 (-> (test-utils/get-uri-json :get (user-vehicle-uri child-user-id second-child-vehicle-id) {:headers child-auth-cookie}) (get-in [:status])))) ;; child user can't view a regular user's vehicles (is (= 403 (-> (test-utils/get-uri-json :get (user-vehicle-uri child-user-id user-vehicle-id) {:headers child-auth-cookie}) (get-in [:status])))) ;; regular user not associated with account can't view another ;; user's vehicle (is (= 403 (-> (test-utils/get-uri-json :get (user-vehicle-uri user-id child-vehicle-id) {:headers user-auth-cookie}) (get-in [:status])))) ;; account managers can't view vehicles that aren't associated ;; with their account (is (= 403 (-> (test-utils/get-uri-json :get (manager-vehicle-uri account-id manager-user-id user-vehicle-id) {:headers manager-auth-cookie}) (get-in [:status])))) (testing "Adding and editing vehicles test" ;; a regular user can add a vehicle (is (-> (test-utils/get-uri-json :post (user-add-vehicle-uri user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "BMW" :model "i8" :color "Red" :user_id user-id}) :id) :headers user-auth-cookie}) (get-in [:body :success]))) ;; a regular user can edit their own vehicle (is (-> (test-utils/get-uri-json :put (user-edit-vehicle-uri user-id) {:json-body (assoc user-vehicle :color "Black") :headers user-auth-cookie}) (get-in [:body :success]))) ;; a regular user can't add a vehicle to ;; another user-id (is (= 403 (-> (test-utils/get-uri-json :post (user-add-vehicle-uri user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "BMW" :model "i8" :color "Red" :user_id child-user-id}) :id) :headers user-auth-cookie}) (get-in [:status])))) ;; a regular user can't edit a vehicle of ;; another user-id (is (= 403 (-> (test-utils/get-uri-json :put (user-edit-vehicle-uri user-id) {:json-body (assoc child-vehicle :color "Green") :headers user-auth-cookie}) (get-in [:status])))) ;; a regular user can't change the user_id to ;; another user (is (= 403 (-> (test-utils/get-uri-json :put (user-edit-vehicle-uri user-id) {:json-body (assoc user-vehicle :user_id manager-user-id) :headers user-auth-cookie}) (get-in [:status])))) ;; a regular user can't add a vehicle to ;; an account (is (= 403 (-> (test-utils/get-uri-json :post (manager-add-vehicle-uri account-id user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "BMW" :model "i8" :color "Red" :user_id user-id}) :id) :headers user-auth-cookie}) (get-in [:status])))) ;; a manager can add a vehicle to an account ;; with their own user-id (is (-> (test-utils/get-uri-json :post (manager-add-vehicle-uri account-id manager-user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "Honda" :model "Civic" :color "Red" :user_id manager-user-id}) :id) :headers manager-auth-cookie}) (get-in [:body :success]))) ;; manager can view their own vehicle (is (= manager-vehicle-id (-> (test-utils/get-uri-json :get (manager-get-vehicle-uri account-id manager-user-id manager-vehicle-id) {:headers manager-auth-cookie}) (get-in [:body :id])))) ;; manager can view child vehicle (is (= child-vehicle-id (-> (test-utils/get-uri-json :get (manager-get-vehicle-uri account-id manager-user-id child-vehicle-id) {:headers manager-auth-cookie}) (get-in [:body :id])))) ;; a manager can add a vehicle to an account ;; with a child-user-id (is (-> (test-utils/get-uri-json :post (manager-add-vehicle-uri account-id manager-user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "Ford" :model "F150" :color "White" :user_id child-user-id}) :id) :headers manager-auth-cookie}) (get-in [:body :success]))) ;; a manager can edit a vehicle associated with an account (is (-> (test-utils/get-uri-json :put (manager-edit-vehicle-uri account-id manager-user-id) {:json-body (assoc child-vehicle :color "White") :headers manager-auth-cookie}) (get-in [:body :success]))) ;; a manager can change the user to themselves (is (-> (test-utils/get-uri-json :put (manager-edit-vehicle-uri account-id manager-user-id) {:json-body (assoc child-vehicle :user_id manager-user-id) :headers manager-auth-cookie}) (get-in [:body :success]))) ;; a manager can change the user to that of a child user (is (-> (test-utils/get-uri-json :put (manager-edit-vehicle-uri account-id manager-user-id) {:json-body (assoc manager-vehicle :user_id child-user-id) :headers manager-auth-cookie}) (get-in [:body :success]))) ;; manager can't change a vehicle user-id to one they ;; don't manage (is (= 403 (-> (test-utils/get-uri-json :put (manager-edit-vehicle-uri account-id manager-user-id) {:json-body (assoc manager-vehicle :user_id user-id) :headers manager-auth-cookie}) (get-in [:status])))) ;; a manager can't add a vehicle to an account ;; for a regular user (is (= 403 (-> (test-utils/get-uri-json :post (manager-add-vehicle-uri account-id manager-user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "BMW" :model "i8" :color "Red" :user_id user-id}) :id) :headers manager-auth-cookie}) (get-in [:status])))) ;; a child user can't add a vehicle to the account (is (= 403 (-> (test-utils/get-uri-json :post (manager-add-vehicle-uri account-id child-user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "Honda" :model "CRV" :color "Beige" :user_id child-vehicle-id}) :id) :headers child-auth-cookie}) (get-in [:status])))) ;; temporary, users should still be allowed to add vehicles ;; a child user can't add a vehicle, period (is (= 403 (-> (test-utils/get-uri-json :post (user-add-vehicle-uri child-user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "BMW" :model "i8" :color "Red" :user_id child-user-id}) :id) :headers child-auth-cookie}) (get-in [:status])))) ;; a child user can't edit a vehicle associated with the account (is (= 403 (-> (test-utils/get-uri-json :put (manager-edit-vehicle-uri account-id child-user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "Honda" :model "CRV" :color "Beige" :user_id child-vehicle-id}) :id) :headers child-auth-cookie}) (get-in [:status])))) ;; temporary, users should still be allowed to edit vehicles ;; a child user can't edit a vehicle, period (is (= 403 (-> (test-utils/get-uri-json :put (user-edit-vehicle-uri child-user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "BMW" :model "i8" :color "Red" :user_id child-user-id}) :id) :headers child-auth-cookie}) (get-in [:status])))))) (let [child-order-1 (test-orders/order-map {:user_id child-user-id :vehicle_id child-vehicle-id}) _ (test-orders/create-order! child-order-1) child-order-2 (test-orders/order-map {:user_id child-user-id :vehicle_id child-vehicle-id}) _ (test-orders/create-order! child-order-2) manager-order-1 (test-orders/order-map {:user_id manager-user-id :vehicle_id manager-vehicle-id}) _ (test-orders/create-order! manager-order-1) manager-order-2 (test-orders/order-map {:user_id manager-user-id :vehicle_id manager-vehicle-id}) _ (test-orders/create-order! manager-order-2) user-order-1 (test-orders/order-map {:user_id user-id :vehicle_id user-vehicle-id}) _ (test-orders/create-order! user-order-1) user-order-2 (test-orders/order-map {:user_id user-id :vehicle_id user-vehicle-id}) _ (test-orders/create-order! user-order-2) user-order-3 (test-orders/order-map {:user_id user-id :vehicle_id user-vehicle-id}) _ (test-orders/create-order! user-order-3)] (testing "Account managers can see all orders" (is (= 4 (-> (test-utils/get-uri-json :get (manager-orders-uri account-id manager-user-id) {:headers manager-auth-cookie}) (get-in [:body]) (count))))) (testing "Regular users can see their own orders" (is (= 3 (-> (test-utils/get-uri-json :get (user-orders-uri user-id) {:headers user-auth-cookie}) (get-in [:body]) (count))))) (testing "Child users can see their own orders" (is (= 2 (-> (test-utils/get-uri-json :get (user-orders-uri child-user-id) {:headers child-auth-cookie}) (get-in [:body]) (count))))) (testing ".. but child users can't see the account orders" (is (= 403 (-> (test-utils/get-uri-json :get (manager-orders-uri account-id child-user-id) {:headers child-auth-cookie}) (get-in [:status]))))) (testing "Regular users can't see orders of other accounts" (is (= 403 (-> (test-utils/get-uri-json :get (manager-orders-uri account-id manager-user-id) {:headers user-auth-cookie}) (get-in [:status]))))))))))) (defn user-creation-date [email] (-> email (login/get-user-by-email) :id (users/get-user) :timestamp_created (util/unix->format (t/formatter "M/d/yyyy")))) (defn user-map->user-str [{:keys [name email phone-number manager? created] :or {created (util/unix->format (util/now-unix) (t/formatter "M/d/yyyy"))}}] (string/join " " (filterv (comp not string/blank?) [name email phone-number (if manager? "Yes" "No") created]))) (defn user-table-row->user-str [email] (let [row-col (fn [col] (str "//div[@id='users']//table/tbody/tr/td[text()='" email "']/parent::tr" "/td[position()=" col "]")) _ (wait-until #(exists? {:xpath (row-col 2)})) _ (wait-until #(= (text {:xpath (row-col 2)}) email)) name (text {:xpath (row-col 1)}) email (text {:xpath (row-col 2)}) phone-number (text {:xpath (row-col 3)}) manager (text {:xpath (row-col 4)}) created (text {:xpath (row-col 5)})] (string/join " " (filterv (comp not string/blank?) [name email phone-number manager created])))) (defn active-users-filter-count [] (edn/read-string (second (re-matches #".*\(([0-9]*)\)" (text active-users-filter))))) (defn deactivated-users-filter-count [] (edn/read-string (second (re-matches #".*\(([0-9]*)\)" (text deactivated-users-filter))))) (defn pending-users-filter-count [] (edn/read-string (second (re-matches #".*\(([0-9]*)\)" (text pending-users-filter))))) (defn users-table-count [] (count (find-elements {:xpath "//div[@id='users']//table/tbody/tr"}))) (defn deactivate-user-at-position [position] (let [deactivate-link {:xpath (str "//div[@id='users']//table/tbody/tr[position()" "=" position "]/td[last()]/div/a[position()=2]")}] (click active-users-filter) (wait-until #(= (active-users-filter-count) (users-table-count))) (wait-until #(exists? deactivate-link)) (click deactivate-link))) (defn activate-user-at-position [position] (let [activate-link {:xpath (str "//div[@id='users']//table/tbody/tr[position()" "=" position "]/td[last()]/div/a[position()=2]")}] (click deactivated-users-filter) (wait-until #(= (deactivated-users-filter-count) (users-table-count))) (wait-until #(exists? activate-link)) (click activate-link))) (defn compare-active-users-table-and-filter-buttons [] (wait-until #(exists? active-users-filter)) (click active-users-filter) (wait-until #(= (active-users-filter-count) (users-table-count))) (is (= (active-users-filter-count) (users-table-count)))) (defn compare-deactivated-users-table-and-filter-buttons [] (wait-until #(exists? deactivated-users-filter)) (click deactivated-users-filter) (wait-until #(= (deactivated-users-filter-count) (users-table-count))) (is (= (deactivated-users-filter-count) (users-table-count)))) (defn count-in-active-users-filter-correct? [n] (wait-until #(= (active-users-filter-count) n)) (is (= n (active-users-filter-count)))) (defn count-in-deactivated-users-filter-correct? [n] (wait-until #(= (deactivated-users-filter-count) n)) (is (= n (deactivated-users-filter-count)))) (defn count-in-pending-users-filter-correct? [n] (wait-until #(= (pending-users-filter-count) n)) (is (= n (pending-users-filter-count)))) (defn deactivate-user-and-check [position new-count] (deactivate-user-at-position position) ;; check that the counts are correct (count-in-active-users-filter-correct? new-count) (compare-active-users-table-and-filter-buttons) (compare-deactivated-users-table-and-filter-buttons)) (defn activate-user-and-check [position new-count] (activate-user-at-position position) ;; check that the counts are correct (count-in-deactivated-users-filter-correct? new-count) (compare-active-users-table-and-filter-buttons) (compare-deactivated-users-table-and-filter-buttons)) (defn create-user [{:keys [email name phone-number]}] (wait-until #(exists? add-users-button)) (click add-users-button) (wait-until #(exists? users-form-email-address)) (clear users-form-email-address) (input-text users-form-email-address email) (clear users-form-full-name) (input-text users-form-full-name name) (clear users-form-phone-number) (input-text users-form-phone-number phone-number) (click users-form-save) (wait-until #(exists? users-form-yes)) (click users-form-yes)) (defn edit-user [email] (wait-until #(exists? {:xpath (str "//div[@id='users']//table/tbody/tr/td[text()='" email "']/parent::tr/td[last()]/div/a[position()=1]")})) (click {:xpath (str "//div[@id='users']//table/tbody/tr/td[text()='" email "']/parent::tr/td[last()]/div/a[position()=1]")})) (defn compare-user-row-and-map [email user-map] (wait-until #(not (exists? users-form-yes))) (wait-until #(exists? {:xpath (str "//div[@id='users']//table/tbody/tr/td[text()='" email "']/parent::tr")})) (wait-until #(= (user-map->user-str (assoc user-map :created (user-creation-date (:email user-map)))) (user-table-row->user-str email))) (is (= (user-map->user-str (assoc user-map :created (user-creation-date (:email user-map)))) (user-table-row->user-str email)))) (deftest selenium-account-user (let [manager-email "<EMAIL>" manager-password "<PASSWORD>" manager-name "<NAME>" ;; register a manager _ (login-test/register-user! {:platform-id manager-email :password <PASSWORD>-password :name manager-name}) manager (login/get-user-by-email manager-email) account-name "FooBar.com" ;; register an account _ (accounts/create-account! account-name) ;; retrieve the account account (accounts/get-account-by-name account-name) account-id (:id account) ;; associate manager with account _ (accounts/associate-account-manager! (:id manager) (:id account)) ;; child account child-email "<EMAIL>" child-password "<PASSWORD>" child-name "Foo Bar" ;; child account 2 second-child-email "<EMAIL>" second-child-name "Baz Bar" ;; child account 3 third-child-email "<EMAIL>" third-child-name "<NAME>" third-child-number "800-555-1212" ;; register another account _ (accounts/create-account! "BazQux.com") ;; A regular user user-email "<EMAIL>" user-password "<PASSWORD>" user-name "<NAME>" ;; vehicles manager-vehicle {:make "Nissan" :model "Altima" :year "2006" :color "Blue" :license-plate "FOOBAR" :fuel-type "91 Octane" :only-top-tier-gas? false :user manager-name} first-child-vehicle {:make "Honda" :model "Accord" :year "2009" :color "Black" :license-plate "BAZQUX" :fuel-type "87 Octane" :only-top-tier-gas? true :user child-name} second-child-vehicle {:make "Ford" :model "F150" :year "1995" :color "White" :license-plate "QUUXCORGE" :fuel-type "91 Octane" :only-top-tier-gas? true :user second-child-name}] (testing "Users can be added" (selenium/go-to-uri "login") (selenium/login-portal manager-email manager-password) (wait-until #(exists? selenium/logout)) (is (exists? (find-element selenium/logout))) (wait-until #(exists? users-link)) (is (exists? (find-element users-link))) (click users-link) ;; check that the manager exists in the table (wait-until #(exists? users-active-tab)) (click users-active-tab) (is (= (user-map->user-str {:name <PASSWORD>-name :email manager-email :manager? true :created (user-creation-date manager-email)}) (user-table-row->user-str manager-email))) ;; check to see that a blank username is invalid (wait-until #(exists? add-users-button)) (click add-users-button) (wait-until #(exists? users-form-email-address)) (clear users-form-email-address) (input-text users-form-email-address child-email) (clear users-form-full-name) (click users-form-save) (wait-until #(exists? users-form-yes)) (click users-form-yes) (wait-until #(exists? users-form-save)) (is (= "Name can not be blank!" (selenium/get-error-alert))) (wait-until #(exists? users-form-dismiss)) (click users-form-dismiss) ;; create a user (create-user {:email child-email :name child-name :phone-number ""}) ;; check that the user shows up in the pending table (wait-until #(exists? users-pending-tab)) (click users-pending-tab) (compare-user-row-and-map child-email {:name child-name :email child-email :manager? false}) ;; add a second child user (create-user {:email second-child-email :name second-child-name :phone-number ""}) ;; check that the user shows up in the pending table (wait-until #(exists? users-pending-tab)) (click users-pending-tab) (compare-user-row-and-map second-child-email {:name second-child-name :email second-child-email :manager? false}) ;; add a third child user (create-user {:email third-child-email :name third-child-name :phone-number third-child-number}) ;; check that the user shows up in the pending table (wait-until #(exists? users-pending-tab)) (click users-pending-tab) (compare-user-row-and-map third-child-email {:name third-child-name :email third-child-email :phone-number third-child-number :manager? false})) (testing "Manager adds vehicles" (click portal/vehicles-link) (wait-until #(exists? portal/no-vehicles-message)) ;; account managers can add vehicles (portal/create-vehicle manager-vehicle) (wait-until #(exists? {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=1]"})) (is (= (portal/vehicle-map->vehicle-str manager-vehicle) (portal/vehicle-table-row->vehicle-str 1))) ;; add another vehicle (portal/create-vehicle first-child-vehicle) (wait-until #(exists? {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=2]"})) (is (= (portal/vehicle-map->vehicle-str first-child-vehicle) (portal/vehicle-table-row->vehicle-str 2))) ;; add the third vehicle (portal/create-vehicle second-child-vehicle) (wait-until #(exists? {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=3]"})) (is (= (portal/vehicle-map->vehicle-str second-child-vehicle) (portal/vehicle-table-row->vehicle-str 3)))) (testing "Manager can edit vehicle" ;; account managers edit vehicles error check (wait-until #(exists? {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=3]/td[last()]/div/a[position()=1]"})) (click {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=3]/td[last()]/div/a[position()=1]"}) (wait-until #(exists? portal/vehicle-form-make)) (portal/fill-vehicle-form (assoc second-child-vehicle :make " " :model " ")) (click portal/vehicle-form-save) (wait-until #(exists? portal/vehicle-form-yes)) (click portal/vehicle-form-yes) (wait-until #(exists? portal/vehicle-form-save)) (is (= "You must assign a make to this vehicle!" (selenium/get-error-alert))) ;; corectly fill in the form, should be updated (wait-until #(exists? portal/vehicle-form-save)) (portal/fill-vehicle-form (assoc second-child-vehicle :model "Escort")) (click portal/vehicle-form-save) (wait-until #(exists? portal/vehicle-form-yes)) (click portal/vehicle-form-yes) (wait-until #(exists? portal/add-vehicle-button)) (is (= (portal/vehicle-map->vehicle-str (assoc second-child-vehicle :model "Escort")) (portal/vehicle-table-row->vehicle-str 3))) ;; account managers can assign users to vehicles (wait-until #(exists? {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=3]/td[last()]/div/a[position()=1]"})) (click {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=3]/td[last()]/div/a[position()=1]"}) (wait-until #(exists? portal/vehicle-form-save)) (portal/fill-vehicle-form (assoc second-child-vehicle :user "<NAME>")) (click portal/vehicle-form-save) (wait-until #(exists? portal/vehicle-form-yes)) (click portal/vehicle-form-yes) (wait-until #(exists? portal/add-vehicle-button)) (is (= (portal/vehicle-map->vehicle-str (assoc second-child-vehicle :user "<NAME>")) (portal/vehicle-table-row->vehicle-str 3)))) (testing "Child account can't add or edit vehicles" ;; users not shown for account-children (portal/logout-portal) (selenium/go-to-uri "login") ;; set the password for the child user (is (:success (db/!update (db/conn) "users" {:reset_key "" :password_hash (<PASSWORD>/encrypt <PASSWORD>-<PASSWORD>)} {:id (:id (login/get-user-by-email child-email))}))) (selenium/login-portal child-email child-password) (wait-until #(exists? selenium/logout)) ;; child users don't have an add vehicles button (click portal/vehicles-link) (wait-until #(exists? portal/vehicles-table)) (is (not (exists? portal/add-vehicle-button))) ;; child user don't have an edit vehicle button (is (not (exists? {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=3]/td[last()]/div/a[position()=1]"}))) ;; child users can see the vehicle they are assigned to (wait-until #(exists? {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=1]"})) (is (= (portal/vehicle-map->vehicle-str (dissoc first-child-vehicle :user)) (portal/vehicle-table-row->vehicle-str 1)))) (testing "Account managers can activate and reactivate vehicles" ;; login manager (selenium/go-to-uri "login") (selenium/login-portal manager-email manager-password) (wait-until #(exists? portal/vehicles-link)) ;; click on the vehicle tab (click portal/vehicles-link) (wait-until #(exists? portal/add-vehicle-button)) ;; check that row count of the active table matches the count in the ;; active filter (portal/compare-active-vehicles-table-and-filter-buttons) ;; check that row count of the deactivated table matches count in the ;; deactivated filter (portal/compare-deactivated-vehicles-table-and-filter-buttons) ;; deactivate the first vehicle (portal/deactivate-vehicle-and-check 1 2) ;; deactivate the second vehicle (portal/deactivate-vehicle-and-check 1 1) ;; deactivate the third vehicle (portal/deactivate-vehicle-and-check 1 0) ;; reactivate the first vehicle (portal/activate-vehicle-and-check 1 2) ;; reactivate the second vehicle (portal/activate-vehicle-and-check 1 1) ;; reactive the third vehicle (portal/activate-vehicle-and-check 1 0)) (testing "Account managers can activate and reactivate users" ;; login manager (selenium/go-to-uri "login") (selenium/login-portal manager-email manager-password) (wait-until #(exists? users-link)) ;; click on the user tab (click users-link) (wait-until #(exists? add-users-button)) ;; check that there are two pending users (count-in-pending-users-filter-correct? 2) (count-in-active-users-filter-correct? 2) (count-in-deactivated-users-filter-correct? 0) ;; set the password for the second child user (is (:success (db/!update (db/conn) "users" {:reset_key "" :password_hash (<PASSWORD>/encrypt <PASSWORD>)} {:id (:id (login/get-user-by-email second-child-email))}))) ;; click the user refresh button (click users-refresh-button) ;; check that the filter counts are now correct (count-in-pending-users-filter-correct? 1) (count-in-active-users-filter-correct? 3) (count-in-deactivated-users-filter-correct? 0) ;; set the password for the third child user (is (:success (db/!update (db/conn) "users" {:reset_key "" :password_hash (<PASSWORD>/encrypt <PASSWORD>)} {:id (:id (login/get-user-by-email third-child-email))}))) ;; click the user refresh button (click users-refresh-button) ;; check that the filter counts are now correct (count-in-pending-users-filter-correct? 0) (count-in-active-users-filter-correct? 4) (count-in-deactivated-users-filter-correct? 0) ;; check that row count of the active table matches the count in the ;; active filter (compare-active-users-table-and-filter-buttons) ;; check that row count of the deactivated table matches count in the ;; deactivated filter (compare-deactivated-users-table-and-filter-buttons) ;; deactivate the first user (deactivate-user-and-check 2 3) ;; deactivate the second user (deactivate-user-and-check 2 2) ;; deactivate the third user (deactivate-user-and-check 2 1) ;; reactivate the first user (activate-user-and-check 1 2) ;; reactivate the second user (activate-user-and-check 1 1) ;; reactive the third user (activate-user-and-check 1 0) ;; check that the account managers can't deactivate manager accounts (click active-users-filter) (wait-until #(= (active-users-filter-count) (users-table-count))) (is (not (re-find #"Deactivate" (text {:xpath (str "//div[@id='users']//table/tbody/tr[position()" "=" 1 "]")}))))) (testing "An account manager can edit users" ;; check that only the name be edited (edit-user third-child-email) (wait-until #(exists? users-form-full-name)) (clear users-form-full-name) (input-text users-form-full-name "<NAME>") (click users-form-save) (wait-until #(exists? users-form-yes)) (click users-form-yes) (wait-until #(exists? add-users-button)) (compare-user-row-and-map third-child-email {:name "<NAME>" :email third-child-email :phone-number third-child-number :manager? false}) ;; check that only the phone number can be edited (edit-user third-child-email) (wait-until #(exists? users-form-full-name)) (clear users-form-phone-number) (input-text users-form-phone-number "800-555-1111") (click users-form-save) (wait-until #(exists? users-form-yes)) (click users-form-yes) (wait-until #(exists? add-users-button)) (compare-user-row-and-map third-child-email {:name "<NAME>" :email third-child-email :phone-number "800-555-1111" :manager? false}) ;; check that name and phone number can be edited together (edit-user third-child-email) (wait-until #(exists? users-form-full-name)) (clear users-form-full-name) (input-text users-form-full-name "<NAME>") (clear users-form-phone-number) (input-text users-form-phone-number "800-555-5555") (click users-form-save) (wait-until #(exists? users-form-yes)) (click users-form-yes) (wait-until #(exists? add-users-button)) (compare-user-row-and-map third-child-email {:name "<NAME>" :email third-child-email :phone-number "800-555-5555" :manager? false}) ;; check that a blank name results in an error message (edit-user third-child-email) (wait-until #(exists? users-form-full-name)) (clear users-form-full-name) (input-text users-form-full-name " ") (click users-form-save) (wait-until #(exists? users-form-yes)) (click users-form-yes) (wait-until #(exists? users-form-save)) (is (= "Name can not be blank!") (selenium/get-error-alert)) (click users-form-dismiss) (wait-until #(exists? add-users-button)) ;; check that a blank phone number can be used (edit-user third-child-email) (wait-until #(exists? users-form-full-name)) (clear users-form-phone-number) (input-text users-form-phone-number " ") (click users-form-save) (wait-until #(exists? users-form-yes)) (click users-form-yes) (wait-until #(exists? add-users-button)) (compare-user-row-and-map third-child-email {:name "<NAME>" :email third-child-email :phone-number "" :manager? false}))))
true
(ns portal.functional.test.accounts (:require [crypto.password.bcrypt :as bcrypt] [clj-time.format :as t] [clj-webdriver.taxi :refer :all] [clojure.edn :as edn] [clojure.string :as string] [clojure.test :refer [deftest is testing use-fixtures]] [common.db :as db] [common.util :as util] [portal.accounts :as accounts] [portal.functional.test.cookies :as cookies] [portal.functional.test.orders :as test-orders] [portal.functional.test.portal :as portal] [portal.functional.test.selenium :as selenium] [portal.functional.test.vehicles :as test-vehicles] [portal.test.db-tools :refer [setup-ebdb-test-pool! setup-ebdb-test-for-conn-fixture clear-and-populate-test-database clear-and-populate-test-database-fixture reset-db!]] [portal.login :as login] [portal.test.login-test :as login-test] [portal.test.utils :as test-utils] [portal.users :as users] [portal.vehicles :as vehicles])) ;; for manual testing: ;; (selenium/startup-test-env!) ; make sure profiles.clj was loaded with ;; ; :base-url "http:localhost:5744/" ;; or if you are going to be doing ring mock tests ;; (setup-ebdb-test-pool!) ;; -- run tests -- ;; (reset-db!) ; note: most tests will need this run between them anyhow ;; -- run more tests ;; (selenium/shutdown-test-env! (use-fixtures :once selenium/with-server selenium/with-browser selenium/with-redefs-fixture setup-ebdb-test-for-conn-fixture) (use-fixtures :each clear-and-populate-test-database-fixture) ;; simplified routes (defn account-manager-context-uri [account-id manager-id] (str "/account/" account-id "/manager/" manager-id)) (defn add-user-uri [account-id manager-id] (str (account-manager-context-uri account-id manager-id) "/add-user")) (defn account-users-uri [account-id manager-id] (str (account-manager-context-uri account-id manager-id) "/users")) (defn manager-get-user-uri [account-id manager-id user-id] (str (account-manager-context-uri account-id manager-id) "/user/" user-id)) (defn manager-get-vehicle-uri [account-id manager-id vehicle-id] (str (account-manager-context-uri account-id manager-id) "/vehicle/" vehicle-id)) (defn user-vehicle-uri [user-id vehicle-id] (str "/user/" user-id "/vehicle/" vehicle-id)) (defn user-vehicles-uri [user-id] (str "/user/" user-id "/vehicles")) (defn user-orders-uri [user-id] (str "/user/" user-id "/orders")) (defn user-add-vehicle-uri [user-id] (str "/user/" user-id "/add-vehicle")) (defn user-edit-vehicle-uri [user-id] (str "/user/" user-id "/edit-vehicle")) (defn manager-vehicle-uri [account-id manager-id vehicle-id] (str (account-manager-context-uri account-id manager-id) "/vehicle/" vehicle-id)) (defn manager-add-vehicle-uri [account-id manager-id] (str (account-manager-context-uri account-id manager-id) "/add-vehicle")) (defn manager-edit-vehicle-uri [account-id manager-id] (str (account-manager-context-uri account-id manager-id) "/edit-vehicle")) (defn manager-edit-user-uri [account-id manager-id] (str (account-manager-context-uri account-id manager-id) "/edit-user")) (defn manager-vehicles-uri [account-id manager-id] (str (account-manager-context-uri account-id manager-id) "/vehicles")) (defn manager-orders-uri [account-id manager-id] (str (account-manager-context-uri account-id manager-id) "/orders")) ;; common elements (def users-link {:xpath "//li/a/div[text()='USERS']"}) (def add-users-button {:xpath "//div[@id='users']//button[text()=' Add']"}) (def users-form-email-address {:xpath "//div[@id='users']//form//input[@placeholder='Email Address']"}) (def users-form-full-name {:xpath "//div[@id='users']//form//input[contains(@placeholder,'Full Name')]"}) (def users-form-phone-number {:xpath "//div[@id='users']//form//input[contains(@placeholder,'Phone Number')]"}) (def users-form-save {:xpath "//div[@id='users']//form//button[text()='Save']"}) (def users-form-dismiss {:xpath "//div[@id='users']//form//button[text()='Dismiss']"}) (def users-form-yes {:xpath "//div[@id='users']//form//button[text()='Yes']"}) (def users-form-no {:xpath "//div[@id='users']//form//button[text()='No']"}) (def users-pending-tab {:xpath "//div[@id='users']//button[contains(text(),'Pending')]"}) (def users-active-tab {:xpath "//div[@id='users']//button[contains(text(),'Active')]"}) (def users-table {:xpath "//div[@id='users']//table"}) (def active-users-filter {:xpath "//div[@id='users']//button[contains(text(),'Active')]"}) (def deactivated-users-filter {:xpath "//div[@id='users']//button[contains(text(),'Deactivated')]"}) (def pending-users-filter {:xpath "//div[@id='users']//button[contains(text(),'Pending')]"}) (def users-refresh-button {:xpath "//div[@id='users']//button/i[contains(@class,'fa-refresh')]"}) (deftest ok-route (is (-> (test-utils/get-uri-json :get "/ok") (get-in [:body :success])))) (deftest account-managers-security (with-redefs [common.sendgrid/send-template-email (fn [to subject message & {:keys [from template-id substitutions]}] (println "No reset password email was actually sent"))] (let [manager-email "PI:EMAIL:<EMAIL>END_PI" manager-password "PI:PASSWORD:<PASSWORD>END_PI" manager-name "PI:NAME:<NAME>END_PI" ;; register a manager _ (login-test/register-user! {:platform-id manager-email :password PI:PASSWORD:<PASSWORD>END_PI :name manager-name}) manager (login/get-user-by-email manager-email) account-name "FooBar.com" ;; register an account _ (accounts/create-account! account-name) ;; retrieve the account account (accounts/get-account-by-name account-name) account-id (:id account) ;; associate manager with account _ (accounts/associate-account-manager! (:id manager) (:id account)) manager-login-response (test-utils/get-uri-json :post "/login" {:json-body {:email manager-email :password PI:PASSWORD:<PASSWORD>END_PI-password}}) manager-user-id (cookies/get-cookie-user-id manager-login-response) manager-auth-cookie (cookies/auth-cookie manager-login-response) ;; child account child-email "PI:EMAIL:<EMAIL>END_PI" child-password "PI:PASSWORD:<PASSWORD>END_PI" child-name "Foo Bar" _ (login-test/register-user! {:platform-id child-email :password child-password :name child-name}) child (login/get-user-by-email child-email) ;; associate child-account with account _ (accounts/associate-child-account! (:id child) (:id account)) ;; generate auth-cokkie child-login-response (test-utils/get-uri-json :post "/login" {:json-body {:email child-email :password child-password}}) child-user-id (cookies/get-cookie-user-id child-login-response) child-auth-cookie (cookies/auth-cookie child-login-response) ;; register another account _ (accounts/create-account! "BazQux.com") ;; retrieve the account another-account (accounts/get-account-by-name "BaxQux.com") second-child-email "PI:EMAIL:<EMAIL>END_PI" second-child-name "Baz Bar" ;; A regular user user-email "PI:EMAIL:<EMAIL>END_PI" user-password "PI:PASSWORD:<PASSWORD>END_PI" user-name "PI:NAME:<NAME>END_PI" _ (login-test/register-user! {:platform-id user-email :password PI:PASSWORD:<PASSWORD>END_PI :name user-name}) user (login/get-user-by-email user-email) user-id (:id user) user-login-response (test-utils/get-uri-json :post "/login" {:json-body {:email user-email :password user-PI:PASSWORD:<PASSWORD>END_PI}}) user-auth-cookie (cookies/auth-cookie user-login-response)] (testing "Only account managers can add and edit users" ;; child user can't add a user (is (= 403 (-> (test-utils/get-uri-json :post (add-user-uri account-id child-user-id) {:json-body {:email second-child-email :name second-child-name} :headers child-auth-cookie}) (get-in [:status])))) ;; a child user can't edit a user (is (= 403 (-> (test-utils/get-uri-json :put (manager-edit-user-uri account-id child-user-id) {:json-body {:email second-child-email :name second-child-name :id child-user-id} :headers child-auth-cookie}) (get-in [:status])))) ;; a regular user can't add a user to another account (is (= 403 (-> (test-utils/get-uri-json :post (add-user-uri account-id user-id) {:json-body {:email second-child-email :name second-child-name} :headers user-auth-cookie}) (get-in [:status])))) ;; a regular user can't edit a user of an account (is (= 403 (-> (test-utils/get-uri-json :put (manager-edit-user-uri account-id user-id) {:json-body {:email second-child-email :name second-child-name :id child-user-id} :headers user-auth-cookie}) (get-in [:status])))) ;; account manager can add a user (is (-> (test-utils/get-uri-json :post (add-user-uri account-id manager-user-id) {:json-body {:email second-child-email :name second-child-name} :headers manager-auth-cookie}) (get-in [:body :success]))) ;; account manager can edit a user (is (-> (test-utils/get-uri-json :put (manager-edit-user-uri account-id manager-user-id) {:json-body {:email child-email :name child-name :id child-user-id :active true} :headers manager-auth-cookie}) (get-in [:body :success]))) (testing "Users can't see other users" ;; can't see their parent account's users (is (= 403 (-> (test-utils/get-uri-json :get (account-users-uri account-id child-user-id) {:headers child-auth-cookie}) (get-in [:status])))) ;; can't see another child account user (is (= 403 (-> (test-utils/get-uri-json :get (manager-get-user-uri account-id child-user-id (:id (login/get-user-by-email second-child-email))) {:headers child-auth-cookie}) (get-in [:status])))) ;; can't see manager account user (is (= 403 (-> (test-utils/get-uri-json :get (manager-get-user-uri account-id child-user-id manager-user-id) {:headers child-auth-cookie}) (get-in [:status])))) ;; ...but the manager can see the child account user (is (= child-user-id (-> (test-utils/get-uri-json :get (manager-get-user-uri account-id manager-user-id child-user-id) {:headers manager-auth-cookie}) (get-in [:body :id])))) ;; manager can't see a user not associated with their account (is (= 403 (-> (test-utils/get-uri-json :get (manager-get-user-uri account-id manager-user-id user-id) {:headers manager-auth-cookie}) (get-in [:status]))))) (let [;; manager vehicles _ (test-vehicles/create-vehicle! (test-vehicles/vehicle-map {}) {:id manager-user-id}) manager-vehicles (vehicles/user-vehicles manager-user-id) manager-vehicle (first manager-vehicles) manager-vehicle-id (:id manager-vehicle) _ (test-vehicles/create-vehicle! (test-vehicles/vehicle-map {:color "red" :year "2006"}) {:id manager-user-id}) ;; child vehicle _ (test-vehicles/create-vehicle! (test-vehicles/vehicle-map {:make "Honda" :model "Accord" :color "Silver"}) {:id child-user-id}) child-vehicles (vehicles/user-vehicles child-user-id) child-vehicle (first child-vehicles) child-vehicle-id (:id child-vehicle) ;; second child vehicle second-child-user-id (:id (login/get-user-by-email second-child-email)) _ (test-vehicles/create-vehicle! (test-vehicles/vehicle-map {:make "Hyundai" :model "Sonota" :color "Orange"}) {:id second-child-user-id}) second-child-vehicles (vehicles/user-vehicles second-child-user-id) second-child-vehicle (first second-child-vehicles) second-child-vehicle-id (:id second-child-vehicle) ;; user-vehicle _ (test-vehicles/create-vehicle! (test-vehicles/vehicle-map {:make "BMW" :model "i8" :color "Blue"}) {:id user-id}) user-vehicles (vehicles/user-vehicles user-id) user-vehicle (first user-vehicles) user-vehicle-id (:id user-vehicle)] (testing "Only account managers can see all vehicles" ;; manager sees all vehicles (is (= 4 (-> (test-utils/get-uri-json :get (manager-vehicles-uri account-id manager-user-id) {:headers manager-auth-cookie}) (get-in [:body]) (count)))) ;; child can not (is (= 403 (-> (test-utils/get-uri-json :get (manager-vehicles-uri account-id child-user-id) {:headers child-auth-cookie}) (get-in [:status]))))) (testing "Child accounts can only see their own vehicles" ;; child account only sees their own vehicle (is (= 1 (-> (test-utils/get-uri-json :get (user-vehicles-uri child-user-id) {:headers child-auth-cookie}) (get-in [:body]) (count)))) ;; child can't see account vehicles (is (= 403 (-> (test-utils/get-uri-json :get (manager-vehicles-uri account-id child-user-id) {:headers child-auth-cookie}) (get-in [:status])))) ;; user can retrieve their own vehicle (is (= user-vehicle-id (-> (test-utils/get-uri-json :get (user-vehicle-uri user-id user-vehicle-id) {:headers user-auth-cookie}) (get-in [:body :id])))) ;; manager can see another vehicle associated with account (is (= child-vehicle-id) (-> (test-utils/get-uri-json :get (manager-vehicle-uri account-id manager-user-id child-vehicle-id) {:headers manager-auth-cookie}) (get-in [:body :id])))) (testing "Users can't see other user's vehicles" ;; a child user can't view another child user's vehicles (is (= 403 (-> (test-utils/get-uri-json :get (user-vehicle-uri child-user-id second-child-vehicle-id) {:headers child-auth-cookie}) (get-in [:status])))) ;; child user can't view a regular user's vehicles (is (= 403 (-> (test-utils/get-uri-json :get (user-vehicle-uri child-user-id user-vehicle-id) {:headers child-auth-cookie}) (get-in [:status])))) ;; regular user not associated with account can't view another ;; user's vehicle (is (= 403 (-> (test-utils/get-uri-json :get (user-vehicle-uri user-id child-vehicle-id) {:headers user-auth-cookie}) (get-in [:status])))) ;; account managers can't view vehicles that aren't associated ;; with their account (is (= 403 (-> (test-utils/get-uri-json :get (manager-vehicle-uri account-id manager-user-id user-vehicle-id) {:headers manager-auth-cookie}) (get-in [:status])))) (testing "Adding and editing vehicles test" ;; a regular user can add a vehicle (is (-> (test-utils/get-uri-json :post (user-add-vehicle-uri user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "BMW" :model "i8" :color "Red" :user_id user-id}) :id) :headers user-auth-cookie}) (get-in [:body :success]))) ;; a regular user can edit their own vehicle (is (-> (test-utils/get-uri-json :put (user-edit-vehicle-uri user-id) {:json-body (assoc user-vehicle :color "Black") :headers user-auth-cookie}) (get-in [:body :success]))) ;; a regular user can't add a vehicle to ;; another user-id (is (= 403 (-> (test-utils/get-uri-json :post (user-add-vehicle-uri user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "BMW" :model "i8" :color "Red" :user_id child-user-id}) :id) :headers user-auth-cookie}) (get-in [:status])))) ;; a regular user can't edit a vehicle of ;; another user-id (is (= 403 (-> (test-utils/get-uri-json :put (user-edit-vehicle-uri user-id) {:json-body (assoc child-vehicle :color "Green") :headers user-auth-cookie}) (get-in [:status])))) ;; a regular user can't change the user_id to ;; another user (is (= 403 (-> (test-utils/get-uri-json :put (user-edit-vehicle-uri user-id) {:json-body (assoc user-vehicle :user_id manager-user-id) :headers user-auth-cookie}) (get-in [:status])))) ;; a regular user can't add a vehicle to ;; an account (is (= 403 (-> (test-utils/get-uri-json :post (manager-add-vehicle-uri account-id user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "BMW" :model "i8" :color "Red" :user_id user-id}) :id) :headers user-auth-cookie}) (get-in [:status])))) ;; a manager can add a vehicle to an account ;; with their own user-id (is (-> (test-utils/get-uri-json :post (manager-add-vehicle-uri account-id manager-user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "Honda" :model "Civic" :color "Red" :user_id manager-user-id}) :id) :headers manager-auth-cookie}) (get-in [:body :success]))) ;; manager can view their own vehicle (is (= manager-vehicle-id (-> (test-utils/get-uri-json :get (manager-get-vehicle-uri account-id manager-user-id manager-vehicle-id) {:headers manager-auth-cookie}) (get-in [:body :id])))) ;; manager can view child vehicle (is (= child-vehicle-id (-> (test-utils/get-uri-json :get (manager-get-vehicle-uri account-id manager-user-id child-vehicle-id) {:headers manager-auth-cookie}) (get-in [:body :id])))) ;; a manager can add a vehicle to an account ;; with a child-user-id (is (-> (test-utils/get-uri-json :post (manager-add-vehicle-uri account-id manager-user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "Ford" :model "F150" :color "White" :user_id child-user-id}) :id) :headers manager-auth-cookie}) (get-in [:body :success]))) ;; a manager can edit a vehicle associated with an account (is (-> (test-utils/get-uri-json :put (manager-edit-vehicle-uri account-id manager-user-id) {:json-body (assoc child-vehicle :color "White") :headers manager-auth-cookie}) (get-in [:body :success]))) ;; a manager can change the user to themselves (is (-> (test-utils/get-uri-json :put (manager-edit-vehicle-uri account-id manager-user-id) {:json-body (assoc child-vehicle :user_id manager-user-id) :headers manager-auth-cookie}) (get-in [:body :success]))) ;; a manager can change the user to that of a child user (is (-> (test-utils/get-uri-json :put (manager-edit-vehicle-uri account-id manager-user-id) {:json-body (assoc manager-vehicle :user_id child-user-id) :headers manager-auth-cookie}) (get-in [:body :success]))) ;; manager can't change a vehicle user-id to one they ;; don't manage (is (= 403 (-> (test-utils/get-uri-json :put (manager-edit-vehicle-uri account-id manager-user-id) {:json-body (assoc manager-vehicle :user_id user-id) :headers manager-auth-cookie}) (get-in [:status])))) ;; a manager can't add a vehicle to an account ;; for a regular user (is (= 403 (-> (test-utils/get-uri-json :post (manager-add-vehicle-uri account-id manager-user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "BMW" :model "i8" :color "Red" :user_id user-id}) :id) :headers manager-auth-cookie}) (get-in [:status])))) ;; a child user can't add a vehicle to the account (is (= 403 (-> (test-utils/get-uri-json :post (manager-add-vehicle-uri account-id child-user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "Honda" :model "CRV" :color "Beige" :user_id child-vehicle-id}) :id) :headers child-auth-cookie}) (get-in [:status])))) ;; temporary, users should still be allowed to add vehicles ;; a child user can't add a vehicle, period (is (= 403 (-> (test-utils/get-uri-json :post (user-add-vehicle-uri child-user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "BMW" :model "i8" :color "Red" :user_id child-user-id}) :id) :headers child-auth-cookie}) (get-in [:status])))) ;; a child user can't edit a vehicle associated with the account (is (= 403 (-> (test-utils/get-uri-json :put (manager-edit-vehicle-uri account-id child-user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "Honda" :model "CRV" :color "Beige" :user_id child-vehicle-id}) :id) :headers child-auth-cookie}) (get-in [:status])))) ;; temporary, users should still be allowed to edit vehicles ;; a child user can't edit a vehicle, period (is (= 403 (-> (test-utils/get-uri-json :put (user-edit-vehicle-uri child-user-id) {:json-body (dissoc (test-vehicles/vehicle-map {:make "BMW" :model "i8" :color "Red" :user_id child-user-id}) :id) :headers child-auth-cookie}) (get-in [:status])))))) (let [child-order-1 (test-orders/order-map {:user_id child-user-id :vehicle_id child-vehicle-id}) _ (test-orders/create-order! child-order-1) child-order-2 (test-orders/order-map {:user_id child-user-id :vehicle_id child-vehicle-id}) _ (test-orders/create-order! child-order-2) manager-order-1 (test-orders/order-map {:user_id manager-user-id :vehicle_id manager-vehicle-id}) _ (test-orders/create-order! manager-order-1) manager-order-2 (test-orders/order-map {:user_id manager-user-id :vehicle_id manager-vehicle-id}) _ (test-orders/create-order! manager-order-2) user-order-1 (test-orders/order-map {:user_id user-id :vehicle_id user-vehicle-id}) _ (test-orders/create-order! user-order-1) user-order-2 (test-orders/order-map {:user_id user-id :vehicle_id user-vehicle-id}) _ (test-orders/create-order! user-order-2) user-order-3 (test-orders/order-map {:user_id user-id :vehicle_id user-vehicle-id}) _ (test-orders/create-order! user-order-3)] (testing "Account managers can see all orders" (is (= 4 (-> (test-utils/get-uri-json :get (manager-orders-uri account-id manager-user-id) {:headers manager-auth-cookie}) (get-in [:body]) (count))))) (testing "Regular users can see their own orders" (is (= 3 (-> (test-utils/get-uri-json :get (user-orders-uri user-id) {:headers user-auth-cookie}) (get-in [:body]) (count))))) (testing "Child users can see their own orders" (is (= 2 (-> (test-utils/get-uri-json :get (user-orders-uri child-user-id) {:headers child-auth-cookie}) (get-in [:body]) (count))))) (testing ".. but child users can't see the account orders" (is (= 403 (-> (test-utils/get-uri-json :get (manager-orders-uri account-id child-user-id) {:headers child-auth-cookie}) (get-in [:status]))))) (testing "Regular users can't see orders of other accounts" (is (= 403 (-> (test-utils/get-uri-json :get (manager-orders-uri account-id manager-user-id) {:headers user-auth-cookie}) (get-in [:status]))))))))))) (defn user-creation-date [email] (-> email (login/get-user-by-email) :id (users/get-user) :timestamp_created (util/unix->format (t/formatter "M/d/yyyy")))) (defn user-map->user-str [{:keys [name email phone-number manager? created] :or {created (util/unix->format (util/now-unix) (t/formatter "M/d/yyyy"))}}] (string/join " " (filterv (comp not string/blank?) [name email phone-number (if manager? "Yes" "No") created]))) (defn user-table-row->user-str [email] (let [row-col (fn [col] (str "//div[@id='users']//table/tbody/tr/td[text()='" email "']/parent::tr" "/td[position()=" col "]")) _ (wait-until #(exists? {:xpath (row-col 2)})) _ (wait-until #(= (text {:xpath (row-col 2)}) email)) name (text {:xpath (row-col 1)}) email (text {:xpath (row-col 2)}) phone-number (text {:xpath (row-col 3)}) manager (text {:xpath (row-col 4)}) created (text {:xpath (row-col 5)})] (string/join " " (filterv (comp not string/blank?) [name email phone-number manager created])))) (defn active-users-filter-count [] (edn/read-string (second (re-matches #".*\(([0-9]*)\)" (text active-users-filter))))) (defn deactivated-users-filter-count [] (edn/read-string (second (re-matches #".*\(([0-9]*)\)" (text deactivated-users-filter))))) (defn pending-users-filter-count [] (edn/read-string (second (re-matches #".*\(([0-9]*)\)" (text pending-users-filter))))) (defn users-table-count [] (count (find-elements {:xpath "//div[@id='users']//table/tbody/tr"}))) (defn deactivate-user-at-position [position] (let [deactivate-link {:xpath (str "//div[@id='users']//table/tbody/tr[position()" "=" position "]/td[last()]/div/a[position()=2]")}] (click active-users-filter) (wait-until #(= (active-users-filter-count) (users-table-count))) (wait-until #(exists? deactivate-link)) (click deactivate-link))) (defn activate-user-at-position [position] (let [activate-link {:xpath (str "//div[@id='users']//table/tbody/tr[position()" "=" position "]/td[last()]/div/a[position()=2]")}] (click deactivated-users-filter) (wait-until #(= (deactivated-users-filter-count) (users-table-count))) (wait-until #(exists? activate-link)) (click activate-link))) (defn compare-active-users-table-and-filter-buttons [] (wait-until #(exists? active-users-filter)) (click active-users-filter) (wait-until #(= (active-users-filter-count) (users-table-count))) (is (= (active-users-filter-count) (users-table-count)))) (defn compare-deactivated-users-table-and-filter-buttons [] (wait-until #(exists? deactivated-users-filter)) (click deactivated-users-filter) (wait-until #(= (deactivated-users-filter-count) (users-table-count))) (is (= (deactivated-users-filter-count) (users-table-count)))) (defn count-in-active-users-filter-correct? [n] (wait-until #(= (active-users-filter-count) n)) (is (= n (active-users-filter-count)))) (defn count-in-deactivated-users-filter-correct? [n] (wait-until #(= (deactivated-users-filter-count) n)) (is (= n (deactivated-users-filter-count)))) (defn count-in-pending-users-filter-correct? [n] (wait-until #(= (pending-users-filter-count) n)) (is (= n (pending-users-filter-count)))) (defn deactivate-user-and-check [position new-count] (deactivate-user-at-position position) ;; check that the counts are correct (count-in-active-users-filter-correct? new-count) (compare-active-users-table-and-filter-buttons) (compare-deactivated-users-table-and-filter-buttons)) (defn activate-user-and-check [position new-count] (activate-user-at-position position) ;; check that the counts are correct (count-in-deactivated-users-filter-correct? new-count) (compare-active-users-table-and-filter-buttons) (compare-deactivated-users-table-and-filter-buttons)) (defn create-user [{:keys [email name phone-number]}] (wait-until #(exists? add-users-button)) (click add-users-button) (wait-until #(exists? users-form-email-address)) (clear users-form-email-address) (input-text users-form-email-address email) (clear users-form-full-name) (input-text users-form-full-name name) (clear users-form-phone-number) (input-text users-form-phone-number phone-number) (click users-form-save) (wait-until #(exists? users-form-yes)) (click users-form-yes)) (defn edit-user [email] (wait-until #(exists? {:xpath (str "//div[@id='users']//table/tbody/tr/td[text()='" email "']/parent::tr/td[last()]/div/a[position()=1]")})) (click {:xpath (str "//div[@id='users']//table/tbody/tr/td[text()='" email "']/parent::tr/td[last()]/div/a[position()=1]")})) (defn compare-user-row-and-map [email user-map] (wait-until #(not (exists? users-form-yes))) (wait-until #(exists? {:xpath (str "//div[@id='users']//table/tbody/tr/td[text()='" email "']/parent::tr")})) (wait-until #(= (user-map->user-str (assoc user-map :created (user-creation-date (:email user-map)))) (user-table-row->user-str email))) (is (= (user-map->user-str (assoc user-map :created (user-creation-date (:email user-map)))) (user-table-row->user-str email)))) (deftest selenium-account-user (let [manager-email "PI:EMAIL:<EMAIL>END_PI" manager-password "PI:PASSWORD:<PASSWORD>END_PI" manager-name "PI:NAME:<NAME>END_PI" ;; register a manager _ (login-test/register-user! {:platform-id manager-email :password PI:PASSWORD:<PASSWORD>END_PI-password :name manager-name}) manager (login/get-user-by-email manager-email) account-name "FooBar.com" ;; register an account _ (accounts/create-account! account-name) ;; retrieve the account account (accounts/get-account-by-name account-name) account-id (:id account) ;; associate manager with account _ (accounts/associate-account-manager! (:id manager) (:id account)) ;; child account child-email "PI:EMAIL:<EMAIL>END_PI" child-password "PI:PASSWORD:<PASSWORD>END_PI" child-name "Foo Bar" ;; child account 2 second-child-email "PI:EMAIL:<EMAIL>END_PI" second-child-name "Baz Bar" ;; child account 3 third-child-email "PI:EMAIL:<EMAIL>END_PI" third-child-name "PI:NAME:<NAME>END_PI" third-child-number "800-555-1212" ;; register another account _ (accounts/create-account! "BazQux.com") ;; A regular user user-email "PI:EMAIL:<EMAIL>END_PI" user-password "PI:PASSWORD:<PASSWORD>END_PI" user-name "PI:NAME:<NAME>END_PI" ;; vehicles manager-vehicle {:make "Nissan" :model "Altima" :year "2006" :color "Blue" :license-plate "FOOBAR" :fuel-type "91 Octane" :only-top-tier-gas? false :user manager-name} first-child-vehicle {:make "Honda" :model "Accord" :year "2009" :color "Black" :license-plate "BAZQUX" :fuel-type "87 Octane" :only-top-tier-gas? true :user child-name} second-child-vehicle {:make "Ford" :model "F150" :year "1995" :color "White" :license-plate "QUUXCORGE" :fuel-type "91 Octane" :only-top-tier-gas? true :user second-child-name}] (testing "Users can be added" (selenium/go-to-uri "login") (selenium/login-portal manager-email manager-password) (wait-until #(exists? selenium/logout)) (is (exists? (find-element selenium/logout))) (wait-until #(exists? users-link)) (is (exists? (find-element users-link))) (click users-link) ;; check that the manager exists in the table (wait-until #(exists? users-active-tab)) (click users-active-tab) (is (= (user-map->user-str {:name PI:NAME:<PASSWORD>END_PI-name :email manager-email :manager? true :created (user-creation-date manager-email)}) (user-table-row->user-str manager-email))) ;; check to see that a blank username is invalid (wait-until #(exists? add-users-button)) (click add-users-button) (wait-until #(exists? users-form-email-address)) (clear users-form-email-address) (input-text users-form-email-address child-email) (clear users-form-full-name) (click users-form-save) (wait-until #(exists? users-form-yes)) (click users-form-yes) (wait-until #(exists? users-form-save)) (is (= "Name can not be blank!" (selenium/get-error-alert))) (wait-until #(exists? users-form-dismiss)) (click users-form-dismiss) ;; create a user (create-user {:email child-email :name child-name :phone-number ""}) ;; check that the user shows up in the pending table (wait-until #(exists? users-pending-tab)) (click users-pending-tab) (compare-user-row-and-map child-email {:name child-name :email child-email :manager? false}) ;; add a second child user (create-user {:email second-child-email :name second-child-name :phone-number ""}) ;; check that the user shows up in the pending table (wait-until #(exists? users-pending-tab)) (click users-pending-tab) (compare-user-row-and-map second-child-email {:name second-child-name :email second-child-email :manager? false}) ;; add a third child user (create-user {:email third-child-email :name third-child-name :phone-number third-child-number}) ;; check that the user shows up in the pending table (wait-until #(exists? users-pending-tab)) (click users-pending-tab) (compare-user-row-and-map third-child-email {:name third-child-name :email third-child-email :phone-number third-child-number :manager? false})) (testing "Manager adds vehicles" (click portal/vehicles-link) (wait-until #(exists? portal/no-vehicles-message)) ;; account managers can add vehicles (portal/create-vehicle manager-vehicle) (wait-until #(exists? {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=1]"})) (is (= (portal/vehicle-map->vehicle-str manager-vehicle) (portal/vehicle-table-row->vehicle-str 1))) ;; add another vehicle (portal/create-vehicle first-child-vehicle) (wait-until #(exists? {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=2]"})) (is (= (portal/vehicle-map->vehicle-str first-child-vehicle) (portal/vehicle-table-row->vehicle-str 2))) ;; add the third vehicle (portal/create-vehicle second-child-vehicle) (wait-until #(exists? {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=3]"})) (is (= (portal/vehicle-map->vehicle-str second-child-vehicle) (portal/vehicle-table-row->vehicle-str 3)))) (testing "Manager can edit vehicle" ;; account managers edit vehicles error check (wait-until #(exists? {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=3]/td[last()]/div/a[position()=1]"})) (click {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=3]/td[last()]/div/a[position()=1]"}) (wait-until #(exists? portal/vehicle-form-make)) (portal/fill-vehicle-form (assoc second-child-vehicle :make " " :model " ")) (click portal/vehicle-form-save) (wait-until #(exists? portal/vehicle-form-yes)) (click portal/vehicle-form-yes) (wait-until #(exists? portal/vehicle-form-save)) (is (= "You must assign a make to this vehicle!" (selenium/get-error-alert))) ;; corectly fill in the form, should be updated (wait-until #(exists? portal/vehicle-form-save)) (portal/fill-vehicle-form (assoc second-child-vehicle :model "Escort")) (click portal/vehicle-form-save) (wait-until #(exists? portal/vehicle-form-yes)) (click portal/vehicle-form-yes) (wait-until #(exists? portal/add-vehicle-button)) (is (= (portal/vehicle-map->vehicle-str (assoc second-child-vehicle :model "Escort")) (portal/vehicle-table-row->vehicle-str 3))) ;; account managers can assign users to vehicles (wait-until #(exists? {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=3]/td[last()]/div/a[position()=1]"})) (click {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=3]/td[last()]/div/a[position()=1]"}) (wait-until #(exists? portal/vehicle-form-save)) (portal/fill-vehicle-form (assoc second-child-vehicle :user "PI:NAME:<NAME>END_PI")) (click portal/vehicle-form-save) (wait-until #(exists? portal/vehicle-form-yes)) (click portal/vehicle-form-yes) (wait-until #(exists? portal/add-vehicle-button)) (is (= (portal/vehicle-map->vehicle-str (assoc second-child-vehicle :user "PI:NAME:<NAME>END_PI")) (portal/vehicle-table-row->vehicle-str 3)))) (testing "Child account can't add or edit vehicles" ;; users not shown for account-children (portal/logout-portal) (selenium/go-to-uri "login") ;; set the password for the child user (is (:success (db/!update (db/conn) "users" {:reset_key "" :password_hash (PI:PASSWORD:<PASSWORD>END_PI/encrypt PI:PASSWORD:<PASSWORD>END_PI-PI:PASSWORD:<PASSWORD>END_PI)} {:id (:id (login/get-user-by-email child-email))}))) (selenium/login-portal child-email child-password) (wait-until #(exists? selenium/logout)) ;; child users don't have an add vehicles button (click portal/vehicles-link) (wait-until #(exists? portal/vehicles-table)) (is (not (exists? portal/add-vehicle-button))) ;; child user don't have an edit vehicle button (is (not (exists? {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=3]/td[last()]/div/a[position()=1]"}))) ;; child users can see the vehicle they are assigned to (wait-until #(exists? {:xpath "//div[@id='vehicles']//table/tbody/tr[position()=1]"})) (is (= (portal/vehicle-map->vehicle-str (dissoc first-child-vehicle :user)) (portal/vehicle-table-row->vehicle-str 1)))) (testing "Account managers can activate and reactivate vehicles" ;; login manager (selenium/go-to-uri "login") (selenium/login-portal manager-email manager-password) (wait-until #(exists? portal/vehicles-link)) ;; click on the vehicle tab (click portal/vehicles-link) (wait-until #(exists? portal/add-vehicle-button)) ;; check that row count of the active table matches the count in the ;; active filter (portal/compare-active-vehicles-table-and-filter-buttons) ;; check that row count of the deactivated table matches count in the ;; deactivated filter (portal/compare-deactivated-vehicles-table-and-filter-buttons) ;; deactivate the first vehicle (portal/deactivate-vehicle-and-check 1 2) ;; deactivate the second vehicle (portal/deactivate-vehicle-and-check 1 1) ;; deactivate the third vehicle (portal/deactivate-vehicle-and-check 1 0) ;; reactivate the first vehicle (portal/activate-vehicle-and-check 1 2) ;; reactivate the second vehicle (portal/activate-vehicle-and-check 1 1) ;; reactive the third vehicle (portal/activate-vehicle-and-check 1 0)) (testing "Account managers can activate and reactivate users" ;; login manager (selenium/go-to-uri "login") (selenium/login-portal manager-email manager-password) (wait-until #(exists? users-link)) ;; click on the user tab (click users-link) (wait-until #(exists? add-users-button)) ;; check that there are two pending users (count-in-pending-users-filter-correct? 2) (count-in-active-users-filter-correct? 2) (count-in-deactivated-users-filter-correct? 0) ;; set the password for the second child user (is (:success (db/!update (db/conn) "users" {:reset_key "" :password_hash (PI:PASSWORD:<PASSWORD>END_PI/encrypt PI:PASSWORD:<PASSWORD>END_PI)} {:id (:id (login/get-user-by-email second-child-email))}))) ;; click the user refresh button (click users-refresh-button) ;; check that the filter counts are now correct (count-in-pending-users-filter-correct? 1) (count-in-active-users-filter-correct? 3) (count-in-deactivated-users-filter-correct? 0) ;; set the password for the third child user (is (:success (db/!update (db/conn) "users" {:reset_key "" :password_hash (PI:PASSWORD:<PASSWORD>END_PI/encrypt PI:PASSWORD:<PASSWORD>END_PI)} {:id (:id (login/get-user-by-email third-child-email))}))) ;; click the user refresh button (click users-refresh-button) ;; check that the filter counts are now correct (count-in-pending-users-filter-correct? 0) (count-in-active-users-filter-correct? 4) (count-in-deactivated-users-filter-correct? 0) ;; check that row count of the active table matches the count in the ;; active filter (compare-active-users-table-and-filter-buttons) ;; check that row count of the deactivated table matches count in the ;; deactivated filter (compare-deactivated-users-table-and-filter-buttons) ;; deactivate the first user (deactivate-user-and-check 2 3) ;; deactivate the second user (deactivate-user-and-check 2 2) ;; deactivate the third user (deactivate-user-and-check 2 1) ;; reactivate the first user (activate-user-and-check 1 2) ;; reactivate the second user (activate-user-and-check 1 1) ;; reactive the third user (activate-user-and-check 1 0) ;; check that the account managers can't deactivate manager accounts (click active-users-filter) (wait-until #(= (active-users-filter-count) (users-table-count))) (is (not (re-find #"Deactivate" (text {:xpath (str "//div[@id='users']//table/tbody/tr[position()" "=" 1 "]")}))))) (testing "An account manager can edit users" ;; check that only the name be edited (edit-user third-child-email) (wait-until #(exists? users-form-full-name)) (clear users-form-full-name) (input-text users-form-full-name "PI:NAME:<NAME>END_PI") (click users-form-save) (wait-until #(exists? users-form-yes)) (click users-form-yes) (wait-until #(exists? add-users-button)) (compare-user-row-and-map third-child-email {:name "PI:NAME:<NAME>END_PI" :email third-child-email :phone-number third-child-number :manager? false}) ;; check that only the phone number can be edited (edit-user third-child-email) (wait-until #(exists? users-form-full-name)) (clear users-form-phone-number) (input-text users-form-phone-number "800-555-1111") (click users-form-save) (wait-until #(exists? users-form-yes)) (click users-form-yes) (wait-until #(exists? add-users-button)) (compare-user-row-and-map third-child-email {:name "PI:NAME:<NAME>END_PI" :email third-child-email :phone-number "800-555-1111" :manager? false}) ;; check that name and phone number can be edited together (edit-user third-child-email) (wait-until #(exists? users-form-full-name)) (clear users-form-full-name) (input-text users-form-full-name "PI:NAME:<NAME>END_PI") (clear users-form-phone-number) (input-text users-form-phone-number "800-555-5555") (click users-form-save) (wait-until #(exists? users-form-yes)) (click users-form-yes) (wait-until #(exists? add-users-button)) (compare-user-row-and-map third-child-email {:name "PI:NAME:<NAME>END_PI" :email third-child-email :phone-number "800-555-5555" :manager? false}) ;; check that a blank name results in an error message (edit-user third-child-email) (wait-until #(exists? users-form-full-name)) (clear users-form-full-name) (input-text users-form-full-name " ") (click users-form-save) (wait-until #(exists? users-form-yes)) (click users-form-yes) (wait-until #(exists? users-form-save)) (is (= "Name can not be blank!") (selenium/get-error-alert)) (click users-form-dismiss) (wait-until #(exists? add-users-button)) ;; check that a blank phone number can be used (edit-user third-child-email) (wait-until #(exists? users-form-full-name)) (clear users-form-phone-number) (input-text users-form-phone-number " ") (click users-form-save) (wait-until #(exists? users-form-yes)) (click users-form-yes) (wait-until #(exists? add-users-button)) (compare-user-row-and-map third-child-email {:name "PI:NAME:<NAME>END_PI" :email third-child-email :phone-number "" :manager? false}))))
[ { "context": "e [overtone.live]))\n\n;; First let's use a tweet by Juan A. Romero\n;; (http://soundcloud.com/rukano)\n;; This code is", "end": 216, "score": 0.9998854398727417, "start": 202, "tag": "NAME", "value": "Juan A. Romero" }, { "context": "tweet by Juan A. Romero\n;; (http://soundcloud.com/rukano)\n;; This code is written in Supercollider's Small", "end": 249, "score": 0.9977962374687195, "start": 243, "tag": "USERNAME", "value": "rukano" }, { "context": "to\n ;; understand...\n ;; https://soundcloud.com/toxi/rukanos-space-organ\n (demo 60 (g-verb (sum (map ", "end": 578, "score": 0.9975073337554932, "start": 574, "tag": "USERNAME", "value": "toxi" }, { "context": "examples and\n;; based on a Supercollider script by Dan Stowells (w/ comments added by toxi)\n;; Creates a dubstep ", "end": 1959, "score": 0.9984509348869324, "start": 1947, "tag": "NAME", "value": "Dan Stowells" } ]
src/resonate2013/ex05_synthesis.clj
howthebodyworks/resonate-2013
0
(ns ^{:doc "A few examples of more complex audio synthesis, ported from SuperCollider to Overtone"} resonate2013.ex05_synthesis (:use [overtone.live])) ;; First let's use a tweet by Juan A. Romero ;; (http://soundcloud.com/rukano) ;; This code is written in Supercollider's Smalltalk dialect: ;; ;; play{d=Duty;f=d.kr(1/[1,2,4],0,Dseq([0,3,7,12,17]+24,inf));GVerb.ar(Blip.ar(f.midicps*[1,4,8],LFNoise1.kr(1/4,3,4)).sum,200,8)} (comment ;; A port to Overtone is almost equally succinct, but still hard to ;; understand... ;; https://soundcloud.com/toxi/rukanos-space-organ (demo 60 (g-verb (sum (map #(blip (* (midicps (duty:kr % 0 (dseq [24 27 31 36 41] INF))) %2) (mul-add:kr (lf-noise1:kr 1/2) 3 4)) [1 1/2 1/4] [1 4 8])) 200 8)) ;; A more easy-on-the-eyes version would look like this: (demo 60 (let [;; First create 3 frequency generators at different ;; tempos/rates [1 1/2 1/4] ;; Each generator will cycle (at its own pace) through the sequence of ;; notes given to dseq and convert notes into actual frequencies f (map #(midicps (duty:kr % 0 (dseq [24 27 31 36 41] INF))) [1 1/2 1/4]) ;; Next we transpose the frequencies over several octaves ;; and create a band limited impulse generator (blip) for ;; each of the freq gens. The blip allows us to configure the number ;; of overtones/harmonics used, which is constantly modulated by a ;; noise generator between 1 and 7 harmonics... tones (map #(blip (* % %2) (mul-add:kr (lf-noise1:kr 1/4) 3 4)) f [1 4 8])] ;; finally, all tones are summed into a single signal ;; and passed through a reverb with a large roomsize and decay time... (g-verb (sum tones) 200 8))) ) ;; The following synth is taken from Overtone's bundled examples and ;; based on a Supercollider script by Dan Stowells (w/ comments added by toxi) ;; Creates a dubstep synth with random wobble bassline, kick & snare patterns (comment (demo 60 (let [bpm 160 ;; create pool of notes as seed for random base line sequence notes (concat (repeat 8 40) [40 41 28 28 28 27 25 35 78]) ;; create an impulse trigger firing once per bar trig (impulse:kr (/ bpm 160)) ;; create frequency generator for a randomly picked note freq (midicps (lag (demand trig 0 (dxrand notes INF)) 0.25)) ;; switch note durations swr (demand trig 0 (dseq [1 6 6 2 1 2 4 8 3 3] INF)) ;; create a sweep curve for filter below sweep (lin-exp (lf-tri swr) -1 1 40 3000) ;; create a slightly detuned stereo sawtooth oscillator wob (apply + (saw (* freq [0.99 1.01]))) ;; apply low pass filter using sweep curve to control cutoff freq wob (lpf wob sweep) ;; normalize to 80% volume wob (* 0.8 (normalizer wob)) ;; apply band pass filter with resonance at 5kHz wob (+ wob (bpf wob 5000 20)) ;; mix in 20% reverb wob (+ wob (* 0.2 (g-verb wob 9 5 0.7))) ;; create impulse generator from given drum pattern kickenv (decay (t2a (demand (impulse:kr (/ bpm 30)) 0 (dseq [1 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0] INF))) 0.7) ;; use modulated sine wave oscillator kick (* (* kickenv 7) (sin-osc (+ 40 (* kickenv kickenv kickenv 200)))) ;; clip at max volume to create distortion kick (clip2 kick 1) ;; snare is just using gated & over-amplified pink noise snare (* 3 (pink-noise) (apply + (* (decay (impulse (/ bpm 240) 0.5) [0.4 2]) [1 0.05]))) ;; send through band pass filter with peak @ 1.5kHz snare (+ snare (bpf (* 8 snare) 1500)) ;; also clip at max vol to distort snare (clip2 snare 1)] ;; mixdown & clip (clip2 (+ wob kick snare) 1))) )
83613
(ns ^{:doc "A few examples of more complex audio synthesis, ported from SuperCollider to Overtone"} resonate2013.ex05_synthesis (:use [overtone.live])) ;; First let's use a tweet by <NAME> ;; (http://soundcloud.com/rukano) ;; This code is written in Supercollider's Smalltalk dialect: ;; ;; play{d=Duty;f=d.kr(1/[1,2,4],0,Dseq([0,3,7,12,17]+24,inf));GVerb.ar(Blip.ar(f.midicps*[1,4,8],LFNoise1.kr(1/4,3,4)).sum,200,8)} (comment ;; A port to Overtone is almost equally succinct, but still hard to ;; understand... ;; https://soundcloud.com/toxi/rukanos-space-organ (demo 60 (g-verb (sum (map #(blip (* (midicps (duty:kr % 0 (dseq [24 27 31 36 41] INF))) %2) (mul-add:kr (lf-noise1:kr 1/2) 3 4)) [1 1/2 1/4] [1 4 8])) 200 8)) ;; A more easy-on-the-eyes version would look like this: (demo 60 (let [;; First create 3 frequency generators at different ;; tempos/rates [1 1/2 1/4] ;; Each generator will cycle (at its own pace) through the sequence of ;; notes given to dseq and convert notes into actual frequencies f (map #(midicps (duty:kr % 0 (dseq [24 27 31 36 41] INF))) [1 1/2 1/4]) ;; Next we transpose the frequencies over several octaves ;; and create a band limited impulse generator (blip) for ;; each of the freq gens. The blip allows us to configure the number ;; of overtones/harmonics used, which is constantly modulated by a ;; noise generator between 1 and 7 harmonics... tones (map #(blip (* % %2) (mul-add:kr (lf-noise1:kr 1/4) 3 4)) f [1 4 8])] ;; finally, all tones are summed into a single signal ;; and passed through a reverb with a large roomsize and decay time... (g-verb (sum tones) 200 8))) ) ;; The following synth is taken from Overtone's bundled examples and ;; based on a Supercollider script by <NAME> (w/ comments added by toxi) ;; Creates a dubstep synth with random wobble bassline, kick & snare patterns (comment (demo 60 (let [bpm 160 ;; create pool of notes as seed for random base line sequence notes (concat (repeat 8 40) [40 41 28 28 28 27 25 35 78]) ;; create an impulse trigger firing once per bar trig (impulse:kr (/ bpm 160)) ;; create frequency generator for a randomly picked note freq (midicps (lag (demand trig 0 (dxrand notes INF)) 0.25)) ;; switch note durations swr (demand trig 0 (dseq [1 6 6 2 1 2 4 8 3 3] INF)) ;; create a sweep curve for filter below sweep (lin-exp (lf-tri swr) -1 1 40 3000) ;; create a slightly detuned stereo sawtooth oscillator wob (apply + (saw (* freq [0.99 1.01]))) ;; apply low pass filter using sweep curve to control cutoff freq wob (lpf wob sweep) ;; normalize to 80% volume wob (* 0.8 (normalizer wob)) ;; apply band pass filter with resonance at 5kHz wob (+ wob (bpf wob 5000 20)) ;; mix in 20% reverb wob (+ wob (* 0.2 (g-verb wob 9 5 0.7))) ;; create impulse generator from given drum pattern kickenv (decay (t2a (demand (impulse:kr (/ bpm 30)) 0 (dseq [1 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0] INF))) 0.7) ;; use modulated sine wave oscillator kick (* (* kickenv 7) (sin-osc (+ 40 (* kickenv kickenv kickenv 200)))) ;; clip at max volume to create distortion kick (clip2 kick 1) ;; snare is just using gated & over-amplified pink noise snare (* 3 (pink-noise) (apply + (* (decay (impulse (/ bpm 240) 0.5) [0.4 2]) [1 0.05]))) ;; send through band pass filter with peak @ 1.5kHz snare (+ snare (bpf (* 8 snare) 1500)) ;; also clip at max vol to distort snare (clip2 snare 1)] ;; mixdown & clip (clip2 (+ wob kick snare) 1))) )
true
(ns ^{:doc "A few examples of more complex audio synthesis, ported from SuperCollider to Overtone"} resonate2013.ex05_synthesis (:use [overtone.live])) ;; First let's use a tweet by PI:NAME:<NAME>END_PI ;; (http://soundcloud.com/rukano) ;; This code is written in Supercollider's Smalltalk dialect: ;; ;; play{d=Duty;f=d.kr(1/[1,2,4],0,Dseq([0,3,7,12,17]+24,inf));GVerb.ar(Blip.ar(f.midicps*[1,4,8],LFNoise1.kr(1/4,3,4)).sum,200,8)} (comment ;; A port to Overtone is almost equally succinct, but still hard to ;; understand... ;; https://soundcloud.com/toxi/rukanos-space-organ (demo 60 (g-verb (sum (map #(blip (* (midicps (duty:kr % 0 (dseq [24 27 31 36 41] INF))) %2) (mul-add:kr (lf-noise1:kr 1/2) 3 4)) [1 1/2 1/4] [1 4 8])) 200 8)) ;; A more easy-on-the-eyes version would look like this: (demo 60 (let [;; First create 3 frequency generators at different ;; tempos/rates [1 1/2 1/4] ;; Each generator will cycle (at its own pace) through the sequence of ;; notes given to dseq and convert notes into actual frequencies f (map #(midicps (duty:kr % 0 (dseq [24 27 31 36 41] INF))) [1 1/2 1/4]) ;; Next we transpose the frequencies over several octaves ;; and create a band limited impulse generator (blip) for ;; each of the freq gens. The blip allows us to configure the number ;; of overtones/harmonics used, which is constantly modulated by a ;; noise generator between 1 and 7 harmonics... tones (map #(blip (* % %2) (mul-add:kr (lf-noise1:kr 1/4) 3 4)) f [1 4 8])] ;; finally, all tones are summed into a single signal ;; and passed through a reverb with a large roomsize and decay time... (g-verb (sum tones) 200 8))) ) ;; The following synth is taken from Overtone's bundled examples and ;; based on a Supercollider script by PI:NAME:<NAME>END_PI (w/ comments added by toxi) ;; Creates a dubstep synth with random wobble bassline, kick & snare patterns (comment (demo 60 (let [bpm 160 ;; create pool of notes as seed for random base line sequence notes (concat (repeat 8 40) [40 41 28 28 28 27 25 35 78]) ;; create an impulse trigger firing once per bar trig (impulse:kr (/ bpm 160)) ;; create frequency generator for a randomly picked note freq (midicps (lag (demand trig 0 (dxrand notes INF)) 0.25)) ;; switch note durations swr (demand trig 0 (dseq [1 6 6 2 1 2 4 8 3 3] INF)) ;; create a sweep curve for filter below sweep (lin-exp (lf-tri swr) -1 1 40 3000) ;; create a slightly detuned stereo sawtooth oscillator wob (apply + (saw (* freq [0.99 1.01]))) ;; apply low pass filter using sweep curve to control cutoff freq wob (lpf wob sweep) ;; normalize to 80% volume wob (* 0.8 (normalizer wob)) ;; apply band pass filter with resonance at 5kHz wob (+ wob (bpf wob 5000 20)) ;; mix in 20% reverb wob (+ wob (* 0.2 (g-verb wob 9 5 0.7))) ;; create impulse generator from given drum pattern kickenv (decay (t2a (demand (impulse:kr (/ bpm 30)) 0 (dseq [1 0 0 0 0 0 1 0 1 0 0 1 0 0 0 0] INF))) 0.7) ;; use modulated sine wave oscillator kick (* (* kickenv 7) (sin-osc (+ 40 (* kickenv kickenv kickenv 200)))) ;; clip at max volume to create distortion kick (clip2 kick 1) ;; snare is just using gated & over-amplified pink noise snare (* 3 (pink-noise) (apply + (* (decay (impulse (/ bpm 240) 0.5) [0.4 2]) [1 0.05]))) ;; send through band pass filter with peak @ 1.5kHz snare (+ snare (bpf (* 8 snare) 1500)) ;; also clip at max vol to distort snare (clip2 snare 1)] ;; mixdown & clip (clip2 (+ wob kick snare) 1))) )
[ { "context": "iles and adhoc Clojure functions.\"\n :author \"Paul Landes\"}\n zensols.cisql.export\n (:require [clojure", "end": 188, "score": 0.9998844861984253, "start": 177, "tag": "NAME", "value": "Paul Landes" } ]
src/clojure/zensols/cisql/export.clj
plandes/cisql
12
(ns ^{:doc "This library contains functions that allow for exporting of table data. This includes functions to export to CSV files and adhoc Clojure functions." :author "Paul Landes"} zensols.cisql.export (:require [clojure.tools.logging :as log] [clojure.java.io :as io] [clojure.data.csv :as csv] [zensols.tabres.display-results :as dis] [zensols.cisql.conf :as conf] [zensols.cisql.db-access :as db])) (defn export-table-csv "Execute **query** and save as an CSV file to **filename**." [query filename] (letfn [(rs-handler [rs _] (let [rs-data (db/result-set-to-array rs) csv (map (fn [row] (map #(get row %) (:header rs-data))) (:rows rs-data)) csv-with-header (cons (:header rs-data) csv)] (with-open [out (io/writer filename)] (csv/write-csv out csv-with-header)) (count (:rows rs-data))))] (log/infof "exporting csv to %s" filename) (db/execute-query query rs-handler))) (defn- function-by-name "Export result set output to a the last defined Clojure function in a file." [clj-file fn-name] (let [last-fn (load-file clj-file) handler-fn (if (nil? fn-name) last-fn (-> (:ns (meta last-fn)) ns-name (ns-resolve (symbol fn-name))))] (or handler-fn (-> (format "no such function %s found in file %s" fn-name clj-file) (ex-info {:file clj-file :fn-name fn-name}) throw)))) (defn export-query-to-function "Export result set output to a the last defined Clojure function in a file." [query clj-file fn-name] (let [handler-fn (function-by-name clj-file fn-name) fmeta (meta handler-fn) fn-name (name (:name fmeta)) res-inst (atom nil)] (letfn [(rs-handler [rs _] (let [rs-data (and rs (db/result-set-to-array rs)) {:keys [header rows]} rs-data argn (count (first (:arglists (meta handler-fn))))] (if (and (> argn 0) (nil? query)) (-> (format "function %s expects a query with %d argument(s)" fn-name argn) (ex-info {:argn argn :fn-name fn-name}) throw)) (->> (case argn 0 (handler-fn) 1 (handler-fn rows) (handler-fn rows header)) (reset! res-inst)) (count (:rows rs-data))))] (log/infof "evaluating function %s" fn-name) (if query (db/execute-query query rs-handler) (rs-handler nil nil)) (let [res @res-inst {:keys [display]} res] (if display (db/display-results (:rows display) (:header display) fn-name) (if res (println res))))))) (defn export-query-to-eval [query code] (let [handler-fn (eval (read-string code)) title "eval" res-inst (atom nil)] (letfn [(rs-handler [rs _] (let [rs-data (db/result-set-to-array rs) {:keys [header rows]} rs-data] (reset! res-inst (handler-fn rows header)) (count (:rows rs-data))))] (db/execute-query query rs-handler) (let [res @res-inst {:keys [display]} res] (if display (db/display-results (:rows display) (:header display) title) (if res (println res)))))))
75868
(ns ^{:doc "This library contains functions that allow for exporting of table data. This includes functions to export to CSV files and adhoc Clojure functions." :author "<NAME>"} zensols.cisql.export (:require [clojure.tools.logging :as log] [clojure.java.io :as io] [clojure.data.csv :as csv] [zensols.tabres.display-results :as dis] [zensols.cisql.conf :as conf] [zensols.cisql.db-access :as db])) (defn export-table-csv "Execute **query** and save as an CSV file to **filename**." [query filename] (letfn [(rs-handler [rs _] (let [rs-data (db/result-set-to-array rs) csv (map (fn [row] (map #(get row %) (:header rs-data))) (:rows rs-data)) csv-with-header (cons (:header rs-data) csv)] (with-open [out (io/writer filename)] (csv/write-csv out csv-with-header)) (count (:rows rs-data))))] (log/infof "exporting csv to %s" filename) (db/execute-query query rs-handler))) (defn- function-by-name "Export result set output to a the last defined Clojure function in a file." [clj-file fn-name] (let [last-fn (load-file clj-file) handler-fn (if (nil? fn-name) last-fn (-> (:ns (meta last-fn)) ns-name (ns-resolve (symbol fn-name))))] (or handler-fn (-> (format "no such function %s found in file %s" fn-name clj-file) (ex-info {:file clj-file :fn-name fn-name}) throw)))) (defn export-query-to-function "Export result set output to a the last defined Clojure function in a file." [query clj-file fn-name] (let [handler-fn (function-by-name clj-file fn-name) fmeta (meta handler-fn) fn-name (name (:name fmeta)) res-inst (atom nil)] (letfn [(rs-handler [rs _] (let [rs-data (and rs (db/result-set-to-array rs)) {:keys [header rows]} rs-data argn (count (first (:arglists (meta handler-fn))))] (if (and (> argn 0) (nil? query)) (-> (format "function %s expects a query with %d argument(s)" fn-name argn) (ex-info {:argn argn :fn-name fn-name}) throw)) (->> (case argn 0 (handler-fn) 1 (handler-fn rows) (handler-fn rows header)) (reset! res-inst)) (count (:rows rs-data))))] (log/infof "evaluating function %s" fn-name) (if query (db/execute-query query rs-handler) (rs-handler nil nil)) (let [res @res-inst {:keys [display]} res] (if display (db/display-results (:rows display) (:header display) fn-name) (if res (println res))))))) (defn export-query-to-eval [query code] (let [handler-fn (eval (read-string code)) title "eval" res-inst (atom nil)] (letfn [(rs-handler [rs _] (let [rs-data (db/result-set-to-array rs) {:keys [header rows]} rs-data] (reset! res-inst (handler-fn rows header)) (count (:rows rs-data))))] (db/execute-query query rs-handler) (let [res @res-inst {:keys [display]} res] (if display (db/display-results (:rows display) (:header display) title) (if res (println res)))))))
true
(ns ^{:doc "This library contains functions that allow for exporting of table data. This includes functions to export to CSV files and adhoc Clojure functions." :author "PI:NAME:<NAME>END_PI"} zensols.cisql.export (:require [clojure.tools.logging :as log] [clojure.java.io :as io] [clojure.data.csv :as csv] [zensols.tabres.display-results :as dis] [zensols.cisql.conf :as conf] [zensols.cisql.db-access :as db])) (defn export-table-csv "Execute **query** and save as an CSV file to **filename**." [query filename] (letfn [(rs-handler [rs _] (let [rs-data (db/result-set-to-array rs) csv (map (fn [row] (map #(get row %) (:header rs-data))) (:rows rs-data)) csv-with-header (cons (:header rs-data) csv)] (with-open [out (io/writer filename)] (csv/write-csv out csv-with-header)) (count (:rows rs-data))))] (log/infof "exporting csv to %s" filename) (db/execute-query query rs-handler))) (defn- function-by-name "Export result set output to a the last defined Clojure function in a file." [clj-file fn-name] (let [last-fn (load-file clj-file) handler-fn (if (nil? fn-name) last-fn (-> (:ns (meta last-fn)) ns-name (ns-resolve (symbol fn-name))))] (or handler-fn (-> (format "no such function %s found in file %s" fn-name clj-file) (ex-info {:file clj-file :fn-name fn-name}) throw)))) (defn export-query-to-function "Export result set output to a the last defined Clojure function in a file." [query clj-file fn-name] (let [handler-fn (function-by-name clj-file fn-name) fmeta (meta handler-fn) fn-name (name (:name fmeta)) res-inst (atom nil)] (letfn [(rs-handler [rs _] (let [rs-data (and rs (db/result-set-to-array rs)) {:keys [header rows]} rs-data argn (count (first (:arglists (meta handler-fn))))] (if (and (> argn 0) (nil? query)) (-> (format "function %s expects a query with %d argument(s)" fn-name argn) (ex-info {:argn argn :fn-name fn-name}) throw)) (->> (case argn 0 (handler-fn) 1 (handler-fn rows) (handler-fn rows header)) (reset! res-inst)) (count (:rows rs-data))))] (log/infof "evaluating function %s" fn-name) (if query (db/execute-query query rs-handler) (rs-handler nil nil)) (let [res @res-inst {:keys [display]} res] (if display (db/display-results (:rows display) (:header display) fn-name) (if res (println res))))))) (defn export-query-to-eval [query code] (let [handler-fn (eval (read-string code)) title "eval" res-inst (atom nil)] (letfn [(rs-handler [rs _] (let [rs-data (db/result-set-to-array rs) {:keys [header rows]} rs-data] (reset! res-inst (handler-fn rows header)) (count (:rows rs-data))))] (db/execute-query query rs-handler) (let [res @res-inst {:keys [display]} res] (if display (db/display-results (:rows display) (:header display) title) (if res (println res)))))))
[ { "context": "(vswap! next-eid inc))\n ::name (rand-nth [\"Ivan\" \"Petr\" \"Sergei\" \"Oleg\" \"Yuri\" \"Dmitry\" \"Fedor\" \"", "end": 141, "score": 0.9998352527618408, "start": 137, "tag": "NAME", "value": "Ivan" }, { "context": " next-eid inc))\n ::name (rand-nth [\"Ivan\" \"Petr\" \"Sergei\" \"Oleg\" \"Yuri\" \"Dmitry\" \"Fedor\" \"Denis\"]", "end": 148, "score": 0.9994286894798279, "start": 144, "tag": "NAME", "value": "Petr" }, { "context": "id inc))\n ::name (rand-nth [\"Ivan\" \"Petr\" \"Sergei\" \"Oleg\" \"Yuri\" \"Dmitry\" \"Fedor\" \"Denis\"])\n ::la", "end": 157, "score": 0.9995817542076111, "start": 151, "tag": "NAME", "value": "Sergei" }, { "context": " ::name (rand-nth [\"Ivan\" \"Petr\" \"Sergei\" \"Oleg\" \"Yuri\" \"Dmitry\" \"Fedor\" \"Denis\"])\n ::last-name", "end": 164, "score": 0.9995414614677429, "start": 160, "tag": "NAME", "value": "Oleg" }, { "context": "me (rand-nth [\"Ivan\" \"Petr\" \"Sergei\" \"Oleg\" \"Yuri\" \"Dmitry\" \"Fedor\" \"Denis\"])\n ::last-name (rand-", "end": 171, "score": 0.9990462064743042, "start": 167, "tag": "NAME", "value": "Yuri" }, { "context": " (rand-nth [\"Ivan\" \"Petr\" \"Sergei\" \"Oleg\" \"Yuri\" \"Dmitry\" \"Fedor\" \"Denis\"])\n ::last-name (rand-nth [\"Iva", "end": 180, "score": 0.9995030760765076, "start": 174, "tag": "NAME", "value": "Dmitry" }, { "context": "h [\"Ivan\" \"Petr\" \"Sergei\" \"Oleg\" \"Yuri\" \"Dmitry\" \"Fedor\" \"Denis\"])\n ::last-name (rand-nth [\"Ivanov\" \"Pe", "end": 188, "score": 0.9996781349182129, "start": 183, "tag": "NAME", "value": "Fedor" }, { "context": "\" \"Petr\" \"Sergei\" \"Oleg\" \"Yuri\" \"Dmitry\" \"Fedor\" \"Denis\"])\n ::last-name (rand-nth [\"Ivanov\" \"Petrov\" \"S", "end": 196, "score": 0.9996594190597534, "start": 191, "tag": "NAME", "value": "Denis" }, { "context": "try\" \"Fedor\" \"Denis\"])\n ::last-name (rand-nth [\"Ivanov\" \"Petrov\" \"Sidorov\" \"Kovalev\" \"Kuznetsov\" \"Vorono", "end": 233, "score": 0.9997913241386414, "start": 227, "tag": "NAME", "value": "Ivanov" }, { "context": "or\" \"Denis\"])\n ::last-name (rand-nth [\"Ivanov\" \"Petrov\" \"Sidorov\" \"Kovalev\" \"Kuznetsov\" \"Voronoi\"])\n :", "end": 242, "score": 0.9743653535842896, "start": 236, "tag": "NAME", "value": "Petrov" }, { "context": "s\"])\n ::last-name (rand-nth [\"Ivanov\" \"Petrov\" \"Sidorov\" \"Kovalev\" \"Kuznetsov\" \"Voronoi\"])\n ::alias ", "end": 252, "score": 0.9987770915031433, "start": 245, "tag": "NAME", "value": "Sidorov" }, { "context": "last-name (rand-nth [\"Ivanov\" \"Petrov\" \"Sidorov\" \"Kovalev\" \"Kuznetsov\" \"Voronoi\"])\n ::alias (vec\n ", "end": 262, "score": 0.9995698928833008, "start": 255, "tag": "NAME", "value": "Kovalev" }, { "context": "(rand-nth [\"Ivanov\" \"Petrov\" \"Sidorov\" \"Kovalev\" \"Kuznetsov\" \"Voronoi\"])\n ::alias (vec\n (", "end": 274, "score": 0.9996026754379272, "start": 265, "tag": "NAME", "value": "Kuznetsov" }, { "context": "Ivanov\" \"Petrov\" \"Sidorov\" \"Kovalev\" \"Kuznetsov\" \"Voronoi\"])\n ::alias (vec\n (repeatedly", "end": 284, "score": 0.9995613694190979, "start": 277, "tag": "NAME", "value": "Voronoi" }, { "context": " (repeatedly (rand-int 10) #(rand-nth [\"A. C. Q. W.\" \"A. J. Finn\" \"A.A. Fair\" \"Aapeli\" \"Aaron Wolfe\"", "end": 372, "score": 0.6853989958763123, "start": 362, "tag": "NAME", "value": "A. C. Q. W" }, { "context": "peatedly (rand-int 10) #(rand-nth [\"A. C. Q. W.\" \"A. J. Finn\" \"A.A. Fair\" \"Aapeli\" \"Aaron Wolfe\" \"Abigail Van ", "end": 386, "score": 0.999826192855835, "start": 376, "tag": "NAME", "value": "A. J. Finn" }, { "context": "d-int 10) #(rand-nth [\"A. C. Q. W.\" \"A. J. Finn\" \"A.A. Fair\" \"Aapeli\" \"Aaron Wolfe\" \"Abigail Van Buren\" \"Jean", "end": 398, "score": 0.9997907280921936, "start": 389, "tag": "NAME", "value": "A.A. Fair" }, { "context": "rand-nth [\"A. C. Q. W.\" \"A. J. Finn\" \"A.A. Fair\" \"Aapeli\" \"Aaron Wolfe\" \"Abigail Van Buren\" \"Jeanne Philli", "end": 407, "score": 0.9997465014457703, "start": 401, "tag": "NAME", "value": "Aapeli" }, { "context": "[\"A. C. Q. W.\" \"A. J. Finn\" \"A.A. Fair\" \"Aapeli\" \"Aaron Wolfe\" \"Abigail Van Buren\" \"Jeanne Phillips\" \"Abram Ter", "end": 421, "score": 0.9998503923416138, "start": 410, "tag": "NAME", "value": "Aaron Wolfe" }, { "context": " \"A. J. Finn\" \"A.A. Fair\" \"Aapeli\" \"Aaron Wolfe\" \"Abigail Van Buren\" \"Jeanne Phillips\" \"Abram Tertz\" \"Abu Nuwas\" \"Act", "end": 441, "score": 0.9998400807380676, "start": 424, "tag": "NAME", "value": "Abigail Van Buren" }, { "context": "Fair\" \"Aapeli\" \"Aaron Wolfe\" \"Abigail Van Buren\" \"Jeanne Phillips\" \"Abram Tertz\" \"Abu Nuwas\" \"Acton Bell\" \"Adunis\"]", "end": 459, "score": 0.9998409152030945, "start": 444, "tag": "NAME", "value": "Jeanne Phillips" }, { "context": "ron Wolfe\" \"Abigail Van Buren\" \"Jeanne Phillips\" \"Abram Tertz\" \"Abu Nuwas\" \"Acton Bell\" \"Adunis\"])))\n ::sex ", "end": 473, "score": 0.9998472332954407, "start": 462, "tag": "NAME", "value": "Abram Tertz" }, { "context": "igail Van Buren\" \"Jeanne Phillips\" \"Abram Tertz\" \"Abu Nuwas\" \"Acton Bell\" \"Adunis\"])))\n ::sex (rand-n", "end": 485, "score": 0.9998407363891602, "start": 476, "tag": "NAME", "value": "Abu Nuwas" }, { "context": "ren\" \"Jeanne Phillips\" \"Abram Tertz\" \"Abu Nuwas\" \"Acton Bell\" \"Adunis\"])))\n ::sex (rand-nth [:male :fe", "end": 498, "score": 0.9998443722724915, "start": 488, "tag": "NAME", "value": "Acton Bell" }, { "context": "Phillips\" \"Abram Tertz\" \"Abu Nuwas\" \"Acton Bell\" \"Adunis\"])))\n ::sex (rand-nth [:male :female])\n ", "end": 507, "score": 0.9997317790985107, "start": 501, "tag": "NAME", "value": "Adunis" } ]
bench-src/people/core.cljc
davesann/odoyle-rules
0
(ns people.core) (def next-eid (volatile! 0)) (defn random-man [] {:db/id (str (vswap! next-eid inc)) ::name (rand-nth ["Ivan" "Petr" "Sergei" "Oleg" "Yuri" "Dmitry" "Fedor" "Denis"]) ::last-name (rand-nth ["Ivanov" "Petrov" "Sidorov" "Kovalev" "Kuznetsov" "Voronoi"]) ::alias (vec (repeatedly (rand-int 10) #(rand-nth ["A. C. Q. W." "A. J. Finn" "A.A. Fair" "Aapeli" "Aaron Wolfe" "Abigail Van Buren" "Jeanne Phillips" "Abram Tertz" "Abu Nuwas" "Acton Bell" "Adunis"]))) ::sex (rand-nth [:male :female]) ::age (rand-int 100) ::salary (rand-int 100000)}) (def people (repeatedly random-man)) (def people20k (shuffle (take 20000 people)))
28375
(ns people.core) (def next-eid (volatile! 0)) (defn random-man [] {:db/id (str (vswap! next-eid inc)) ::name (rand-nth ["<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>"]) ::last-name (rand-nth ["<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>"]) ::alias (vec (repeatedly (rand-int 10) #(rand-nth ["<NAME>." "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>" "<NAME>"]))) ::sex (rand-nth [:male :female]) ::age (rand-int 100) ::salary (rand-int 100000)}) (def people (repeatedly random-man)) (def people20k (shuffle (take 20000 people)))
true
(ns people.core) (def next-eid (volatile! 0)) (defn random-man [] {:db/id (str (vswap! next-eid inc)) ::name (rand-nth ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]) ::last-name (rand-nth ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]) ::alias (vec (repeatedly (rand-int 10) #(rand-nth ["PI:NAME:<NAME>END_PI." "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"]))) ::sex (rand-nth [:male :female]) ::age (rand-int 100) ::salary (rand-int 100000)}) (def people (repeatedly random-man)) (def people20k (shuffle (take 20000 people)))
[ { "context": ".native\n\n \"Building native iamges.\"\n\n {:author \"Adam Helinski\"}\n\n (:refer-clojure :exclude [agent])\n (:requir", "end": 73, "score": 0.9993374943733215, "start": 60, "tag": "NAME", "value": "Adam Helinski" }, { "context": "reparation.\"\n\n ;; Inspired by https://github.com/borkdude/refl/blob/4eefd89b1f70407ac3e50c84ce2a6ceae3babad", "end": 707, "score": 0.9442169070243835, "start": 699, "tag": "USERNAME", "value": "borkdude" } ]
script/script/native.clj
rosejn/convex.cljc
30
(ns script.native "Building native iamges." {:author "Adam Helinski"} (:refer-clojure :exclude [agent]) (:require [babashka.tasks :as bb.task] [cheshire.core :as cheshire] [clojure.java.io] [clojure.string])) ;;;;;;;;;; (defn agent "Starts the native-image-agent for tracing and output reflection configuration." [] (apply bb.task/shell "java" "-agentlib:native-image-agent=config-output-dir=./private/agent" *command-line-args*)) (defn reflect-config "Copies './private/agent/reflect-config.json' to the folder given as CLI arg after doing some preparation." ;; Inspired by https://github.com/borkdude/refl/blob/4eefd89b1f70407ac3e50c84ce2a6ceae3babad3/script/gen-reflect-config.clj#L64-L67 ;; ;; Without this, building the native image will fail. [] (cheshire/generate-stream (mapv (fn [hmap] (if (= (get hmap "name") "java.lang.reflect.Method") {"name" "java.lang.reflect.AccessibleObject" "methods" [{"name" "canAccess" "parameterTypes" ["java.lang.Object"]}]} hmap)) (cheshire/parse-stream (clojure.java.io/reader "./private/agent/reflect-config.json"))) (clojure.java.io/writer (str (or (first *command-line-args*) (throw (ex-info "Path to project root missing" {}))) "reflect-config.json")) {:pretty true})) (defn image "Builds a native image." [] (let [^String path (or (first *command-line-args*) (throw (ex-info "Path to directly-linked uberjar required" {})))] (apply bb.task/shell "native-image" "-jar" (str "build/uberjar/" (.substring path 1) ".jar") "--initialize-at-build-time" "--no-fallback" "--no-server" "-H:+ReportExceptionStackTraces" (rest *command-line-args*))))
77891
(ns script.native "Building native iamges." {:author "<NAME>"} (:refer-clojure :exclude [agent]) (:require [babashka.tasks :as bb.task] [cheshire.core :as cheshire] [clojure.java.io] [clojure.string])) ;;;;;;;;;; (defn agent "Starts the native-image-agent for tracing and output reflection configuration." [] (apply bb.task/shell "java" "-agentlib:native-image-agent=config-output-dir=./private/agent" *command-line-args*)) (defn reflect-config "Copies './private/agent/reflect-config.json' to the folder given as CLI arg after doing some preparation." ;; Inspired by https://github.com/borkdude/refl/blob/4eefd89b1f70407ac3e50c84ce2a6ceae3babad3/script/gen-reflect-config.clj#L64-L67 ;; ;; Without this, building the native image will fail. [] (cheshire/generate-stream (mapv (fn [hmap] (if (= (get hmap "name") "java.lang.reflect.Method") {"name" "java.lang.reflect.AccessibleObject" "methods" [{"name" "canAccess" "parameterTypes" ["java.lang.Object"]}]} hmap)) (cheshire/parse-stream (clojure.java.io/reader "./private/agent/reflect-config.json"))) (clojure.java.io/writer (str (or (first *command-line-args*) (throw (ex-info "Path to project root missing" {}))) "reflect-config.json")) {:pretty true})) (defn image "Builds a native image." [] (let [^String path (or (first *command-line-args*) (throw (ex-info "Path to directly-linked uberjar required" {})))] (apply bb.task/shell "native-image" "-jar" (str "build/uberjar/" (.substring path 1) ".jar") "--initialize-at-build-time" "--no-fallback" "--no-server" "-H:+ReportExceptionStackTraces" (rest *command-line-args*))))
true
(ns script.native "Building native iamges." {:author "PI:NAME:<NAME>END_PI"} (:refer-clojure :exclude [agent]) (:require [babashka.tasks :as bb.task] [cheshire.core :as cheshire] [clojure.java.io] [clojure.string])) ;;;;;;;;;; (defn agent "Starts the native-image-agent for tracing and output reflection configuration." [] (apply bb.task/shell "java" "-agentlib:native-image-agent=config-output-dir=./private/agent" *command-line-args*)) (defn reflect-config "Copies './private/agent/reflect-config.json' to the folder given as CLI arg after doing some preparation." ;; Inspired by https://github.com/borkdude/refl/blob/4eefd89b1f70407ac3e50c84ce2a6ceae3babad3/script/gen-reflect-config.clj#L64-L67 ;; ;; Without this, building the native image will fail. [] (cheshire/generate-stream (mapv (fn [hmap] (if (= (get hmap "name") "java.lang.reflect.Method") {"name" "java.lang.reflect.AccessibleObject" "methods" [{"name" "canAccess" "parameterTypes" ["java.lang.Object"]}]} hmap)) (cheshire/parse-stream (clojure.java.io/reader "./private/agent/reflect-config.json"))) (clojure.java.io/writer (str (or (first *command-line-args*) (throw (ex-info "Path to project root missing" {}))) "reflect-config.json")) {:pretty true})) (defn image "Builds a native image." [] (let [^String path (or (first *command-line-args*) (throw (ex-info "Path to directly-linked uberjar required" {})))] (apply bb.task/shell "native-image" "-jar" (str "build/uberjar/" (.substring path 1) ".jar") "--initialize-at-build-time" "--no-fallback" "--no-server" "-H:+ReportExceptionStackTraces" (rest *command-line-args*))))
[ { "context": ".01Z\"\n last {:m0 {:key \"m0\"\n :value 50.0\n", "end": 577, "score": 0.9717007875442505, "start": 575, "tag": "KEY", "value": "m0" }, { "context": "tion}\n :m1 {:key \"m1\"\n :value 51\n ", "end": 733, "score": 0.9441585540771484, "start": 731, "tag": "KEY", "value": "m1" } ]
server/test/com/sixsq/slipstream/ssclj/resources/spec/sla_assessment_test.cljc
mF2C/cimi
0
(ns com.sixsq.slipstream.ssclj.resources.spec.sla-assessment-test (:require [clojure.spec.alpha :as s] [clojure.test :refer [are deftest is]] [com.sixsq.slipstream.ssclj.resources.common.schema :as schema] [com.sixsq.slipstream.ssclj.resources.common.utils :as u] [com.sixsq.slipstream.ssclj.resources.spec.common :as c])) (deftest check-assessment-resource-schema (let [ first_execution "2019-07-08T10:00:00.01Z" last_execution "2019-07-08T14:57:00.01Z" last {:m0 {:key "m0" :value 50.0 :datetime first_execution} :m1 {:key "m1" :value 51 :datetime last_execution}} guarantees {:gt0 {:first_execution first_execution :last_execution last_execution :last_values last} } initial-assessment {:first_execution first_execution :last_execution last_execution }] ; Not working - testing directly in agreement-test ; (is (s/valid? :cimi/sla-assessment/assessment initial-assessment)) ; (is (s/valid? :cimi/sla-assessment/assessment (assoc initial-assessment :guarantees guarantees))) ; (is (not (s/valid? :cimi/sla-assessment/assessment (assoc initial-assessment :bad-field "bla bla bla")))) ))
83969
(ns com.sixsq.slipstream.ssclj.resources.spec.sla-assessment-test (:require [clojure.spec.alpha :as s] [clojure.test :refer [are deftest is]] [com.sixsq.slipstream.ssclj.resources.common.schema :as schema] [com.sixsq.slipstream.ssclj.resources.common.utils :as u] [com.sixsq.slipstream.ssclj.resources.spec.common :as c])) (deftest check-assessment-resource-schema (let [ first_execution "2019-07-08T10:00:00.01Z" last_execution "2019-07-08T14:57:00.01Z" last {:m0 {:key "<KEY>" :value 50.0 :datetime first_execution} :m1 {:key "<KEY>" :value 51 :datetime last_execution}} guarantees {:gt0 {:first_execution first_execution :last_execution last_execution :last_values last} } initial-assessment {:first_execution first_execution :last_execution last_execution }] ; Not working - testing directly in agreement-test ; (is (s/valid? :cimi/sla-assessment/assessment initial-assessment)) ; (is (s/valid? :cimi/sla-assessment/assessment (assoc initial-assessment :guarantees guarantees))) ; (is (not (s/valid? :cimi/sla-assessment/assessment (assoc initial-assessment :bad-field "bla bla bla")))) ))
true
(ns com.sixsq.slipstream.ssclj.resources.spec.sla-assessment-test (:require [clojure.spec.alpha :as s] [clojure.test :refer [are deftest is]] [com.sixsq.slipstream.ssclj.resources.common.schema :as schema] [com.sixsq.slipstream.ssclj.resources.common.utils :as u] [com.sixsq.slipstream.ssclj.resources.spec.common :as c])) (deftest check-assessment-resource-schema (let [ first_execution "2019-07-08T10:00:00.01Z" last_execution "2019-07-08T14:57:00.01Z" last {:m0 {:key "PI:KEY:<KEY>END_PI" :value 50.0 :datetime first_execution} :m1 {:key "PI:KEY:<KEY>END_PI" :value 51 :datetime last_execution}} guarantees {:gt0 {:first_execution first_execution :last_execution last_execution :last_values last} } initial-assessment {:first_execution first_execution :last_execution last_execution }] ; Not working - testing directly in agreement-test ; (is (s/valid? :cimi/sla-assessment/assessment initial-assessment)) ; (is (s/valid? :cimi/sla-assessment/assessment (assoc initial-assessment :guarantees guarantees))) ; (is (not (s/valid? :cimi/sla-assessment/assessment (assoc initial-assessment :bad-field "bla bla bla")))) ))
[ { "context": "getResponse \"{\\\"method\\\":\\\"login\\\",\\\"userName\\\":\\\"Pavel\\\",\\\"password\\\":\\\"1\\\"}\" 1)) \"Failed! Incorrect use", "end": 485, "score": 0.9995958209037781, "start": 480, "tag": "USERNAME", "value": "Pavel" }, { "context": "\":\\\"login\\\",\\\"userName\\\":\\\"Pavel\\\",\\\"password\\\":\\\"1\\\"}\" 1)) \"Failed! Incorrect user name or password\"", "end": 504, "score": 0.8924291133880615, "start": 503, "tag": "PASSWORD", "value": "1" }, { "context": "onse \"{\\\"method\\\":\\\"registration\\\",\\\"userName\\\":\\\"Pavel\\\",\\\"password\\\":\\\"1\\\"}\" 1)) \"Success\")))\n\n (testi", "end": 668, "score": 0.9995594024658203, "start": 663, "tag": "USERNAME", "value": "Pavel" }, { "context": "istration\\\",\\\"userName\\\":\\\"Pavel\\\",\\\"password\\\":\\\"1\\\"}\" 1)) \"Success\")))\n\n (testing \"Login\"\n (is ", "end": 687, "score": 0.6690153479576111, "start": 686, "tag": "PASSWORD", "value": "1" }, { "context": "getResponse \"{\\\"method\\\":\\\"login\\\",\\\"userName\\\":\\\"Pavel\\\",\\\"password\\\":\\\"1\\\"}\" 1)) \"Success\")))\n\n\n (test", "end": 805, "score": 0.9995333552360535, "start": 800, "tag": "USERNAME", "value": "Pavel" }, { "context": "\":\\\"login\\\",\\\"userName\\\":\\\"Pavel\\\",\\\"password\\\":\\\"1\\\"}\" 1)) \"Success\")))\n\n\n (testing \"Room list\"\n ", "end": 824, "score": 0.9830034375190735, "start": 823, "tag": "PASSWORD", "value": "1" } ]
Labs/FP/test/chat/logic_test.clj
VerkhovtsovPavel/BSUIR_Labs
1
(ns chat.logic-test (:require [clojure.test :refer :all] [chat.model.dispatcher :refer :all] [chat.data.persistance :as pers] [monger.core :as mcore])) (defn use-db [f] (binding [pers/db (mcore/get-db pers/conn "chat-test")] (f) (mcore/drop-db pers/conn "chat-test"))) (use-fixtures :once use-db) (deftest logic-test (testing "Login without registration" (is (= (:result (getResponse "{\"method\":\"login\",\"userName\":\"Pavel\",\"password\":\"1\"}" 1)) "Failed! Incorrect user name or password"))) (testing "Registration" (is (= (:result (getResponse "{\"method\":\"registration\",\"userName\":\"Pavel\",\"password\":\"1\"}" 1)) "Success"))) (testing "Login" (is (= (:result (getResponse "{\"method\":\"login\",\"userName\":\"Pavel\",\"password\":\"1\"}" 1)) "Success"))) (testing "Room list" (is (= (:result (getResponse "{\"method\":\"roomList\"}" 1)) ()))) (let [roomName "TestRoom"] (testing "Add room" (is (= (:result (getResponse (str "{\"method\":\"newRoom\",\"roomName\": \"" roomName "\" ,\"part\":[]}") 1)) roomName))) (testing "Room list" (is (= (:result (getResponse "{\"method\":\"roomList\"}" 1)) (list roomName)))) (testing "Enter to invalid room" (is (= (:result (getResponse "{\"method\":\"roomEnter\",\"room\":\"Secret Room\"}" 1)) "Illegal access"))) (testing "Enter to valid room" (is (= (:result (getResponse (str "{\"method\":\"roomEnter\",\"room\":\"" roomName "\"}") 1)) "Ok"))) (testing "Leave room" (is (= (:result (getResponse (str "{\"method\" : \"roomLeave\", \"room\" : \"" roomName "\"}") 1)) "Ok")))) (testing "Send message" (is (= (:result (getResponse "{\"method\":\"message\",\"text\":\"4\",\"room\":\"TestRoom\"}" 1)) "4"))) (testing "Search message (empty)" (is (= (:result (getResponse "{\"method\":\"search\",\"query\":\"(current (with-text \\\"5\\\"))\",\"room\":\"TestRoom\"}" 1)) ()))) (testing "Search message" (is (= (:text (first (:result (getResponse "{\"method\":\"search\",\"query\":\"(current (with-text \\\"4\\\"))\",\"room\":\"TestRoom\"}" 1)))) "4"))))
79485
(ns chat.logic-test (:require [clojure.test :refer :all] [chat.model.dispatcher :refer :all] [chat.data.persistance :as pers] [monger.core :as mcore])) (defn use-db [f] (binding [pers/db (mcore/get-db pers/conn "chat-test")] (f) (mcore/drop-db pers/conn "chat-test"))) (use-fixtures :once use-db) (deftest logic-test (testing "Login without registration" (is (= (:result (getResponse "{\"method\":\"login\",\"userName\":\"Pavel\",\"password\":\"<PASSWORD>\"}" 1)) "Failed! Incorrect user name or password"))) (testing "Registration" (is (= (:result (getResponse "{\"method\":\"registration\",\"userName\":\"Pavel\",\"password\":\"<PASSWORD>\"}" 1)) "Success"))) (testing "Login" (is (= (:result (getResponse "{\"method\":\"login\",\"userName\":\"Pavel\",\"password\":\"<PASSWORD>\"}" 1)) "Success"))) (testing "Room list" (is (= (:result (getResponse "{\"method\":\"roomList\"}" 1)) ()))) (let [roomName "TestRoom"] (testing "Add room" (is (= (:result (getResponse (str "{\"method\":\"newRoom\",\"roomName\": \"" roomName "\" ,\"part\":[]}") 1)) roomName))) (testing "Room list" (is (= (:result (getResponse "{\"method\":\"roomList\"}" 1)) (list roomName)))) (testing "Enter to invalid room" (is (= (:result (getResponse "{\"method\":\"roomEnter\",\"room\":\"Secret Room\"}" 1)) "Illegal access"))) (testing "Enter to valid room" (is (= (:result (getResponse (str "{\"method\":\"roomEnter\",\"room\":\"" roomName "\"}") 1)) "Ok"))) (testing "Leave room" (is (= (:result (getResponse (str "{\"method\" : \"roomLeave\", \"room\" : \"" roomName "\"}") 1)) "Ok")))) (testing "Send message" (is (= (:result (getResponse "{\"method\":\"message\",\"text\":\"4\",\"room\":\"TestRoom\"}" 1)) "4"))) (testing "Search message (empty)" (is (= (:result (getResponse "{\"method\":\"search\",\"query\":\"(current (with-text \\\"5\\\"))\",\"room\":\"TestRoom\"}" 1)) ()))) (testing "Search message" (is (= (:text (first (:result (getResponse "{\"method\":\"search\",\"query\":\"(current (with-text \\\"4\\\"))\",\"room\":\"TestRoom\"}" 1)))) "4"))))
true
(ns chat.logic-test (:require [clojure.test :refer :all] [chat.model.dispatcher :refer :all] [chat.data.persistance :as pers] [monger.core :as mcore])) (defn use-db [f] (binding [pers/db (mcore/get-db pers/conn "chat-test")] (f) (mcore/drop-db pers/conn "chat-test"))) (use-fixtures :once use-db) (deftest logic-test (testing "Login without registration" (is (= (:result (getResponse "{\"method\":\"login\",\"userName\":\"Pavel\",\"password\":\"PI:PASSWORD:<PASSWORD>END_PI\"}" 1)) "Failed! Incorrect user name or password"))) (testing "Registration" (is (= (:result (getResponse "{\"method\":\"registration\",\"userName\":\"Pavel\",\"password\":\"PI:PASSWORD:<PASSWORD>END_PI\"}" 1)) "Success"))) (testing "Login" (is (= (:result (getResponse "{\"method\":\"login\",\"userName\":\"Pavel\",\"password\":\"PI:PASSWORD:<PASSWORD>END_PI\"}" 1)) "Success"))) (testing "Room list" (is (= (:result (getResponse "{\"method\":\"roomList\"}" 1)) ()))) (let [roomName "TestRoom"] (testing "Add room" (is (= (:result (getResponse (str "{\"method\":\"newRoom\",\"roomName\": \"" roomName "\" ,\"part\":[]}") 1)) roomName))) (testing "Room list" (is (= (:result (getResponse "{\"method\":\"roomList\"}" 1)) (list roomName)))) (testing "Enter to invalid room" (is (= (:result (getResponse "{\"method\":\"roomEnter\",\"room\":\"Secret Room\"}" 1)) "Illegal access"))) (testing "Enter to valid room" (is (= (:result (getResponse (str "{\"method\":\"roomEnter\",\"room\":\"" roomName "\"}") 1)) "Ok"))) (testing "Leave room" (is (= (:result (getResponse (str "{\"method\" : \"roomLeave\", \"room\" : \"" roomName "\"}") 1)) "Ok")))) (testing "Send message" (is (= (:result (getResponse "{\"method\":\"message\",\"text\":\"4\",\"room\":\"TestRoom\"}" 1)) "4"))) (testing "Search message (empty)" (is (= (:result (getResponse "{\"method\":\"search\",\"query\":\"(current (with-text \\\"5\\\"))\",\"room\":\"TestRoom\"}" 1)) ()))) (testing "Search message" (is (= (:text (first (:result (getResponse "{\"method\":\"search\",\"query\":\"(current (with-text \\\"4\\\"))\",\"room\":\"TestRoom\"}" 1)))) "4"))))
[ { "context": "> empty-state\n (add-player \"tim\" \"sharon\" \"louise\")\n (add-c", "end": 171, "score": 0.9986152648925781, "start": 168, "tag": "NAME", "value": "tim" }, { "context": "y-state\n (add-player \"tim\" \"sharon\" \"louise\")\n (add-cards \"tim", "end": 180, "score": 0.9986940622329712, "start": 174, "tag": "NAME", "value": "sharon" }, { "context": " (add-player \"tim\" \"sharon\" \"louise\")\n (add-cards \"tim\" [\"AC\" \"", "end": 189, "score": 0.9972783923149109, "start": 183, "tag": "NAME", "value": "louise" }, { "context": "ron\" \"louise\")\n (add-cards \"tim\" [\"AC\" \"KC\" \"JC\"])\n (add-ca", "end": 230, "score": 0.6356819868087769, "start": 227, "tag": "NAME", "value": "tim" }, { "context": "C\" \"KC\" \"JC\"])\n (add-cards \"sharon\" [\"2D\" \"4D\" \"6D\"])\n (add-ca", "end": 291, "score": 0.9944512248039246, "start": 285, "tag": "NAME", "value": "sharon" }, { "context": " (dealt-state)\n (bid \"sharon\" 0)\n (bid \"louise\" 3)\n ", "end": 444, "score": 0.9854227304458618, "start": 438, "tag": "NAME", "value": "sharon" }, { "context": " (bid \"louise\" 3)\n (bid \"tim\" 0)\n ;; first hand\n ", "end": 521, "score": 0.8828547596931458, "start": 518, "tag": "NAME", "value": "tim" }, { "context": " (play \"tim\" \"AC\")\n (play \"sharon\" \"2D\")\n ;; second hand\n ", "end": 684, "score": 0.9913502931594849, "start": 678, "tag": "NAME", "value": "sharon" }, { "context": " ;; second hand\n (play \"tim\" \"KC\")\n (play \"sharon\" \"4D\"", "end": 763, "score": 0.5455320477485657, "start": 760, "tag": "NAME", "value": "tim" }, { "context": " (play \"tim\" \"KC\")\n (play \"sharon\" \"4D\")\n (play \"louise\" \"2S\"", "end": 807, "score": 0.989343523979187, "start": 801, "tag": "NAME", "value": "sharon" }, { "context": " ;; third hand\n (play \"tim\" \"JC\")\n (play \"sharon\" \"6D\"", "end": 929, "score": 0.7759544253349304, "start": 926, "tag": "NAME", "value": "tim" }, { "context": " (play \"tim\" \"JC\")\n (play \"sharon\" \"6D\")\n (play \"louise\" \"3S\"", "end": 973, "score": 0.9861382246017456, "start": 967, "tag": "NAME", "value": "sharon" }, { "context": "empty-state\n (add-player \"tim\" \"sharon\" \"louise\")\n (add", "end": 1163, "score": 0.9988973736763, "start": 1160, "tag": "NAME", "value": "tim" }, { "context": "state\n (add-player \"tim\" \"sharon\" \"louise\")\n (add-cards \"t", "end": 1172, "score": 0.9985030889511108, "start": 1166, "tag": "NAME", "value": "sharon" }, { "context": " (add-player \"tim\" \"sharon\" \"louise\")\n (add-cards \"tim\" [\"AD\"", "end": 1181, "score": 0.996876060962677, "start": 1175, "tag": "NAME", "value": "louise" }, { "context": "n\" \"louise\")\n (add-cards \"tim\" [\"AD\" \"2C\" \"3C\"])\n (add-", "end": 1224, "score": 0.8920307159423828, "start": 1221, "tag": "NAME", "value": "tim" }, { "context": " \"2C\" \"3C\"])\n (add-cards \"sharon\" [\"AH\" \"2S\" \"3S\"])\n (add-", "end": 1287, "score": 0.9780797362327576, "start": 1281, "tag": "NAME", "value": "sharon" }, { "context": " (dealt-state)\n (bid \"sharon\" 0)\n (bid \"louise\" 0)\n ", "end": 1446, "score": 0.9730343818664551, "start": 1440, "tag": "NAME", "value": "sharon" }, { "context": " (bid \"louise\" 0)\n (bid \"tim\" 2)\n ;; first hand\n ", "end": 1527, "score": 0.898002028465271, "start": 1524, "tag": "NAME", "value": "tim" }, { "context": "(play \"tim\" \"AD\")\n (play \"sharon\" \"2S\")\n (play \"louise\" \"2", "end": 1652, "score": 0.976689875125885, "start": 1646, "tag": "NAME", "value": "sharon" }, { "context": " ;; second hand\n (play \"tim\" \"2C\")\n (play \"sharon\" \"3", "end": 1781, "score": 0.7478275895118713, "start": 1778, "tag": "NAME", "value": "tim" }, { "context": "(play \"tim\" \"2C\")\n (play \"sharon\" \"3S\")\n (play \"louise\" \"A", "end": 1827, "score": 0.9667387008666992, "start": 1821, "tag": "NAME", "value": "sharon" }, { "context": "(play \"tim\" \"3C\")\n (play \"sharon\" \"AH\"))))\n", "end": 2047, "score": 0.8300668001174927, "start": 2041, "tag": "NAME", "value": "sharon" } ]
test/bidpitch/test/scenarios.clj
tlicata/bidpitch
1
(ns bidpitch.test.scenarios (:use clojure.test bidpitch.cards bidpitch.game)) (def dont-make-bid (-> empty-state (add-player "tim" "sharon" "louise") (add-cards "tim" ["AC" "KC" "JC"]) (add-cards "sharon" ["2D" "4D" "6D"]) (add-cards "louise" ["9C" "2S" "3S"]) (dealt-state) (bid "sharon" 0) (bid "louise" 3) (bid "tim" 0) ;; first hand (play "louise" "9C") (play "tim" "AC") (play "sharon" "2D") ;; second hand (play "tim" "KC") (play "sharon" "4D") (play "louise" "2S") ;; third hand (play "tim" "JC") (play "sharon" "6D") (play "louise" "3S"))) (def tied-game-pts (binding [*reconcile-end-game* false] (-> empty-state (add-player "tim" "sharon" "louise") (add-cards "tim" ["AD" "2C" "3C"]) (add-cards "sharon" ["AH" "2S" "3S"]) (add-cards "louise" ["AC" "2D" "2H"]) (dealt-state) (bid "sharon" 0) (bid "louise" 0) (bid "tim" 2) ;; first hand (play "tim" "AD") (play "sharon" "2S") (play "louise" "2D") ;; second hand (play "tim" "2C") (play "sharon" "3S") (play "louise" "AC") ;; third hand (play "louise" "2H") (play "tim" "3C") (play "sharon" "AH"))))
4613
(ns bidpitch.test.scenarios (:use clojure.test bidpitch.cards bidpitch.game)) (def dont-make-bid (-> empty-state (add-player "<NAME>" "<NAME>" "<NAME>") (add-cards "<NAME>" ["AC" "KC" "JC"]) (add-cards "<NAME>" ["2D" "4D" "6D"]) (add-cards "louise" ["9C" "2S" "3S"]) (dealt-state) (bid "<NAME>" 0) (bid "louise" 3) (bid "<NAME>" 0) ;; first hand (play "louise" "9C") (play "tim" "AC") (play "<NAME>" "2D") ;; second hand (play "<NAME>" "KC") (play "<NAME>" "4D") (play "louise" "2S") ;; third hand (play "<NAME>" "JC") (play "<NAME>" "6D") (play "louise" "3S"))) (def tied-game-pts (binding [*reconcile-end-game* false] (-> empty-state (add-player "<NAME>" "<NAME>" "<NAME>") (add-cards "<NAME>" ["AD" "2C" "3C"]) (add-cards "<NAME>" ["AH" "2S" "3S"]) (add-cards "louise" ["AC" "2D" "2H"]) (dealt-state) (bid "<NAME>" 0) (bid "louise" 0) (bid "<NAME>" 2) ;; first hand (play "tim" "AD") (play "<NAME>" "2S") (play "louise" "2D") ;; second hand (play "<NAME>" "2C") (play "<NAME>" "3S") (play "louise" "AC") ;; third hand (play "louise" "2H") (play "tim" "3C") (play "<NAME>" "AH"))))
true
(ns bidpitch.test.scenarios (:use clojure.test bidpitch.cards bidpitch.game)) (def dont-make-bid (-> empty-state (add-player "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") (add-cards "PI:NAME:<NAME>END_PI" ["AC" "KC" "JC"]) (add-cards "PI:NAME:<NAME>END_PI" ["2D" "4D" "6D"]) (add-cards "louise" ["9C" "2S" "3S"]) (dealt-state) (bid "PI:NAME:<NAME>END_PI" 0) (bid "louise" 3) (bid "PI:NAME:<NAME>END_PI" 0) ;; first hand (play "louise" "9C") (play "tim" "AC") (play "PI:NAME:<NAME>END_PI" "2D") ;; second hand (play "PI:NAME:<NAME>END_PI" "KC") (play "PI:NAME:<NAME>END_PI" "4D") (play "louise" "2S") ;; third hand (play "PI:NAME:<NAME>END_PI" "JC") (play "PI:NAME:<NAME>END_PI" "6D") (play "louise" "3S"))) (def tied-game-pts (binding [*reconcile-end-game* false] (-> empty-state (add-player "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI") (add-cards "PI:NAME:<NAME>END_PI" ["AD" "2C" "3C"]) (add-cards "PI:NAME:<NAME>END_PI" ["AH" "2S" "3S"]) (add-cards "louise" ["AC" "2D" "2H"]) (dealt-state) (bid "PI:NAME:<NAME>END_PI" 0) (bid "louise" 0) (bid "PI:NAME:<NAME>END_PI" 2) ;; first hand (play "tim" "AD") (play "PI:NAME:<NAME>END_PI" "2S") (play "louise" "2D") ;; second hand (play "PI:NAME:<NAME>END_PI" "2C") (play "PI:NAME:<NAME>END_PI" "3S") (play "louise" "AC") ;; third hand (play "louise" "2H") (play "tim" "3C") (play "PI:NAME:<NAME>END_PI" "AH"))))
[ { "context": " :hits \"Ergebnisse\"}\n :login {:nickname \"Benutzername\"\n :password \"Passwort\"\n ", "end": 3018, "score": 0.9994852542877197, "start": 3006, "tag": "USERNAME", "value": "Benutzername" }, { "context": "ickname \"Benutzername\"\n :password \"Passwort\"\n :hhu-ldap \"Wir benutzen das Pers", "end": 3055, "score": 0.9950088262557983, "start": 3047, "tag": "PASSWORD", "value": "Passwort" }, { "context": " :origin \"Herkunft\"\n :author \"Autor\"}\n :tooltip {:discuss/start \"Argument erze", "end": 5534, "score": 0.5495599508285522, "start": 5529, "tag": "NAME", "value": "Autor" }, { "context": " :hits \"Results\"}\n :login {:nickname \"Nickname\"\n :password \"Password\"\n ", "end": 8287, "score": 0.9989914894104004, "start": 8279, "tag": "USERNAME", "value": "Nickname" }, { "context": " {:nickname \"Nickname\"\n :password \"Password\"\n :hhu-ldap \"We are using the Regi", "end": 8324, "score": 0.9985861778259277, "start": 8316, "tag": "PASSWORD", "value": "Password" }, { "context": " :origin \"Origin\"\n :author \"Author\"}\n :tooltip {:discuss/start \"Create Argume", "end": 10472, "score": 0.8052806258201599, "start": 10466, "tag": "NAME", "value": "Author" } ]
src/discuss/translations.cljs
hhucn/discuss
4
(ns discuss.translations (:require [discuss.utils.common :as lib] [cljs.spec.alpha :as s])) (def available [[:de "deutsch"] [:en "english"]]) (def translations {:de {:common {:and "und" :argue/con "denkt nicht, dass" :argue/that "denkt, dass" :author "Autor" :back "Zurück" :because "weil" :chars-remaining "noch mind. %d Zeichen eingeben" :close "Schließen" :delete "Löschen" :hello "Hallo" :issue "Diskussionsthema" :login "Login" :logout "Logout" :options "Einstellungen" :select "Auswählen" :save "Speichern" :show-discuss "Zeige discuss" :start-discussion "Starte die Diskussion" :that "dass"} :clipboard {:heading "Zwischenablage" :instruction "Wählen Sie eine Referenz aus dieser Liste aus, um beim Erzeugen eines neuen Arguments diese Referenz mit dem neuen Argument zu verknüpfen."} :create/argument {:header "Erzeugen Sie ein Argument zu einer Textstelle" :short "Neues Argument zur Referenz erstellen" :lead "Sie können hier Position zu einer Textstelle beziehen." :logged-in "Füllen Sie dazu die folgenden Felder aus." :not-logged-in "Aber vorher müssen Sie sich einlogggen."} :discussion {:add-position "Nichts von all dem. Ich habe eine andere Idee" :add-position-heading "Ich denke, " :add-position-placeholder "wir dieses oder jenes machen sollten" :add-reason-placeholder "dieser Grund dafür existiert" :bubble/congrats "Sie haben das Ende der Diskussion erreicht. Suchen Sie sich einen anderen Einstiegspunkt in dem Artikel, um weiter zu diskutieren." :current "Aktuelle Diskussion" :reference/missing "Sie müssen sich auf eine Textstelle beziehen" :restart "Neustarten" :submit "Abschicken"} :eden {:overview "Meine Argumente" :overview/lead "Finden Sie hier Ihre Argumente, welche Sie in verschiedenen Diskussionen eingeführt haben und springen Sie direkt in die Diskussionen hinein." :arguments/construct "Neues Argument erstellen" :arguments/not-found "Es konnten noch keine Argumente von Ihnen gefunden werden. Ein guter Zeitpunkt eine Diskussion zu wählen und mit anderen Benutzern zu diskutieren!" :arguments/show "Meine Argumente anzeigen"} :errors {:login "Login fehlgeschlagen. Vermutlich sind die Zugangsdaten nicht korrekt."} :find {:statement "Finde Aussage in Diskussion" :hits "Ergebnisse"} :login {:nickname "Benutzername" :password "Passwort" :hhu-ldap "Wir benutzen das Personenverzeichnis der Heinrich-Heine-Universität Düsseldorf. Alle Daten und Informationen werden natürlich SSL-verschlüsselt gesendet und nach Erhalt unter keinen Umständen an Dritte weitergegeben." :item "Hier klicken, damit Sie sich einloggen und eine neue Aussage hinzufügen können"} :nav {:home "Start" :find "Suchen" :eden "Meine Argumente"} :options {:current "Aktuell" :default "Standard" :delete "Löschen" :heading "Einstellungen" :lang "Interface-Sprache" :new-route "Neue Route" :reconnect "Neu verbinden" :reset "Zurücksetzen" :routes "Routen" :save "Speichere"} :references {:jump "Springe in die Diskussion" :save/to-clipboard "In Zwischenablage" :usages/view-heading "Interaktionen mit dem Artikel" :usages/lead "Beziehen Sie sich hier auf die ausgewählte Referenz oder schauen Sie sich an, wo diese Referenz bereits in der Diskussion verwendet wurde." :usages/not-found-lead "Argument konnte nicht gefunden werden" :usages/not-found-body "Vielleicht wurden die mit dieser Referenz verknüpften Argumente entfernt" :usages/list "Hier ist eine Liste der bisherigen Verwendungen dieser Textstelle in anderen Argumenten" :where-used "Wo wird diese Referenz verwendet?" :find-statement "Finde Aussage in der Diskussion" :clipboard "Ziehen Sie diese Referenzen in das Textfeld beim Erzeugen eines neuen Arguments hinein, um die Referenz zu nutzen." :ask-to-add "Möchten Sie Ihre Aussage durch eine Referenz von dieser Seite stützen? Dann markieren Sie einfach einen Teil des Textes mit der Maus." :has-to-add "Um sich auf eine Stelle im Artikel zu beziehen, müssen Sie die Stelle mit der Maus markieren. Dann erscheint der Text in diesem Textfeld." :disabled/tooltip "Dieses Feld kann nicht direkt modifiziert werden. Bitte markieren Sie die gewünschte Stelle direkt auf der Webseite. Dieses Feld füllt sich dann automatisch."} :search {:reuse "Statement auswählen" :origin "Herkunft" :author "Autor"} :tooltip {:discuss/start "Argument erzeugen"} :undercut {:text "Laut %s kann man die Aussage, dass \"%s\", nicht damit begründen, dass \"%s\", weil %s."}} :en {:common {:and "and" :argue/con "does not think that" :argue/that "thinks that" :author "Author" :back "Back" :because "because" :chars-remaining "add at least %d more character(s)" :close "Close" :delete "Delete" :hello "Hello" :issue "Issue" :login "Login" :logout "Logout" :options "Options" :select "Select" :save "Save" :show-discuss "Show discuss" :start-discussion "Start Discussion" :that "that"} :clipboard {:heading "Clipboard" :instruction "Select a reference from this list on new argument creation to link the reference with your argument."} :create/argument {:header "Create an argument with a text reference" :short "Create Argument with Reference" :lead "You can refer position to a text passage here." :logged-in "Please fill in the following fields." :not-logged-in "But first you need to login."} :discussion {:add-position "Neither of the above, I have a different idea" :add-position-heading "I think that" :add-position-placeholder "we should do this or that" :add-reason-placeholder "of this reason" :bubble/congrats "You've reached the end of the current discussion. Find a different position in the article to start over again." :current "Current Discussion" :reference/missing "You need to refer to a text passage" :restart "Restart" :submit "Submit"} :eden {:overview "My Arguments" :overview/lead "You provided these arguments in your discussions. Create a list of them and directly jump into the discussion." :arguments/construct "Construct new Argument" :arguments/not-found "Currently there are no arguments from your account. A good starting point to find a discussion and start adding your own arguments!" :arguments/show "Show my Arguments"} :errors {:login "Could not login. Maybe your credentials are wrong."} :find {:statement "Find statement in the discussion" :hits "Results"} :login {:nickname "Nickname" :password "Password" :hhu-ldap "We are using the Register of Persons of the Heinrich-Heine-University Düsseldorf. All data and information are of course sent SSL encrypted and will never be passed on to any third parties after receipt." :item "Click here to authenticate and to be able to submit your own statements"} :nav {:home "Home" :eden "My Arguments" :find "Find"} :options {:current "Current" :default "Default" :delete "Delete" :heading "Options" :lang "Interface Language" :new-route "Set new Route" :reconnect "Reconnect" :reset "Reset to Defaults" :routes "Routes" :save "Save"} :references {:jump "Jump into the discussion" :save/to-clipboard "Save into Clipboard" :usages/view-heading "Interacting with the Article" :usages/lead "Create your own argument based on the text selection or take a look at those arguments, which already refer to this position." :usages/not-found-lead "No assigned arguments found" :usages/not-found-body "Maybe the assigned arguments have been removed" :usages/list "Here you can find a list of those arguments, which refer to the selected text passage" :where-used "Where has this reference been used?" :ask-to-add "Do you want to add a reference from this site to your statement? Just select the desired text-passage and it will be inserted in this field." :has-to-add "To refer position to a passage in the article, you have to select the desired text-passage with your mouse selection." :disabled/tooltip "You can't modify this field. Please select the appropriate text-passage from the website. The selection will be automatically added to this field."} :search {:reuse "Select Statement" :origin "Origin" :author "Author"} :tooltip {:discuss/start "Create Argument"} :undercut {:text "According to %s, the statement that \"%s\" can not be explained by the fact that \"%s\", because %s."}}}) (defn- prepend-translation "Lookup given key and prepend some string to it." [group key prepend] (str prepend (get-in translations [(lib/language) group key]))) (defn translate "Get translation string according to currently configured language." ([group key option] (cond (= :space option) (prepend-translation group key " ") :else (prepend-translation group key ""))) ([group key] (translate group key :default))) (s/fdef translate :args (s/or :option (s/cat :group keyword? :key keyword? :option keyword?) :no-option (s/cat :group keyword? :key keyword?)) :ret string?)
12112
(ns discuss.translations (:require [discuss.utils.common :as lib] [cljs.spec.alpha :as s])) (def available [[:de "deutsch"] [:en "english"]]) (def translations {:de {:common {:and "und" :argue/con "denkt nicht, dass" :argue/that "denkt, dass" :author "Autor" :back "Zurück" :because "weil" :chars-remaining "noch mind. %d Zeichen eingeben" :close "Schließen" :delete "Löschen" :hello "Hallo" :issue "Diskussionsthema" :login "Login" :logout "Logout" :options "Einstellungen" :select "Auswählen" :save "Speichern" :show-discuss "Zeige discuss" :start-discussion "Starte die Diskussion" :that "dass"} :clipboard {:heading "Zwischenablage" :instruction "Wählen Sie eine Referenz aus dieser Liste aus, um beim Erzeugen eines neuen Arguments diese Referenz mit dem neuen Argument zu verknüpfen."} :create/argument {:header "Erzeugen Sie ein Argument zu einer Textstelle" :short "Neues Argument zur Referenz erstellen" :lead "Sie können hier Position zu einer Textstelle beziehen." :logged-in "Füllen Sie dazu die folgenden Felder aus." :not-logged-in "Aber vorher müssen Sie sich einlogggen."} :discussion {:add-position "Nichts von all dem. Ich habe eine andere Idee" :add-position-heading "Ich denke, " :add-position-placeholder "wir dieses oder jenes machen sollten" :add-reason-placeholder "dieser Grund dafür existiert" :bubble/congrats "Sie haben das Ende der Diskussion erreicht. Suchen Sie sich einen anderen Einstiegspunkt in dem Artikel, um weiter zu diskutieren." :current "Aktuelle Diskussion" :reference/missing "Sie müssen sich auf eine Textstelle beziehen" :restart "Neustarten" :submit "Abschicken"} :eden {:overview "Meine Argumente" :overview/lead "Finden Sie hier Ihre Argumente, welche Sie in verschiedenen Diskussionen eingeführt haben und springen Sie direkt in die Diskussionen hinein." :arguments/construct "Neues Argument erstellen" :arguments/not-found "Es konnten noch keine Argumente von Ihnen gefunden werden. Ein guter Zeitpunkt eine Diskussion zu wählen und mit anderen Benutzern zu diskutieren!" :arguments/show "Meine Argumente anzeigen"} :errors {:login "Login fehlgeschlagen. Vermutlich sind die Zugangsdaten nicht korrekt."} :find {:statement "Finde Aussage in Diskussion" :hits "Ergebnisse"} :login {:nickname "Benutzername" :password "<PASSWORD>" :hhu-ldap "Wir benutzen das Personenverzeichnis der Heinrich-Heine-Universität Düsseldorf. Alle Daten und Informationen werden natürlich SSL-verschlüsselt gesendet und nach Erhalt unter keinen Umständen an Dritte weitergegeben." :item "Hier klicken, damit Sie sich einloggen und eine neue Aussage hinzufügen können"} :nav {:home "Start" :find "Suchen" :eden "Meine Argumente"} :options {:current "Aktuell" :default "Standard" :delete "Löschen" :heading "Einstellungen" :lang "Interface-Sprache" :new-route "Neue Route" :reconnect "Neu verbinden" :reset "Zurücksetzen" :routes "Routen" :save "Speichere"} :references {:jump "Springe in die Diskussion" :save/to-clipboard "In Zwischenablage" :usages/view-heading "Interaktionen mit dem Artikel" :usages/lead "Beziehen Sie sich hier auf die ausgewählte Referenz oder schauen Sie sich an, wo diese Referenz bereits in der Diskussion verwendet wurde." :usages/not-found-lead "Argument konnte nicht gefunden werden" :usages/not-found-body "Vielleicht wurden die mit dieser Referenz verknüpften Argumente entfernt" :usages/list "Hier ist eine Liste der bisherigen Verwendungen dieser Textstelle in anderen Argumenten" :where-used "Wo wird diese Referenz verwendet?" :find-statement "Finde Aussage in der Diskussion" :clipboard "Ziehen Sie diese Referenzen in das Textfeld beim Erzeugen eines neuen Arguments hinein, um die Referenz zu nutzen." :ask-to-add "Möchten Sie Ihre Aussage durch eine Referenz von dieser Seite stützen? Dann markieren Sie einfach einen Teil des Textes mit der Maus." :has-to-add "Um sich auf eine Stelle im Artikel zu beziehen, müssen Sie die Stelle mit der Maus markieren. Dann erscheint der Text in diesem Textfeld." :disabled/tooltip "Dieses Feld kann nicht direkt modifiziert werden. Bitte markieren Sie die gewünschte Stelle direkt auf der Webseite. Dieses Feld füllt sich dann automatisch."} :search {:reuse "Statement auswählen" :origin "Herkunft" :author "<NAME>"} :tooltip {:discuss/start "Argument erzeugen"} :undercut {:text "Laut %s kann man die Aussage, dass \"%s\", nicht damit begründen, dass \"%s\", weil %s."}} :en {:common {:and "and" :argue/con "does not think that" :argue/that "thinks that" :author "Author" :back "Back" :because "because" :chars-remaining "add at least %d more character(s)" :close "Close" :delete "Delete" :hello "Hello" :issue "Issue" :login "Login" :logout "Logout" :options "Options" :select "Select" :save "Save" :show-discuss "Show discuss" :start-discussion "Start Discussion" :that "that"} :clipboard {:heading "Clipboard" :instruction "Select a reference from this list on new argument creation to link the reference with your argument."} :create/argument {:header "Create an argument with a text reference" :short "Create Argument with Reference" :lead "You can refer position to a text passage here." :logged-in "Please fill in the following fields." :not-logged-in "But first you need to login."} :discussion {:add-position "Neither of the above, I have a different idea" :add-position-heading "I think that" :add-position-placeholder "we should do this or that" :add-reason-placeholder "of this reason" :bubble/congrats "You've reached the end of the current discussion. Find a different position in the article to start over again." :current "Current Discussion" :reference/missing "You need to refer to a text passage" :restart "Restart" :submit "Submit"} :eden {:overview "My Arguments" :overview/lead "You provided these arguments in your discussions. Create a list of them and directly jump into the discussion." :arguments/construct "Construct new Argument" :arguments/not-found "Currently there are no arguments from your account. A good starting point to find a discussion and start adding your own arguments!" :arguments/show "Show my Arguments"} :errors {:login "Could not login. Maybe your credentials are wrong."} :find {:statement "Find statement in the discussion" :hits "Results"} :login {:nickname "Nickname" :password "<PASSWORD>" :hhu-ldap "We are using the Register of Persons of the Heinrich-Heine-University Düsseldorf. All data and information are of course sent SSL encrypted and will never be passed on to any third parties after receipt." :item "Click here to authenticate and to be able to submit your own statements"} :nav {:home "Home" :eden "My Arguments" :find "Find"} :options {:current "Current" :default "Default" :delete "Delete" :heading "Options" :lang "Interface Language" :new-route "Set new Route" :reconnect "Reconnect" :reset "Reset to Defaults" :routes "Routes" :save "Save"} :references {:jump "Jump into the discussion" :save/to-clipboard "Save into Clipboard" :usages/view-heading "Interacting with the Article" :usages/lead "Create your own argument based on the text selection or take a look at those arguments, which already refer to this position." :usages/not-found-lead "No assigned arguments found" :usages/not-found-body "Maybe the assigned arguments have been removed" :usages/list "Here you can find a list of those arguments, which refer to the selected text passage" :where-used "Where has this reference been used?" :ask-to-add "Do you want to add a reference from this site to your statement? Just select the desired text-passage and it will be inserted in this field." :has-to-add "To refer position to a passage in the article, you have to select the desired text-passage with your mouse selection." :disabled/tooltip "You can't modify this field. Please select the appropriate text-passage from the website. The selection will be automatically added to this field."} :search {:reuse "Select Statement" :origin "Origin" :author "<NAME>"} :tooltip {:discuss/start "Create Argument"} :undercut {:text "According to %s, the statement that \"%s\" can not be explained by the fact that \"%s\", because %s."}}}) (defn- prepend-translation "Lookup given key and prepend some string to it." [group key prepend] (str prepend (get-in translations [(lib/language) group key]))) (defn translate "Get translation string according to currently configured language." ([group key option] (cond (= :space option) (prepend-translation group key " ") :else (prepend-translation group key ""))) ([group key] (translate group key :default))) (s/fdef translate :args (s/or :option (s/cat :group keyword? :key keyword? :option keyword?) :no-option (s/cat :group keyword? :key keyword?)) :ret string?)
true
(ns discuss.translations (:require [discuss.utils.common :as lib] [cljs.spec.alpha :as s])) (def available [[:de "deutsch"] [:en "english"]]) (def translations {:de {:common {:and "und" :argue/con "denkt nicht, dass" :argue/that "denkt, dass" :author "Autor" :back "Zurück" :because "weil" :chars-remaining "noch mind. %d Zeichen eingeben" :close "Schließen" :delete "Löschen" :hello "Hallo" :issue "Diskussionsthema" :login "Login" :logout "Logout" :options "Einstellungen" :select "Auswählen" :save "Speichern" :show-discuss "Zeige discuss" :start-discussion "Starte die Diskussion" :that "dass"} :clipboard {:heading "Zwischenablage" :instruction "Wählen Sie eine Referenz aus dieser Liste aus, um beim Erzeugen eines neuen Arguments diese Referenz mit dem neuen Argument zu verknüpfen."} :create/argument {:header "Erzeugen Sie ein Argument zu einer Textstelle" :short "Neues Argument zur Referenz erstellen" :lead "Sie können hier Position zu einer Textstelle beziehen." :logged-in "Füllen Sie dazu die folgenden Felder aus." :not-logged-in "Aber vorher müssen Sie sich einlogggen."} :discussion {:add-position "Nichts von all dem. Ich habe eine andere Idee" :add-position-heading "Ich denke, " :add-position-placeholder "wir dieses oder jenes machen sollten" :add-reason-placeholder "dieser Grund dafür existiert" :bubble/congrats "Sie haben das Ende der Diskussion erreicht. Suchen Sie sich einen anderen Einstiegspunkt in dem Artikel, um weiter zu diskutieren." :current "Aktuelle Diskussion" :reference/missing "Sie müssen sich auf eine Textstelle beziehen" :restart "Neustarten" :submit "Abschicken"} :eden {:overview "Meine Argumente" :overview/lead "Finden Sie hier Ihre Argumente, welche Sie in verschiedenen Diskussionen eingeführt haben und springen Sie direkt in die Diskussionen hinein." :arguments/construct "Neues Argument erstellen" :arguments/not-found "Es konnten noch keine Argumente von Ihnen gefunden werden. Ein guter Zeitpunkt eine Diskussion zu wählen und mit anderen Benutzern zu diskutieren!" :arguments/show "Meine Argumente anzeigen"} :errors {:login "Login fehlgeschlagen. Vermutlich sind die Zugangsdaten nicht korrekt."} :find {:statement "Finde Aussage in Diskussion" :hits "Ergebnisse"} :login {:nickname "Benutzername" :password "PI:PASSWORD:<PASSWORD>END_PI" :hhu-ldap "Wir benutzen das Personenverzeichnis der Heinrich-Heine-Universität Düsseldorf. Alle Daten und Informationen werden natürlich SSL-verschlüsselt gesendet und nach Erhalt unter keinen Umständen an Dritte weitergegeben." :item "Hier klicken, damit Sie sich einloggen und eine neue Aussage hinzufügen können"} :nav {:home "Start" :find "Suchen" :eden "Meine Argumente"} :options {:current "Aktuell" :default "Standard" :delete "Löschen" :heading "Einstellungen" :lang "Interface-Sprache" :new-route "Neue Route" :reconnect "Neu verbinden" :reset "Zurücksetzen" :routes "Routen" :save "Speichere"} :references {:jump "Springe in die Diskussion" :save/to-clipboard "In Zwischenablage" :usages/view-heading "Interaktionen mit dem Artikel" :usages/lead "Beziehen Sie sich hier auf die ausgewählte Referenz oder schauen Sie sich an, wo diese Referenz bereits in der Diskussion verwendet wurde." :usages/not-found-lead "Argument konnte nicht gefunden werden" :usages/not-found-body "Vielleicht wurden die mit dieser Referenz verknüpften Argumente entfernt" :usages/list "Hier ist eine Liste der bisherigen Verwendungen dieser Textstelle in anderen Argumenten" :where-used "Wo wird diese Referenz verwendet?" :find-statement "Finde Aussage in der Diskussion" :clipboard "Ziehen Sie diese Referenzen in das Textfeld beim Erzeugen eines neuen Arguments hinein, um die Referenz zu nutzen." :ask-to-add "Möchten Sie Ihre Aussage durch eine Referenz von dieser Seite stützen? Dann markieren Sie einfach einen Teil des Textes mit der Maus." :has-to-add "Um sich auf eine Stelle im Artikel zu beziehen, müssen Sie die Stelle mit der Maus markieren. Dann erscheint der Text in diesem Textfeld." :disabled/tooltip "Dieses Feld kann nicht direkt modifiziert werden. Bitte markieren Sie die gewünschte Stelle direkt auf der Webseite. Dieses Feld füllt sich dann automatisch."} :search {:reuse "Statement auswählen" :origin "Herkunft" :author "PI:NAME:<NAME>END_PI"} :tooltip {:discuss/start "Argument erzeugen"} :undercut {:text "Laut %s kann man die Aussage, dass \"%s\", nicht damit begründen, dass \"%s\", weil %s."}} :en {:common {:and "and" :argue/con "does not think that" :argue/that "thinks that" :author "Author" :back "Back" :because "because" :chars-remaining "add at least %d more character(s)" :close "Close" :delete "Delete" :hello "Hello" :issue "Issue" :login "Login" :logout "Logout" :options "Options" :select "Select" :save "Save" :show-discuss "Show discuss" :start-discussion "Start Discussion" :that "that"} :clipboard {:heading "Clipboard" :instruction "Select a reference from this list on new argument creation to link the reference with your argument."} :create/argument {:header "Create an argument with a text reference" :short "Create Argument with Reference" :lead "You can refer position to a text passage here." :logged-in "Please fill in the following fields." :not-logged-in "But first you need to login."} :discussion {:add-position "Neither of the above, I have a different idea" :add-position-heading "I think that" :add-position-placeholder "we should do this or that" :add-reason-placeholder "of this reason" :bubble/congrats "You've reached the end of the current discussion. Find a different position in the article to start over again." :current "Current Discussion" :reference/missing "You need to refer to a text passage" :restart "Restart" :submit "Submit"} :eden {:overview "My Arguments" :overview/lead "You provided these arguments in your discussions. Create a list of them and directly jump into the discussion." :arguments/construct "Construct new Argument" :arguments/not-found "Currently there are no arguments from your account. A good starting point to find a discussion and start adding your own arguments!" :arguments/show "Show my Arguments"} :errors {:login "Could not login. Maybe your credentials are wrong."} :find {:statement "Find statement in the discussion" :hits "Results"} :login {:nickname "Nickname" :password "PI:PASSWORD:<PASSWORD>END_PI" :hhu-ldap "We are using the Register of Persons of the Heinrich-Heine-University Düsseldorf. All data and information are of course sent SSL encrypted and will never be passed on to any third parties after receipt." :item "Click here to authenticate and to be able to submit your own statements"} :nav {:home "Home" :eden "My Arguments" :find "Find"} :options {:current "Current" :default "Default" :delete "Delete" :heading "Options" :lang "Interface Language" :new-route "Set new Route" :reconnect "Reconnect" :reset "Reset to Defaults" :routes "Routes" :save "Save"} :references {:jump "Jump into the discussion" :save/to-clipboard "Save into Clipboard" :usages/view-heading "Interacting with the Article" :usages/lead "Create your own argument based on the text selection or take a look at those arguments, which already refer to this position." :usages/not-found-lead "No assigned arguments found" :usages/not-found-body "Maybe the assigned arguments have been removed" :usages/list "Here you can find a list of those arguments, which refer to the selected text passage" :where-used "Where has this reference been used?" :ask-to-add "Do you want to add a reference from this site to your statement? Just select the desired text-passage and it will be inserted in this field." :has-to-add "To refer position to a passage in the article, you have to select the desired text-passage with your mouse selection." :disabled/tooltip "You can't modify this field. Please select the appropriate text-passage from the website. The selection will be automatically added to this field."} :search {:reuse "Select Statement" :origin "Origin" :author "PI:NAME:<NAME>END_PI"} :tooltip {:discuss/start "Create Argument"} :undercut {:text "According to %s, the statement that \"%s\" can not be explained by the fact that \"%s\", because %s."}}}) (defn- prepend-translation "Lookup given key and prepend some string to it." [group key prepend] (str prepend (get-in translations [(lib/language) group key]))) (defn translate "Get translation string according to currently configured language." ([group key option] (cond (= :space option) (prepend-translation group key " ") :else (prepend-translation group key ""))) ([group key] (translate group key :default))) (s/fdef translate :args (s/or :option (s/cat :group keyword? :key keyword? :option keyword?) :no-option (s/cat :group keyword? :key keyword?)) :ret string?)
[ { "context": "; Copyright (c) Anna Shchiptsova, IIASA. All rights reserved.\r\n; The use and dis", "end": 34, "score": 0.9998927712440491, "start": 18, "tag": "NAME", "value": "Anna Shchiptsova" }, { "context": "ides some I/O utility functions.\"\r\n :author \"Anna Shchiptsova\"}\r\n utilities-clj.file\r\n (:require [clojure.java", "end": 534, "score": 0.9998977780342102, "start": 518, "tag": "NAME", "value": "Anna Shchiptsova" } ]
src/utilities_clj/file.clj
shchipts/utilities-clj
0
; Copyright (c) Anna Shchiptsova, IIASA. All rights reserved. ; The use and distribution terms for this software are covered by the ; MIT License (http://opensource.org/licenses/MIT) ; which can be found in the file LICENSE at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:doc "Provides some I/O utility functions." :author "Anna Shchiptsova"} utilities-clj.file (:require [clojure.java.io :as io] [clojure.string :as string])) (defn walk "Walks through the folder files which match the specified pattern. Returns a java.io.File collection of the files in the folder, whose name matches the pattern. ## Usage (require '[utilities.file :refer :all]) (walk source-folder #\".*\\.asc\") " [folder pattern] (->> (io/file folder) file-seq (filter #(re-matches pattern (.getName ^java.io.File %))) doall)) (defn basename "Returns a file name without extension." [path] (->> (io/file path) (#(.getName ^java.io.File %)) (#(string/split % #"\.")) first))
114562
; Copyright (c) <NAME>, IIASA. All rights reserved. ; The use and distribution terms for this software are covered by the ; MIT License (http://opensource.org/licenses/MIT) ; which can be found in the file LICENSE at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:doc "Provides some I/O utility functions." :author "<NAME>"} utilities-clj.file (:require [clojure.java.io :as io] [clojure.string :as string])) (defn walk "Walks through the folder files which match the specified pattern. Returns a java.io.File collection of the files in the folder, whose name matches the pattern. ## Usage (require '[utilities.file :refer :all]) (walk source-folder #\".*\\.asc\") " [folder pattern] (->> (io/file folder) file-seq (filter #(re-matches pattern (.getName ^java.io.File %))) doall)) (defn basename "Returns a file name without extension." [path] (->> (io/file path) (#(.getName ^java.io.File %)) (#(string/split % #"\.")) first))
true
; Copyright (c) PI:NAME:<NAME>END_PI, IIASA. All rights reserved. ; The use and distribution terms for this software are covered by the ; MIT License (http://opensource.org/licenses/MIT) ; which can be found in the file LICENSE at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns ^{:doc "Provides some I/O utility functions." :author "PI:NAME:<NAME>END_PI"} utilities-clj.file (:require [clojure.java.io :as io] [clojure.string :as string])) (defn walk "Walks through the folder files which match the specified pattern. Returns a java.io.File collection of the files in the folder, whose name matches the pattern. ## Usage (require '[utilities.file :refer :all]) (walk source-folder #\".*\\.asc\") " [folder pattern] (->> (io/file folder) file-seq (filter #(re-matches pattern (.getName ^java.io.File %))) doall)) (defn basename "Returns a file name without extension." [path] (->> (io/file path) (#(.getName ^java.io.File %)) (#(string/split % #"\.")) first))
[ { "context": "\n; Copyright 2013 Anthony Campbell (anthonycampbell.co.uk)\n;\n; Licensed under the Ap", "end": 34, "score": 0.9998769760131836, "start": 18, "tag": "NAME", "value": "Anthony Campbell" }, { "context": "\n; Copyright 2013 Anthony Campbell (anthonycampbell.co.uk)\n;\n; Licensed under the Apache License, Version 2", "end": 57, "score": 0.9897549152374268, "start": 36, "tag": "EMAIL", "value": "anthonycampbell.co.uk" } ]
src/uk/co/anthonycampbell/imdb/log.clj
acampbell3000/clojure-imdb-parser
1
; Copyright 2013 Anthony Campbell (anthonycampbell.co.uk) ; ; 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 uk.co.anthonycampbell.imdb.log (:gen-class) (:use clojure.tools.logging) (:use clj-logging-config.log4j)) (defn setup-logging "Prepare log4j root logger with with console appender set to level WARN" [] (org.apache.log4j.BasicConfigurator/configure) (.setLevel (org.apache.log4j.Logger/getRootLogger) (org.apache.log4j.Level/WARN)))
120287
; Copyright 2013 <NAME> (<EMAIL>) ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns uk.co.anthonycampbell.imdb.log (:gen-class) (:use clojure.tools.logging) (:use clj-logging-config.log4j)) (defn setup-logging "Prepare log4j root logger with with console appender set to level WARN" [] (org.apache.log4j.BasicConfigurator/configure) (.setLevel (org.apache.log4j.Logger/getRootLogger) (org.apache.log4j.Level/WARN)))
true
; Copyright 2013 PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns uk.co.anthonycampbell.imdb.log (:gen-class) (:use clojure.tools.logging) (:use clj-logging-config.log4j)) (defn setup-logging "Prepare log4j root logger with with console appender set to level WARN" [] (org.apache.log4j.BasicConfigurator/configure) (.setLevel (org.apache.log4j.Logger/getRootLogger) (org.apache.log4j.Level/WARN)))
[ { "context": " of their house.\",\n :director \"Tim Burton\",\n :genres [\"Comedy\" \"Fantas", "end": 548, "score": 0.9998945593833923, "start": 538, "tag": "NAME", "value": "Tim Burton" }, { "context": " :year \"1988\",\n :actors \"Alec Baldwin, Geena Davis, Annie McEnroe, Maurice Page\",\n ", "end": 729, "score": 0.9998939633369446, "start": 717, "tag": "NAME", "value": "Alec Baldwin" }, { "context": "988\",\n :actors \"Alec Baldwin, Geena Davis, Annie McEnroe, Maurice Page\",\n ", "end": 742, "score": 0.9998847842216492, "start": 731, "tag": "NAME", "value": "Geena Davis" }, { "context": " :actors \"Alec Baldwin, Geena Davis, Annie McEnroe, Maurice Page\",\n :id 1,\n", "end": 757, "score": 0.9998758435249329, "start": 744, "tag": "NAME", "value": "Annie McEnroe" }, { "context": "ctors \"Alec Baldwin, Geena Davis, Annie McEnroe, Maurice Page\",\n :id 1,\n ", "end": 771, "score": 0.9998718500137329, "start": 759, "tag": "NAME", "value": "Maurice Page" }, { "context": "de it so famous.\",\n :director \"Francis Ford Coppola\",\n :genres [\"Crime\" \"Drama\" ", "end": 1311, "score": 0.9998751878738403, "start": 1291, "tag": "NAME", "value": "Francis Ford Coppola" }, { "context": " :year \"1984\",\n :actors \"Richard Gere, Gregory Hines, Diane Lane, Lonette McKee\",\n ", "end": 1501, "score": 0.9998913407325745, "start": 1489, "tag": "NAME", "value": "Richard Gere" }, { "context": "984\",\n :actors \"Richard Gere, Gregory Hines, Diane Lane, Lonette McKee\",\n ", "end": 1516, "score": 0.9998869895935059, "start": 1503, "tag": "NAME", "value": "Gregory Hines" }, { "context": " :actors \"Richard Gere, Gregory Hines, Diane Lane, Lonette McKee\",\n :id 2,", "end": 1528, "score": 0.999855637550354, "start": 1518, "tag": "NAME", "value": "Diane Lane" }, { "context": "actors \"Richard Gere, Gregory Hines, Diane Lane, Lonette McKee\",\n :id 2,\n ", "end": 1543, "score": 0.9998348355293274, "start": 1530, "tag": "NAME", "value": "Lonette McKee" }, { "context": " common decency.\",\n :director \"Frank Darabont\",\n :genres [\"Crime\" \"Drama\"]", "end": 2015, "score": 0.9998806118965149, "start": 2001, "tag": "NAME", "value": "Frank Darabont" }, { "context": " :year \"1994\",\n :actors \"Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler\",\n ", "end": 2205, "score": 0.9998822212219238, "start": 2194, "tag": "NAME", "value": "Tim Robbins" }, { "context": "1994\",\n :actors \"Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler\",\n ", "end": 2221, "score": 0.9998895525932312, "start": 2207, "tag": "NAME", "value": "Morgan Freeman" }, { "context": " :actors \"Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler\",\n :id 3", "end": 2233, "score": 0.9998761415481567, "start": 2223, "tag": "NAME", "value": "Bob Gunton" }, { "context": "actors \"Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler\",\n :id 3,\n ", "end": 2249, "score": 0.9998614192008972, "start": 2235, "tag": "NAME", "value": "William Sadler" }, { "context": "o New York City.\",\n :director \"Peter Faiman\",\n :genres [\"Adventure\" \"Com", "end": 2725, "score": 0.9998663067817688, "start": 2713, "tag": "NAME", "value": "Peter Faiman" }, { "context": " :year \"1986\",\n :actors \"Paul Hogan, Linda Kozlowski, John Meillon, David Gulpilil\",\n", "end": 2911, "score": 0.9998893737792969, "start": 2901, "tag": "NAME", "value": "Paul Hogan" }, { "context": "\"1986\",\n :actors \"Paul Hogan, Linda Kozlowski, John Meillon, David Gulpilil\",\n ", "end": 2928, "score": 0.9998714327812195, "start": 2913, "tag": "NAME", "value": "Linda Kozlowski" }, { "context": " :actors \"Paul Hogan, Linda Kozlowski, John Meillon, David Gulpilil\",\n :id 4", "end": 2942, "score": 0.9998698830604553, "start": 2930, "tag": "NAME", "value": "John Meillon" }, { "context": "tors \"Paul Hogan, Linda Kozlowski, John Meillon, David Gulpilil\",\n :id 4,\n ", "end": 2958, "score": 0.999869704246521, "start": 2944, "tag": "NAME", "value": "David Gulpilil" }, { "context": " foresight.\",\n :director \"Adam McKay\",\n :genres [\"Biography\"", "end": 7939, "score": 0.9998849630355835, "start": 7929, "tag": "NAME", "value": "Adam McKay" }, { "context": "r \"2015\",\n :actors \"Ryan Gosling, Rudy Eisenzopf, Casey Groves, Charlie Talbert\",\n", "end": 8152, "score": 0.9998920559883118, "start": 8140, "tag": "NAME", "value": "Ryan Gosling" }, { "context": "\n :actors \"Ryan Gosling, Rudy Eisenzopf, Casey Groves, Charlie Talbert\",\n ", "end": 8168, "score": 0.9998914003372192, "start": 8154, "tag": "NAME", "value": "Rudy Eisenzopf" }, { "context": " :actors \"Ryan Gosling, Rudy Eisenzopf, Casey Groves, Charlie Talbert\",\n :id ", "end": 8182, "score": 0.9998781085014343, "start": 8170, "tag": "NAME", "value": "Casey Groves" }, { "context": "ors \"Ryan Gosling, Rudy Eisenzopf, Casey Groves, Charlie Talbert\",\n :id 146,\n ", "end": 8199, "score": 0.9998856782913208, "start": 8184, "tag": "NAME", "value": "Charlie Talbert" } ]
workspace/hello-web-compojure-sweet-part-3/src/hello_web_compojure_sweet/movies.clj
muthuishere/clojure-web-fundamentals
0
(ns hello-web-compojure-sweet.movies (:require [compojure.api.sweet :as sw] [ring.middleware.defaults :refer [wrap-defaults site-defaults api-defaults]] [ring.util.http-response :as http-response] ) (:use [org.httpkit.server :only [run-server]]) ) (def movies (atom [{:plot "A couple of recently deceased ghosts contract the services of a \"bio-exorcist\" in order to remove the obnoxious new owners of their house.", :director "Tim Burton", :genres ["Comedy" "Fantasy"], :title "Beetlejuice", :year "1988", :actors "Alec Baldwin, Geena Davis, Annie McEnroe, Maurice Page", :id 1, :runtime "92", :posterUrl "https://images-na.ssl-images-amazon.com/images/M/MV5BMTUwODE3MDE0MV5BMl5BanBnXkFtZTgwNTk1MjI4MzE@._V1_SX300.jpg"} {:plot "The Cotton Club was a famous night club in Harlem. The story follows the people that visited the club, those that ran it, and is peppered with the Jazz music that made it so famous.", :director "Francis Ford Coppola", :genres ["Crime" "Drama" "Music"], :title "The Cotton Club", :year "1984", :actors "Richard Gere, Gregory Hines, Diane Lane, Lonette McKee", :id 2, :runtime "127", :posterUrl "https://images-na.ssl-images-amazon.com/images/M/MV5BMTU5ODAyNzA4OV5BMl5BanBnXkFtZTcwNzYwNTIzNA@@._V1_SX300.jpg"} {:plot "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.", :director "Frank Darabont", :genres ["Crime" "Drama"], :title "The Shawshank Redemption", :year "1994", :actors "Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler", :id 3, :runtime "142", :posterUrl "https://images-na.ssl-images-amazon.com/images/M/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE@._V1_SX300.jpg"} {:plot "An American reporter goes to the Australian outback to meet an eccentric crocodile poacher and invites him to New York City.", :director "Peter Faiman", :genres ["Adventure" "Comedy"], :title "Crocodile Dundee", :year "1986", :actors "Paul Hogan, Linda Kozlowski, John Meillon, David Gulpilil", :id 4, :runtime "97", :posterUrl "https://images-na.ssl-images-amazon.com/images/M/MV5BMTg0MTU1MTg4NF5BMl5BanBnXkFtZTgwMDgzNzYxMTE@._V1_SX300.jpg"}] )) (defn all-movies [request] (println "Total Movies" (count @movies)) {:status 200 :body @movies } ) (defn movie-by-id [request] (let [ id (Integer/parseInt (get-in request [:path-params :id])) result (first (filter #(= id (get % :id)) @movies)) ] (print result) (if (nil? result) {:status 404 :body "Movie not found" } {:status 200 :body result } ) ) ) ;Find a remote REPL for Clojure , And show all the values (defn insert-movie [request] (println (get request :body-params)) (swap! movies conj (get request :body-params)) {:status 200 :body { :result "Succesfully Inserted" :request (get request :body-params) :all-movies @movies } } ) (defn update-movie-for [id updated-data existing-movies] (map #(if (= (get % :id) id) (merge % updated-data) %) existing-movies ) ) (defn update-movie-by-id-old [request] (let [ id (Integer/parseInt (get-in request [:path-params :id])) updated-data (get request :body-params) ] (swap! movies (fn [values] (update-movie-for id updated-data values) )) {:status 200 :body { :result "Succesfully Updated Movie" :request (get request :body-params) :all-movies @movies } } ) ) (defn update-movie-by-id [request] (let [ id (Integer/parseInt (get-in request [:path-params :id])) updated-data (get request :body-params) update-movie-handler (partial update-movie-for id updated-data) ] ; ;(swap! movies (fn [values] ; (update-movie-handler values) ; )) (swap! movies update-movie-handler) {:status 200 :body { :result "Succesfully Updated Movie with partial" :request (get request :body-params) :all-movies @movies } } ) ) (defn delete-movie-by-id [request] (let [ id (Integer/parseInt (get-in request [:path-params :id])) ] (swap! movies (fn [values] (filter #(not= id (get % :id)) values) )) {:status 200 :body { :result "Succesfully Deleted Movie " :request (get request :body-params) :all-movies @movies } } ) ) (def app (sw/api (sw/context "/api" [] (sw/GET "/movies" request (all-movies request) ) (sw/POST "/movies" request (insert-movie request) ) (sw/GET "/movies/:id" request (movie-by-id request) ) (sw/PUT "/movies/:id" request (update-movie-by-id request) ) (sw/DELETE "/movies/:id" request (delete-movie-by-id request) ) ) )) ;; (def app ;; ["/api" [ ;; ["/movies" { ;; :get all-movies ;; :post insert-movie ;; }] ;; ["/movies/:id" { ;; :get movie-by-id ;; :put update-movie-by-id ;; :delete delete-movie-by-id ;; }] ;; ]] ;; )))) (comment (update-movie-for @movies 1 {:title "Changed Name" :year "2000"}) (def id 1) (first (filter #(= 104 (get % :id)) @movies)) (first (filter #(= "1" (get % :id)) @movies)) (app {:request-method :put :uri "/api/movies/1" :body-params { :title "Changed Name newest new" :year "2000" }} ) (app {:request-method :get :uri "/api/movies/1" }) (app {:request-method :delete :uri "/api/movies/1" } ) (app {:request-method :get :uri "/api/movies/1" }) (app {:request-method :get :uri "/api/movies/233" }) (app {:request-method :get :uri "/api/movies" }) (app {:request-method :post :uri "/api/movies" :body-params { :plot "Four denizens in the world of high-finance predict the credit and housing bubble collapse of the mid-2000s, and decide to take on the big banks for their greed and lack of foresight.", :director "Adam McKay", :genres ["Biography" "Comedy" "Drama"], :title "The Big Short", :year "2015", :actors "Ryan Gosling, Rudy Eisenzopf, Casey Groves, Charlie Talbert", :id 146, :runtime "130", :posterUrl "https://images-na.ssl-images-amazon.com/images/M/MV5BNDc4MThhN2EtZjMzNC00ZDJmLThiZTgtNThlY2UxZWMzNjdkXkEyXkFqcGdeQXVyNDk3NzU2MTQ@._V1_SX300.jpg"} }) (app {:request-method :get :uri "/hello" }) (app {:request-method :post :uri "/insertdata" }) ) ; ;(defroutes app-routes ; (GET "/hello" [] "Hello Clojure ") ; ;(GET "/hello/:name" [name] (str "Hello " name) ) ; (GET "/hello/:name" [name] ; {:status 200 ; :body (str "Hello with status " name) ; } ; ; ) ; (POST "/insertdata" request ; ; (insert-data request) ; ; ; ) ; ; (route/not-found "Not Found") ; ) ;wrap-defaults is a middleware that wraps the default middleware with routes and basic server side parameters ;site-defaults is a middleware that sets the default site parameters ;api-defaults ;(def oldapp ; (wrap-defaults app-routes api-defaults)) ; ; ;(def app (-> ; app-routes ; (middleware/wrap-json-body {:keywords? true}) ; (middleware/wrap-json-response) ; (wrap-defaults api-defaults) ; ) ; ) ;Use ;lein ring server-headless to reload and run the server (defn stop-app [] (println "Stopping") ) (defn -main [& args] (println "Starting") ;shut d ;(.addShutdownHook (Runtime/getRuntime) (Thread. stop-app)) (run-server app {:port 4500 :event-logger (fn [& args] (println args) ) } ) ; (println "started") )
73684
(ns hello-web-compojure-sweet.movies (:require [compojure.api.sweet :as sw] [ring.middleware.defaults :refer [wrap-defaults site-defaults api-defaults]] [ring.util.http-response :as http-response] ) (:use [org.httpkit.server :only [run-server]]) ) (def movies (atom [{:plot "A couple of recently deceased ghosts contract the services of a \"bio-exorcist\" in order to remove the obnoxious new owners of their house.", :director "<NAME>", :genres ["Comedy" "Fantasy"], :title "Beetlejuice", :year "1988", :actors "<NAME>, <NAME>, <NAME>, <NAME>", :id 1, :runtime "92", :posterUrl "https://images-na.ssl-images-amazon.com/images/M/MV5BMTUwODE3MDE0MV5BMl5BanBnXkFtZTgwNTk1MjI4MzE@._V1_SX300.jpg"} {:plot "The Cotton Club was a famous night club in Harlem. The story follows the people that visited the club, those that ran it, and is peppered with the Jazz music that made it so famous.", :director "<NAME>", :genres ["Crime" "Drama" "Music"], :title "The Cotton Club", :year "1984", :actors "<NAME>, <NAME>, <NAME>, <NAME>", :id 2, :runtime "127", :posterUrl "https://images-na.ssl-images-amazon.com/images/M/MV5BMTU5ODAyNzA4OV5BMl5BanBnXkFtZTcwNzYwNTIzNA@@._V1_SX300.jpg"} {:plot "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.", :director "<NAME>", :genres ["Crime" "Drama"], :title "The Shawshank Redemption", :year "1994", :actors "<NAME>, <NAME>, <NAME>, <NAME>", :id 3, :runtime "142", :posterUrl "https://images-na.ssl-images-amazon.com/images/M/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE@._V1_SX300.jpg"} {:plot "An American reporter goes to the Australian outback to meet an eccentric crocodile poacher and invites him to New York City.", :director "<NAME>", :genres ["Adventure" "Comedy"], :title "Crocodile Dundee", :year "1986", :actors "<NAME>, <NAME>, <NAME>, <NAME>", :id 4, :runtime "97", :posterUrl "https://images-na.ssl-images-amazon.com/images/M/MV5BMTg0MTU1MTg4NF5BMl5BanBnXkFtZTgwMDgzNzYxMTE@._V1_SX300.jpg"}] )) (defn all-movies [request] (println "Total Movies" (count @movies)) {:status 200 :body @movies } ) (defn movie-by-id [request] (let [ id (Integer/parseInt (get-in request [:path-params :id])) result (first (filter #(= id (get % :id)) @movies)) ] (print result) (if (nil? result) {:status 404 :body "Movie not found" } {:status 200 :body result } ) ) ) ;Find a remote REPL for Clojure , And show all the values (defn insert-movie [request] (println (get request :body-params)) (swap! movies conj (get request :body-params)) {:status 200 :body { :result "Succesfully Inserted" :request (get request :body-params) :all-movies @movies } } ) (defn update-movie-for [id updated-data existing-movies] (map #(if (= (get % :id) id) (merge % updated-data) %) existing-movies ) ) (defn update-movie-by-id-old [request] (let [ id (Integer/parseInt (get-in request [:path-params :id])) updated-data (get request :body-params) ] (swap! movies (fn [values] (update-movie-for id updated-data values) )) {:status 200 :body { :result "Succesfully Updated Movie" :request (get request :body-params) :all-movies @movies } } ) ) (defn update-movie-by-id [request] (let [ id (Integer/parseInt (get-in request [:path-params :id])) updated-data (get request :body-params) update-movie-handler (partial update-movie-for id updated-data) ] ; ;(swap! movies (fn [values] ; (update-movie-handler values) ; )) (swap! movies update-movie-handler) {:status 200 :body { :result "Succesfully Updated Movie with partial" :request (get request :body-params) :all-movies @movies } } ) ) (defn delete-movie-by-id [request] (let [ id (Integer/parseInt (get-in request [:path-params :id])) ] (swap! movies (fn [values] (filter #(not= id (get % :id)) values) )) {:status 200 :body { :result "Succesfully Deleted Movie " :request (get request :body-params) :all-movies @movies } } ) ) (def app (sw/api (sw/context "/api" [] (sw/GET "/movies" request (all-movies request) ) (sw/POST "/movies" request (insert-movie request) ) (sw/GET "/movies/:id" request (movie-by-id request) ) (sw/PUT "/movies/:id" request (update-movie-by-id request) ) (sw/DELETE "/movies/:id" request (delete-movie-by-id request) ) ) )) ;; (def app ;; ["/api" [ ;; ["/movies" { ;; :get all-movies ;; :post insert-movie ;; }] ;; ["/movies/:id" { ;; :get movie-by-id ;; :put update-movie-by-id ;; :delete delete-movie-by-id ;; }] ;; ]] ;; )))) (comment (update-movie-for @movies 1 {:title "Changed Name" :year "2000"}) (def id 1) (first (filter #(= 104 (get % :id)) @movies)) (first (filter #(= "1" (get % :id)) @movies)) (app {:request-method :put :uri "/api/movies/1" :body-params { :title "Changed Name newest new" :year "2000" }} ) (app {:request-method :get :uri "/api/movies/1" }) (app {:request-method :delete :uri "/api/movies/1" } ) (app {:request-method :get :uri "/api/movies/1" }) (app {:request-method :get :uri "/api/movies/233" }) (app {:request-method :get :uri "/api/movies" }) (app {:request-method :post :uri "/api/movies" :body-params { :plot "Four denizens in the world of high-finance predict the credit and housing bubble collapse of the mid-2000s, and decide to take on the big banks for their greed and lack of foresight.", :director "<NAME>", :genres ["Biography" "Comedy" "Drama"], :title "The Big Short", :year "2015", :actors "<NAME>, <NAME>, <NAME>, <NAME>", :id 146, :runtime "130", :posterUrl "https://images-na.ssl-images-amazon.com/images/M/MV5BNDc4MThhN2EtZjMzNC00ZDJmLThiZTgtNThlY2UxZWMzNjdkXkEyXkFqcGdeQXVyNDk3NzU2MTQ@._V1_SX300.jpg"} }) (app {:request-method :get :uri "/hello" }) (app {:request-method :post :uri "/insertdata" }) ) ; ;(defroutes app-routes ; (GET "/hello" [] "Hello Clojure ") ; ;(GET "/hello/:name" [name] (str "Hello " name) ) ; (GET "/hello/:name" [name] ; {:status 200 ; :body (str "Hello with status " name) ; } ; ; ) ; (POST "/insertdata" request ; ; (insert-data request) ; ; ; ) ; ; (route/not-found "Not Found") ; ) ;wrap-defaults is a middleware that wraps the default middleware with routes and basic server side parameters ;site-defaults is a middleware that sets the default site parameters ;api-defaults ;(def oldapp ; (wrap-defaults app-routes api-defaults)) ; ; ;(def app (-> ; app-routes ; (middleware/wrap-json-body {:keywords? true}) ; (middleware/wrap-json-response) ; (wrap-defaults api-defaults) ; ) ; ) ;Use ;lein ring server-headless to reload and run the server (defn stop-app [] (println "Stopping") ) (defn -main [& args] (println "Starting") ;shut d ;(.addShutdownHook (Runtime/getRuntime) (Thread. stop-app)) (run-server app {:port 4500 :event-logger (fn [& args] (println args) ) } ) ; (println "started") )
true
(ns hello-web-compojure-sweet.movies (:require [compojure.api.sweet :as sw] [ring.middleware.defaults :refer [wrap-defaults site-defaults api-defaults]] [ring.util.http-response :as http-response] ) (:use [org.httpkit.server :only [run-server]]) ) (def movies (atom [{:plot "A couple of recently deceased ghosts contract the services of a \"bio-exorcist\" in order to remove the obnoxious new owners of their house.", :director "PI:NAME:<NAME>END_PI", :genres ["Comedy" "Fantasy"], :title "Beetlejuice", :year "1988", :actors "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI", :id 1, :runtime "92", :posterUrl "https://images-na.ssl-images-amazon.com/images/M/MV5BMTUwODE3MDE0MV5BMl5BanBnXkFtZTgwNTk1MjI4MzE@._V1_SX300.jpg"} {:plot "The Cotton Club was a famous night club in Harlem. The story follows the people that visited the club, those that ran it, and is peppered with the Jazz music that made it so famous.", :director "PI:NAME:<NAME>END_PI", :genres ["Crime" "Drama" "Music"], :title "The Cotton Club", :year "1984", :actors "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI", :id 2, :runtime "127", :posterUrl "https://images-na.ssl-images-amazon.com/images/M/MV5BMTU5ODAyNzA4OV5BMl5BanBnXkFtZTcwNzYwNTIzNA@@._V1_SX300.jpg"} {:plot "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.", :director "PI:NAME:<NAME>END_PI", :genres ["Crime" "Drama"], :title "The Shawshank Redemption", :year "1994", :actors "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI", :id 3, :runtime "142", :posterUrl "https://images-na.ssl-images-amazon.com/images/M/MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE@._V1_SX300.jpg"} {:plot "An American reporter goes to the Australian outback to meet an eccentric crocodile poacher and invites him to New York City.", :director "PI:NAME:<NAME>END_PI", :genres ["Adventure" "Comedy"], :title "Crocodile Dundee", :year "1986", :actors "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI", :id 4, :runtime "97", :posterUrl "https://images-na.ssl-images-amazon.com/images/M/MV5BMTg0MTU1MTg4NF5BMl5BanBnXkFtZTgwMDgzNzYxMTE@._V1_SX300.jpg"}] )) (defn all-movies [request] (println "Total Movies" (count @movies)) {:status 200 :body @movies } ) (defn movie-by-id [request] (let [ id (Integer/parseInt (get-in request [:path-params :id])) result (first (filter #(= id (get % :id)) @movies)) ] (print result) (if (nil? result) {:status 404 :body "Movie not found" } {:status 200 :body result } ) ) ) ;Find a remote REPL for Clojure , And show all the values (defn insert-movie [request] (println (get request :body-params)) (swap! movies conj (get request :body-params)) {:status 200 :body { :result "Succesfully Inserted" :request (get request :body-params) :all-movies @movies } } ) (defn update-movie-for [id updated-data existing-movies] (map #(if (= (get % :id) id) (merge % updated-data) %) existing-movies ) ) (defn update-movie-by-id-old [request] (let [ id (Integer/parseInt (get-in request [:path-params :id])) updated-data (get request :body-params) ] (swap! movies (fn [values] (update-movie-for id updated-data values) )) {:status 200 :body { :result "Succesfully Updated Movie" :request (get request :body-params) :all-movies @movies } } ) ) (defn update-movie-by-id [request] (let [ id (Integer/parseInt (get-in request [:path-params :id])) updated-data (get request :body-params) update-movie-handler (partial update-movie-for id updated-data) ] ; ;(swap! movies (fn [values] ; (update-movie-handler values) ; )) (swap! movies update-movie-handler) {:status 200 :body { :result "Succesfully Updated Movie with partial" :request (get request :body-params) :all-movies @movies } } ) ) (defn delete-movie-by-id [request] (let [ id (Integer/parseInt (get-in request [:path-params :id])) ] (swap! movies (fn [values] (filter #(not= id (get % :id)) values) )) {:status 200 :body { :result "Succesfully Deleted Movie " :request (get request :body-params) :all-movies @movies } } ) ) (def app (sw/api (sw/context "/api" [] (sw/GET "/movies" request (all-movies request) ) (sw/POST "/movies" request (insert-movie request) ) (sw/GET "/movies/:id" request (movie-by-id request) ) (sw/PUT "/movies/:id" request (update-movie-by-id request) ) (sw/DELETE "/movies/:id" request (delete-movie-by-id request) ) ) )) ;; (def app ;; ["/api" [ ;; ["/movies" { ;; :get all-movies ;; :post insert-movie ;; }] ;; ["/movies/:id" { ;; :get movie-by-id ;; :put update-movie-by-id ;; :delete delete-movie-by-id ;; }] ;; ]] ;; )))) (comment (update-movie-for @movies 1 {:title "Changed Name" :year "2000"}) (def id 1) (first (filter #(= 104 (get % :id)) @movies)) (first (filter #(= "1" (get % :id)) @movies)) (app {:request-method :put :uri "/api/movies/1" :body-params { :title "Changed Name newest new" :year "2000" }} ) (app {:request-method :get :uri "/api/movies/1" }) (app {:request-method :delete :uri "/api/movies/1" } ) (app {:request-method :get :uri "/api/movies/1" }) (app {:request-method :get :uri "/api/movies/233" }) (app {:request-method :get :uri "/api/movies" }) (app {:request-method :post :uri "/api/movies" :body-params { :plot "Four denizens in the world of high-finance predict the credit and housing bubble collapse of the mid-2000s, and decide to take on the big banks for their greed and lack of foresight.", :director "PI:NAME:<NAME>END_PI", :genres ["Biography" "Comedy" "Drama"], :title "The Big Short", :year "2015", :actors "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI", :id 146, :runtime "130", :posterUrl "https://images-na.ssl-images-amazon.com/images/M/MV5BNDc4MThhN2EtZjMzNC00ZDJmLThiZTgtNThlY2UxZWMzNjdkXkEyXkFqcGdeQXVyNDk3NzU2MTQ@._V1_SX300.jpg"} }) (app {:request-method :get :uri "/hello" }) (app {:request-method :post :uri "/insertdata" }) ) ; ;(defroutes app-routes ; (GET "/hello" [] "Hello Clojure ") ; ;(GET "/hello/:name" [name] (str "Hello " name) ) ; (GET "/hello/:name" [name] ; {:status 200 ; :body (str "Hello with status " name) ; } ; ; ) ; (POST "/insertdata" request ; ; (insert-data request) ; ; ; ) ; ; (route/not-found "Not Found") ; ) ;wrap-defaults is a middleware that wraps the default middleware with routes and basic server side parameters ;site-defaults is a middleware that sets the default site parameters ;api-defaults ;(def oldapp ; (wrap-defaults app-routes api-defaults)) ; ; ;(def app (-> ; app-routes ; (middleware/wrap-json-body {:keywords? true}) ; (middleware/wrap-json-response) ; (wrap-defaults api-defaults) ; ) ; ) ;Use ;lein ring server-headless to reload and run the server (defn stop-app [] (println "Stopping") ) (defn -main [& args] (println "Starting") ;shut d ;(.addShutdownHook (Runtime/getRuntime) (Thread. stop-app)) (run-server app {:port 4500 :event-logger (fn [& args] (println args) ) } ) ; (println "started") )
[ { "context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"John Alan McDonald\" :date \"2016-07-08\"\n :doc \"Profile pyramid f", "end": 105, "score": 0.9998689889907837, "start": 87, "tag": "NAME", "value": "John Alan McDonald" } ]
src/scripts/clojure/taiga/scripts/profile/pyramid.clj
wahpenayo/taiga
4
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "John Alan McDonald" :date "2016-07-08" :doc "Profile pyramid function probability forest example." } taiga.scripts.profile.pyramid (:require [clojure.test :as test] [zana.api :as z] [taiga.test.classify.pyramid.bias-majority-vote-probability] [taiga.test.classify.pyramid.bias-positive-fraction-probability] [taiga.test.classify.pyramid.bias-weight-majority-vote-probability] [taiga.test.classify.pyramid.bias-weight-positive-fraction-probability] [taiga.test.classify.pyramid.classifier] [taiga.test.classify.pyramid.majority-vote-probability] [taiga.test.classify.pyramid.positive-fraction-probability])) ;;------------------------------------------------------------------------------ (z/seconds (print-str *ns*) (test/run-tests 'taiga.test.classify.pyramid.bias-majority-vote-probability) (test/run-tests 'taiga.test.classify.pyramid.bias-positive-fraction-probability) (test/run-tests 'taiga.test.classify.pyramid.bias-weight-majority-vote-probability) (test/run-tests 'taiga.test.classify.pyramid.bias-weight-positive-fraction-probability) (test/run-tests 'taiga.test.classify.pyramid.classifier) (test/run-tests 'taiga.test.classify.pyramid.majority-vote-probability) (test/run-tests 'taiga.test.classify.pyramid.positive-fraction-probability)) ;;------------------------------------------------------------------------------
5071
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "<NAME>" :date "2016-07-08" :doc "Profile pyramid function probability forest example." } taiga.scripts.profile.pyramid (:require [clojure.test :as test] [zana.api :as z] [taiga.test.classify.pyramid.bias-majority-vote-probability] [taiga.test.classify.pyramid.bias-positive-fraction-probability] [taiga.test.classify.pyramid.bias-weight-majority-vote-probability] [taiga.test.classify.pyramid.bias-weight-positive-fraction-probability] [taiga.test.classify.pyramid.classifier] [taiga.test.classify.pyramid.majority-vote-probability] [taiga.test.classify.pyramid.positive-fraction-probability])) ;;------------------------------------------------------------------------------ (z/seconds (print-str *ns*) (test/run-tests 'taiga.test.classify.pyramid.bias-majority-vote-probability) (test/run-tests 'taiga.test.classify.pyramid.bias-positive-fraction-probability) (test/run-tests 'taiga.test.classify.pyramid.bias-weight-majority-vote-probability) (test/run-tests 'taiga.test.classify.pyramid.bias-weight-positive-fraction-probability) (test/run-tests 'taiga.test.classify.pyramid.classifier) (test/run-tests 'taiga.test.classify.pyramid.majority-vote-probability) (test/run-tests 'taiga.test.classify.pyramid.positive-fraction-probability)) ;;------------------------------------------------------------------------------
true
(set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) (ns ^{:author "PI:NAME:<NAME>END_PI" :date "2016-07-08" :doc "Profile pyramid function probability forest example." } taiga.scripts.profile.pyramid (:require [clojure.test :as test] [zana.api :as z] [taiga.test.classify.pyramid.bias-majority-vote-probability] [taiga.test.classify.pyramid.bias-positive-fraction-probability] [taiga.test.classify.pyramid.bias-weight-majority-vote-probability] [taiga.test.classify.pyramid.bias-weight-positive-fraction-probability] [taiga.test.classify.pyramid.classifier] [taiga.test.classify.pyramid.majority-vote-probability] [taiga.test.classify.pyramid.positive-fraction-probability])) ;;------------------------------------------------------------------------------ (z/seconds (print-str *ns*) (test/run-tests 'taiga.test.classify.pyramid.bias-majority-vote-probability) (test/run-tests 'taiga.test.classify.pyramid.bias-positive-fraction-probability) (test/run-tests 'taiga.test.classify.pyramid.bias-weight-majority-vote-probability) (test/run-tests 'taiga.test.classify.pyramid.bias-weight-positive-fraction-probability) (test/run-tests 'taiga.test.classify.pyramid.classifier) (test/run-tests 'taiga.test.classify.pyramid.majority-vote-probability) (test/run-tests 'taiga.test.classify.pyramid.positive-fraction-probability)) ;;------------------------------------------------------------------------------
[ { "context": ";; Copyright (c) Nicola Mometto, Rich Hickey & contributors.\n;; The use and dis", "end": 33, "score": 0.9998559951782227, "start": 19, "tag": "NAME", "value": "Nicola Mometto" }, { "context": ";; Copyright (c) Nicola Mometto, Rich Hickey & contributors.\n;; The use and distribution ter", "end": 46, "score": 0.9998408555984497, "start": 35, "tag": "NAME", "value": "Rich Hickey" } ]
tools.emitter/clojureRB/resources/tools.emitter.jvm-tools.emitter.jvm-0.1.0-beta5/src/main/clojure/clojure/tools/emitter/jvm/intrinsics.clj
abhi18av/ClojureToolsOCaml
0
;; Copyright (c) Nicola Mometto, Rich Hickey & contributors. ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns clojure.tools.emitter.jvm.intrinsics (:import (org.objectweb.asm Opcodes))) (def intrinsic {"public static double clojure.lang.Numbers.add(double,double)" [Opcodes/DADD] "public static long clojure.lang.Numbers.and(long,long)" [Opcodes/LAND] "public static long clojure.lang.Numbers.or(long,long)" [Opcodes/LOR] "public static long clojure.lang.Numbers.xor(long,long)" [Opcodes/LXOR] "public static double clojure.lang.Numbers.multiply(double,double)" [Opcodes/DMUL] "public static double clojure.lang.Numbers.divide(double,double)" [Opcodes/DDIV] "public static long clojure.lang.Numbers.remainder(long,long)" [Opcodes/LREM] "public static long clojure.lang.Numbers.shiftLeft(long,long)" [Opcodes/L2I Opcodes/LSHL] "public static long clojure.lang.Numbers.shiftRight(long,long)" [Opcodes/L2I Opcodes/LSHR] "public static double clojure.lang.Numbers.minus(double)" [Opcodes/DNEG] "public static double clojure.lang.Numbers.minus(double,double)" [Opcodes/DSUB] "public static double clojure.lang.Numbers.inc(double)" [Opcodes/DCONST_1 Opcodes/DADD] "public static double clojure.lang.Numbers.dec(double)" [Opcodes/DCONST_1 Opcodes/DSUB] "public static long clojure.lang.Numbers.quotient(long,long)" [Opcodes/LDIV] "public static int clojure.lang.Numbers.shiftLeftInt(int,int)" [Opcodes/ISHL] "public static int clojure.lang.Numbers.shiftRightInt(int,int)" [Opcodes/ISHR] "public static int clojure.lang.Numbers.unchecked_int_add(int,int)" [Opcodes/IADD] "public static int clojure.lang.Numbers.unchecked_int_subtract(int,int)" [Opcodes/ISUB] "public static int clojure.lang.Numbers.unchecked_int_negate(int)" [Opcodes/INEG] "public static int clojure.lang.Numbers.unchecked_int_inc(int)" [Opcodes/ICONST_1 Opcodes/IADD] "public static int clojure.lang.Numbers.unchecked_int_dec(int)" [Opcodes/ICONST_1 Opcodes/ISUB] "public static int clojure.lang.Numbers.unchecked_int_multiply(int,int)" [Opcodes/IMUL] "public static int clojure.lang.Numbers.unchecked_int_divide(int,int)" [Opcodes/IDIV] "public static int clojure.lang.Numbers.unchecked_int_remainder(int,int)" [Opcodes/IREM] "public static long clojure.lang.Numbers.unchecked_add(long,long)" [Opcodes/LADD] "public static double clojure.lang.Numbers.unchecked_add(double,double)" [Opcodes/DADD] "public static long clojure.lang.Numbers.unchecked_minus(long)" [Opcodes/LNEG] "public static double clojure.lang.Numbers.unchecked_minus(double)" [Opcodes/DNEG] "public static double clojure.lang.Numbers.unchecked_minus(double,double)" [Opcodes/DSUB] "public static long clojure.lang.Numbers.unchecked_minus(long,long)" [Opcodes/LSUB] "public static long clojure.lang.Numbers.unchecked_multiply(long,long)" [Opcodes/LMUL] "public static double clojure.lang.Numbers.unchecked_multiply(double,double)" [Opcodes/DMUL] "public static double clojure.lang.Numbers.unchecked_inc(double)" [Opcodes/DCONST_1 Opcodes/DADD] "public static long clojure.lang.Numbers.unchecked_inc(long)" [Opcodes/LCONST_1 Opcodes/LADD] "public static double clojure.lang.Numbers.unchecked_dec(double)" [Opcodes/DCONST_1 Opcodes/DSUB] "public static long clojure.lang.Numbers.unchecked_dec(long)" [Opcodes/LCONST_1 Opcodes/LSUB] "public static short clojure.lang.RT.aget(short[]int)" [Opcodes/SALOAD] "public static float clojure.lang.RT.aget(float[]int)" [Opcodes/FALOAD] "public static double clojure.lang.RT.aget(double[]int)" [Opcodes/DALOAD] "public static int clojure.lang.RT.aget(int[]int)" [Opcodes/IALOAD] "public static long clojure.lang.RT.aget(long[]int)" [Opcodes/LALOAD] "public static char clojure.lang.RT.aget(char[]int)" [Opcodes/CALOAD] "public static byte clojure.lang.RT.aget(byte[]int)" [Opcodes/BALOAD] "public static boolean clojure.lang.RT.aget(boolean[]int)" [Opcodes/BALOAD] "public static java.lang.Object clojure.lang.RT.aget(java.lang.Object[]int)" [Opcodes/AALOAD] "public static int clojure.lang.RT.alength(int[])" [Opcodes/ARRAYLENGTH] "public static int clojure.lang.RT.alength(long[])" [Opcodes/ARRAYLENGTH] "public static int clojure.lang.RT.alength(char[])" [Opcodes/ARRAYLENGTH] "public static int clojure.lang.RT.alength(java.lang.Object[])" [Opcodes/ARRAYLENGTH] "public static int clojure.lang.RT.alength(byte[])" [Opcodes/ARRAYLENGTH] "public static int clojure.lang.RT.alength(float[])" [Opcodes/ARRAYLENGTH] "public static int clojure.lang.RT.alength(short[])" [Opcodes/ARRAYLENGTH] "public static int clojure.lang.RT.alength(boolean[])" [Opcodes/ARRAYLENGTH] "public static int clojure.lang.RT.alength(double[])" [Opcodes/ARRAYLENGTH] "public static double clojure.lang.RT.doubleCast(long)" [Opcodes/L2D] "public static double clojure.lang.RT.doubleCast(double)" [Opcodes/NOP] "public static double clojure.lang.RT.doubleCast(float)" [Opcodes/F2D] "public static double clojure.lang.RT.doubleCast(int)" [Opcodes/I2D] "public static double clojure.lang.RT.doubleCast(short)" [Opcodes/I2D] "public static double clojure.lang.RT.doubleCast(byte)" [Opcodes/I2D] "public static double clojure.lang.RT.uncheckedDoubleCast(double)" [Opcodes/NOP] "public static double clojure.lang.RT.uncheckedDoubleCast(float)" [Opcodes/F2D] "public static double clojure.lang.RT.uncheckedDoubleCast(long)" [Opcodes/L2D] "public static double clojure.lang.RT.uncheckedDoubleCast(int)" [Opcodes/I2D] "public static double clojure.lang.RT.uncheckedDoubleCast(short)" [Opcodes/I2D] "public static double clojure.lang.RT.uncheckedDoubleCast(byte)" [Opcodes/I2D] "public static long clojure.lang.RT.longCast(long)" [Opcodes/NOP] "public static long clojure.lang.RT.longCast(short)" [Opcodes/I2L] "public static long clojure.lang.RT.longCast(byte)" [Opcodes/I2L] "public static long clojure.lang.RT.longCast(int)" [Opcodes/I2L] "public static int clojure.lang.RT.uncheckedIntCast(long)" [Opcodes/L2I] "public static int clojure.lang.RT.uncheckedIntCast(double)" [Opcodes/D2I] "public static int clojure.lang.RT.uncheckedIntCast(byte)" [Opcodes/NOP] "public static int clojure.lang.RT.uncheckedIntCast(short)" [Opcodes/NOP] "public static int clojure.lang.RT.uncheckedIntCast(char)" [Opcodes/NOP] "public static int clojure.lang.RT.uncheckedIntCast(int)" [Opcodes/NOP] "public static int clojure.lang.RT.uncheckedIntCast(float)" [Opcodes/F2I] "public static long clojure.lang.RT.uncheckedLongCast(short)" [Opcodes/I2L] "public static long clojure.lang.RT.uncheckedLongCast(float)" [Opcodes/F2L] "public static long clojure.lang.RT.uncheckedLongCast(double)" [Opcodes/D2L] "public static long clojure.lang.RT.uncheckedLongCast(byte)" [Opcodes/I2L] "public static long clojure.lang.RT.uncheckedLongCast(long)" [Opcodes/NOP] "public static long clojure.lang.RT.uncheckedLongCast(int)" [Opcodes/I2L]}) (def intrinsic-predicate {"public static boolean clojure.lang.Numbers.lt(double,double)" [Opcodes/DCMPG Opcodes/IFGE] "public static boolean clojure.lang.Numbers.lt(long,long)" [Opcodes/LCMP Opcodes/IFGE] "public static boolean clojure.lang.Numbers.equiv(double,double)" [Opcodes/DCMPL Opcodes/IFNE] "public static boolean clojure.lang.Numbers.equiv(long,long)" [Opcodes/LCMP Opcodes/IFNE] "public static boolean clojure.lang.Numbers.lte(double,double)" [Opcodes/DCMPG Opcodes/IFGT] "public static boolean clojure.lang.Numbers.lte(long,long)" [Opcodes/LCMP Opcodes/IFGT] "public static boolean clojure.lang.Numbers.gt(long,long)" [Opcodes/LCMP Opcodes/IFLE] "public static boolean clojure.lang.Numbers.gt(double,double)" [Opcodes/DCMPL Opcodes/IFLE] "public static boolean clojure.lang.Numbers.gte(long,long)" [Opcodes/LCMP Opcodes/IFLT] "public static boolean clojure.lang.Numbers.gte(double,double)" [Opcodes/DCMPL Opcodes/IFLT] "public static boolean clojure.lang.Util.equiv(long,long)" [Opcodes/LCMP Opcodes/IFNE] "public static boolean clojure.lang.Util.equiv(boolean,boolean)" [Opcodes/IF_ICMPNE] "public static boolean clojure.lang.Util.equiv(double,double)" [Opcodes/DCMPL Opcodes/IFNE] "public static boolean clojure.lang.Numbers.isZero(double)" [Opcodes/DCONST_0 Opcodes/DCMPL Opcodes/IFNE] "public static boolean clojure.lang.Numbers.isZero(long)" [Opcodes/LCONST_0 Opcodes/LCMP Opcodes/IFNE] "public static boolean clojure.lang.Numbers.isPos(long)" [Opcodes/LCONST_0 Opcodes/LCMP Opcodes/IFLE] "public static boolean clojure.lang.Numbers.isPos(double)" [Opcodes/DCONST_0 Opcodes/DCMPL Opcodes/IFLE] "public static boolean clojure.lang.Numbers.isNeg(long)" [Opcodes/LCONST_0 Opcodes/LCMP Opcodes/IFGE] "public static boolean clojure.lang.Numbers.isNeg(double)" [Opcodes/DCONST_0 Opcodes/DCMPG Opcodes/IFGE]})
77
;; Copyright (c) <NAME>, <NAME> & contributors. ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns clojure.tools.emitter.jvm.intrinsics (:import (org.objectweb.asm Opcodes))) (def intrinsic {"public static double clojure.lang.Numbers.add(double,double)" [Opcodes/DADD] "public static long clojure.lang.Numbers.and(long,long)" [Opcodes/LAND] "public static long clojure.lang.Numbers.or(long,long)" [Opcodes/LOR] "public static long clojure.lang.Numbers.xor(long,long)" [Opcodes/LXOR] "public static double clojure.lang.Numbers.multiply(double,double)" [Opcodes/DMUL] "public static double clojure.lang.Numbers.divide(double,double)" [Opcodes/DDIV] "public static long clojure.lang.Numbers.remainder(long,long)" [Opcodes/LREM] "public static long clojure.lang.Numbers.shiftLeft(long,long)" [Opcodes/L2I Opcodes/LSHL] "public static long clojure.lang.Numbers.shiftRight(long,long)" [Opcodes/L2I Opcodes/LSHR] "public static double clojure.lang.Numbers.minus(double)" [Opcodes/DNEG] "public static double clojure.lang.Numbers.minus(double,double)" [Opcodes/DSUB] "public static double clojure.lang.Numbers.inc(double)" [Opcodes/DCONST_1 Opcodes/DADD] "public static double clojure.lang.Numbers.dec(double)" [Opcodes/DCONST_1 Opcodes/DSUB] "public static long clojure.lang.Numbers.quotient(long,long)" [Opcodes/LDIV] "public static int clojure.lang.Numbers.shiftLeftInt(int,int)" [Opcodes/ISHL] "public static int clojure.lang.Numbers.shiftRightInt(int,int)" [Opcodes/ISHR] "public static int clojure.lang.Numbers.unchecked_int_add(int,int)" [Opcodes/IADD] "public static int clojure.lang.Numbers.unchecked_int_subtract(int,int)" [Opcodes/ISUB] "public static int clojure.lang.Numbers.unchecked_int_negate(int)" [Opcodes/INEG] "public static int clojure.lang.Numbers.unchecked_int_inc(int)" [Opcodes/ICONST_1 Opcodes/IADD] "public static int clojure.lang.Numbers.unchecked_int_dec(int)" [Opcodes/ICONST_1 Opcodes/ISUB] "public static int clojure.lang.Numbers.unchecked_int_multiply(int,int)" [Opcodes/IMUL] "public static int clojure.lang.Numbers.unchecked_int_divide(int,int)" [Opcodes/IDIV] "public static int clojure.lang.Numbers.unchecked_int_remainder(int,int)" [Opcodes/IREM] "public static long clojure.lang.Numbers.unchecked_add(long,long)" [Opcodes/LADD] "public static double clojure.lang.Numbers.unchecked_add(double,double)" [Opcodes/DADD] "public static long clojure.lang.Numbers.unchecked_minus(long)" [Opcodes/LNEG] "public static double clojure.lang.Numbers.unchecked_minus(double)" [Opcodes/DNEG] "public static double clojure.lang.Numbers.unchecked_minus(double,double)" [Opcodes/DSUB] "public static long clojure.lang.Numbers.unchecked_minus(long,long)" [Opcodes/LSUB] "public static long clojure.lang.Numbers.unchecked_multiply(long,long)" [Opcodes/LMUL] "public static double clojure.lang.Numbers.unchecked_multiply(double,double)" [Opcodes/DMUL] "public static double clojure.lang.Numbers.unchecked_inc(double)" [Opcodes/DCONST_1 Opcodes/DADD] "public static long clojure.lang.Numbers.unchecked_inc(long)" [Opcodes/LCONST_1 Opcodes/LADD] "public static double clojure.lang.Numbers.unchecked_dec(double)" [Opcodes/DCONST_1 Opcodes/DSUB] "public static long clojure.lang.Numbers.unchecked_dec(long)" [Opcodes/LCONST_1 Opcodes/LSUB] "public static short clojure.lang.RT.aget(short[]int)" [Opcodes/SALOAD] "public static float clojure.lang.RT.aget(float[]int)" [Opcodes/FALOAD] "public static double clojure.lang.RT.aget(double[]int)" [Opcodes/DALOAD] "public static int clojure.lang.RT.aget(int[]int)" [Opcodes/IALOAD] "public static long clojure.lang.RT.aget(long[]int)" [Opcodes/LALOAD] "public static char clojure.lang.RT.aget(char[]int)" [Opcodes/CALOAD] "public static byte clojure.lang.RT.aget(byte[]int)" [Opcodes/BALOAD] "public static boolean clojure.lang.RT.aget(boolean[]int)" [Opcodes/BALOAD] "public static java.lang.Object clojure.lang.RT.aget(java.lang.Object[]int)" [Opcodes/AALOAD] "public static int clojure.lang.RT.alength(int[])" [Opcodes/ARRAYLENGTH] "public static int clojure.lang.RT.alength(long[])" [Opcodes/ARRAYLENGTH] "public static int clojure.lang.RT.alength(char[])" [Opcodes/ARRAYLENGTH] "public static int clojure.lang.RT.alength(java.lang.Object[])" [Opcodes/ARRAYLENGTH] "public static int clojure.lang.RT.alength(byte[])" [Opcodes/ARRAYLENGTH] "public static int clojure.lang.RT.alength(float[])" [Opcodes/ARRAYLENGTH] "public static int clojure.lang.RT.alength(short[])" [Opcodes/ARRAYLENGTH] "public static int clojure.lang.RT.alength(boolean[])" [Opcodes/ARRAYLENGTH] "public static int clojure.lang.RT.alength(double[])" [Opcodes/ARRAYLENGTH] "public static double clojure.lang.RT.doubleCast(long)" [Opcodes/L2D] "public static double clojure.lang.RT.doubleCast(double)" [Opcodes/NOP] "public static double clojure.lang.RT.doubleCast(float)" [Opcodes/F2D] "public static double clojure.lang.RT.doubleCast(int)" [Opcodes/I2D] "public static double clojure.lang.RT.doubleCast(short)" [Opcodes/I2D] "public static double clojure.lang.RT.doubleCast(byte)" [Opcodes/I2D] "public static double clojure.lang.RT.uncheckedDoubleCast(double)" [Opcodes/NOP] "public static double clojure.lang.RT.uncheckedDoubleCast(float)" [Opcodes/F2D] "public static double clojure.lang.RT.uncheckedDoubleCast(long)" [Opcodes/L2D] "public static double clojure.lang.RT.uncheckedDoubleCast(int)" [Opcodes/I2D] "public static double clojure.lang.RT.uncheckedDoubleCast(short)" [Opcodes/I2D] "public static double clojure.lang.RT.uncheckedDoubleCast(byte)" [Opcodes/I2D] "public static long clojure.lang.RT.longCast(long)" [Opcodes/NOP] "public static long clojure.lang.RT.longCast(short)" [Opcodes/I2L] "public static long clojure.lang.RT.longCast(byte)" [Opcodes/I2L] "public static long clojure.lang.RT.longCast(int)" [Opcodes/I2L] "public static int clojure.lang.RT.uncheckedIntCast(long)" [Opcodes/L2I] "public static int clojure.lang.RT.uncheckedIntCast(double)" [Opcodes/D2I] "public static int clojure.lang.RT.uncheckedIntCast(byte)" [Opcodes/NOP] "public static int clojure.lang.RT.uncheckedIntCast(short)" [Opcodes/NOP] "public static int clojure.lang.RT.uncheckedIntCast(char)" [Opcodes/NOP] "public static int clojure.lang.RT.uncheckedIntCast(int)" [Opcodes/NOP] "public static int clojure.lang.RT.uncheckedIntCast(float)" [Opcodes/F2I] "public static long clojure.lang.RT.uncheckedLongCast(short)" [Opcodes/I2L] "public static long clojure.lang.RT.uncheckedLongCast(float)" [Opcodes/F2L] "public static long clojure.lang.RT.uncheckedLongCast(double)" [Opcodes/D2L] "public static long clojure.lang.RT.uncheckedLongCast(byte)" [Opcodes/I2L] "public static long clojure.lang.RT.uncheckedLongCast(long)" [Opcodes/NOP] "public static long clojure.lang.RT.uncheckedLongCast(int)" [Opcodes/I2L]}) (def intrinsic-predicate {"public static boolean clojure.lang.Numbers.lt(double,double)" [Opcodes/DCMPG Opcodes/IFGE] "public static boolean clojure.lang.Numbers.lt(long,long)" [Opcodes/LCMP Opcodes/IFGE] "public static boolean clojure.lang.Numbers.equiv(double,double)" [Opcodes/DCMPL Opcodes/IFNE] "public static boolean clojure.lang.Numbers.equiv(long,long)" [Opcodes/LCMP Opcodes/IFNE] "public static boolean clojure.lang.Numbers.lte(double,double)" [Opcodes/DCMPG Opcodes/IFGT] "public static boolean clojure.lang.Numbers.lte(long,long)" [Opcodes/LCMP Opcodes/IFGT] "public static boolean clojure.lang.Numbers.gt(long,long)" [Opcodes/LCMP Opcodes/IFLE] "public static boolean clojure.lang.Numbers.gt(double,double)" [Opcodes/DCMPL Opcodes/IFLE] "public static boolean clojure.lang.Numbers.gte(long,long)" [Opcodes/LCMP Opcodes/IFLT] "public static boolean clojure.lang.Numbers.gte(double,double)" [Opcodes/DCMPL Opcodes/IFLT] "public static boolean clojure.lang.Util.equiv(long,long)" [Opcodes/LCMP Opcodes/IFNE] "public static boolean clojure.lang.Util.equiv(boolean,boolean)" [Opcodes/IF_ICMPNE] "public static boolean clojure.lang.Util.equiv(double,double)" [Opcodes/DCMPL Opcodes/IFNE] "public static boolean clojure.lang.Numbers.isZero(double)" [Opcodes/DCONST_0 Opcodes/DCMPL Opcodes/IFNE] "public static boolean clojure.lang.Numbers.isZero(long)" [Opcodes/LCONST_0 Opcodes/LCMP Opcodes/IFNE] "public static boolean clojure.lang.Numbers.isPos(long)" [Opcodes/LCONST_0 Opcodes/LCMP Opcodes/IFLE] "public static boolean clojure.lang.Numbers.isPos(double)" [Opcodes/DCONST_0 Opcodes/DCMPL Opcodes/IFLE] "public static boolean clojure.lang.Numbers.isNeg(long)" [Opcodes/LCONST_0 Opcodes/LCMP Opcodes/IFGE] "public static boolean clojure.lang.Numbers.isNeg(double)" [Opcodes/DCONST_0 Opcodes/DCMPG Opcodes/IFGE]})
true
;; Copyright (c) PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI & contributors. ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns clojure.tools.emitter.jvm.intrinsics (:import (org.objectweb.asm Opcodes))) (def intrinsic {"public static double clojure.lang.Numbers.add(double,double)" [Opcodes/DADD] "public static long clojure.lang.Numbers.and(long,long)" [Opcodes/LAND] "public static long clojure.lang.Numbers.or(long,long)" [Opcodes/LOR] "public static long clojure.lang.Numbers.xor(long,long)" [Opcodes/LXOR] "public static double clojure.lang.Numbers.multiply(double,double)" [Opcodes/DMUL] "public static double clojure.lang.Numbers.divide(double,double)" [Opcodes/DDIV] "public static long clojure.lang.Numbers.remainder(long,long)" [Opcodes/LREM] "public static long clojure.lang.Numbers.shiftLeft(long,long)" [Opcodes/L2I Opcodes/LSHL] "public static long clojure.lang.Numbers.shiftRight(long,long)" [Opcodes/L2I Opcodes/LSHR] "public static double clojure.lang.Numbers.minus(double)" [Opcodes/DNEG] "public static double clojure.lang.Numbers.minus(double,double)" [Opcodes/DSUB] "public static double clojure.lang.Numbers.inc(double)" [Opcodes/DCONST_1 Opcodes/DADD] "public static double clojure.lang.Numbers.dec(double)" [Opcodes/DCONST_1 Opcodes/DSUB] "public static long clojure.lang.Numbers.quotient(long,long)" [Opcodes/LDIV] "public static int clojure.lang.Numbers.shiftLeftInt(int,int)" [Opcodes/ISHL] "public static int clojure.lang.Numbers.shiftRightInt(int,int)" [Opcodes/ISHR] "public static int clojure.lang.Numbers.unchecked_int_add(int,int)" [Opcodes/IADD] "public static int clojure.lang.Numbers.unchecked_int_subtract(int,int)" [Opcodes/ISUB] "public static int clojure.lang.Numbers.unchecked_int_negate(int)" [Opcodes/INEG] "public static int clojure.lang.Numbers.unchecked_int_inc(int)" [Opcodes/ICONST_1 Opcodes/IADD] "public static int clojure.lang.Numbers.unchecked_int_dec(int)" [Opcodes/ICONST_1 Opcodes/ISUB] "public static int clojure.lang.Numbers.unchecked_int_multiply(int,int)" [Opcodes/IMUL] "public static int clojure.lang.Numbers.unchecked_int_divide(int,int)" [Opcodes/IDIV] "public static int clojure.lang.Numbers.unchecked_int_remainder(int,int)" [Opcodes/IREM] "public static long clojure.lang.Numbers.unchecked_add(long,long)" [Opcodes/LADD] "public static double clojure.lang.Numbers.unchecked_add(double,double)" [Opcodes/DADD] "public static long clojure.lang.Numbers.unchecked_minus(long)" [Opcodes/LNEG] "public static double clojure.lang.Numbers.unchecked_minus(double)" [Opcodes/DNEG] "public static double clojure.lang.Numbers.unchecked_minus(double,double)" [Opcodes/DSUB] "public static long clojure.lang.Numbers.unchecked_minus(long,long)" [Opcodes/LSUB] "public static long clojure.lang.Numbers.unchecked_multiply(long,long)" [Opcodes/LMUL] "public static double clojure.lang.Numbers.unchecked_multiply(double,double)" [Opcodes/DMUL] "public static double clojure.lang.Numbers.unchecked_inc(double)" [Opcodes/DCONST_1 Opcodes/DADD] "public static long clojure.lang.Numbers.unchecked_inc(long)" [Opcodes/LCONST_1 Opcodes/LADD] "public static double clojure.lang.Numbers.unchecked_dec(double)" [Opcodes/DCONST_1 Opcodes/DSUB] "public static long clojure.lang.Numbers.unchecked_dec(long)" [Opcodes/LCONST_1 Opcodes/LSUB] "public static short clojure.lang.RT.aget(short[]int)" [Opcodes/SALOAD] "public static float clojure.lang.RT.aget(float[]int)" [Opcodes/FALOAD] "public static double clojure.lang.RT.aget(double[]int)" [Opcodes/DALOAD] "public static int clojure.lang.RT.aget(int[]int)" [Opcodes/IALOAD] "public static long clojure.lang.RT.aget(long[]int)" [Opcodes/LALOAD] "public static char clojure.lang.RT.aget(char[]int)" [Opcodes/CALOAD] "public static byte clojure.lang.RT.aget(byte[]int)" [Opcodes/BALOAD] "public static boolean clojure.lang.RT.aget(boolean[]int)" [Opcodes/BALOAD] "public static java.lang.Object clojure.lang.RT.aget(java.lang.Object[]int)" [Opcodes/AALOAD] "public static int clojure.lang.RT.alength(int[])" [Opcodes/ARRAYLENGTH] "public static int clojure.lang.RT.alength(long[])" [Opcodes/ARRAYLENGTH] "public static int clojure.lang.RT.alength(char[])" [Opcodes/ARRAYLENGTH] "public static int clojure.lang.RT.alength(java.lang.Object[])" [Opcodes/ARRAYLENGTH] "public static int clojure.lang.RT.alength(byte[])" [Opcodes/ARRAYLENGTH] "public static int clojure.lang.RT.alength(float[])" [Opcodes/ARRAYLENGTH] "public static int clojure.lang.RT.alength(short[])" [Opcodes/ARRAYLENGTH] "public static int clojure.lang.RT.alength(boolean[])" [Opcodes/ARRAYLENGTH] "public static int clojure.lang.RT.alength(double[])" [Opcodes/ARRAYLENGTH] "public static double clojure.lang.RT.doubleCast(long)" [Opcodes/L2D] "public static double clojure.lang.RT.doubleCast(double)" [Opcodes/NOP] "public static double clojure.lang.RT.doubleCast(float)" [Opcodes/F2D] "public static double clojure.lang.RT.doubleCast(int)" [Opcodes/I2D] "public static double clojure.lang.RT.doubleCast(short)" [Opcodes/I2D] "public static double clojure.lang.RT.doubleCast(byte)" [Opcodes/I2D] "public static double clojure.lang.RT.uncheckedDoubleCast(double)" [Opcodes/NOP] "public static double clojure.lang.RT.uncheckedDoubleCast(float)" [Opcodes/F2D] "public static double clojure.lang.RT.uncheckedDoubleCast(long)" [Opcodes/L2D] "public static double clojure.lang.RT.uncheckedDoubleCast(int)" [Opcodes/I2D] "public static double clojure.lang.RT.uncheckedDoubleCast(short)" [Opcodes/I2D] "public static double clojure.lang.RT.uncheckedDoubleCast(byte)" [Opcodes/I2D] "public static long clojure.lang.RT.longCast(long)" [Opcodes/NOP] "public static long clojure.lang.RT.longCast(short)" [Opcodes/I2L] "public static long clojure.lang.RT.longCast(byte)" [Opcodes/I2L] "public static long clojure.lang.RT.longCast(int)" [Opcodes/I2L] "public static int clojure.lang.RT.uncheckedIntCast(long)" [Opcodes/L2I] "public static int clojure.lang.RT.uncheckedIntCast(double)" [Opcodes/D2I] "public static int clojure.lang.RT.uncheckedIntCast(byte)" [Opcodes/NOP] "public static int clojure.lang.RT.uncheckedIntCast(short)" [Opcodes/NOP] "public static int clojure.lang.RT.uncheckedIntCast(char)" [Opcodes/NOP] "public static int clojure.lang.RT.uncheckedIntCast(int)" [Opcodes/NOP] "public static int clojure.lang.RT.uncheckedIntCast(float)" [Opcodes/F2I] "public static long clojure.lang.RT.uncheckedLongCast(short)" [Opcodes/I2L] "public static long clojure.lang.RT.uncheckedLongCast(float)" [Opcodes/F2L] "public static long clojure.lang.RT.uncheckedLongCast(double)" [Opcodes/D2L] "public static long clojure.lang.RT.uncheckedLongCast(byte)" [Opcodes/I2L] "public static long clojure.lang.RT.uncheckedLongCast(long)" [Opcodes/NOP] "public static long clojure.lang.RT.uncheckedLongCast(int)" [Opcodes/I2L]}) (def intrinsic-predicate {"public static boolean clojure.lang.Numbers.lt(double,double)" [Opcodes/DCMPG Opcodes/IFGE] "public static boolean clojure.lang.Numbers.lt(long,long)" [Opcodes/LCMP Opcodes/IFGE] "public static boolean clojure.lang.Numbers.equiv(double,double)" [Opcodes/DCMPL Opcodes/IFNE] "public static boolean clojure.lang.Numbers.equiv(long,long)" [Opcodes/LCMP Opcodes/IFNE] "public static boolean clojure.lang.Numbers.lte(double,double)" [Opcodes/DCMPG Opcodes/IFGT] "public static boolean clojure.lang.Numbers.lte(long,long)" [Opcodes/LCMP Opcodes/IFGT] "public static boolean clojure.lang.Numbers.gt(long,long)" [Opcodes/LCMP Opcodes/IFLE] "public static boolean clojure.lang.Numbers.gt(double,double)" [Opcodes/DCMPL Opcodes/IFLE] "public static boolean clojure.lang.Numbers.gte(long,long)" [Opcodes/LCMP Opcodes/IFLT] "public static boolean clojure.lang.Numbers.gte(double,double)" [Opcodes/DCMPL Opcodes/IFLT] "public static boolean clojure.lang.Util.equiv(long,long)" [Opcodes/LCMP Opcodes/IFNE] "public static boolean clojure.lang.Util.equiv(boolean,boolean)" [Opcodes/IF_ICMPNE] "public static boolean clojure.lang.Util.equiv(double,double)" [Opcodes/DCMPL Opcodes/IFNE] "public static boolean clojure.lang.Numbers.isZero(double)" [Opcodes/DCONST_0 Opcodes/DCMPL Opcodes/IFNE] "public static boolean clojure.lang.Numbers.isZero(long)" [Opcodes/LCONST_0 Opcodes/LCMP Opcodes/IFNE] "public static boolean clojure.lang.Numbers.isPos(long)" [Opcodes/LCONST_0 Opcodes/LCMP Opcodes/IFLE] "public static boolean clojure.lang.Numbers.isPos(double)" [Opcodes/DCONST_0 Opcodes/DCMPL Opcodes/IFLE] "public static boolean clojure.lang.Numbers.isNeg(long)" [Opcodes/LCONST_0 Opcodes/LCMP Opcodes/IFGE] "public static boolean clojure.lang.Numbers.isNeg(double)" [Opcodes/DCONST_0 Opcodes/DCMPG Opcodes/IFGE]})
[ { "context": "e :challenger {:card kate-choice})))\n akiko \"Akiko Nisei: Head Case\"\n kate \"Kate \\\"Mac\\\" McCaffrey: D", "end": 571, "score": 0.9976896047592163, "start": 560, "tag": "NAME", "value": "Akiko Nisei" }, { "context": "\n akiko \"Akiko Nisei: Head Case\"\n kate \"Kate \\\"Mac\\\" McCaffrey: Digital Tinker\"\n kit \"Rie", "end": 600, "score": 0.8929122686386108, "start": 596, "tag": "NAME", "value": "Kate" }, { "context": "kiko Nisei: Head Case\"\n kate \"Kate \\\"Mac\\\" McCaffrey: Digital Tinker\"\n kit \"Rielle \\\"Kit\\\" Peddle", "end": 618, "score": 0.9364299178123474, "start": 611, "tag": "NAME", "value": "Caffrey" }, { "context": "ate \\\"Mac\\\" McCaffrey: Digital Tinker\"\n kit \"Rielle \\\"Kit\\\" Peddler: Transhuman\"\n professor \"The", "end": 653, "score": 0.8116231560707092, "start": 647, "tag": "NAME", "value": "Rielle" }, { "context": "\"The Professor: Keeper of Knowledge\"\n jamie \"Jamie \\\"Bzzz\\\" Micken: Techno Savant\"\n chaos \"Chao", "end": 754, "score": 0.9878386855125427, "start": 749, "tag": "NAME", "value": "Jamie" }, { "context": "essor: Keeper of Knowledge\"\n jamie \"Jamie \\\"Bzzz\\\" Micken: Techno Savant\"\n chaos \"Chaos Theor", "end": 761, "score": 0.9178703427314758, "start": 758, "tag": "NAME", "value": "zzz" }, { "context": ": Keeper of Knowledge\"\n jamie \"Jamie \\\"Bzzz\\\" Micken: Techno Savant\"\n chaos \"Chaos Theory: Wünder", "end": 770, "score": 0.9161586761474609, "start": 764, "tag": "NAME", "value": "Micken" }, { "context": " whizzard \"Whizzard: Master Gamer\"\n reina \"Reina Roja: Freedom Fighter\"]\n (deftest rebirth\n ;; Rebi", "end": 889, "score": 0.9880324006080627, "start": 879, "tag": "NAME", "value": "Reina Roja" }, { "context": " (play-from-hand state :challenger \"Magnum Opus\")))))\n (testing \"Whizzard works after rebirth\"", "end": 1907, "score": 0.6688616275787354, "start": 1896, "tag": "NAME", "value": "Magnum Opus" } ]
test/clj/game_test/cards/events.clj
rezwits/carncode
15
(ns game-test.cards.events (:require [game.core :as core] [game-test.core :refer :all] [game-test.utils :refer :all] [game-test.macros :refer :all] [clojure.test :refer :all])) (use-fixtures :once load-all-cards (partial reset-card-defs "events")) ;; Rebirth (let [choose-challenger (fn [id-name state prompt-map] (let [kate-choice (some #(when (= id-name (:title %)) %) (:choices (prompt-map :challenger)))] (core/resolve-prompt state :challenger {:card kate-choice}))) akiko "Akiko Nisei: Head Case" kate "Kate \"Mac\" McCaffrey: Digital Tinker" kit "Rielle \"Kit\" Peddler: Transhuman" professor "The Professor: Keeper of Knowledge" jamie "Jamie \"Bzzz\" Micken: Techno Savant" chaos "Chaos Theory: Wünderkind" whizzard "Whizzard: Master Gamer" reina "Reina Roja: Freedom Fighter"] (deftest rebirth ;; Rebirth - Kate's discount applies after rebirth (testing "Kate" (do-game (new-game (default-contestant) (default-challenger ["Magnum Opus" "Rebirth"]) {:start-as :challenger}) (play-from-hand state :challenger "Rebirth") (is (= (first (prompt-titles :challenger)) akiko) "List is sorted") (is (every? #(some #{%} (prompt-titles :challenger)) [kate kit])) (is (not-any? #(some #{%} (prompt-titles :challenger)) [professor whizzard jamie])) (choose-challenger kate state prompt-map) (is (= kate (-> (get-challenger) :identity :title))) (is (= 1 (:link (get-challenger))) "1 link") (is (empty? (:discard (get-challenger)))) (is (= "Rebirth" (-> (get-challenger) :rfg first :title))) (is (changes-credits (get-challenger) -4 (play-from-hand state :challenger "Magnum Opus"))))) (testing "Whizzard works after rebirth" (do-game (new-game (default-contestant ["Character Wall"]) (make-deck reina ["Rebirth"])) (play-from-hand state :contestant "Character Wall" "R&D") (play-from-hand state :challenger "Rebirth") (choose-challenger whizzard state prompt-map) (card-ability state :challenger (:identity (get-challenger)) 0) (is (= 6 (:credit (get-challenger))) "Took a Whizzard credit") (is (changes-credits (get-contestant) -1 (core/reveal state :contestant (get-character state :rd 0))) "Reina is no longer active"))) (testing "Lose link from ID" (do-game (new-game (default-contestant) (make-deck kate ["Rebirth" "Access to Globalsec"]) {:start-as :challenger}) (play-from-hand state :challenger "Access to Globalsec") (is (= 2 (:link (get-challenger))) "2 link before rebirth") (play-from-hand state :challenger "Rebirth") (choose-challenger chaos state prompt-map) (is (= 1 (:link (get-challenger))) "1 link after rebirth"))) (testing "Gain link from ID" (do-game (new-game (default-contestant) (default-challenger ["Rebirth" "Access to Globalsec"]) {:start-as :challenger}) (play-from-hand state :challenger "Access to Globalsec") (is (= 1 (:link (get-challenger))) "1 link before rebirth") (play-from-hand state :challenger "Rebirth") (choose-challenger kate state prompt-map) (is (= 2 (:link (get-challenger))) "2 link after rebirth")))) (deftest-pending rebirth-kate-twcharacter ;; Rebirth - Kate's discount does not after rebirth if something already placed (do-game (new-game (default-contestant) (default-challenger ["Akamatsu Mem Chip" "Rebirth" "Clone Chip"]) {:start-as :challenger}) (play-from-hand state :challenger "Clone Chip") (play-from-hand state :challenger "Rebirth") (choose-challenger kate state prompt-map) (is (changes-credits (get-contestant) -1 (play-from-hand state :challenger "Akamatsu Mem Chip")) "Discount not applied for 2nd place"))))
104276
(ns game-test.cards.events (:require [game.core :as core] [game-test.core :refer :all] [game-test.utils :refer :all] [game-test.macros :refer :all] [clojure.test :refer :all])) (use-fixtures :once load-all-cards (partial reset-card-defs "events")) ;; Rebirth (let [choose-challenger (fn [id-name state prompt-map] (let [kate-choice (some #(when (= id-name (:title %)) %) (:choices (prompt-map :challenger)))] (core/resolve-prompt state :challenger {:card kate-choice}))) akiko "<NAME>: Head Case" kate "<NAME> \"Mac\" Mc<NAME>: Digital Tinker" kit "<NAME> \"Kit\" Peddler: Transhuman" professor "The Professor: Keeper of Knowledge" jamie "<NAME> \"B<NAME>\" <NAME>: Techno Savant" chaos "Chaos Theory: Wünderkind" whizzard "Whizzard: Master Gamer" reina "<NAME>: Freedom Fighter"] (deftest rebirth ;; Rebirth - Kate's discount applies after rebirth (testing "Kate" (do-game (new-game (default-contestant) (default-challenger ["Magnum Opus" "Rebirth"]) {:start-as :challenger}) (play-from-hand state :challenger "Rebirth") (is (= (first (prompt-titles :challenger)) akiko) "List is sorted") (is (every? #(some #{%} (prompt-titles :challenger)) [kate kit])) (is (not-any? #(some #{%} (prompt-titles :challenger)) [professor whizzard jamie])) (choose-challenger kate state prompt-map) (is (= kate (-> (get-challenger) :identity :title))) (is (= 1 (:link (get-challenger))) "1 link") (is (empty? (:discard (get-challenger)))) (is (= "Rebirth" (-> (get-challenger) :rfg first :title))) (is (changes-credits (get-challenger) -4 (play-from-hand state :challenger "<NAME>"))))) (testing "Whizzard works after rebirth" (do-game (new-game (default-contestant ["Character Wall"]) (make-deck reina ["Rebirth"])) (play-from-hand state :contestant "Character Wall" "R&D") (play-from-hand state :challenger "Rebirth") (choose-challenger whizzard state prompt-map) (card-ability state :challenger (:identity (get-challenger)) 0) (is (= 6 (:credit (get-challenger))) "Took a Whizzard credit") (is (changes-credits (get-contestant) -1 (core/reveal state :contestant (get-character state :rd 0))) "Reina is no longer active"))) (testing "Lose link from ID" (do-game (new-game (default-contestant) (make-deck kate ["Rebirth" "Access to Globalsec"]) {:start-as :challenger}) (play-from-hand state :challenger "Access to Globalsec") (is (= 2 (:link (get-challenger))) "2 link before rebirth") (play-from-hand state :challenger "Rebirth") (choose-challenger chaos state prompt-map) (is (= 1 (:link (get-challenger))) "1 link after rebirth"))) (testing "Gain link from ID" (do-game (new-game (default-contestant) (default-challenger ["Rebirth" "Access to Globalsec"]) {:start-as :challenger}) (play-from-hand state :challenger "Access to Globalsec") (is (= 1 (:link (get-challenger))) "1 link before rebirth") (play-from-hand state :challenger "Rebirth") (choose-challenger kate state prompt-map) (is (= 2 (:link (get-challenger))) "2 link after rebirth")))) (deftest-pending rebirth-kate-twcharacter ;; Rebirth - Kate's discount does not after rebirth if something already placed (do-game (new-game (default-contestant) (default-challenger ["Akamatsu Mem Chip" "Rebirth" "Clone Chip"]) {:start-as :challenger}) (play-from-hand state :challenger "Clone Chip") (play-from-hand state :challenger "Rebirth") (choose-challenger kate state prompt-map) (is (changes-credits (get-contestant) -1 (play-from-hand state :challenger "Akamatsu Mem Chip")) "Discount not applied for 2nd place"))))
true
(ns game-test.cards.events (:require [game.core :as core] [game-test.core :refer :all] [game-test.utils :refer :all] [game-test.macros :refer :all] [clojure.test :refer :all])) (use-fixtures :once load-all-cards (partial reset-card-defs "events")) ;; Rebirth (let [choose-challenger (fn [id-name state prompt-map] (let [kate-choice (some #(when (= id-name (:title %)) %) (:choices (prompt-map :challenger)))] (core/resolve-prompt state :challenger {:card kate-choice}))) akiko "PI:NAME:<NAME>END_PI: Head Case" kate "PI:NAME:<NAME>END_PI \"Mac\" McPI:NAME:<NAME>END_PI: Digital Tinker" kit "PI:NAME:<NAME>END_PI \"Kit\" Peddler: Transhuman" professor "The Professor: Keeper of Knowledge" jamie "PI:NAME:<NAME>END_PI \"BPI:NAME:<NAME>END_PI\" PI:NAME:<NAME>END_PI: Techno Savant" chaos "Chaos Theory: Wünderkind" whizzard "Whizzard: Master Gamer" reina "PI:NAME:<NAME>END_PI: Freedom Fighter"] (deftest rebirth ;; Rebirth - Kate's discount applies after rebirth (testing "Kate" (do-game (new-game (default-contestant) (default-challenger ["Magnum Opus" "Rebirth"]) {:start-as :challenger}) (play-from-hand state :challenger "Rebirth") (is (= (first (prompt-titles :challenger)) akiko) "List is sorted") (is (every? #(some #{%} (prompt-titles :challenger)) [kate kit])) (is (not-any? #(some #{%} (prompt-titles :challenger)) [professor whizzard jamie])) (choose-challenger kate state prompt-map) (is (= kate (-> (get-challenger) :identity :title))) (is (= 1 (:link (get-challenger))) "1 link") (is (empty? (:discard (get-challenger)))) (is (= "Rebirth" (-> (get-challenger) :rfg first :title))) (is (changes-credits (get-challenger) -4 (play-from-hand state :challenger "PI:NAME:<NAME>END_PI"))))) (testing "Whizzard works after rebirth" (do-game (new-game (default-contestant ["Character Wall"]) (make-deck reina ["Rebirth"])) (play-from-hand state :contestant "Character Wall" "R&D") (play-from-hand state :challenger "Rebirth") (choose-challenger whizzard state prompt-map) (card-ability state :challenger (:identity (get-challenger)) 0) (is (= 6 (:credit (get-challenger))) "Took a Whizzard credit") (is (changes-credits (get-contestant) -1 (core/reveal state :contestant (get-character state :rd 0))) "Reina is no longer active"))) (testing "Lose link from ID" (do-game (new-game (default-contestant) (make-deck kate ["Rebirth" "Access to Globalsec"]) {:start-as :challenger}) (play-from-hand state :challenger "Access to Globalsec") (is (= 2 (:link (get-challenger))) "2 link before rebirth") (play-from-hand state :challenger "Rebirth") (choose-challenger chaos state prompt-map) (is (= 1 (:link (get-challenger))) "1 link after rebirth"))) (testing "Gain link from ID" (do-game (new-game (default-contestant) (default-challenger ["Rebirth" "Access to Globalsec"]) {:start-as :challenger}) (play-from-hand state :challenger "Access to Globalsec") (is (= 1 (:link (get-challenger))) "1 link before rebirth") (play-from-hand state :challenger "Rebirth") (choose-challenger kate state prompt-map) (is (= 2 (:link (get-challenger))) "2 link after rebirth")))) (deftest-pending rebirth-kate-twcharacter ;; Rebirth - Kate's discount does not after rebirth if something already placed (do-game (new-game (default-contestant) (default-challenger ["Akamatsu Mem Chip" "Rebirth" "Clone Chip"]) {:start-as :challenger}) (play-from-hand state :challenger "Clone Chip") (play-from-hand state :challenger "Rebirth") (choose-challenger kate state prompt-map) (is (changes-credits (get-contestant) -1 (play-from-hand state :challenger "Akamatsu Mem Chip")) "Discount not applied for 2nd place"))))
[ { "context": "dant.com/tagalong_dispatch\")\n :username \"ftedictiontiverstrustrin\"\n :password \"20c9f6fee4da63003649f0b1d6b", "end": 259, "score": 0.9993930459022522, "start": 235, "tag": "USERNAME", "value": "ftedictiontiverstrustrin" }, { "context": "e \"ftedictiontiverstrustrin\"\n :password \"20c9f6fee4da63003649f0b1d6b6ee2fbb6fe342\"))\n\n(def main-db (assoc (cemerick.url/url \"https:", "end": 322, "score": 0.9990075826644897, "start": 282, "tag": "PASSWORD", "value": "20c9f6fee4da63003649f0b1d6b6ee2fbb6fe342" }, { "context": "dant.com/tagalong\")\n :username \"auldimenneedissasenowdre\"\n :password \"2fd53c981c25972e66", "end": 462, "score": 0.9993317127227783, "start": 438, "tag": "USERNAME", "value": "auldimenneedissasenowdre" }, { "context": "enneedissasenowdre\"\n :password \"2fd53c981c25972e66235ff2259850e0b39eb246\"))\n\n(def log-db (assoc (cemerick.url/url \"https:/", "end": 534, "score": 0.999151885509491, "start": 494, "tag": "PASSWORD", "value": "2fd53c981c25972e66235ff2259850e0b39eb246" }, { "context": "ant.com/tagalong_logs\")\n :username \"appousureatteninjuntstio\"\n :password \"7c5976d4ca72c7b15d4be8", "end": 674, "score": 0.9980654716491699, "start": 650, "tag": "USERNAME", "value": "appousureatteninjuntstio" }, { "context": "pousureatteninjuntstio\"\n :password \"7c5976d4ca72c7b15d4be82b19c15441db7e84cd\"))\n\n(defn log [& args]\n (do (apply println args)", "end": 742, "score": 0.9992275238037109, "start": 702, "tag": "PASSWORD", "value": "7c5976d4ca72c7b15d4be82b19c15441db7e84cd" } ]
data/train/clojure/d7c365dcb3e6bad061caa054d5d64b729564edfbcore.clj
harshp8l/deep-learning-lang-detection
84
(ns tagalong-middle.core (:gen-class) (:require [com.ashafa.clutch :as c] [clojure.core.async :as a])) (def dispatch-db (assoc (cemerick.url/url "https://dwoodlock.cloudant.com/tagalong_dispatch") :username "ftedictiontiverstrustrin" :password "20c9f6fee4da63003649f0b1d6b6ee2fbb6fe342")) (def main-db (assoc (cemerick.url/url "https://dwoodlock.cloudant.com/tagalong") :username "auldimenneedissasenowdre" :password "2fd53c981c25972e66235ff2259850e0b39eb246")) (def log-db (assoc (cemerick.url/url "https://dwoodlock.cloudant.com/tagalong_logs") :username "appousureatteninjuntstio" :password "7c5976d4ca72c7b15d4be82b19c15441db7e84cd")) (defn log [& args] (do (apply println args) (c/put-document log-db {:datetime (java.util.Date.) :arguments args}))) (defn get-all-dispatches [] (c/all-documents dispatch-db {:include_docs true})) (defn delete-dispatch [doc] (c/delete-document dispatch-db doc)) (defn process-doc [doc] (log "processing id " (:_id doc)) (if (= (:type doc) "INCREMENT") (let [master-doc (c/get-document main-db "reducer") updated-doc (update-in master-doc [:state :count] inc)] (do (c/put-document main-db updated-doc) (log "Success with id " (:_id doc)) (delete-dispatch doc)) ))) (defn process-existing-queue [] (do (log "processing existing queue...") (let [all-dispatches (get-all-dispatches)] (dorun (map (fn [d] (process-doc (:doc d))) all-dispatches))))) (defn print-dispatch [change] (let [dispatch-doc (:doc change)] (if (and dispatch-doc (not (:_deleted dispatch-doc))) (process-doc dispatch-doc)))) (def change-agent (c/change-agent dispatch-db :include_docs true)) (defn listen-for-new-dispatches [] (log "listening for new dispatches...") (c/start-changes change-agent) (add-watch change-agent :process (fn [key agent previous-change change] (print-dispatch change)))) (defn -main [] (do (process-existing-queue) (listen-for-new-dispatches)))
28912
(ns tagalong-middle.core (:gen-class) (:require [com.ashafa.clutch :as c] [clojure.core.async :as a])) (def dispatch-db (assoc (cemerick.url/url "https://dwoodlock.cloudant.com/tagalong_dispatch") :username "ftedictiontiverstrustrin" :password "<PASSWORD>")) (def main-db (assoc (cemerick.url/url "https://dwoodlock.cloudant.com/tagalong") :username "auldimenneedissasenowdre" :password "<PASSWORD>")) (def log-db (assoc (cemerick.url/url "https://dwoodlock.cloudant.com/tagalong_logs") :username "appousureatteninjuntstio" :password "<PASSWORD>")) (defn log [& args] (do (apply println args) (c/put-document log-db {:datetime (java.util.Date.) :arguments args}))) (defn get-all-dispatches [] (c/all-documents dispatch-db {:include_docs true})) (defn delete-dispatch [doc] (c/delete-document dispatch-db doc)) (defn process-doc [doc] (log "processing id " (:_id doc)) (if (= (:type doc) "INCREMENT") (let [master-doc (c/get-document main-db "reducer") updated-doc (update-in master-doc [:state :count] inc)] (do (c/put-document main-db updated-doc) (log "Success with id " (:_id doc)) (delete-dispatch doc)) ))) (defn process-existing-queue [] (do (log "processing existing queue...") (let [all-dispatches (get-all-dispatches)] (dorun (map (fn [d] (process-doc (:doc d))) all-dispatches))))) (defn print-dispatch [change] (let [dispatch-doc (:doc change)] (if (and dispatch-doc (not (:_deleted dispatch-doc))) (process-doc dispatch-doc)))) (def change-agent (c/change-agent dispatch-db :include_docs true)) (defn listen-for-new-dispatches [] (log "listening for new dispatches...") (c/start-changes change-agent) (add-watch change-agent :process (fn [key agent previous-change change] (print-dispatch change)))) (defn -main [] (do (process-existing-queue) (listen-for-new-dispatches)))
true
(ns tagalong-middle.core (:gen-class) (:require [com.ashafa.clutch :as c] [clojure.core.async :as a])) (def dispatch-db (assoc (cemerick.url/url "https://dwoodlock.cloudant.com/tagalong_dispatch") :username "ftedictiontiverstrustrin" :password "PI:PASSWORD:<PASSWORD>END_PI")) (def main-db (assoc (cemerick.url/url "https://dwoodlock.cloudant.com/tagalong") :username "auldimenneedissasenowdre" :password "PI:PASSWORD:<PASSWORD>END_PI")) (def log-db (assoc (cemerick.url/url "https://dwoodlock.cloudant.com/tagalong_logs") :username "appousureatteninjuntstio" :password "PI:PASSWORD:<PASSWORD>END_PI")) (defn log [& args] (do (apply println args) (c/put-document log-db {:datetime (java.util.Date.) :arguments args}))) (defn get-all-dispatches [] (c/all-documents dispatch-db {:include_docs true})) (defn delete-dispatch [doc] (c/delete-document dispatch-db doc)) (defn process-doc [doc] (log "processing id " (:_id doc)) (if (= (:type doc) "INCREMENT") (let [master-doc (c/get-document main-db "reducer") updated-doc (update-in master-doc [:state :count] inc)] (do (c/put-document main-db updated-doc) (log "Success with id " (:_id doc)) (delete-dispatch doc)) ))) (defn process-existing-queue [] (do (log "processing existing queue...") (let [all-dispatches (get-all-dispatches)] (dorun (map (fn [d] (process-doc (:doc d))) all-dispatches))))) (defn print-dispatch [change] (let [dispatch-doc (:doc change)] (if (and dispatch-doc (not (:_deleted dispatch-doc))) (process-doc dispatch-doc)))) (def change-agent (c/change-agent dispatch-db :include_docs true)) (defn listen-for-new-dispatches [] (log "listening for new dispatches...") (c/start-changes change-agent) (add-watch change-agent :process (fn [key agent previous-change change] (print-dispatch change)))) (defn -main [] (do (process-existing-queue) (listen-for-new-dispatches)))
[ { "context": "lename fan-out part-limit n]\n (let [field-keys #{:a :b :c :d :e :f}\n families {:bc #{:b :c}, :de #{:d :e}}\n ", "end": 3174, "score": 0.9914588928222656, "start": 3158, "tag": "KEY", "value": "a :b :c :d :e :f" } ]
dev/user.clj
greglook/merkle-db
47
(ns user "Custom repl customization for local development." (:require [blocks.core :as block] [blocks.store.file :refer [file-block-store]] [clojure.data.csv :as csv] [clojure.java.io :as io] [clojure.repl :refer :all] [clojure.set :as set] [clojure.stacktrace :refer [print-cause-trace]] [clojure.string :as str] [clojure.test.check.generators :as gen] [clojure.tools.namespace.repl :refer [refresh]] [com.stuartsierra.component :as component] [merkledag.core :as mdag] [merkledag.link :as link] [merkledag.node :as node] [merkledag.ref.file :as mrf] [merkle-db.bloom :as bloom] [merkle-db.connection :as conn] [merkle-db.database :as db] ;[merkle-db.generators :as mdgen] [merkle-db.graph :as graph] [merkle-db.index :as index] [merkle-db.key :as key] [merkle-db.partition :as part] [merkle-db.patch :as patch] [merkle-db.record :as record] [merkle-db.table :as table] [merkle-db.tablet :as tablet] [merkle-db.tools.viz :as viz] [multihash.core :as multihash] [multihash.digest :as digest] [rhizome.viz :as rhizome])) ; TODO: replace this with reloaded repl (def conn (conn/connect (mdag/init-store :store (file-block-store "var/db/blocks") :cache {:total-size-limit (* 32 1024)} :types graph/codec-types) (doto (mrf/file-ref-tracker "var/db/refs.tsv") (mrf/load-history!)))) (def db (try (conn/open-db conn "iris") (catch Exception ex (println "Failed to load iris database:" (.getMessage ex))))) (defn alter-db [f & args] (apply alter-var-root #'db f args)) (defn build-table [table-name params records] (let [store (.store conn) lexicoder (key/lexicoder (::key/lexicoder params :bytes)) root (->> records (map (partial record/encode-entry lexicoder (::table/primary-key params))) (part/partition-records store params) (index/build-tree store params)) node (-> params (assoc :data/type :merkle-db/table ::record/count (::record/count root 0)) (cond-> root (assoc ::table/data (mdag/link "data" root))) (dissoc ::table/patch) (->> (mdag/store-node! store nil)) (::node/data))] (table/load-table store table-name node))) ;; ## visualization dev utils (defn sample-record-data "Generates a vector of `n` maps of record data using the given field keys." [field-keys n] (rand-nth (gen/sample (gen/vector (gen/map (gen/elements field-keys) gen/large-integer) n)))) (defn sample-subset "Given a sequence of values, returns a subset of them in the same order, where each element has the given chance of being in the subset." [p xs] (->> (repeatedly #(< (rand) p)) (map vector xs) (filter second) (mapv first))) (defn viz-index-build [filename fan-out part-limit n] (let [field-keys #{:a :b :c :d :e :f} families {:bc #{:b :c}, :de #{:d :e}} record-keys (map (partial key/encode key/integer-lexicoder) (range n)) record-data (sample-record-data field-keys n) records (zipmap record-keys record-data) store (mdag/init-store :types graph/codec-types) params {::record/count n ::record/families families ::index/fan-out fan-out ::part/limit part-limit} parts (part/from-records store params records) root (index/build-tree store params parts)] (viz/save-tree store (::node/id (meta root)) (constantly true) filename) [store root])) (defn gen-update! "Generate an example update case for the given set of fields, families, and number of contextual records." [field-keys families n] (let [record-keys (map (partial key/encode key/integer-lexicoder) (range n)) extant-keys (sample-subset 0.5 record-keys) records (zipmap extant-keys (sample-record-data field-keys (count extant-keys))) pick-half (fn [xs] (let [half (int (/ (count xs) 2))] (condp > (rand) 0.25 nil 0.50 (take half xs) 0.75 (drop half xs) xs))) changes (merge (let [ins-keys (sample-subset 0.25 (pick-half record-keys))] (zipmap ins-keys (sample-record-data field-keys (count ins-keys)))) (let [del-keys (sample-subset 0.25 (pick-half record-keys))] (zipmap del-keys (repeat ::patch/tombstone))))] {::record/families families ::index/fan-out 4 ::part/limit 5 :records records :changes changes})) (defn viz-update [update-case] (let [store (mdag/init-store :types graph/codec-types) root (->> (:records update-case) (sort-by first) (part/partition-records store update-case) (index/build-tree store update-case))] (try (let [root' (index/update-tree store update-case root (sort-by first (:changes update-case))) old-nodes (graph/find-nodes store {} (mdag/get-node store (::node/id (meta root))) (constantly true)) new-nodes (graph/find-nodes store {} (mdag/get-node store (::node/id (meta root'))) (constantly true)) all-nodes (merge old-nodes new-nodes) shared-ids (set/intersection (set (keys old-nodes)) (set (keys new-nodes)))] (rhizome/view-graph (vals all-nodes) (fn adjacent [node] (keep #(when-let [target (get all-nodes (::link/target %))] (vary-meta target assoc ::link/name (::link/name %))) (::node/links node))) :node->descriptor (fn [node] (assoc (viz/node->descriptor node) :color (cond (shared-ids (::node/id node)) :blue (new-nodes (::node/id node)) :green :else :black))) :edge->descriptor viz/edge->descriptor :options {:dpi 64}) ['context update-case 'original-root (link/identify root) root 'updated-root (link/identify root') root']) (catch Exception ex (throw (ex-info "Error updating tree!" {:context update-case :original root} ex)))))) (defn read-test-case "Read a test case from standard input as output by the generative test case." [] (let [tcase (read-string (read-line)) {:syms [families fan-out part-limit rkeys ukeys dkeys]} tcase records (map-indexed #(vector (key/create (.data %2)) {:a %1}) rkeys) updates (map-indexed #(vector (key/create (.data %2)) {:b %1}) ukeys) deletions (map #(vector (key/create (.data %)) ::patch/tombstone) dkeys) changes (vec (into (sorted-map) (concat updates deletions))) update-map {::record/families families ::index/fan-out fan-out ::part/limit part-limit :records records :changes changes}] (viz-update update-map)))
12540
(ns user "Custom repl customization for local development." (:require [blocks.core :as block] [blocks.store.file :refer [file-block-store]] [clojure.data.csv :as csv] [clojure.java.io :as io] [clojure.repl :refer :all] [clojure.set :as set] [clojure.stacktrace :refer [print-cause-trace]] [clojure.string :as str] [clojure.test.check.generators :as gen] [clojure.tools.namespace.repl :refer [refresh]] [com.stuartsierra.component :as component] [merkledag.core :as mdag] [merkledag.link :as link] [merkledag.node :as node] [merkledag.ref.file :as mrf] [merkle-db.bloom :as bloom] [merkle-db.connection :as conn] [merkle-db.database :as db] ;[merkle-db.generators :as mdgen] [merkle-db.graph :as graph] [merkle-db.index :as index] [merkle-db.key :as key] [merkle-db.partition :as part] [merkle-db.patch :as patch] [merkle-db.record :as record] [merkle-db.table :as table] [merkle-db.tablet :as tablet] [merkle-db.tools.viz :as viz] [multihash.core :as multihash] [multihash.digest :as digest] [rhizome.viz :as rhizome])) ; TODO: replace this with reloaded repl (def conn (conn/connect (mdag/init-store :store (file-block-store "var/db/blocks") :cache {:total-size-limit (* 32 1024)} :types graph/codec-types) (doto (mrf/file-ref-tracker "var/db/refs.tsv") (mrf/load-history!)))) (def db (try (conn/open-db conn "iris") (catch Exception ex (println "Failed to load iris database:" (.getMessage ex))))) (defn alter-db [f & args] (apply alter-var-root #'db f args)) (defn build-table [table-name params records] (let [store (.store conn) lexicoder (key/lexicoder (::key/lexicoder params :bytes)) root (->> records (map (partial record/encode-entry lexicoder (::table/primary-key params))) (part/partition-records store params) (index/build-tree store params)) node (-> params (assoc :data/type :merkle-db/table ::record/count (::record/count root 0)) (cond-> root (assoc ::table/data (mdag/link "data" root))) (dissoc ::table/patch) (->> (mdag/store-node! store nil)) (::node/data))] (table/load-table store table-name node))) ;; ## visualization dev utils (defn sample-record-data "Generates a vector of `n` maps of record data using the given field keys." [field-keys n] (rand-nth (gen/sample (gen/vector (gen/map (gen/elements field-keys) gen/large-integer) n)))) (defn sample-subset "Given a sequence of values, returns a subset of them in the same order, where each element has the given chance of being in the subset." [p xs] (->> (repeatedly #(< (rand) p)) (map vector xs) (filter second) (mapv first))) (defn viz-index-build [filename fan-out part-limit n] (let [field-keys #{:<KEY>} families {:bc #{:b :c}, :de #{:d :e}} record-keys (map (partial key/encode key/integer-lexicoder) (range n)) record-data (sample-record-data field-keys n) records (zipmap record-keys record-data) store (mdag/init-store :types graph/codec-types) params {::record/count n ::record/families families ::index/fan-out fan-out ::part/limit part-limit} parts (part/from-records store params records) root (index/build-tree store params parts)] (viz/save-tree store (::node/id (meta root)) (constantly true) filename) [store root])) (defn gen-update! "Generate an example update case for the given set of fields, families, and number of contextual records." [field-keys families n] (let [record-keys (map (partial key/encode key/integer-lexicoder) (range n)) extant-keys (sample-subset 0.5 record-keys) records (zipmap extant-keys (sample-record-data field-keys (count extant-keys))) pick-half (fn [xs] (let [half (int (/ (count xs) 2))] (condp > (rand) 0.25 nil 0.50 (take half xs) 0.75 (drop half xs) xs))) changes (merge (let [ins-keys (sample-subset 0.25 (pick-half record-keys))] (zipmap ins-keys (sample-record-data field-keys (count ins-keys)))) (let [del-keys (sample-subset 0.25 (pick-half record-keys))] (zipmap del-keys (repeat ::patch/tombstone))))] {::record/families families ::index/fan-out 4 ::part/limit 5 :records records :changes changes})) (defn viz-update [update-case] (let [store (mdag/init-store :types graph/codec-types) root (->> (:records update-case) (sort-by first) (part/partition-records store update-case) (index/build-tree store update-case))] (try (let [root' (index/update-tree store update-case root (sort-by first (:changes update-case))) old-nodes (graph/find-nodes store {} (mdag/get-node store (::node/id (meta root))) (constantly true)) new-nodes (graph/find-nodes store {} (mdag/get-node store (::node/id (meta root'))) (constantly true)) all-nodes (merge old-nodes new-nodes) shared-ids (set/intersection (set (keys old-nodes)) (set (keys new-nodes)))] (rhizome/view-graph (vals all-nodes) (fn adjacent [node] (keep #(when-let [target (get all-nodes (::link/target %))] (vary-meta target assoc ::link/name (::link/name %))) (::node/links node))) :node->descriptor (fn [node] (assoc (viz/node->descriptor node) :color (cond (shared-ids (::node/id node)) :blue (new-nodes (::node/id node)) :green :else :black))) :edge->descriptor viz/edge->descriptor :options {:dpi 64}) ['context update-case 'original-root (link/identify root) root 'updated-root (link/identify root') root']) (catch Exception ex (throw (ex-info "Error updating tree!" {:context update-case :original root} ex)))))) (defn read-test-case "Read a test case from standard input as output by the generative test case." [] (let [tcase (read-string (read-line)) {:syms [families fan-out part-limit rkeys ukeys dkeys]} tcase records (map-indexed #(vector (key/create (.data %2)) {:a %1}) rkeys) updates (map-indexed #(vector (key/create (.data %2)) {:b %1}) ukeys) deletions (map #(vector (key/create (.data %)) ::patch/tombstone) dkeys) changes (vec (into (sorted-map) (concat updates deletions))) update-map {::record/families families ::index/fan-out fan-out ::part/limit part-limit :records records :changes changes}] (viz-update update-map)))
true
(ns user "Custom repl customization for local development." (:require [blocks.core :as block] [blocks.store.file :refer [file-block-store]] [clojure.data.csv :as csv] [clojure.java.io :as io] [clojure.repl :refer :all] [clojure.set :as set] [clojure.stacktrace :refer [print-cause-trace]] [clojure.string :as str] [clojure.test.check.generators :as gen] [clojure.tools.namespace.repl :refer [refresh]] [com.stuartsierra.component :as component] [merkledag.core :as mdag] [merkledag.link :as link] [merkledag.node :as node] [merkledag.ref.file :as mrf] [merkle-db.bloom :as bloom] [merkle-db.connection :as conn] [merkle-db.database :as db] ;[merkle-db.generators :as mdgen] [merkle-db.graph :as graph] [merkle-db.index :as index] [merkle-db.key :as key] [merkle-db.partition :as part] [merkle-db.patch :as patch] [merkle-db.record :as record] [merkle-db.table :as table] [merkle-db.tablet :as tablet] [merkle-db.tools.viz :as viz] [multihash.core :as multihash] [multihash.digest :as digest] [rhizome.viz :as rhizome])) ; TODO: replace this with reloaded repl (def conn (conn/connect (mdag/init-store :store (file-block-store "var/db/blocks") :cache {:total-size-limit (* 32 1024)} :types graph/codec-types) (doto (mrf/file-ref-tracker "var/db/refs.tsv") (mrf/load-history!)))) (def db (try (conn/open-db conn "iris") (catch Exception ex (println "Failed to load iris database:" (.getMessage ex))))) (defn alter-db [f & args] (apply alter-var-root #'db f args)) (defn build-table [table-name params records] (let [store (.store conn) lexicoder (key/lexicoder (::key/lexicoder params :bytes)) root (->> records (map (partial record/encode-entry lexicoder (::table/primary-key params))) (part/partition-records store params) (index/build-tree store params)) node (-> params (assoc :data/type :merkle-db/table ::record/count (::record/count root 0)) (cond-> root (assoc ::table/data (mdag/link "data" root))) (dissoc ::table/patch) (->> (mdag/store-node! store nil)) (::node/data))] (table/load-table store table-name node))) ;; ## visualization dev utils (defn sample-record-data "Generates a vector of `n` maps of record data using the given field keys." [field-keys n] (rand-nth (gen/sample (gen/vector (gen/map (gen/elements field-keys) gen/large-integer) n)))) (defn sample-subset "Given a sequence of values, returns a subset of them in the same order, where each element has the given chance of being in the subset." [p xs] (->> (repeatedly #(< (rand) p)) (map vector xs) (filter second) (mapv first))) (defn viz-index-build [filename fan-out part-limit n] (let [field-keys #{:PI:KEY:<KEY>END_PI} families {:bc #{:b :c}, :de #{:d :e}} record-keys (map (partial key/encode key/integer-lexicoder) (range n)) record-data (sample-record-data field-keys n) records (zipmap record-keys record-data) store (mdag/init-store :types graph/codec-types) params {::record/count n ::record/families families ::index/fan-out fan-out ::part/limit part-limit} parts (part/from-records store params records) root (index/build-tree store params parts)] (viz/save-tree store (::node/id (meta root)) (constantly true) filename) [store root])) (defn gen-update! "Generate an example update case for the given set of fields, families, and number of contextual records." [field-keys families n] (let [record-keys (map (partial key/encode key/integer-lexicoder) (range n)) extant-keys (sample-subset 0.5 record-keys) records (zipmap extant-keys (sample-record-data field-keys (count extant-keys))) pick-half (fn [xs] (let [half (int (/ (count xs) 2))] (condp > (rand) 0.25 nil 0.50 (take half xs) 0.75 (drop half xs) xs))) changes (merge (let [ins-keys (sample-subset 0.25 (pick-half record-keys))] (zipmap ins-keys (sample-record-data field-keys (count ins-keys)))) (let [del-keys (sample-subset 0.25 (pick-half record-keys))] (zipmap del-keys (repeat ::patch/tombstone))))] {::record/families families ::index/fan-out 4 ::part/limit 5 :records records :changes changes})) (defn viz-update [update-case] (let [store (mdag/init-store :types graph/codec-types) root (->> (:records update-case) (sort-by first) (part/partition-records store update-case) (index/build-tree store update-case))] (try (let [root' (index/update-tree store update-case root (sort-by first (:changes update-case))) old-nodes (graph/find-nodes store {} (mdag/get-node store (::node/id (meta root))) (constantly true)) new-nodes (graph/find-nodes store {} (mdag/get-node store (::node/id (meta root'))) (constantly true)) all-nodes (merge old-nodes new-nodes) shared-ids (set/intersection (set (keys old-nodes)) (set (keys new-nodes)))] (rhizome/view-graph (vals all-nodes) (fn adjacent [node] (keep #(when-let [target (get all-nodes (::link/target %))] (vary-meta target assoc ::link/name (::link/name %))) (::node/links node))) :node->descriptor (fn [node] (assoc (viz/node->descriptor node) :color (cond (shared-ids (::node/id node)) :blue (new-nodes (::node/id node)) :green :else :black))) :edge->descriptor viz/edge->descriptor :options {:dpi 64}) ['context update-case 'original-root (link/identify root) root 'updated-root (link/identify root') root']) (catch Exception ex (throw (ex-info "Error updating tree!" {:context update-case :original root} ex)))))) (defn read-test-case "Read a test case from standard input as output by the generative test case." [] (let [tcase (read-string (read-line)) {:syms [families fan-out part-limit rkeys ukeys dkeys]} tcase records (map-indexed #(vector (key/create (.data %2)) {:a %1}) rkeys) updates (map-indexed #(vector (key/create (.data %2)) {:b %1}) ukeys) deletions (map #(vector (key/create (.data %)) ::patch/tombstone) dkeys) changes (vec (into (sorted-map) (concat updates deletions))) update-map {::record/families families ::index/fan-out fan-out ::part/limit part-limit :records records :changes changes}] (viz-update update-map)))
[ { "context": "defn mapify\n \"Return a seq of maps like {:name \\\"Edward Cullen\\\" :glitter-index 10}\"\n [rows]\n (map (fn [unmapp", "end": 593, "score": 0.9998323321342468, "start": 580, "tag": "NAME", "value": "Edward Cullen" } ]
ch4/fwpd/src/fwpd/core.clj
jeyoor/brave-clojure-notes
0
(ns fwpd.core) (def filename "suspects.csv") (defn reload "reload this file" [] (do (load-file "src/fwpd/core.clj") (use 'fwpd.core))) (def vamp-keys [:name :glitter-index]) (defn str->int [str] (Integer. str)) (def conversions {:name identity :glitter-index str->int}) (defn convert [vamp-key value] ((get conversions vamp-key) value)) (defn parse "Convert a CSV into rows of columns" [string] (map #(clojure.string/split % #",") (clojure.string/split string #"\n"))) (defn mapify "Return a seq of maps like {:name \"Edward Cullen\" :glitter-index 10}" [rows] (map (fn [unmapped-row] (reduce (fn [row-map [vamp-key value]] (assoc row-map vamp-key (convert vamp-key value))) {} (map vector vamp-keys unmapped-row))) rows)) (defn glitter-filter [minimum-glitter records] (filter #(>= (:glitter-index %) minimum-glitter) records)) (defn glitter-filter-names "retrieve names from records with at least the minimum glitter index" [minimum-glitter records] (map #(% :name) (glitter-filter minimum-glitter records))) (defn find-vampires! "parse the file and return the names of records with a glitter-index greater than 3" [] (map #(% :name) (glitter-filter 3 (mapify (parse (slurp filename))))))
119006
(ns fwpd.core) (def filename "suspects.csv") (defn reload "reload this file" [] (do (load-file "src/fwpd/core.clj") (use 'fwpd.core))) (def vamp-keys [:name :glitter-index]) (defn str->int [str] (Integer. str)) (def conversions {:name identity :glitter-index str->int}) (defn convert [vamp-key value] ((get conversions vamp-key) value)) (defn parse "Convert a CSV into rows of columns" [string] (map #(clojure.string/split % #",") (clojure.string/split string #"\n"))) (defn mapify "Return a seq of maps like {:name \"<NAME>\" :glitter-index 10}" [rows] (map (fn [unmapped-row] (reduce (fn [row-map [vamp-key value]] (assoc row-map vamp-key (convert vamp-key value))) {} (map vector vamp-keys unmapped-row))) rows)) (defn glitter-filter [minimum-glitter records] (filter #(>= (:glitter-index %) minimum-glitter) records)) (defn glitter-filter-names "retrieve names from records with at least the minimum glitter index" [minimum-glitter records] (map #(% :name) (glitter-filter minimum-glitter records))) (defn find-vampires! "parse the file and return the names of records with a glitter-index greater than 3" [] (map #(% :name) (glitter-filter 3 (mapify (parse (slurp filename))))))
true
(ns fwpd.core) (def filename "suspects.csv") (defn reload "reload this file" [] (do (load-file "src/fwpd/core.clj") (use 'fwpd.core))) (def vamp-keys [:name :glitter-index]) (defn str->int [str] (Integer. str)) (def conversions {:name identity :glitter-index str->int}) (defn convert [vamp-key value] ((get conversions vamp-key) value)) (defn parse "Convert a CSV into rows of columns" [string] (map #(clojure.string/split % #",") (clojure.string/split string #"\n"))) (defn mapify "Return a seq of maps like {:name \"PI:NAME:<NAME>END_PI\" :glitter-index 10}" [rows] (map (fn [unmapped-row] (reduce (fn [row-map [vamp-key value]] (assoc row-map vamp-key (convert vamp-key value))) {} (map vector vamp-keys unmapped-row))) rows)) (defn glitter-filter [minimum-glitter records] (filter #(>= (:glitter-index %) minimum-glitter) records)) (defn glitter-filter-names "retrieve names from records with at least the minimum glitter index" [minimum-glitter records] (map #(% :name) (glitter-filter minimum-glitter records))) (defn find-vampires! "parse the file and return the names of records with a glitter-index greater than 3" [] (map #(% :name) (glitter-filter 3 (mapify (parse (slurp filename))))))
[ { "context": "ho-brings answers)\n [\"Miles McInnis\"] unpopular-date)}\n (sut/who-brings u", "end": 631, "score": 0.9992643594741821, "start": 618, "tag": "NAME", "value": "Miles McInnis" } ]
test/breakfastbot/handlers/who_brings_test.clj
studer-l/breakfastbot
0
(ns breakfastbot.handlers.who-brings-test (:require [breakfastbot.handlers.who-brings :as sut] [clojure.test :as t] [breakfastbot.handlers.common :refer [answers]] [breakfastbot.db-test :refer [prepare-mock-db unpopular-date random-date]])) (t/deftest who-brings-action (prepare-mock-db) (t/testing "exception thrown if not known" (t/is (thrown? clojure.lang.ExceptionInfo (sut/who-brings random-date)))) (t/testing "message formatted if known" (t/is (= {:direct-reply ((:who-brings answers) ["Miles McInnis"] unpopular-date)} (sut/who-brings unpopular-date)))))
55144
(ns breakfastbot.handlers.who-brings-test (:require [breakfastbot.handlers.who-brings :as sut] [clojure.test :as t] [breakfastbot.handlers.common :refer [answers]] [breakfastbot.db-test :refer [prepare-mock-db unpopular-date random-date]])) (t/deftest who-brings-action (prepare-mock-db) (t/testing "exception thrown if not known" (t/is (thrown? clojure.lang.ExceptionInfo (sut/who-brings random-date)))) (t/testing "message formatted if known" (t/is (= {:direct-reply ((:who-brings answers) ["<NAME>"] unpopular-date)} (sut/who-brings unpopular-date)))))
true
(ns breakfastbot.handlers.who-brings-test (:require [breakfastbot.handlers.who-brings :as sut] [clojure.test :as t] [breakfastbot.handlers.common :refer [answers]] [breakfastbot.db-test :refer [prepare-mock-db unpopular-date random-date]])) (t/deftest who-brings-action (prepare-mock-db) (t/testing "exception thrown if not known" (t/is (thrown? clojure.lang.ExceptionInfo (sut/who-brings random-date)))) (t/testing "message formatted if known" (t/is (= {:direct-reply ((:who-brings answers) ["PI:NAME:<NAME>END_PI"] unpopular-date)} (sut/who-brings unpopular-date)))))
[ { "context": "s a value that looks like a list\n;; \n(seq {:name \"Billy\" :age 43})\n;; => ([:name \"Billy\"] [:age 43])\n;; W", "end": 1506, "score": 0.9996615648269653, "start": 1501, "tag": "NAME", "value": "Billy" }, { "context": "\n;; \n(seq {:name \"Billy\" :age 43})\n;; => ([:name \"Billy\"] [:age 43])\n;; We get a list of two element vect", "end": 1538, "score": 0.9996333122253418, "start": 1533, "tag": "NAME", "value": "Billy" }, { "context": "used as functions\n;; \n(def identities\n [{:alias \"Batman\" :real \"Bruce Wayne\"}\n {:alias \"Spiderman\" :rea", "end": 2109, "score": 0.9997141361236572, "start": 2103, "tag": "NAME", "value": "Batman" }, { "context": "ns\n;; \n(def identities\n [{:alias \"Batman\" :real \"Bruce Wayne\"}\n {:alias \"Spiderman\" :real \"Peter Parker\"}\n ", "end": 2129, "score": 0.9997881650924683, "start": 2118, "tag": "NAME", "value": "Bruce Wayne" }, { "context": "{:alias \"Batman\" :real \"Bruce Wayne\"}\n {:alias \"Spiderman\" :real \"Peter Parker\"}\n {:alias \"Santa\" :real \"", "end": 2153, "score": 0.9996377229690552, "start": 2144, "tag": "NAME", "value": "Spiderman" }, { "context": "real \"Bruce Wayne\"}\n {:alias \"Spiderman\" :real \"Peter Parker\"}\n {:alias \"Santa\" :real \"Your mom\"}\n {:alias", "end": 2174, "score": 0.9997450113296509, "start": 2162, "tag": "NAME", "value": "Peter Parker" }, { "context": "ias \"Spiderman\" :real \"Peter Parker\"}\n {:alias \"Santa\" :real \"Your mom\"}\n {:alias \"Easter Bunny\" :rea", "end": 2194, "score": 0.998146116733551, "start": 2189, "tag": "NAME", "value": "Santa" }, { "context": "\n {:alias \"Santa\" :real \"Your mom\"}\n {:alias \"Easter Bunny\" :real \"Your dad\"}])\n\n\n(map :real identities)\n;; ", "end": 2238, "score": 0.9993588328361511, "start": 2226, "tag": "NAME", "value": "Easter Bunny" }, { "context": "al \"Your dad\"}])\n\n\n(map :real identities)\n;; => (\"Bruce Wayne\" \"Peter Parker\" \"Your mom\" \"Your dad\")\n\n;; Passin", "end": 2304, "score": 0.9997841715812683, "start": 2293, "tag": "NAME", "value": "Bruce Wayne" }, { "context": "])\n\n\n(map :real identities)\n;; => (\"Bruce Wayne\" \"Peter Parker\" \"Your mom\" \"Your dad\")\n\n;; Passing a collection ", "end": 2319, "score": 0.9996820092201233, "start": 2307, "tag": "NAME", "value": "Peter Parker" }, { "context": "makes-blood-puns? false, :has-pulse? true :name \"McFishwich\"}\n 1 {:makes-blood-puns? false, :has-pulse? tru", "end": 4331, "score": 0.9576016068458557, "start": 4321, "tag": "NAME", "value": "McFishwich" }, { "context": "makes-blood-puns? false, :has-pulse? true :name \"McMackson\"}\n 2 {:makes-blood-puns? true, :has-pulse? fal", "end": 4400, "score": 0.9910309314727783, "start": 4391, "tag": "NAME", "value": "McMackson" }, { "context": "makes-blood-puns? true, :has-pulse? false :name \"Damon Salvatore\"}\n 3 {:makes-blood-puns? true, :has-pulse? tru", "end": 4475, "score": 0.999438464641571, "start": 4460, "tag": "NAME", "value": "Damon Salvatore" }, { "context": "makes-blood-puns? true, :has-pulse? true :name \"Mickey Mouse\"}})\n\n\n(defn vampire-related-details\n [ssn]\n (Th", "end": 4547, "score": 0.9988980293273926, "start": 4535, "tag": "NAME", "value": "Mickey Mouse" }, { "context": "makes-blood-puns? false, :has-pulse? true, :name \"McFishwich\"}\n\n;; lazy seq is a seq whose members aren't comp", "end": 4995, "score": 0.9868201613426208, "start": 4985, "tag": "NAME", "value": "McFishwich" }, { "context": "makes-blood-puns? false, :has-pulse? true, :name \"McFishwich\"}\n\n;; Took 32 seconds because when Clojure has to", "end": 5741, "score": 0.9788625836372375, "start": 5731, "tag": "NAME", "value": "McFishwich" }, { "context": "s are cached\n;; \n(concat (take 8 (repeat \"na\")) [\"Batman!\"])\n;; => (\"na\" \"na\" \"na\" \"na\" \"na\" \"na\" \"na\" \"na", "end": 6043, "score": 0.8868551850318909, "start": 6037, "tag": "NAME", "value": "Batman" }, { "context": ")\n;; => (\"na\" \"na\" \"na\" \"na\" \"na\" \"na\" \"na\" \"na\" \"Batman!\")\n\n(take 3 (repeatedly (fn [] (rand-int 10))))\n;", "end": 6102, "score": 0.852928638458252, "start": 6096, "tag": "NAME", "value": "Batman" } ]
code/clojure-noob/src/clojure_noob/ch4.clj
itsrainingmani/learn-clojure-in-public
7
(ns clojure-noob.ch4 (:gen-class)) ;; If you can perform all of an abstraction’s operations on an object, then that object is an instance of the abstraction ;; ;; A sequence is a collection of elements organized in linear order vs an unordered collection or a graph without a before-after ;; relationship between its nodes ;; ;; Implements functions in terms of sequence abstractions. map, reduce take a seq. ;; ;; If the core sequence functions (first, rest and cons) work on a DS, it implements the sequence abstraction. ;; (defn titleize [topic] (str topic " for the Brave and True")) ;; vectors (map titleize ["Hamsters" "ragnarok"]) ;; => ("Hamsters for the Brave and True" "ragnarok for the Brave and True") ;; list (map titleize '("Table Tennis" "Empathy")) ;; => ("Table Tennis for the Brave and True" "Empathy for the Brave and True") ;; set (map titleize #{"Hamsters" "ragnarok"}) ;; => ("Hamsters for the Brave and True" "ragnarok for the Brave and True") ;; Abstraction through indirection ;; Indirection is a term for a mechanism that a programming language employs so that one name can have multiple, related meanings ;; Polymorphic functions dispatch to different function bodies based on the type of the argument supplied. ;; ;; Whenever a Clojure function expects a seq, it uses the seq function on the data structure in order to obtain a data structure that ;; allows for first, rest and cons ;; ;; seq always returns a value that looks like a list ;; (seq {:name "Billy" :age 43}) ;; => ([:name "Billy"] [:age 43]) ;; We get a list of two element vectors (def human-consumption [8.1 8.3 4.4 6.1]) (def critter-consumption [0.0 0.2 0.3 1.3]) (defn unify-diet [human critter] {:human human :critter critter}) (map unify-diet human-consumption critter-consumption) ;; => ({:human 8.1, :critter 0.0} {:human 8.3, :critter 0.2} {:human 4.4, :critter 0.3} {:human 6.1, :critter 1.3}) ;; Use map to retrieve the value associated with a keyword from a collection of map data structures. ;; Because keywords can be used as functions ;; (def identities [{:alias "Batman" :real "Bruce Wayne"} {:alias "Spiderman" :real "Peter Parker"} {:alias "Santa" :real "Your mom"} {:alias "Easter Bunny" :real "Your dad"}]) (map :real identities) ;; => ("Bruce Wayne" "Peter Parker" "Your mom" "Your dad") ;; Passing a collection of functions as an argument (def sum #(reduce + %)) (def avg #(/ (sum %) (count %))) (defn stats [numbers] (map #(% numbers) [sum count avg])) (stats [1 2 3 4]) ;; => (10 4 5/2) (stats [80 1 44 13 6]) ;; => (144 5 144/5) ;; Reduce ;; Reduce processes each element in a sequence to build a result. The result does not have to a single value. ;; You can use reduce to build a larger sequence from a smaller one as well. ;; (reduce (fn [new-map [key val]] (assoc new-map key (inc val))) {} {:max 30 :min 10}) ;; => {:max 31, :min 11} ;; (def food-journal [{:month 1 :day 1 :human 5.3 :critter 2.3} {:month 1 :day 2 :human 5.1 :critter 2.0} {:month 2 :day 1 :human 4.9 :critter 2.1} {:month 2 :day 2 :human 5.0 :critter 2.5} {:month 3 :day 1 :human 4.2 :critter 3.3} {:month 3 :day 2 :human 4.0 :critter 3.8} {:month 4 :day 1 :human 3.7 :critter 3.9} {:month 4 :day 2 :human 3.7 :critter 3.6}]) (take-while #(< (:month %) 3) food-journal) ;; => ({:month 1, :day 1, :human 5.3, :critter 2.3} ;; {:month 1, :day 2, :human 5.1, :critter 2.0} ;; {:month 2, :day 1, :human 4.9, :critter 2.1} ;; {:month 2, :day 2, :human 5.0, :critter 2.5}) ;; => ({:month 1, :day 1, :human 5.3, :critter 2.3} ;; {:month 1, :day 2, :human 5.1, :critter 2.0} ;; {:month 2, :day 1, :human 4.9, :critter 2.1} ;; {:month 2, :day 2, :human 5.0, :critter 2.5}) ;; take while the predicate returns true ;; drop while the predicate returns true ;; filter returns all elements of a sequence that tests true for predicate ;; some returns the first truthy value that satisfies the predicate and nil otherwise ;; (sort [3 2 1]) ;; => (1 2 3) (sort-by count ["aaa" "c" "vv"]) ;; => ("c" "vv" "aaa") (concat [1 2] [3 4]) ;; => (1 2 3 4) ;; Use reduce to derive a new value from a seq-able data structure. ;; ;; Demonstrating Lazy Seq Efficiency (def vampire-database {0 {:makes-blood-puns? false, :has-pulse? true :name "McFishwich"} 1 {:makes-blood-puns? false, :has-pulse? true :name "McMackson"} 2 {:makes-blood-puns? true, :has-pulse? false :name "Damon Salvatore"} 3 {:makes-blood-puns? true, :has-pulse? true :name "Mickey Mouse"}}) (defn vampire-related-details [ssn] (Thread/sleep 1000) (get vampire-database ssn)) (defn vampire? [record] (and (:makes-blood-puns? record) (not (:has-pulse? record)) record)) (defn identity-vampire [ssns] (first (filter vampire? (map vampire-related-details ssns)))) (time (vampire-related-details 0)) ;; takes 1 second ;; => {:makes-blood-puns? false, :has-pulse? true, :name "McFishwich"} ;; lazy seq is a seq whose members aren't computed until you try to access them ;; ;; Deferring the computation until it's needed makes the program more efficient and allows you to construct infinite sequences ;; (time (def mapped-details (map vampire-related-details (range 0 1000000)))) ;; "Elapsed time: 0.042193 msecs" ;; #'clojure-noob.ch4/mapped-details ;; ;; Lazy Seq - recipe for how to realize the elements of a sequence and the elements that have been realized so far. Everytime you try to access an unrealized element, the lazy seq will use its recipe to generate the requested element. ;; (time (first mapped-details)) ;; => "Elapsed time: 32030.767 msecs" ;; => {:makes-blood-puns? false, :has-pulse? true, :name "McFishwich"} ;; Took 32 seconds because when Clojure has to realize an element, it realizes the next 31 elements as well pre-emptively. This is done for better performance ;; ;; Accessing (first mapped-details) again takes almost no time since the results are cached ;; (concat (take 8 (repeat "na")) ["Batman!"]) ;; => ("na" "na" "na" "na" "na" "na" "na" "na" "Batman!") (take 3 (repeatedly (fn [] (rand-int 10)))) ;; => (2 9 4) (defn even-nums ([] (even-nums 0)) ([n] (cons n (lazy-seq (even-nums (+ n 2)))))) (take 10 (even-nums)) ;; => (0 2 4 6 8 10 12 14 16 18) (cons 0 '(2 4 6)) ;; => (0 2 4 6) ;; Collection Abstraction ;; The sequence absrtaction is about operating on members individually, whereas the collection abstraction is about the data structure as a whole. For eg. the collection functions count, empty? and every?. ;; (empty? []) ;; => true (empty? ["no!"]) ;; => false ;; into converts a sequence into another type ;; (map identity {:sunlight "Glitter"}) ;; => ([:sunlight "Glitter"]) (into {} (map identity {:sunlight "Glitter"})) ;; => {:sunlight "Glitter"} (into {:favorite-animal "kitty"} {:least-favorite-smell "dog" :relationship-with-teenager "creepy"}) ;; => {:favorite-animal "kitty", :least-favorite-smell "dog", :relationship-with-teenager "creepy"} ;; into basically takes two collections and adds all elements from the second to the first ;; ;; Function Functions ;; ;; Clojure can accept and return functions as function args ;; ;; apply explodes a seqable data structure so it can be passed to a function that expects a rest parameter ;; ;; (apply max [0 1 2]) ;; => 2 ;; ;; max expects a number of args, not a seqable data structure ;; (apply max [0 1 2]) is equivalent to (max 0 1 2) ;; ;; partial takes a function and any number of args and returns a new function. it forms a closure with the originally supplied args and you can call this function with new args ;; (def add10 (partial + 10)) (add10 3) ;; => 13 (add10 5) ;; => 15 (def add-missing-elements (partial conj ["water" "earth" "air"])) (add-missing-elements "fire") ;; => ["water" "earth" "air" "fire"] (defn my-partial [partialized-fn & args] (fn [& more-args] (apply partialized-fn (into args more-args)))) (def add20 (my-partial + 20)) (add20 5) ;; => 25 ;; complement - takes a fn f and returns a fn that takes the same args as f, has the same effects, but returns the opposite truth value ;; (defn iseven? [n] (prn (str "Given number is: " n)) (= (rem n 2) 0)) (def isodd? (complement iseven?)) (iseven? 20) (isodd? 21)
11092
(ns clojure-noob.ch4 (:gen-class)) ;; If you can perform all of an abstraction’s operations on an object, then that object is an instance of the abstraction ;; ;; A sequence is a collection of elements organized in linear order vs an unordered collection or a graph without a before-after ;; relationship between its nodes ;; ;; Implements functions in terms of sequence abstractions. map, reduce take a seq. ;; ;; If the core sequence functions (first, rest and cons) work on a DS, it implements the sequence abstraction. ;; (defn titleize [topic] (str topic " for the Brave and True")) ;; vectors (map titleize ["Hamsters" "ragnarok"]) ;; => ("Hamsters for the Brave and True" "ragnarok for the Brave and True") ;; list (map titleize '("Table Tennis" "Empathy")) ;; => ("Table Tennis for the Brave and True" "Empathy for the Brave and True") ;; set (map titleize #{"Hamsters" "ragnarok"}) ;; => ("Hamsters for the Brave and True" "ragnarok for the Brave and True") ;; Abstraction through indirection ;; Indirection is a term for a mechanism that a programming language employs so that one name can have multiple, related meanings ;; Polymorphic functions dispatch to different function bodies based on the type of the argument supplied. ;; ;; Whenever a Clojure function expects a seq, it uses the seq function on the data structure in order to obtain a data structure that ;; allows for first, rest and cons ;; ;; seq always returns a value that looks like a list ;; (seq {:name "<NAME>" :age 43}) ;; => ([:name "<NAME>"] [:age 43]) ;; We get a list of two element vectors (def human-consumption [8.1 8.3 4.4 6.1]) (def critter-consumption [0.0 0.2 0.3 1.3]) (defn unify-diet [human critter] {:human human :critter critter}) (map unify-diet human-consumption critter-consumption) ;; => ({:human 8.1, :critter 0.0} {:human 8.3, :critter 0.2} {:human 4.4, :critter 0.3} {:human 6.1, :critter 1.3}) ;; Use map to retrieve the value associated with a keyword from a collection of map data structures. ;; Because keywords can be used as functions ;; (def identities [{:alias "<NAME>" :real "<NAME>"} {:alias "<NAME>" :real "<NAME>"} {:alias "<NAME>" :real "Your mom"} {:alias "<NAME>" :real "Your dad"}]) (map :real identities) ;; => ("<NAME>" "<NAME>" "Your mom" "Your dad") ;; Passing a collection of functions as an argument (def sum #(reduce + %)) (def avg #(/ (sum %) (count %))) (defn stats [numbers] (map #(% numbers) [sum count avg])) (stats [1 2 3 4]) ;; => (10 4 5/2) (stats [80 1 44 13 6]) ;; => (144 5 144/5) ;; Reduce ;; Reduce processes each element in a sequence to build a result. The result does not have to a single value. ;; You can use reduce to build a larger sequence from a smaller one as well. ;; (reduce (fn [new-map [key val]] (assoc new-map key (inc val))) {} {:max 30 :min 10}) ;; => {:max 31, :min 11} ;; (def food-journal [{:month 1 :day 1 :human 5.3 :critter 2.3} {:month 1 :day 2 :human 5.1 :critter 2.0} {:month 2 :day 1 :human 4.9 :critter 2.1} {:month 2 :day 2 :human 5.0 :critter 2.5} {:month 3 :day 1 :human 4.2 :critter 3.3} {:month 3 :day 2 :human 4.0 :critter 3.8} {:month 4 :day 1 :human 3.7 :critter 3.9} {:month 4 :day 2 :human 3.7 :critter 3.6}]) (take-while #(< (:month %) 3) food-journal) ;; => ({:month 1, :day 1, :human 5.3, :critter 2.3} ;; {:month 1, :day 2, :human 5.1, :critter 2.0} ;; {:month 2, :day 1, :human 4.9, :critter 2.1} ;; {:month 2, :day 2, :human 5.0, :critter 2.5}) ;; => ({:month 1, :day 1, :human 5.3, :critter 2.3} ;; {:month 1, :day 2, :human 5.1, :critter 2.0} ;; {:month 2, :day 1, :human 4.9, :critter 2.1} ;; {:month 2, :day 2, :human 5.0, :critter 2.5}) ;; take while the predicate returns true ;; drop while the predicate returns true ;; filter returns all elements of a sequence that tests true for predicate ;; some returns the first truthy value that satisfies the predicate and nil otherwise ;; (sort [3 2 1]) ;; => (1 2 3) (sort-by count ["aaa" "c" "vv"]) ;; => ("c" "vv" "aaa") (concat [1 2] [3 4]) ;; => (1 2 3 4) ;; Use reduce to derive a new value from a seq-able data structure. ;; ;; Demonstrating Lazy Seq Efficiency (def vampire-database {0 {:makes-blood-puns? false, :has-pulse? true :name "<NAME>"} 1 {:makes-blood-puns? false, :has-pulse? true :name "<NAME>"} 2 {:makes-blood-puns? true, :has-pulse? false :name "<NAME>"} 3 {:makes-blood-puns? true, :has-pulse? true :name "<NAME>"}}) (defn vampire-related-details [ssn] (Thread/sleep 1000) (get vampire-database ssn)) (defn vampire? [record] (and (:makes-blood-puns? record) (not (:has-pulse? record)) record)) (defn identity-vampire [ssns] (first (filter vampire? (map vampire-related-details ssns)))) (time (vampire-related-details 0)) ;; takes 1 second ;; => {:makes-blood-puns? false, :has-pulse? true, :name "<NAME>"} ;; lazy seq is a seq whose members aren't computed until you try to access them ;; ;; Deferring the computation until it's needed makes the program more efficient and allows you to construct infinite sequences ;; (time (def mapped-details (map vampire-related-details (range 0 1000000)))) ;; "Elapsed time: 0.042193 msecs" ;; #'clojure-noob.ch4/mapped-details ;; ;; Lazy Seq - recipe for how to realize the elements of a sequence and the elements that have been realized so far. Everytime you try to access an unrealized element, the lazy seq will use its recipe to generate the requested element. ;; (time (first mapped-details)) ;; => "Elapsed time: 32030.767 msecs" ;; => {:makes-blood-puns? false, :has-pulse? true, :name "<NAME>"} ;; Took 32 seconds because when Clojure has to realize an element, it realizes the next 31 elements as well pre-emptively. This is done for better performance ;; ;; Accessing (first mapped-details) again takes almost no time since the results are cached ;; (concat (take 8 (repeat "na")) ["<NAME>!"]) ;; => ("na" "na" "na" "na" "na" "na" "na" "na" "<NAME>!") (take 3 (repeatedly (fn [] (rand-int 10)))) ;; => (2 9 4) (defn even-nums ([] (even-nums 0)) ([n] (cons n (lazy-seq (even-nums (+ n 2)))))) (take 10 (even-nums)) ;; => (0 2 4 6 8 10 12 14 16 18) (cons 0 '(2 4 6)) ;; => (0 2 4 6) ;; Collection Abstraction ;; The sequence absrtaction is about operating on members individually, whereas the collection abstraction is about the data structure as a whole. For eg. the collection functions count, empty? and every?. ;; (empty? []) ;; => true (empty? ["no!"]) ;; => false ;; into converts a sequence into another type ;; (map identity {:sunlight "Glitter"}) ;; => ([:sunlight "Glitter"]) (into {} (map identity {:sunlight "Glitter"})) ;; => {:sunlight "Glitter"} (into {:favorite-animal "kitty"} {:least-favorite-smell "dog" :relationship-with-teenager "creepy"}) ;; => {:favorite-animal "kitty", :least-favorite-smell "dog", :relationship-with-teenager "creepy"} ;; into basically takes two collections and adds all elements from the second to the first ;; ;; Function Functions ;; ;; Clojure can accept and return functions as function args ;; ;; apply explodes a seqable data structure so it can be passed to a function that expects a rest parameter ;; ;; (apply max [0 1 2]) ;; => 2 ;; ;; max expects a number of args, not a seqable data structure ;; (apply max [0 1 2]) is equivalent to (max 0 1 2) ;; ;; partial takes a function and any number of args and returns a new function. it forms a closure with the originally supplied args and you can call this function with new args ;; (def add10 (partial + 10)) (add10 3) ;; => 13 (add10 5) ;; => 15 (def add-missing-elements (partial conj ["water" "earth" "air"])) (add-missing-elements "fire") ;; => ["water" "earth" "air" "fire"] (defn my-partial [partialized-fn & args] (fn [& more-args] (apply partialized-fn (into args more-args)))) (def add20 (my-partial + 20)) (add20 5) ;; => 25 ;; complement - takes a fn f and returns a fn that takes the same args as f, has the same effects, but returns the opposite truth value ;; (defn iseven? [n] (prn (str "Given number is: " n)) (= (rem n 2) 0)) (def isodd? (complement iseven?)) (iseven? 20) (isodd? 21)
true
(ns clojure-noob.ch4 (:gen-class)) ;; If you can perform all of an abstraction’s operations on an object, then that object is an instance of the abstraction ;; ;; A sequence is a collection of elements organized in linear order vs an unordered collection or a graph without a before-after ;; relationship between its nodes ;; ;; Implements functions in terms of sequence abstractions. map, reduce take a seq. ;; ;; If the core sequence functions (first, rest and cons) work on a DS, it implements the sequence abstraction. ;; (defn titleize [topic] (str topic " for the Brave and True")) ;; vectors (map titleize ["Hamsters" "ragnarok"]) ;; => ("Hamsters for the Brave and True" "ragnarok for the Brave and True") ;; list (map titleize '("Table Tennis" "Empathy")) ;; => ("Table Tennis for the Brave and True" "Empathy for the Brave and True") ;; set (map titleize #{"Hamsters" "ragnarok"}) ;; => ("Hamsters for the Brave and True" "ragnarok for the Brave and True") ;; Abstraction through indirection ;; Indirection is a term for a mechanism that a programming language employs so that one name can have multiple, related meanings ;; Polymorphic functions dispatch to different function bodies based on the type of the argument supplied. ;; ;; Whenever a Clojure function expects a seq, it uses the seq function on the data structure in order to obtain a data structure that ;; allows for first, rest and cons ;; ;; seq always returns a value that looks like a list ;; (seq {:name "PI:NAME:<NAME>END_PI" :age 43}) ;; => ([:name "PI:NAME:<NAME>END_PI"] [:age 43]) ;; We get a list of two element vectors (def human-consumption [8.1 8.3 4.4 6.1]) (def critter-consumption [0.0 0.2 0.3 1.3]) (defn unify-diet [human critter] {:human human :critter critter}) (map unify-diet human-consumption critter-consumption) ;; => ({:human 8.1, :critter 0.0} {:human 8.3, :critter 0.2} {:human 4.4, :critter 0.3} {:human 6.1, :critter 1.3}) ;; Use map to retrieve the value associated with a keyword from a collection of map data structures. ;; Because keywords can be used as functions ;; (def identities [{:alias "PI:NAME:<NAME>END_PI" :real "PI:NAME:<NAME>END_PI"} {:alias "PI:NAME:<NAME>END_PI" :real "PI:NAME:<NAME>END_PI"} {:alias "PI:NAME:<NAME>END_PI" :real "Your mom"} {:alias "PI:NAME:<NAME>END_PI" :real "Your dad"}]) (map :real identities) ;; => ("PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "Your mom" "Your dad") ;; Passing a collection of functions as an argument (def sum #(reduce + %)) (def avg #(/ (sum %) (count %))) (defn stats [numbers] (map #(% numbers) [sum count avg])) (stats [1 2 3 4]) ;; => (10 4 5/2) (stats [80 1 44 13 6]) ;; => (144 5 144/5) ;; Reduce ;; Reduce processes each element in a sequence to build a result. The result does not have to a single value. ;; You can use reduce to build a larger sequence from a smaller one as well. ;; (reduce (fn [new-map [key val]] (assoc new-map key (inc val))) {} {:max 30 :min 10}) ;; => {:max 31, :min 11} ;; (def food-journal [{:month 1 :day 1 :human 5.3 :critter 2.3} {:month 1 :day 2 :human 5.1 :critter 2.0} {:month 2 :day 1 :human 4.9 :critter 2.1} {:month 2 :day 2 :human 5.0 :critter 2.5} {:month 3 :day 1 :human 4.2 :critter 3.3} {:month 3 :day 2 :human 4.0 :critter 3.8} {:month 4 :day 1 :human 3.7 :critter 3.9} {:month 4 :day 2 :human 3.7 :critter 3.6}]) (take-while #(< (:month %) 3) food-journal) ;; => ({:month 1, :day 1, :human 5.3, :critter 2.3} ;; {:month 1, :day 2, :human 5.1, :critter 2.0} ;; {:month 2, :day 1, :human 4.9, :critter 2.1} ;; {:month 2, :day 2, :human 5.0, :critter 2.5}) ;; => ({:month 1, :day 1, :human 5.3, :critter 2.3} ;; {:month 1, :day 2, :human 5.1, :critter 2.0} ;; {:month 2, :day 1, :human 4.9, :critter 2.1} ;; {:month 2, :day 2, :human 5.0, :critter 2.5}) ;; take while the predicate returns true ;; drop while the predicate returns true ;; filter returns all elements of a sequence that tests true for predicate ;; some returns the first truthy value that satisfies the predicate and nil otherwise ;; (sort [3 2 1]) ;; => (1 2 3) (sort-by count ["aaa" "c" "vv"]) ;; => ("c" "vv" "aaa") (concat [1 2] [3 4]) ;; => (1 2 3 4) ;; Use reduce to derive a new value from a seq-able data structure. ;; ;; Demonstrating Lazy Seq Efficiency (def vampire-database {0 {:makes-blood-puns? false, :has-pulse? true :name "PI:NAME:<NAME>END_PI"} 1 {:makes-blood-puns? false, :has-pulse? true :name "PI:NAME:<NAME>END_PI"} 2 {:makes-blood-puns? true, :has-pulse? false :name "PI:NAME:<NAME>END_PI"} 3 {:makes-blood-puns? true, :has-pulse? true :name "PI:NAME:<NAME>END_PI"}}) (defn vampire-related-details [ssn] (Thread/sleep 1000) (get vampire-database ssn)) (defn vampire? [record] (and (:makes-blood-puns? record) (not (:has-pulse? record)) record)) (defn identity-vampire [ssns] (first (filter vampire? (map vampire-related-details ssns)))) (time (vampire-related-details 0)) ;; takes 1 second ;; => {:makes-blood-puns? false, :has-pulse? true, :name "PI:NAME:<NAME>END_PI"} ;; lazy seq is a seq whose members aren't computed until you try to access them ;; ;; Deferring the computation until it's needed makes the program more efficient and allows you to construct infinite sequences ;; (time (def mapped-details (map vampire-related-details (range 0 1000000)))) ;; "Elapsed time: 0.042193 msecs" ;; #'clojure-noob.ch4/mapped-details ;; ;; Lazy Seq - recipe for how to realize the elements of a sequence and the elements that have been realized so far. Everytime you try to access an unrealized element, the lazy seq will use its recipe to generate the requested element. ;; (time (first mapped-details)) ;; => "Elapsed time: 32030.767 msecs" ;; => {:makes-blood-puns? false, :has-pulse? true, :name "PI:NAME:<NAME>END_PI"} ;; Took 32 seconds because when Clojure has to realize an element, it realizes the next 31 elements as well pre-emptively. This is done for better performance ;; ;; Accessing (first mapped-details) again takes almost no time since the results are cached ;; (concat (take 8 (repeat "na")) ["PI:NAME:<NAME>END_PI!"]) ;; => ("na" "na" "na" "na" "na" "na" "na" "na" "PI:NAME:<NAME>END_PI!") (take 3 (repeatedly (fn [] (rand-int 10)))) ;; => (2 9 4) (defn even-nums ([] (even-nums 0)) ([n] (cons n (lazy-seq (even-nums (+ n 2)))))) (take 10 (even-nums)) ;; => (0 2 4 6 8 10 12 14 16 18) (cons 0 '(2 4 6)) ;; => (0 2 4 6) ;; Collection Abstraction ;; The sequence absrtaction is about operating on members individually, whereas the collection abstraction is about the data structure as a whole. For eg. the collection functions count, empty? and every?. ;; (empty? []) ;; => true (empty? ["no!"]) ;; => false ;; into converts a sequence into another type ;; (map identity {:sunlight "Glitter"}) ;; => ([:sunlight "Glitter"]) (into {} (map identity {:sunlight "Glitter"})) ;; => {:sunlight "Glitter"} (into {:favorite-animal "kitty"} {:least-favorite-smell "dog" :relationship-with-teenager "creepy"}) ;; => {:favorite-animal "kitty", :least-favorite-smell "dog", :relationship-with-teenager "creepy"} ;; into basically takes two collections and adds all elements from the second to the first ;; ;; Function Functions ;; ;; Clojure can accept and return functions as function args ;; ;; apply explodes a seqable data structure so it can be passed to a function that expects a rest parameter ;; ;; (apply max [0 1 2]) ;; => 2 ;; ;; max expects a number of args, not a seqable data structure ;; (apply max [0 1 2]) is equivalent to (max 0 1 2) ;; ;; partial takes a function and any number of args and returns a new function. it forms a closure with the originally supplied args and you can call this function with new args ;; (def add10 (partial + 10)) (add10 3) ;; => 13 (add10 5) ;; => 15 (def add-missing-elements (partial conj ["water" "earth" "air"])) (add-missing-elements "fire") ;; => ["water" "earth" "air" "fire"] (defn my-partial [partialized-fn & args] (fn [& more-args] (apply partialized-fn (into args more-args)))) (def add20 (my-partial + 20)) (add20 5) ;; => 25 ;; complement - takes a fn f and returns a fn that takes the same args as f, has the same effects, but returns the opposite truth value ;; (defn iseven? [n] (prn (str "Given number is: " n)) (= (rem n 2) 0)) (def isodd? (complement iseven?)) (iseven? 20) (isodd? 21)
[ { "context": "\n :dialog-password, \"dialog-password\"\n :dialog-question, ", "end": 15763, "score": 0.9974222183227539, "start": 15748, "tag": "PASSWORD", "value": "dialog-password" } ]
src/notify_send/icons.clj
willGuimont/interval
0
(ns notify-send.icons) (def icons {:address-book-new, "address-book-new" :application-exit, "application-exit" :appointment-new, "appointment-new" :call-start, "call-start" :call-stop, "call-stop" :contact-new, "contact-new" :document-new, "document-new" :document-open, "document-open" :document-open-recent, "document-open-recent" :document-page-setup, "document-page-setup" :document-print, "document-print" :document-print-preview, "document-print-preview" :document-properties, "document-properties" :document-revert, "document-revert" :document-save, "document-save" :document-save-as, "document-save-as" :document-send, "document-send" :edit-clear, "edit-clear" :edit-copy, "edit-copy" :edit-cut, "edit-cut" :edit-delete, "edit-delete" :edit-find, "edit-find" :edit-find-replace, "edit-find-replace" :edit-paste, "edit-paste" :edit-redo, "edit-redo" :edit-select-all, "edit-select-all" :edit-undo, "edit-undo" :folder-new, "folder-new" :format-indent-less, "format-indent-less" :format-indent-more, "format-indent-more" :format-justify-center, "format-justify-center" :format-justify-fill, "format-justify-fill" :format-justify-left, "format-justify-left" :format-justify-right, "format-justify-right" :format-text-direction-ltr, "format-text-direction-ltr" :format-text-direction-rtl, "format-text-direction-rtl" :format-text-bold, "format-text-bold" :format-text-italic, "format-text-italic" :format-text-underline, "format-text-underline" :format-text-strikethrough, "format-text-strikethrough" :go-bottom, "go-bottom" :go-down, "go-down" :go-first, "go-first" :go-home, "go-home" :go-jump, "go-jump" :go-last, "go-last" :go-next, "go-next" :go-previous, "go-previous" :go-top, "go-top" :go-up, "go-up" :help-about, "help-about" :help-contents, "help-contents" :help-faq, "help-faq" :insert-image, "insert-image" :insert-link, "insert-link" :insert-object, "insert-object" :insert-text, "insert-text" :list-add, "list-add" :list-remove, "list-remove" :mail-forward, "mail-forward" :mail-mark-important, "mail-mark-important" :mail-mark-junk, "mail-mark-junk" :mail-mark-notjunk, "mail-mark-notjunk" :mail-mark-read, "mail-mark-read" :mail-mark-unread, "mail-mark-unread" :mail-message-new, "mail-message-new" :mail-reply-all, "mail-reply-all" :mail-reply-sender, "mail-reply-sender" :mail-send, "mail-send" :mail-send-receive, "mail-send-receive" :media-eject, "media-eject" :media-playback-pause, "media-playback-pause" :media-playback-start, "media-playback-start" :media-playback-stop, "media-playback-stop" :media-record, "media-record" :media-seek-backward, "media-seek-backward" :media-seek-forward, "media-seek-forward" :media-skip-backward, "media-skip-backward" :media-skip-forward, "media-skip-forward" :object-flip-horizontal, "object-flip-horizontal" :object-flip-vertical, "object-flip-vertical" :object-rotate-left, "object-rotate-left" :object-rotate-right, "object-rotate-right" :process-stop, "process-stop" :system-lock-screen, "system-lock-screen" :system-log-out, "system-log-out" :system-run, "system-run" :system-search, "system-search" :system-reboot, "system-reboot" :system-shutdown, "system-shutdown" :tools-check-spelling, "tools-check-spelling" :view-fullscreen, "view-fullscreen" :view-refresh, "view-refresh" :view-restore, "view-restore" :view-sort-ascending, "view-sort-ascending" :view-sort-descending, "view-sort-descending" :window-close, "window-close" :window-new, "window-new" :zoom-fit-best, "zoom-fit-best" :zoom-in, "zoom-in" :zoom-original, "zoom-original" :zoom-out, "zoom-out" :process-working, "process-working" :accessories-calculator, "accessories-calculator" :accessories-character-map, "accessories-character-map" :accessories-dictionary, "accessories-dictionary" :accessories-text-editor, "accessories-text-editor" :help-browser, "help-browser" :multimedia-volume-control, "multimedia-volume-control" :preferences-desktop-accessibility, "preferences-desktop-accessibility" :preferences-desktop-font, "preferences-desktop-font" :preferences-desktop-keyboard, "preferences-desktop-keyboard" :preferences-desktop-locale, "preferences-desktop-locale" :preferences-desktop-multimedia, "preferences-desktop-multimedia" :preferences-desktop-screensaver, "preferences-desktop-screensaver" :preferences-desktop-theme, "preferences-desktop-theme" :preferences-desktop-wallpaper, "preferences-desktop-wallpaper" :system-file-manager, "system-file-manager" :system-software-install, "system-software-install" :system-software-update, "system-software-update" :utilities-system-monitor, "utilities-system-monitor" :utilities-terminal, "utilities-terminal" :applications-accessories, "applications-accessories" :applications-development, "applications-development" :applications-engineering, "applications-engineering" :applications-games, "applications-games" :applications-graphics, "applications-graphics" :applications-internet, "applications-internet" :applications-multimedia, "applications-multimedia" :applications-office, "applications-office" :applications-other, "applications-other" :applications-science, "applications-science" :applications-system, "applications-system" :applications-utilities, "applications-utilities" :preferences-desktop, "preferences-desktop" :preferences-desktop-peripherals, "preferences-desktop-peripherals" :preferences-desktop-personal, "preferences-desktop-personal" :preferences-other, "preferences-other" :preferences-system, "preferences-system" :preferences-system-network, "preferences-system-network" :system-help, "system-help" :audio-card, "audio-card" :audio-input-microphone, "audio-input-microphone" :battery, "battery" :camera-photo, "camera-photo" :camera-video, "camera-video" :camera-web, "camera-web" :computer, "computer" :drive-harddisk, "drive-harddisk" :drive-optical, "drive-optical" :drive-removable-media, "drive-removable-media" :input-gaming, "input-gaming" :input-keyboard, "input-keyboard" :input-mouse, "input-mouse" :input-tablet, "input-tablet" :media-flash, "media-flash" :media-floppy, "media-floppy" :media-optical, "media-optical" :media-tape, "media-tape" :modem, "modem" :multimedia-player, "multimedia-player" :network-wired, "network-wired" :network-wireless, "network-wireless" :pda, "pda" :phone, "phone" :printer, "printer" :scanner, "scanner" :video-display, "video-display" :emblem-default, "emblem-default" :emblem-documents, "emblem-documents" :emblem-downloads, "emblem-downloads" :emblem-favorite, "emblem-favorite" :emblem-important, "emblem-important" :emblem-mail, "emblem-mail" :emblem-photos, "emblem-photos" :emblem-readonly, "emblem-readonly" :emblem-shared, "emblem-shared" :emblem-symbolic-link, "emblem-symbolic-link" :emblem-synchronized, "emblem-synchronized" :emblem-system, "emblem-system" :emblem-unreadable, "emblem-unreadable" :face-angel, "face-angel" :face-angry, "face-angry" :face-cool, "face-cool" :face-crying, "face-crying" :face-devilish, "face-devilish" :face-embarrassed, "face-embarrassed" :face-kiss, "face-kiss" :face-laugh, "face-laugh" :face-monkey, "face-monkey" :face-plain, "face-plain" :face-raspberry, "face-raspberry" :face-sad, "face-sad" :face-sick, "face-sick" :face-smile, "face-smile" :face-smile-big, "face-smile-big" :face-smirk, "face-smirk" :face-surprise, "face-surprise" :face-tired, "face-tired" :face-uncertain, "face-uncertain" :face-wink, "face-wink" :face-worried, "face-worried" :flag-aa, "flag-aa" :application-x-executable, "application-x-executable" :audio-x-generic, "audio-x-generic" :font-x-generic, "font-x-generic" :image-x-generic, "image-x-generic" :package-x-generic, "package-x-generic" :text-html, "text-html" :text-x-generic, "text-x-generic" :text-x-generic-template, "text-x-generic-template" :text-x-script, "text-x-script" :video-x-generic, "video-x-generic" :x-office-address-book, "x-office-address-book" :x-office-calendar, "x-office-calendar" :x-office-document, "x-office-document" :x-office-presentation, "x-office-presentation" :x-office-spreadsheet, "x-office-spreadsheet" :folder, "folder" :folder-remote, "folder-remote" :network-server, "network-server" :network-workgroup, "network-workgroup" :start-here, "start-here" :user-bookmarks, "user-bookmarks" :user-desktop, "user-desktop" :user-home, "user-home" :user-trash, "user-trash" :appointment-missed, "appointment-missed" :appointment-soon, "appointment-soon" :audio-volume-high, "audio-volume-high" :audio-volume-low, "audio-volume-low" :audio-volume-medium, "audio-volume-medium" :audio-volume-muted, "audio-volume-muted" :battery-caution, "battery-caution" :battery-low, "battery-low" :dialog-error, "dialog-error" :dialog-information, "dialog-information" :dialog-password, "dialog-password" :dialog-question, "dialog-question" :dialog-warning, "dialog-warning" :folder-drag-accept, "folder-drag-accept" :folder-open, "folder-open" :folder-visiting, "folder-visiting" :image-loading, "image-loading" :image-missing, "image-missing" :mail-attachment, "mail-attachment" :mail-unread, "mail-unread" :mail-read, "mail-read" :mail-replied, "mail-replied" :mail-signed, "mail-signed" :mail-signed-verified, "mail-signed-verified" :media-playlist-repeat, "media-playlist-repeat" :media-playlist-shuffle, "media-playlist-shuffle" :network-error, "network-error" :network-idle, "network-idle" :network-offline, "network-offline" :network-receive, "network-receive" :network-transmit, "network-transmit" :network-transmit-receive, "network-transmit-receive" :printer-error, "printer-error" :printer-printing, "printer-printing" :security-high, "security-high" :security-medium, "security-medium" :security-low, "security-low" :software-update-available, "software-update-available" :software-update-urgent, "software-update-urgent" :sync-error, "sync-error" :sync-synchronizing, "sync-synchronizing" :task-due, "task-due" :task-past-due, "task-past-due" :user-available, "user-available" :user-away, "user-away" :user-idle, "user-idle" :user-offline, "user-offline" :user-trash-full, "user-trash-full" :weather-clear, "weather-clear" :weather-clear-night, "weather-clear-night" :weather-few-clouds, "weather-few-clouds" :weather-few-clouds-night, "weather-few-clouds-night" :weather-fog, "weather-fog" :weather-overcast, "weather-overcast" :weather-severe-alert, "weather-severe-alert" :weather-showers, "weather-showers" :weather-showers-scattered, "weather-showers-scattered" :weather-snow, "weather-snow" :weather-storm, "weather-storm"})
13068
(ns notify-send.icons) (def icons {:address-book-new, "address-book-new" :application-exit, "application-exit" :appointment-new, "appointment-new" :call-start, "call-start" :call-stop, "call-stop" :contact-new, "contact-new" :document-new, "document-new" :document-open, "document-open" :document-open-recent, "document-open-recent" :document-page-setup, "document-page-setup" :document-print, "document-print" :document-print-preview, "document-print-preview" :document-properties, "document-properties" :document-revert, "document-revert" :document-save, "document-save" :document-save-as, "document-save-as" :document-send, "document-send" :edit-clear, "edit-clear" :edit-copy, "edit-copy" :edit-cut, "edit-cut" :edit-delete, "edit-delete" :edit-find, "edit-find" :edit-find-replace, "edit-find-replace" :edit-paste, "edit-paste" :edit-redo, "edit-redo" :edit-select-all, "edit-select-all" :edit-undo, "edit-undo" :folder-new, "folder-new" :format-indent-less, "format-indent-less" :format-indent-more, "format-indent-more" :format-justify-center, "format-justify-center" :format-justify-fill, "format-justify-fill" :format-justify-left, "format-justify-left" :format-justify-right, "format-justify-right" :format-text-direction-ltr, "format-text-direction-ltr" :format-text-direction-rtl, "format-text-direction-rtl" :format-text-bold, "format-text-bold" :format-text-italic, "format-text-italic" :format-text-underline, "format-text-underline" :format-text-strikethrough, "format-text-strikethrough" :go-bottom, "go-bottom" :go-down, "go-down" :go-first, "go-first" :go-home, "go-home" :go-jump, "go-jump" :go-last, "go-last" :go-next, "go-next" :go-previous, "go-previous" :go-top, "go-top" :go-up, "go-up" :help-about, "help-about" :help-contents, "help-contents" :help-faq, "help-faq" :insert-image, "insert-image" :insert-link, "insert-link" :insert-object, "insert-object" :insert-text, "insert-text" :list-add, "list-add" :list-remove, "list-remove" :mail-forward, "mail-forward" :mail-mark-important, "mail-mark-important" :mail-mark-junk, "mail-mark-junk" :mail-mark-notjunk, "mail-mark-notjunk" :mail-mark-read, "mail-mark-read" :mail-mark-unread, "mail-mark-unread" :mail-message-new, "mail-message-new" :mail-reply-all, "mail-reply-all" :mail-reply-sender, "mail-reply-sender" :mail-send, "mail-send" :mail-send-receive, "mail-send-receive" :media-eject, "media-eject" :media-playback-pause, "media-playback-pause" :media-playback-start, "media-playback-start" :media-playback-stop, "media-playback-stop" :media-record, "media-record" :media-seek-backward, "media-seek-backward" :media-seek-forward, "media-seek-forward" :media-skip-backward, "media-skip-backward" :media-skip-forward, "media-skip-forward" :object-flip-horizontal, "object-flip-horizontal" :object-flip-vertical, "object-flip-vertical" :object-rotate-left, "object-rotate-left" :object-rotate-right, "object-rotate-right" :process-stop, "process-stop" :system-lock-screen, "system-lock-screen" :system-log-out, "system-log-out" :system-run, "system-run" :system-search, "system-search" :system-reboot, "system-reboot" :system-shutdown, "system-shutdown" :tools-check-spelling, "tools-check-spelling" :view-fullscreen, "view-fullscreen" :view-refresh, "view-refresh" :view-restore, "view-restore" :view-sort-ascending, "view-sort-ascending" :view-sort-descending, "view-sort-descending" :window-close, "window-close" :window-new, "window-new" :zoom-fit-best, "zoom-fit-best" :zoom-in, "zoom-in" :zoom-original, "zoom-original" :zoom-out, "zoom-out" :process-working, "process-working" :accessories-calculator, "accessories-calculator" :accessories-character-map, "accessories-character-map" :accessories-dictionary, "accessories-dictionary" :accessories-text-editor, "accessories-text-editor" :help-browser, "help-browser" :multimedia-volume-control, "multimedia-volume-control" :preferences-desktop-accessibility, "preferences-desktop-accessibility" :preferences-desktop-font, "preferences-desktop-font" :preferences-desktop-keyboard, "preferences-desktop-keyboard" :preferences-desktop-locale, "preferences-desktop-locale" :preferences-desktop-multimedia, "preferences-desktop-multimedia" :preferences-desktop-screensaver, "preferences-desktop-screensaver" :preferences-desktop-theme, "preferences-desktop-theme" :preferences-desktop-wallpaper, "preferences-desktop-wallpaper" :system-file-manager, "system-file-manager" :system-software-install, "system-software-install" :system-software-update, "system-software-update" :utilities-system-monitor, "utilities-system-monitor" :utilities-terminal, "utilities-terminal" :applications-accessories, "applications-accessories" :applications-development, "applications-development" :applications-engineering, "applications-engineering" :applications-games, "applications-games" :applications-graphics, "applications-graphics" :applications-internet, "applications-internet" :applications-multimedia, "applications-multimedia" :applications-office, "applications-office" :applications-other, "applications-other" :applications-science, "applications-science" :applications-system, "applications-system" :applications-utilities, "applications-utilities" :preferences-desktop, "preferences-desktop" :preferences-desktop-peripherals, "preferences-desktop-peripherals" :preferences-desktop-personal, "preferences-desktop-personal" :preferences-other, "preferences-other" :preferences-system, "preferences-system" :preferences-system-network, "preferences-system-network" :system-help, "system-help" :audio-card, "audio-card" :audio-input-microphone, "audio-input-microphone" :battery, "battery" :camera-photo, "camera-photo" :camera-video, "camera-video" :camera-web, "camera-web" :computer, "computer" :drive-harddisk, "drive-harddisk" :drive-optical, "drive-optical" :drive-removable-media, "drive-removable-media" :input-gaming, "input-gaming" :input-keyboard, "input-keyboard" :input-mouse, "input-mouse" :input-tablet, "input-tablet" :media-flash, "media-flash" :media-floppy, "media-floppy" :media-optical, "media-optical" :media-tape, "media-tape" :modem, "modem" :multimedia-player, "multimedia-player" :network-wired, "network-wired" :network-wireless, "network-wireless" :pda, "pda" :phone, "phone" :printer, "printer" :scanner, "scanner" :video-display, "video-display" :emblem-default, "emblem-default" :emblem-documents, "emblem-documents" :emblem-downloads, "emblem-downloads" :emblem-favorite, "emblem-favorite" :emblem-important, "emblem-important" :emblem-mail, "emblem-mail" :emblem-photos, "emblem-photos" :emblem-readonly, "emblem-readonly" :emblem-shared, "emblem-shared" :emblem-symbolic-link, "emblem-symbolic-link" :emblem-synchronized, "emblem-synchronized" :emblem-system, "emblem-system" :emblem-unreadable, "emblem-unreadable" :face-angel, "face-angel" :face-angry, "face-angry" :face-cool, "face-cool" :face-crying, "face-crying" :face-devilish, "face-devilish" :face-embarrassed, "face-embarrassed" :face-kiss, "face-kiss" :face-laugh, "face-laugh" :face-monkey, "face-monkey" :face-plain, "face-plain" :face-raspberry, "face-raspberry" :face-sad, "face-sad" :face-sick, "face-sick" :face-smile, "face-smile" :face-smile-big, "face-smile-big" :face-smirk, "face-smirk" :face-surprise, "face-surprise" :face-tired, "face-tired" :face-uncertain, "face-uncertain" :face-wink, "face-wink" :face-worried, "face-worried" :flag-aa, "flag-aa" :application-x-executable, "application-x-executable" :audio-x-generic, "audio-x-generic" :font-x-generic, "font-x-generic" :image-x-generic, "image-x-generic" :package-x-generic, "package-x-generic" :text-html, "text-html" :text-x-generic, "text-x-generic" :text-x-generic-template, "text-x-generic-template" :text-x-script, "text-x-script" :video-x-generic, "video-x-generic" :x-office-address-book, "x-office-address-book" :x-office-calendar, "x-office-calendar" :x-office-document, "x-office-document" :x-office-presentation, "x-office-presentation" :x-office-spreadsheet, "x-office-spreadsheet" :folder, "folder" :folder-remote, "folder-remote" :network-server, "network-server" :network-workgroup, "network-workgroup" :start-here, "start-here" :user-bookmarks, "user-bookmarks" :user-desktop, "user-desktop" :user-home, "user-home" :user-trash, "user-trash" :appointment-missed, "appointment-missed" :appointment-soon, "appointment-soon" :audio-volume-high, "audio-volume-high" :audio-volume-low, "audio-volume-low" :audio-volume-medium, "audio-volume-medium" :audio-volume-muted, "audio-volume-muted" :battery-caution, "battery-caution" :battery-low, "battery-low" :dialog-error, "dialog-error" :dialog-information, "dialog-information" :dialog-password, "<PASSWORD>" :dialog-question, "dialog-question" :dialog-warning, "dialog-warning" :folder-drag-accept, "folder-drag-accept" :folder-open, "folder-open" :folder-visiting, "folder-visiting" :image-loading, "image-loading" :image-missing, "image-missing" :mail-attachment, "mail-attachment" :mail-unread, "mail-unread" :mail-read, "mail-read" :mail-replied, "mail-replied" :mail-signed, "mail-signed" :mail-signed-verified, "mail-signed-verified" :media-playlist-repeat, "media-playlist-repeat" :media-playlist-shuffle, "media-playlist-shuffle" :network-error, "network-error" :network-idle, "network-idle" :network-offline, "network-offline" :network-receive, "network-receive" :network-transmit, "network-transmit" :network-transmit-receive, "network-transmit-receive" :printer-error, "printer-error" :printer-printing, "printer-printing" :security-high, "security-high" :security-medium, "security-medium" :security-low, "security-low" :software-update-available, "software-update-available" :software-update-urgent, "software-update-urgent" :sync-error, "sync-error" :sync-synchronizing, "sync-synchronizing" :task-due, "task-due" :task-past-due, "task-past-due" :user-available, "user-available" :user-away, "user-away" :user-idle, "user-idle" :user-offline, "user-offline" :user-trash-full, "user-trash-full" :weather-clear, "weather-clear" :weather-clear-night, "weather-clear-night" :weather-few-clouds, "weather-few-clouds" :weather-few-clouds-night, "weather-few-clouds-night" :weather-fog, "weather-fog" :weather-overcast, "weather-overcast" :weather-severe-alert, "weather-severe-alert" :weather-showers, "weather-showers" :weather-showers-scattered, "weather-showers-scattered" :weather-snow, "weather-snow" :weather-storm, "weather-storm"})
true
(ns notify-send.icons) (def icons {:address-book-new, "address-book-new" :application-exit, "application-exit" :appointment-new, "appointment-new" :call-start, "call-start" :call-stop, "call-stop" :contact-new, "contact-new" :document-new, "document-new" :document-open, "document-open" :document-open-recent, "document-open-recent" :document-page-setup, "document-page-setup" :document-print, "document-print" :document-print-preview, "document-print-preview" :document-properties, "document-properties" :document-revert, "document-revert" :document-save, "document-save" :document-save-as, "document-save-as" :document-send, "document-send" :edit-clear, "edit-clear" :edit-copy, "edit-copy" :edit-cut, "edit-cut" :edit-delete, "edit-delete" :edit-find, "edit-find" :edit-find-replace, "edit-find-replace" :edit-paste, "edit-paste" :edit-redo, "edit-redo" :edit-select-all, "edit-select-all" :edit-undo, "edit-undo" :folder-new, "folder-new" :format-indent-less, "format-indent-less" :format-indent-more, "format-indent-more" :format-justify-center, "format-justify-center" :format-justify-fill, "format-justify-fill" :format-justify-left, "format-justify-left" :format-justify-right, "format-justify-right" :format-text-direction-ltr, "format-text-direction-ltr" :format-text-direction-rtl, "format-text-direction-rtl" :format-text-bold, "format-text-bold" :format-text-italic, "format-text-italic" :format-text-underline, "format-text-underline" :format-text-strikethrough, "format-text-strikethrough" :go-bottom, "go-bottom" :go-down, "go-down" :go-first, "go-first" :go-home, "go-home" :go-jump, "go-jump" :go-last, "go-last" :go-next, "go-next" :go-previous, "go-previous" :go-top, "go-top" :go-up, "go-up" :help-about, "help-about" :help-contents, "help-contents" :help-faq, "help-faq" :insert-image, "insert-image" :insert-link, "insert-link" :insert-object, "insert-object" :insert-text, "insert-text" :list-add, "list-add" :list-remove, "list-remove" :mail-forward, "mail-forward" :mail-mark-important, "mail-mark-important" :mail-mark-junk, "mail-mark-junk" :mail-mark-notjunk, "mail-mark-notjunk" :mail-mark-read, "mail-mark-read" :mail-mark-unread, "mail-mark-unread" :mail-message-new, "mail-message-new" :mail-reply-all, "mail-reply-all" :mail-reply-sender, "mail-reply-sender" :mail-send, "mail-send" :mail-send-receive, "mail-send-receive" :media-eject, "media-eject" :media-playback-pause, "media-playback-pause" :media-playback-start, "media-playback-start" :media-playback-stop, "media-playback-stop" :media-record, "media-record" :media-seek-backward, "media-seek-backward" :media-seek-forward, "media-seek-forward" :media-skip-backward, "media-skip-backward" :media-skip-forward, "media-skip-forward" :object-flip-horizontal, "object-flip-horizontal" :object-flip-vertical, "object-flip-vertical" :object-rotate-left, "object-rotate-left" :object-rotate-right, "object-rotate-right" :process-stop, "process-stop" :system-lock-screen, "system-lock-screen" :system-log-out, "system-log-out" :system-run, "system-run" :system-search, "system-search" :system-reboot, "system-reboot" :system-shutdown, "system-shutdown" :tools-check-spelling, "tools-check-spelling" :view-fullscreen, "view-fullscreen" :view-refresh, "view-refresh" :view-restore, "view-restore" :view-sort-ascending, "view-sort-ascending" :view-sort-descending, "view-sort-descending" :window-close, "window-close" :window-new, "window-new" :zoom-fit-best, "zoom-fit-best" :zoom-in, "zoom-in" :zoom-original, "zoom-original" :zoom-out, "zoom-out" :process-working, "process-working" :accessories-calculator, "accessories-calculator" :accessories-character-map, "accessories-character-map" :accessories-dictionary, "accessories-dictionary" :accessories-text-editor, "accessories-text-editor" :help-browser, "help-browser" :multimedia-volume-control, "multimedia-volume-control" :preferences-desktop-accessibility, "preferences-desktop-accessibility" :preferences-desktop-font, "preferences-desktop-font" :preferences-desktop-keyboard, "preferences-desktop-keyboard" :preferences-desktop-locale, "preferences-desktop-locale" :preferences-desktop-multimedia, "preferences-desktop-multimedia" :preferences-desktop-screensaver, "preferences-desktop-screensaver" :preferences-desktop-theme, "preferences-desktop-theme" :preferences-desktop-wallpaper, "preferences-desktop-wallpaper" :system-file-manager, "system-file-manager" :system-software-install, "system-software-install" :system-software-update, "system-software-update" :utilities-system-monitor, "utilities-system-monitor" :utilities-terminal, "utilities-terminal" :applications-accessories, "applications-accessories" :applications-development, "applications-development" :applications-engineering, "applications-engineering" :applications-games, "applications-games" :applications-graphics, "applications-graphics" :applications-internet, "applications-internet" :applications-multimedia, "applications-multimedia" :applications-office, "applications-office" :applications-other, "applications-other" :applications-science, "applications-science" :applications-system, "applications-system" :applications-utilities, "applications-utilities" :preferences-desktop, "preferences-desktop" :preferences-desktop-peripherals, "preferences-desktop-peripherals" :preferences-desktop-personal, "preferences-desktop-personal" :preferences-other, "preferences-other" :preferences-system, "preferences-system" :preferences-system-network, "preferences-system-network" :system-help, "system-help" :audio-card, "audio-card" :audio-input-microphone, "audio-input-microphone" :battery, "battery" :camera-photo, "camera-photo" :camera-video, "camera-video" :camera-web, "camera-web" :computer, "computer" :drive-harddisk, "drive-harddisk" :drive-optical, "drive-optical" :drive-removable-media, "drive-removable-media" :input-gaming, "input-gaming" :input-keyboard, "input-keyboard" :input-mouse, "input-mouse" :input-tablet, "input-tablet" :media-flash, "media-flash" :media-floppy, "media-floppy" :media-optical, "media-optical" :media-tape, "media-tape" :modem, "modem" :multimedia-player, "multimedia-player" :network-wired, "network-wired" :network-wireless, "network-wireless" :pda, "pda" :phone, "phone" :printer, "printer" :scanner, "scanner" :video-display, "video-display" :emblem-default, "emblem-default" :emblem-documents, "emblem-documents" :emblem-downloads, "emblem-downloads" :emblem-favorite, "emblem-favorite" :emblem-important, "emblem-important" :emblem-mail, "emblem-mail" :emblem-photos, "emblem-photos" :emblem-readonly, "emblem-readonly" :emblem-shared, "emblem-shared" :emblem-symbolic-link, "emblem-symbolic-link" :emblem-synchronized, "emblem-synchronized" :emblem-system, "emblem-system" :emblem-unreadable, "emblem-unreadable" :face-angel, "face-angel" :face-angry, "face-angry" :face-cool, "face-cool" :face-crying, "face-crying" :face-devilish, "face-devilish" :face-embarrassed, "face-embarrassed" :face-kiss, "face-kiss" :face-laugh, "face-laugh" :face-monkey, "face-monkey" :face-plain, "face-plain" :face-raspberry, "face-raspberry" :face-sad, "face-sad" :face-sick, "face-sick" :face-smile, "face-smile" :face-smile-big, "face-smile-big" :face-smirk, "face-smirk" :face-surprise, "face-surprise" :face-tired, "face-tired" :face-uncertain, "face-uncertain" :face-wink, "face-wink" :face-worried, "face-worried" :flag-aa, "flag-aa" :application-x-executable, "application-x-executable" :audio-x-generic, "audio-x-generic" :font-x-generic, "font-x-generic" :image-x-generic, "image-x-generic" :package-x-generic, "package-x-generic" :text-html, "text-html" :text-x-generic, "text-x-generic" :text-x-generic-template, "text-x-generic-template" :text-x-script, "text-x-script" :video-x-generic, "video-x-generic" :x-office-address-book, "x-office-address-book" :x-office-calendar, "x-office-calendar" :x-office-document, "x-office-document" :x-office-presentation, "x-office-presentation" :x-office-spreadsheet, "x-office-spreadsheet" :folder, "folder" :folder-remote, "folder-remote" :network-server, "network-server" :network-workgroup, "network-workgroup" :start-here, "start-here" :user-bookmarks, "user-bookmarks" :user-desktop, "user-desktop" :user-home, "user-home" :user-trash, "user-trash" :appointment-missed, "appointment-missed" :appointment-soon, "appointment-soon" :audio-volume-high, "audio-volume-high" :audio-volume-low, "audio-volume-low" :audio-volume-medium, "audio-volume-medium" :audio-volume-muted, "audio-volume-muted" :battery-caution, "battery-caution" :battery-low, "battery-low" :dialog-error, "dialog-error" :dialog-information, "dialog-information" :dialog-password, "PI:PASSWORD:<PASSWORD>END_PI" :dialog-question, "dialog-question" :dialog-warning, "dialog-warning" :folder-drag-accept, "folder-drag-accept" :folder-open, "folder-open" :folder-visiting, "folder-visiting" :image-loading, "image-loading" :image-missing, "image-missing" :mail-attachment, "mail-attachment" :mail-unread, "mail-unread" :mail-read, "mail-read" :mail-replied, "mail-replied" :mail-signed, "mail-signed" :mail-signed-verified, "mail-signed-verified" :media-playlist-repeat, "media-playlist-repeat" :media-playlist-shuffle, "media-playlist-shuffle" :network-error, "network-error" :network-idle, "network-idle" :network-offline, "network-offline" :network-receive, "network-receive" :network-transmit, "network-transmit" :network-transmit-receive, "network-transmit-receive" :printer-error, "printer-error" :printer-printing, "printer-printing" :security-high, "security-high" :security-medium, "security-medium" :security-low, "security-low" :software-update-available, "software-update-available" :software-update-urgent, "software-update-urgent" :sync-error, "sync-error" :sync-synchronizing, "sync-synchronizing" :task-due, "task-due" :task-past-due, "task-past-due" :user-available, "user-available" :user-away, "user-away" :user-idle, "user-idle" :user-offline, "user-offline" :user-trash-full, "user-trash-full" :weather-clear, "weather-clear" :weather-clear-night, "weather-clear-night" :weather-few-clouds, "weather-few-clouds" :weather-few-clouds-night, "weather-few-clouds-night" :weather-fog, "weather-fog" :weather-overcast, "weather-overcast" :weather-severe-alert, "weather-severe-alert" :weather-showers, "weather-showers" :weather-showers-scattered, "weather-showers-scattered" :weather-snow, "weather-snow" :weather-storm, "weather-storm"})
[ { "context": "; Copyright (c) 2017-present Walmart, Inc.\n;\n; Licensed under the Apache License, Vers", "end": 36, "score": 0.9919411540031433, "start": 29, "tag": "NAME", "value": "Walmart" } ]
src/com/walmartlabs/lacinia/immutant/subscriptions.clj
dissoc/lacinia-immutant
0
; Copyright (c) 2017-present Walmart, Inc. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns com.walmartlabs.lacinia.immutant.subscriptions "Support for GraphQL subscriptions using Jetty WebSockets, following the design of the Apollo client and server." {:added "0.3.0"} (:require [com.walmartlabs.lacinia :as lacinia] [com.walmartlabs.lacinia.util :as util] [com.walmartlabs.lacinia.internal-utils :refer [cond-let to-message]] [clojure.core.async :as async :refer [chan put! close! go-loop <! >! alt! thread]] [cheshire.core :as cheshire] [io.pedestal.interceptor :refer [interceptor]] [io.pedestal.interceptor.chain :as chain] ;; Removed jetty websockets ;;[io.pedestal.http.jetty.websockets :as ws] [com.walmartlabs.lacinia.immutant.websockets :as ws] [io.pedestal.log :as log] [com.walmartlabs.lacinia.parser :as parser] [com.walmartlabs.lacinia.validator :as validator] [com.walmartlabs.lacinia.executor :as executor] [com.walmartlabs.lacinia.constants :as constants] [com.walmartlabs.lacinia.resolve :as resolve] [clojure.string :as str] [clojure.spec.alpha :as s] [com.walmartlabs.lacinia.immutant.spec :as spec] [immutant.web.async :as imm-async]) ;; (:import ;; (org.eclipse.jetty.websocket.api UpgradeResponse)) ) (when (-> *clojure-version* :minor (< 9)) (require '[clojure.future :refer [pos-int?]])) (defn ^:private xform-channel [input-ch output-ch xf] (go-loop [] (if-some [input (<! input-ch)] (let [output (xf input)] (when (imm-async/send! output-ch output) ;;(>! output-ch output) (recur))) ;;(close! output-ch) (imm-async/close output-ch)))) (defn ^:private response-encode-loop "Takes values from the input channel, encodes them as a JSON string, and puts them into the output-ch." [input-ch output-ch] (xform-channel input-ch output-ch cheshire/generate-string)) (defn ^:private ws-parse-loop "Parses text messages sent from the client into Clojure data with keyword keys, which is passed along to the output-ch. Parse errors are converted into connection_error messages sent to the response-ch." [input-ch output-ch response-data-ch] (go-loop [] (when-some [text (<! input-ch)] (when-some [parsed (try (cheshire/parse-string text true) (catch Throwable t (log/debug :event ::malformed-text :message text) (>! response-data-ch {:type :connection_error :payload (util/as-error-map t)})))] (>! output-ch parsed)) (recur)))) (defn ^:private execute-query-interceptors "Executes the interceptor chain for an operation, and returns a channel used to shutdown and cleanup the operation." [id payload response-data-ch cleanup-ch context] (let [shutdown-ch (chan) response-spy-ch (chan 1) request (assoc payload :id id :shutdown-ch shutdown-ch :response-data-ch response-spy-ch)] ;; When the spy channel is closed, we write the id ;; to the cleanup-ch; the containing CSP then removes the ;; shutdown-ch from its subs map. (go-loop [] (let [message (<! response-spy-ch)] (if (some? message) (do (>! response-data-ch message) (recur)) (>! cleanup-ch id)))) ;; Execute the chain, for side-effects. (chain/execute (update context :request merge request)) ;; Return a shutdown channel that the CSP can close to shutdown the subscription shutdown-ch)) (defn ^:private connection-loop "A loop started for each connection." [keep-alive-ms ws-data-ch response-data-ch context] (let [cleanup-ch (chan 1)] ;; Keep track of subscriptions by (client-supplied) unique id. ;; The value is a shutdown channel that, when closed, triggers ;; a cleanup of the subscription. (go-loop [connection-state {:subs {} :connection-params nil}] (alt! cleanup-ch ([id] (log/debug :event ::cleanup-ch :id id) (recur (update connection-state :subs dissoc id))) ;; TODO: Maybe only after connection_init? (async/timeout keep-alive-ms) (do (log/debug :event ::timeout) (>! response-data-ch {:type :ka}) (recur connection-state)) ws-data-ch ([data] (if (nil? data) ;; When the client closes the connection, any running subscriptions need to ;; shutdown and cleanup. (do (log/debug :event ::client-close) (run! close! (-> connection-state :subs vals))) ;; Otherwise it's a message from the client to be acted upon. (let [{:keys [id payload type]} data] (case type "connection_init" (when (>! response-data-ch {:type :connection_ack}) (recur (assoc connection-state :connection-params payload))) ;; TODO: Track state, don't allow start, etc. until after connection_init "start" (if (contains? (:subs connection-state) id) (do (log/debug :event ::ignoring-duplicate :id id) (recur connection-state)) (do (log/debug :event ::start :id id) (let [merged-context (assoc context :connection-params (:connection-params connection-state)) sub-shutdown-ch (execute-query-interceptors id payload response-data-ch cleanup-ch merged-context)] (recur (assoc-in connection-state [:subs id] sub-shutdown-ch))))) "stop" (do (log/debug :event ::stop :id id) (when-some [sub-shutdown-ch (get-in connection-state [:subs id])] (close! sub-shutdown-ch)) (recur connection-state)) "connection_terminate" (do (log/debug :event ::terminate) (run! close! (-> connection-state :subs vals)) ;; This shuts down the connection entirely. (close! response-data-ch)) ;; Not recognized! (let [response (cond-> {:type :error :payload {:message "Unrecognized message type." :type type}} id (assoc :id id))] (log/debug :event ::unknown-type :type type) (>! response-data-ch response) (recur connection-state)))))))))) ;; We try to keep the interceptors here and in the main namespace as similar as possible, but ;; there are distinctions that can't be readily smoothed over. (defn ^:private fix-up-message [s] (when-not (str/blank? s) (-> s str/trim (str/replace #"\s*\.+$" "") str/capitalize))) (defn ^:private ex-data-seq "Uses the exception root causes to build a sequence of non-nil ex-data from each exception in the exception stack." [t] (loop [stack [] current ^Throwable t] (let [stack' (conj stack current) next-t (.getCause current)] ;; Sometime .getCause returns this, sometimes nil, when the end of the stack is ;; reached. (if (or (nil? next-t) (= current next-t)) (keep ex-data stack') (recur stack' next-t))))) (defn ^:private construct-exception-payload [^Throwable t] (cond-let :let [errors (->> t ex-data-seq (keep ::errors) first) parse-errors (->> errors (keep :message) distinct) locations (->> (mapcat :locations errors) (remove nil?) distinct seq)] (seq parse-errors) (cond-> {:message (str "Failed to parse GraphQL query. " (->> parse-errors (keep fix-up-message) (str/join "; ")) ".")} locations (assoc :locations locations)) ;; Apollo spec only has room for one error, so just use the first (seq errors) (cond-> (first errors) locations (assoc :locations locations)) :else ;; Strip off the exception added by Pedestal and convert ;; the message into an error map (cond-> {:message (to-message t)} locations (assoc :locations locations)))) (def exception-handler-interceptor "An interceptor that implements the :error callback, to send an \"error\" message to the client." (interceptor {:name ::exception-handler :error (fn [context ^Throwable t] (let [{:keys [id response-data-ch]} (:request context) ;; Strip off the wrapper exception added by Pedestal payload (construct-exception-payload (.getCause t))] (put! response-data-ch {:type :error :id id :payload payload}) (close! response-data-ch)))})) (def send-operation-response-interceptor "Interceptor responsible for the :response key of the context (set when a request is either a query or mutation, but not a subscription). The :response data is packaged up as the payload of a \"data\" message to the client, followed by a \"complete\" message." (interceptor {:name ::send-operation-response :leave (fn [context] (when-let [response (:response context)] (let [{:keys [id response-data-ch]} (:request context)] (put! response-data-ch {:type :data :id id :payload response}) (put! response-data-ch {:type :complete :id id}) (close! response-data-ch))) context)})) (defn query-parser-interceptor "An interceptor that parses the query and places a prepared and validated query into the :parsed-lacinia-query key of the request. `compiled-schema` may be the actual compiled schema, or a no-arguments function that returns the compiled schema." [compiled-schema] (interceptor {:name ::query-parser :enter (fn [context] (let [{operation-name :operationName :keys [query variables]} (:request context) actual-schema (if (map? compiled-schema) compiled-schema (compiled-schema)) parsed-query (try (parser/parse-query actual-schema query operation-name) (catch Throwable t (throw (ex-info (to-message t) {::errors (-> t ex-data :errors)} t)))) prepared (parser/prepare-with-query-variables parsed-query variables) errors (validator/validate actual-schema prepared {})] (if (seq errors) (throw (ex-info "Query validation errors." {::errors errors})) (assoc-in context [:request :parsed-lacinia-query] prepared))))})) (defn inject-app-context-interceptor "Adds a :lacinia-app-context key to the request, used when executing the query. It is not uncommon to replace this interceptor with one that constructs the application context dynamically." [app-context] (interceptor {:name ::inject-app-context :enter (fn [context] (assoc-in context [:request :lacinia-app-context] app-context))})) (defn ^:private execute-operation [context parsed-query] (let [ch (chan 1)] (-> context (get-in [:request :lacinia-app-context]) (assoc ::lacinia/connection-params (:connection-params context) constants/parsed-query-key parsed-query) executor/execute-query (resolve/on-deliver! (fn [response] (put! ch (assoc context :response response)))) ;; Don't execute the query in a limited go block thread thread) ch)) (defn ^:private execute-subscription [context parsed-query] (let [{:keys [::values-chan-fn request]} context source-stream-ch (values-chan-fn) {:keys [id shutdown-ch response-data-ch]} request source-stream (fn [value] (if (some? value) (put! source-stream-ch value) (close! source-stream-ch))) app-context (-> context (get-in [:request :lacinia-app-context]) (assoc ::lacinia/connection-params (:connection-params context) constants/parsed-query-key parsed-query)) cleanup-fn (executor/invoke-streamer app-context source-stream)] (go-loop [] (alt! ;; TODO: A timeout? ;; This channel is closed when the client sends a "stop" message shutdown-ch (do (close! response-data-ch) (cleanup-fn)) source-stream-ch ([value] (if (some? value) (do (-> app-context (assoc ::executor/resolved-value value) executor/execute-query (resolve/on-deliver! (fn [response] (put! response-data-ch {:type :data :id id :payload response}))) ;; Don't execute the query in a limited go block thread thread) (recur)) (do ;; The streamer has signalled that it has exhausted the subscription. (>! response-data-ch {:type :complete :id id}) (close! response-data-ch) (cleanup-fn)))))) ;; Return the context unchanged, it will unwind while the above process ;; does the real work. context)) (def execute-operation-interceptor "Executes a mutation or query operation and sets the :response key of the context, or executes a long-lived subscription operation." (interceptor {:name ::execute-operation :enter (fn [context] (let [request (:request context) parsed-query (:parsed-lacinia-query request) operation-type (-> parsed-query parser/operations :type)] (if (= operation-type :subscription) (execute-subscription context parsed-query) (execute-operation context parsed-query))))})) (defn default-subscription-interceptors "Processing of operation requests from the client is passed through interceptor pipeline. The context for the pipeline includes special keys for the necessary channels. The :request key is the payload sent from the client, along with additional keys: :response-data-ch : Channel to which Clojure data destined for the client should be written. : This should be closed when the subscription data is exhausted. :shutdown-ch : This channel will be closed if the client terminates the connection. For subscriptions, this ensures that the subscription is cleaned up. :id : The client-provided string that must be included in the response. For mutation and query operations, a :response key is added to the context, which triggers a response to the client. For subscription operations, it's a bit different; there's no immediate response, but a new CSP will work with the streamer defined by the subscription to send a sequence of \"data\" messages to the client. * ::exception-handler -- [[exception-handler-interceptor]] * ::send-operation-response -- [[send-operation-response-interceptor]] * ::query-parser -- [[query-parser-interceptor]] * ::inject-app-context -- [[inject-app-context-interceptor]] * ::execute-operation -- [[execute-operation-interceptor]] Returns a vector of interceptors." [compiled-schema app-context] [exception-handler-interceptor send-operation-response-interceptor (query-parser-interceptor compiled-schema) (inject-app-context-interceptor app-context) execute-operation-interceptor]) (defn listener-fn-factory "A factory for the function used to create a WS listener. This function is invoked for each new client connecting to the service. `compiled-schema` may be the actual compiled schema, or a no-arguments function that returns the compiled schema. Once a subscription is initiated, the flow is: streamer -> values channel -> resolver -> response channel -> send channel The default channels are all buffered and non-lossy, which means that a very active streamer may be able to saturate the web socket used to send responses to the client. By introducing lossiness or different buffers, the behavior can be tuned. Each new subscription from the same client will invoke a new streamer and create a corresponding values channel, but there is only one response channel per client. Options: :keep-alive-ms (default: 30000) : The interval at which keep alive messages are sent to the client. :app-context : The base application context provided to Lacinia when executing a query. :subscription-interceptors : A seq of interceptors for processing queries. The default is derived from [[default-subscription-interceptors]]. :init-context : A function returning the base context for the subscription-interceptors to operate on. The function takes the following arguments: - the minimal viable context for operation - the ServletUpgradeRequest that initiated this connection - the ServletUpgradeResponse to the upgrade request Defaults to returning the context unchanged. :response-chan-fn : A function that returns a new channel. Responses to be written to client are put into this channel. The default is a non-lossy channel with a buffer size of 10. :values-chan-fn : A function that returns a new channel. The channel conveys the values provided by the subscription's streamer. The values are executed as queries, then transformed into responses that are put into the response channel. The default is a non-lossy channel with a buffer size of 1. :send-buffer-or-n : Used to create the channel of text responses sent to the client. The default is 10 (a non-lossy channel)." [compiled-schema options] (let [{:keys [keep-alive-ms app-context init-context send-buffer-or-n response-chan-fn values-chan-fn] :or {keep-alive-ms 30000 send-buffer-or-n 10 response-chan-fn #(chan 10) values-chan-fn #(chan 1) init-context (fn [ctx & _args] ctx)}} options interceptors (or (:subscription-interceptors options) (default-subscription-interceptors compiled-schema app-context)) base-context (chain/enqueue {::chain/terminators [:response] ::values-chan-fn values-chan-fn} interceptors)] (log/debug :event ::configuring :keep-alive-ms keep-alive-ms) (fn [req] ;; [req resp _ws-map] ;; immutant doesnt support subprotocols?? but not required ;;(.setAcceptedSubProtocol ^UpgradeResponse resp "graphql-ws") (log/debug :event ::upgrade-requested) (let [response-data-ch (response-chan-fn) ; server data -> client ws-text-ch (chan 1) ; client text -> server ws-data-ch (chan 10) ; client text -> client data on-close (fn [_ _] (log/debug :event ::closed) (close! response-data-ch) (close! ws-data-ch)) ;;base-context' (init-context base-context req resp) base-context' (init-context base-context req) ;; on-connect (fn [_session send-ch] ;; (log/debug :event ::connected) ;; (response-encode-loop response-data-ch send-ch) ;; (ws-parse-loop ws-text-ch ws-data-ch response-data-ch) ;; (connection-loop keep-alive-ms ws-data-ch response-data-ch base-context')) on-connect (fn [_ send-ch] (log/debug :event ::connected) (response-encode-loop response-data-ch send-ch) (ws-parse-loop ws-text-ch ws-data-ch response-data-ch) (connection-loop keep-alive-ms ws-data-ch response-data-ch base-context'))] ;; (ws/make-ws-listener ;; {:on-connect (ws/start-ws-connection on-connect send-buffer-or-n) ;; :on-text #(put! ws-text-ch %) ;; :on-error #(log/error :event ::error :exception %) ;; :on-close on-close}) (ws/make-ws-listener {:on-open (ws/start-ws-connection on-connect send-buffer-or-n) :on-message #(put! ws-text-ch %) :on-error #(log/error :event ::error :exception %) :on-close on-close}))))) (s/fdef listener-fn-factory :args (s/cat :compiled-schema ::spec/compiled-schema :options (s/nilable ::listener-fn-factory-options))) (s/def ::listener-fn-factory-options (s/keys :opt-un [::keep-alive-ms ::spec/app-context ::subscription-interceptors ::init-context ::response-ch-fn ::values-chan-fn ::send-buffer-or-n])) (s/def ::keep-alive-ms pos-int?) (s/def ::subscription-interceptors ::spec/interceptors) (s/def ::init-context fn?) (s/def ::response-chan-fn fn?) (s/def ::values-chan-fn fn?) (s/def ::send-buffer-or-n ::spec/buffer-or-n)
15175
; Copyright (c) 2017-present <NAME>, Inc. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns com.walmartlabs.lacinia.immutant.subscriptions "Support for GraphQL subscriptions using Jetty WebSockets, following the design of the Apollo client and server." {:added "0.3.0"} (:require [com.walmartlabs.lacinia :as lacinia] [com.walmartlabs.lacinia.util :as util] [com.walmartlabs.lacinia.internal-utils :refer [cond-let to-message]] [clojure.core.async :as async :refer [chan put! close! go-loop <! >! alt! thread]] [cheshire.core :as cheshire] [io.pedestal.interceptor :refer [interceptor]] [io.pedestal.interceptor.chain :as chain] ;; Removed jetty websockets ;;[io.pedestal.http.jetty.websockets :as ws] [com.walmartlabs.lacinia.immutant.websockets :as ws] [io.pedestal.log :as log] [com.walmartlabs.lacinia.parser :as parser] [com.walmartlabs.lacinia.validator :as validator] [com.walmartlabs.lacinia.executor :as executor] [com.walmartlabs.lacinia.constants :as constants] [com.walmartlabs.lacinia.resolve :as resolve] [clojure.string :as str] [clojure.spec.alpha :as s] [com.walmartlabs.lacinia.immutant.spec :as spec] [immutant.web.async :as imm-async]) ;; (:import ;; (org.eclipse.jetty.websocket.api UpgradeResponse)) ) (when (-> *clojure-version* :minor (< 9)) (require '[clojure.future :refer [pos-int?]])) (defn ^:private xform-channel [input-ch output-ch xf] (go-loop [] (if-some [input (<! input-ch)] (let [output (xf input)] (when (imm-async/send! output-ch output) ;;(>! output-ch output) (recur))) ;;(close! output-ch) (imm-async/close output-ch)))) (defn ^:private response-encode-loop "Takes values from the input channel, encodes them as a JSON string, and puts them into the output-ch." [input-ch output-ch] (xform-channel input-ch output-ch cheshire/generate-string)) (defn ^:private ws-parse-loop "Parses text messages sent from the client into Clojure data with keyword keys, which is passed along to the output-ch. Parse errors are converted into connection_error messages sent to the response-ch." [input-ch output-ch response-data-ch] (go-loop [] (when-some [text (<! input-ch)] (when-some [parsed (try (cheshire/parse-string text true) (catch Throwable t (log/debug :event ::malformed-text :message text) (>! response-data-ch {:type :connection_error :payload (util/as-error-map t)})))] (>! output-ch parsed)) (recur)))) (defn ^:private execute-query-interceptors "Executes the interceptor chain for an operation, and returns a channel used to shutdown and cleanup the operation." [id payload response-data-ch cleanup-ch context] (let [shutdown-ch (chan) response-spy-ch (chan 1) request (assoc payload :id id :shutdown-ch shutdown-ch :response-data-ch response-spy-ch)] ;; When the spy channel is closed, we write the id ;; to the cleanup-ch; the containing CSP then removes the ;; shutdown-ch from its subs map. (go-loop [] (let [message (<! response-spy-ch)] (if (some? message) (do (>! response-data-ch message) (recur)) (>! cleanup-ch id)))) ;; Execute the chain, for side-effects. (chain/execute (update context :request merge request)) ;; Return a shutdown channel that the CSP can close to shutdown the subscription shutdown-ch)) (defn ^:private connection-loop "A loop started for each connection." [keep-alive-ms ws-data-ch response-data-ch context] (let [cleanup-ch (chan 1)] ;; Keep track of subscriptions by (client-supplied) unique id. ;; The value is a shutdown channel that, when closed, triggers ;; a cleanup of the subscription. (go-loop [connection-state {:subs {} :connection-params nil}] (alt! cleanup-ch ([id] (log/debug :event ::cleanup-ch :id id) (recur (update connection-state :subs dissoc id))) ;; TODO: Maybe only after connection_init? (async/timeout keep-alive-ms) (do (log/debug :event ::timeout) (>! response-data-ch {:type :ka}) (recur connection-state)) ws-data-ch ([data] (if (nil? data) ;; When the client closes the connection, any running subscriptions need to ;; shutdown and cleanup. (do (log/debug :event ::client-close) (run! close! (-> connection-state :subs vals))) ;; Otherwise it's a message from the client to be acted upon. (let [{:keys [id payload type]} data] (case type "connection_init" (when (>! response-data-ch {:type :connection_ack}) (recur (assoc connection-state :connection-params payload))) ;; TODO: Track state, don't allow start, etc. until after connection_init "start" (if (contains? (:subs connection-state) id) (do (log/debug :event ::ignoring-duplicate :id id) (recur connection-state)) (do (log/debug :event ::start :id id) (let [merged-context (assoc context :connection-params (:connection-params connection-state)) sub-shutdown-ch (execute-query-interceptors id payload response-data-ch cleanup-ch merged-context)] (recur (assoc-in connection-state [:subs id] sub-shutdown-ch))))) "stop" (do (log/debug :event ::stop :id id) (when-some [sub-shutdown-ch (get-in connection-state [:subs id])] (close! sub-shutdown-ch)) (recur connection-state)) "connection_terminate" (do (log/debug :event ::terminate) (run! close! (-> connection-state :subs vals)) ;; This shuts down the connection entirely. (close! response-data-ch)) ;; Not recognized! (let [response (cond-> {:type :error :payload {:message "Unrecognized message type." :type type}} id (assoc :id id))] (log/debug :event ::unknown-type :type type) (>! response-data-ch response) (recur connection-state)))))))))) ;; We try to keep the interceptors here and in the main namespace as similar as possible, but ;; there are distinctions that can't be readily smoothed over. (defn ^:private fix-up-message [s] (when-not (str/blank? s) (-> s str/trim (str/replace #"\s*\.+$" "") str/capitalize))) (defn ^:private ex-data-seq "Uses the exception root causes to build a sequence of non-nil ex-data from each exception in the exception stack." [t] (loop [stack [] current ^Throwable t] (let [stack' (conj stack current) next-t (.getCause current)] ;; Sometime .getCause returns this, sometimes nil, when the end of the stack is ;; reached. (if (or (nil? next-t) (= current next-t)) (keep ex-data stack') (recur stack' next-t))))) (defn ^:private construct-exception-payload [^Throwable t] (cond-let :let [errors (->> t ex-data-seq (keep ::errors) first) parse-errors (->> errors (keep :message) distinct) locations (->> (mapcat :locations errors) (remove nil?) distinct seq)] (seq parse-errors) (cond-> {:message (str "Failed to parse GraphQL query. " (->> parse-errors (keep fix-up-message) (str/join "; ")) ".")} locations (assoc :locations locations)) ;; Apollo spec only has room for one error, so just use the first (seq errors) (cond-> (first errors) locations (assoc :locations locations)) :else ;; Strip off the exception added by Pedestal and convert ;; the message into an error map (cond-> {:message (to-message t)} locations (assoc :locations locations)))) (def exception-handler-interceptor "An interceptor that implements the :error callback, to send an \"error\" message to the client." (interceptor {:name ::exception-handler :error (fn [context ^Throwable t] (let [{:keys [id response-data-ch]} (:request context) ;; Strip off the wrapper exception added by Pedestal payload (construct-exception-payload (.getCause t))] (put! response-data-ch {:type :error :id id :payload payload}) (close! response-data-ch)))})) (def send-operation-response-interceptor "Interceptor responsible for the :response key of the context (set when a request is either a query or mutation, but not a subscription). The :response data is packaged up as the payload of a \"data\" message to the client, followed by a \"complete\" message." (interceptor {:name ::send-operation-response :leave (fn [context] (when-let [response (:response context)] (let [{:keys [id response-data-ch]} (:request context)] (put! response-data-ch {:type :data :id id :payload response}) (put! response-data-ch {:type :complete :id id}) (close! response-data-ch))) context)})) (defn query-parser-interceptor "An interceptor that parses the query and places a prepared and validated query into the :parsed-lacinia-query key of the request. `compiled-schema` may be the actual compiled schema, or a no-arguments function that returns the compiled schema." [compiled-schema] (interceptor {:name ::query-parser :enter (fn [context] (let [{operation-name :operationName :keys [query variables]} (:request context) actual-schema (if (map? compiled-schema) compiled-schema (compiled-schema)) parsed-query (try (parser/parse-query actual-schema query operation-name) (catch Throwable t (throw (ex-info (to-message t) {::errors (-> t ex-data :errors)} t)))) prepared (parser/prepare-with-query-variables parsed-query variables) errors (validator/validate actual-schema prepared {})] (if (seq errors) (throw (ex-info "Query validation errors." {::errors errors})) (assoc-in context [:request :parsed-lacinia-query] prepared))))})) (defn inject-app-context-interceptor "Adds a :lacinia-app-context key to the request, used when executing the query. It is not uncommon to replace this interceptor with one that constructs the application context dynamically." [app-context] (interceptor {:name ::inject-app-context :enter (fn [context] (assoc-in context [:request :lacinia-app-context] app-context))})) (defn ^:private execute-operation [context parsed-query] (let [ch (chan 1)] (-> context (get-in [:request :lacinia-app-context]) (assoc ::lacinia/connection-params (:connection-params context) constants/parsed-query-key parsed-query) executor/execute-query (resolve/on-deliver! (fn [response] (put! ch (assoc context :response response)))) ;; Don't execute the query in a limited go block thread thread) ch)) (defn ^:private execute-subscription [context parsed-query] (let [{:keys [::values-chan-fn request]} context source-stream-ch (values-chan-fn) {:keys [id shutdown-ch response-data-ch]} request source-stream (fn [value] (if (some? value) (put! source-stream-ch value) (close! source-stream-ch))) app-context (-> context (get-in [:request :lacinia-app-context]) (assoc ::lacinia/connection-params (:connection-params context) constants/parsed-query-key parsed-query)) cleanup-fn (executor/invoke-streamer app-context source-stream)] (go-loop [] (alt! ;; TODO: A timeout? ;; This channel is closed when the client sends a "stop" message shutdown-ch (do (close! response-data-ch) (cleanup-fn)) source-stream-ch ([value] (if (some? value) (do (-> app-context (assoc ::executor/resolved-value value) executor/execute-query (resolve/on-deliver! (fn [response] (put! response-data-ch {:type :data :id id :payload response}))) ;; Don't execute the query in a limited go block thread thread) (recur)) (do ;; The streamer has signalled that it has exhausted the subscription. (>! response-data-ch {:type :complete :id id}) (close! response-data-ch) (cleanup-fn)))))) ;; Return the context unchanged, it will unwind while the above process ;; does the real work. context)) (def execute-operation-interceptor "Executes a mutation or query operation and sets the :response key of the context, or executes a long-lived subscription operation." (interceptor {:name ::execute-operation :enter (fn [context] (let [request (:request context) parsed-query (:parsed-lacinia-query request) operation-type (-> parsed-query parser/operations :type)] (if (= operation-type :subscription) (execute-subscription context parsed-query) (execute-operation context parsed-query))))})) (defn default-subscription-interceptors "Processing of operation requests from the client is passed through interceptor pipeline. The context for the pipeline includes special keys for the necessary channels. The :request key is the payload sent from the client, along with additional keys: :response-data-ch : Channel to which Clojure data destined for the client should be written. : This should be closed when the subscription data is exhausted. :shutdown-ch : This channel will be closed if the client terminates the connection. For subscriptions, this ensures that the subscription is cleaned up. :id : The client-provided string that must be included in the response. For mutation and query operations, a :response key is added to the context, which triggers a response to the client. For subscription operations, it's a bit different; there's no immediate response, but a new CSP will work with the streamer defined by the subscription to send a sequence of \"data\" messages to the client. * ::exception-handler -- [[exception-handler-interceptor]] * ::send-operation-response -- [[send-operation-response-interceptor]] * ::query-parser -- [[query-parser-interceptor]] * ::inject-app-context -- [[inject-app-context-interceptor]] * ::execute-operation -- [[execute-operation-interceptor]] Returns a vector of interceptors." [compiled-schema app-context] [exception-handler-interceptor send-operation-response-interceptor (query-parser-interceptor compiled-schema) (inject-app-context-interceptor app-context) execute-operation-interceptor]) (defn listener-fn-factory "A factory for the function used to create a WS listener. This function is invoked for each new client connecting to the service. `compiled-schema` may be the actual compiled schema, or a no-arguments function that returns the compiled schema. Once a subscription is initiated, the flow is: streamer -> values channel -> resolver -> response channel -> send channel The default channels are all buffered and non-lossy, which means that a very active streamer may be able to saturate the web socket used to send responses to the client. By introducing lossiness or different buffers, the behavior can be tuned. Each new subscription from the same client will invoke a new streamer and create a corresponding values channel, but there is only one response channel per client. Options: :keep-alive-ms (default: 30000) : The interval at which keep alive messages are sent to the client. :app-context : The base application context provided to Lacinia when executing a query. :subscription-interceptors : A seq of interceptors for processing queries. The default is derived from [[default-subscription-interceptors]]. :init-context : A function returning the base context for the subscription-interceptors to operate on. The function takes the following arguments: - the minimal viable context for operation - the ServletUpgradeRequest that initiated this connection - the ServletUpgradeResponse to the upgrade request Defaults to returning the context unchanged. :response-chan-fn : A function that returns a new channel. Responses to be written to client are put into this channel. The default is a non-lossy channel with a buffer size of 10. :values-chan-fn : A function that returns a new channel. The channel conveys the values provided by the subscription's streamer. The values are executed as queries, then transformed into responses that are put into the response channel. The default is a non-lossy channel with a buffer size of 1. :send-buffer-or-n : Used to create the channel of text responses sent to the client. The default is 10 (a non-lossy channel)." [compiled-schema options] (let [{:keys [keep-alive-ms app-context init-context send-buffer-or-n response-chan-fn values-chan-fn] :or {keep-alive-ms 30000 send-buffer-or-n 10 response-chan-fn #(chan 10) values-chan-fn #(chan 1) init-context (fn [ctx & _args] ctx)}} options interceptors (or (:subscription-interceptors options) (default-subscription-interceptors compiled-schema app-context)) base-context (chain/enqueue {::chain/terminators [:response] ::values-chan-fn values-chan-fn} interceptors)] (log/debug :event ::configuring :keep-alive-ms keep-alive-ms) (fn [req] ;; [req resp _ws-map] ;; immutant doesnt support subprotocols?? but not required ;;(.setAcceptedSubProtocol ^UpgradeResponse resp "graphql-ws") (log/debug :event ::upgrade-requested) (let [response-data-ch (response-chan-fn) ; server data -> client ws-text-ch (chan 1) ; client text -> server ws-data-ch (chan 10) ; client text -> client data on-close (fn [_ _] (log/debug :event ::closed) (close! response-data-ch) (close! ws-data-ch)) ;;base-context' (init-context base-context req resp) base-context' (init-context base-context req) ;; on-connect (fn [_session send-ch] ;; (log/debug :event ::connected) ;; (response-encode-loop response-data-ch send-ch) ;; (ws-parse-loop ws-text-ch ws-data-ch response-data-ch) ;; (connection-loop keep-alive-ms ws-data-ch response-data-ch base-context')) on-connect (fn [_ send-ch] (log/debug :event ::connected) (response-encode-loop response-data-ch send-ch) (ws-parse-loop ws-text-ch ws-data-ch response-data-ch) (connection-loop keep-alive-ms ws-data-ch response-data-ch base-context'))] ;; (ws/make-ws-listener ;; {:on-connect (ws/start-ws-connection on-connect send-buffer-or-n) ;; :on-text #(put! ws-text-ch %) ;; :on-error #(log/error :event ::error :exception %) ;; :on-close on-close}) (ws/make-ws-listener {:on-open (ws/start-ws-connection on-connect send-buffer-or-n) :on-message #(put! ws-text-ch %) :on-error #(log/error :event ::error :exception %) :on-close on-close}))))) (s/fdef listener-fn-factory :args (s/cat :compiled-schema ::spec/compiled-schema :options (s/nilable ::listener-fn-factory-options))) (s/def ::listener-fn-factory-options (s/keys :opt-un [::keep-alive-ms ::spec/app-context ::subscription-interceptors ::init-context ::response-ch-fn ::values-chan-fn ::send-buffer-or-n])) (s/def ::keep-alive-ms pos-int?) (s/def ::subscription-interceptors ::spec/interceptors) (s/def ::init-context fn?) (s/def ::response-chan-fn fn?) (s/def ::values-chan-fn fn?) (s/def ::send-buffer-or-n ::spec/buffer-or-n)
true
; Copyright (c) 2017-present PI:NAME:<NAME>END_PI, Inc. ; ; Licensed under the Apache License, Version 2.0 (the "License") ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. (ns com.walmartlabs.lacinia.immutant.subscriptions "Support for GraphQL subscriptions using Jetty WebSockets, following the design of the Apollo client and server." {:added "0.3.0"} (:require [com.walmartlabs.lacinia :as lacinia] [com.walmartlabs.lacinia.util :as util] [com.walmartlabs.lacinia.internal-utils :refer [cond-let to-message]] [clojure.core.async :as async :refer [chan put! close! go-loop <! >! alt! thread]] [cheshire.core :as cheshire] [io.pedestal.interceptor :refer [interceptor]] [io.pedestal.interceptor.chain :as chain] ;; Removed jetty websockets ;;[io.pedestal.http.jetty.websockets :as ws] [com.walmartlabs.lacinia.immutant.websockets :as ws] [io.pedestal.log :as log] [com.walmartlabs.lacinia.parser :as parser] [com.walmartlabs.lacinia.validator :as validator] [com.walmartlabs.lacinia.executor :as executor] [com.walmartlabs.lacinia.constants :as constants] [com.walmartlabs.lacinia.resolve :as resolve] [clojure.string :as str] [clojure.spec.alpha :as s] [com.walmartlabs.lacinia.immutant.spec :as spec] [immutant.web.async :as imm-async]) ;; (:import ;; (org.eclipse.jetty.websocket.api UpgradeResponse)) ) (when (-> *clojure-version* :minor (< 9)) (require '[clojure.future :refer [pos-int?]])) (defn ^:private xform-channel [input-ch output-ch xf] (go-loop [] (if-some [input (<! input-ch)] (let [output (xf input)] (when (imm-async/send! output-ch output) ;;(>! output-ch output) (recur))) ;;(close! output-ch) (imm-async/close output-ch)))) (defn ^:private response-encode-loop "Takes values from the input channel, encodes them as a JSON string, and puts them into the output-ch." [input-ch output-ch] (xform-channel input-ch output-ch cheshire/generate-string)) (defn ^:private ws-parse-loop "Parses text messages sent from the client into Clojure data with keyword keys, which is passed along to the output-ch. Parse errors are converted into connection_error messages sent to the response-ch." [input-ch output-ch response-data-ch] (go-loop [] (when-some [text (<! input-ch)] (when-some [parsed (try (cheshire/parse-string text true) (catch Throwable t (log/debug :event ::malformed-text :message text) (>! response-data-ch {:type :connection_error :payload (util/as-error-map t)})))] (>! output-ch parsed)) (recur)))) (defn ^:private execute-query-interceptors "Executes the interceptor chain for an operation, and returns a channel used to shutdown and cleanup the operation." [id payload response-data-ch cleanup-ch context] (let [shutdown-ch (chan) response-spy-ch (chan 1) request (assoc payload :id id :shutdown-ch shutdown-ch :response-data-ch response-spy-ch)] ;; When the spy channel is closed, we write the id ;; to the cleanup-ch; the containing CSP then removes the ;; shutdown-ch from its subs map. (go-loop [] (let [message (<! response-spy-ch)] (if (some? message) (do (>! response-data-ch message) (recur)) (>! cleanup-ch id)))) ;; Execute the chain, for side-effects. (chain/execute (update context :request merge request)) ;; Return a shutdown channel that the CSP can close to shutdown the subscription shutdown-ch)) (defn ^:private connection-loop "A loop started for each connection." [keep-alive-ms ws-data-ch response-data-ch context] (let [cleanup-ch (chan 1)] ;; Keep track of subscriptions by (client-supplied) unique id. ;; The value is a shutdown channel that, when closed, triggers ;; a cleanup of the subscription. (go-loop [connection-state {:subs {} :connection-params nil}] (alt! cleanup-ch ([id] (log/debug :event ::cleanup-ch :id id) (recur (update connection-state :subs dissoc id))) ;; TODO: Maybe only after connection_init? (async/timeout keep-alive-ms) (do (log/debug :event ::timeout) (>! response-data-ch {:type :ka}) (recur connection-state)) ws-data-ch ([data] (if (nil? data) ;; When the client closes the connection, any running subscriptions need to ;; shutdown and cleanup. (do (log/debug :event ::client-close) (run! close! (-> connection-state :subs vals))) ;; Otherwise it's a message from the client to be acted upon. (let [{:keys [id payload type]} data] (case type "connection_init" (when (>! response-data-ch {:type :connection_ack}) (recur (assoc connection-state :connection-params payload))) ;; TODO: Track state, don't allow start, etc. until after connection_init "start" (if (contains? (:subs connection-state) id) (do (log/debug :event ::ignoring-duplicate :id id) (recur connection-state)) (do (log/debug :event ::start :id id) (let [merged-context (assoc context :connection-params (:connection-params connection-state)) sub-shutdown-ch (execute-query-interceptors id payload response-data-ch cleanup-ch merged-context)] (recur (assoc-in connection-state [:subs id] sub-shutdown-ch))))) "stop" (do (log/debug :event ::stop :id id) (when-some [sub-shutdown-ch (get-in connection-state [:subs id])] (close! sub-shutdown-ch)) (recur connection-state)) "connection_terminate" (do (log/debug :event ::terminate) (run! close! (-> connection-state :subs vals)) ;; This shuts down the connection entirely. (close! response-data-ch)) ;; Not recognized! (let [response (cond-> {:type :error :payload {:message "Unrecognized message type." :type type}} id (assoc :id id))] (log/debug :event ::unknown-type :type type) (>! response-data-ch response) (recur connection-state)))))))))) ;; We try to keep the interceptors here and in the main namespace as similar as possible, but ;; there are distinctions that can't be readily smoothed over. (defn ^:private fix-up-message [s] (when-not (str/blank? s) (-> s str/trim (str/replace #"\s*\.+$" "") str/capitalize))) (defn ^:private ex-data-seq "Uses the exception root causes to build a sequence of non-nil ex-data from each exception in the exception stack." [t] (loop [stack [] current ^Throwable t] (let [stack' (conj stack current) next-t (.getCause current)] ;; Sometime .getCause returns this, sometimes nil, when the end of the stack is ;; reached. (if (or (nil? next-t) (= current next-t)) (keep ex-data stack') (recur stack' next-t))))) (defn ^:private construct-exception-payload [^Throwable t] (cond-let :let [errors (->> t ex-data-seq (keep ::errors) first) parse-errors (->> errors (keep :message) distinct) locations (->> (mapcat :locations errors) (remove nil?) distinct seq)] (seq parse-errors) (cond-> {:message (str "Failed to parse GraphQL query. " (->> parse-errors (keep fix-up-message) (str/join "; ")) ".")} locations (assoc :locations locations)) ;; Apollo spec only has room for one error, so just use the first (seq errors) (cond-> (first errors) locations (assoc :locations locations)) :else ;; Strip off the exception added by Pedestal and convert ;; the message into an error map (cond-> {:message (to-message t)} locations (assoc :locations locations)))) (def exception-handler-interceptor "An interceptor that implements the :error callback, to send an \"error\" message to the client." (interceptor {:name ::exception-handler :error (fn [context ^Throwable t] (let [{:keys [id response-data-ch]} (:request context) ;; Strip off the wrapper exception added by Pedestal payload (construct-exception-payload (.getCause t))] (put! response-data-ch {:type :error :id id :payload payload}) (close! response-data-ch)))})) (def send-operation-response-interceptor "Interceptor responsible for the :response key of the context (set when a request is either a query or mutation, but not a subscription). The :response data is packaged up as the payload of a \"data\" message to the client, followed by a \"complete\" message." (interceptor {:name ::send-operation-response :leave (fn [context] (when-let [response (:response context)] (let [{:keys [id response-data-ch]} (:request context)] (put! response-data-ch {:type :data :id id :payload response}) (put! response-data-ch {:type :complete :id id}) (close! response-data-ch))) context)})) (defn query-parser-interceptor "An interceptor that parses the query and places a prepared and validated query into the :parsed-lacinia-query key of the request. `compiled-schema` may be the actual compiled schema, or a no-arguments function that returns the compiled schema." [compiled-schema] (interceptor {:name ::query-parser :enter (fn [context] (let [{operation-name :operationName :keys [query variables]} (:request context) actual-schema (if (map? compiled-schema) compiled-schema (compiled-schema)) parsed-query (try (parser/parse-query actual-schema query operation-name) (catch Throwable t (throw (ex-info (to-message t) {::errors (-> t ex-data :errors)} t)))) prepared (parser/prepare-with-query-variables parsed-query variables) errors (validator/validate actual-schema prepared {})] (if (seq errors) (throw (ex-info "Query validation errors." {::errors errors})) (assoc-in context [:request :parsed-lacinia-query] prepared))))})) (defn inject-app-context-interceptor "Adds a :lacinia-app-context key to the request, used when executing the query. It is not uncommon to replace this interceptor with one that constructs the application context dynamically." [app-context] (interceptor {:name ::inject-app-context :enter (fn [context] (assoc-in context [:request :lacinia-app-context] app-context))})) (defn ^:private execute-operation [context parsed-query] (let [ch (chan 1)] (-> context (get-in [:request :lacinia-app-context]) (assoc ::lacinia/connection-params (:connection-params context) constants/parsed-query-key parsed-query) executor/execute-query (resolve/on-deliver! (fn [response] (put! ch (assoc context :response response)))) ;; Don't execute the query in a limited go block thread thread) ch)) (defn ^:private execute-subscription [context parsed-query] (let [{:keys [::values-chan-fn request]} context source-stream-ch (values-chan-fn) {:keys [id shutdown-ch response-data-ch]} request source-stream (fn [value] (if (some? value) (put! source-stream-ch value) (close! source-stream-ch))) app-context (-> context (get-in [:request :lacinia-app-context]) (assoc ::lacinia/connection-params (:connection-params context) constants/parsed-query-key parsed-query)) cleanup-fn (executor/invoke-streamer app-context source-stream)] (go-loop [] (alt! ;; TODO: A timeout? ;; This channel is closed when the client sends a "stop" message shutdown-ch (do (close! response-data-ch) (cleanup-fn)) source-stream-ch ([value] (if (some? value) (do (-> app-context (assoc ::executor/resolved-value value) executor/execute-query (resolve/on-deliver! (fn [response] (put! response-data-ch {:type :data :id id :payload response}))) ;; Don't execute the query in a limited go block thread thread) (recur)) (do ;; The streamer has signalled that it has exhausted the subscription. (>! response-data-ch {:type :complete :id id}) (close! response-data-ch) (cleanup-fn)))))) ;; Return the context unchanged, it will unwind while the above process ;; does the real work. context)) (def execute-operation-interceptor "Executes a mutation or query operation and sets the :response key of the context, or executes a long-lived subscription operation." (interceptor {:name ::execute-operation :enter (fn [context] (let [request (:request context) parsed-query (:parsed-lacinia-query request) operation-type (-> parsed-query parser/operations :type)] (if (= operation-type :subscription) (execute-subscription context parsed-query) (execute-operation context parsed-query))))})) (defn default-subscription-interceptors "Processing of operation requests from the client is passed through interceptor pipeline. The context for the pipeline includes special keys for the necessary channels. The :request key is the payload sent from the client, along with additional keys: :response-data-ch : Channel to which Clojure data destined for the client should be written. : This should be closed when the subscription data is exhausted. :shutdown-ch : This channel will be closed if the client terminates the connection. For subscriptions, this ensures that the subscription is cleaned up. :id : The client-provided string that must be included in the response. For mutation and query operations, a :response key is added to the context, which triggers a response to the client. For subscription operations, it's a bit different; there's no immediate response, but a new CSP will work with the streamer defined by the subscription to send a sequence of \"data\" messages to the client. * ::exception-handler -- [[exception-handler-interceptor]] * ::send-operation-response -- [[send-operation-response-interceptor]] * ::query-parser -- [[query-parser-interceptor]] * ::inject-app-context -- [[inject-app-context-interceptor]] * ::execute-operation -- [[execute-operation-interceptor]] Returns a vector of interceptors." [compiled-schema app-context] [exception-handler-interceptor send-operation-response-interceptor (query-parser-interceptor compiled-schema) (inject-app-context-interceptor app-context) execute-operation-interceptor]) (defn listener-fn-factory "A factory for the function used to create a WS listener. This function is invoked for each new client connecting to the service. `compiled-schema` may be the actual compiled schema, or a no-arguments function that returns the compiled schema. Once a subscription is initiated, the flow is: streamer -> values channel -> resolver -> response channel -> send channel The default channels are all buffered and non-lossy, which means that a very active streamer may be able to saturate the web socket used to send responses to the client. By introducing lossiness or different buffers, the behavior can be tuned. Each new subscription from the same client will invoke a new streamer and create a corresponding values channel, but there is only one response channel per client. Options: :keep-alive-ms (default: 30000) : The interval at which keep alive messages are sent to the client. :app-context : The base application context provided to Lacinia when executing a query. :subscription-interceptors : A seq of interceptors for processing queries. The default is derived from [[default-subscription-interceptors]]. :init-context : A function returning the base context for the subscription-interceptors to operate on. The function takes the following arguments: - the minimal viable context for operation - the ServletUpgradeRequest that initiated this connection - the ServletUpgradeResponse to the upgrade request Defaults to returning the context unchanged. :response-chan-fn : A function that returns a new channel. Responses to be written to client are put into this channel. The default is a non-lossy channel with a buffer size of 10. :values-chan-fn : A function that returns a new channel. The channel conveys the values provided by the subscription's streamer. The values are executed as queries, then transformed into responses that are put into the response channel. The default is a non-lossy channel with a buffer size of 1. :send-buffer-or-n : Used to create the channel of text responses sent to the client. The default is 10 (a non-lossy channel)." [compiled-schema options] (let [{:keys [keep-alive-ms app-context init-context send-buffer-or-n response-chan-fn values-chan-fn] :or {keep-alive-ms 30000 send-buffer-or-n 10 response-chan-fn #(chan 10) values-chan-fn #(chan 1) init-context (fn [ctx & _args] ctx)}} options interceptors (or (:subscription-interceptors options) (default-subscription-interceptors compiled-schema app-context)) base-context (chain/enqueue {::chain/terminators [:response] ::values-chan-fn values-chan-fn} interceptors)] (log/debug :event ::configuring :keep-alive-ms keep-alive-ms) (fn [req] ;; [req resp _ws-map] ;; immutant doesnt support subprotocols?? but not required ;;(.setAcceptedSubProtocol ^UpgradeResponse resp "graphql-ws") (log/debug :event ::upgrade-requested) (let [response-data-ch (response-chan-fn) ; server data -> client ws-text-ch (chan 1) ; client text -> server ws-data-ch (chan 10) ; client text -> client data on-close (fn [_ _] (log/debug :event ::closed) (close! response-data-ch) (close! ws-data-ch)) ;;base-context' (init-context base-context req resp) base-context' (init-context base-context req) ;; on-connect (fn [_session send-ch] ;; (log/debug :event ::connected) ;; (response-encode-loop response-data-ch send-ch) ;; (ws-parse-loop ws-text-ch ws-data-ch response-data-ch) ;; (connection-loop keep-alive-ms ws-data-ch response-data-ch base-context')) on-connect (fn [_ send-ch] (log/debug :event ::connected) (response-encode-loop response-data-ch send-ch) (ws-parse-loop ws-text-ch ws-data-ch response-data-ch) (connection-loop keep-alive-ms ws-data-ch response-data-ch base-context'))] ;; (ws/make-ws-listener ;; {:on-connect (ws/start-ws-connection on-connect send-buffer-or-n) ;; :on-text #(put! ws-text-ch %) ;; :on-error #(log/error :event ::error :exception %) ;; :on-close on-close}) (ws/make-ws-listener {:on-open (ws/start-ws-connection on-connect send-buffer-or-n) :on-message #(put! ws-text-ch %) :on-error #(log/error :event ::error :exception %) :on-close on-close}))))) (s/fdef listener-fn-factory :args (s/cat :compiled-schema ::spec/compiled-schema :options (s/nilable ::listener-fn-factory-options))) (s/def ::listener-fn-factory-options (s/keys :opt-un [::keep-alive-ms ::spec/app-context ::subscription-interceptors ::init-context ::response-ch-fn ::values-chan-fn ::send-buffer-or-n])) (s/def ::keep-alive-ms pos-int?) (s/def ::subscription-interceptors ::spec/interceptors) (s/def ::init-context fn?) (s/def ::response-chan-fn fn?) (s/def ::values-chan-fn fn?) (s/def ::send-buffer-or-n ::spec/buffer-or-n)
[ { "context": "])\n\n(defn deep-merge\n {:license \"Copyright © 2019 James Reeves\n\nDistributed under the Eclipse Public License eit", "end": 99, "score": 0.9998618364334106, "start": 87, "tag": "NAME", "value": "James Reeves" }, { "context": "\n :password :env/clojars_password\n ", "end": 6769, "score": 0.8780090808868408, "start": 6766, "tag": "PASSWORD", "value": "env" }, { "context": " :password :env/clojars_password\n :sign-relea", "end": 6786, "score": 0.9092157483100891, "start": 6770, "tag": "PASSWORD", "value": "clojars_password" } ]
project.clj
rksm/clj-runtime-completion
83
(require '[clojure.string :as string]) (defn deep-merge {:license "Copyright © 2019 James Reeves Distributed under the Eclipse Public License either version 1.0 or (at your option) any later version."} ([]) ([a] a) ([a b] (when (or a b) (letfn [(merge-entry [m e] (let [k (key e) v' (val e)] (if (contains? m k) (assoc m k (let [v (get m k)] (cond (and (map? v) (map? v')) (deep-merge v v') (and (coll? v) (coll? v')) (into (empty v) (distinct (into v v'))) true (do (assert (not (and v v'))) (or v v'))))) (assoc m k v'))))] (->> b seq (reduce merge-entry (or a {})))))) ([a b & more] (reduce deep-merge (or a {}) (cons b more)))) (def repo-mapping (atom {})) (def git-hosts (atom #{})) (defn process-dep-entry! [{:keys [jars-atom subprojects-atom]} [k {:keys [mvn/version sha exclusions git/url local/root]}]] {:pre [@jars-atom @subprojects-atom]} (when url (let [{:keys [host path]} (-> url java.net.URI. bean) [gh-org gh-project] (-> path (string/replace #"^/" "") (string/replace #"\.git$" "") (string/split #"/"))] (swap! repo-mapping assoc k {:coordinates (symbol (str gh-org "/" gh-project))}) (swap! git-hosts conj host))) (if-not root [k (or version sha) :exclusions (->> exclusions (mapv (fn [e] (-> e str (string/replace #"\$.*" "") symbol))))] (do (if (string/ends-with? root ".jar") (swap! jars-atom conj root) (let [f (java.io.File. root "deps.edn")] (assert (-> f .exists) (str "Expected " root " to denote an existing deps.edn file")) (swap! subprojects-atom conj (.getCanonicalPath f)))) nil))) (defn prefix [filename item] (-> filename java.io.File. .getParent (java.io.File. item) .getCanonicalPath)) (defn add-jars [m jars-atom sub? deps-edn-filename] {:pre [@jars-atom]} (cond-> m (seq @jars-atom) (update :resource-paths (fn [v] (cond->> @jars-atom true (into (or v [])) sub? (mapv (partial prefix deps-edn-filename))))))) (declare add-subprojects) (defn process-profiles [aliases deps-edn-filename root-deps-edn-filename] (->> (for [[k {:keys [override-deps extra-deps extra-paths replace-paths]}] aliases :let [jars-atom (atom #{}) subprojects-atom (atom #{} :validator (fn [v] (not (contains? v deps-edn-filename)))) sub? (not= deps-edn-filename root-deps-edn-filename) sot (cond->> [[] extra-paths replace-paths] true (reduce into) true distinct sub? (map (partial prefix deps-edn-filename)) true vec)]] [k (-> {:dependencies (->> [override-deps extra-deps] (keep (partial map (partial process-dep-entry! {:jars-atom jars-atom :subprojects-atom subprojects-atom}))) (apply concat) distinct vec) :source-paths sot :test-paths sot} (add-jars jars-atom sub? deps-edn-filename) (add-subprojects subprojects-atom deps-edn-filename))]) (into {}))) (defn parse-deps-edn [deps-edn-filename root-deps-edn-filename] (let [{:keys [aliases deps paths]} (clojure.edn/read-string (slurp deps-edn-filename)) profiles (process-profiles aliases deps-edn-filename root-deps-edn-filename) jars-atom (atom #{}) subprojects-atom (atom #{} :validator (fn [v] (not (contains? v root-deps-edn-filename)))) dependencies (->> deps (keep (partial process-dep-entry! {:jars-atom jars-atom :subprojects-atom subprojects-atom})) (vec)) sub? (not= deps-edn-filename root-deps-edn-filename) sot (cond->> paths sub? (mapv (partial prefix deps-edn-filename)))] (-> {:dependencies dependencies :profiles (clojure.set/rename-keys profiles {:test-common :test}) :source-paths sot :test-paths sot :resource-paths (cond->> @jars-atom sub? (map (partial prefix deps-edn-filename)) true vec)} (add-subprojects subprojects-atom root-deps-edn-filename)))) (defn add-subprojects [m subprojects-atom root-deps-edn-filename] (->> @subprojects-atom (reduce (fn [v subproject] (deep-merge v (parse-deps-edn subproject root-deps-edn-filename))) m))) (let [f (-> "deps.edn" java.io.File. .getCanonicalPath) {:keys [profiles dependencies resource-paths source-paths]} (parse-deps-edn f f)] (defproject org.rksm/suitable "0.4.1" :source-paths ~source-paths :resource-paths ~resource-paths :dependencies ~dependencies :profiles ~profiles :plugins [[reifyhealth/lein-git-down "0.4.0"]] :middleware [lein-git-down.plugin/inject-properties] :git-down ~(deref repo-mapping) :repositories ~(->> @git-hosts (map (fn [r] (let [n (-> r (string/split #"\.") first) u (str "git://" r)] [[(str "public-" n) {:url u}] [(str "private-" n) {:url u :protocol :ssh}]]))) (apply concat) vec) :deploy-repositories [["clojars" {:url "https://clojars.org/repo" :username :env/clojars_username :password :env/clojars_password :sign-releases false}]]))
12792
(require '[clojure.string :as string]) (defn deep-merge {:license "Copyright © 2019 <NAME> Distributed under the Eclipse Public License either version 1.0 or (at your option) any later version."} ([]) ([a] a) ([a b] (when (or a b) (letfn [(merge-entry [m e] (let [k (key e) v' (val e)] (if (contains? m k) (assoc m k (let [v (get m k)] (cond (and (map? v) (map? v')) (deep-merge v v') (and (coll? v) (coll? v')) (into (empty v) (distinct (into v v'))) true (do (assert (not (and v v'))) (or v v'))))) (assoc m k v'))))] (->> b seq (reduce merge-entry (or a {})))))) ([a b & more] (reduce deep-merge (or a {}) (cons b more)))) (def repo-mapping (atom {})) (def git-hosts (atom #{})) (defn process-dep-entry! [{:keys [jars-atom subprojects-atom]} [k {:keys [mvn/version sha exclusions git/url local/root]}]] {:pre [@jars-atom @subprojects-atom]} (when url (let [{:keys [host path]} (-> url java.net.URI. bean) [gh-org gh-project] (-> path (string/replace #"^/" "") (string/replace #"\.git$" "") (string/split #"/"))] (swap! repo-mapping assoc k {:coordinates (symbol (str gh-org "/" gh-project))}) (swap! git-hosts conj host))) (if-not root [k (or version sha) :exclusions (->> exclusions (mapv (fn [e] (-> e str (string/replace #"\$.*" "") symbol))))] (do (if (string/ends-with? root ".jar") (swap! jars-atom conj root) (let [f (java.io.File. root "deps.edn")] (assert (-> f .exists) (str "Expected " root " to denote an existing deps.edn file")) (swap! subprojects-atom conj (.getCanonicalPath f)))) nil))) (defn prefix [filename item] (-> filename java.io.File. .getParent (java.io.File. item) .getCanonicalPath)) (defn add-jars [m jars-atom sub? deps-edn-filename] {:pre [@jars-atom]} (cond-> m (seq @jars-atom) (update :resource-paths (fn [v] (cond->> @jars-atom true (into (or v [])) sub? (mapv (partial prefix deps-edn-filename))))))) (declare add-subprojects) (defn process-profiles [aliases deps-edn-filename root-deps-edn-filename] (->> (for [[k {:keys [override-deps extra-deps extra-paths replace-paths]}] aliases :let [jars-atom (atom #{}) subprojects-atom (atom #{} :validator (fn [v] (not (contains? v deps-edn-filename)))) sub? (not= deps-edn-filename root-deps-edn-filename) sot (cond->> [[] extra-paths replace-paths] true (reduce into) true distinct sub? (map (partial prefix deps-edn-filename)) true vec)]] [k (-> {:dependencies (->> [override-deps extra-deps] (keep (partial map (partial process-dep-entry! {:jars-atom jars-atom :subprojects-atom subprojects-atom}))) (apply concat) distinct vec) :source-paths sot :test-paths sot} (add-jars jars-atom sub? deps-edn-filename) (add-subprojects subprojects-atom deps-edn-filename))]) (into {}))) (defn parse-deps-edn [deps-edn-filename root-deps-edn-filename] (let [{:keys [aliases deps paths]} (clojure.edn/read-string (slurp deps-edn-filename)) profiles (process-profiles aliases deps-edn-filename root-deps-edn-filename) jars-atom (atom #{}) subprojects-atom (atom #{} :validator (fn [v] (not (contains? v root-deps-edn-filename)))) dependencies (->> deps (keep (partial process-dep-entry! {:jars-atom jars-atom :subprojects-atom subprojects-atom})) (vec)) sub? (not= deps-edn-filename root-deps-edn-filename) sot (cond->> paths sub? (mapv (partial prefix deps-edn-filename)))] (-> {:dependencies dependencies :profiles (clojure.set/rename-keys profiles {:test-common :test}) :source-paths sot :test-paths sot :resource-paths (cond->> @jars-atom sub? (map (partial prefix deps-edn-filename)) true vec)} (add-subprojects subprojects-atom root-deps-edn-filename)))) (defn add-subprojects [m subprojects-atom root-deps-edn-filename] (->> @subprojects-atom (reduce (fn [v subproject] (deep-merge v (parse-deps-edn subproject root-deps-edn-filename))) m))) (let [f (-> "deps.edn" java.io.File. .getCanonicalPath) {:keys [profiles dependencies resource-paths source-paths]} (parse-deps-edn f f)] (defproject org.rksm/suitable "0.4.1" :source-paths ~source-paths :resource-paths ~resource-paths :dependencies ~dependencies :profiles ~profiles :plugins [[reifyhealth/lein-git-down "0.4.0"]] :middleware [lein-git-down.plugin/inject-properties] :git-down ~(deref repo-mapping) :repositories ~(->> @git-hosts (map (fn [r] (let [n (-> r (string/split #"\.") first) u (str "git://" r)] [[(str "public-" n) {:url u}] [(str "private-" n) {:url u :protocol :ssh}]]))) (apply concat) vec) :deploy-repositories [["clojars" {:url "https://clojars.org/repo" :username :env/clojars_username :password :<PASSWORD>/<PASSWORD> :sign-releases false}]]))
true
(require '[clojure.string :as string]) (defn deep-merge {:license "Copyright © 2019 PI:NAME:<NAME>END_PI Distributed under the Eclipse Public License either version 1.0 or (at your option) any later version."} ([]) ([a] a) ([a b] (when (or a b) (letfn [(merge-entry [m e] (let [k (key e) v' (val e)] (if (contains? m k) (assoc m k (let [v (get m k)] (cond (and (map? v) (map? v')) (deep-merge v v') (and (coll? v) (coll? v')) (into (empty v) (distinct (into v v'))) true (do (assert (not (and v v'))) (or v v'))))) (assoc m k v'))))] (->> b seq (reduce merge-entry (or a {})))))) ([a b & more] (reduce deep-merge (or a {}) (cons b more)))) (def repo-mapping (atom {})) (def git-hosts (atom #{})) (defn process-dep-entry! [{:keys [jars-atom subprojects-atom]} [k {:keys [mvn/version sha exclusions git/url local/root]}]] {:pre [@jars-atom @subprojects-atom]} (when url (let [{:keys [host path]} (-> url java.net.URI. bean) [gh-org gh-project] (-> path (string/replace #"^/" "") (string/replace #"\.git$" "") (string/split #"/"))] (swap! repo-mapping assoc k {:coordinates (symbol (str gh-org "/" gh-project))}) (swap! git-hosts conj host))) (if-not root [k (or version sha) :exclusions (->> exclusions (mapv (fn [e] (-> e str (string/replace #"\$.*" "") symbol))))] (do (if (string/ends-with? root ".jar") (swap! jars-atom conj root) (let [f (java.io.File. root "deps.edn")] (assert (-> f .exists) (str "Expected " root " to denote an existing deps.edn file")) (swap! subprojects-atom conj (.getCanonicalPath f)))) nil))) (defn prefix [filename item] (-> filename java.io.File. .getParent (java.io.File. item) .getCanonicalPath)) (defn add-jars [m jars-atom sub? deps-edn-filename] {:pre [@jars-atom]} (cond-> m (seq @jars-atom) (update :resource-paths (fn [v] (cond->> @jars-atom true (into (or v [])) sub? (mapv (partial prefix deps-edn-filename))))))) (declare add-subprojects) (defn process-profiles [aliases deps-edn-filename root-deps-edn-filename] (->> (for [[k {:keys [override-deps extra-deps extra-paths replace-paths]}] aliases :let [jars-atom (atom #{}) subprojects-atom (atom #{} :validator (fn [v] (not (contains? v deps-edn-filename)))) sub? (not= deps-edn-filename root-deps-edn-filename) sot (cond->> [[] extra-paths replace-paths] true (reduce into) true distinct sub? (map (partial prefix deps-edn-filename)) true vec)]] [k (-> {:dependencies (->> [override-deps extra-deps] (keep (partial map (partial process-dep-entry! {:jars-atom jars-atom :subprojects-atom subprojects-atom}))) (apply concat) distinct vec) :source-paths sot :test-paths sot} (add-jars jars-atom sub? deps-edn-filename) (add-subprojects subprojects-atom deps-edn-filename))]) (into {}))) (defn parse-deps-edn [deps-edn-filename root-deps-edn-filename] (let [{:keys [aliases deps paths]} (clojure.edn/read-string (slurp deps-edn-filename)) profiles (process-profiles aliases deps-edn-filename root-deps-edn-filename) jars-atom (atom #{}) subprojects-atom (atom #{} :validator (fn [v] (not (contains? v root-deps-edn-filename)))) dependencies (->> deps (keep (partial process-dep-entry! {:jars-atom jars-atom :subprojects-atom subprojects-atom})) (vec)) sub? (not= deps-edn-filename root-deps-edn-filename) sot (cond->> paths sub? (mapv (partial prefix deps-edn-filename)))] (-> {:dependencies dependencies :profiles (clojure.set/rename-keys profiles {:test-common :test}) :source-paths sot :test-paths sot :resource-paths (cond->> @jars-atom sub? (map (partial prefix deps-edn-filename)) true vec)} (add-subprojects subprojects-atom root-deps-edn-filename)))) (defn add-subprojects [m subprojects-atom root-deps-edn-filename] (->> @subprojects-atom (reduce (fn [v subproject] (deep-merge v (parse-deps-edn subproject root-deps-edn-filename))) m))) (let [f (-> "deps.edn" java.io.File. .getCanonicalPath) {:keys [profiles dependencies resource-paths source-paths]} (parse-deps-edn f f)] (defproject org.rksm/suitable "0.4.1" :source-paths ~source-paths :resource-paths ~resource-paths :dependencies ~dependencies :profiles ~profiles :plugins [[reifyhealth/lein-git-down "0.4.0"]] :middleware [lein-git-down.plugin/inject-properties] :git-down ~(deref repo-mapping) :repositories ~(->> @git-hosts (map (fn [r] (let [n (-> r (string/split #"\.") first) u (str "git://" r)] [[(str "public-" n) {:url u}] [(str "private-" n) {:url u :protocol :ssh}]]))) (apply concat) vec) :deploy-repositories [["clojars" {:url "https://clojars.org/repo" :username :env/clojars_username :password :PI:PASSWORD:<PASSWORD>END_PI/PI:PASSWORD:<PASSWORD>END_PI :sign-releases false}]]))
[ { "context": "lution for 125. Infix Calculator\n\n\n;;; Your friend Joe is always whining about Lisps using the prefix no", "end": 61, "score": 0.9993175268173218, "start": 58, "tag": "NAME", "value": "Joe" } ]
solutions/easy/135.clj
realead/my4clojure
0
;;;; Solution for 125. Infix Calculator ;;; Your friend Joe is always whining about Lisps using the prefix notation for math. Show him how you could easily write a function that does math using the infix notation. Is your favorite language that flexible, Joe? Write a function that accepts a variable length mathematical expression consisting of numbers and the operations +, -, *, and /. Assume a simple calculator that does not do precedence and instead just calculates left to right. (defn my-infix [a op b & others] (let [acc (op a b)] (if (empty? others) acc (recur acc (first others) (second others) (drop 2 others)) ) ) ) (def __ my-infix) ; tests: (= 7 (__ 2 + 5)) (= 42 (__ 38 + 48 - 2 / 2)) (= 8 (__ 10 / 2 - 1 * 2)) (= 72 (__ 20 / 2 + 2 + 4 + 8 - 6 - 10 * 9))
122362
;;;; Solution for 125. Infix Calculator ;;; Your friend <NAME> is always whining about Lisps using the prefix notation for math. Show him how you could easily write a function that does math using the infix notation. Is your favorite language that flexible, Joe? Write a function that accepts a variable length mathematical expression consisting of numbers and the operations +, -, *, and /. Assume a simple calculator that does not do precedence and instead just calculates left to right. (defn my-infix [a op b & others] (let [acc (op a b)] (if (empty? others) acc (recur acc (first others) (second others) (drop 2 others)) ) ) ) (def __ my-infix) ; tests: (= 7 (__ 2 + 5)) (= 42 (__ 38 + 48 - 2 / 2)) (= 8 (__ 10 / 2 - 1 * 2)) (= 72 (__ 20 / 2 + 2 + 4 + 8 - 6 - 10 * 9))
true
;;;; Solution for 125. Infix Calculator ;;; Your friend PI:NAME:<NAME>END_PI is always whining about Lisps using the prefix notation for math. Show him how you could easily write a function that does math using the infix notation. Is your favorite language that flexible, Joe? Write a function that accepts a variable length mathematical expression consisting of numbers and the operations +, -, *, and /. Assume a simple calculator that does not do precedence and instead just calculates left to right. (defn my-infix [a op b & others] (let [acc (op a b)] (if (empty? others) acc (recur acc (first others) (second others) (drop 2 others)) ) ) ) (def __ my-infix) ; tests: (= 7 (__ 2 + 5)) (= 42 (__ 38 + 48 - 2 / 2)) (= 8 (__ 10 / 2 - 1 * 2)) (= 72 (__ 20 / 2 + 2 + 4 + 8 - 6 - 10 * 9))
[ { "context": "isode :NEWHOPE)\n {:id 1000\n :name \"Luke\"\n :home_planet \"Tatooine\"\n :appea", "end": 270, "score": 0.9996055960655212, "start": 266, "tag": "NAME", "value": "Luke" }, { "context": "MPIRE\" \"JEDI\"]}\n {:id 2000\n :name \"Lando Calrissian\"\n :home_planet \"Socorro\"\n :appear", "end": 405, "score": 0.9998371005058289, "start": 389, "tag": "NAME", "value": "Lando Calrissian" } ]
examples/starwars/src/starwars/resolver/human.clj
eunmin/duct-lacinia
37
(ns starwars.resolver.human (:require [integrant.core :as ig])) (defmethod ig/init-key :starwars.resolver.human/get-hero [_ _] (fn [context arguments value] (let [{:keys [episode]} arguments] (if (= episode :NEWHOPE) {:id 1000 :name "Luke" :home_planet "Tatooine" :appears_in ["NEWHOPE" "EMPIRE" "JEDI"]} {:id 2000 :name "Lando Calrissian" :home_planet "Socorro" :appears_in ["EMPIRE" "JEDI"]}))))
52970
(ns starwars.resolver.human (:require [integrant.core :as ig])) (defmethod ig/init-key :starwars.resolver.human/get-hero [_ _] (fn [context arguments value] (let [{:keys [episode]} arguments] (if (= episode :NEWHOPE) {:id 1000 :name "<NAME>" :home_planet "Tatooine" :appears_in ["NEWHOPE" "EMPIRE" "JEDI"]} {:id 2000 :name "<NAME>" :home_planet "Socorro" :appears_in ["EMPIRE" "JEDI"]}))))
true
(ns starwars.resolver.human (:require [integrant.core :as ig])) (defmethod ig/init-key :starwars.resolver.human/get-hero [_ _] (fn [context arguments value] (let [{:keys [episode]} arguments] (if (= episode :NEWHOPE) {:id 1000 :name "PI:NAME:<NAME>END_PI" :home_planet "Tatooine" :appears_in ["NEWHOPE" "EMPIRE" "JEDI"]} {:id 2000 :name "PI:NAME:<NAME>END_PI" :home_planet "Socorro" :appears_in ["EMPIRE" "JEDI"]}))))
[ { "context": "l License Management.\"\n :url \"https://github.com/brianide/lein-license\"\n :license {:name \"MIT License\"\n ", "end": 150, "score": 0.9983143210411072, "start": 142, "tag": "USERNAME", "value": "brianide" }, { "context": "://opensource.org/licenses/MIT\"\n :key \"mit\"\n :year 2015}\n :dependencies [^:sourc", "end": 273, "score": 0.9847833514213562, "start": 270, "tag": "KEY", "value": "mit" } ]
project.clj
brianide/lein-license
0
(defproject org.clojars.brianide/lein-license "0.1.10-SNAPSHOT" :description "Project-Level License Management." :url "https://github.com/brianide/lein-license" :license {:name "MIT License" :url "https://opensource.org/licenses/MIT" :key "mit" :year 2015} :dependencies [^:source-dep [rewrite-clj "0.6.1" :exclusions [org.clojure/clojure]] ^:source-dep [cheshire "5.8.0" :exclusions [org.clojure/clojure]]] :eval-in-leiningen true :pedantic? :abort)
95368
(defproject org.clojars.brianide/lein-license "0.1.10-SNAPSHOT" :description "Project-Level License Management." :url "https://github.com/brianide/lein-license" :license {:name "MIT License" :url "https://opensource.org/licenses/MIT" :key "<KEY>" :year 2015} :dependencies [^:source-dep [rewrite-clj "0.6.1" :exclusions [org.clojure/clojure]] ^:source-dep [cheshire "5.8.0" :exclusions [org.clojure/clojure]]] :eval-in-leiningen true :pedantic? :abort)
true
(defproject org.clojars.brianide/lein-license "0.1.10-SNAPSHOT" :description "Project-Level License Management." :url "https://github.com/brianide/lein-license" :license {:name "MIT License" :url "https://opensource.org/licenses/MIT" :key "PI:KEY:<KEY>END_PI" :year 2015} :dependencies [^:source-dep [rewrite-clj "0.6.1" :exclusions [org.clojure/clojure]] ^:source-dep [cheshire "5.8.0" :exclusions [org.clojure/clojure]]] :eval-in-leiningen true :pedantic? :abort)
[ { "context": "ne-id])))))))\n\n(defsc PersonForm [this {:keys [:db/id ::phone-numbers]}]\n {:query [:db/id ::pers", "end": 6378, "score": 0.6015798449516296, "start": 6376, "tag": "KEY", "value": "id" } ]
src/book/book/forms/form_state_demo_2.cljs
d4hines/fulcro
0
(ns book.forms.form-state-demo-2 (:require [devcards.core] [fulcro.ui.elements :as ele] [fulcro.server :as server] [fulcro.client.mutations :as m :refer [defmutation]] [fulcro.ui.bootstrap3 :as bs] [fulcro.client.primitives :as prim :refer [defsc]] [fulcro.client.dom :as dom] [fulcro.ui.form-state :as fs] [clojure.string :as str] [cljs.spec.alpha :as s] [fulcro.client.data-fetch :as df])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Server Code ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; a simple query for any person, that will return valid-looking data (server/defquery-entity :person/by-id (value [env id params] {:db/id id ::person-name (str "User " id) ::person-age 56 ::phone-numbers [{:db/id 1 ::phone-number "555-111-1212" ::phone-type :work} {:db/id 2 ::phone-number "555-333-4444" ::phone-type :home}]})) (defonce id (atom 1000)) (defn next-id [] (swap! id inc)) ; Server submission...just prints delta for demo, and remaps tempids (forms with tempids are always considered dirty) (server/defmutation submit-person [params] (action [env] (js/console.log "Server received form submission with content: ") (cljs.pprint/pprint params) (let [ids (map (fn [[k v]] (second k)) (:diff params)) remaps (into {} (keep (fn [v] (when (prim/tempid? v) [v (next-id)])) ids))] {:tempids remaps}))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Client Code ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def ::person-name (s/and string? #(seq (str/trim %)))) (s/def ::person-age #(s/int-in-range? 1 120 %)) (defn render-field [component field renderer] (let [form (prim/props component) entity-ident (prim/get-ident component form) id (str (first entity-ident) "-" (second entity-ident)) is-dirty? (fs/dirty? form field) clean? (not is-dirty?) validity (fs/get-spec-validity form field) is-invalid? (= :invalid validity) value (get form field "")] (renderer {:dirty? is-dirty? :ident entity-ident :id id :clean? clean? :validity validity :invalid? is-invalid? :value value}))) (def integer-fields #{::person-age}) (defn input-with-label "A non-library helper function, written by you to help lay out your form." ([component field field-label validation-string input-element] (render-field component field (fn [{:keys [invalid? id dirty?]}] (bs/labeled-input {:error (when invalid? validation-string) :id id :warning (when dirty? "(unsaved)") :input-generator input-element} field-label)))) ([component field field-label validation-string] (render-field component field (fn [{:keys [invalid? id dirty? value invalid ident]}] (bs/labeled-input {:value value :id id :error (when invalid? validation-string) :warning (when dirty? "(unsaved)") :onBlur #(prim/transact! component `[(fs/mark-complete! {:entity-ident ~ident :field ~field}) :root/person]) :onChange (if (integer-fields field) #(m/set-integer! component field :event %) #(m/set-string! component field :event %))} field-label))))) (s/def ::phone-number #(re-matches #"\(?[0-9]{3}[-.)]? *[0-9]{3}-?[0-9]{4}" %)) (defsc PhoneForm [this {:keys [::phone-type ui/dropdown] :as props}] {:query [:db/id ::phone-number ::phone-type {:ui/dropdown (prim/get-query bs/Dropdown)} fs/form-config-join] :form-fields #{::phone-number ::phone-type} :ident [:phone/by-id :db/id]} (dom/div #js {:className "form"} (input-with-label this ::phone-number "Phone:" "10-digit phone number is required.") (input-with-label this ::phone-type "Type:" "" (fn [attrs] (bs/ui-dropdown dropdown :value phone-type :onSelect (fn [v] (m/set-value! this ::phone-type v) (prim/transact! this `[(fs/mark-complete! {:field ::phone-type}) :root/person]))))))) (def ui-phone-form (prim/factory PhoneForm {:keyfn :db/id})) (defn add-phone-dropdown* "Add a phone type dropdown to a phone entity" [state-map phone-id default-type] (let [dropdown-id (random-uuid) dropdown (bs/dropdown dropdown-id "Type" [(bs/dropdown-item :work "Work") (bs/dropdown-item :home "Home")])] (-> state-map (prim/merge-component bs/Dropdown dropdown) ; we're being a bit wasteful here and adding a new dropdown to state every time (bs/set-dropdown-item-active* dropdown-id default-type) (assoc-in [:phone/by-id phone-id :ui/dropdown] (bs/dropdown-ident dropdown-id))))) (defn add-phone* "Add the given phone info to a person." [state-map phone-id person-id type number] (let [phone-ident [:phone/by-id phone-id] new-phone-entity {:db/id phone-id ::phone-type type ::phone-number number}] (-> state-map (update-in [:person/by-id person-id ::phone-numbers] (fnil conj []) phone-ident) (assoc-in phone-ident new-phone-entity) (add-phone-dropdown* phone-id type)))) (defmutation add-phone "Mutation: Add a phone number to a person, and initialize it as a working form." [{:keys [person-id]}] (action [{:keys [state]}] (let [phone-id (prim/tempid)] (swap! state (fn [s] (-> s (add-phone* phone-id person-id :home "") (fs/add-form-config* PhoneForm [:phone/by-id phone-id]))))))) (defsc PersonForm [this {:keys [:db/id ::phone-numbers]}] {:query [:db/id ::person-name ::person-age {::phone-numbers (prim/get-query PhoneForm)} fs/form-config-join] :form-fields #{::person-name ::person-age ::phone-numbers} ; ::phone-numbers here becomes a subform because it is a join in the query. :ident [:person/by-id :db/id]} (dom/div #js {:className "form"} (input-with-label this ::person-name "Name:" "Name is required.") (input-with-label this ::person-age "Age:" "Age must be between 1 and 120") (dom/h4 #js {} "Phone numbers:") (when (seq phone-numbers) (map ui-phone-form phone-numbers)) (bs/button {:onClick #(prim/transact! this `[(add-phone {:person-id ~id})])} (bs/glyphicon {} :plus)))) (def ui-person-form (prim/factory PersonForm {:keyfn :db/id})) (defn add-person* "Add a person with the given details to the state database." [state-map id name age] (let [person-ident [:person/by-id id] person {:db/id id ::person-name name ::person-age age}] (assoc-in state-map person-ident person))) (defmutation edit-new-person [_] (action [{:keys [state]}] (let [person-id (prim/tempid) person-ident [:person/by-id person-id] phone-id (prim/tempid)] (swap! state (fn [s] (-> s (add-person* person-id "" 0) (add-phone* phone-id person-id :home "") (assoc :root/person person-ident) ; join it into the UI as the person to edit (fs/add-form-config* PersonForm [:person/by-id person-id]))))))) (defn add-dropdowns* [state-map person-id] (let [phone-number-idents (get-in state-map [:person/by-id person-id ::phone-numbers])] (reduce (fn [s phone-ident] (let [phone-id (second phone-ident) phone-type (get-in s [:phone/by-id phone-id ::phone-type])] (add-phone-dropdown* s phone-id phone-type))) state-map phone-number-idents))) (defmutation edit-existing-person "Turn an existing person with phone numbers into an editable form with phone subforms." [{:keys [person-id]}] (action [{:keys [state]}] (swap! state (fn [s] (-> s (assoc :root/person [:person/by-id person-id]) (fs/add-form-config* PersonForm [:person/by-id person-id]) ; will not re-add config to entities that were present (fs/entity->pristine* [:person/by-id person-id]) ; in case we're re-loading it, make sure the pristine copy it up-to-date (fs/mark-complete* [:person/by-id person-id]) ; it just came from server, so all fields should be valid (add-dropdowns* person-id)))))) ; each phone number needs a dropdown (defmutation submit-person [{:keys [id]}] (action [{:keys [state]}] (swap! state fs/entity->pristine* [:person/by-id id])) (remote [env] true)) (defsc Root [this {:keys [root/person]}] {:query [{:root/person (prim/get-query PersonForm)}] :initial-state (fn [params] {})} (ele/ui-iframe {:frameBorder 0 :width 800 :height 700} (dom/div #js {} (dom/link #js {:rel "stylesheet" :href "bootstrap-3.3.7/css/bootstrap.min.css"}) (bs/button {:onClick #(df/load this [:person/by-id 21] PersonForm {:target [:root/person] :marker false :post-mutation `edit-existing-person :post-mutation-params {:person-id 21}})} "Simulate Edit (existing) Person from Server") (bs/button {:onClick #(prim/transact! this `[(edit-new-person {})])} "Simulate New Person Creation") (when (::person-name person) (ui-person-form person)) (dom/div nil (bs/button {:onClick #(prim/transact! this `[(fs/reset-form! {:form-ident [:person/by-id ~(:db/id person)]})]) :disabled (not (fs/dirty? person))} "Reset") (bs/button {:onClick #(prim/transact! this `[(submit-person {:id ~(:db/id person) :diff ~(fs/dirty-fields person false)})]) :disabled (or (fs/invalid-spec? person) (not (fs/dirty? person)))} "Submit")))))
120177
(ns book.forms.form-state-demo-2 (:require [devcards.core] [fulcro.ui.elements :as ele] [fulcro.server :as server] [fulcro.client.mutations :as m :refer [defmutation]] [fulcro.ui.bootstrap3 :as bs] [fulcro.client.primitives :as prim :refer [defsc]] [fulcro.client.dom :as dom] [fulcro.ui.form-state :as fs] [clojure.string :as str] [cljs.spec.alpha :as s] [fulcro.client.data-fetch :as df])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Server Code ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; a simple query for any person, that will return valid-looking data (server/defquery-entity :person/by-id (value [env id params] {:db/id id ::person-name (str "User " id) ::person-age 56 ::phone-numbers [{:db/id 1 ::phone-number "555-111-1212" ::phone-type :work} {:db/id 2 ::phone-number "555-333-4444" ::phone-type :home}]})) (defonce id (atom 1000)) (defn next-id [] (swap! id inc)) ; Server submission...just prints delta for demo, and remaps tempids (forms with tempids are always considered dirty) (server/defmutation submit-person [params] (action [env] (js/console.log "Server received form submission with content: ") (cljs.pprint/pprint params) (let [ids (map (fn [[k v]] (second k)) (:diff params)) remaps (into {} (keep (fn [v] (when (prim/tempid? v) [v (next-id)])) ids))] {:tempids remaps}))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Client Code ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def ::person-name (s/and string? #(seq (str/trim %)))) (s/def ::person-age #(s/int-in-range? 1 120 %)) (defn render-field [component field renderer] (let [form (prim/props component) entity-ident (prim/get-ident component form) id (str (first entity-ident) "-" (second entity-ident)) is-dirty? (fs/dirty? form field) clean? (not is-dirty?) validity (fs/get-spec-validity form field) is-invalid? (= :invalid validity) value (get form field "")] (renderer {:dirty? is-dirty? :ident entity-ident :id id :clean? clean? :validity validity :invalid? is-invalid? :value value}))) (def integer-fields #{::person-age}) (defn input-with-label "A non-library helper function, written by you to help lay out your form." ([component field field-label validation-string input-element] (render-field component field (fn [{:keys [invalid? id dirty?]}] (bs/labeled-input {:error (when invalid? validation-string) :id id :warning (when dirty? "(unsaved)") :input-generator input-element} field-label)))) ([component field field-label validation-string] (render-field component field (fn [{:keys [invalid? id dirty? value invalid ident]}] (bs/labeled-input {:value value :id id :error (when invalid? validation-string) :warning (when dirty? "(unsaved)") :onBlur #(prim/transact! component `[(fs/mark-complete! {:entity-ident ~ident :field ~field}) :root/person]) :onChange (if (integer-fields field) #(m/set-integer! component field :event %) #(m/set-string! component field :event %))} field-label))))) (s/def ::phone-number #(re-matches #"\(?[0-9]{3}[-.)]? *[0-9]{3}-?[0-9]{4}" %)) (defsc PhoneForm [this {:keys [::phone-type ui/dropdown] :as props}] {:query [:db/id ::phone-number ::phone-type {:ui/dropdown (prim/get-query bs/Dropdown)} fs/form-config-join] :form-fields #{::phone-number ::phone-type} :ident [:phone/by-id :db/id]} (dom/div #js {:className "form"} (input-with-label this ::phone-number "Phone:" "10-digit phone number is required.") (input-with-label this ::phone-type "Type:" "" (fn [attrs] (bs/ui-dropdown dropdown :value phone-type :onSelect (fn [v] (m/set-value! this ::phone-type v) (prim/transact! this `[(fs/mark-complete! {:field ::phone-type}) :root/person]))))))) (def ui-phone-form (prim/factory PhoneForm {:keyfn :db/id})) (defn add-phone-dropdown* "Add a phone type dropdown to a phone entity" [state-map phone-id default-type] (let [dropdown-id (random-uuid) dropdown (bs/dropdown dropdown-id "Type" [(bs/dropdown-item :work "Work") (bs/dropdown-item :home "Home")])] (-> state-map (prim/merge-component bs/Dropdown dropdown) ; we're being a bit wasteful here and adding a new dropdown to state every time (bs/set-dropdown-item-active* dropdown-id default-type) (assoc-in [:phone/by-id phone-id :ui/dropdown] (bs/dropdown-ident dropdown-id))))) (defn add-phone* "Add the given phone info to a person." [state-map phone-id person-id type number] (let [phone-ident [:phone/by-id phone-id] new-phone-entity {:db/id phone-id ::phone-type type ::phone-number number}] (-> state-map (update-in [:person/by-id person-id ::phone-numbers] (fnil conj []) phone-ident) (assoc-in phone-ident new-phone-entity) (add-phone-dropdown* phone-id type)))) (defmutation add-phone "Mutation: Add a phone number to a person, and initialize it as a working form." [{:keys [person-id]}] (action [{:keys [state]}] (let [phone-id (prim/tempid)] (swap! state (fn [s] (-> s (add-phone* phone-id person-id :home "") (fs/add-form-config* PhoneForm [:phone/by-id phone-id]))))))) (defsc PersonForm [this {:keys [:db/<KEY> ::phone-numbers]}] {:query [:db/id ::person-name ::person-age {::phone-numbers (prim/get-query PhoneForm)} fs/form-config-join] :form-fields #{::person-name ::person-age ::phone-numbers} ; ::phone-numbers here becomes a subform because it is a join in the query. :ident [:person/by-id :db/id]} (dom/div #js {:className "form"} (input-with-label this ::person-name "Name:" "Name is required.") (input-with-label this ::person-age "Age:" "Age must be between 1 and 120") (dom/h4 #js {} "Phone numbers:") (when (seq phone-numbers) (map ui-phone-form phone-numbers)) (bs/button {:onClick #(prim/transact! this `[(add-phone {:person-id ~id})])} (bs/glyphicon {} :plus)))) (def ui-person-form (prim/factory PersonForm {:keyfn :db/id})) (defn add-person* "Add a person with the given details to the state database." [state-map id name age] (let [person-ident [:person/by-id id] person {:db/id id ::person-name name ::person-age age}] (assoc-in state-map person-ident person))) (defmutation edit-new-person [_] (action [{:keys [state]}] (let [person-id (prim/tempid) person-ident [:person/by-id person-id] phone-id (prim/tempid)] (swap! state (fn [s] (-> s (add-person* person-id "" 0) (add-phone* phone-id person-id :home "") (assoc :root/person person-ident) ; join it into the UI as the person to edit (fs/add-form-config* PersonForm [:person/by-id person-id]))))))) (defn add-dropdowns* [state-map person-id] (let [phone-number-idents (get-in state-map [:person/by-id person-id ::phone-numbers])] (reduce (fn [s phone-ident] (let [phone-id (second phone-ident) phone-type (get-in s [:phone/by-id phone-id ::phone-type])] (add-phone-dropdown* s phone-id phone-type))) state-map phone-number-idents))) (defmutation edit-existing-person "Turn an existing person with phone numbers into an editable form with phone subforms." [{:keys [person-id]}] (action [{:keys [state]}] (swap! state (fn [s] (-> s (assoc :root/person [:person/by-id person-id]) (fs/add-form-config* PersonForm [:person/by-id person-id]) ; will not re-add config to entities that were present (fs/entity->pristine* [:person/by-id person-id]) ; in case we're re-loading it, make sure the pristine copy it up-to-date (fs/mark-complete* [:person/by-id person-id]) ; it just came from server, so all fields should be valid (add-dropdowns* person-id)))))) ; each phone number needs a dropdown (defmutation submit-person [{:keys [id]}] (action [{:keys [state]}] (swap! state fs/entity->pristine* [:person/by-id id])) (remote [env] true)) (defsc Root [this {:keys [root/person]}] {:query [{:root/person (prim/get-query PersonForm)}] :initial-state (fn [params] {})} (ele/ui-iframe {:frameBorder 0 :width 800 :height 700} (dom/div #js {} (dom/link #js {:rel "stylesheet" :href "bootstrap-3.3.7/css/bootstrap.min.css"}) (bs/button {:onClick #(df/load this [:person/by-id 21] PersonForm {:target [:root/person] :marker false :post-mutation `edit-existing-person :post-mutation-params {:person-id 21}})} "Simulate Edit (existing) Person from Server") (bs/button {:onClick #(prim/transact! this `[(edit-new-person {})])} "Simulate New Person Creation") (when (::person-name person) (ui-person-form person)) (dom/div nil (bs/button {:onClick #(prim/transact! this `[(fs/reset-form! {:form-ident [:person/by-id ~(:db/id person)]})]) :disabled (not (fs/dirty? person))} "Reset") (bs/button {:onClick #(prim/transact! this `[(submit-person {:id ~(:db/id person) :diff ~(fs/dirty-fields person false)})]) :disabled (or (fs/invalid-spec? person) (not (fs/dirty? person)))} "Submit")))))
true
(ns book.forms.form-state-demo-2 (:require [devcards.core] [fulcro.ui.elements :as ele] [fulcro.server :as server] [fulcro.client.mutations :as m :refer [defmutation]] [fulcro.ui.bootstrap3 :as bs] [fulcro.client.primitives :as prim :refer [defsc]] [fulcro.client.dom :as dom] [fulcro.ui.form-state :as fs] [clojure.string :as str] [cljs.spec.alpha :as s] [fulcro.client.data-fetch :as df])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Server Code ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; a simple query for any person, that will return valid-looking data (server/defquery-entity :person/by-id (value [env id params] {:db/id id ::person-name (str "User " id) ::person-age 56 ::phone-numbers [{:db/id 1 ::phone-number "555-111-1212" ::phone-type :work} {:db/id 2 ::phone-number "555-333-4444" ::phone-type :home}]})) (defonce id (atom 1000)) (defn next-id [] (swap! id inc)) ; Server submission...just prints delta for demo, and remaps tempids (forms with tempids are always considered dirty) (server/defmutation submit-person [params] (action [env] (js/console.log "Server received form submission with content: ") (cljs.pprint/pprint params) (let [ids (map (fn [[k v]] (second k)) (:diff params)) remaps (into {} (keep (fn [v] (when (prim/tempid? v) [v (next-id)])) ids))] {:tempids remaps}))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Client Code ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (s/def ::person-name (s/and string? #(seq (str/trim %)))) (s/def ::person-age #(s/int-in-range? 1 120 %)) (defn render-field [component field renderer] (let [form (prim/props component) entity-ident (prim/get-ident component form) id (str (first entity-ident) "-" (second entity-ident)) is-dirty? (fs/dirty? form field) clean? (not is-dirty?) validity (fs/get-spec-validity form field) is-invalid? (= :invalid validity) value (get form field "")] (renderer {:dirty? is-dirty? :ident entity-ident :id id :clean? clean? :validity validity :invalid? is-invalid? :value value}))) (def integer-fields #{::person-age}) (defn input-with-label "A non-library helper function, written by you to help lay out your form." ([component field field-label validation-string input-element] (render-field component field (fn [{:keys [invalid? id dirty?]}] (bs/labeled-input {:error (when invalid? validation-string) :id id :warning (when dirty? "(unsaved)") :input-generator input-element} field-label)))) ([component field field-label validation-string] (render-field component field (fn [{:keys [invalid? id dirty? value invalid ident]}] (bs/labeled-input {:value value :id id :error (when invalid? validation-string) :warning (when dirty? "(unsaved)") :onBlur #(prim/transact! component `[(fs/mark-complete! {:entity-ident ~ident :field ~field}) :root/person]) :onChange (if (integer-fields field) #(m/set-integer! component field :event %) #(m/set-string! component field :event %))} field-label))))) (s/def ::phone-number #(re-matches #"\(?[0-9]{3}[-.)]? *[0-9]{3}-?[0-9]{4}" %)) (defsc PhoneForm [this {:keys [::phone-type ui/dropdown] :as props}] {:query [:db/id ::phone-number ::phone-type {:ui/dropdown (prim/get-query bs/Dropdown)} fs/form-config-join] :form-fields #{::phone-number ::phone-type} :ident [:phone/by-id :db/id]} (dom/div #js {:className "form"} (input-with-label this ::phone-number "Phone:" "10-digit phone number is required.") (input-with-label this ::phone-type "Type:" "" (fn [attrs] (bs/ui-dropdown dropdown :value phone-type :onSelect (fn [v] (m/set-value! this ::phone-type v) (prim/transact! this `[(fs/mark-complete! {:field ::phone-type}) :root/person]))))))) (def ui-phone-form (prim/factory PhoneForm {:keyfn :db/id})) (defn add-phone-dropdown* "Add a phone type dropdown to a phone entity" [state-map phone-id default-type] (let [dropdown-id (random-uuid) dropdown (bs/dropdown dropdown-id "Type" [(bs/dropdown-item :work "Work") (bs/dropdown-item :home "Home")])] (-> state-map (prim/merge-component bs/Dropdown dropdown) ; we're being a bit wasteful here and adding a new dropdown to state every time (bs/set-dropdown-item-active* dropdown-id default-type) (assoc-in [:phone/by-id phone-id :ui/dropdown] (bs/dropdown-ident dropdown-id))))) (defn add-phone* "Add the given phone info to a person." [state-map phone-id person-id type number] (let [phone-ident [:phone/by-id phone-id] new-phone-entity {:db/id phone-id ::phone-type type ::phone-number number}] (-> state-map (update-in [:person/by-id person-id ::phone-numbers] (fnil conj []) phone-ident) (assoc-in phone-ident new-phone-entity) (add-phone-dropdown* phone-id type)))) (defmutation add-phone "Mutation: Add a phone number to a person, and initialize it as a working form." [{:keys [person-id]}] (action [{:keys [state]}] (let [phone-id (prim/tempid)] (swap! state (fn [s] (-> s (add-phone* phone-id person-id :home "") (fs/add-form-config* PhoneForm [:phone/by-id phone-id]))))))) (defsc PersonForm [this {:keys [:db/PI:KEY:<KEY>END_PI ::phone-numbers]}] {:query [:db/id ::person-name ::person-age {::phone-numbers (prim/get-query PhoneForm)} fs/form-config-join] :form-fields #{::person-name ::person-age ::phone-numbers} ; ::phone-numbers here becomes a subform because it is a join in the query. :ident [:person/by-id :db/id]} (dom/div #js {:className "form"} (input-with-label this ::person-name "Name:" "Name is required.") (input-with-label this ::person-age "Age:" "Age must be between 1 and 120") (dom/h4 #js {} "Phone numbers:") (when (seq phone-numbers) (map ui-phone-form phone-numbers)) (bs/button {:onClick #(prim/transact! this `[(add-phone {:person-id ~id})])} (bs/glyphicon {} :plus)))) (def ui-person-form (prim/factory PersonForm {:keyfn :db/id})) (defn add-person* "Add a person with the given details to the state database." [state-map id name age] (let [person-ident [:person/by-id id] person {:db/id id ::person-name name ::person-age age}] (assoc-in state-map person-ident person))) (defmutation edit-new-person [_] (action [{:keys [state]}] (let [person-id (prim/tempid) person-ident [:person/by-id person-id] phone-id (prim/tempid)] (swap! state (fn [s] (-> s (add-person* person-id "" 0) (add-phone* phone-id person-id :home "") (assoc :root/person person-ident) ; join it into the UI as the person to edit (fs/add-form-config* PersonForm [:person/by-id person-id]))))))) (defn add-dropdowns* [state-map person-id] (let [phone-number-idents (get-in state-map [:person/by-id person-id ::phone-numbers])] (reduce (fn [s phone-ident] (let [phone-id (second phone-ident) phone-type (get-in s [:phone/by-id phone-id ::phone-type])] (add-phone-dropdown* s phone-id phone-type))) state-map phone-number-idents))) (defmutation edit-existing-person "Turn an existing person with phone numbers into an editable form with phone subforms." [{:keys [person-id]}] (action [{:keys [state]}] (swap! state (fn [s] (-> s (assoc :root/person [:person/by-id person-id]) (fs/add-form-config* PersonForm [:person/by-id person-id]) ; will not re-add config to entities that were present (fs/entity->pristine* [:person/by-id person-id]) ; in case we're re-loading it, make sure the pristine copy it up-to-date (fs/mark-complete* [:person/by-id person-id]) ; it just came from server, so all fields should be valid (add-dropdowns* person-id)))))) ; each phone number needs a dropdown (defmutation submit-person [{:keys [id]}] (action [{:keys [state]}] (swap! state fs/entity->pristine* [:person/by-id id])) (remote [env] true)) (defsc Root [this {:keys [root/person]}] {:query [{:root/person (prim/get-query PersonForm)}] :initial-state (fn [params] {})} (ele/ui-iframe {:frameBorder 0 :width 800 :height 700} (dom/div #js {} (dom/link #js {:rel "stylesheet" :href "bootstrap-3.3.7/css/bootstrap.min.css"}) (bs/button {:onClick #(df/load this [:person/by-id 21] PersonForm {:target [:root/person] :marker false :post-mutation `edit-existing-person :post-mutation-params {:person-id 21}})} "Simulate Edit (existing) Person from Server") (bs/button {:onClick #(prim/transact! this `[(edit-new-person {})])} "Simulate New Person Creation") (when (::person-name person) (ui-person-form person)) (dom/div nil (bs/button {:onClick #(prim/transact! this `[(fs/reset-form! {:form-ident [:person/by-id ~(:db/id person)]})]) :disabled (not (fs/dirty? person))} "Reset") (bs/button {:onClick #(prim/transact! this `[(submit-person {:id ~(:db/id person) :diff ~(fs/dirty-fields person false)})]) :disabled (or (fs/invalid-spec? person) (not (fs/dirty? person)))} "Submit")))))
[ { "context": "))\n ([file new-name cred]\n (let [key (str (UUID/randomUUID) \"/\" new-name)\n ;resized (resize file 640", "end": 1102, "score": 0.8212102055549622, "start": 1092, "tag": "KEY", "value": "randomUUID" } ]
src/where_was_that_photo_taken/helpers/filehelpers.clj
itmeze/where-was-that-photo-taken
0
(ns where-was-that-photo-taken.helpers.filehelpers (:require [clojure.java.io :as io] [aws.sdk.s3 :as s3] [noir.io :as noir-io]) (:import [java.io File ByteArrayOutputStream ByteArrayInputStream] (main.java JpegGeoTagReader) (java.util UUID) (java.net URLDecoder) (javax.imageio ImageIO))) (defn file-path [path & [filename]] (URLDecoder/decode (str path File/separator filename) "utf-8")) (def image-content-types ["image/jpeg" "image/pjpeg" "image/png" "image/svg+xml" "image/gif"]) (defn is-img [file] (some #(= (:content-type file) %) image-content-types)) (defn with-file [path] (io/file path)) (defn resize-to-byte-array [file] (let [ort-bi (ImageIO/read file) res-bi (ImageResizer/getScaledImage ort-bi (int 640)) out (ByteArrayOutputStream.)] (ImageIO/write res-bi "jpg" out) (ByteArrayInputStream. (.toByteArray out)))) (defn resize-and-upload-to-s3 ([file cred] (resize-and-upload-to-s3 file (.getName file) cred)) ([file new-name cred] (let [key (str (UUID/randomUUID) "/" new-name) ;resized (resize file 640 640) ;resized-stream (format/as-stream resized "jpg") ;resized-stream (resize-to-byte-array file) bucket "where-was-that-photo-taken"] (s3/put-object cred bucket key file {} (s3/grant :all-users :read)) (str "https://s3.amazonaws.com/" bucket "/" key)))) (defn geo-tag-file [file] (let [geo-tag-reader (new JpegGeoTagReader) geo-info (.readMetadata geo-tag-reader file)] {:latitude (.getLatitude geo-info) :longitude (.getLongitude geo-info)})) (defn geo-tag-path [path] (geo-tag-file (io/file path))) ;(defn resize-file-to-stream ; [file] ; (format/as-stream (resize-to-width file 480) "jpg")) ;(defn resize-file ; "returns file path of resized file" ; [file new-width] ; (let [resized (resize-to-width file new-width)] ; (format/as-file resized (.getAbsolutePath file)))) (defn upload-file [ifile to-folder] (noir-io/upload-file to-folder ifile))
27553
(ns where-was-that-photo-taken.helpers.filehelpers (:require [clojure.java.io :as io] [aws.sdk.s3 :as s3] [noir.io :as noir-io]) (:import [java.io File ByteArrayOutputStream ByteArrayInputStream] (main.java JpegGeoTagReader) (java.util UUID) (java.net URLDecoder) (javax.imageio ImageIO))) (defn file-path [path & [filename]] (URLDecoder/decode (str path File/separator filename) "utf-8")) (def image-content-types ["image/jpeg" "image/pjpeg" "image/png" "image/svg+xml" "image/gif"]) (defn is-img [file] (some #(= (:content-type file) %) image-content-types)) (defn with-file [path] (io/file path)) (defn resize-to-byte-array [file] (let [ort-bi (ImageIO/read file) res-bi (ImageResizer/getScaledImage ort-bi (int 640)) out (ByteArrayOutputStream.)] (ImageIO/write res-bi "jpg" out) (ByteArrayInputStream. (.toByteArray out)))) (defn resize-and-upload-to-s3 ([file cred] (resize-and-upload-to-s3 file (.getName file) cred)) ([file new-name cred] (let [key (str (UUID/<KEY>) "/" new-name) ;resized (resize file 640 640) ;resized-stream (format/as-stream resized "jpg") ;resized-stream (resize-to-byte-array file) bucket "where-was-that-photo-taken"] (s3/put-object cred bucket key file {} (s3/grant :all-users :read)) (str "https://s3.amazonaws.com/" bucket "/" key)))) (defn geo-tag-file [file] (let [geo-tag-reader (new JpegGeoTagReader) geo-info (.readMetadata geo-tag-reader file)] {:latitude (.getLatitude geo-info) :longitude (.getLongitude geo-info)})) (defn geo-tag-path [path] (geo-tag-file (io/file path))) ;(defn resize-file-to-stream ; [file] ; (format/as-stream (resize-to-width file 480) "jpg")) ;(defn resize-file ; "returns file path of resized file" ; [file new-width] ; (let [resized (resize-to-width file new-width)] ; (format/as-file resized (.getAbsolutePath file)))) (defn upload-file [ifile to-folder] (noir-io/upload-file to-folder ifile))
true
(ns where-was-that-photo-taken.helpers.filehelpers (:require [clojure.java.io :as io] [aws.sdk.s3 :as s3] [noir.io :as noir-io]) (:import [java.io File ByteArrayOutputStream ByteArrayInputStream] (main.java JpegGeoTagReader) (java.util UUID) (java.net URLDecoder) (javax.imageio ImageIO))) (defn file-path [path & [filename]] (URLDecoder/decode (str path File/separator filename) "utf-8")) (def image-content-types ["image/jpeg" "image/pjpeg" "image/png" "image/svg+xml" "image/gif"]) (defn is-img [file] (some #(= (:content-type file) %) image-content-types)) (defn with-file [path] (io/file path)) (defn resize-to-byte-array [file] (let [ort-bi (ImageIO/read file) res-bi (ImageResizer/getScaledImage ort-bi (int 640)) out (ByteArrayOutputStream.)] (ImageIO/write res-bi "jpg" out) (ByteArrayInputStream. (.toByteArray out)))) (defn resize-and-upload-to-s3 ([file cred] (resize-and-upload-to-s3 file (.getName file) cred)) ([file new-name cred] (let [key (str (UUID/PI:KEY:<KEY>END_PI) "/" new-name) ;resized (resize file 640 640) ;resized-stream (format/as-stream resized "jpg") ;resized-stream (resize-to-byte-array file) bucket "where-was-that-photo-taken"] (s3/put-object cred bucket key file {} (s3/grant :all-users :read)) (str "https://s3.amazonaws.com/" bucket "/" key)))) (defn geo-tag-file [file] (let [geo-tag-reader (new JpegGeoTagReader) geo-info (.readMetadata geo-tag-reader file)] {:latitude (.getLatitude geo-info) :longitude (.getLongitude geo-info)})) (defn geo-tag-path [path] (geo-tag-file (io/file path))) ;(defn resize-file-to-stream ; [file] ; (format/as-stream (resize-to-width file 480) "jpg")) ;(defn resize-file ; "returns file path of resized file" ; [file new-width] ; (let [resized (resize-to-width file new-width)] ; (format/as-file resized (.getAbsolutePath file)))) (defn upload-file [ifile to-folder] (noir-io/upload-file to-folder ifile))
[ { "context": " {:key :data}]\n [{:name \\\"Chris\\\"\n :data \\\"1\\\"}\n ", "end": 3750, "score": 0.9831365346908569, "start": 3745, "tag": "NAME", "value": "Chris" }, { "context": " :data \\\"1\\\"}\n {:name \\\"Bob\\\"\n :data \\\"100\\\"}])\n => [{", "end": 3821, "score": 0.9997454881668091, "start": 3818, "tag": "NAME", "value": "Bob" } ]
src/hara/function/task/bulk.clj
zcaudate/hara
309
(ns hara.function.task.bulk (:require [hara.print :as print] [hara.core.base.result :as result] [hara.string :as string] [hara.data.base.map :as map]) (:refer-clojure :exclude [format])) (defn bulk-items "processes each item given a input" {:added "3.0"} [task f inputs {:keys [print] :as params} lookup env args] (when (:item print) (clojure.core/print "\n") (print/print-subtitle (string/format "ITEMS (%s)" (count inputs)))) (cond (empty? inputs) [] :else (let [total (count inputs) index-len (let [digits (if (pos? total) (inc (long (Math/log10 total))) 1)] (+ 2 (* 2 digits))) input-len (->> inputs (map (comp count str)) (apply max) (+ 2)) display-fn (or (-> task :item :display) identity) display {:padding 1 :spacing 1 :columns [{:id :index :length index-len :color #{:blue} :align :right} {:id :input :length input-len} {:id :data :length 60 :color #{:white}} {:id :time :length 10 :color #{:bold}}]}] (if (:item print) (clojure.core/print "\n")) (mapv (fn [i input] (let [start (System/currentTimeMillis) [key result] (try (apply f input params lookup env args) (catch Exception e (let [end (System/currentTimeMillis)] [input (result/result {:status :error :time (- end start) :data :errored})]))) end (System/currentTimeMillis) result (assoc result :time (- end start)) {:keys [status data time]} result _ (if (:item print) (let [index (string/format "%s/%s" (inc i) total) item (if (= status :return) (display-fn data) result) time (string/format "%.2fs" (/ time 1000.0))] (print/print-row [index key item time] display)))] [key result])) (range (count inputs)) inputs)))) (defn bulk-warnings "outputs warnings that have been processed" {:added "3.0"} [{:keys [print] :as params} items] (let [warnings (filter #(-> % second :status (= :warn)) items)] (when (and (:result print) (seq warnings)) (clojure.core/print "\n") (print/print-subtitle (string/format "WARNINGS (%s)" (count warnings))) (clojure.core/print "\n") (print/print-column warnings :data #{:warn})) warnings)) (defn bulk-errors "outputs errors that have been processed" {:added "3.0"} [{:keys [print] :as params} items] (let [errors (filter #(-> % second :status #{:critical :error}) items)] (when (and (:result print) (seq errors)) (clojure.core/print "\n") (print/print-subtitle (string/format "ERRORS (%s)" (count errors))) (clojure.core/print "\n") (print/print-column errors :data #{:error})) errors)) (defn prepare-columns "prepares columns for printing (prepare-columns [{:key :name} {:key :data}] [{:name \"Chris\" :data \"1\"} {:name \"Bob\" :data \"100\"}]) => [{:key :name, :id :name, :length 7} {:key :data, :id :data, :length 5}]" {:added "3.0"} [columns outputs] (mapv (fn [{:keys [length key] :as column}] (let [id key length (cond (number? length) length :else (->> outputs (map key) (map (comp count str)) (apply max) (+ 2)))] (assoc column :id key :length length))) columns)) (defn bulk-results "outputs results that have been processed" {:added "3.0"} [task {:keys [print order-by] :as params} items] (let [ignore-fn (-> task :result :ignore) remove-fn (fn [[key {:keys [data status] :as result}]] (or (#{:error :warn :info :critical} status) (and ignore-fn (ignore-fn data)))) results (remove remove-fn items) _ (when (:result print) (clojure.core/print "\n") (print/print-subtitle (string/format "RESULTS (%s)" (count results))))] (cond (empty? results) [] :else (let [key-fns (-> task :result :keys) sort-by-fn (-> task :result :sort-by) outputs (mapv (fn [[key {:keys [id data] :as result}]] (->> key-fns (map (fn [[k f]] [k (f data)])) (into result))) results) outputs (if order-by (clojure.core/sort-by order-by outputs) outputs) columns (-> task :result :columns) display {:padding 1 :spacing 1 :columns (prepare-columns columns outputs)} row-keys (map :key columns)] (when (:result print) (clojure.core/print "\n") (print/print-header row-keys display) (mapv (fn [output] (let [row (mapv #(get output %) row-keys)] (print/print-row row display))) outputs)) outputs)))) (defn bulk-summary "outputs summary of processed results" {:added "3.0"} [task {:keys [print] :as params} items results warnings errors] (let [aggregate-fns (-> task :summary :aggregate) finalise-fn (-> task :summary :finalise) time (string/format "%.2fs" (/ (apply + (map (comp :time second) items)) 1000.0)) summary (merge {:errors (count errors) :warnings (count warnings) :items (count items) :results (count results)} (->> aggregate-fns (map/map-vals (fn [[sel acc init]] (reduce (fn [out v] (acc out (sel v))) init results))))) summary (if finalise-fn (finalise-fn summary items results) summary) display (->> summary (remove (comp zero? second)) (into {})) _ (when (:summary print) (clojure.core/print "\n") (print/print-subtitle (string/format "SUMMARY %s" (str (assoc display :time time)))) (println))] (assoc summary :time time))) (defn bulk-package "packages results for return" {:added "3.0"} [task {:keys [items warnings errors results summary] :as bundle} return package] (cond (= return :all) (bulk-package task bundle #{:items :warnings :errors :results :summary} package) (keyword? return) (first (vals (bulk-package task bundle #{return} package))) :else (let [items-fn (or (-> task :item :output) identity) results-fn (or (-> task :result :output) identity)] (reduce (fn [out kw] (cond (#{:summary :warnings :errors} kw) (assoc out kw (get bundle kw)) (= :items kw) (cond->> (get bundle kw) :then (map (fn [[key v]] [key (items-fn (:data v))])) (not= package :vector) (into {}) :then (assoc out :items)) (= :results kw) (cond->> (get bundle kw) :then (map (fn [v] [(:key v) (results-fn (:data v))])) (not= package :vector) (into {}) :then (assoc out :results)) :else out)) {} return)))) (defn bulk "process and output results for a group of inputs" {:added "3.0"} [task f inputs {:keys [print package title return] :as params} lookup env & args] (let [params (assoc params :bulk true) _ (when (and (or (:function print) (:item print) (:result print) (:summary print)) title) (print/print-title title)) items (bulk-items task f inputs params lookup env args) warnings (bulk-warnings params items) errors (bulk-errors params items) results (bulk-results task params items) summary (bulk-summary task params items results warnings errors)] (bulk-package task {:items items :warnings warnings :errors errors :results results :summary summary} (or return :results) package)))
3295
(ns hara.function.task.bulk (:require [hara.print :as print] [hara.core.base.result :as result] [hara.string :as string] [hara.data.base.map :as map]) (:refer-clojure :exclude [format])) (defn bulk-items "processes each item given a input" {:added "3.0"} [task f inputs {:keys [print] :as params} lookup env args] (when (:item print) (clojure.core/print "\n") (print/print-subtitle (string/format "ITEMS (%s)" (count inputs)))) (cond (empty? inputs) [] :else (let [total (count inputs) index-len (let [digits (if (pos? total) (inc (long (Math/log10 total))) 1)] (+ 2 (* 2 digits))) input-len (->> inputs (map (comp count str)) (apply max) (+ 2)) display-fn (or (-> task :item :display) identity) display {:padding 1 :spacing 1 :columns [{:id :index :length index-len :color #{:blue} :align :right} {:id :input :length input-len} {:id :data :length 60 :color #{:white}} {:id :time :length 10 :color #{:bold}}]}] (if (:item print) (clojure.core/print "\n")) (mapv (fn [i input] (let [start (System/currentTimeMillis) [key result] (try (apply f input params lookup env args) (catch Exception e (let [end (System/currentTimeMillis)] [input (result/result {:status :error :time (- end start) :data :errored})]))) end (System/currentTimeMillis) result (assoc result :time (- end start)) {:keys [status data time]} result _ (if (:item print) (let [index (string/format "%s/%s" (inc i) total) item (if (= status :return) (display-fn data) result) time (string/format "%.2fs" (/ time 1000.0))] (print/print-row [index key item time] display)))] [key result])) (range (count inputs)) inputs)))) (defn bulk-warnings "outputs warnings that have been processed" {:added "3.0"} [{:keys [print] :as params} items] (let [warnings (filter #(-> % second :status (= :warn)) items)] (when (and (:result print) (seq warnings)) (clojure.core/print "\n") (print/print-subtitle (string/format "WARNINGS (%s)" (count warnings))) (clojure.core/print "\n") (print/print-column warnings :data #{:warn})) warnings)) (defn bulk-errors "outputs errors that have been processed" {:added "3.0"} [{:keys [print] :as params} items] (let [errors (filter #(-> % second :status #{:critical :error}) items)] (when (and (:result print) (seq errors)) (clojure.core/print "\n") (print/print-subtitle (string/format "ERRORS (%s)" (count errors))) (clojure.core/print "\n") (print/print-column errors :data #{:error})) errors)) (defn prepare-columns "prepares columns for printing (prepare-columns [{:key :name} {:key :data}] [{:name \"<NAME>\" :data \"1\"} {:name \"<NAME>\" :data \"100\"}]) => [{:key :name, :id :name, :length 7} {:key :data, :id :data, :length 5}]" {:added "3.0"} [columns outputs] (mapv (fn [{:keys [length key] :as column}] (let [id key length (cond (number? length) length :else (->> outputs (map key) (map (comp count str)) (apply max) (+ 2)))] (assoc column :id key :length length))) columns)) (defn bulk-results "outputs results that have been processed" {:added "3.0"} [task {:keys [print order-by] :as params} items] (let [ignore-fn (-> task :result :ignore) remove-fn (fn [[key {:keys [data status] :as result}]] (or (#{:error :warn :info :critical} status) (and ignore-fn (ignore-fn data)))) results (remove remove-fn items) _ (when (:result print) (clojure.core/print "\n") (print/print-subtitle (string/format "RESULTS (%s)" (count results))))] (cond (empty? results) [] :else (let [key-fns (-> task :result :keys) sort-by-fn (-> task :result :sort-by) outputs (mapv (fn [[key {:keys [id data] :as result}]] (->> key-fns (map (fn [[k f]] [k (f data)])) (into result))) results) outputs (if order-by (clojure.core/sort-by order-by outputs) outputs) columns (-> task :result :columns) display {:padding 1 :spacing 1 :columns (prepare-columns columns outputs)} row-keys (map :key columns)] (when (:result print) (clojure.core/print "\n") (print/print-header row-keys display) (mapv (fn [output] (let [row (mapv #(get output %) row-keys)] (print/print-row row display))) outputs)) outputs)))) (defn bulk-summary "outputs summary of processed results" {:added "3.0"} [task {:keys [print] :as params} items results warnings errors] (let [aggregate-fns (-> task :summary :aggregate) finalise-fn (-> task :summary :finalise) time (string/format "%.2fs" (/ (apply + (map (comp :time second) items)) 1000.0)) summary (merge {:errors (count errors) :warnings (count warnings) :items (count items) :results (count results)} (->> aggregate-fns (map/map-vals (fn [[sel acc init]] (reduce (fn [out v] (acc out (sel v))) init results))))) summary (if finalise-fn (finalise-fn summary items results) summary) display (->> summary (remove (comp zero? second)) (into {})) _ (when (:summary print) (clojure.core/print "\n") (print/print-subtitle (string/format "SUMMARY %s" (str (assoc display :time time)))) (println))] (assoc summary :time time))) (defn bulk-package "packages results for return" {:added "3.0"} [task {:keys [items warnings errors results summary] :as bundle} return package] (cond (= return :all) (bulk-package task bundle #{:items :warnings :errors :results :summary} package) (keyword? return) (first (vals (bulk-package task bundle #{return} package))) :else (let [items-fn (or (-> task :item :output) identity) results-fn (or (-> task :result :output) identity)] (reduce (fn [out kw] (cond (#{:summary :warnings :errors} kw) (assoc out kw (get bundle kw)) (= :items kw) (cond->> (get bundle kw) :then (map (fn [[key v]] [key (items-fn (:data v))])) (not= package :vector) (into {}) :then (assoc out :items)) (= :results kw) (cond->> (get bundle kw) :then (map (fn [v] [(:key v) (results-fn (:data v))])) (not= package :vector) (into {}) :then (assoc out :results)) :else out)) {} return)))) (defn bulk "process and output results for a group of inputs" {:added "3.0"} [task f inputs {:keys [print package title return] :as params} lookup env & args] (let [params (assoc params :bulk true) _ (when (and (or (:function print) (:item print) (:result print) (:summary print)) title) (print/print-title title)) items (bulk-items task f inputs params lookup env args) warnings (bulk-warnings params items) errors (bulk-errors params items) results (bulk-results task params items) summary (bulk-summary task params items results warnings errors)] (bulk-package task {:items items :warnings warnings :errors errors :results results :summary summary} (or return :results) package)))
true
(ns hara.function.task.bulk (:require [hara.print :as print] [hara.core.base.result :as result] [hara.string :as string] [hara.data.base.map :as map]) (:refer-clojure :exclude [format])) (defn bulk-items "processes each item given a input" {:added "3.0"} [task f inputs {:keys [print] :as params} lookup env args] (when (:item print) (clojure.core/print "\n") (print/print-subtitle (string/format "ITEMS (%s)" (count inputs)))) (cond (empty? inputs) [] :else (let [total (count inputs) index-len (let [digits (if (pos? total) (inc (long (Math/log10 total))) 1)] (+ 2 (* 2 digits))) input-len (->> inputs (map (comp count str)) (apply max) (+ 2)) display-fn (or (-> task :item :display) identity) display {:padding 1 :spacing 1 :columns [{:id :index :length index-len :color #{:blue} :align :right} {:id :input :length input-len} {:id :data :length 60 :color #{:white}} {:id :time :length 10 :color #{:bold}}]}] (if (:item print) (clojure.core/print "\n")) (mapv (fn [i input] (let [start (System/currentTimeMillis) [key result] (try (apply f input params lookup env args) (catch Exception e (let [end (System/currentTimeMillis)] [input (result/result {:status :error :time (- end start) :data :errored})]))) end (System/currentTimeMillis) result (assoc result :time (- end start)) {:keys [status data time]} result _ (if (:item print) (let [index (string/format "%s/%s" (inc i) total) item (if (= status :return) (display-fn data) result) time (string/format "%.2fs" (/ time 1000.0))] (print/print-row [index key item time] display)))] [key result])) (range (count inputs)) inputs)))) (defn bulk-warnings "outputs warnings that have been processed" {:added "3.0"} [{:keys [print] :as params} items] (let [warnings (filter #(-> % second :status (= :warn)) items)] (when (and (:result print) (seq warnings)) (clojure.core/print "\n") (print/print-subtitle (string/format "WARNINGS (%s)" (count warnings))) (clojure.core/print "\n") (print/print-column warnings :data #{:warn})) warnings)) (defn bulk-errors "outputs errors that have been processed" {:added "3.0"} [{:keys [print] :as params} items] (let [errors (filter #(-> % second :status #{:critical :error}) items)] (when (and (:result print) (seq errors)) (clojure.core/print "\n") (print/print-subtitle (string/format "ERRORS (%s)" (count errors))) (clojure.core/print "\n") (print/print-column errors :data #{:error})) errors)) (defn prepare-columns "prepares columns for printing (prepare-columns [{:key :name} {:key :data}] [{:name \"PI:NAME:<NAME>END_PI\" :data \"1\"} {:name \"PI:NAME:<NAME>END_PI\" :data \"100\"}]) => [{:key :name, :id :name, :length 7} {:key :data, :id :data, :length 5}]" {:added "3.0"} [columns outputs] (mapv (fn [{:keys [length key] :as column}] (let [id key length (cond (number? length) length :else (->> outputs (map key) (map (comp count str)) (apply max) (+ 2)))] (assoc column :id key :length length))) columns)) (defn bulk-results "outputs results that have been processed" {:added "3.0"} [task {:keys [print order-by] :as params} items] (let [ignore-fn (-> task :result :ignore) remove-fn (fn [[key {:keys [data status] :as result}]] (or (#{:error :warn :info :critical} status) (and ignore-fn (ignore-fn data)))) results (remove remove-fn items) _ (when (:result print) (clojure.core/print "\n") (print/print-subtitle (string/format "RESULTS (%s)" (count results))))] (cond (empty? results) [] :else (let [key-fns (-> task :result :keys) sort-by-fn (-> task :result :sort-by) outputs (mapv (fn [[key {:keys [id data] :as result}]] (->> key-fns (map (fn [[k f]] [k (f data)])) (into result))) results) outputs (if order-by (clojure.core/sort-by order-by outputs) outputs) columns (-> task :result :columns) display {:padding 1 :spacing 1 :columns (prepare-columns columns outputs)} row-keys (map :key columns)] (when (:result print) (clojure.core/print "\n") (print/print-header row-keys display) (mapv (fn [output] (let [row (mapv #(get output %) row-keys)] (print/print-row row display))) outputs)) outputs)))) (defn bulk-summary "outputs summary of processed results" {:added "3.0"} [task {:keys [print] :as params} items results warnings errors] (let [aggregate-fns (-> task :summary :aggregate) finalise-fn (-> task :summary :finalise) time (string/format "%.2fs" (/ (apply + (map (comp :time second) items)) 1000.0)) summary (merge {:errors (count errors) :warnings (count warnings) :items (count items) :results (count results)} (->> aggregate-fns (map/map-vals (fn [[sel acc init]] (reduce (fn [out v] (acc out (sel v))) init results))))) summary (if finalise-fn (finalise-fn summary items results) summary) display (->> summary (remove (comp zero? second)) (into {})) _ (when (:summary print) (clojure.core/print "\n") (print/print-subtitle (string/format "SUMMARY %s" (str (assoc display :time time)))) (println))] (assoc summary :time time))) (defn bulk-package "packages results for return" {:added "3.0"} [task {:keys [items warnings errors results summary] :as bundle} return package] (cond (= return :all) (bulk-package task bundle #{:items :warnings :errors :results :summary} package) (keyword? return) (first (vals (bulk-package task bundle #{return} package))) :else (let [items-fn (or (-> task :item :output) identity) results-fn (or (-> task :result :output) identity)] (reduce (fn [out kw] (cond (#{:summary :warnings :errors} kw) (assoc out kw (get bundle kw)) (= :items kw) (cond->> (get bundle kw) :then (map (fn [[key v]] [key (items-fn (:data v))])) (not= package :vector) (into {}) :then (assoc out :items)) (= :results kw) (cond->> (get bundle kw) :then (map (fn [v] [(:key v) (results-fn (:data v))])) (not= package :vector) (into {}) :then (assoc out :results)) :else out)) {} return)))) (defn bulk "process and output results for a group of inputs" {:added "3.0"} [task f inputs {:keys [print package title return] :as params} lookup env & args] (let [params (assoc params :bulk true) _ (when (and (or (:function print) (:item print) (:result print) (:summary print)) title) (print/print-title title)) items (bulk-items task f inputs params lookup env args) warnings (bulk-warnings params items) errors (bulk-errors params items) results (bulk-results task params items) summary (bulk-summary task params items results warnings errors)] (bulk-package task {:items items :warnings warnings :errors errors :results results :summary summary} (or return :results) package)))
[ { "context": "y-seq (even-numbers (+ n 2))))))\n\n\n(def csv-data \"Edward Cullen,10\\nBella Swan,0\\nCharlie Swan,0\\nJacob Black,3\\n", "end": 787, "score": 0.9998146295547485, "start": 774, "tag": "NAME", "value": "Edward Cullen" }, { "context": "rs (+ n 2))))))\n\n\n(def csv-data \"Edward Cullen,10\\nBella Swan,0\\nCharlie Swan,0\\nJacob Black,3\\nCarlisle Cullen", "end": 802, "score": 0.9928836822509766, "start": 791, "tag": "NAME", "value": "nBella Swan" }, { "context": "\n\n\n(def csv-data \"Edward Cullen,10\\nBella Swan,0\\nCharlie Swan,0\\nJacob Black,3\\nCarlisle Cullen,6\")\n\n(def vamp-", "end": 818, "score": 0.9997577667236328, "start": 806, "tag": "NAME", "value": "Charlie Swan" }, { "context": " \"Edward Cullen,10\\nBella Swan,0\\nCharlie Swan,0\\nJacob Black,3\\nCarlisle Cullen,6\")\n\n(def vamp-keys [:name :gl", "end": 833, "score": 0.9997720122337341, "start": 822, "tag": "NAME", "value": "Jacob Black" }, { "context": ",10\\nBella Swan,0\\nCharlie Swan,0\\nJacob Black,3\\nCarlisle Cullen,6\")\n\n(def vamp-keys [:name :glitter-index])\n\n(def", "end": 852, "score": 0.9997594356536865, "start": 837, "tag": "NAME", "value": "Carlisle Cullen" }, { "context": "defn mapify\n \"Return a seq of maps like {:name \\\"Edward Cullen\\\" :glitter-index 10}\"\n [rows]\n (map (fn [unmapp", "end": 1247, "score": 0.9996830224990845, "start": 1234, "tag": "NAME", "value": "Edward Cullen" }, { "context": "pects suspect))\n\n(println (append-suspect {:name \"Matija\" :glitter-index 1} result))\n\n\n(defn my-and\n [& a", "end": 1963, "score": 0.9993656277656555, "start": 1957, "tag": "NAME", "value": "Matija" }, { "context": " keys-to-vf)))\n\n\n(def student {:name \"Matija\" :age 23})\n(defn validate-name [name] name)\n(defn", "end": 2284, "score": 0.9995120167732239, "start": 2278, "tag": "NAME", "value": "Matija" }, { "context": "-csv-row maps)))\n\n(println (maps-to-csv [{\"name\" \"Matija\" \"age\" 24} {\"name\" \"Sale\" \"age\" 23}]))", "end": 2745, "score": 0.9992336630821228, "start": 2739, "tag": "NAME", "value": "Matija" }, { "context": "(maps-to-csv [{\"name\" \"Matija\" \"age\" 24} {\"name\" \"Sale\" \"age\" 23}]))", "end": 2770, "score": 0.998763918876648, "start": 2766, "tag": "NAME", "value": "Sale" } ]
fonclojure/src/com/matija/vampire_data.clj
matija94/show-me-the-code
1
(ns com.matija.vampire-data) (defn my-reduce [f acc s] (loop [s (seq s) res acc] (if s (let [[part & remaining] s] (recur remaining (f res part))) res))) (defn my-reduce-v2 [f acc s] (loop [res acc s (seq s)] (if s (recur (f res (first s)) (next s)) res))) (println (my-reduce into [] [[1 2] [3 4] [5 6] [7]])) (println (my-reduce + 0 [])) (defn map-using-reduce "Maps each element from vector using supplied function f" [f s] (my-reduce (fn [new-s e] (conj new-s (f e))) () s)) (println (map-using-reduce #(str % " mapped") ["first" "second"])) (println (and true true )) (defn even-numbers ([] (even-numbers 0)) ([n] (cons n (lazy-seq (even-numbers (+ n 2)))))) (def csv-data "Edward Cullen,10\nBella Swan,0\nCharlie Swan,0\nJacob Black,3\nCarlisle Cullen,6") (def vamp-keys [:name :glitter-index]) (defn str->int [str] (Integer. str)) (def conversions {:name identity :glitter-index str->int}) (defn convert [vamp-key value] ((get conversions vamp-key) value)) (defn parse [csv-data] (map #(clojure.string/split % #",") (clojure.string/split csv-data #"\n"))) (defn mapify "Return a seq of maps like {:name \"Edward Cullen\" :glitter-index 10}" [rows] (map (fn [unmapped-row] (reduce (fn [row-map [vamp-key value]] (assoc row-map vamp-key (convert vamp-key value))) {} (map vector vamp-keys unmapped-row))) rows)) (defn glitter-filter [minimum-glitter records] (filter #(>= (:glitter-index %) minimum-glitter) records)) (def result (glitter-filter 3 (mapify (parse csv-data)))) (println result) ; ----EXERCISES----- (defn glitter-filter-tolist [glitter-filtter] (into [] (map :name glitter-filtter))) (println (glitter-filter-tolist result)) (defn append-suspect [suspect suspects] (conj suspects suspect)) (println (append-suspect {:name "Matija" :glitter-index 1} result)) (defn my-and [& args] (reduce (fn [prev curr] (and prev curr)) true args)) (defn validate-record [keys-to-vf record] (apply my-and (map (fn [[key val]] (boolean (val (key record)))) keys-to-vf))) (def student {:name "Matija" :age 23}) (defn validate-name [name] name) (defn validate-age [age] age) (println (validate-record {:name validate-name :age validate-age} student)) (println (boolean (validate-name (:name student)))) (defn map-to-csv-row [mapping] (clojure.string/join "," (map (fn [[_ val]] (str val)) mapping))) (defn maps-to-csv [maps] (clojure.string/join "\n" (map map-to-csv-row maps))) (println (maps-to-csv [{"name" "Matija" "age" 24} {"name" "Sale" "age" 23}]))
39709
(ns com.matija.vampire-data) (defn my-reduce [f acc s] (loop [s (seq s) res acc] (if s (let [[part & remaining] s] (recur remaining (f res part))) res))) (defn my-reduce-v2 [f acc s] (loop [res acc s (seq s)] (if s (recur (f res (first s)) (next s)) res))) (println (my-reduce into [] [[1 2] [3 4] [5 6] [7]])) (println (my-reduce + 0 [])) (defn map-using-reduce "Maps each element from vector using supplied function f" [f s] (my-reduce (fn [new-s e] (conj new-s (f e))) () s)) (println (map-using-reduce #(str % " mapped") ["first" "second"])) (println (and true true )) (defn even-numbers ([] (even-numbers 0)) ([n] (cons n (lazy-seq (even-numbers (+ n 2)))))) (def csv-data "<NAME>,10\<NAME>,0\n<NAME>,0\n<NAME>,3\n<NAME>,6") (def vamp-keys [:name :glitter-index]) (defn str->int [str] (Integer. str)) (def conversions {:name identity :glitter-index str->int}) (defn convert [vamp-key value] ((get conversions vamp-key) value)) (defn parse [csv-data] (map #(clojure.string/split % #",") (clojure.string/split csv-data #"\n"))) (defn mapify "Return a seq of maps like {:name \"<NAME>\" :glitter-index 10}" [rows] (map (fn [unmapped-row] (reduce (fn [row-map [vamp-key value]] (assoc row-map vamp-key (convert vamp-key value))) {} (map vector vamp-keys unmapped-row))) rows)) (defn glitter-filter [minimum-glitter records] (filter #(>= (:glitter-index %) minimum-glitter) records)) (def result (glitter-filter 3 (mapify (parse csv-data)))) (println result) ; ----EXERCISES----- (defn glitter-filter-tolist [glitter-filtter] (into [] (map :name glitter-filtter))) (println (glitter-filter-tolist result)) (defn append-suspect [suspect suspects] (conj suspects suspect)) (println (append-suspect {:name "<NAME>" :glitter-index 1} result)) (defn my-and [& args] (reduce (fn [prev curr] (and prev curr)) true args)) (defn validate-record [keys-to-vf record] (apply my-and (map (fn [[key val]] (boolean (val (key record)))) keys-to-vf))) (def student {:name "<NAME>" :age 23}) (defn validate-name [name] name) (defn validate-age [age] age) (println (validate-record {:name validate-name :age validate-age} student)) (println (boolean (validate-name (:name student)))) (defn map-to-csv-row [mapping] (clojure.string/join "," (map (fn [[_ val]] (str val)) mapping))) (defn maps-to-csv [maps] (clojure.string/join "\n" (map map-to-csv-row maps))) (println (maps-to-csv [{"name" "<NAME>" "age" 24} {"name" "<NAME>" "age" 23}]))
true
(ns com.matija.vampire-data) (defn my-reduce [f acc s] (loop [s (seq s) res acc] (if s (let [[part & remaining] s] (recur remaining (f res part))) res))) (defn my-reduce-v2 [f acc s] (loop [res acc s (seq s)] (if s (recur (f res (first s)) (next s)) res))) (println (my-reduce into [] [[1 2] [3 4] [5 6] [7]])) (println (my-reduce + 0 [])) (defn map-using-reduce "Maps each element from vector using supplied function f" [f s] (my-reduce (fn [new-s e] (conj new-s (f e))) () s)) (println (map-using-reduce #(str % " mapped") ["first" "second"])) (println (and true true )) (defn even-numbers ([] (even-numbers 0)) ([n] (cons n (lazy-seq (even-numbers (+ n 2)))))) (def csv-data "PI:NAME:<NAME>END_PI,10\PI:NAME:<NAME>END_PI,0\nPI:NAME:<NAME>END_PI,0\nPI:NAME:<NAME>END_PI,3\nPI:NAME:<NAME>END_PI,6") (def vamp-keys [:name :glitter-index]) (defn str->int [str] (Integer. str)) (def conversions {:name identity :glitter-index str->int}) (defn convert [vamp-key value] ((get conversions vamp-key) value)) (defn parse [csv-data] (map #(clojure.string/split % #",") (clojure.string/split csv-data #"\n"))) (defn mapify "Return a seq of maps like {:name \"PI:NAME:<NAME>END_PI\" :glitter-index 10}" [rows] (map (fn [unmapped-row] (reduce (fn [row-map [vamp-key value]] (assoc row-map vamp-key (convert vamp-key value))) {} (map vector vamp-keys unmapped-row))) rows)) (defn glitter-filter [minimum-glitter records] (filter #(>= (:glitter-index %) minimum-glitter) records)) (def result (glitter-filter 3 (mapify (parse csv-data)))) (println result) ; ----EXERCISES----- (defn glitter-filter-tolist [glitter-filtter] (into [] (map :name glitter-filtter))) (println (glitter-filter-tolist result)) (defn append-suspect [suspect suspects] (conj suspects suspect)) (println (append-suspect {:name "PI:NAME:<NAME>END_PI" :glitter-index 1} result)) (defn my-and [& args] (reduce (fn [prev curr] (and prev curr)) true args)) (defn validate-record [keys-to-vf record] (apply my-and (map (fn [[key val]] (boolean (val (key record)))) keys-to-vf))) (def student {:name "PI:NAME:<NAME>END_PI" :age 23}) (defn validate-name [name] name) (defn validate-age [age] age) (println (validate-record {:name validate-name :age validate-age} student)) (println (boolean (validate-name (:name student)))) (defn map-to-csv-row [mapping] (clojure.string/join "," (map (fn [[_ val]] (str val)) mapping))) (defn maps-to-csv [maps] (clojure.string/join "\n" (map map-to-csv-row maps))) (println (maps-to-csv [{"name" "PI:NAME:<NAME>END_PI" "age" 24} {"name" "PI:NAME:<NAME>END_PI" "age" 23}]))
[ { "context": "est.example.com\"\n :prefix \"/\"\n :access-key \"key\"\n :secret-key \"secret\"}\n\n :java\n {}\n\n :p", "end": 963, "score": 0.9385035037994385, "start": 960, "tag": "KEY", "value": "key" }, { "context": "prefix \"/\"\n :access-key \"key\"\n :secret-key \"secret\"}\n\n :java\n {}\n\n :process\n {:inherit-exit-", "end": 988, "score": 0.9892686009407043, "start": 982, "tag": "KEY", "value": "secret" } ]
src/clj/runbld/opts.clj
ddillinger/runbld
6
(ns runbld.opts (:require [clj-yaml.core :as yaml] [clojure.string :as str] [clojure.tools.cli :as cli] [environ.core :as environ] [runbld.env :as env] [runbld.io :as io] [runbld.java :as java] [runbld.schema :refer :all] [runbld.store :as store] [runbld.util.data :refer [deep-merge-with deep-merge]] [runbld.util.date :as date] [runbld.util.debug :as debug] [runbld.util.http :refer [wrap-retries]] [runbld.version :as version] [schema.core :as s] [slingshot.slingshot :refer [throw+]])) (defn windows? [] (.startsWith (System/getProperty "os.name") "Windows")) (def config-file-defaults {:es {:url "http://localhost:9200" :build-index "build" :failure-index "failure" :log-index "log" :http-opts {:insecure? false} :max-index-bytes store/MAX_INDEX_BYTES :bulk-timeout-ms 2000 :bulk-size 500} :s3 {:bucket "test.example.com" :prefix "/" :access-key "key" :secret-key "secret"} :java {} :process {:inherit-exit-code true :inherit-env false :cwd (System/getProperty "user.dir") :stdout ".stdout.log" :stderr ".stderr.log" :output ".output.log" :env {}} :email {:host "localhost" :port 587 :tls true :template-txt "templates/email.mustache.txt" :template-html "templates/email.mustache.html" :text-only false :max-failure-notify 10 :disable false} :slack {:first-success false :success true :failure true :template "templates/slack.mustache.json" :disable false} :build-metadata {:disable false} :tests {:junit-filename-pattern "TEST-.*\\.xml$"}}) (s/defn merge-profiles :- java.util.Map [job-name :- s/Str profiles :- [{s/Keyword s/Any}]] (if profiles (apply deep-merge-with deep-merge (for [ms profiles] (let [[k v] (first ms) pat (re-pattern (name k))] (if (re-find pat job-name) (do (debug/log "Job" job-name "matched the pattern" k "Using profile:" v) v) {})))) {})) (defn load-config [filepath] (let [f (io/file filepath)] (when (not (.isFile f)) (throw+ {:error ::file-not-found :msg (format "config file %s not found" filepath)})) (yaml/parse-string (slurp f)))) (s/defn load-config-with-profiles :- java.util.Map [job-name :- s/Str filepath :- (s/cond-pre s/Str java.io.File)] (let [conf (load-config filepath) res (deep-merge-with deep-merge (dissoc conf :profiles) (merge-profiles job-name (:profiles conf)))] res)) (defn system-config [] (io/file (if (windows?) "c:\\runbld\\runbld.conf" "/etc/runbld/runbld.conf"))) (defn normalize "Normalize the tools.cli map to the local structure." [cli-opts] (merge {:process (select-keys cli-opts [:program :args :cwd]) :job-name (:job-name cli-opts) :configfile (:config cli-opts) :version (:version cli-opts)} (when (:java-home cli-opts) {:java-home (:java-home cli-opts)}) (when (:last-good-commit cli-opts) {:last-good-commit (:last-good-commit cli-opts)}))) (defn assemble-all-opts "Merge the options gathered from defaults, system config, the config file specified on the command line, and any separate opts specified by command line arguments" [{:keys [job-name] cli-cwd :cwd :as cli-opts}] (let [opts (normalize cli-opts) merged (deep-merge-with deep-merge config-file-defaults (if (environ/env :dev) (do (io/log "DEV enabled, not attempting to read" (str (system-config))) {}) (let [sys (system-config)] (if (.isFile sys) (load-config-with-profiles job-name (system-config)) {}))) (if (:configfile opts) (load-config-with-profiles job-name (:configfile opts)) {}) opts) cfg-cwd (get-in merged [:process :cwd]) scm-basedir (get-in merged [:scm :basedir])] ;; Need to fix the precedence of the cwd (assoc-in merged [:process :cwd] (cond ;; -d option was provided cli-cwd cli-cwd ;; basedir was provided scm-basedir (str/replace (str/join "/" [cfg-cwd scm-basedir]) #"/+" "/") :else cfg-cwd)))) (def opts [["-v" "--version" "Print version"] ["-c" "--config FILE" "Config file"] ["-d" "--cwd DIR" "Set CWD for the process"] ["-j" "--job-name JOBNAME" (str "Job name: org,project,branch,etc " "also read from $JOB_NAME") :default (environ/env :job-name)] [nil "--last-good-commit JOBNAME" "Whether to checkout the latest commit to have passed a matching job."] [nil "--java-home PATH" (str "If different from JAVA_HOME or need to " " override what will be discovered in PATH")] ["-p" "--program PROGRAM" "Program that will run the scriptfile" :default (if (windows?) "CMD.EXE" "bash")] ["-a" "--args ARGS" "Args to pass PROGRAM" :default (if (windows?) ["/C"] ["-x"]) :parse-fn #(str/split % #" ")] [nil "--system-info" "Just dump facts output"] ["-h" "--help" "Help me"]]) (s/defn set-up-es [{:keys [url build-index failure-index log-index max-index-bytes] :as opts}] (let [conn (store/make-connection (assoc (select-keys opts [:url :http-opts]) :additional-middleware [wrap-retries])) build-index-write (store/set-up-index conn build-index StoredBuildIndexSettings max-index-bytes) failure-index-write (store/set-up-index conn failure-index StoredFailureIndexSettings max-index-bytes) log-index-write (store/set-up-index conn log-index StoredLogIndexSettings max-index-bytes)] (-> opts (assoc :build-index-search (format "%s*" build-index)) (assoc :failure-index-search (format "%s*" failure-index)) (assoc :log-index-search (format "%s*" log-index)) (assoc :build-index-write build-index-write) (assoc :failure-index-write failure-index-write) (assoc :log-index-write log-index-write) (assoc :conn conn)))) (s/defn make-script :- s/Str ([filename :- s/Str] (make-script filename *in*)) ([filename :- s/Str rdr :- java.io.Reader] (if (= filename "-") (let [tmp (io/make-tmp-file "stdin" (if (windows?) ".bat" ".program") :del? true)] (spit tmp (slurp rdr)) (str tmp)) filename))) (s/defn parse-args :- Opts "Prepares the configuration/options for runbld. This currently includes: 1. reading, parsing, validating the command line args 2. printing usage 3. gathering information about the JVM and the environment 4. connecting to and initializing ES 5. writing out the script file that will drive the build And returning all of the useful information from the above." ([args :- [s/Str]] (let [{:keys [options arguments summary errors] :as parsed-opts} (cli/parse-opts args opts :nodefault true)] (when (:help options) (throw+ {:help ::usage :msg summary})) (when (:system-info options) (throw+ {:help ::system})) (when (pos? (count errors)) (throw+ {:error ::parse-error :msg (with-out-str (doseq [err errors] (println err)))})) (when (:version options) (throw+ {:help ::version :msg (version/string)})) (when (not (= 1 (count arguments))) (throw+ {:help ::usage :msg (format "runbld %s\nusage: runbld /path/to/script.bash" (version/string))})) (when (not (:job-name options)) (throw+ {:help ::usage :msg "must set -j or $JOB_NAME"})) (let [options (assemble-all-opts options) java-facts (java/jvm-facts (or (options :java-home) (env/get-env "JAVA_HOME") (-> options :process :env :JAVA_HOME))) process-env (merge (when (-> options :process :inherit-env) (env/get-env)) (-> options :process :env) {:JAVA_HOME (:home java-facts)}) scriptfile (make-script (first arguments))] (merge (dissoc options :java-home) {:es (set-up-es (:es options)) :env (env/get-env) :process (-> (:process options) ;; Invariant: Jenkins passes it in through arguments (assoc :scriptfile scriptfile) ;; Go ahead and resolve (update :cwd io/abspath) (assoc :env process-env)) :version {:string (version/version) :hash (version/build)} :java java-facts})))))
120321
(ns runbld.opts (:require [clj-yaml.core :as yaml] [clojure.string :as str] [clojure.tools.cli :as cli] [environ.core :as environ] [runbld.env :as env] [runbld.io :as io] [runbld.java :as java] [runbld.schema :refer :all] [runbld.store :as store] [runbld.util.data :refer [deep-merge-with deep-merge]] [runbld.util.date :as date] [runbld.util.debug :as debug] [runbld.util.http :refer [wrap-retries]] [runbld.version :as version] [schema.core :as s] [slingshot.slingshot :refer [throw+]])) (defn windows? [] (.startsWith (System/getProperty "os.name") "Windows")) (def config-file-defaults {:es {:url "http://localhost:9200" :build-index "build" :failure-index "failure" :log-index "log" :http-opts {:insecure? false} :max-index-bytes store/MAX_INDEX_BYTES :bulk-timeout-ms 2000 :bulk-size 500} :s3 {:bucket "test.example.com" :prefix "/" :access-key "<KEY>" :secret-key "<KEY>"} :java {} :process {:inherit-exit-code true :inherit-env false :cwd (System/getProperty "user.dir") :stdout ".stdout.log" :stderr ".stderr.log" :output ".output.log" :env {}} :email {:host "localhost" :port 587 :tls true :template-txt "templates/email.mustache.txt" :template-html "templates/email.mustache.html" :text-only false :max-failure-notify 10 :disable false} :slack {:first-success false :success true :failure true :template "templates/slack.mustache.json" :disable false} :build-metadata {:disable false} :tests {:junit-filename-pattern "TEST-.*\\.xml$"}}) (s/defn merge-profiles :- java.util.Map [job-name :- s/Str profiles :- [{s/Keyword s/Any}]] (if profiles (apply deep-merge-with deep-merge (for [ms profiles] (let [[k v] (first ms) pat (re-pattern (name k))] (if (re-find pat job-name) (do (debug/log "Job" job-name "matched the pattern" k "Using profile:" v) v) {})))) {})) (defn load-config [filepath] (let [f (io/file filepath)] (when (not (.isFile f)) (throw+ {:error ::file-not-found :msg (format "config file %s not found" filepath)})) (yaml/parse-string (slurp f)))) (s/defn load-config-with-profiles :- java.util.Map [job-name :- s/Str filepath :- (s/cond-pre s/Str java.io.File)] (let [conf (load-config filepath) res (deep-merge-with deep-merge (dissoc conf :profiles) (merge-profiles job-name (:profiles conf)))] res)) (defn system-config [] (io/file (if (windows?) "c:\\runbld\\runbld.conf" "/etc/runbld/runbld.conf"))) (defn normalize "Normalize the tools.cli map to the local structure." [cli-opts] (merge {:process (select-keys cli-opts [:program :args :cwd]) :job-name (:job-name cli-opts) :configfile (:config cli-opts) :version (:version cli-opts)} (when (:java-home cli-opts) {:java-home (:java-home cli-opts)}) (when (:last-good-commit cli-opts) {:last-good-commit (:last-good-commit cli-opts)}))) (defn assemble-all-opts "Merge the options gathered from defaults, system config, the config file specified on the command line, and any separate opts specified by command line arguments" [{:keys [job-name] cli-cwd :cwd :as cli-opts}] (let [opts (normalize cli-opts) merged (deep-merge-with deep-merge config-file-defaults (if (environ/env :dev) (do (io/log "DEV enabled, not attempting to read" (str (system-config))) {}) (let [sys (system-config)] (if (.isFile sys) (load-config-with-profiles job-name (system-config)) {}))) (if (:configfile opts) (load-config-with-profiles job-name (:configfile opts)) {}) opts) cfg-cwd (get-in merged [:process :cwd]) scm-basedir (get-in merged [:scm :basedir])] ;; Need to fix the precedence of the cwd (assoc-in merged [:process :cwd] (cond ;; -d option was provided cli-cwd cli-cwd ;; basedir was provided scm-basedir (str/replace (str/join "/" [cfg-cwd scm-basedir]) #"/+" "/") :else cfg-cwd)))) (def opts [["-v" "--version" "Print version"] ["-c" "--config FILE" "Config file"] ["-d" "--cwd DIR" "Set CWD for the process"] ["-j" "--job-name JOBNAME" (str "Job name: org,project,branch,etc " "also read from $JOB_NAME") :default (environ/env :job-name)] [nil "--last-good-commit JOBNAME" "Whether to checkout the latest commit to have passed a matching job."] [nil "--java-home PATH" (str "If different from JAVA_HOME or need to " " override what will be discovered in PATH")] ["-p" "--program PROGRAM" "Program that will run the scriptfile" :default (if (windows?) "CMD.EXE" "bash")] ["-a" "--args ARGS" "Args to pass PROGRAM" :default (if (windows?) ["/C"] ["-x"]) :parse-fn #(str/split % #" ")] [nil "--system-info" "Just dump facts output"] ["-h" "--help" "Help me"]]) (s/defn set-up-es [{:keys [url build-index failure-index log-index max-index-bytes] :as opts}] (let [conn (store/make-connection (assoc (select-keys opts [:url :http-opts]) :additional-middleware [wrap-retries])) build-index-write (store/set-up-index conn build-index StoredBuildIndexSettings max-index-bytes) failure-index-write (store/set-up-index conn failure-index StoredFailureIndexSettings max-index-bytes) log-index-write (store/set-up-index conn log-index StoredLogIndexSettings max-index-bytes)] (-> opts (assoc :build-index-search (format "%s*" build-index)) (assoc :failure-index-search (format "%s*" failure-index)) (assoc :log-index-search (format "%s*" log-index)) (assoc :build-index-write build-index-write) (assoc :failure-index-write failure-index-write) (assoc :log-index-write log-index-write) (assoc :conn conn)))) (s/defn make-script :- s/Str ([filename :- s/Str] (make-script filename *in*)) ([filename :- s/Str rdr :- java.io.Reader] (if (= filename "-") (let [tmp (io/make-tmp-file "stdin" (if (windows?) ".bat" ".program") :del? true)] (spit tmp (slurp rdr)) (str tmp)) filename))) (s/defn parse-args :- Opts "Prepares the configuration/options for runbld. This currently includes: 1. reading, parsing, validating the command line args 2. printing usage 3. gathering information about the JVM and the environment 4. connecting to and initializing ES 5. writing out the script file that will drive the build And returning all of the useful information from the above." ([args :- [s/Str]] (let [{:keys [options arguments summary errors] :as parsed-opts} (cli/parse-opts args opts :nodefault true)] (when (:help options) (throw+ {:help ::usage :msg summary})) (when (:system-info options) (throw+ {:help ::system})) (when (pos? (count errors)) (throw+ {:error ::parse-error :msg (with-out-str (doseq [err errors] (println err)))})) (when (:version options) (throw+ {:help ::version :msg (version/string)})) (when (not (= 1 (count arguments))) (throw+ {:help ::usage :msg (format "runbld %s\nusage: runbld /path/to/script.bash" (version/string))})) (when (not (:job-name options)) (throw+ {:help ::usage :msg "must set -j or $JOB_NAME"})) (let [options (assemble-all-opts options) java-facts (java/jvm-facts (or (options :java-home) (env/get-env "JAVA_HOME") (-> options :process :env :JAVA_HOME))) process-env (merge (when (-> options :process :inherit-env) (env/get-env)) (-> options :process :env) {:JAVA_HOME (:home java-facts)}) scriptfile (make-script (first arguments))] (merge (dissoc options :java-home) {:es (set-up-es (:es options)) :env (env/get-env) :process (-> (:process options) ;; Invariant: Jenkins passes it in through arguments (assoc :scriptfile scriptfile) ;; Go ahead and resolve (update :cwd io/abspath) (assoc :env process-env)) :version {:string (version/version) :hash (version/build)} :java java-facts})))))
true
(ns runbld.opts (:require [clj-yaml.core :as yaml] [clojure.string :as str] [clojure.tools.cli :as cli] [environ.core :as environ] [runbld.env :as env] [runbld.io :as io] [runbld.java :as java] [runbld.schema :refer :all] [runbld.store :as store] [runbld.util.data :refer [deep-merge-with deep-merge]] [runbld.util.date :as date] [runbld.util.debug :as debug] [runbld.util.http :refer [wrap-retries]] [runbld.version :as version] [schema.core :as s] [slingshot.slingshot :refer [throw+]])) (defn windows? [] (.startsWith (System/getProperty "os.name") "Windows")) (def config-file-defaults {:es {:url "http://localhost:9200" :build-index "build" :failure-index "failure" :log-index "log" :http-opts {:insecure? false} :max-index-bytes store/MAX_INDEX_BYTES :bulk-timeout-ms 2000 :bulk-size 500} :s3 {:bucket "test.example.com" :prefix "/" :access-key "PI:KEY:<KEY>END_PI" :secret-key "PI:KEY:<KEY>END_PI"} :java {} :process {:inherit-exit-code true :inherit-env false :cwd (System/getProperty "user.dir") :stdout ".stdout.log" :stderr ".stderr.log" :output ".output.log" :env {}} :email {:host "localhost" :port 587 :tls true :template-txt "templates/email.mustache.txt" :template-html "templates/email.mustache.html" :text-only false :max-failure-notify 10 :disable false} :slack {:first-success false :success true :failure true :template "templates/slack.mustache.json" :disable false} :build-metadata {:disable false} :tests {:junit-filename-pattern "TEST-.*\\.xml$"}}) (s/defn merge-profiles :- java.util.Map [job-name :- s/Str profiles :- [{s/Keyword s/Any}]] (if profiles (apply deep-merge-with deep-merge (for [ms profiles] (let [[k v] (first ms) pat (re-pattern (name k))] (if (re-find pat job-name) (do (debug/log "Job" job-name "matched the pattern" k "Using profile:" v) v) {})))) {})) (defn load-config [filepath] (let [f (io/file filepath)] (when (not (.isFile f)) (throw+ {:error ::file-not-found :msg (format "config file %s not found" filepath)})) (yaml/parse-string (slurp f)))) (s/defn load-config-with-profiles :- java.util.Map [job-name :- s/Str filepath :- (s/cond-pre s/Str java.io.File)] (let [conf (load-config filepath) res (deep-merge-with deep-merge (dissoc conf :profiles) (merge-profiles job-name (:profiles conf)))] res)) (defn system-config [] (io/file (if (windows?) "c:\\runbld\\runbld.conf" "/etc/runbld/runbld.conf"))) (defn normalize "Normalize the tools.cli map to the local structure." [cli-opts] (merge {:process (select-keys cli-opts [:program :args :cwd]) :job-name (:job-name cli-opts) :configfile (:config cli-opts) :version (:version cli-opts)} (when (:java-home cli-opts) {:java-home (:java-home cli-opts)}) (when (:last-good-commit cli-opts) {:last-good-commit (:last-good-commit cli-opts)}))) (defn assemble-all-opts "Merge the options gathered from defaults, system config, the config file specified on the command line, and any separate opts specified by command line arguments" [{:keys [job-name] cli-cwd :cwd :as cli-opts}] (let [opts (normalize cli-opts) merged (deep-merge-with deep-merge config-file-defaults (if (environ/env :dev) (do (io/log "DEV enabled, not attempting to read" (str (system-config))) {}) (let [sys (system-config)] (if (.isFile sys) (load-config-with-profiles job-name (system-config)) {}))) (if (:configfile opts) (load-config-with-profiles job-name (:configfile opts)) {}) opts) cfg-cwd (get-in merged [:process :cwd]) scm-basedir (get-in merged [:scm :basedir])] ;; Need to fix the precedence of the cwd (assoc-in merged [:process :cwd] (cond ;; -d option was provided cli-cwd cli-cwd ;; basedir was provided scm-basedir (str/replace (str/join "/" [cfg-cwd scm-basedir]) #"/+" "/") :else cfg-cwd)))) (def opts [["-v" "--version" "Print version"] ["-c" "--config FILE" "Config file"] ["-d" "--cwd DIR" "Set CWD for the process"] ["-j" "--job-name JOBNAME" (str "Job name: org,project,branch,etc " "also read from $JOB_NAME") :default (environ/env :job-name)] [nil "--last-good-commit JOBNAME" "Whether to checkout the latest commit to have passed a matching job."] [nil "--java-home PATH" (str "If different from JAVA_HOME or need to " " override what will be discovered in PATH")] ["-p" "--program PROGRAM" "Program that will run the scriptfile" :default (if (windows?) "CMD.EXE" "bash")] ["-a" "--args ARGS" "Args to pass PROGRAM" :default (if (windows?) ["/C"] ["-x"]) :parse-fn #(str/split % #" ")] [nil "--system-info" "Just dump facts output"] ["-h" "--help" "Help me"]]) (s/defn set-up-es [{:keys [url build-index failure-index log-index max-index-bytes] :as opts}] (let [conn (store/make-connection (assoc (select-keys opts [:url :http-opts]) :additional-middleware [wrap-retries])) build-index-write (store/set-up-index conn build-index StoredBuildIndexSettings max-index-bytes) failure-index-write (store/set-up-index conn failure-index StoredFailureIndexSettings max-index-bytes) log-index-write (store/set-up-index conn log-index StoredLogIndexSettings max-index-bytes)] (-> opts (assoc :build-index-search (format "%s*" build-index)) (assoc :failure-index-search (format "%s*" failure-index)) (assoc :log-index-search (format "%s*" log-index)) (assoc :build-index-write build-index-write) (assoc :failure-index-write failure-index-write) (assoc :log-index-write log-index-write) (assoc :conn conn)))) (s/defn make-script :- s/Str ([filename :- s/Str] (make-script filename *in*)) ([filename :- s/Str rdr :- java.io.Reader] (if (= filename "-") (let [tmp (io/make-tmp-file "stdin" (if (windows?) ".bat" ".program") :del? true)] (spit tmp (slurp rdr)) (str tmp)) filename))) (s/defn parse-args :- Opts "Prepares the configuration/options for runbld. This currently includes: 1. reading, parsing, validating the command line args 2. printing usage 3. gathering information about the JVM and the environment 4. connecting to and initializing ES 5. writing out the script file that will drive the build And returning all of the useful information from the above." ([args :- [s/Str]] (let [{:keys [options arguments summary errors] :as parsed-opts} (cli/parse-opts args opts :nodefault true)] (when (:help options) (throw+ {:help ::usage :msg summary})) (when (:system-info options) (throw+ {:help ::system})) (when (pos? (count errors)) (throw+ {:error ::parse-error :msg (with-out-str (doseq [err errors] (println err)))})) (when (:version options) (throw+ {:help ::version :msg (version/string)})) (when (not (= 1 (count arguments))) (throw+ {:help ::usage :msg (format "runbld %s\nusage: runbld /path/to/script.bash" (version/string))})) (when (not (:job-name options)) (throw+ {:help ::usage :msg "must set -j or $JOB_NAME"})) (let [options (assemble-all-opts options) java-facts (java/jvm-facts (or (options :java-home) (env/get-env "JAVA_HOME") (-> options :process :env :JAVA_HOME))) process-env (merge (when (-> options :process :inherit-env) (env/get-env)) (-> options :process :env) {:JAVA_HOME (:home java-facts)}) scriptfile (make-script (first arguments))] (merge (dissoc options :java-home) {:es (set-up-es (:es options)) :env (env/get-env) :process (-> (:process options) ;; Invariant: Jenkins passes it in through arguments (assoc :scriptfile scriptfile) ;; Go ahead and resolve (update :cwd io/abspath) (assoc :env process-env)) :version {:string (version/version) :hash (version/build)} :java java-facts})))))
[ { "context": "\n (keyword \"/users\") {:displayName \"Users\"\n (keyword \"/it", "end": 3089, "score": 0.9859931468963623, "start": 3084, "tag": "NAME", "value": "Users" }, { "context": "\n (let [input {(keyword \"/users\") {:displayName \"Users\"\n :get {:displa", "end": 3761, "score": 0.9876731038093567, "start": 3756, "tag": "NAME", "value": "Users" } ]
test/api_modeling_framework/generators/domain/raml_test.cljc
raml-org/api-modeling-framework
28
(ns api-modeling-framework.generators.domain.raml-test #?(:cljs (:require-macros [cljs.test :refer [deftest is async]])) (:require #?(:clj [clojure.test :refer :all]) [api-modeling-framework.model.vocabulary :as v] [api-modeling-framework.model.document :as document] [api-modeling-framework.model.domain :as domain] [api-modeling-framework.generators.domain.raml :as generator] [api-modeling-framework.generators.domain.common :as common] [api-modeling-framework.parser.domain.raml :as raml-parser])) (deftest to-raml-APIDocumentation (let [api-documentation (domain/map->ParsedAPIDocumentation {:host "test.com" :scheme ["http" "https"] :base-path "/path" :accepts ["application/json"] :content-type ["appliaton/json"] :version "1.0" :terms-of-service "terms" :id "id" :name "name" :description "description"})] (is (= {:title "name" :description "description" :version "1.0" :baseUri "test.com/path" :protocols ["http" "https"] :mediaType ["appliaton/json" "application/json"]} (generator/to-raml api-documentation {}))))) (deftest to-raml-APIDocumentation-with-amf (let [api-documentation (domain/map->ParsedAPIDocumentation {:host "test.com" :scheme ["http" "https"] :base-path "/path" :accepts ["application/json"] :content-type ["appliaton/json"] :version "1.0" :terms-of-service "terms" :id "model-id" :name "name" :description "description"}) generated (generator/to-raml api-documentation {:syntax :raml :generate-amf-info true})] (is (= "model-id" (get generated (keyword "(amf-id)")))) (is (= "http://raml.org/vocabularies/http#APIDocumentation" (get generated (keyword "(amf-class)")))))) (deftest to-raml-EndPoint (let [input {:baseUri "test.com" :protocols "http" :version "1.0" (keyword "/users") {:displayName "Users" (keyword "/items") {:displayName "items" (keyword "/prices") {:displayName "prices"}}}} api-documentation (raml-parser/parse-ast input {:location "file://path/to/resource.raml#" :parsed-location "file://path/to/resource.raml#" :is-fragment false}) generated (generator/to-raml api-documentation {})] (is (= input generated)))) (deftest to-raml-Operations (let [input {(keyword "/users") {:displayName "Users" :get {:displayName "get method" :description "get description" :protocols ["http"]} :post {:displayName "post method" :description "post description" :protocols ["http"]}}} api-documentation (raml-parser/parse-ast input {:location "file://path/to/resource.raml#" :parsed-location "file://path/to/resource.raml#" :is-fragment false :path "/test"}) generated (generator/to-raml api-documentation {})] (is (= input generated)))) (deftest to-raml-Response (let [input {:displayName "get method" :description "get description" :protocols ["http"] :responses {"200" {:description "200 response"} "400" {:description "400 response"}}} parsed (raml-parser/parse-ast input {:parsed-location "file://path/to/resource.raml#/api-documentation/resources/0" :location "file://path/to/resource.raml#/users" :path "/users" :is-fragment false}) generated (generator/to-raml parsed {})] (is (= input generated))) (let [input {:displayName "get method" :description "get description" :protocols ["http"] :responses {"200" {:description "200 response" :body {"application/json" "any" "text/plain" "any"}} "400" {:description "400 response" :body "any"}}} parsed (raml-parser/parse-ast input {:parsed-location "file://path/to/resource.raml#/api-documentation/resources/0" :location "file://path/to/resource.raml#/users" :path "/users" :is-fragment false}) generated (generator/to-raml parsed {})] (is (= input generated)))) (deftest to-raml-operation-with-request (let [input {:displayName "get method" :description "get description" :protocols ["http"] :headers {:Zencoder-Api-Key "integer"} :body "string" :queryParameters {:page "integer" :per_page "integer"} :responses {"200" {:description "200 response" :body {"application/json" "string" "text/plain" "string"}} "400" {:description "400 response" :body "string"}}} parsed (raml-parser/parse-ast input {:parsed-location "file://path/to/resource.raml#/api-documentation/resources/0" :location "file://path/to/resource.raml#/users" :path "/users" :method "get" :is-fragment false}) generated (generator/to-raml parsed {})] (is(= generated input)))) (deftest to-raml-traits (let [location "file://path/to/resource.raml#" input {:title "Github API" :baseUri "api.github.com" :protocols "http" :version "v3" :traits {:paged {:queryParameters {:start "number"}}} (keyword "/users") {:displayName "Users" :get {:description "get description" :is ["paged"] :protocols ["http"] :responses {"200" {:description "200 response"} "400" {:description "400 response"}}}}} declarations (raml-parser/process-traits input {:location (str location "") :parsed-location (str location "/declares")}) parsed (raml-parser/parse-ast input {:parsed-location location :location location :references declarations :is-fragment false}) generated (generator/to-raml parsed {:references (vals declarations)})] (is (= input generated)))) (deftest to-raml-body (let [location "file://path/to/file.raml#" input {:post {:body {"application/json" {:properties {:name "string"}}}}} parsed (raml-parser/parse-ast input {:location location :parsed-location location}) generated (generator/to-raml (first parsed) {})] (is (= input generated)))) (deftest to-raml-body-2 (let [location "file://path/to/file.raml#" input {:post {:body {:properties {:name "string"}}}} parsed (raml-parser/parse-ast input {:location location :parsed-location location}) generated (generator/to-raml (first parsed) {})] (is (= input generated)))) (deftest to-raml-body-3 (let [location "file://path/to/file.raml#" input {:post {:body {"application/json" {:properties {:name "string"}} "application/json-ld" {:properties {:name2 "string"}}}}} parsed (raml-parser/parse-ast input {:location location :parsed-location location}) generated (generator/to-raml (first parsed) {})] (is (= input generated)))) (deftest to-raml-Annotations (let [base-uri "file://path/to/resource.raml" location "file://path/to/resource.raml#" input {:annotationTypes {:testHarness {:type "string" :displayName "test harness" :allowedTargets ["API"]}} (keyword "/users") {:displayName "Users" "(testHarness)" "usersTest" :get {:displayName "get method" :description "get description" :protocols ["http"]}}} annotations (raml-parser/process-annotations input {:base-uri base-uri :location location :parsed-location (str location "/annotations")}) parsed (raml-parser/parse-ast input {:location location :parsed-location "file://path/to/resource.raml#" :is-fragment false :annotations annotations :path "/test"}) generated-annotations (common/model->annotationTypes (vals annotations) {} generator/to-raml!) generated (generator/to-raml parsed {})] (is (= input (assoc generated :annotationTypes generated-annotations)))))
52787
(ns api-modeling-framework.generators.domain.raml-test #?(:cljs (:require-macros [cljs.test :refer [deftest is async]])) (:require #?(:clj [clojure.test :refer :all]) [api-modeling-framework.model.vocabulary :as v] [api-modeling-framework.model.document :as document] [api-modeling-framework.model.domain :as domain] [api-modeling-framework.generators.domain.raml :as generator] [api-modeling-framework.generators.domain.common :as common] [api-modeling-framework.parser.domain.raml :as raml-parser])) (deftest to-raml-APIDocumentation (let [api-documentation (domain/map->ParsedAPIDocumentation {:host "test.com" :scheme ["http" "https"] :base-path "/path" :accepts ["application/json"] :content-type ["appliaton/json"] :version "1.0" :terms-of-service "terms" :id "id" :name "name" :description "description"})] (is (= {:title "name" :description "description" :version "1.0" :baseUri "test.com/path" :protocols ["http" "https"] :mediaType ["appliaton/json" "application/json"]} (generator/to-raml api-documentation {}))))) (deftest to-raml-APIDocumentation-with-amf (let [api-documentation (domain/map->ParsedAPIDocumentation {:host "test.com" :scheme ["http" "https"] :base-path "/path" :accepts ["application/json"] :content-type ["appliaton/json"] :version "1.0" :terms-of-service "terms" :id "model-id" :name "name" :description "description"}) generated (generator/to-raml api-documentation {:syntax :raml :generate-amf-info true})] (is (= "model-id" (get generated (keyword "(amf-id)")))) (is (= "http://raml.org/vocabularies/http#APIDocumentation" (get generated (keyword "(amf-class)")))))) (deftest to-raml-EndPoint (let [input {:baseUri "test.com" :protocols "http" :version "1.0" (keyword "/users") {:displayName "<NAME>" (keyword "/items") {:displayName "items" (keyword "/prices") {:displayName "prices"}}}} api-documentation (raml-parser/parse-ast input {:location "file://path/to/resource.raml#" :parsed-location "file://path/to/resource.raml#" :is-fragment false}) generated (generator/to-raml api-documentation {})] (is (= input generated)))) (deftest to-raml-Operations (let [input {(keyword "/users") {:displayName "<NAME>" :get {:displayName "get method" :description "get description" :protocols ["http"]} :post {:displayName "post method" :description "post description" :protocols ["http"]}}} api-documentation (raml-parser/parse-ast input {:location "file://path/to/resource.raml#" :parsed-location "file://path/to/resource.raml#" :is-fragment false :path "/test"}) generated (generator/to-raml api-documentation {})] (is (= input generated)))) (deftest to-raml-Response (let [input {:displayName "get method" :description "get description" :protocols ["http"] :responses {"200" {:description "200 response"} "400" {:description "400 response"}}} parsed (raml-parser/parse-ast input {:parsed-location "file://path/to/resource.raml#/api-documentation/resources/0" :location "file://path/to/resource.raml#/users" :path "/users" :is-fragment false}) generated (generator/to-raml parsed {})] (is (= input generated))) (let [input {:displayName "get method" :description "get description" :protocols ["http"] :responses {"200" {:description "200 response" :body {"application/json" "any" "text/plain" "any"}} "400" {:description "400 response" :body "any"}}} parsed (raml-parser/parse-ast input {:parsed-location "file://path/to/resource.raml#/api-documentation/resources/0" :location "file://path/to/resource.raml#/users" :path "/users" :is-fragment false}) generated (generator/to-raml parsed {})] (is (= input generated)))) (deftest to-raml-operation-with-request (let [input {:displayName "get method" :description "get description" :protocols ["http"] :headers {:Zencoder-Api-Key "integer"} :body "string" :queryParameters {:page "integer" :per_page "integer"} :responses {"200" {:description "200 response" :body {"application/json" "string" "text/plain" "string"}} "400" {:description "400 response" :body "string"}}} parsed (raml-parser/parse-ast input {:parsed-location "file://path/to/resource.raml#/api-documentation/resources/0" :location "file://path/to/resource.raml#/users" :path "/users" :method "get" :is-fragment false}) generated (generator/to-raml parsed {})] (is(= generated input)))) (deftest to-raml-traits (let [location "file://path/to/resource.raml#" input {:title "Github API" :baseUri "api.github.com" :protocols "http" :version "v3" :traits {:paged {:queryParameters {:start "number"}}} (keyword "/users") {:displayName "Users" :get {:description "get description" :is ["paged"] :protocols ["http"] :responses {"200" {:description "200 response"} "400" {:description "400 response"}}}}} declarations (raml-parser/process-traits input {:location (str location "") :parsed-location (str location "/declares")}) parsed (raml-parser/parse-ast input {:parsed-location location :location location :references declarations :is-fragment false}) generated (generator/to-raml parsed {:references (vals declarations)})] (is (= input generated)))) (deftest to-raml-body (let [location "file://path/to/file.raml#" input {:post {:body {"application/json" {:properties {:name "string"}}}}} parsed (raml-parser/parse-ast input {:location location :parsed-location location}) generated (generator/to-raml (first parsed) {})] (is (= input generated)))) (deftest to-raml-body-2 (let [location "file://path/to/file.raml#" input {:post {:body {:properties {:name "string"}}}} parsed (raml-parser/parse-ast input {:location location :parsed-location location}) generated (generator/to-raml (first parsed) {})] (is (= input generated)))) (deftest to-raml-body-3 (let [location "file://path/to/file.raml#" input {:post {:body {"application/json" {:properties {:name "string"}} "application/json-ld" {:properties {:name2 "string"}}}}} parsed (raml-parser/parse-ast input {:location location :parsed-location location}) generated (generator/to-raml (first parsed) {})] (is (= input generated)))) (deftest to-raml-Annotations (let [base-uri "file://path/to/resource.raml" location "file://path/to/resource.raml#" input {:annotationTypes {:testHarness {:type "string" :displayName "test harness" :allowedTargets ["API"]}} (keyword "/users") {:displayName "Users" "(testHarness)" "usersTest" :get {:displayName "get method" :description "get description" :protocols ["http"]}}} annotations (raml-parser/process-annotations input {:base-uri base-uri :location location :parsed-location (str location "/annotations")}) parsed (raml-parser/parse-ast input {:location location :parsed-location "file://path/to/resource.raml#" :is-fragment false :annotations annotations :path "/test"}) generated-annotations (common/model->annotationTypes (vals annotations) {} generator/to-raml!) generated (generator/to-raml parsed {})] (is (= input (assoc generated :annotationTypes generated-annotations)))))
true
(ns api-modeling-framework.generators.domain.raml-test #?(:cljs (:require-macros [cljs.test :refer [deftest is async]])) (:require #?(:clj [clojure.test :refer :all]) [api-modeling-framework.model.vocabulary :as v] [api-modeling-framework.model.document :as document] [api-modeling-framework.model.domain :as domain] [api-modeling-framework.generators.domain.raml :as generator] [api-modeling-framework.generators.domain.common :as common] [api-modeling-framework.parser.domain.raml :as raml-parser])) (deftest to-raml-APIDocumentation (let [api-documentation (domain/map->ParsedAPIDocumentation {:host "test.com" :scheme ["http" "https"] :base-path "/path" :accepts ["application/json"] :content-type ["appliaton/json"] :version "1.0" :terms-of-service "terms" :id "id" :name "name" :description "description"})] (is (= {:title "name" :description "description" :version "1.0" :baseUri "test.com/path" :protocols ["http" "https"] :mediaType ["appliaton/json" "application/json"]} (generator/to-raml api-documentation {}))))) (deftest to-raml-APIDocumentation-with-amf (let [api-documentation (domain/map->ParsedAPIDocumentation {:host "test.com" :scheme ["http" "https"] :base-path "/path" :accepts ["application/json"] :content-type ["appliaton/json"] :version "1.0" :terms-of-service "terms" :id "model-id" :name "name" :description "description"}) generated (generator/to-raml api-documentation {:syntax :raml :generate-amf-info true})] (is (= "model-id" (get generated (keyword "(amf-id)")))) (is (= "http://raml.org/vocabularies/http#APIDocumentation" (get generated (keyword "(amf-class)")))))) (deftest to-raml-EndPoint (let [input {:baseUri "test.com" :protocols "http" :version "1.0" (keyword "/users") {:displayName "PI:NAME:<NAME>END_PI" (keyword "/items") {:displayName "items" (keyword "/prices") {:displayName "prices"}}}} api-documentation (raml-parser/parse-ast input {:location "file://path/to/resource.raml#" :parsed-location "file://path/to/resource.raml#" :is-fragment false}) generated (generator/to-raml api-documentation {})] (is (= input generated)))) (deftest to-raml-Operations (let [input {(keyword "/users") {:displayName "PI:NAME:<NAME>END_PI" :get {:displayName "get method" :description "get description" :protocols ["http"]} :post {:displayName "post method" :description "post description" :protocols ["http"]}}} api-documentation (raml-parser/parse-ast input {:location "file://path/to/resource.raml#" :parsed-location "file://path/to/resource.raml#" :is-fragment false :path "/test"}) generated (generator/to-raml api-documentation {})] (is (= input generated)))) (deftest to-raml-Response (let [input {:displayName "get method" :description "get description" :protocols ["http"] :responses {"200" {:description "200 response"} "400" {:description "400 response"}}} parsed (raml-parser/parse-ast input {:parsed-location "file://path/to/resource.raml#/api-documentation/resources/0" :location "file://path/to/resource.raml#/users" :path "/users" :is-fragment false}) generated (generator/to-raml parsed {})] (is (= input generated))) (let [input {:displayName "get method" :description "get description" :protocols ["http"] :responses {"200" {:description "200 response" :body {"application/json" "any" "text/plain" "any"}} "400" {:description "400 response" :body "any"}}} parsed (raml-parser/parse-ast input {:parsed-location "file://path/to/resource.raml#/api-documentation/resources/0" :location "file://path/to/resource.raml#/users" :path "/users" :is-fragment false}) generated (generator/to-raml parsed {})] (is (= input generated)))) (deftest to-raml-operation-with-request (let [input {:displayName "get method" :description "get description" :protocols ["http"] :headers {:Zencoder-Api-Key "integer"} :body "string" :queryParameters {:page "integer" :per_page "integer"} :responses {"200" {:description "200 response" :body {"application/json" "string" "text/plain" "string"}} "400" {:description "400 response" :body "string"}}} parsed (raml-parser/parse-ast input {:parsed-location "file://path/to/resource.raml#/api-documentation/resources/0" :location "file://path/to/resource.raml#/users" :path "/users" :method "get" :is-fragment false}) generated (generator/to-raml parsed {})] (is(= generated input)))) (deftest to-raml-traits (let [location "file://path/to/resource.raml#" input {:title "Github API" :baseUri "api.github.com" :protocols "http" :version "v3" :traits {:paged {:queryParameters {:start "number"}}} (keyword "/users") {:displayName "Users" :get {:description "get description" :is ["paged"] :protocols ["http"] :responses {"200" {:description "200 response"} "400" {:description "400 response"}}}}} declarations (raml-parser/process-traits input {:location (str location "") :parsed-location (str location "/declares")}) parsed (raml-parser/parse-ast input {:parsed-location location :location location :references declarations :is-fragment false}) generated (generator/to-raml parsed {:references (vals declarations)})] (is (= input generated)))) (deftest to-raml-body (let [location "file://path/to/file.raml#" input {:post {:body {"application/json" {:properties {:name "string"}}}}} parsed (raml-parser/parse-ast input {:location location :parsed-location location}) generated (generator/to-raml (first parsed) {})] (is (= input generated)))) (deftest to-raml-body-2 (let [location "file://path/to/file.raml#" input {:post {:body {:properties {:name "string"}}}} parsed (raml-parser/parse-ast input {:location location :parsed-location location}) generated (generator/to-raml (first parsed) {})] (is (= input generated)))) (deftest to-raml-body-3 (let [location "file://path/to/file.raml#" input {:post {:body {"application/json" {:properties {:name "string"}} "application/json-ld" {:properties {:name2 "string"}}}}} parsed (raml-parser/parse-ast input {:location location :parsed-location location}) generated (generator/to-raml (first parsed) {})] (is (= input generated)))) (deftest to-raml-Annotations (let [base-uri "file://path/to/resource.raml" location "file://path/to/resource.raml#" input {:annotationTypes {:testHarness {:type "string" :displayName "test harness" :allowedTargets ["API"]}} (keyword "/users") {:displayName "Users" "(testHarness)" "usersTest" :get {:displayName "get method" :description "get description" :protocols ["http"]}}} annotations (raml-parser/process-annotations input {:base-uri base-uri :location location :parsed-location (str location "/annotations")}) parsed (raml-parser/parse-ast input {:location location :parsed-location "file://path/to/resource.raml#" :is-fragment false :annotations annotations :path "/test"}) generated-annotations (common/model->annotationTypes (vals annotations) {} generator/to-raml!) generated (generator/to-raml parsed {})] (is (= input (assoc generated :annotationTypes generated-annotations)))))
[ { "context": " :source-paths [\"src\"]\n :url \"https://github.com/rm-hull/photosphere\"\n :license {:name \"The MIT License (", "end": 216, "score": 0.9984366297721863, "start": 209, "tag": "USERNAME", "value": "rm-hull" }, { "context": "ttp://opensource.org/licenses/MIT\"}\n :scm {:url \"git@github.com:rm-hull/photosphere\"}\n :min-lein-version \"2.3.4\"", "end": 355, "score": 0.998687744140625, "start": 341, "tag": "EMAIL", "value": "git@github.com" }, { "context": "e.org/licenses/MIT\"}\n :scm {:url \"git@github.com:rm-hull/photosphere\"}\n :min-lein-version \"2.3.4\"\n :glob", "end": 363, "score": 0.9982158541679382, "start": 356, "tag": "USERNAME", "value": "rm-hull" } ]
project.clj
rm-hull/photosphere
0
(defproject rm-hull/photosphere "0.0.1-SNAPSHOT" :clojurescript? true :description "A ClojureScript library for reading and displaying 360° photospheres" :source-paths ["src"] :url "https://github.com/rm-hull/photosphere" :license {:name "The MIT License (MIT)" :url "http://opensource.org/licenses/MIT"} :scm {:url "git@github.com:rm-hull/photosphere"} :min-lein-version "2.3.4" :global-vars {*warn-on-reflection* true} :plugins [[lein-cljsbuild "1.0.2"]] :dependencies [[org.clojure/clojure "1.5.1"] [org.clojure/clojurescript "0.0-2173"] [rm-hull/dommy "0.1.3-SNAPSHOT"] [rm-hull/cljs-test "0.0.7"] [rm-hull/big-bang "0.0.1-SNAPSHOT"] [rm-hull/cljs-dataview "0.0.1-SNAPSHOT"] [rm-hull/wireframes "0.0.1-SNAPSHOT"]] :cljsbuild { :test-commands {"phantomjs" ["phantomjs" "target/unit-test.js"]} :builds { :test { :source-paths ["src" "test"] :incremental? true :compiler { :output-to "target/unit-test.js" :source-map "target/unit-test.map" :static-fns true :optimizations :whitespace :pretty-print true }} ;:examples { ; :source-paths ["src" "examples"] ; :incremental? true ; :compiler { ; :output-to "target/example.js" ; :source-map "target/example.map" ; :static-fns true ; ;:optimizations :advanced ; :pretty-print true }} }})
64242
(defproject rm-hull/photosphere "0.0.1-SNAPSHOT" :clojurescript? true :description "A ClojureScript library for reading and displaying 360° photospheres" :source-paths ["src"] :url "https://github.com/rm-hull/photosphere" :license {:name "The MIT License (MIT)" :url "http://opensource.org/licenses/MIT"} :scm {:url "<EMAIL>:rm-hull/photosphere"} :min-lein-version "2.3.4" :global-vars {*warn-on-reflection* true} :plugins [[lein-cljsbuild "1.0.2"]] :dependencies [[org.clojure/clojure "1.5.1"] [org.clojure/clojurescript "0.0-2173"] [rm-hull/dommy "0.1.3-SNAPSHOT"] [rm-hull/cljs-test "0.0.7"] [rm-hull/big-bang "0.0.1-SNAPSHOT"] [rm-hull/cljs-dataview "0.0.1-SNAPSHOT"] [rm-hull/wireframes "0.0.1-SNAPSHOT"]] :cljsbuild { :test-commands {"phantomjs" ["phantomjs" "target/unit-test.js"]} :builds { :test { :source-paths ["src" "test"] :incremental? true :compiler { :output-to "target/unit-test.js" :source-map "target/unit-test.map" :static-fns true :optimizations :whitespace :pretty-print true }} ;:examples { ; :source-paths ["src" "examples"] ; :incremental? true ; :compiler { ; :output-to "target/example.js" ; :source-map "target/example.map" ; :static-fns true ; ;:optimizations :advanced ; :pretty-print true }} }})
true
(defproject rm-hull/photosphere "0.0.1-SNAPSHOT" :clojurescript? true :description "A ClojureScript library for reading and displaying 360° photospheres" :source-paths ["src"] :url "https://github.com/rm-hull/photosphere" :license {:name "The MIT License (MIT)" :url "http://opensource.org/licenses/MIT"} :scm {:url "PI:EMAIL:<EMAIL>END_PI:rm-hull/photosphere"} :min-lein-version "2.3.4" :global-vars {*warn-on-reflection* true} :plugins [[lein-cljsbuild "1.0.2"]] :dependencies [[org.clojure/clojure "1.5.1"] [org.clojure/clojurescript "0.0-2173"] [rm-hull/dommy "0.1.3-SNAPSHOT"] [rm-hull/cljs-test "0.0.7"] [rm-hull/big-bang "0.0.1-SNAPSHOT"] [rm-hull/cljs-dataview "0.0.1-SNAPSHOT"] [rm-hull/wireframes "0.0.1-SNAPSHOT"]] :cljsbuild { :test-commands {"phantomjs" ["phantomjs" "target/unit-test.js"]} :builds { :test { :source-paths ["src" "test"] :incremental? true :compiler { :output-to "target/unit-test.js" :source-map "target/unit-test.map" :static-fns true :optimizations :whitespace :pretty-print true }} ;:examples { ; :source-paths ["src" "examples"] ; :incremental? true ; :compiler { ; :output-to "target/example.js" ; :source-map "target/example.map" ; :static-fns true ; ;:optimizations :advanced ; :pretty-print true }} }})
[ { "context": ";; Copyright (c) 2014-2016 Andrey Antukh <niwi@niwi.nz>\n;;\n;; Licensed under the Apache Li", "end": 40, "score": 0.9998810887336731, "start": 27, "tag": "NAME", "value": "Andrey Antukh" }, { "context": ";; Copyright (c) 2014-2016 Andrey Antukh <niwi@niwi.nz>\n;;\n;; Licensed under the Apache License, Version", "end": 54, "score": 0.9999321699142456, "start": 42, "tag": "EMAIL", "value": "niwi@niwi.nz" } ]
src/buddy/sign/jwe/cek.clj
FieryCod/buddy-sign
0
;; Copyright (c) 2014-2016 Andrey Antukh <niwi@niwi.nz> ;; ;; 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 buddy.sign.jwe.cek "Json Web Encryption Content Encryption Key utilities." (:require [buddy.core.codecs :as codecs] [buddy.core.nonce :as nonce] [buddy.core.keys :as keys]) (:import javax.crypto.Cipher java.security.SecureRandom java.security.Key)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Implementation: Content Encryption Keys ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- validate-keylength-for-algorithm [key algorithn] (case algorithn :dir true :rsa-oaep true :rsa-oaep-256 true :rsa1_5 true :a128kw (= (count key) 16) :a192kw (= (count key) 24) :a256kw (= (count key) 32))) (defn- encrypt-with-rsaaoep [cek pubkey] (let [cipher (Cipher/getInstance "RSA/ECB/OAEPWithSHA-1AndMGF1Padding" "BC") sr (SecureRandom.)] (.init cipher Cipher/ENCRYPT_MODE ^Key pubkey sr) (.doFinal cipher cek))) (defn- decrypt-with-rsaaoep [ecek privkey] (let [cipher (Cipher/getInstance "RSA/ECB/OAEPWithSHA-1AndMGF1Padding" "BC") sr (SecureRandom.)] (.init cipher Cipher/DECRYPT_MODE ^Key privkey sr) (.doFinal cipher ecek))) (defn- encrypt-with-rsaaoep-sha256 [cek pubkey] (let [cipher (Cipher/getInstance "RSA/ECB/OAEPWithSHA-256AndMGF1Padding" "BC") sr (SecureRandom.)] (.init cipher Cipher/ENCRYPT_MODE ^Key pubkey sr) (.doFinal cipher cek))) (defn- decrypt-with-rsaaoep-sha256 [ecek privkey] (let [cipher (Cipher/getInstance "RSA/ECB/OAEPWithSHA-256AndMGF1Padding" "BC") sr (SecureRandom.)] (.init cipher Cipher/DECRYPT_MODE ^Key privkey sr) (.doFinal cipher ecek))) (defn- encrypt-with-rsa-pkcs15 [cek pubkey] (let [cipher (Cipher/getInstance "RSA/ECB/PKCS1Padding" "BC") sr (SecureRandom.)] (.init cipher Cipher/ENCRYPT_MODE ^Key pubkey sr) (.doFinal cipher cek))) (defn- decrypt-with-rsa-pkcs15 [ecek privkey] (let [cipher (Cipher/getInstance "RSA/ECB/PKCS1Padding" "BC") sr (SecureRandom.)] (.init cipher Cipher/DECRYPT_MODE ^Key privkey sr) (.doFinal cipher ecek))) (def ^:private aeskw? #{:a128kw :a192kw :a256kw}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Public Api ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn generate [{:keys [key alg enc] :as options}] (case alg :dir (codecs/to-bytes key) (case enc :a128cbc-hs256 (nonce/random-bytes 32) :a192cbc-hs384 (nonce/random-bytes 48) :a256cbc-hs512 (nonce/random-bytes 64) :a128gcm (nonce/random-bytes 16) :a192gcm (nonce/random-bytes 24) :a256gcm (nonce/random-bytes 32)))) (defn encrypt [{:keys [key alg enc cek] :as options}] {:pre [(validate-keylength-for-algorithm key alg)]} (cond (= alg :dir) (byte-array 0) (= alg :rsa-oaep) (encrypt-with-rsaaoep cek key) (= alg :rsa-oaep-256) (encrypt-with-rsaaoep-sha256 cek key) (= alg :rsa-oaep-256) (encrypt-with-rsaaoep-sha256 cek key) (= alg :rsa1_5) (encrypt-with-rsa-pkcs15 cek key) (aeskw? alg) (let [secret (codecs/to-bytes key)] (keys/wrap cek secret :aes)))) (defn decrypt [{:keys [key alg enc ecek] :as options}] (cond (= alg :dir) (codecs/to-bytes key) (= alg :rsa-oaep) (decrypt-with-rsaaoep ecek key) (= alg :rsa-oaep-256) (decrypt-with-rsaaoep-sha256 ecek key) (= alg :rsa1_5) (decrypt-with-rsa-pkcs15 ecek key) (aeskw? alg) (let [secret (codecs/to-bytes key)] (keys/unwrap ecek secret :aes))))
76118
;; Copyright (c) 2014-2016 <NAME> <<EMAIL>> ;; ;; Licensed under the Apache License, Version 2.0 (the "License") ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns buddy.sign.jwe.cek "Json Web Encryption Content Encryption Key utilities." (:require [buddy.core.codecs :as codecs] [buddy.core.nonce :as nonce] [buddy.core.keys :as keys]) (:import javax.crypto.Cipher java.security.SecureRandom java.security.Key)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Implementation: Content Encryption Keys ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- validate-keylength-for-algorithm [key algorithn] (case algorithn :dir true :rsa-oaep true :rsa-oaep-256 true :rsa1_5 true :a128kw (= (count key) 16) :a192kw (= (count key) 24) :a256kw (= (count key) 32))) (defn- encrypt-with-rsaaoep [cek pubkey] (let [cipher (Cipher/getInstance "RSA/ECB/OAEPWithSHA-1AndMGF1Padding" "BC") sr (SecureRandom.)] (.init cipher Cipher/ENCRYPT_MODE ^Key pubkey sr) (.doFinal cipher cek))) (defn- decrypt-with-rsaaoep [ecek privkey] (let [cipher (Cipher/getInstance "RSA/ECB/OAEPWithSHA-1AndMGF1Padding" "BC") sr (SecureRandom.)] (.init cipher Cipher/DECRYPT_MODE ^Key privkey sr) (.doFinal cipher ecek))) (defn- encrypt-with-rsaaoep-sha256 [cek pubkey] (let [cipher (Cipher/getInstance "RSA/ECB/OAEPWithSHA-256AndMGF1Padding" "BC") sr (SecureRandom.)] (.init cipher Cipher/ENCRYPT_MODE ^Key pubkey sr) (.doFinal cipher cek))) (defn- decrypt-with-rsaaoep-sha256 [ecek privkey] (let [cipher (Cipher/getInstance "RSA/ECB/OAEPWithSHA-256AndMGF1Padding" "BC") sr (SecureRandom.)] (.init cipher Cipher/DECRYPT_MODE ^Key privkey sr) (.doFinal cipher ecek))) (defn- encrypt-with-rsa-pkcs15 [cek pubkey] (let [cipher (Cipher/getInstance "RSA/ECB/PKCS1Padding" "BC") sr (SecureRandom.)] (.init cipher Cipher/ENCRYPT_MODE ^Key pubkey sr) (.doFinal cipher cek))) (defn- decrypt-with-rsa-pkcs15 [ecek privkey] (let [cipher (Cipher/getInstance "RSA/ECB/PKCS1Padding" "BC") sr (SecureRandom.)] (.init cipher Cipher/DECRYPT_MODE ^Key privkey sr) (.doFinal cipher ecek))) (def ^:private aeskw? #{:a128kw :a192kw :a256kw}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Public Api ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn generate [{:keys [key alg enc] :as options}] (case alg :dir (codecs/to-bytes key) (case enc :a128cbc-hs256 (nonce/random-bytes 32) :a192cbc-hs384 (nonce/random-bytes 48) :a256cbc-hs512 (nonce/random-bytes 64) :a128gcm (nonce/random-bytes 16) :a192gcm (nonce/random-bytes 24) :a256gcm (nonce/random-bytes 32)))) (defn encrypt [{:keys [key alg enc cek] :as options}] {:pre [(validate-keylength-for-algorithm key alg)]} (cond (= alg :dir) (byte-array 0) (= alg :rsa-oaep) (encrypt-with-rsaaoep cek key) (= alg :rsa-oaep-256) (encrypt-with-rsaaoep-sha256 cek key) (= alg :rsa-oaep-256) (encrypt-with-rsaaoep-sha256 cek key) (= alg :rsa1_5) (encrypt-with-rsa-pkcs15 cek key) (aeskw? alg) (let [secret (codecs/to-bytes key)] (keys/wrap cek secret :aes)))) (defn decrypt [{:keys [key alg enc ecek] :as options}] (cond (= alg :dir) (codecs/to-bytes key) (= alg :rsa-oaep) (decrypt-with-rsaaoep ecek key) (= alg :rsa-oaep-256) (decrypt-with-rsaaoep-sha256 ecek key) (= alg :rsa1_5) (decrypt-with-rsa-pkcs15 ecek key) (aeskw? alg) (let [secret (codecs/to-bytes key)] (keys/unwrap ecek secret :aes))))
true
;; Copyright (c) 2014-2016 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ;; ;; Licensed under the Apache License, Version 2.0 (the "License") ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; http://www.apache.org/licenses/LICENSE-2.0 ;; ;; Unless required by applicable law or agreed to in writing, software ;; distributed under the License is distributed on an "AS IS" BASIS, ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns buddy.sign.jwe.cek "Json Web Encryption Content Encryption Key utilities." (:require [buddy.core.codecs :as codecs] [buddy.core.nonce :as nonce] [buddy.core.keys :as keys]) (:import javax.crypto.Cipher java.security.SecureRandom java.security.Key)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Implementation: Content Encryption Keys ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- validate-keylength-for-algorithm [key algorithn] (case algorithn :dir true :rsa-oaep true :rsa-oaep-256 true :rsa1_5 true :a128kw (= (count key) 16) :a192kw (= (count key) 24) :a256kw (= (count key) 32))) (defn- encrypt-with-rsaaoep [cek pubkey] (let [cipher (Cipher/getInstance "RSA/ECB/OAEPWithSHA-1AndMGF1Padding" "BC") sr (SecureRandom.)] (.init cipher Cipher/ENCRYPT_MODE ^Key pubkey sr) (.doFinal cipher cek))) (defn- decrypt-with-rsaaoep [ecek privkey] (let [cipher (Cipher/getInstance "RSA/ECB/OAEPWithSHA-1AndMGF1Padding" "BC") sr (SecureRandom.)] (.init cipher Cipher/DECRYPT_MODE ^Key privkey sr) (.doFinal cipher ecek))) (defn- encrypt-with-rsaaoep-sha256 [cek pubkey] (let [cipher (Cipher/getInstance "RSA/ECB/OAEPWithSHA-256AndMGF1Padding" "BC") sr (SecureRandom.)] (.init cipher Cipher/ENCRYPT_MODE ^Key pubkey sr) (.doFinal cipher cek))) (defn- decrypt-with-rsaaoep-sha256 [ecek privkey] (let [cipher (Cipher/getInstance "RSA/ECB/OAEPWithSHA-256AndMGF1Padding" "BC") sr (SecureRandom.)] (.init cipher Cipher/DECRYPT_MODE ^Key privkey sr) (.doFinal cipher ecek))) (defn- encrypt-with-rsa-pkcs15 [cek pubkey] (let [cipher (Cipher/getInstance "RSA/ECB/PKCS1Padding" "BC") sr (SecureRandom.)] (.init cipher Cipher/ENCRYPT_MODE ^Key pubkey sr) (.doFinal cipher cek))) (defn- decrypt-with-rsa-pkcs15 [ecek privkey] (let [cipher (Cipher/getInstance "RSA/ECB/PKCS1Padding" "BC") sr (SecureRandom.)] (.init cipher Cipher/DECRYPT_MODE ^Key privkey sr) (.doFinal cipher ecek))) (def ^:private aeskw? #{:a128kw :a192kw :a256kw}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Public Api ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn generate [{:keys [key alg enc] :as options}] (case alg :dir (codecs/to-bytes key) (case enc :a128cbc-hs256 (nonce/random-bytes 32) :a192cbc-hs384 (nonce/random-bytes 48) :a256cbc-hs512 (nonce/random-bytes 64) :a128gcm (nonce/random-bytes 16) :a192gcm (nonce/random-bytes 24) :a256gcm (nonce/random-bytes 32)))) (defn encrypt [{:keys [key alg enc cek] :as options}] {:pre [(validate-keylength-for-algorithm key alg)]} (cond (= alg :dir) (byte-array 0) (= alg :rsa-oaep) (encrypt-with-rsaaoep cek key) (= alg :rsa-oaep-256) (encrypt-with-rsaaoep-sha256 cek key) (= alg :rsa-oaep-256) (encrypt-with-rsaaoep-sha256 cek key) (= alg :rsa1_5) (encrypt-with-rsa-pkcs15 cek key) (aeskw? alg) (let [secret (codecs/to-bytes key)] (keys/wrap cek secret :aes)))) (defn decrypt [{:keys [key alg enc ecek] :as options}] (cond (= alg :dir) (codecs/to-bytes key) (= alg :rsa-oaep) (decrypt-with-rsaaoep ecek key) (= alg :rsa-oaep-256) (decrypt-with-rsaaoep-sha256 ecek key) (= alg :rsa1_5) (decrypt-with-rsa-pkcs15 ecek key) (aeskw? alg) (let [secret (codecs/to-bytes key)] (keys/unwrap ecek secret :aes))))
[ { "context": " \"bill-to\" {\"given\" \"Chris\"\n ", "end": 2119, "score": 0.9990214109420776, "start": 2114, "tag": "NAME", "value": "Chris" }, { "context": "e\" 34843\n \"bill-to\" {\"given\" \"Chris\"\n \"family\" \"Dumars\"}", "end": 2423, "score": 0.9966762065887451, "start": 2418, "tag": "NAME", "value": "Chris" } ]
test/com/lmc/monkey/config/config_monkey_test.clj
lmchoi/configmonkey
0
(ns com.lmc.monkey.config.config-monkey-test (:use midje.sweet) (:require [com.lmc.monkey.config.config-monkey :as monkey] [com.lmc.monkey.config.template-reader :as template])) (facts "about finding required attributes based on erb subs" (fact "top-level values" (let [all-entries {"host" "<%= node['some']['host'] %>" "port" "<%= node['some']['port'] %>" "useless" irrelevant}] (template/select-entries-with-erb-placeholders all-entries) => {"host" "<%= node['some']['host'] %>" "port" "<%= node['some']['port'] %>"})) (fact "nested values" (let [all-entries {"invoice" "<%= id %>" "bill-to" {"given" "<%= firstname %>" "useless2" irrelevant} "ship-to" {"given" "<%= firstname %>"} "useless" irrelevant}] (template/select-entries-with-erb-placeholders all-entries) => {"invoice" "<%= id %>" "bill-to" {"given" "<%= firstname %>"} "ship-to" {"given" "<%= firstname %>"}}))) (facts "select from map" (fact "top-level values" (let [required-attributes {"port" "<%= some-port %>" "host" "<%= some-host %>"}] (monkey/select-entries-by-name {"host" "localhost" "port" 1337 "some-other-data" irrelevant} required-attributes) => {"host" "localhost" "port" 1337})) (fact "nested values" (let [required-attributes {"invoice" anything "bill-to" {"given" anything "family" anything}} original-map {"invoice" 34843 "bill-to" {"given" "Chris" "family" "Dumars"} "some-other-data" irrelevant}] (monkey/select-entries-by-name original-map required-attributes) => {"invoice" 34843 "bill-to" {"given" "Chris" "family" "Dumars"}})) (fact "multi level nested values" (let [required-attributes {"invoice" anything "bill-to" {"address" {"city" anything "postal" anything} "family" anything}} original-map {"invoice" 34843 "bill-to" {"given" irrelevant "family" "Dumars" "address" {"city" "Royal Oak" "postal" 48046}}}] (monkey/select-entries-by-name original-map required-attributes) => {"invoice" 34843 "bill-to" {"family" "Dumars" "address" {"city" "Royal Oak" "postal" 48046}}}))) (facts "about munching configs" (fact "munch configs" (monkey/munch {:input "munchy_input" :output "munchy_out"}) => {:dev {"override['local']['host']" "munchy.dev" "override['local']['port']" 1337} :qa {"override['local']['host']" "munchy.qa" "override['local']['port']" 9001}}) (fact "extract template and values" (monkey/extract {:input "munchy_input" :output "munchy_out"}) => {:template {:erb {:host "<%= node['local']['host'] %>", :port "<%= node['local']['port'] %>"}} :values {:dev {:host "munchy.dev" :port 1337} :qa {:host "munchy.qa" :port 9001}}}))
92897
(ns com.lmc.monkey.config.config-monkey-test (:use midje.sweet) (:require [com.lmc.monkey.config.config-monkey :as monkey] [com.lmc.monkey.config.template-reader :as template])) (facts "about finding required attributes based on erb subs" (fact "top-level values" (let [all-entries {"host" "<%= node['some']['host'] %>" "port" "<%= node['some']['port'] %>" "useless" irrelevant}] (template/select-entries-with-erb-placeholders all-entries) => {"host" "<%= node['some']['host'] %>" "port" "<%= node['some']['port'] %>"})) (fact "nested values" (let [all-entries {"invoice" "<%= id %>" "bill-to" {"given" "<%= firstname %>" "useless2" irrelevant} "ship-to" {"given" "<%= firstname %>"} "useless" irrelevant}] (template/select-entries-with-erb-placeholders all-entries) => {"invoice" "<%= id %>" "bill-to" {"given" "<%= firstname %>"} "ship-to" {"given" "<%= firstname %>"}}))) (facts "select from map" (fact "top-level values" (let [required-attributes {"port" "<%= some-port %>" "host" "<%= some-host %>"}] (monkey/select-entries-by-name {"host" "localhost" "port" 1337 "some-other-data" irrelevant} required-attributes) => {"host" "localhost" "port" 1337})) (fact "nested values" (let [required-attributes {"invoice" anything "bill-to" {"given" anything "family" anything}} original-map {"invoice" 34843 "bill-to" {"given" "<NAME>" "family" "Dumars"} "some-other-data" irrelevant}] (monkey/select-entries-by-name original-map required-attributes) => {"invoice" 34843 "bill-to" {"given" "<NAME>" "family" "Dumars"}})) (fact "multi level nested values" (let [required-attributes {"invoice" anything "bill-to" {"address" {"city" anything "postal" anything} "family" anything}} original-map {"invoice" 34843 "bill-to" {"given" irrelevant "family" "Dumars" "address" {"city" "Royal Oak" "postal" 48046}}}] (monkey/select-entries-by-name original-map required-attributes) => {"invoice" 34843 "bill-to" {"family" "Dumars" "address" {"city" "Royal Oak" "postal" 48046}}}))) (facts "about munching configs" (fact "munch configs" (monkey/munch {:input "munchy_input" :output "munchy_out"}) => {:dev {"override['local']['host']" "munchy.dev" "override['local']['port']" 1337} :qa {"override['local']['host']" "munchy.qa" "override['local']['port']" 9001}}) (fact "extract template and values" (monkey/extract {:input "munchy_input" :output "munchy_out"}) => {:template {:erb {:host "<%= node['local']['host'] %>", :port "<%= node['local']['port'] %>"}} :values {:dev {:host "munchy.dev" :port 1337} :qa {:host "munchy.qa" :port 9001}}}))
true
(ns com.lmc.monkey.config.config-monkey-test (:use midje.sweet) (:require [com.lmc.monkey.config.config-monkey :as monkey] [com.lmc.monkey.config.template-reader :as template])) (facts "about finding required attributes based on erb subs" (fact "top-level values" (let [all-entries {"host" "<%= node['some']['host'] %>" "port" "<%= node['some']['port'] %>" "useless" irrelevant}] (template/select-entries-with-erb-placeholders all-entries) => {"host" "<%= node['some']['host'] %>" "port" "<%= node['some']['port'] %>"})) (fact "nested values" (let [all-entries {"invoice" "<%= id %>" "bill-to" {"given" "<%= firstname %>" "useless2" irrelevant} "ship-to" {"given" "<%= firstname %>"} "useless" irrelevant}] (template/select-entries-with-erb-placeholders all-entries) => {"invoice" "<%= id %>" "bill-to" {"given" "<%= firstname %>"} "ship-to" {"given" "<%= firstname %>"}}))) (facts "select from map" (fact "top-level values" (let [required-attributes {"port" "<%= some-port %>" "host" "<%= some-host %>"}] (monkey/select-entries-by-name {"host" "localhost" "port" 1337 "some-other-data" irrelevant} required-attributes) => {"host" "localhost" "port" 1337})) (fact "nested values" (let [required-attributes {"invoice" anything "bill-to" {"given" anything "family" anything}} original-map {"invoice" 34843 "bill-to" {"given" "PI:NAME:<NAME>END_PI" "family" "Dumars"} "some-other-data" irrelevant}] (monkey/select-entries-by-name original-map required-attributes) => {"invoice" 34843 "bill-to" {"given" "PI:NAME:<NAME>END_PI" "family" "Dumars"}})) (fact "multi level nested values" (let [required-attributes {"invoice" anything "bill-to" {"address" {"city" anything "postal" anything} "family" anything}} original-map {"invoice" 34843 "bill-to" {"given" irrelevant "family" "Dumars" "address" {"city" "Royal Oak" "postal" 48046}}}] (monkey/select-entries-by-name original-map required-attributes) => {"invoice" 34843 "bill-to" {"family" "Dumars" "address" {"city" "Royal Oak" "postal" 48046}}}))) (facts "about munching configs" (fact "munch configs" (monkey/munch {:input "munchy_input" :output "munchy_out"}) => {:dev {"override['local']['host']" "munchy.dev" "override['local']['port']" 1337} :qa {"override['local']['host']" "munchy.qa" "override['local']['port']" 9001}}) (fact "extract template and values" (monkey/extract {:input "munchy_input" :output "munchy_out"}) => {:template {:erb {:host "<%= node['local']['host'] %>", :port "<%= node['local']['port'] %>"}} :values {:dev {:host "munchy.dev" :port 1337} :qa {:host "munchy.qa" :port 9001}}}))
[ { "context": "ngled is meant to be as simple as possible, but as Rich Hickey would tell you:\n simple does not mean easy. Fort", "end": 5477, "score": 0.9995341300964355, "start": 5466, "tag": "NAME", "value": "Rich Hickey" } ]
src/devguide/untangled_devguide/A_Quick_Tour.cljs
goodbobk/untangled
1
(ns untangled-devguide.A-Quick-Tour (:require-macros [cljs.test :refer [is]] [untangled-devguide.tutmacros :refer [untangled-app]]) (:require [om.next :as om :refer-macros [defui]] [om.dom :as dom] [untangled.client.core :as uc] [untangled.client.network :as un] [devcards.core :as dc :refer-macros [defcard defcard-doc]] [untangled.client.mutations :as m] [untangled.client.logging :as log] [untangled.client.data-fetch :as df])) (defn increment-counter [counter] (update counter :counter/n inc)) (defui ^:once Counter static uc/InitialAppState (uc/initial-state [this {:keys [id start] :or {id 1 start 1} :as params}] {:counter/id id :counter/n start}) static om/IQuery (query [this] [:counter/id :counter/n]) static om/Ident (ident [this props] [:counter/by-id (:counter/id props)]) Object (render [this] (let [{:keys [counter/id counter/n]} (om/props this) onClick (om/get-computed this :onClick)] (dom/div #js {:className "counter"} (dom/span #js {:className "counter-label"} (str "Current count for counter " id ": ")) (dom/span #js {:className "counter-value"} n) (dom/button #js {:onClick #(onClick id)} "Increment"))))) (def ui-counter (om/factory Counter {:keyfn :counter/id})) (defmethod m/mutate 'counter/inc [{:keys [state] :as env} k {:keys [id] :as params}] {:remote true :action (fn [] (swap! state update-in [:counter/by-id id] increment-counter))}) (defui ^:once CounterPanel static uc/InitialAppState (uc/initial-state [this params] {:counters [(uc/initial-state Counter {:id 1 :start 1})]}) static om/IQuery (query [this] [{:counters (om/get-query Counter)}]) static om/Ident (ident [this props] [:panels/by-kw :counter]) Object (render [this] (let [{:keys [counters]} (om/props this) click-callback (fn [id] (om/transact! this `[(counter/inc {:id ~id}) :counter-sum]))] (dom/div nil ; embedded style: kind of silly in a real app, but doable (dom/style nil ".counter { width: 400px; padding-bottom: 20px; } button { margin-left: 10px; }") (map #(ui-counter (om/computed % {:onClick click-callback})) counters))))) (def ui-counter-panel (om/factory CounterPanel)) (defui ^:once CounterSum static uc/InitialAppState (uc/initial-state [this params] {}) static om/IQuery (query [this] [[:counter/by-id '_]]) Object (render [this] (let [{:keys [counter/by-id]} (om/props this) total (reduce (fn [total c] (+ total (:counter/n c))) 0 (vals by-id))] (dom/div nil (str "Grand total: " total))))) (def ui-counter-sum (om/factory CounterSum)) (defui ^:once Root static uc/InitialAppState (uc/initial-state [this params] {:panel (uc/initial-state CounterPanel {})}) static om/IQuery (query [this] [:ui/loading-data {:panel (om/get-query CounterPanel)} {:counter-sum (om/get-query CounterSum)}]) Object (render [this] (let [{:keys [ui/loading-data counter-sum panel]} (om/props this)] (dom/div nil (when loading-data (dom/span #js {:style #js {:float "right"}} "Loading...")) (ui-counter-panel panel) (ui-counter-sum counter-sum))))) ;; Simulated Server ; Servers could keep state in RAM (defonce server-state (atom {:THIS_IS_SERVER_STATE true :counters {1 {:counter/id 1 :counter/n 44} 2 {:counter/id 2 :counter/n 23} 3 {:counter/id 3 :counter/n 99}}})) ; The server queries are handled by returning a map with a :value key, which will be placed in the appropriate ; response format (defn read-handler [{:keys [ast state]} k p] (log/info "SERVER query for " k) (case k ; When querying for :all-counters, return the complete set of values in our server counter db (atom in RAM) :all-counters {:value (-> (get @state :counters) vals vec)} nil)) ; The server mutations are handled by returning a map with a :action key whose value is the function that will ; cause the change on the server (defn write-handler [env k p] (log/info "SERVER mutation for " k " with params " p) (case k ; When asked to increment a counter on the server, do so by updating in-memory atom database 'counter/inc (let [{:keys [id]} p] {:action (fn [] (swap! server-state update-in [:counters id :counter/n] inc) nil)}) nil)) ; Om Next query parser. Calls read/write handlers with keywords from the query (def server-parser (om/parser {:read read-handler :mutate write-handler})) ; Simulated server. You'd never write this part (defn server [env tx] (server-parser (assoc env :state server-state) tx)) ; Networking that pretends to talk to server. You'd never write this part (defrecord MockNetwork [complete-app] un/UntangledNetwork (send [this edn ok err] (let [resp (server {} edn)] ; simulates a network delay: (js/setTimeout #(ok resp) 700))) (start [this app] (assoc this :complete-app app))) (defcard-doc "# Quick Tour Untangled is meant to be as simple as possible, but as Rich Hickey would tell you: simple does not mean easy. Fortunately, hard vs. easy is something you can fix just by learning. Om Next (the lower layer of Untangled) takes a very progressive approach to web development, and as such requires that you understand some new concepts. This is *by far* the most difficult part of adapting to Untangled. In this quick tour our intention is to show you a full-stack Untangled application. We hope that as you read this Quick Start you will start to comprehend how *simple* the resulting structure is: - No controllers are needed, ever. - Networking becomes mostly transparent, and gives a synchronous reasoning model (by default) - Server and client code structure are identical. In fact, this tour leverages this fact to simulate server code in the browser that is identical to what you'd *put* on the server. - The reasoning at the UI layer can be completely local. - The reasoning at the model layer can be completely local. - The render refresh story is mostly automatic, and where it isn't, it is completely abstracted from the UI structure to ease developer reasoning. If you're coming from Om Next, you should know that Untangled is *not* a competing project. Untangled is a set of thin libraries that provide default implementations of all of the artifacts you'd normally have to write to make a full-stack Om Next application. In many cases Untangled is required to 'make a call' about how to do something. When it does, our documentation tries to discuss the relative merits and costs. The name 'Untangled' is *not* meant to be a commentary on Om Next, but instead on the general state of web development circa 2016. Om Next and Untangled are two layers of a solution that makes things simpler for you. ## Om Next Components can use Stock React components The first major strength is that Om Next (and therefore Untangled) integrates with stock React components. So, if you already understand React then you already have a head start. If you know nothing of React, you should eventually read more about it. For now, we'll cover everything you need to know. ## The Rendering Model Untangled recommends you treat the UI as a pure function that, given the state of the application 'right now', can be re-rendered on each frame (change of state). ``` App state -> render -> DOM ``` This is a key part of the simplification: You don't have to worry how to keep bits of UI up-to-date. There is a key difference that users of other frameworks might miss here: not only do you *not* have to figure out the complexities of keeping the DOM up to date: there is no mutation or hidden local state to trip you up. As you move from state to state (a sequence of app states, each of which is itself immutable) you can pretend as if render re-creates the entire DOM. This means you can test and reason about your UI in isolation from all other logic! ## Core Model Concepts Untangled uses a very simple (default Om Next) database format for the application state in the browser. Basically this format is a normalized graph database made of maps and vectors. Anything you show on the UI is structured into this database, and can be queried to create arbitrary UI trees for display. A given item in this database can be shown in as many places on the UI as makes sense. The fact that the database is *normalized* means that changing the item once in the database will result in being able to refresh all displayed versions easily. The model manipulation thus maintains the desired local reasoning model (of entries in database tables). You write functions that know how to manipulate specific 'kinds' of things in the database, and think nothing of the UI. For example, say we have a counter that we'd like to represent with this data structure: ``` { :counter/id 1 :counter/n 22 } ``` We can write simple functions to manipulate counters: " (dc/mkdn-pprint-source increment-counter) " and think about that counter as a complete abstract thing (and write tests and clojure specs for it, etc.). The Untangled database table for counters then looks something like this: ``` { :counter/by-id { 1 { :counter/id 1 :counter/n 1 } 2 { :counter/id 2 :counter/n 9 } ...}} ``` A table is just an entry in the database (map) that, by convention, is keyed with a keyword whose namespace indicates the kind of thing in the table, and whose name indicates how it is indexed. The k-v pairs in the table are the keys (of the implied index) and the values of the actual data. The general app state is held in a top-level atom. So, updating any object in the database generally takes the form: ``` (swap! app-state-atom update-in [:table/key id] operation) ``` or in our example case: ``` (swap! app-state-atom update-in [:counter/by-id 1] increment-counter) ``` NOTE: You still need to know *where* to put this code, and how to find/access the `app-state-atom`. ## Mutations as Abstract Transactions In Untangled, you don't do model twiddling on the UI. There is a clear separation of concerns for several good reasons: - It generally pays not to mix your low-level logic with the UI. - The concept of an abstract mutation can isolate the UI from networking, server interactions, and async thinking. - Abstract mutations give nice auditing and comprehension on both client and server. The main UI entry point for affecting a change is the `om/transact!` function. This function lets you submit an abstract sequence of operations that you'd like to accomplish, and isolates the UI author from the details of implementing that behavior (and of even having to know things like 'will that happen locally or on the server?'). The concrete artifacts you'll see in Untangled code are the invocation of the `transact!`, and the implementation of the operations listed in the transaction: ``` (om/transact! this `[(counter/inc {:id ~id})]) ``` in the above transaction, we must use Clojure syntax quoting so that we can list an abstract mutation (which looks like a function call, but is not) and parameters that themselves are derived from the environment (in this case an id). If you're not a Clojure(script) programmer, we understand that the above expression looks a little scary. The '&grave;' means 'treat the following thing literally', and the '~' means 'don't treat this thing literally'. It's a way of keeping the compiler from treating the increment as a function while still being able to embed `id` from the local execution environment. The concrete implementation of the mutation on the model side looks like this: ``` (defmethod m/mutate 'counter/inc [{:keys [state] :as env} k {:keys [id] :as params}] { :action (fn [] (swap! state update-in [:counter/by-id id] increment-counter))}) ``` This looks a little hairy at first until you notice the primary guts are just what we talked about earlier in the model manipulation: it's just an `update-in`. The wrapping is a pretty consistent pattern: the app state and parameters are passed into a multimethod, which is dispatched on the symbol mentioned in the `transact!`. The basics are: - You key on a symbol instead of writing a function with that symbol name (this is what gives an abstraction that is already 'network ready') - You return a map - The `:action` key of that map specifies a function to run to accomplish the optimistic update to the browser database. The use of a thunk (function) here is what helps isolate asynchronous internals and networking from synchronous abstract reasoning. When you want to interact with a server, you need merely change it to: ``` (defmethod m/mutate 'counter/inc [{:keys [state] :as env} k {:keys [id] :as params}] { :remote true ; <---- this is all!!! :action (fn [] (swap! state update-in [:counter/by-id id] increment-counter))}) ``` and then write a similar function on the server that has an `:action` to affect the change on the server! At first this seems like a bit of overkill on the boilerplate until you realize that there are a number of things being handled here: - Sychronous *reasoning* about most aspects of the application. - Local optimistic (immediate) updates (through `:action`) - Automatically plumbed server interactions (triggered through `:remote` at transaction time) - Use of the same abstract symbol for the operation on the client and server. - Operations in the UI and on the server are identical in appearance. - Consistent implementation pattern for model manipulations on the client and server. - The operations 'on the wire' read like abstract function calls, and lead to easy auditing and reasoning, or even easy-to-implement CQRS architectures. ## An Example Let's write a simple application that shows counters that can be incremented. Each counter has an ID and a value (n). ### Making a Counter component Here's the Untangled implementation of that UI component: " (dc/mkdn-pprint-source Counter) " (the `^:once` is helper metadata that ensures correct operation of development-time hot code reload) It looks a bit like a `defrecord` implementing protocols. Here is a description of the parts: - InitialAppState : Represents how to make an instance of the counter in the browser database. Parameters are supported for making more than one on the UI. This function should return a map that matches the properties asked for in the query. - IQuery : Represents what data is needed for the UI. In this case, a list of properties that exist (keys of the map that represents counters in the database). Note we can tune this up/down depending on the needs of the UI. Counters could have labels, owners, purposes, etc. - Ident : Represents the table/ID of the database data for the component. This is a function that, given an example of a counter, will return a vector that has two elements: the table and the ID of the entry. This is used to assist in auto-normalization of the browser database, and also with UI refreshes of components that display the same data. - Object/render : This is the (pure) function that outputs what a Counter should look like on the DOM The incoming data from the database comes in via `om/props`, and things like callbacks come in via a mechanism known as the 'computed' data (e.g. stuff that isn't in the database, but is generated by the UI, such as callbacks). A `defui` generates a React Component (class). In order to render an instance of a Counter, we must make an element factory: " (dc/mkdn-pprint-source ui-counter) " If more than one of something can appear in the UI as siblings, you must specify a `:keyfn` that helps React distinguish the DOM elements. The most important point is that you can reason about `Counter` in a totally local way. ### Combining Counters into a Panel Lets assume we want to display some arbitrary number of counters together in a panel. We can encode that (and the element factory) as: " (dc/mkdn-pprint-source CounterPanel) (dc/mkdn-pprint-source ui-counter-panel) " Note the mirroring again between the initial state and the query. The initial state provides an initial model of what should be in the database *for the component at hand*, and the query indicates which bits of that state are required for that same local component. In this case the query contains a map, which is the query syntax for a JOIN. You can read this query as 'Query for :counters, which is a JOIN on Counter'. Note that since initial state is setting up a vector of counters, the implied result will be a to-many JOIN. The cardinality of JOINS is derived from the structure of the actual database, NOT the query. The join is necessary because this component will be rendering Counter components. The panel should not need to know anything concrete about the implementation of Counter: only that it has a query, initial state, and a way to render. The render is very similar to Counter's. The queried data will appear in props: pull it out, and then render it. Note the use of `ui-counter`, which is the DOM element factory for `Counter`. Finally, we include a callback. The counter has the 'Increment' button, but we've connected that from the counter UI back through to an implementation of a callback via 'computed' properties. This is a common pattern. In this simple example the callback structure was added to demonstrate what it looks like. One could argue that the counter could update itself (while maintaining local reasoning). The implementation of the `counter/inc` mutation was shown earlier. There are many important points to make here, but we would like to stress the fact that the UI has no idea *how* counters are implemented, *if* that logic includes server interactions, etc. There are no nested callbacks of callbacks, no XhrIO mixed into the UI, and interestingly: no need for controller at all! A simple pattern of updating an abstraction in a database is all you need. There is one exception: That weird inclusion of `:counter-sum` in the transaction. We'll explain that shortly. ### Adding the Panel to a Root element Untangled UI (and DOM UI in general) forms a tree. All trees must eventually have a root. The UI composition (and the composition of queries and initial state) must continue to your UI Root. So, in our case our root looks like this: " (dc/mkdn-pprint-source Root) " The initial state is a composition from the nested panel, as is the query. We add in two additional things here: - `:ui/loading-data` is a special key, available at the root, that is true when data is loading over the network - We compose in another component we've yet to discuss (which sums all counters). We'll talk more about that shortly There should be no surprises here. It is the same pattern all over again, except Root does not need an `Ident`, since it need not live in a database table. The data for root can just be a standalone map entry (as can other things. There is *no rule that absolutely everything* lives in tables. Top-level entries for other data structures are also useful). ### Starting up the App Normally you create an Untangled application and mount it on a DIV in your real HTML DOM. We'll cover that later in the Guide. Here we're in devcards and we have a helper to do that. It accepts the same basic parameters as `make-untangled-app`, but mounts the resulting application in a devcard: ``` (defcard SampleApp (untangled-app Root :started-callback (fn [app] (log/info \"Application (re)started\") (df/load app :all-counters Counter {:target [:panels/by-kw :counter :counters]})))) ``` In this quick tour we're faking the networking so you can easily explore what the server and client look like in a single file. The `:started-callback` is triggered as the application loads. This is where you can use Untangled's networking layer to pre-fetch data from the server. In our case, we want to get all of the counters. Note that we can (and should) use UI queries. This triggers auto-normalization of the response. The `:target` option indicates that the loaded data should be places in the database at the given path (usually 1 to 3 keywords in the vector, since the db is normalized). In this case the ident of the target panel gives the location of the component that wants the counters, and the `:counters` property of that component is where it wants to know about them. Therefore the desired target path is the ident + the property as a vector. You'll need to understand a bit more about the structure of the database to completely understand this code, but you see it is really quite simple: pull `:all-counters` from the server-side database, and put them on the panel according to the location (known via Ident) of the panel data in the database. ### Server Implementation We're representing our server database as an in-RAM atom: " (dc/mkdn-pprint-source server-state) " #### Server Queries To respond to the `:all-counters` query, we simply write a function that returns the correct data and hook it into the server engine. In real server code this is commonly done with a multimethod (your choice). The take-away here is that you write very little 'plumbing'...just the logic to get the data, and return it in a map with a `:value` key: " (dc/mkdn-pprint-source read-handler) " #### Server Mutations We mentioned earlier that turning a client mutation into something that also happens on the server is as simple as adding a `:remote true` to the response of the mutation function. The server code is equally trivial (again, in a real server you'd typically use a multimethod): " (dc/mkdn-pprint-source write-handler)) (defcard mock-server-state (dom/div nil "The state shown below is the active state of the mock server for the FinalResult card.") server-state {:watch-atom true :inspect-data true}) (defcard FinalResult "Below is the final result of the above application, complete with faked server interactions (we use setTimeout to fake network latency). If you reload this page and jump to the bottom, you'll see the initial server loading. (If you see an error related to mounting a DOM node, try reloading the page). You can see the mocked server processing take place in a delayed fashion in the Javascript Console of your browser. NOTE: The map shown at the bottom is our simulated server state. Note how, if you click rapidly on increment, that the server state lags behind (because of our simulated delay). You can see how the UI remains responsive even though the server is lagging." (untangled-app Root :started-callback (fn [app] (log/info "Application (re)started") (df/load app :all-counters Counter {:target [:panels/by-kw :counter :counters]})) :networking (map->MockNetwork {})) {} {:inspect-data true}) (defcard-doc "### The Grand Total You'll notice that there is a part of the UI that is tracking the grand total of the counters. This component shows a few more interesting features: Rendering derived values, querying entire tables, and refreshing derived UI. This is the implementation of the counter UI: " (dc/mkdn-pprint-source CounterSum) " The query is interesting. Queries are vectors of things you want. When one of those things is a two-element vector it knows you want an entry in a table (e.g. [:counter/by-id 3]). If you use the special symbol `'_`, then you're asking for an entire top-level entry (in this case a whole table). Thus we can easily use that to calculate our desired UI. However, it turns out that we have a problem: Nothing in Untangled or Om Next will trigger this component to refresh when an individual counter changes! The mutations are abstract, and even though you can imagine that the UI refresh is a pure function that recreates the DOM, it is in fact optimized to only refresh the bits that have changed. Since the data that changed wasn't a counter, Om Next will short-circuit the sum for efficiency. This is the point of the earlier mysterious `:counter-sum` in the `transact!`. Any keyword that appears in a transaction will cause Om to re-render any component that queried for that property (in our case the Root UI component). These are called 'follow-on reads', to imply that 'anything that reads the given property should be asked to re-read it (and implicitly, this means it will re-render if the value has changed)'. You can, of course, play with the source code of this example in the devcards. We certainly hope you will continue reading into the details of all of these features. You should start with the [next chapter](#!/untangled_devguide.B_UI) on UI. ")
95018
(ns untangled-devguide.A-Quick-Tour (:require-macros [cljs.test :refer [is]] [untangled-devguide.tutmacros :refer [untangled-app]]) (:require [om.next :as om :refer-macros [defui]] [om.dom :as dom] [untangled.client.core :as uc] [untangled.client.network :as un] [devcards.core :as dc :refer-macros [defcard defcard-doc]] [untangled.client.mutations :as m] [untangled.client.logging :as log] [untangled.client.data-fetch :as df])) (defn increment-counter [counter] (update counter :counter/n inc)) (defui ^:once Counter static uc/InitialAppState (uc/initial-state [this {:keys [id start] :or {id 1 start 1} :as params}] {:counter/id id :counter/n start}) static om/IQuery (query [this] [:counter/id :counter/n]) static om/Ident (ident [this props] [:counter/by-id (:counter/id props)]) Object (render [this] (let [{:keys [counter/id counter/n]} (om/props this) onClick (om/get-computed this :onClick)] (dom/div #js {:className "counter"} (dom/span #js {:className "counter-label"} (str "Current count for counter " id ": ")) (dom/span #js {:className "counter-value"} n) (dom/button #js {:onClick #(onClick id)} "Increment"))))) (def ui-counter (om/factory Counter {:keyfn :counter/id})) (defmethod m/mutate 'counter/inc [{:keys [state] :as env} k {:keys [id] :as params}] {:remote true :action (fn [] (swap! state update-in [:counter/by-id id] increment-counter))}) (defui ^:once CounterPanel static uc/InitialAppState (uc/initial-state [this params] {:counters [(uc/initial-state Counter {:id 1 :start 1})]}) static om/IQuery (query [this] [{:counters (om/get-query Counter)}]) static om/Ident (ident [this props] [:panels/by-kw :counter]) Object (render [this] (let [{:keys [counters]} (om/props this) click-callback (fn [id] (om/transact! this `[(counter/inc {:id ~id}) :counter-sum]))] (dom/div nil ; embedded style: kind of silly in a real app, but doable (dom/style nil ".counter { width: 400px; padding-bottom: 20px; } button { margin-left: 10px; }") (map #(ui-counter (om/computed % {:onClick click-callback})) counters))))) (def ui-counter-panel (om/factory CounterPanel)) (defui ^:once CounterSum static uc/InitialAppState (uc/initial-state [this params] {}) static om/IQuery (query [this] [[:counter/by-id '_]]) Object (render [this] (let [{:keys [counter/by-id]} (om/props this) total (reduce (fn [total c] (+ total (:counter/n c))) 0 (vals by-id))] (dom/div nil (str "Grand total: " total))))) (def ui-counter-sum (om/factory CounterSum)) (defui ^:once Root static uc/InitialAppState (uc/initial-state [this params] {:panel (uc/initial-state CounterPanel {})}) static om/IQuery (query [this] [:ui/loading-data {:panel (om/get-query CounterPanel)} {:counter-sum (om/get-query CounterSum)}]) Object (render [this] (let [{:keys [ui/loading-data counter-sum panel]} (om/props this)] (dom/div nil (when loading-data (dom/span #js {:style #js {:float "right"}} "Loading...")) (ui-counter-panel panel) (ui-counter-sum counter-sum))))) ;; Simulated Server ; Servers could keep state in RAM (defonce server-state (atom {:THIS_IS_SERVER_STATE true :counters {1 {:counter/id 1 :counter/n 44} 2 {:counter/id 2 :counter/n 23} 3 {:counter/id 3 :counter/n 99}}})) ; The server queries are handled by returning a map with a :value key, which will be placed in the appropriate ; response format (defn read-handler [{:keys [ast state]} k p] (log/info "SERVER query for " k) (case k ; When querying for :all-counters, return the complete set of values in our server counter db (atom in RAM) :all-counters {:value (-> (get @state :counters) vals vec)} nil)) ; The server mutations are handled by returning a map with a :action key whose value is the function that will ; cause the change on the server (defn write-handler [env k p] (log/info "SERVER mutation for " k " with params " p) (case k ; When asked to increment a counter on the server, do so by updating in-memory atom database 'counter/inc (let [{:keys [id]} p] {:action (fn [] (swap! server-state update-in [:counters id :counter/n] inc) nil)}) nil)) ; Om Next query parser. Calls read/write handlers with keywords from the query (def server-parser (om/parser {:read read-handler :mutate write-handler})) ; Simulated server. You'd never write this part (defn server [env tx] (server-parser (assoc env :state server-state) tx)) ; Networking that pretends to talk to server. You'd never write this part (defrecord MockNetwork [complete-app] un/UntangledNetwork (send [this edn ok err] (let [resp (server {} edn)] ; simulates a network delay: (js/setTimeout #(ok resp) 700))) (start [this app] (assoc this :complete-app app))) (defcard-doc "# Quick Tour Untangled is meant to be as simple as possible, but as <NAME> would tell you: simple does not mean easy. Fortunately, hard vs. easy is something you can fix just by learning. Om Next (the lower layer of Untangled) takes a very progressive approach to web development, and as such requires that you understand some new concepts. This is *by far* the most difficult part of adapting to Untangled. In this quick tour our intention is to show you a full-stack Untangled application. We hope that as you read this Quick Start you will start to comprehend how *simple* the resulting structure is: - No controllers are needed, ever. - Networking becomes mostly transparent, and gives a synchronous reasoning model (by default) - Server and client code structure are identical. In fact, this tour leverages this fact to simulate server code in the browser that is identical to what you'd *put* on the server. - The reasoning at the UI layer can be completely local. - The reasoning at the model layer can be completely local. - The render refresh story is mostly automatic, and where it isn't, it is completely abstracted from the UI structure to ease developer reasoning. If you're coming from Om Next, you should know that Untangled is *not* a competing project. Untangled is a set of thin libraries that provide default implementations of all of the artifacts you'd normally have to write to make a full-stack Om Next application. In many cases Untangled is required to 'make a call' about how to do something. When it does, our documentation tries to discuss the relative merits and costs. The name 'Untangled' is *not* meant to be a commentary on Om Next, but instead on the general state of web development circa 2016. Om Next and Untangled are two layers of a solution that makes things simpler for you. ## Om Next Components can use Stock React components The first major strength is that Om Next (and therefore Untangled) integrates with stock React components. So, if you already understand React then you already have a head start. If you know nothing of React, you should eventually read more about it. For now, we'll cover everything you need to know. ## The Rendering Model Untangled recommends you treat the UI as a pure function that, given the state of the application 'right now', can be re-rendered on each frame (change of state). ``` App state -> render -> DOM ``` This is a key part of the simplification: You don't have to worry how to keep bits of UI up-to-date. There is a key difference that users of other frameworks might miss here: not only do you *not* have to figure out the complexities of keeping the DOM up to date: there is no mutation or hidden local state to trip you up. As you move from state to state (a sequence of app states, each of which is itself immutable) you can pretend as if render re-creates the entire DOM. This means you can test and reason about your UI in isolation from all other logic! ## Core Model Concepts Untangled uses a very simple (default Om Next) database format for the application state in the browser. Basically this format is a normalized graph database made of maps and vectors. Anything you show on the UI is structured into this database, and can be queried to create arbitrary UI trees for display. A given item in this database can be shown in as many places on the UI as makes sense. The fact that the database is *normalized* means that changing the item once in the database will result in being able to refresh all displayed versions easily. The model manipulation thus maintains the desired local reasoning model (of entries in database tables). You write functions that know how to manipulate specific 'kinds' of things in the database, and think nothing of the UI. For example, say we have a counter that we'd like to represent with this data structure: ``` { :counter/id 1 :counter/n 22 } ``` We can write simple functions to manipulate counters: " (dc/mkdn-pprint-source increment-counter) " and think about that counter as a complete abstract thing (and write tests and clojure specs for it, etc.). The Untangled database table for counters then looks something like this: ``` { :counter/by-id { 1 { :counter/id 1 :counter/n 1 } 2 { :counter/id 2 :counter/n 9 } ...}} ``` A table is just an entry in the database (map) that, by convention, is keyed with a keyword whose namespace indicates the kind of thing in the table, and whose name indicates how it is indexed. The k-v pairs in the table are the keys (of the implied index) and the values of the actual data. The general app state is held in a top-level atom. So, updating any object in the database generally takes the form: ``` (swap! app-state-atom update-in [:table/key id] operation) ``` or in our example case: ``` (swap! app-state-atom update-in [:counter/by-id 1] increment-counter) ``` NOTE: You still need to know *where* to put this code, and how to find/access the `app-state-atom`. ## Mutations as Abstract Transactions In Untangled, you don't do model twiddling on the UI. There is a clear separation of concerns for several good reasons: - It generally pays not to mix your low-level logic with the UI. - The concept of an abstract mutation can isolate the UI from networking, server interactions, and async thinking. - Abstract mutations give nice auditing and comprehension on both client and server. The main UI entry point for affecting a change is the `om/transact!` function. This function lets you submit an abstract sequence of operations that you'd like to accomplish, and isolates the UI author from the details of implementing that behavior (and of even having to know things like 'will that happen locally or on the server?'). The concrete artifacts you'll see in Untangled code are the invocation of the `transact!`, and the implementation of the operations listed in the transaction: ``` (om/transact! this `[(counter/inc {:id ~id})]) ``` in the above transaction, we must use Clojure syntax quoting so that we can list an abstract mutation (which looks like a function call, but is not) and parameters that themselves are derived from the environment (in this case an id). If you're not a Clojure(script) programmer, we understand that the above expression looks a little scary. The '&grave;' means 'treat the following thing literally', and the '~' means 'don't treat this thing literally'. It's a way of keeping the compiler from treating the increment as a function while still being able to embed `id` from the local execution environment. The concrete implementation of the mutation on the model side looks like this: ``` (defmethod m/mutate 'counter/inc [{:keys [state] :as env} k {:keys [id] :as params}] { :action (fn [] (swap! state update-in [:counter/by-id id] increment-counter))}) ``` This looks a little hairy at first until you notice the primary guts are just what we talked about earlier in the model manipulation: it's just an `update-in`. The wrapping is a pretty consistent pattern: the app state and parameters are passed into a multimethod, which is dispatched on the symbol mentioned in the `transact!`. The basics are: - You key on a symbol instead of writing a function with that symbol name (this is what gives an abstraction that is already 'network ready') - You return a map - The `:action` key of that map specifies a function to run to accomplish the optimistic update to the browser database. The use of a thunk (function) here is what helps isolate asynchronous internals and networking from synchronous abstract reasoning. When you want to interact with a server, you need merely change it to: ``` (defmethod m/mutate 'counter/inc [{:keys [state] :as env} k {:keys [id] :as params}] { :remote true ; <---- this is all!!! :action (fn [] (swap! state update-in [:counter/by-id id] increment-counter))}) ``` and then write a similar function on the server that has an `:action` to affect the change on the server! At first this seems like a bit of overkill on the boilerplate until you realize that there are a number of things being handled here: - Sychronous *reasoning* about most aspects of the application. - Local optimistic (immediate) updates (through `:action`) - Automatically plumbed server interactions (triggered through `:remote` at transaction time) - Use of the same abstract symbol for the operation on the client and server. - Operations in the UI and on the server are identical in appearance. - Consistent implementation pattern for model manipulations on the client and server. - The operations 'on the wire' read like abstract function calls, and lead to easy auditing and reasoning, or even easy-to-implement CQRS architectures. ## An Example Let's write a simple application that shows counters that can be incremented. Each counter has an ID and a value (n). ### Making a Counter component Here's the Untangled implementation of that UI component: " (dc/mkdn-pprint-source Counter) " (the `^:once` is helper metadata that ensures correct operation of development-time hot code reload) It looks a bit like a `defrecord` implementing protocols. Here is a description of the parts: - InitialAppState : Represents how to make an instance of the counter in the browser database. Parameters are supported for making more than one on the UI. This function should return a map that matches the properties asked for in the query. - IQuery : Represents what data is needed for the UI. In this case, a list of properties that exist (keys of the map that represents counters in the database). Note we can tune this up/down depending on the needs of the UI. Counters could have labels, owners, purposes, etc. - Ident : Represents the table/ID of the database data for the component. This is a function that, given an example of a counter, will return a vector that has two elements: the table and the ID of the entry. This is used to assist in auto-normalization of the browser database, and also with UI refreshes of components that display the same data. - Object/render : This is the (pure) function that outputs what a Counter should look like on the DOM The incoming data from the database comes in via `om/props`, and things like callbacks come in via a mechanism known as the 'computed' data (e.g. stuff that isn't in the database, but is generated by the UI, such as callbacks). A `defui` generates a React Component (class). In order to render an instance of a Counter, we must make an element factory: " (dc/mkdn-pprint-source ui-counter) " If more than one of something can appear in the UI as siblings, you must specify a `:keyfn` that helps React distinguish the DOM elements. The most important point is that you can reason about `Counter` in a totally local way. ### Combining Counters into a Panel Lets assume we want to display some arbitrary number of counters together in a panel. We can encode that (and the element factory) as: " (dc/mkdn-pprint-source CounterPanel) (dc/mkdn-pprint-source ui-counter-panel) " Note the mirroring again between the initial state and the query. The initial state provides an initial model of what should be in the database *for the component at hand*, and the query indicates which bits of that state are required for that same local component. In this case the query contains a map, which is the query syntax for a JOIN. You can read this query as 'Query for :counters, which is a JOIN on Counter'. Note that since initial state is setting up a vector of counters, the implied result will be a to-many JOIN. The cardinality of JOINS is derived from the structure of the actual database, NOT the query. The join is necessary because this component will be rendering Counter components. The panel should not need to know anything concrete about the implementation of Counter: only that it has a query, initial state, and a way to render. The render is very similar to Counter's. The queried data will appear in props: pull it out, and then render it. Note the use of `ui-counter`, which is the DOM element factory for `Counter`. Finally, we include a callback. The counter has the 'Increment' button, but we've connected that from the counter UI back through to an implementation of a callback via 'computed' properties. This is a common pattern. In this simple example the callback structure was added to demonstrate what it looks like. One could argue that the counter could update itself (while maintaining local reasoning). The implementation of the `counter/inc` mutation was shown earlier. There are many important points to make here, but we would like to stress the fact that the UI has no idea *how* counters are implemented, *if* that logic includes server interactions, etc. There are no nested callbacks of callbacks, no XhrIO mixed into the UI, and interestingly: no need for controller at all! A simple pattern of updating an abstraction in a database is all you need. There is one exception: That weird inclusion of `:counter-sum` in the transaction. We'll explain that shortly. ### Adding the Panel to a Root element Untangled UI (and DOM UI in general) forms a tree. All trees must eventually have a root. The UI composition (and the composition of queries and initial state) must continue to your UI Root. So, in our case our root looks like this: " (dc/mkdn-pprint-source Root) " The initial state is a composition from the nested panel, as is the query. We add in two additional things here: - `:ui/loading-data` is a special key, available at the root, that is true when data is loading over the network - We compose in another component we've yet to discuss (which sums all counters). We'll talk more about that shortly There should be no surprises here. It is the same pattern all over again, except Root does not need an `Ident`, since it need not live in a database table. The data for root can just be a standalone map entry (as can other things. There is *no rule that absolutely everything* lives in tables. Top-level entries for other data structures are also useful). ### Starting up the App Normally you create an Untangled application and mount it on a DIV in your real HTML DOM. We'll cover that later in the Guide. Here we're in devcards and we have a helper to do that. It accepts the same basic parameters as `make-untangled-app`, but mounts the resulting application in a devcard: ``` (defcard SampleApp (untangled-app Root :started-callback (fn [app] (log/info \"Application (re)started\") (df/load app :all-counters Counter {:target [:panels/by-kw :counter :counters]})))) ``` In this quick tour we're faking the networking so you can easily explore what the server and client look like in a single file. The `:started-callback` is triggered as the application loads. This is where you can use Untangled's networking layer to pre-fetch data from the server. In our case, we want to get all of the counters. Note that we can (and should) use UI queries. This triggers auto-normalization of the response. The `:target` option indicates that the loaded data should be places in the database at the given path (usually 1 to 3 keywords in the vector, since the db is normalized). In this case the ident of the target panel gives the location of the component that wants the counters, and the `:counters` property of that component is where it wants to know about them. Therefore the desired target path is the ident + the property as a vector. You'll need to understand a bit more about the structure of the database to completely understand this code, but you see it is really quite simple: pull `:all-counters` from the server-side database, and put them on the panel according to the location (known via Ident) of the panel data in the database. ### Server Implementation We're representing our server database as an in-RAM atom: " (dc/mkdn-pprint-source server-state) " #### Server Queries To respond to the `:all-counters` query, we simply write a function that returns the correct data and hook it into the server engine. In real server code this is commonly done with a multimethod (your choice). The take-away here is that you write very little 'plumbing'...just the logic to get the data, and return it in a map with a `:value` key: " (dc/mkdn-pprint-source read-handler) " #### Server Mutations We mentioned earlier that turning a client mutation into something that also happens on the server is as simple as adding a `:remote true` to the response of the mutation function. The server code is equally trivial (again, in a real server you'd typically use a multimethod): " (dc/mkdn-pprint-source write-handler)) (defcard mock-server-state (dom/div nil "The state shown below is the active state of the mock server for the FinalResult card.") server-state {:watch-atom true :inspect-data true}) (defcard FinalResult "Below is the final result of the above application, complete with faked server interactions (we use setTimeout to fake network latency). If you reload this page and jump to the bottom, you'll see the initial server loading. (If you see an error related to mounting a DOM node, try reloading the page). You can see the mocked server processing take place in a delayed fashion in the Javascript Console of your browser. NOTE: The map shown at the bottom is our simulated server state. Note how, if you click rapidly on increment, that the server state lags behind (because of our simulated delay). You can see how the UI remains responsive even though the server is lagging." (untangled-app Root :started-callback (fn [app] (log/info "Application (re)started") (df/load app :all-counters Counter {:target [:panels/by-kw :counter :counters]})) :networking (map->MockNetwork {})) {} {:inspect-data true}) (defcard-doc "### The Grand Total You'll notice that there is a part of the UI that is tracking the grand total of the counters. This component shows a few more interesting features: Rendering derived values, querying entire tables, and refreshing derived UI. This is the implementation of the counter UI: " (dc/mkdn-pprint-source CounterSum) " The query is interesting. Queries are vectors of things you want. When one of those things is a two-element vector it knows you want an entry in a table (e.g. [:counter/by-id 3]). If you use the special symbol `'_`, then you're asking for an entire top-level entry (in this case a whole table). Thus we can easily use that to calculate our desired UI. However, it turns out that we have a problem: Nothing in Untangled or Om Next will trigger this component to refresh when an individual counter changes! The mutations are abstract, and even though you can imagine that the UI refresh is a pure function that recreates the DOM, it is in fact optimized to only refresh the bits that have changed. Since the data that changed wasn't a counter, Om Next will short-circuit the sum for efficiency. This is the point of the earlier mysterious `:counter-sum` in the `transact!`. Any keyword that appears in a transaction will cause Om to re-render any component that queried for that property (in our case the Root UI component). These are called 'follow-on reads', to imply that 'anything that reads the given property should be asked to re-read it (and implicitly, this means it will re-render if the value has changed)'. You can, of course, play with the source code of this example in the devcards. We certainly hope you will continue reading into the details of all of these features. You should start with the [next chapter](#!/untangled_devguide.B_UI) on UI. ")
true
(ns untangled-devguide.A-Quick-Tour (:require-macros [cljs.test :refer [is]] [untangled-devguide.tutmacros :refer [untangled-app]]) (:require [om.next :as om :refer-macros [defui]] [om.dom :as dom] [untangled.client.core :as uc] [untangled.client.network :as un] [devcards.core :as dc :refer-macros [defcard defcard-doc]] [untangled.client.mutations :as m] [untangled.client.logging :as log] [untangled.client.data-fetch :as df])) (defn increment-counter [counter] (update counter :counter/n inc)) (defui ^:once Counter static uc/InitialAppState (uc/initial-state [this {:keys [id start] :or {id 1 start 1} :as params}] {:counter/id id :counter/n start}) static om/IQuery (query [this] [:counter/id :counter/n]) static om/Ident (ident [this props] [:counter/by-id (:counter/id props)]) Object (render [this] (let [{:keys [counter/id counter/n]} (om/props this) onClick (om/get-computed this :onClick)] (dom/div #js {:className "counter"} (dom/span #js {:className "counter-label"} (str "Current count for counter " id ": ")) (dom/span #js {:className "counter-value"} n) (dom/button #js {:onClick #(onClick id)} "Increment"))))) (def ui-counter (om/factory Counter {:keyfn :counter/id})) (defmethod m/mutate 'counter/inc [{:keys [state] :as env} k {:keys [id] :as params}] {:remote true :action (fn [] (swap! state update-in [:counter/by-id id] increment-counter))}) (defui ^:once CounterPanel static uc/InitialAppState (uc/initial-state [this params] {:counters [(uc/initial-state Counter {:id 1 :start 1})]}) static om/IQuery (query [this] [{:counters (om/get-query Counter)}]) static om/Ident (ident [this props] [:panels/by-kw :counter]) Object (render [this] (let [{:keys [counters]} (om/props this) click-callback (fn [id] (om/transact! this `[(counter/inc {:id ~id}) :counter-sum]))] (dom/div nil ; embedded style: kind of silly in a real app, but doable (dom/style nil ".counter { width: 400px; padding-bottom: 20px; } button { margin-left: 10px; }") (map #(ui-counter (om/computed % {:onClick click-callback})) counters))))) (def ui-counter-panel (om/factory CounterPanel)) (defui ^:once CounterSum static uc/InitialAppState (uc/initial-state [this params] {}) static om/IQuery (query [this] [[:counter/by-id '_]]) Object (render [this] (let [{:keys [counter/by-id]} (om/props this) total (reduce (fn [total c] (+ total (:counter/n c))) 0 (vals by-id))] (dom/div nil (str "Grand total: " total))))) (def ui-counter-sum (om/factory CounterSum)) (defui ^:once Root static uc/InitialAppState (uc/initial-state [this params] {:panel (uc/initial-state CounterPanel {})}) static om/IQuery (query [this] [:ui/loading-data {:panel (om/get-query CounterPanel)} {:counter-sum (om/get-query CounterSum)}]) Object (render [this] (let [{:keys [ui/loading-data counter-sum panel]} (om/props this)] (dom/div nil (when loading-data (dom/span #js {:style #js {:float "right"}} "Loading...")) (ui-counter-panel panel) (ui-counter-sum counter-sum))))) ;; Simulated Server ; Servers could keep state in RAM (defonce server-state (atom {:THIS_IS_SERVER_STATE true :counters {1 {:counter/id 1 :counter/n 44} 2 {:counter/id 2 :counter/n 23} 3 {:counter/id 3 :counter/n 99}}})) ; The server queries are handled by returning a map with a :value key, which will be placed in the appropriate ; response format (defn read-handler [{:keys [ast state]} k p] (log/info "SERVER query for " k) (case k ; When querying for :all-counters, return the complete set of values in our server counter db (atom in RAM) :all-counters {:value (-> (get @state :counters) vals vec)} nil)) ; The server mutations are handled by returning a map with a :action key whose value is the function that will ; cause the change on the server (defn write-handler [env k p] (log/info "SERVER mutation for " k " with params " p) (case k ; When asked to increment a counter on the server, do so by updating in-memory atom database 'counter/inc (let [{:keys [id]} p] {:action (fn [] (swap! server-state update-in [:counters id :counter/n] inc) nil)}) nil)) ; Om Next query parser. Calls read/write handlers with keywords from the query (def server-parser (om/parser {:read read-handler :mutate write-handler})) ; Simulated server. You'd never write this part (defn server [env tx] (server-parser (assoc env :state server-state) tx)) ; Networking that pretends to talk to server. You'd never write this part (defrecord MockNetwork [complete-app] un/UntangledNetwork (send [this edn ok err] (let [resp (server {} edn)] ; simulates a network delay: (js/setTimeout #(ok resp) 700))) (start [this app] (assoc this :complete-app app))) (defcard-doc "# Quick Tour Untangled is meant to be as simple as possible, but as PI:NAME:<NAME>END_PI would tell you: simple does not mean easy. Fortunately, hard vs. easy is something you can fix just by learning. Om Next (the lower layer of Untangled) takes a very progressive approach to web development, and as such requires that you understand some new concepts. This is *by far* the most difficult part of adapting to Untangled. In this quick tour our intention is to show you a full-stack Untangled application. We hope that as you read this Quick Start you will start to comprehend how *simple* the resulting structure is: - No controllers are needed, ever. - Networking becomes mostly transparent, and gives a synchronous reasoning model (by default) - Server and client code structure are identical. In fact, this tour leverages this fact to simulate server code in the browser that is identical to what you'd *put* on the server. - The reasoning at the UI layer can be completely local. - The reasoning at the model layer can be completely local. - The render refresh story is mostly automatic, and where it isn't, it is completely abstracted from the UI structure to ease developer reasoning. If you're coming from Om Next, you should know that Untangled is *not* a competing project. Untangled is a set of thin libraries that provide default implementations of all of the artifacts you'd normally have to write to make a full-stack Om Next application. In many cases Untangled is required to 'make a call' about how to do something. When it does, our documentation tries to discuss the relative merits and costs. The name 'Untangled' is *not* meant to be a commentary on Om Next, but instead on the general state of web development circa 2016. Om Next and Untangled are two layers of a solution that makes things simpler for you. ## Om Next Components can use Stock React components The first major strength is that Om Next (and therefore Untangled) integrates with stock React components. So, if you already understand React then you already have a head start. If you know nothing of React, you should eventually read more about it. For now, we'll cover everything you need to know. ## The Rendering Model Untangled recommends you treat the UI as a pure function that, given the state of the application 'right now', can be re-rendered on each frame (change of state). ``` App state -> render -> DOM ``` This is a key part of the simplification: You don't have to worry how to keep bits of UI up-to-date. There is a key difference that users of other frameworks might miss here: not only do you *not* have to figure out the complexities of keeping the DOM up to date: there is no mutation or hidden local state to trip you up. As you move from state to state (a sequence of app states, each of which is itself immutable) you can pretend as if render re-creates the entire DOM. This means you can test and reason about your UI in isolation from all other logic! ## Core Model Concepts Untangled uses a very simple (default Om Next) database format for the application state in the browser. Basically this format is a normalized graph database made of maps and vectors. Anything you show on the UI is structured into this database, and can be queried to create arbitrary UI trees for display. A given item in this database can be shown in as many places on the UI as makes sense. The fact that the database is *normalized* means that changing the item once in the database will result in being able to refresh all displayed versions easily. The model manipulation thus maintains the desired local reasoning model (of entries in database tables). You write functions that know how to manipulate specific 'kinds' of things in the database, and think nothing of the UI. For example, say we have a counter that we'd like to represent with this data structure: ``` { :counter/id 1 :counter/n 22 } ``` We can write simple functions to manipulate counters: " (dc/mkdn-pprint-source increment-counter) " and think about that counter as a complete abstract thing (and write tests and clojure specs for it, etc.). The Untangled database table for counters then looks something like this: ``` { :counter/by-id { 1 { :counter/id 1 :counter/n 1 } 2 { :counter/id 2 :counter/n 9 } ...}} ``` A table is just an entry in the database (map) that, by convention, is keyed with a keyword whose namespace indicates the kind of thing in the table, and whose name indicates how it is indexed. The k-v pairs in the table are the keys (of the implied index) and the values of the actual data. The general app state is held in a top-level atom. So, updating any object in the database generally takes the form: ``` (swap! app-state-atom update-in [:table/key id] operation) ``` or in our example case: ``` (swap! app-state-atom update-in [:counter/by-id 1] increment-counter) ``` NOTE: You still need to know *where* to put this code, and how to find/access the `app-state-atom`. ## Mutations as Abstract Transactions In Untangled, you don't do model twiddling on the UI. There is a clear separation of concerns for several good reasons: - It generally pays not to mix your low-level logic with the UI. - The concept of an abstract mutation can isolate the UI from networking, server interactions, and async thinking. - Abstract mutations give nice auditing and comprehension on both client and server. The main UI entry point for affecting a change is the `om/transact!` function. This function lets you submit an abstract sequence of operations that you'd like to accomplish, and isolates the UI author from the details of implementing that behavior (and of even having to know things like 'will that happen locally or on the server?'). The concrete artifacts you'll see in Untangled code are the invocation of the `transact!`, and the implementation of the operations listed in the transaction: ``` (om/transact! this `[(counter/inc {:id ~id})]) ``` in the above transaction, we must use Clojure syntax quoting so that we can list an abstract mutation (which looks like a function call, but is not) and parameters that themselves are derived from the environment (in this case an id). If you're not a Clojure(script) programmer, we understand that the above expression looks a little scary. The '&grave;' means 'treat the following thing literally', and the '~' means 'don't treat this thing literally'. It's a way of keeping the compiler from treating the increment as a function while still being able to embed `id` from the local execution environment. The concrete implementation of the mutation on the model side looks like this: ``` (defmethod m/mutate 'counter/inc [{:keys [state] :as env} k {:keys [id] :as params}] { :action (fn [] (swap! state update-in [:counter/by-id id] increment-counter))}) ``` This looks a little hairy at first until you notice the primary guts are just what we talked about earlier in the model manipulation: it's just an `update-in`. The wrapping is a pretty consistent pattern: the app state and parameters are passed into a multimethod, which is dispatched on the symbol mentioned in the `transact!`. The basics are: - You key on a symbol instead of writing a function with that symbol name (this is what gives an abstraction that is already 'network ready') - You return a map - The `:action` key of that map specifies a function to run to accomplish the optimistic update to the browser database. The use of a thunk (function) here is what helps isolate asynchronous internals and networking from synchronous abstract reasoning. When you want to interact with a server, you need merely change it to: ``` (defmethod m/mutate 'counter/inc [{:keys [state] :as env} k {:keys [id] :as params}] { :remote true ; <---- this is all!!! :action (fn [] (swap! state update-in [:counter/by-id id] increment-counter))}) ``` and then write a similar function on the server that has an `:action` to affect the change on the server! At first this seems like a bit of overkill on the boilerplate until you realize that there are a number of things being handled here: - Sychronous *reasoning* about most aspects of the application. - Local optimistic (immediate) updates (through `:action`) - Automatically plumbed server interactions (triggered through `:remote` at transaction time) - Use of the same abstract symbol for the operation on the client and server. - Operations in the UI and on the server are identical in appearance. - Consistent implementation pattern for model manipulations on the client and server. - The operations 'on the wire' read like abstract function calls, and lead to easy auditing and reasoning, or even easy-to-implement CQRS architectures. ## An Example Let's write a simple application that shows counters that can be incremented. Each counter has an ID and a value (n). ### Making a Counter component Here's the Untangled implementation of that UI component: " (dc/mkdn-pprint-source Counter) " (the `^:once` is helper metadata that ensures correct operation of development-time hot code reload) It looks a bit like a `defrecord` implementing protocols. Here is a description of the parts: - InitialAppState : Represents how to make an instance of the counter in the browser database. Parameters are supported for making more than one on the UI. This function should return a map that matches the properties asked for in the query. - IQuery : Represents what data is needed for the UI. In this case, a list of properties that exist (keys of the map that represents counters in the database). Note we can tune this up/down depending on the needs of the UI. Counters could have labels, owners, purposes, etc. - Ident : Represents the table/ID of the database data for the component. This is a function that, given an example of a counter, will return a vector that has two elements: the table and the ID of the entry. This is used to assist in auto-normalization of the browser database, and also with UI refreshes of components that display the same data. - Object/render : This is the (pure) function that outputs what a Counter should look like on the DOM The incoming data from the database comes in via `om/props`, and things like callbacks come in via a mechanism known as the 'computed' data (e.g. stuff that isn't in the database, but is generated by the UI, such as callbacks). A `defui` generates a React Component (class). In order to render an instance of a Counter, we must make an element factory: " (dc/mkdn-pprint-source ui-counter) " If more than one of something can appear in the UI as siblings, you must specify a `:keyfn` that helps React distinguish the DOM elements. The most important point is that you can reason about `Counter` in a totally local way. ### Combining Counters into a Panel Lets assume we want to display some arbitrary number of counters together in a panel. We can encode that (and the element factory) as: " (dc/mkdn-pprint-source CounterPanel) (dc/mkdn-pprint-source ui-counter-panel) " Note the mirroring again between the initial state and the query. The initial state provides an initial model of what should be in the database *for the component at hand*, and the query indicates which bits of that state are required for that same local component. In this case the query contains a map, which is the query syntax for a JOIN. You can read this query as 'Query for :counters, which is a JOIN on Counter'. Note that since initial state is setting up a vector of counters, the implied result will be a to-many JOIN. The cardinality of JOINS is derived from the structure of the actual database, NOT the query. The join is necessary because this component will be rendering Counter components. The panel should not need to know anything concrete about the implementation of Counter: only that it has a query, initial state, and a way to render. The render is very similar to Counter's. The queried data will appear in props: pull it out, and then render it. Note the use of `ui-counter`, which is the DOM element factory for `Counter`. Finally, we include a callback. The counter has the 'Increment' button, but we've connected that from the counter UI back through to an implementation of a callback via 'computed' properties. This is a common pattern. In this simple example the callback structure was added to demonstrate what it looks like. One could argue that the counter could update itself (while maintaining local reasoning). The implementation of the `counter/inc` mutation was shown earlier. There are many important points to make here, but we would like to stress the fact that the UI has no idea *how* counters are implemented, *if* that logic includes server interactions, etc. There are no nested callbacks of callbacks, no XhrIO mixed into the UI, and interestingly: no need for controller at all! A simple pattern of updating an abstraction in a database is all you need. There is one exception: That weird inclusion of `:counter-sum` in the transaction. We'll explain that shortly. ### Adding the Panel to a Root element Untangled UI (and DOM UI in general) forms a tree. All trees must eventually have a root. The UI composition (and the composition of queries and initial state) must continue to your UI Root. So, in our case our root looks like this: " (dc/mkdn-pprint-source Root) " The initial state is a composition from the nested panel, as is the query. We add in two additional things here: - `:ui/loading-data` is a special key, available at the root, that is true when data is loading over the network - We compose in another component we've yet to discuss (which sums all counters). We'll talk more about that shortly There should be no surprises here. It is the same pattern all over again, except Root does not need an `Ident`, since it need not live in a database table. The data for root can just be a standalone map entry (as can other things. There is *no rule that absolutely everything* lives in tables. Top-level entries for other data structures are also useful). ### Starting up the App Normally you create an Untangled application and mount it on a DIV in your real HTML DOM. We'll cover that later in the Guide. Here we're in devcards and we have a helper to do that. It accepts the same basic parameters as `make-untangled-app`, but mounts the resulting application in a devcard: ``` (defcard SampleApp (untangled-app Root :started-callback (fn [app] (log/info \"Application (re)started\") (df/load app :all-counters Counter {:target [:panels/by-kw :counter :counters]})))) ``` In this quick tour we're faking the networking so you can easily explore what the server and client look like in a single file. The `:started-callback` is triggered as the application loads. This is where you can use Untangled's networking layer to pre-fetch data from the server. In our case, we want to get all of the counters. Note that we can (and should) use UI queries. This triggers auto-normalization of the response. The `:target` option indicates that the loaded data should be places in the database at the given path (usually 1 to 3 keywords in the vector, since the db is normalized). In this case the ident of the target panel gives the location of the component that wants the counters, and the `:counters` property of that component is where it wants to know about them. Therefore the desired target path is the ident + the property as a vector. You'll need to understand a bit more about the structure of the database to completely understand this code, but you see it is really quite simple: pull `:all-counters` from the server-side database, and put them on the panel according to the location (known via Ident) of the panel data in the database. ### Server Implementation We're representing our server database as an in-RAM atom: " (dc/mkdn-pprint-source server-state) " #### Server Queries To respond to the `:all-counters` query, we simply write a function that returns the correct data and hook it into the server engine. In real server code this is commonly done with a multimethod (your choice). The take-away here is that you write very little 'plumbing'...just the logic to get the data, and return it in a map with a `:value` key: " (dc/mkdn-pprint-source read-handler) " #### Server Mutations We mentioned earlier that turning a client mutation into something that also happens on the server is as simple as adding a `:remote true` to the response of the mutation function. The server code is equally trivial (again, in a real server you'd typically use a multimethod): " (dc/mkdn-pprint-source write-handler)) (defcard mock-server-state (dom/div nil "The state shown below is the active state of the mock server for the FinalResult card.") server-state {:watch-atom true :inspect-data true}) (defcard FinalResult "Below is the final result of the above application, complete with faked server interactions (we use setTimeout to fake network latency). If you reload this page and jump to the bottom, you'll see the initial server loading. (If you see an error related to mounting a DOM node, try reloading the page). You can see the mocked server processing take place in a delayed fashion in the Javascript Console of your browser. NOTE: The map shown at the bottom is our simulated server state. Note how, if you click rapidly on increment, that the server state lags behind (because of our simulated delay). You can see how the UI remains responsive even though the server is lagging." (untangled-app Root :started-callback (fn [app] (log/info "Application (re)started") (df/load app :all-counters Counter {:target [:panels/by-kw :counter :counters]})) :networking (map->MockNetwork {})) {} {:inspect-data true}) (defcard-doc "### The Grand Total You'll notice that there is a part of the UI that is tracking the grand total of the counters. This component shows a few more interesting features: Rendering derived values, querying entire tables, and refreshing derived UI. This is the implementation of the counter UI: " (dc/mkdn-pprint-source CounterSum) " The query is interesting. Queries are vectors of things you want. When one of those things is a two-element vector it knows you want an entry in a table (e.g. [:counter/by-id 3]). If you use the special symbol `'_`, then you're asking for an entire top-level entry (in this case a whole table). Thus we can easily use that to calculate our desired UI. However, it turns out that we have a problem: Nothing in Untangled or Om Next will trigger this component to refresh when an individual counter changes! The mutations are abstract, and even though you can imagine that the UI refresh is a pure function that recreates the DOM, it is in fact optimized to only refresh the bits that have changed. Since the data that changed wasn't a counter, Om Next will short-circuit the sum for efficiency. This is the point of the earlier mysterious `:counter-sum` in the `transact!`. Any keyword that appears in a transaction will cause Om to re-render any component that queried for that property (in our case the Root UI component). These are called 'follow-on reads', to imply that 'anything that reads the given property should be asked to re-read it (and implicitly, this means it will re-render if the value has changed)'. You can, of course, play with the source code of this example in the devcards. We certainly hope you will continue reading into the details of all of these features. You should start with the [next chapter](#!/untangled_devguide.B_UI) on UI. ")
[ { "context": "ns under the License.\n;;\n;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.\n\n(ns ^{:doc \"\"\n :autho", "end": 597, "score": 0.9998722076416016, "start": 584, "tag": "NAME", "value": "Kenneth Leung" }, { "context": "ll rights reserved.\n\n(ns ^{:doc \"\"\n :author \"Kenneth Leung\"}\n\n czlab.loki.game.arena\n\n (:require [czlab.lo", "end": 663, "score": 0.9998812675476074, "start": 650, "tag": "NAME", "value": "Kenneth Leung" } ]
src/main/clojure/czlab/loki/game/arena.clj
llnek/loki
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 ^{:doc "" :author "Kenneth Leung"} czlab.loki.game.arena (:require [czlab.loki.net.core :as nc] [czlab.loki.net.disp :as dp] [czlab.loki.xpis :as loki] [clojure.java.io :as io] [czlab.basal.core :as c] [czlab.basal.io :as i] [czlab.basal.util :as u] [czlab.loki.session :as ss]) (:import [java.io Closeable] [java.util.concurrent.atomic AtomicInteger])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- fmtStartBody "" [impl sessions] (c/preduce<map> #(let [{:keys [number player]} (deref %2) yid (:id player) g (loki/get-player-gist impl yid)] (assoc! %1 yid (merge {:pnum number} g))) sessions)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/decl-object<> Arena c/AtomicGS (getf [me n] (get @(:o me) n)) (setf [me n v] (swap! (:o me) assoc n v)) c/Sendable (send [me msg] (cond (nc/is-private? msg) (some-> (:context msg) (c/send msg)) (nc/is-public? msg) (loki/broad-cast me msg))) c/Receivable (receive [me evt] (when (.getf me :opened?) (c/debug "room recv'ed msg %s" (nc/pretty-event evt)) (cond (nc/is-public? evt) (loki/broad-cast me evt) (nc/is-private? evt) (loki/on-room-event me evt)))) c/Idable (id [me] (.getf me :id)) c/Openable (open [me] (.open me nil)) (open [me _] (let [{:keys [disp conns source game]} @(:o me) sss (sort-by #(:created (deref %)) (vals conns)) g (@(:implClass game) me sss)] (c/debug "activating room [%s]" (.id me)) (doseq [s sss] (loki/sub disp (dp/esubr<> s))) (swap! (:o me) merge {:impl g :latch conns :starting? false :opened? true :active? false}) (c/init g nil) (nc/bcast! me loki/start (fmtStartBody g sss)))) Closeable (close [me] (c/debug "closing arena [%s]" (.id me)) (doseq [[_ s] (.getf me :conns)] (doto s ss/remove-session i/klose)) (.setf me :conns nil) ((.getf me :finz) (.id me))) c/Restartable (restart [me] (c/debug "arena [%s] restart() called" (.id me)) (->> (-> (.getf me :impl) (fmtStartBody (vals (.getf me :conns)))) (nc/bcast! me loki/restart))) c/Startable (start [me arg] (c/debug "arena [%s] start called" (.id me)) (.setf me :active? true) (c/start (.getf me :impl) arg)) (start [me] (.start me nil)) (stop [me] (.setf me :active? false)) loki/GameRoom (broad-cast [me evt] (loki/pub-event (.getf me :disp) evt)) (count-players [me] (count (.getf me :conns))) (can-open-room? [me] (and (not (.getf me :opened?)) (>= (loki/count-players me) (:minPlayers (.getf me :game))))) (on-room-event [me evt] (let [{:keys [context body]} evt {:keys [impl latch conns active?]} @(:o me)] (assert (some? context)) (cond (and (not active?) (nc/is-code? loki/replay evt)) (locking me (when (and (not (.getf me :starting?)) (empty? (.getf me :latch))) (swap! (:o me) merge {:latch conns :starting true}) (c/restart me))) (and (not active?) (nc/is-code? loki/started evt)) (if (contains? latch (:id context)) (locking me (c/debug "latch: drop-off: %s" (:id context)) (.setf me :latch (dissoc (.getf me :latch) (:id context))) (if (empty? (.getf me :latch)) (c/start me (i/read-json body))))) (and active? (some? latch) (empty? latch)) (let [rc (loki/on-game-event impl evt)] (when (and (nc/is-quit? evt) (= rc loki/tear-down)) (nc/bcast! me loki/play-scrubbed {:pnum (:number @context)}) (u/pause 1000) (.close me))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn arena<> "" [game finzer source] (c/atomic<> Arena {:shutting? false :opened? false :active? false :source source :finz finzer :game game :conns {} :id (keyword (czlab.basal.util/uid<>)) :disp (czlab.loki.net.disp/edispatcher<>) :numctr (java.util.concurrent.atomic.AtomicInteger.)})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
121665
;; 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 ^{:doc "" :author "<NAME>"} czlab.loki.game.arena (:require [czlab.loki.net.core :as nc] [czlab.loki.net.disp :as dp] [czlab.loki.xpis :as loki] [clojure.java.io :as io] [czlab.basal.core :as c] [czlab.basal.io :as i] [czlab.basal.util :as u] [czlab.loki.session :as ss]) (:import [java.io Closeable] [java.util.concurrent.atomic AtomicInteger])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- fmtStartBody "" [impl sessions] (c/preduce<map> #(let [{:keys [number player]} (deref %2) yid (:id player) g (loki/get-player-gist impl yid)] (assoc! %1 yid (merge {:pnum number} g))) sessions)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/decl-object<> Arena c/AtomicGS (getf [me n] (get @(:o me) n)) (setf [me n v] (swap! (:o me) assoc n v)) c/Sendable (send [me msg] (cond (nc/is-private? msg) (some-> (:context msg) (c/send msg)) (nc/is-public? msg) (loki/broad-cast me msg))) c/Receivable (receive [me evt] (when (.getf me :opened?) (c/debug "room recv'ed msg %s" (nc/pretty-event evt)) (cond (nc/is-public? evt) (loki/broad-cast me evt) (nc/is-private? evt) (loki/on-room-event me evt)))) c/Idable (id [me] (.getf me :id)) c/Openable (open [me] (.open me nil)) (open [me _] (let [{:keys [disp conns source game]} @(:o me) sss (sort-by #(:created (deref %)) (vals conns)) g (@(:implClass game) me sss)] (c/debug "activating room [%s]" (.id me)) (doseq [s sss] (loki/sub disp (dp/esubr<> s))) (swap! (:o me) merge {:impl g :latch conns :starting? false :opened? true :active? false}) (c/init g nil) (nc/bcast! me loki/start (fmtStartBody g sss)))) Closeable (close [me] (c/debug "closing arena [%s]" (.id me)) (doseq [[_ s] (.getf me :conns)] (doto s ss/remove-session i/klose)) (.setf me :conns nil) ((.getf me :finz) (.id me))) c/Restartable (restart [me] (c/debug "arena [%s] restart() called" (.id me)) (->> (-> (.getf me :impl) (fmtStartBody (vals (.getf me :conns)))) (nc/bcast! me loki/restart))) c/Startable (start [me arg] (c/debug "arena [%s] start called" (.id me)) (.setf me :active? true) (c/start (.getf me :impl) arg)) (start [me] (.start me nil)) (stop [me] (.setf me :active? false)) loki/GameRoom (broad-cast [me evt] (loki/pub-event (.getf me :disp) evt)) (count-players [me] (count (.getf me :conns))) (can-open-room? [me] (and (not (.getf me :opened?)) (>= (loki/count-players me) (:minPlayers (.getf me :game))))) (on-room-event [me evt] (let [{:keys [context body]} evt {:keys [impl latch conns active?]} @(:o me)] (assert (some? context)) (cond (and (not active?) (nc/is-code? loki/replay evt)) (locking me (when (and (not (.getf me :starting?)) (empty? (.getf me :latch))) (swap! (:o me) merge {:latch conns :starting true}) (c/restart me))) (and (not active?) (nc/is-code? loki/started evt)) (if (contains? latch (:id context)) (locking me (c/debug "latch: drop-off: %s" (:id context)) (.setf me :latch (dissoc (.getf me :latch) (:id context))) (if (empty? (.getf me :latch)) (c/start me (i/read-json body))))) (and active? (some? latch) (empty? latch)) (let [rc (loki/on-game-event impl evt)] (when (and (nc/is-quit? evt) (= rc loki/tear-down)) (nc/bcast! me loki/play-scrubbed {:pnum (:number @context)}) (u/pause 1000) (.close me))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn arena<> "" [game finzer source] (c/atomic<> Arena {:shutting? false :opened? false :active? false :source source :finz finzer :game game :conns {} :id (keyword (czlab.basal.util/uid<>)) :disp (czlab.loki.net.disp/edispatcher<>) :numctr (java.util.concurrent.atomic.AtomicInteger.)})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;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 ^{:doc "" :author "PI:NAME:<NAME>END_PI"} czlab.loki.game.arena (:require [czlab.loki.net.core :as nc] [czlab.loki.net.disp :as dp] [czlab.loki.xpis :as loki] [clojure.java.io :as io] [czlab.basal.core :as c] [czlab.basal.io :as i] [czlab.basal.util :as u] [czlab.loki.session :as ss]) (:import [java.io Closeable] [java.util.concurrent.atomic AtomicInteger])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;(set! *warn-on-reflection* true) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn- fmtStartBody "" [impl sessions] (c/preduce<map> #(let [{:keys [number player]} (deref %2) yid (:id player) g (loki/get-player-gist impl yid)] (assoc! %1 yid (merge {:pnum number} g))) sessions)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (c/decl-object<> Arena c/AtomicGS (getf [me n] (get @(:o me) n)) (setf [me n v] (swap! (:o me) assoc n v)) c/Sendable (send [me msg] (cond (nc/is-private? msg) (some-> (:context msg) (c/send msg)) (nc/is-public? msg) (loki/broad-cast me msg))) c/Receivable (receive [me evt] (when (.getf me :opened?) (c/debug "room recv'ed msg %s" (nc/pretty-event evt)) (cond (nc/is-public? evt) (loki/broad-cast me evt) (nc/is-private? evt) (loki/on-room-event me evt)))) c/Idable (id [me] (.getf me :id)) c/Openable (open [me] (.open me nil)) (open [me _] (let [{:keys [disp conns source game]} @(:o me) sss (sort-by #(:created (deref %)) (vals conns)) g (@(:implClass game) me sss)] (c/debug "activating room [%s]" (.id me)) (doseq [s sss] (loki/sub disp (dp/esubr<> s))) (swap! (:o me) merge {:impl g :latch conns :starting? false :opened? true :active? false}) (c/init g nil) (nc/bcast! me loki/start (fmtStartBody g sss)))) Closeable (close [me] (c/debug "closing arena [%s]" (.id me)) (doseq [[_ s] (.getf me :conns)] (doto s ss/remove-session i/klose)) (.setf me :conns nil) ((.getf me :finz) (.id me))) c/Restartable (restart [me] (c/debug "arena [%s] restart() called" (.id me)) (->> (-> (.getf me :impl) (fmtStartBody (vals (.getf me :conns)))) (nc/bcast! me loki/restart))) c/Startable (start [me arg] (c/debug "arena [%s] start called" (.id me)) (.setf me :active? true) (c/start (.getf me :impl) arg)) (start [me] (.start me nil)) (stop [me] (.setf me :active? false)) loki/GameRoom (broad-cast [me evt] (loki/pub-event (.getf me :disp) evt)) (count-players [me] (count (.getf me :conns))) (can-open-room? [me] (and (not (.getf me :opened?)) (>= (loki/count-players me) (:minPlayers (.getf me :game))))) (on-room-event [me evt] (let [{:keys [context body]} evt {:keys [impl latch conns active?]} @(:o me)] (assert (some? context)) (cond (and (not active?) (nc/is-code? loki/replay evt)) (locking me (when (and (not (.getf me :starting?)) (empty? (.getf me :latch))) (swap! (:o me) merge {:latch conns :starting true}) (c/restart me))) (and (not active?) (nc/is-code? loki/started evt)) (if (contains? latch (:id context)) (locking me (c/debug "latch: drop-off: %s" (:id context)) (.setf me :latch (dissoc (.getf me :latch) (:id context))) (if (empty? (.getf me :latch)) (c/start me (i/read-json body))))) (and active? (some? latch) (empty? latch)) (let [rc (loki/on-game-event impl evt)] (when (and (nc/is-quit? evt) (= rc loki/tear-down)) (nc/bcast! me loki/play-scrubbed {:pnum (:number @context)}) (u/pause 1000) (.close me))))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defn arena<> "" [game finzer source] (c/atomic<> Arena {:shutting? false :opened? false :active? false :source source :finz finzer :game game :conns {} :id (keyword (czlab.basal.util/uid<>)) :disp (czlab.loki.net.disp/edispatcher<>) :numctr (java.util.concurrent.atomic.AtomicInteger.)})) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;EOF
[ { "context": ";;; Iterative fibonacci.\n;;;\n;;; Eli Bendersky [http://eli.thegreenplace.net]\n;;; This code is i", "end": 46, "score": 0.999189019203186, "start": 33, "tag": "NAME", "value": "Eli Bendersky" } ]
2017/continuations-trampolines/clojure-samples/src/clojure_samples/fib_loop.clj
mikiec84/code-for-blog
1,199
;;; Iterative fibonacci. ;;; ;;; Eli Bendersky [http://eli.thegreenplace.net] ;;; This code is in the public domain. (ns clojure-samples.fib-loop) (defn fib_iterative [n] (loop [n n accum1 1 accum2 1] (if (< n 2) accum1 (recur (- n 1) (+ accum1 accum2) accum1)))) (fib_tail 10)
20717
;;; Iterative fibonacci. ;;; ;;; <NAME> [http://eli.thegreenplace.net] ;;; This code is in the public domain. (ns clojure-samples.fib-loop) (defn fib_iterative [n] (loop [n n accum1 1 accum2 1] (if (< n 2) accum1 (recur (- n 1) (+ accum1 accum2) accum1)))) (fib_tail 10)
true
;;; Iterative fibonacci. ;;; ;;; PI:NAME:<NAME>END_PI [http://eli.thegreenplace.net] ;;; This code is in the public domain. (ns clojure-samples.fib-loop) (defn fib_iterative [n] (loop [n n accum1 1 accum2 1] (if (< n 2) accum1 (recur (- n 1) (+ accum1 accum2) accum1)))) (fib_tail 10)
[ { "context": "; Copyright (c) Christian von Essen. All rights reserved.\n; The use and distributio", "end": 37, "score": 0.9998696446418762, "start": 18, "tag": "NAME", "value": "Christian von Essen" }, { "context": "efaults\nto 10. The returned socket will listen on 127.0.0.1.\"\n ([port]\n\t (create-server port 10))\n ([port b", "end": 4866, "score": 0.9985402226448059, "start": 4857, "tag": "IP_ADDRESS", "value": "127.0.0.1" } ]
src/clojure_server/server.clj
Neronus/clj-server
3
; Copyright (c) Christian von Essen. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns clojure-server.server (:refer-clojure) (:import (clojure_server ChunkOutputStream ExitException) (java.io InputStreamReader PrintWriter BufferedInputStream BufferedOutputStream) (java.net ServerSocket InetAddress) (java.util.concurrent ThreadPoolExecutor TimeUnit LinkedBlockingQueue)) (:use clojure-server.main clojure.contrib.duck-streams)) (def MSG-STDOUT 0) (def MSG-STDERR 1) (def MSG-EXIT 2) (def MSG-PATH 3) (def MSG-OK 4) (def MSG-ERR 5) (def *security-file*) (defmacro bytearray->int [n array] (let [array-sym (gensym "array")] (letfn [(inner [i] (let [ai (- n i)] (if (= 1 i) `(bit-and (int (aget ~array-sym ~ai)) 255) `(bit-or (bit-shift-left (bit-and (int (aget ~array-sym ~ai)) 255) ~(* (- i 1) 8)) ~(inner (dec i))))))] `(let [~array-sym ~array] ~(inner n))))) (defn read-int [in] (let [buffer (make-array Byte/TYPE 4)] (if (= (.read in buffer) 4) (bytearray->int 4 buffer) (throw (Exception. "Error while reading integer."))))) (defn read-sized-data "Reads from in first an integer and then the number of bytes specified. Returns the data as a byte array." ([in length] (let [array (make-array Byte/TYPE length)] (loop [read 0] (if (= read length) array (let [new (.read in array read (- length read))] (if (= new -1) (throw (Exception. "Error while reading from socket")) (recur (+ new read)))))))) ([in] (let [length (read-int in)] (read-sized-data in length)))) (defn read-sized-string ([in] (let [array (read-sized-data in)] (String. array))) ([in length] (let [array (read-sized-data in length)] (String. array)))) (defn- read-command-line-parms "Reads n null-terminated strings from the reader." [in n] (doall (for [i (range n)] (read-sized-string in)))) (defn- set-property! "Set the system property" [key value] (let [properties (System/getProperties)] (.setProperty properties (str key) (str value)))) (defn- is-relative? "Returns false iff the first character of the sequence given as path is equals to /" [path] (not (= (first path) \/))) (defn- send-int "Send an 4 byte integer down the stream" [out int] (println int) (.write out (bit-shift-right int 24)) (.write out (bit-shift-right int 16)) (.write out (bit-shift-right int 8)) (.write out int)) (defn send-message ([out message data] (let [out (ChunkOutputStream. out message)] (.write out data) (.flush out))) ([out message] (send-message out message (make-array Byte/TYPE 0)))) (defn auth "Works the authorization procedure using in and out for communication, which should be Reader and Writer instannces. If authorization was successful, true is returned, false otherwise." [in out] (letfn ((dont-accept [] (send-message out MSG-ERR) (.flush out) false) (accept [] (send-message out MSG-OK) (.flush out) true) (check-path [path] (send-message out MSG-PATH (.getBytes path)) (let [content (.getBytes (slurp* path)) recieved-content (read-sized-data in (count content))] (and (= (count content) (count recieved-content)) (loop [i (int 0)] (cond (>= i (count content)) true (= (aget content i) (aget recieved-content i)) (recur (unchecked-inc i)) :else false)))))) (let [path *security-file*] (if (is-relative? path) (dont-accept) (try (do (if (not (check-path path)) (dont-accept) (accept))) (catch Exception e (dont-accept))))))) (defn- reciever "Called by the server main loop. This instance calls the authorizatoin procedure and, if successful, starts the main repl on the given input and output streams." [input output] (when (auth input output) (let [pwd (read-sized-string input) n-args (read-int input) args (seq (read-command-line-parms input n-args))] (binding [*in* (clojure.lang.LineNumberingPushbackReader. (InputStreamReader. input)) *out* (PrintWriter. (ChunkOutputStream. output MSG-STDOUT)) *err* (PrintWriter. (ChunkOutputStream. output MSG-STDERR)) *exit* (ChunkOutputStream. output MSG-EXIT) *pwd* pwd] (apply clojure-server.main/server-main args))))) (defn create-server "Creates a server socket on the given port with the given backlog, which defaults to 10. The returned socket will listen on 127.0.0.1." ([port] (create-server port 10)) ([port backlog] (let [socket (ServerSocket. port backlog (InetAddress/getByAddress (into-array (Byte/TYPE) [(byte 127) (byte 0) (byte 0) (byte 1)])))] socket))) (defn set-security-manager [manager] (System/setSecurityManager manager)) (defn get-security-manager [] (System/getSecurityManager)) (defn build-security-manager [] (proxy [SecurityManager] [] (checkExit [status] (throw (ExitException. status))) (checkAccept [host port]) (checkAccess [g]) (checkAwtEventQueueAccess []) (checkConnect ([host port]) ([host port context])) (checkCreateClassLoader []) (checkDelete [file]) (checkExec [cmd]) (checkLink [lib]) (checkListen [port]) (checkMemberAccess [clazz which]) (checkMulticast ([maddr]) ([maddr ttl])) (checkPackageAccess [pkg]) (checkPackageDefinition [pkg]) (checkPermission ([perm]) ([perm context])) (checkPrintJobAccess []) (checkPropertiesAccess ([]) ([key])) (checkRead ([file]) ([file context])) (checkSecurityAccess [target]) (checkSetFactory []) (checkSystemClipboardAccess []) (checkTopLevelWindow [window] true) (checkWrite ([fd])))) (defn set-exit-security-manager [] (set-security-manager (build-security-manager))) (defn server-loop "accepts connections on the socket, and launches the repl on incoming connections. Doesn't return." [socket minThreads maxThreads security-file] (let [exec (ThreadPoolExecutor. minThreads maxThreads (* 60 5) TimeUnit/SECONDS (LinkedBlockingQueue.))] (loop [] (let [csocket (.accept socket) gensym-ns *gensym-ns*] (.submit exec #^Callable #(with-open [csocket csocket] (with-open [csocket csocket] (binding [*gensym-ns* gensym-ns *security-file* security-file] (reciever (BufferedInputStream. (.getInputStream csocket)) (BufferedOutputStream. (.getOutputStream csocket)))))))) (recur))))
27614
; Copyright (c) <NAME>. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns clojure-server.server (:refer-clojure) (:import (clojure_server ChunkOutputStream ExitException) (java.io InputStreamReader PrintWriter BufferedInputStream BufferedOutputStream) (java.net ServerSocket InetAddress) (java.util.concurrent ThreadPoolExecutor TimeUnit LinkedBlockingQueue)) (:use clojure-server.main clojure.contrib.duck-streams)) (def MSG-STDOUT 0) (def MSG-STDERR 1) (def MSG-EXIT 2) (def MSG-PATH 3) (def MSG-OK 4) (def MSG-ERR 5) (def *security-file*) (defmacro bytearray->int [n array] (let [array-sym (gensym "array")] (letfn [(inner [i] (let [ai (- n i)] (if (= 1 i) `(bit-and (int (aget ~array-sym ~ai)) 255) `(bit-or (bit-shift-left (bit-and (int (aget ~array-sym ~ai)) 255) ~(* (- i 1) 8)) ~(inner (dec i))))))] `(let [~array-sym ~array] ~(inner n))))) (defn read-int [in] (let [buffer (make-array Byte/TYPE 4)] (if (= (.read in buffer) 4) (bytearray->int 4 buffer) (throw (Exception. "Error while reading integer."))))) (defn read-sized-data "Reads from in first an integer and then the number of bytes specified. Returns the data as a byte array." ([in length] (let [array (make-array Byte/TYPE length)] (loop [read 0] (if (= read length) array (let [new (.read in array read (- length read))] (if (= new -1) (throw (Exception. "Error while reading from socket")) (recur (+ new read)))))))) ([in] (let [length (read-int in)] (read-sized-data in length)))) (defn read-sized-string ([in] (let [array (read-sized-data in)] (String. array))) ([in length] (let [array (read-sized-data in length)] (String. array)))) (defn- read-command-line-parms "Reads n null-terminated strings from the reader." [in n] (doall (for [i (range n)] (read-sized-string in)))) (defn- set-property! "Set the system property" [key value] (let [properties (System/getProperties)] (.setProperty properties (str key) (str value)))) (defn- is-relative? "Returns false iff the first character of the sequence given as path is equals to /" [path] (not (= (first path) \/))) (defn- send-int "Send an 4 byte integer down the stream" [out int] (println int) (.write out (bit-shift-right int 24)) (.write out (bit-shift-right int 16)) (.write out (bit-shift-right int 8)) (.write out int)) (defn send-message ([out message data] (let [out (ChunkOutputStream. out message)] (.write out data) (.flush out))) ([out message] (send-message out message (make-array Byte/TYPE 0)))) (defn auth "Works the authorization procedure using in and out for communication, which should be Reader and Writer instannces. If authorization was successful, true is returned, false otherwise." [in out] (letfn ((dont-accept [] (send-message out MSG-ERR) (.flush out) false) (accept [] (send-message out MSG-OK) (.flush out) true) (check-path [path] (send-message out MSG-PATH (.getBytes path)) (let [content (.getBytes (slurp* path)) recieved-content (read-sized-data in (count content))] (and (= (count content) (count recieved-content)) (loop [i (int 0)] (cond (>= i (count content)) true (= (aget content i) (aget recieved-content i)) (recur (unchecked-inc i)) :else false)))))) (let [path *security-file*] (if (is-relative? path) (dont-accept) (try (do (if (not (check-path path)) (dont-accept) (accept))) (catch Exception e (dont-accept))))))) (defn- reciever "Called by the server main loop. This instance calls the authorizatoin procedure and, if successful, starts the main repl on the given input and output streams." [input output] (when (auth input output) (let [pwd (read-sized-string input) n-args (read-int input) args (seq (read-command-line-parms input n-args))] (binding [*in* (clojure.lang.LineNumberingPushbackReader. (InputStreamReader. input)) *out* (PrintWriter. (ChunkOutputStream. output MSG-STDOUT)) *err* (PrintWriter. (ChunkOutputStream. output MSG-STDERR)) *exit* (ChunkOutputStream. output MSG-EXIT) *pwd* pwd] (apply clojure-server.main/server-main args))))) (defn create-server "Creates a server socket on the given port with the given backlog, which defaults to 10. The returned socket will listen on 127.0.0.1." ([port] (create-server port 10)) ([port backlog] (let [socket (ServerSocket. port backlog (InetAddress/getByAddress (into-array (Byte/TYPE) [(byte 127) (byte 0) (byte 0) (byte 1)])))] socket))) (defn set-security-manager [manager] (System/setSecurityManager manager)) (defn get-security-manager [] (System/getSecurityManager)) (defn build-security-manager [] (proxy [SecurityManager] [] (checkExit [status] (throw (ExitException. status))) (checkAccept [host port]) (checkAccess [g]) (checkAwtEventQueueAccess []) (checkConnect ([host port]) ([host port context])) (checkCreateClassLoader []) (checkDelete [file]) (checkExec [cmd]) (checkLink [lib]) (checkListen [port]) (checkMemberAccess [clazz which]) (checkMulticast ([maddr]) ([maddr ttl])) (checkPackageAccess [pkg]) (checkPackageDefinition [pkg]) (checkPermission ([perm]) ([perm context])) (checkPrintJobAccess []) (checkPropertiesAccess ([]) ([key])) (checkRead ([file]) ([file context])) (checkSecurityAccess [target]) (checkSetFactory []) (checkSystemClipboardAccess []) (checkTopLevelWindow [window] true) (checkWrite ([fd])))) (defn set-exit-security-manager [] (set-security-manager (build-security-manager))) (defn server-loop "accepts connections on the socket, and launches the repl on incoming connections. Doesn't return." [socket minThreads maxThreads security-file] (let [exec (ThreadPoolExecutor. minThreads maxThreads (* 60 5) TimeUnit/SECONDS (LinkedBlockingQueue.))] (loop [] (let [csocket (.accept socket) gensym-ns *gensym-ns*] (.submit exec #^Callable #(with-open [csocket csocket] (with-open [csocket csocket] (binding [*gensym-ns* gensym-ns *security-file* security-file] (reciever (BufferedInputStream. (.getInputStream csocket)) (BufferedOutputStream. (.getOutputStream csocket)))))))) (recur))))
true
; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns clojure-server.server (:refer-clojure) (:import (clojure_server ChunkOutputStream ExitException) (java.io InputStreamReader PrintWriter BufferedInputStream BufferedOutputStream) (java.net ServerSocket InetAddress) (java.util.concurrent ThreadPoolExecutor TimeUnit LinkedBlockingQueue)) (:use clojure-server.main clojure.contrib.duck-streams)) (def MSG-STDOUT 0) (def MSG-STDERR 1) (def MSG-EXIT 2) (def MSG-PATH 3) (def MSG-OK 4) (def MSG-ERR 5) (def *security-file*) (defmacro bytearray->int [n array] (let [array-sym (gensym "array")] (letfn [(inner [i] (let [ai (- n i)] (if (= 1 i) `(bit-and (int (aget ~array-sym ~ai)) 255) `(bit-or (bit-shift-left (bit-and (int (aget ~array-sym ~ai)) 255) ~(* (- i 1) 8)) ~(inner (dec i))))))] `(let [~array-sym ~array] ~(inner n))))) (defn read-int [in] (let [buffer (make-array Byte/TYPE 4)] (if (= (.read in buffer) 4) (bytearray->int 4 buffer) (throw (Exception. "Error while reading integer."))))) (defn read-sized-data "Reads from in first an integer and then the number of bytes specified. Returns the data as a byte array." ([in length] (let [array (make-array Byte/TYPE length)] (loop [read 0] (if (= read length) array (let [new (.read in array read (- length read))] (if (= new -1) (throw (Exception. "Error while reading from socket")) (recur (+ new read)))))))) ([in] (let [length (read-int in)] (read-sized-data in length)))) (defn read-sized-string ([in] (let [array (read-sized-data in)] (String. array))) ([in length] (let [array (read-sized-data in length)] (String. array)))) (defn- read-command-line-parms "Reads n null-terminated strings from the reader." [in n] (doall (for [i (range n)] (read-sized-string in)))) (defn- set-property! "Set the system property" [key value] (let [properties (System/getProperties)] (.setProperty properties (str key) (str value)))) (defn- is-relative? "Returns false iff the first character of the sequence given as path is equals to /" [path] (not (= (first path) \/))) (defn- send-int "Send an 4 byte integer down the stream" [out int] (println int) (.write out (bit-shift-right int 24)) (.write out (bit-shift-right int 16)) (.write out (bit-shift-right int 8)) (.write out int)) (defn send-message ([out message data] (let [out (ChunkOutputStream. out message)] (.write out data) (.flush out))) ([out message] (send-message out message (make-array Byte/TYPE 0)))) (defn auth "Works the authorization procedure using in and out for communication, which should be Reader and Writer instannces. If authorization was successful, true is returned, false otherwise." [in out] (letfn ((dont-accept [] (send-message out MSG-ERR) (.flush out) false) (accept [] (send-message out MSG-OK) (.flush out) true) (check-path [path] (send-message out MSG-PATH (.getBytes path)) (let [content (.getBytes (slurp* path)) recieved-content (read-sized-data in (count content))] (and (= (count content) (count recieved-content)) (loop [i (int 0)] (cond (>= i (count content)) true (= (aget content i) (aget recieved-content i)) (recur (unchecked-inc i)) :else false)))))) (let [path *security-file*] (if (is-relative? path) (dont-accept) (try (do (if (not (check-path path)) (dont-accept) (accept))) (catch Exception e (dont-accept))))))) (defn- reciever "Called by the server main loop. This instance calls the authorizatoin procedure and, if successful, starts the main repl on the given input and output streams." [input output] (when (auth input output) (let [pwd (read-sized-string input) n-args (read-int input) args (seq (read-command-line-parms input n-args))] (binding [*in* (clojure.lang.LineNumberingPushbackReader. (InputStreamReader. input)) *out* (PrintWriter. (ChunkOutputStream. output MSG-STDOUT)) *err* (PrintWriter. (ChunkOutputStream. output MSG-STDERR)) *exit* (ChunkOutputStream. output MSG-EXIT) *pwd* pwd] (apply clojure-server.main/server-main args))))) (defn create-server "Creates a server socket on the given port with the given backlog, which defaults to 10. The returned socket will listen on 127.0.0.1." ([port] (create-server port 10)) ([port backlog] (let [socket (ServerSocket. port backlog (InetAddress/getByAddress (into-array (Byte/TYPE) [(byte 127) (byte 0) (byte 0) (byte 1)])))] socket))) (defn set-security-manager [manager] (System/setSecurityManager manager)) (defn get-security-manager [] (System/getSecurityManager)) (defn build-security-manager [] (proxy [SecurityManager] [] (checkExit [status] (throw (ExitException. status))) (checkAccept [host port]) (checkAccess [g]) (checkAwtEventQueueAccess []) (checkConnect ([host port]) ([host port context])) (checkCreateClassLoader []) (checkDelete [file]) (checkExec [cmd]) (checkLink [lib]) (checkListen [port]) (checkMemberAccess [clazz which]) (checkMulticast ([maddr]) ([maddr ttl])) (checkPackageAccess [pkg]) (checkPackageDefinition [pkg]) (checkPermission ([perm]) ([perm context])) (checkPrintJobAccess []) (checkPropertiesAccess ([]) ([key])) (checkRead ([file]) ([file context])) (checkSecurityAccess [target]) (checkSetFactory []) (checkSystemClipboardAccess []) (checkTopLevelWindow [window] true) (checkWrite ([fd])))) (defn set-exit-security-manager [] (set-security-manager (build-security-manager))) (defn server-loop "accepts connections on the socket, and launches the repl on incoming connections. Doesn't return." [socket minThreads maxThreads security-file] (let [exec (ThreadPoolExecutor. minThreads maxThreads (* 60 5) TimeUnit/SECONDS (LinkedBlockingQueue.))] (loop [] (let [csocket (.accept socket) gensym-ns *gensym-ns*] (.submit exec #^Callable #(with-open [csocket csocket] (with-open [csocket csocket] (binding [*gensym-ns* gensym-ns *security-file* security-file] (reciever (BufferedInputStream. (.getInputStream csocket)) (BufferedOutputStream. (.getOutputStream csocket)))))))) (recur))))
[ { "context": "googleapis.com/nextjournal-cas-eu/data/8VujAQ3bHzgNYiC3C61DJwUmXP7xW6bB8tT92xAKhDyu5vXReakaHVSrqJfurggZdCJVuAf3B7AujNBvkJAcz974uH\"})\n\n(defn ->html [{:keys [conn-ws? live-js?] :or ", "end": 3454, "score": 0.9971385598182678, "start": 3375, "tag": "KEY", "value": "NYiC3C61DJwUmXP7xW6bB8tT92xAKhDyu5vXReakaHVSrqJfurggZdCJVuAf3B7AujNBvkJAcz974uH" } ]
src/nextjournal/clerk/view.clj
ivanpierre/clerk
1
(ns nextjournal.clerk.view (:require [nextjournal.clerk.viewer :as v] [hiccup.page :as hiccup] [clojure.pprint :as pprint] [clojure.string :as str] [clojure.walk :as w])) (defn ex->viewer [e] (v/exception (Throwable->map e))) #_(doc->viewer (nextjournal.clerk/eval-file "notebooks/elements.clj")) (defn var->data [v] (v/with-viewer* :clerk/var (symbol v))) #_(var->data #'var->data) (defn fn->str [f] (let [pr-rep (pr-str f) f-name (subs pr-rep (count "#function[") (- (count pr-rep) 1))] f-name)) #_(fn->str (fn [])) #_(fn->str +) (defn make-printable [x] (cond-> x (var? x) var->data (meta x) (with-meta {}) (fn? x) fn->str)) #_(meta (make-printable ^{:f (fn [])} [])) (defn ->edn [x] (binding [*print-namespace-maps* false] (pr-str (try (w/prewalk make-printable x) (catch Throwable _ x))))) #_(->edn [:vec (with-meta [] {'clojure.core.protocols/datafy (fn [x] x)}) :var #'->edn]) (defn described-result [_ns {:keys [result blob-id]}] (v/with-viewer* :clerk/result {:blob-id blob-id :viewer (v/viewer result)})) (defn inline-result [ns {:keys [result]}] (v/with-viewer* :clerk/inline-result (try {:edn (->edn (v/describe result {:viewers (v/get-viewers ns (v/viewers result))}))} (catch Exception _ {:string (pr-str result)})))) (defn doc->viewer ([doc] (doc->viewer {} doc)) ([{:keys [inline-results?] :or {inline-results? false}} doc] (let [{:keys [ns]} (meta doc)] (cond-> (into [] (mapcat (fn [{:as x :keys [type text result]}] (case type :markdown [(v/md text)] :code (cond-> [(v/code text)] (contains? x :result) (conj (cond (v/registration? (:result result)) (:result result) (and (not inline-results?) (map? result) (contains? result :result) (contains? result :blob-id)) (described-result ns result) :else (inline-result ns result))))))) doc) true v/notebook ns (assoc :scope (v/datafy-scope ns)))))) #_(meta (doc->viewer (nextjournal.clerk/eval-file "notebooks/elements.clj"))) #_(nextjournal.clerk/show! "notebooks/test.clj") (defonce ^{:doc "Load dynamic js from shadow or static bundle from cdn."} live-js? (when-let [prop (System/getProperty "clerk.live_js")] (not= "false" prop))) (def resource->static-url {"/css/app.css" "https://storage.googleapis.com/nextjournal-cas-eu/data/8VxQBDwk3cvr1bt8YVL5m6bJGrFEmzrSbCrH1roypLjJr4AbbteCKh9Y6gQVYexdY85QA2HG5nQFLWpRp69zFSPDJ9" "/css/viewer.css" "https://storage.googleapis.com/nextjournal-cas-eu/data/8VxoxUgsBRs2yjjBBcfeCc8XigM7erXHmjJg2tjdGxNBxwTYuDonuYswXqRStaCA2b3rTEPCgPwixJmAVrea1qAHHU" "/js/viewer.js" "https://storage.googleapis.com/nextjournal-cas-eu/data/8VujAQ3bHzgNYiC3C61DJwUmXP7xW6bB8tT92xAKhDyu5vXReakaHVSrqJfurggZdCJVuAf3B7AujNBvkJAcz974uH"}) (defn ->html [{:keys [conn-ws? live-js?] :or {conn-ws? true live-js? live-js?}} doc] (hiccup/html5 [:head [:meta {:charset "UTF-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1"}] (hiccup/include-css "https://cdn.jsdelivr.net/npm/katex@0.13.13/dist/katex.min.css") (hiccup/include-css (cond-> "/css/app.css" (not live-js?) resource->static-url)) (hiccup/include-css (cond-> "/css/viewer.css" (not live-js?) resource->static-url)) (hiccup/include-js (cond-> "/js/viewer.js" (not live-js?) resource->static-url))] [:body [:div#clerk] [:script "let viewer = nextjournal.clerk.sci_viewer let doc = " (-> doc ->edn pr-str) " viewer.reset_doc(viewer.read_string(doc)) viewer.mount(document.getElementById('clerk'))\n" (when conn-ws? "const ws = new WebSocket(document.location.origin.replace(/^http/, 'ws') + '/_ws') ws.onmessage = msg => viewer.reset_doc(viewer.read_string(msg.data))")]])) (defn ->static-app [{:keys [live-js?] :or {live-js? live-js?}} docs] (hiccup/html5 [:head [:meta {:charset "UTF-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1"}] (hiccup/include-css "https://cdn.jsdelivr.net/npm/katex@0.13.13/dist/katex.min.css") (hiccup/include-css (cond-> "/css/app.css" (not live-js?) resource->static-url)) (hiccup/include-css (cond-> "/css/viewer.css" (not live-js?) resource->static-url)) (hiccup/include-js (cond-> "/js/viewer.js" (not live-js?) resource->static-url))] [:body [:div#clerk-static-app] [:script "let viewer = nextjournal.clerk.sci_viewer let app = nextjournal.clerk.static_app let docs = viewer.read_string(" (-> docs ->edn pr-str) ") app.init(docs)\n"]])) (defn doc->html [doc] (->html {} (doc->viewer {} doc))) (defn doc->static-html [doc] (->html {:conn-ws? false :live-js? false} (doc->viewer {:inline-results? true} doc))) #_(let [out "test.html"] (spit out (doc->static-html (nextjournal.clerk/eval-file "notebooks/pagination.clj"))) (clojure.java.browse/browse-url out))
68781
(ns nextjournal.clerk.view (:require [nextjournal.clerk.viewer :as v] [hiccup.page :as hiccup] [clojure.pprint :as pprint] [clojure.string :as str] [clojure.walk :as w])) (defn ex->viewer [e] (v/exception (Throwable->map e))) #_(doc->viewer (nextjournal.clerk/eval-file "notebooks/elements.clj")) (defn var->data [v] (v/with-viewer* :clerk/var (symbol v))) #_(var->data #'var->data) (defn fn->str [f] (let [pr-rep (pr-str f) f-name (subs pr-rep (count "#function[") (- (count pr-rep) 1))] f-name)) #_(fn->str (fn [])) #_(fn->str +) (defn make-printable [x] (cond-> x (var? x) var->data (meta x) (with-meta {}) (fn? x) fn->str)) #_(meta (make-printable ^{:f (fn [])} [])) (defn ->edn [x] (binding [*print-namespace-maps* false] (pr-str (try (w/prewalk make-printable x) (catch Throwable _ x))))) #_(->edn [:vec (with-meta [] {'clojure.core.protocols/datafy (fn [x] x)}) :var #'->edn]) (defn described-result [_ns {:keys [result blob-id]}] (v/with-viewer* :clerk/result {:blob-id blob-id :viewer (v/viewer result)})) (defn inline-result [ns {:keys [result]}] (v/with-viewer* :clerk/inline-result (try {:edn (->edn (v/describe result {:viewers (v/get-viewers ns (v/viewers result))}))} (catch Exception _ {:string (pr-str result)})))) (defn doc->viewer ([doc] (doc->viewer {} doc)) ([{:keys [inline-results?] :or {inline-results? false}} doc] (let [{:keys [ns]} (meta doc)] (cond-> (into [] (mapcat (fn [{:as x :keys [type text result]}] (case type :markdown [(v/md text)] :code (cond-> [(v/code text)] (contains? x :result) (conj (cond (v/registration? (:result result)) (:result result) (and (not inline-results?) (map? result) (contains? result :result) (contains? result :blob-id)) (described-result ns result) :else (inline-result ns result))))))) doc) true v/notebook ns (assoc :scope (v/datafy-scope ns)))))) #_(meta (doc->viewer (nextjournal.clerk/eval-file "notebooks/elements.clj"))) #_(nextjournal.clerk/show! "notebooks/test.clj") (defonce ^{:doc "Load dynamic js from shadow or static bundle from cdn."} live-js? (when-let [prop (System/getProperty "clerk.live_js")] (not= "false" prop))) (def resource->static-url {"/css/app.css" "https://storage.googleapis.com/nextjournal-cas-eu/data/8VxQBDwk3cvr1bt8YVL5m6bJGrFEmzrSbCrH1roypLjJr4AbbteCKh9Y6gQVYexdY85QA2HG5nQFLWpRp69zFSPDJ9" "/css/viewer.css" "https://storage.googleapis.com/nextjournal-cas-eu/data/8VxoxUgsBRs2yjjBBcfeCc8XigM7erXHmjJg2tjdGxNBxwTYuDonuYswXqRStaCA2b3rTEPCgPwixJmAVrea1qAHHU" "/js/viewer.js" "https://storage.googleapis.com/nextjournal-cas-eu/data/8VujAQ3bHzg<KEY>"}) (defn ->html [{:keys [conn-ws? live-js?] :or {conn-ws? true live-js? live-js?}} doc] (hiccup/html5 [:head [:meta {:charset "UTF-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1"}] (hiccup/include-css "https://cdn.jsdelivr.net/npm/katex@0.13.13/dist/katex.min.css") (hiccup/include-css (cond-> "/css/app.css" (not live-js?) resource->static-url)) (hiccup/include-css (cond-> "/css/viewer.css" (not live-js?) resource->static-url)) (hiccup/include-js (cond-> "/js/viewer.js" (not live-js?) resource->static-url))] [:body [:div#clerk] [:script "let viewer = nextjournal.clerk.sci_viewer let doc = " (-> doc ->edn pr-str) " viewer.reset_doc(viewer.read_string(doc)) viewer.mount(document.getElementById('clerk'))\n" (when conn-ws? "const ws = new WebSocket(document.location.origin.replace(/^http/, 'ws') + '/_ws') ws.onmessage = msg => viewer.reset_doc(viewer.read_string(msg.data))")]])) (defn ->static-app [{:keys [live-js?] :or {live-js? live-js?}} docs] (hiccup/html5 [:head [:meta {:charset "UTF-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1"}] (hiccup/include-css "https://cdn.jsdelivr.net/npm/katex@0.13.13/dist/katex.min.css") (hiccup/include-css (cond-> "/css/app.css" (not live-js?) resource->static-url)) (hiccup/include-css (cond-> "/css/viewer.css" (not live-js?) resource->static-url)) (hiccup/include-js (cond-> "/js/viewer.js" (not live-js?) resource->static-url))] [:body [:div#clerk-static-app] [:script "let viewer = nextjournal.clerk.sci_viewer let app = nextjournal.clerk.static_app let docs = viewer.read_string(" (-> docs ->edn pr-str) ") app.init(docs)\n"]])) (defn doc->html [doc] (->html {} (doc->viewer {} doc))) (defn doc->static-html [doc] (->html {:conn-ws? false :live-js? false} (doc->viewer {:inline-results? true} doc))) #_(let [out "test.html"] (spit out (doc->static-html (nextjournal.clerk/eval-file "notebooks/pagination.clj"))) (clojure.java.browse/browse-url out))
true
(ns nextjournal.clerk.view (:require [nextjournal.clerk.viewer :as v] [hiccup.page :as hiccup] [clojure.pprint :as pprint] [clojure.string :as str] [clojure.walk :as w])) (defn ex->viewer [e] (v/exception (Throwable->map e))) #_(doc->viewer (nextjournal.clerk/eval-file "notebooks/elements.clj")) (defn var->data [v] (v/with-viewer* :clerk/var (symbol v))) #_(var->data #'var->data) (defn fn->str [f] (let [pr-rep (pr-str f) f-name (subs pr-rep (count "#function[") (- (count pr-rep) 1))] f-name)) #_(fn->str (fn [])) #_(fn->str +) (defn make-printable [x] (cond-> x (var? x) var->data (meta x) (with-meta {}) (fn? x) fn->str)) #_(meta (make-printable ^{:f (fn [])} [])) (defn ->edn [x] (binding [*print-namespace-maps* false] (pr-str (try (w/prewalk make-printable x) (catch Throwable _ x))))) #_(->edn [:vec (with-meta [] {'clojure.core.protocols/datafy (fn [x] x)}) :var #'->edn]) (defn described-result [_ns {:keys [result blob-id]}] (v/with-viewer* :clerk/result {:blob-id blob-id :viewer (v/viewer result)})) (defn inline-result [ns {:keys [result]}] (v/with-viewer* :clerk/inline-result (try {:edn (->edn (v/describe result {:viewers (v/get-viewers ns (v/viewers result))}))} (catch Exception _ {:string (pr-str result)})))) (defn doc->viewer ([doc] (doc->viewer {} doc)) ([{:keys [inline-results?] :or {inline-results? false}} doc] (let [{:keys [ns]} (meta doc)] (cond-> (into [] (mapcat (fn [{:as x :keys [type text result]}] (case type :markdown [(v/md text)] :code (cond-> [(v/code text)] (contains? x :result) (conj (cond (v/registration? (:result result)) (:result result) (and (not inline-results?) (map? result) (contains? result :result) (contains? result :blob-id)) (described-result ns result) :else (inline-result ns result))))))) doc) true v/notebook ns (assoc :scope (v/datafy-scope ns)))))) #_(meta (doc->viewer (nextjournal.clerk/eval-file "notebooks/elements.clj"))) #_(nextjournal.clerk/show! "notebooks/test.clj") (defonce ^{:doc "Load dynamic js from shadow or static bundle from cdn."} live-js? (when-let [prop (System/getProperty "clerk.live_js")] (not= "false" prop))) (def resource->static-url {"/css/app.css" "https://storage.googleapis.com/nextjournal-cas-eu/data/8VxQBDwk3cvr1bt8YVL5m6bJGrFEmzrSbCrH1roypLjJr4AbbteCKh9Y6gQVYexdY85QA2HG5nQFLWpRp69zFSPDJ9" "/css/viewer.css" "https://storage.googleapis.com/nextjournal-cas-eu/data/8VxoxUgsBRs2yjjBBcfeCc8XigM7erXHmjJg2tjdGxNBxwTYuDonuYswXqRStaCA2b3rTEPCgPwixJmAVrea1qAHHU" "/js/viewer.js" "https://storage.googleapis.com/nextjournal-cas-eu/data/8VujAQ3bHzgPI:KEY:<KEY>END_PI"}) (defn ->html [{:keys [conn-ws? live-js?] :or {conn-ws? true live-js? live-js?}} doc] (hiccup/html5 [:head [:meta {:charset "UTF-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1"}] (hiccup/include-css "https://cdn.jsdelivr.net/npm/katex@0.13.13/dist/katex.min.css") (hiccup/include-css (cond-> "/css/app.css" (not live-js?) resource->static-url)) (hiccup/include-css (cond-> "/css/viewer.css" (not live-js?) resource->static-url)) (hiccup/include-js (cond-> "/js/viewer.js" (not live-js?) resource->static-url))] [:body [:div#clerk] [:script "let viewer = nextjournal.clerk.sci_viewer let doc = " (-> doc ->edn pr-str) " viewer.reset_doc(viewer.read_string(doc)) viewer.mount(document.getElementById('clerk'))\n" (when conn-ws? "const ws = new WebSocket(document.location.origin.replace(/^http/, 'ws') + '/_ws') ws.onmessage = msg => viewer.reset_doc(viewer.read_string(msg.data))")]])) (defn ->static-app [{:keys [live-js?] :or {live-js? live-js?}} docs] (hiccup/html5 [:head [:meta {:charset "UTF-8"}] [:meta {:name "viewport" :content "width=device-width, initial-scale=1"}] (hiccup/include-css "https://cdn.jsdelivr.net/npm/katex@0.13.13/dist/katex.min.css") (hiccup/include-css (cond-> "/css/app.css" (not live-js?) resource->static-url)) (hiccup/include-css (cond-> "/css/viewer.css" (not live-js?) resource->static-url)) (hiccup/include-js (cond-> "/js/viewer.js" (not live-js?) resource->static-url))] [:body [:div#clerk-static-app] [:script "let viewer = nextjournal.clerk.sci_viewer let app = nextjournal.clerk.static_app let docs = viewer.read_string(" (-> docs ->edn pr-str) ") app.init(docs)\n"]])) (defn doc->html [doc] (->html {} (doc->viewer {} doc))) (defn doc->static-html [doc] (->html {:conn-ws? false :live-js? false} (doc->viewer {:inline-results? true} doc))) #_(let [out "test.html"] (spit out (doc->static-html (nextjournal.clerk/eval-file "notebooks/pagination.clj"))) (clojure.java.browse/browse-url out))
[ { "context": "TODO use the helpers here:\n;;; https://github.com/fulcrologic/fulcro-rad/blob/develop/src/main/com/fulcrologic/", "end": 2614, "score": 0.9944445490837097, "start": 2603, "tag": "USERNAME", "value": "fulcrologic" }, { "context": "-keys resp))\n resp))))\n\n(def response-key :dv/response)\n\n(defn assoc-response [in-map response]\n (assoc", "end": 5904, "score": 0.9967266917228699, "start": 5893, "tag": "KEY", "value": "dv/response" } ]
src/main/dv/pathom.clj
callum-herries/my-clj-utils
0
(ns dv.pathom (:require [clojure.pprint :refer [pprint]] [com.wsscode.pathom.connect :as pc] [com.wsscode.pathom.core :as p] [com.wsscode.pathom.viz.ws-connector.core :as pathom-viz] [io.pedestal.interceptor.chain :as chain] [io.pedestal.interceptor.helpers :as ih] [edn-query-language.core :as eql] [taoensso.timbre :as log] [clojure.walk :as w])) (pc/defresolver index-explorer [env _] {::pc/input #{:com.wsscode.pathom.viz.index-explorer/id} ::pc/output [:com.wsscode.pathom.viz.index-explorer/index]} {:com.wsscode.pathom.viz.index-explorer/index (-> (get env ::pc/indexes) (update ::pc/index-resolvers #(into {} (map (fn [[k v]] [k (dissoc v ::pc/resolve)])) %)) (update ::pc/index-mutations #(into {} (map (fn [[k v]] [k (dissoc v ::pc/mutate)])) %)))}) (defn preprocess-parser-plugin "Helper to create a plugin that can view/modify the env/tx of a top-level request. f - (fn [{:keys [env tx]}] {:env new-env :tx new-tx}) If the function returns no env or tx, then the parser will not be called (aborts the parse)" [f] {::p/wrap-parser (fn transform-parser-out-plugin-external [parser] (fn transform-parser-out-plugin-internal [env tx] (let [{:keys [env tx] :as req} (f {:env env :tx tx})] (if (and (map? env) (seq tx)) (parser env tx) {}))))}) (defn log-requests [{:keys [env tx] :as req}] (println) (log/debug "Pathom transaction:") (pprint tx) (println) req) ;; Captures the last env so you can inspect it at the repl (def -env (atom nil)) (comment (keys @-env) (@-env :target) (@-env :ring/request) (@-env ::p/entity-key) (@-env ::p/entity)) (defn mk-augment-env-request [get-config-map] (fn augment-env-request [env] (reset! -env env) (merge env (get-config-map env)))) ;; Copied from fulcro-rad, but changed to also pass params for mutations. (def query-params-to-env-plugin "Adds top-level load params to env, so nested parsing layers can see them." {::p/wrap-parser (fn [parser] (fn [env tx] (let [children (-> tx eql/query->ast :children) query-params (reduce (fn [qps {:keys [params]}] (cond-> qps (seq params) (merge params))) {} children) env (assoc env :query-params query-params)] (log/info "Query params are: " query-params) (parser env tx))))}) ;;; TODO use the helpers here: ;;; https://github.com/fulcrologic/fulcro-rad/blob/develop/src/main/com/fulcrologic/rad/pathom.clj ;; deals with removing keys and logging responses etc. (defn remove-omissions "Replaces black-listed keys from tx with ::omitted, meant for logging tx's without logging sensitive details like passwords." [sensitive-keys tx] (w/postwalk (fn [x] (if (and (vector? x) (= 2 (count x)) (contains? sensitive-keys (first x))) [(first x) ::omitted] x)) tx)) (defn pprint-val [value] (binding [*print-level* 4 *print-length* 4] (try (with-out-str (pprint value)) (catch Throwable e (log/error (.getMessage e)) "<failed to serialize>")))) (defn log-response! [sensitive-keys response] (log/info "Pathom response:\n" (pprint-val (remove-omissions sensitive-keys response)))) (defn build-parser [{:keys [resolvers log-responses? enable-pathom-viz? env-additions trace? index-explorer? sensitive-keys handle-errors?] :or {handle-errors? true}}] (when (and env-additions (not (fn? env-additions))) (throw (Exception. "build-parser: env-additions must be a function."))) (let [sensitive-keys (conj (set sensitive-keys) :com.wsscode.pathom/trace) handle-errors? handle-errors? parser (p/parser {::p/mutate pc/mutate ::p/env {::p/reader [p/map-reader pc/reader2 pc/index-reader pc/open-ident-reader p/env-placeholder-reader] ::p/placeholder-prefixes #{">"}} ::p/plugins (cond-> [(pc/connect-plugin {::pc/register (cond-> resolvers index-explorer? (conj index-explorer))}) (preprocess-parser-plugin log-requests) query-params-to-env-plugin (p/post-process-parser-plugin p/elide-not-found)] handle-errors? (conj p/error-handler-plugin) env-additions (conj (p/env-wrap-plugin (mk-augment-env-request env-additions))) trace? (conj p/trace-plugin))}) parser (cond->> parser enable-pathom-viz? (pathom-viz/connect-parser {::pathom-viz/parser-id ::parser}))] (fn wrapped-parser [env tx] (when-not (vector? tx) (throw (Exception. "You must pass a vector for the transaction."))) ;; Add trace - pathom-viz already adds it so only add if that's not included. (let [tx (if (and trace? (not enable-pathom-viz?)) (conj tx :com.wsscode.pathom/trace) tx) resp (parser env tx)] (when log-responses? (log-response! sensitive-keys resp)) resp)))) (def response-key :dv/response) (defn assoc-response [in-map response] (assoc-in in-map [:env response-key] response)) (defn get-response [in-map] (get-in in-map [:env response-key])) (defn response-interceptor [{:keys [opts env params] :as in}] (let [{::pc/keys [mutate resolve]} opts response (get-response in)] (if response in (if resolve (assoc-response in (resolve env params)) (assoc-response in (mutate env params)))))) (comment (macroexpand-1 '(go 5)) (def i1 (i/interceptor {:enter (fn [c] (log/info "in i1") c)})) (def i2 (i/interceptor {:enter (fn [c] (go (log/info "in i2")) c)})) (def i3 (ih/before (fn [c] (log/info "in i3") c))) (def my-ints [i1 i2 i3]) (chain/execute-only {} :enter my-ints) ;(def my-chain ()) ) (defn interceptors->pathom-transform "Executes vector of interceptors on a pathom resolver or mutation. Each interceptor is passed a single map (the environment) which has the keys: :opts - The definition-time pathom resolver or mutation map of options. :env - The pathom connect environment for the resolver or mutation passed by pathom at request-time. :params - The params to the resolver or the mutation. Responses are set on the env like so: (assoc-response input-map {:my-pathom-resp :value}) " [interceptors] (fn pathom-transform* [{::pc/keys [mutate resolve] :as opts}] (let [interceptors (conj interceptors (ih/after response-interceptor))] (cond resolve (assoc opts ::pc/resolve (fn [en params] (let [respo (chain/execute {:opts opts :env en :params params} interceptors)] (get-response respo)))) mutate (assoc opts ::pc/mutate (fn [en params] (let [respo (chain/execute {:opts opts :env en :params params} interceptors)] (get-response respo)))) :else (throw (Exception. (str "Attempting to use interceptor transform on a map that is not a resolve or mutate."))))))) ;; todo ;; I think I can use pedestals chain/terminate-when for this type of logic (defn unless-response [f] (fn unless-response* [in] (if (get-response in) in (f in))))
94640
(ns dv.pathom (:require [clojure.pprint :refer [pprint]] [com.wsscode.pathom.connect :as pc] [com.wsscode.pathom.core :as p] [com.wsscode.pathom.viz.ws-connector.core :as pathom-viz] [io.pedestal.interceptor.chain :as chain] [io.pedestal.interceptor.helpers :as ih] [edn-query-language.core :as eql] [taoensso.timbre :as log] [clojure.walk :as w])) (pc/defresolver index-explorer [env _] {::pc/input #{:com.wsscode.pathom.viz.index-explorer/id} ::pc/output [:com.wsscode.pathom.viz.index-explorer/index]} {:com.wsscode.pathom.viz.index-explorer/index (-> (get env ::pc/indexes) (update ::pc/index-resolvers #(into {} (map (fn [[k v]] [k (dissoc v ::pc/resolve)])) %)) (update ::pc/index-mutations #(into {} (map (fn [[k v]] [k (dissoc v ::pc/mutate)])) %)))}) (defn preprocess-parser-plugin "Helper to create a plugin that can view/modify the env/tx of a top-level request. f - (fn [{:keys [env tx]}] {:env new-env :tx new-tx}) If the function returns no env or tx, then the parser will not be called (aborts the parse)" [f] {::p/wrap-parser (fn transform-parser-out-plugin-external [parser] (fn transform-parser-out-plugin-internal [env tx] (let [{:keys [env tx] :as req} (f {:env env :tx tx})] (if (and (map? env) (seq tx)) (parser env tx) {}))))}) (defn log-requests [{:keys [env tx] :as req}] (println) (log/debug "Pathom transaction:") (pprint tx) (println) req) ;; Captures the last env so you can inspect it at the repl (def -env (atom nil)) (comment (keys @-env) (@-env :target) (@-env :ring/request) (@-env ::p/entity-key) (@-env ::p/entity)) (defn mk-augment-env-request [get-config-map] (fn augment-env-request [env] (reset! -env env) (merge env (get-config-map env)))) ;; Copied from fulcro-rad, but changed to also pass params for mutations. (def query-params-to-env-plugin "Adds top-level load params to env, so nested parsing layers can see them." {::p/wrap-parser (fn [parser] (fn [env tx] (let [children (-> tx eql/query->ast :children) query-params (reduce (fn [qps {:keys [params]}] (cond-> qps (seq params) (merge params))) {} children) env (assoc env :query-params query-params)] (log/info "Query params are: " query-params) (parser env tx))))}) ;;; TODO use the helpers here: ;;; https://github.com/fulcrologic/fulcro-rad/blob/develop/src/main/com/fulcrologic/rad/pathom.clj ;; deals with removing keys and logging responses etc. (defn remove-omissions "Replaces black-listed keys from tx with ::omitted, meant for logging tx's without logging sensitive details like passwords." [sensitive-keys tx] (w/postwalk (fn [x] (if (and (vector? x) (= 2 (count x)) (contains? sensitive-keys (first x))) [(first x) ::omitted] x)) tx)) (defn pprint-val [value] (binding [*print-level* 4 *print-length* 4] (try (with-out-str (pprint value)) (catch Throwable e (log/error (.getMessage e)) "<failed to serialize>")))) (defn log-response! [sensitive-keys response] (log/info "Pathom response:\n" (pprint-val (remove-omissions sensitive-keys response)))) (defn build-parser [{:keys [resolvers log-responses? enable-pathom-viz? env-additions trace? index-explorer? sensitive-keys handle-errors?] :or {handle-errors? true}}] (when (and env-additions (not (fn? env-additions))) (throw (Exception. "build-parser: env-additions must be a function."))) (let [sensitive-keys (conj (set sensitive-keys) :com.wsscode.pathom/trace) handle-errors? handle-errors? parser (p/parser {::p/mutate pc/mutate ::p/env {::p/reader [p/map-reader pc/reader2 pc/index-reader pc/open-ident-reader p/env-placeholder-reader] ::p/placeholder-prefixes #{">"}} ::p/plugins (cond-> [(pc/connect-plugin {::pc/register (cond-> resolvers index-explorer? (conj index-explorer))}) (preprocess-parser-plugin log-requests) query-params-to-env-plugin (p/post-process-parser-plugin p/elide-not-found)] handle-errors? (conj p/error-handler-plugin) env-additions (conj (p/env-wrap-plugin (mk-augment-env-request env-additions))) trace? (conj p/trace-plugin))}) parser (cond->> parser enable-pathom-viz? (pathom-viz/connect-parser {::pathom-viz/parser-id ::parser}))] (fn wrapped-parser [env tx] (when-not (vector? tx) (throw (Exception. "You must pass a vector for the transaction."))) ;; Add trace - pathom-viz already adds it so only add if that's not included. (let [tx (if (and trace? (not enable-pathom-viz?)) (conj tx :com.wsscode.pathom/trace) tx) resp (parser env tx)] (when log-responses? (log-response! sensitive-keys resp)) resp)))) (def response-key :<KEY>) (defn assoc-response [in-map response] (assoc-in in-map [:env response-key] response)) (defn get-response [in-map] (get-in in-map [:env response-key])) (defn response-interceptor [{:keys [opts env params] :as in}] (let [{::pc/keys [mutate resolve]} opts response (get-response in)] (if response in (if resolve (assoc-response in (resolve env params)) (assoc-response in (mutate env params)))))) (comment (macroexpand-1 '(go 5)) (def i1 (i/interceptor {:enter (fn [c] (log/info "in i1") c)})) (def i2 (i/interceptor {:enter (fn [c] (go (log/info "in i2")) c)})) (def i3 (ih/before (fn [c] (log/info "in i3") c))) (def my-ints [i1 i2 i3]) (chain/execute-only {} :enter my-ints) ;(def my-chain ()) ) (defn interceptors->pathom-transform "Executes vector of interceptors on a pathom resolver or mutation. Each interceptor is passed a single map (the environment) which has the keys: :opts - The definition-time pathom resolver or mutation map of options. :env - The pathom connect environment for the resolver or mutation passed by pathom at request-time. :params - The params to the resolver or the mutation. Responses are set on the env like so: (assoc-response input-map {:my-pathom-resp :value}) " [interceptors] (fn pathom-transform* [{::pc/keys [mutate resolve] :as opts}] (let [interceptors (conj interceptors (ih/after response-interceptor))] (cond resolve (assoc opts ::pc/resolve (fn [en params] (let [respo (chain/execute {:opts opts :env en :params params} interceptors)] (get-response respo)))) mutate (assoc opts ::pc/mutate (fn [en params] (let [respo (chain/execute {:opts opts :env en :params params} interceptors)] (get-response respo)))) :else (throw (Exception. (str "Attempting to use interceptor transform on a map that is not a resolve or mutate."))))))) ;; todo ;; I think I can use pedestals chain/terminate-when for this type of logic (defn unless-response [f] (fn unless-response* [in] (if (get-response in) in (f in))))
true
(ns dv.pathom (:require [clojure.pprint :refer [pprint]] [com.wsscode.pathom.connect :as pc] [com.wsscode.pathom.core :as p] [com.wsscode.pathom.viz.ws-connector.core :as pathom-viz] [io.pedestal.interceptor.chain :as chain] [io.pedestal.interceptor.helpers :as ih] [edn-query-language.core :as eql] [taoensso.timbre :as log] [clojure.walk :as w])) (pc/defresolver index-explorer [env _] {::pc/input #{:com.wsscode.pathom.viz.index-explorer/id} ::pc/output [:com.wsscode.pathom.viz.index-explorer/index]} {:com.wsscode.pathom.viz.index-explorer/index (-> (get env ::pc/indexes) (update ::pc/index-resolvers #(into {} (map (fn [[k v]] [k (dissoc v ::pc/resolve)])) %)) (update ::pc/index-mutations #(into {} (map (fn [[k v]] [k (dissoc v ::pc/mutate)])) %)))}) (defn preprocess-parser-plugin "Helper to create a plugin that can view/modify the env/tx of a top-level request. f - (fn [{:keys [env tx]}] {:env new-env :tx new-tx}) If the function returns no env or tx, then the parser will not be called (aborts the parse)" [f] {::p/wrap-parser (fn transform-parser-out-plugin-external [parser] (fn transform-parser-out-plugin-internal [env tx] (let [{:keys [env tx] :as req} (f {:env env :tx tx})] (if (and (map? env) (seq tx)) (parser env tx) {}))))}) (defn log-requests [{:keys [env tx] :as req}] (println) (log/debug "Pathom transaction:") (pprint tx) (println) req) ;; Captures the last env so you can inspect it at the repl (def -env (atom nil)) (comment (keys @-env) (@-env :target) (@-env :ring/request) (@-env ::p/entity-key) (@-env ::p/entity)) (defn mk-augment-env-request [get-config-map] (fn augment-env-request [env] (reset! -env env) (merge env (get-config-map env)))) ;; Copied from fulcro-rad, but changed to also pass params for mutations. (def query-params-to-env-plugin "Adds top-level load params to env, so nested parsing layers can see them." {::p/wrap-parser (fn [parser] (fn [env tx] (let [children (-> tx eql/query->ast :children) query-params (reduce (fn [qps {:keys [params]}] (cond-> qps (seq params) (merge params))) {} children) env (assoc env :query-params query-params)] (log/info "Query params are: " query-params) (parser env tx))))}) ;;; TODO use the helpers here: ;;; https://github.com/fulcrologic/fulcro-rad/blob/develop/src/main/com/fulcrologic/rad/pathom.clj ;; deals with removing keys and logging responses etc. (defn remove-omissions "Replaces black-listed keys from tx with ::omitted, meant for logging tx's without logging sensitive details like passwords." [sensitive-keys tx] (w/postwalk (fn [x] (if (and (vector? x) (= 2 (count x)) (contains? sensitive-keys (first x))) [(first x) ::omitted] x)) tx)) (defn pprint-val [value] (binding [*print-level* 4 *print-length* 4] (try (with-out-str (pprint value)) (catch Throwable e (log/error (.getMessage e)) "<failed to serialize>")))) (defn log-response! [sensitive-keys response] (log/info "Pathom response:\n" (pprint-val (remove-omissions sensitive-keys response)))) (defn build-parser [{:keys [resolvers log-responses? enable-pathom-viz? env-additions trace? index-explorer? sensitive-keys handle-errors?] :or {handle-errors? true}}] (when (and env-additions (not (fn? env-additions))) (throw (Exception. "build-parser: env-additions must be a function."))) (let [sensitive-keys (conj (set sensitive-keys) :com.wsscode.pathom/trace) handle-errors? handle-errors? parser (p/parser {::p/mutate pc/mutate ::p/env {::p/reader [p/map-reader pc/reader2 pc/index-reader pc/open-ident-reader p/env-placeholder-reader] ::p/placeholder-prefixes #{">"}} ::p/plugins (cond-> [(pc/connect-plugin {::pc/register (cond-> resolvers index-explorer? (conj index-explorer))}) (preprocess-parser-plugin log-requests) query-params-to-env-plugin (p/post-process-parser-plugin p/elide-not-found)] handle-errors? (conj p/error-handler-plugin) env-additions (conj (p/env-wrap-plugin (mk-augment-env-request env-additions))) trace? (conj p/trace-plugin))}) parser (cond->> parser enable-pathom-viz? (pathom-viz/connect-parser {::pathom-viz/parser-id ::parser}))] (fn wrapped-parser [env tx] (when-not (vector? tx) (throw (Exception. "You must pass a vector for the transaction."))) ;; Add trace - pathom-viz already adds it so only add if that's not included. (let [tx (if (and trace? (not enable-pathom-viz?)) (conj tx :com.wsscode.pathom/trace) tx) resp (parser env tx)] (when log-responses? (log-response! sensitive-keys resp)) resp)))) (def response-key :PI:KEY:<KEY>END_PI) (defn assoc-response [in-map response] (assoc-in in-map [:env response-key] response)) (defn get-response [in-map] (get-in in-map [:env response-key])) (defn response-interceptor [{:keys [opts env params] :as in}] (let [{::pc/keys [mutate resolve]} opts response (get-response in)] (if response in (if resolve (assoc-response in (resolve env params)) (assoc-response in (mutate env params)))))) (comment (macroexpand-1 '(go 5)) (def i1 (i/interceptor {:enter (fn [c] (log/info "in i1") c)})) (def i2 (i/interceptor {:enter (fn [c] (go (log/info "in i2")) c)})) (def i3 (ih/before (fn [c] (log/info "in i3") c))) (def my-ints [i1 i2 i3]) (chain/execute-only {} :enter my-ints) ;(def my-chain ()) ) (defn interceptors->pathom-transform "Executes vector of interceptors on a pathom resolver or mutation. Each interceptor is passed a single map (the environment) which has the keys: :opts - The definition-time pathom resolver or mutation map of options. :env - The pathom connect environment for the resolver or mutation passed by pathom at request-time. :params - The params to the resolver or the mutation. Responses are set on the env like so: (assoc-response input-map {:my-pathom-resp :value}) " [interceptors] (fn pathom-transform* [{::pc/keys [mutate resolve] :as opts}] (let [interceptors (conj interceptors (ih/after response-interceptor))] (cond resolve (assoc opts ::pc/resolve (fn [en params] (let [respo (chain/execute {:opts opts :env en :params params} interceptors)] (get-response respo)))) mutate (assoc opts ::pc/mutate (fn [en params] (let [respo (chain/execute {:opts opts :env en :params params} interceptors)] (get-response respo)))) :else (throw (Exception. (str "Attempting to use interceptor transform on a map that is not a resolve or mutate."))))))) ;; todo ;; I think I can use pedestals chain/terminate-when for this type of logic (defn unless-response [f] (fn unless-response* [in] (if (get-response in) in (f in))))
[ { "context": ";; Copyright (c) Stephen C. Gilardi. All rights reserved. The use and\n;; distributi", "end": 36, "score": 0.9998669624328613, "start": 18, "tag": "NAME", "value": "Stephen C. Gilardi" }, { "context": "ib.condition to implement a \"Throwable map\"\n;;\n;; scgilardi (gmail)\n;; Created 09 June 2009\n\n(ns clojure.co", "end": 581, "score": 0.6783812642097473, "start": 573, "tag": "USERNAME", "value": "scgilard" } ]
ThirdParty/clojure-contrib-1.1.0/src/clojure/contrib/condition/Condition.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. ;; ;; Condition.clj ;; ;; Used by clojure.contrib.condition to implement a "Throwable map" ;; ;; scgilardi (gmail) ;; Created 09 June 2009 (ns clojure.contrib.condition.Condition (:gen-class :extends Throwable :implements [clojure.lang.IMeta] :state state :init init :post-init post-init :constructors {[clojure.lang.IPersistentMap] [String Throwable]})) (defn -init "Constructs a Condition object with condition (a map) as its metadata. Also initializes the superclass with the values at :message and :cause, if any, so they are also available via .getMessage and .getCause." [condition] [[(:message condition) (:cause condition)] (atom condition)]) (defn -post-init "Adds :stack-trace to the condition. Drops the bottom 3 frames because they are always the same: implementation details of Condition and raise." [this condition] (swap! (.state this) assoc :stack-trace (into-array (drop 3 (.getStackTrace this))))) (defn -meta "Returns this object's metadata, the condition" [this] @(.state this))
68615
;; 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. ;; ;; Condition.clj ;; ;; Used by clojure.contrib.condition to implement a "Throwable map" ;; ;; scgilardi (gmail) ;; Created 09 June 2009 (ns clojure.contrib.condition.Condition (:gen-class :extends Throwable :implements [clojure.lang.IMeta] :state state :init init :post-init post-init :constructors {[clojure.lang.IPersistentMap] [String Throwable]})) (defn -init "Constructs a Condition object with condition (a map) as its metadata. Also initializes the superclass with the values at :message and :cause, if any, so they are also available via .getMessage and .getCause." [condition] [[(:message condition) (:cause condition)] (atom condition)]) (defn -post-init "Adds :stack-trace to the condition. Drops the bottom 3 frames because they are always the same: implementation details of Condition and raise." [this condition] (swap! (.state this) assoc :stack-trace (into-array (drop 3 (.getStackTrace this))))) (defn -meta "Returns this object's metadata, the condition" [this] @(.state this))
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. ;; ;; Condition.clj ;; ;; Used by clojure.contrib.condition to implement a "Throwable map" ;; ;; scgilardi (gmail) ;; Created 09 June 2009 (ns clojure.contrib.condition.Condition (:gen-class :extends Throwable :implements [clojure.lang.IMeta] :state state :init init :post-init post-init :constructors {[clojure.lang.IPersistentMap] [String Throwable]})) (defn -init "Constructs a Condition object with condition (a map) as its metadata. Also initializes the superclass with the values at :message and :cause, if any, so they are also available via .getMessage and .getCause." [condition] [[(:message condition) (:cause condition)] (atom condition)]) (defn -post-init "Adds :stack-trace to the condition. Drops the bottom 3 frames because they are always the same: implementation details of Condition and raise." [this condition] (swap! (.state this) assoc :stack-trace (into-array (drop 3 (.getStackTrace this))))) (defn -meta "Returns this object's metadata, the condition" [this] @(.state this))