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": ";; A Ukelele by Roger Allen.\n(ns explore-overtone.ukelele\n (:use [explore-ov",
"end": 27,
"score": 0.9998594522476196,
"start": 16,
"tag": "NAME",
"value": "Roger Allen"
}
] | data/train/clojure/24730c43af3c2f316e54426ccc7d7365617d2f65ukelele.clj | harshp8l/deep-learning-lang-detection | 84 | ;; A Ukelele by Roger Allen.
(ns explore-overtone.ukelele
(:use [explore-overtone.stringed]
[overtone.music pitch]
[overtone.studio inst]
[overtone.sc envelope node server ugens]
[overtone.sc.cgens mix]))
;; a map of chords to frets.
;; -1 indicates you mute that string
;; -2 indicates you leave that string alone
(def ukelele-chord-frets
{:A [ 2 1 0 0 ]
:A7 [ 0 1 0 0 ]
:Am [ 2 0 0 0 ]
:Am7 [ 0 0 0 0 ]
:Bb [ 3 2 1 1 ]
:Bb7 [ 1 2 1 1 ]
:Bbm [ 3 1 1 1 ]
:Bbm7 [ 1 1 1 1 ]
:B [ 4 3 2 2 ]
:B7 [ 2 3 2 2 ]
:Bm [ 4 2 2 2 ]
:Bm7 [ 2 2 2 2 ]
:C [ 0 0 0 3 ]
:C7 [ 0 0 0 1 ]
:Cm [ 0 3 3 3 ]
:Cm7 [ 3 3 3 3 ]
:Db [ 1 1 1 4 ]
:Db7 [ 1 1 1 2 ]
:Dbm [ 1 4 4 4 ]
:Dbm7 [ 4 4 4 4 ]
:D [ 2 2 2 0 ]
:D7 [ 2 2 2 3 ]
:Dm [ 2 2 1 0 ]
:Dm7 [ 2 2 1 3 ]
:Eb [ 3 3 3 6 ]
:Eb7 [ 3 3 3 4 ]
:Ebm [ 3 6 6 6 ]
:Ebm7 [ 3 3 2 4 ]
:E [ 4 4 4 7 ]
:E7 [ 1 2 0 2 ]
:Em [ 0 4 3 2 ]
:Em7 [ 0 2 0 2 ]
:F [ 2 0 1 0 ]
:F7 [ 2 3 1 0 ]
:Fm [ 1 0 1 3 ]
:Fm7 [ 2 2 1 3 ]
:Gb [ 3 1 2 1 ]
:Gb7 [ 3 4 2 4 ]
:Gbm [ 2 1 2 0 ]
:Gbm7 [ 2 4 2 4 ]
:G [ 0 2 3 2 ]
:G7 [ 0 2 1 2 ]
:Gm [ 0 2 3 1 ]
:Gm7 [ 0 2 1 1 ]
:Ab [ 5 3 4 3 ]
:Ab7 [ 1 3 2 3 ]
:Abm [ 4 3 4 2 ]
:Abm7 [ 1 3 2 2 ]
})
;; ======================================================================
;; an array of 4 ukelele strings: GCEA (order low-to-hi is CEGA)
(def ukelele-string-notes (map note [:g4 :c4 :e4 :a4]))
;; ======================================================================
;; Main helper functions. Use pick or strum to play the ukelele instrument.
(def pick (partial pick-string ukelele-string-notes))
(def strum (partial strum-strings ukelele-chord-frets ukelele-string-notes))
;; ======================================================================
;; Create the ukelele definst. Now via the power of macros
(gen-stringed-inst ukelele 4)
| 30391 | ;; A Ukelele by <NAME>.
(ns explore-overtone.ukelele
(:use [explore-overtone.stringed]
[overtone.music pitch]
[overtone.studio inst]
[overtone.sc envelope node server ugens]
[overtone.sc.cgens mix]))
;; a map of chords to frets.
;; -1 indicates you mute that string
;; -2 indicates you leave that string alone
(def ukelele-chord-frets
{:A [ 2 1 0 0 ]
:A7 [ 0 1 0 0 ]
:Am [ 2 0 0 0 ]
:Am7 [ 0 0 0 0 ]
:Bb [ 3 2 1 1 ]
:Bb7 [ 1 2 1 1 ]
:Bbm [ 3 1 1 1 ]
:Bbm7 [ 1 1 1 1 ]
:B [ 4 3 2 2 ]
:B7 [ 2 3 2 2 ]
:Bm [ 4 2 2 2 ]
:Bm7 [ 2 2 2 2 ]
:C [ 0 0 0 3 ]
:C7 [ 0 0 0 1 ]
:Cm [ 0 3 3 3 ]
:Cm7 [ 3 3 3 3 ]
:Db [ 1 1 1 4 ]
:Db7 [ 1 1 1 2 ]
:Dbm [ 1 4 4 4 ]
:Dbm7 [ 4 4 4 4 ]
:D [ 2 2 2 0 ]
:D7 [ 2 2 2 3 ]
:Dm [ 2 2 1 0 ]
:Dm7 [ 2 2 1 3 ]
:Eb [ 3 3 3 6 ]
:Eb7 [ 3 3 3 4 ]
:Ebm [ 3 6 6 6 ]
:Ebm7 [ 3 3 2 4 ]
:E [ 4 4 4 7 ]
:E7 [ 1 2 0 2 ]
:Em [ 0 4 3 2 ]
:Em7 [ 0 2 0 2 ]
:F [ 2 0 1 0 ]
:F7 [ 2 3 1 0 ]
:Fm [ 1 0 1 3 ]
:Fm7 [ 2 2 1 3 ]
:Gb [ 3 1 2 1 ]
:Gb7 [ 3 4 2 4 ]
:Gbm [ 2 1 2 0 ]
:Gbm7 [ 2 4 2 4 ]
:G [ 0 2 3 2 ]
:G7 [ 0 2 1 2 ]
:Gm [ 0 2 3 1 ]
:Gm7 [ 0 2 1 1 ]
:Ab [ 5 3 4 3 ]
:Ab7 [ 1 3 2 3 ]
:Abm [ 4 3 4 2 ]
:Abm7 [ 1 3 2 2 ]
})
;; ======================================================================
;; an array of 4 ukelele strings: GCEA (order low-to-hi is CEGA)
(def ukelele-string-notes (map note [:g4 :c4 :e4 :a4]))
;; ======================================================================
;; Main helper functions. Use pick or strum to play the ukelele instrument.
(def pick (partial pick-string ukelele-string-notes))
(def strum (partial strum-strings ukelele-chord-frets ukelele-string-notes))
;; ======================================================================
;; Create the ukelele definst. Now via the power of macros
(gen-stringed-inst ukelele 4)
| true | ;; A Ukelele by PI:NAME:<NAME>END_PI.
(ns explore-overtone.ukelele
(:use [explore-overtone.stringed]
[overtone.music pitch]
[overtone.studio inst]
[overtone.sc envelope node server ugens]
[overtone.sc.cgens mix]))
;; a map of chords to frets.
;; -1 indicates you mute that string
;; -2 indicates you leave that string alone
(def ukelele-chord-frets
{:A [ 2 1 0 0 ]
:A7 [ 0 1 0 0 ]
:Am [ 2 0 0 0 ]
:Am7 [ 0 0 0 0 ]
:Bb [ 3 2 1 1 ]
:Bb7 [ 1 2 1 1 ]
:Bbm [ 3 1 1 1 ]
:Bbm7 [ 1 1 1 1 ]
:B [ 4 3 2 2 ]
:B7 [ 2 3 2 2 ]
:Bm [ 4 2 2 2 ]
:Bm7 [ 2 2 2 2 ]
:C [ 0 0 0 3 ]
:C7 [ 0 0 0 1 ]
:Cm [ 0 3 3 3 ]
:Cm7 [ 3 3 3 3 ]
:Db [ 1 1 1 4 ]
:Db7 [ 1 1 1 2 ]
:Dbm [ 1 4 4 4 ]
:Dbm7 [ 4 4 4 4 ]
:D [ 2 2 2 0 ]
:D7 [ 2 2 2 3 ]
:Dm [ 2 2 1 0 ]
:Dm7 [ 2 2 1 3 ]
:Eb [ 3 3 3 6 ]
:Eb7 [ 3 3 3 4 ]
:Ebm [ 3 6 6 6 ]
:Ebm7 [ 3 3 2 4 ]
:E [ 4 4 4 7 ]
:E7 [ 1 2 0 2 ]
:Em [ 0 4 3 2 ]
:Em7 [ 0 2 0 2 ]
:F [ 2 0 1 0 ]
:F7 [ 2 3 1 0 ]
:Fm [ 1 0 1 3 ]
:Fm7 [ 2 2 1 3 ]
:Gb [ 3 1 2 1 ]
:Gb7 [ 3 4 2 4 ]
:Gbm [ 2 1 2 0 ]
:Gbm7 [ 2 4 2 4 ]
:G [ 0 2 3 2 ]
:G7 [ 0 2 1 2 ]
:Gm [ 0 2 3 1 ]
:Gm7 [ 0 2 1 1 ]
:Ab [ 5 3 4 3 ]
:Ab7 [ 1 3 2 3 ]
:Abm [ 4 3 4 2 ]
:Abm7 [ 1 3 2 2 ]
})
;; ======================================================================
;; an array of 4 ukelele strings: GCEA (order low-to-hi is CEGA)
(def ukelele-string-notes (map note [:g4 :c4 :e4 :a4]))
;; ======================================================================
;; Main helper functions. Use pick or strum to play the ukelele instrument.
(def pick (partial pick-string ukelele-string-notes))
(def strum (partial strum-strings ukelele-chord-frets ukelele-string-notes))
;; ======================================================================
;; Create the ukelele definst. Now via the power of macros
(gen-stringed-inst ukelele 4)
|
[
{
"context": "e \"otto\" :href \"http://otto.de\"}]}\n\n {:title \"Spaß\"\n :items [{:title \"kicker\" :href \"http://kick",
"end": 238,
"score": 0.6136068105697632,
"start": 237,
"tag": "NAME",
"value": "a"
}
] | src/cljs/bookmarks/db.cljs | meandor/motherbox | 1 | (ns bookmarks.db)
(def bookmark-groups
[{:title "General"
:items [{:title "google" :href "http://google.de"}
{:title "heise" :href "http://heise.de"}
{:title "otto" :href "http://otto.de"}]}
{:title "Spaß"
:items [{:title "kicker" :href "http://kicker.de"}
{:title "heise" :href "http://heise.de"}
{:title "otto" :href "http://otto.de"}]}])
(def default-db
{:name "Company Name"
:bookmarks bookmark-groups
:filter-by ""})
| 103413 | (ns bookmarks.db)
(def bookmark-groups
[{:title "General"
:items [{:title "google" :href "http://google.de"}
{:title "heise" :href "http://heise.de"}
{:title "otto" :href "http://otto.de"}]}
{:title "Sp<NAME>ß"
:items [{:title "kicker" :href "http://kicker.de"}
{:title "heise" :href "http://heise.de"}
{:title "otto" :href "http://otto.de"}]}])
(def default-db
{:name "Company Name"
:bookmarks bookmark-groups
:filter-by ""})
| true | (ns bookmarks.db)
(def bookmark-groups
[{:title "General"
:items [{:title "google" :href "http://google.de"}
{:title "heise" :href "http://heise.de"}
{:title "otto" :href "http://otto.de"}]}
{:title "SpPI:NAME:<NAME>END_PIß"
:items [{:title "kicker" :href "http://kicker.de"}
{:title "heise" :href "http://heise.de"}
{:title "otto" :href "http://otto.de"}]}])
(def default-db
{:name "Company Name"
:bookmarks bookmark-groups
:filter-by ""})
|
[
{
"context": " [clojure.test :as t]))\n\n(def admin-login \"admin\")\n(def admin-password \"secretadmin\")\n(def auth-se",
"end": 245,
"score": 0.9979813098907471,
"start": 240,
"tag": "USERNAME",
"value": "admin"
},
{
"context": ")\n\n(def admin-login \"admin\")\n(def admin-password \"secretadmin\")\n(def auth-server-url \"http://localhost:8090/aut",
"end": 280,
"score": 0.9993115663528442,
"start": 269,
"tag": "PASSWORD",
"value": "secretadmin"
}
] | test/keycloak/authz_test.clj | borkdude/keycloak-clojure | 122 | (ns keycloak.authz-test
(:require [keycloak.admin :refer :all]
[keycloak.deployment :as deploy :refer [client-conf keycloak-client]]
[keycloak.authz :as authz]
[clojure.test :as t]))
(def admin-login "admin")
(def admin-password "secretadmin")
(def auth-server-url "http://localhost:8090/auth")
(def integration-test-conf
(deploy/client-conf auth-server-url "master" "admin-cli"))
(def admin-client (deploy/keycloak-client integration-test-conf admin-login admin-password))
(comment
(def kc-admin (deploy/keycloak-client
(deploy/client-conf "master" "mybackend" "http://localhost:8080/auth")
"10337ce2-8dee-44a9-80b2-bc08ff8fc695"))
(def kc-authz (authz/authz-client (deploy/client-conf-input-stream "master" "mybackend" "http://localhost:8080/auth" "10337ce2-8dee-44a9-80b2-bc08ff8fc695")))
(authz/create-resource kc-authz "My resource" "urn:my-authz:resources:my-resource" ["urn:my-authz:scopes:access"])
(authz/create-role-policy kc-admin "master" "mybackend" "testrole" "urn:my-authz:resources:my-resource" ["urn:my-authz:scopes:access"] ))
| 38338 | (ns keycloak.authz-test
(:require [keycloak.admin :refer :all]
[keycloak.deployment :as deploy :refer [client-conf keycloak-client]]
[keycloak.authz :as authz]
[clojure.test :as t]))
(def admin-login "admin")
(def admin-password "<PASSWORD>")
(def auth-server-url "http://localhost:8090/auth")
(def integration-test-conf
(deploy/client-conf auth-server-url "master" "admin-cli"))
(def admin-client (deploy/keycloak-client integration-test-conf admin-login admin-password))
(comment
(def kc-admin (deploy/keycloak-client
(deploy/client-conf "master" "mybackend" "http://localhost:8080/auth")
"10337ce2-8dee-44a9-80b2-bc08ff8fc695"))
(def kc-authz (authz/authz-client (deploy/client-conf-input-stream "master" "mybackend" "http://localhost:8080/auth" "10337ce2-8dee-44a9-80b2-bc08ff8fc695")))
(authz/create-resource kc-authz "My resource" "urn:my-authz:resources:my-resource" ["urn:my-authz:scopes:access"])
(authz/create-role-policy kc-admin "master" "mybackend" "testrole" "urn:my-authz:resources:my-resource" ["urn:my-authz:scopes:access"] ))
| true | (ns keycloak.authz-test
(:require [keycloak.admin :refer :all]
[keycloak.deployment :as deploy :refer [client-conf keycloak-client]]
[keycloak.authz :as authz]
[clojure.test :as t]))
(def admin-login "admin")
(def admin-password "PI:PASSWORD:<PASSWORD>END_PI")
(def auth-server-url "http://localhost:8090/auth")
(def integration-test-conf
(deploy/client-conf auth-server-url "master" "admin-cli"))
(def admin-client (deploy/keycloak-client integration-test-conf admin-login admin-password))
(comment
(def kc-admin (deploy/keycloak-client
(deploy/client-conf "master" "mybackend" "http://localhost:8080/auth")
"10337ce2-8dee-44a9-80b2-bc08ff8fc695"))
(def kc-authz (authz/authz-client (deploy/client-conf-input-stream "master" "mybackend" "http://localhost:8080/auth" "10337ce2-8dee-44a9-80b2-bc08ff8fc695")))
(authz/create-resource kc-authz "My resource" "urn:my-authz:resources:my-resource" ["urn:my-authz:scopes:access"])
(authz/create-role-policy kc-admin "master" "mybackend" "testrole" "urn:my-authz:resources:my-resource" ["urn:my-authz:scopes:access"] ))
|
[
{
"context": "sc \"username or password missing\"\n :username username\n :password password}))\n\n (::aws/data\n (<",
"end": 419,
"score": 0.9965259432792664,
"start": 411,
"tag": "USERNAME",
"value": "username"
},
{
"context": "nt-id opts)\n :AuthParameters {\"USERNAME\" username\n \"PASSWORD\" password}}",
"end": 716,
"score": 0.9953827261924744,
"start": 708,
"tag": "USERNAME",
"value": "username"
},
{
"context": "E\" username\n \"PASSWORD\" password}}]))))\n\n(defn <respond-update-password [opts\n ",
"end": 764,
"score": 0.9963698387145996,
"start": 756,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " :ChallengeResponses\n {\"USERNAME\" username\n \"NEW_PASSWORD\" new-password}}]))))\n\n(",
"end": 1513,
"score": 0.961494505405426,
"start": 1505,
"tag": "USERNAME",
"value": "username"
},
{
"context": "{:ClientId (::client-id opts)\n :Username username\n :Password password}]))))\n\n(<defn <crea",
"end": 1803,
"score": 0.9922426342964172,
"start": 1795,
"tag": "USERNAME",
"value": "username"
},
{
"context": " :Username username\n :Password password}]))))\n\n(<defn <create-user [opts username passwor",
"end": 1833,
"score": 0.9990488290786743,
"start": 1825,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "::user-pool-id opts)\n :Username username\n :MessageAction \"SUPPRESS\"\n ",
"end": 2149,
"score": 0.995114803314209,
"start": 2141,
"tag": "USERNAME",
"value": "username"
},
{
"context": "::user-pool-id opts)\n :Password password\n :Username username\n ",
"end": 2518,
"score": 0.9978259205818176,
"start": 2510,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " :Password password\n :Username username\n :Permanent true}]))]\n res)",
"end": 2557,
"score": 0.9990944862365723,
"start": 2549,
"tag": "USERNAME",
"value": "username"
}
] | src/cljs/rx/cognito.cljs | zk/rx-lib | 0 | (ns rx.cognito
(:require [rx.kitchen-sink :as ks]
[rx.anom :as anom :refer-macros [<defn <? gol]]
[rx.aws :as aws]))
(defn new-password-required? [res]
(= "NEW_PASSWORD_REQUIRED"
(:ChallengeName res)))
(<defn <auth-username-password [opts username password]
(when-not (and username password)
(anom/throw-anom
{:desc "username or password missing"
:username username
:password password}))
(::aws/data
(<? (aws/<aws
(::aws/AWS opts)
opts
"CognitoIdentityServiceProvider"
"initiateAuth"
[{:AuthFlow "USER_PASSWORD_AUTH"
:ClientId (::client-id opts)
:AuthParameters {"USERNAME" username
"PASSWORD" password}}]))))
(defn <respond-update-password [opts
last-res
username
new-password]
(when-not last-res
(anom/throw-anom
{:desc "initiate-res required"}))
(when-not username
(anom/throw-anom
{:desc "username required"}))
(when-not new-password
(anom/throw-anom
{:desc "new password required"}))
(::aws/data
(<? (aws/<aws
(::aws/AWS opts)
opts
"CognitoIdentityServiceProvider"
"respondToAuthChallenge"
[{:ChallengeName "NEW_PASSWORD_REQUIRED"
:Session (-> last-res
:Session)
:ChallengeResponses
{"USERNAME" username
"NEW_PASSWORD" new-password}}]))))
(<defn <sign-up [opts username password]
(::aws/data
(<? (aws/<aws
(::aws/AWS opts)
opts
"CognitoIdentityServiceProvider"
"signUp"
[{:ClientId (::client-id opts)
:Username username
:Password password}]))))
(<defn <create-user [opts username password]
(let [res (<? (aws/<aws
(::aws/AWS opts)
opts
"CognitoIdentityServiceProvider"
"adminCreateUser"
[{:UserPoolId (::user-pool-id opts)
:Username username
:MessageAction "SUPPRESS"
:TemporaryPassword (ks/uuid)}]))
res (<? (aws/<aws
(::aws/AWS opts)
opts
"CognitoIdentityServiceProvider"
"adminSetUserPassword"
[{:UserPoolId (::user-pool-id opts)
:Password password
:Username username
:Permanent true}]))]
res))
| 114303 | (ns rx.cognito
(:require [rx.kitchen-sink :as ks]
[rx.anom :as anom :refer-macros [<defn <? gol]]
[rx.aws :as aws]))
(defn new-password-required? [res]
(= "NEW_PASSWORD_REQUIRED"
(:ChallengeName res)))
(<defn <auth-username-password [opts username password]
(when-not (and username password)
(anom/throw-anom
{:desc "username or password missing"
:username username
:password password}))
(::aws/data
(<? (aws/<aws
(::aws/AWS opts)
opts
"CognitoIdentityServiceProvider"
"initiateAuth"
[{:AuthFlow "USER_PASSWORD_AUTH"
:ClientId (::client-id opts)
:AuthParameters {"USERNAME" username
"PASSWORD" <PASSWORD>}}]))))
(defn <respond-update-password [opts
last-res
username
new-password]
(when-not last-res
(anom/throw-anom
{:desc "initiate-res required"}))
(when-not username
(anom/throw-anom
{:desc "username required"}))
(when-not new-password
(anom/throw-anom
{:desc "new password required"}))
(::aws/data
(<? (aws/<aws
(::aws/AWS opts)
opts
"CognitoIdentityServiceProvider"
"respondToAuthChallenge"
[{:ChallengeName "NEW_PASSWORD_REQUIRED"
:Session (-> last-res
:Session)
:ChallengeResponses
{"USERNAME" username
"NEW_PASSWORD" new-password}}]))))
(<defn <sign-up [opts username password]
(::aws/data
(<? (aws/<aws
(::aws/AWS opts)
opts
"CognitoIdentityServiceProvider"
"signUp"
[{:ClientId (::client-id opts)
:Username username
:Password <PASSWORD>}]))))
(<defn <create-user [opts username password]
(let [res (<? (aws/<aws
(::aws/AWS opts)
opts
"CognitoIdentityServiceProvider"
"adminCreateUser"
[{:UserPoolId (::user-pool-id opts)
:Username username
:MessageAction "SUPPRESS"
:TemporaryPassword (ks/uuid)}]))
res (<? (aws/<aws
(::aws/AWS opts)
opts
"CognitoIdentityServiceProvider"
"adminSetUserPassword"
[{:UserPoolId (::user-pool-id opts)
:Password <PASSWORD>
:Username username
:Permanent true}]))]
res))
| true | (ns rx.cognito
(:require [rx.kitchen-sink :as ks]
[rx.anom :as anom :refer-macros [<defn <? gol]]
[rx.aws :as aws]))
(defn new-password-required? [res]
(= "NEW_PASSWORD_REQUIRED"
(:ChallengeName res)))
(<defn <auth-username-password [opts username password]
(when-not (and username password)
(anom/throw-anom
{:desc "username or password missing"
:username username
:password password}))
(::aws/data
(<? (aws/<aws
(::aws/AWS opts)
opts
"CognitoIdentityServiceProvider"
"initiateAuth"
[{:AuthFlow "USER_PASSWORD_AUTH"
:ClientId (::client-id opts)
:AuthParameters {"USERNAME" username
"PASSWORD" PI:PASSWORD:<PASSWORD>END_PI}}]))))
(defn <respond-update-password [opts
last-res
username
new-password]
(when-not last-res
(anom/throw-anom
{:desc "initiate-res required"}))
(when-not username
(anom/throw-anom
{:desc "username required"}))
(when-not new-password
(anom/throw-anom
{:desc "new password required"}))
(::aws/data
(<? (aws/<aws
(::aws/AWS opts)
opts
"CognitoIdentityServiceProvider"
"respondToAuthChallenge"
[{:ChallengeName "NEW_PASSWORD_REQUIRED"
:Session (-> last-res
:Session)
:ChallengeResponses
{"USERNAME" username
"NEW_PASSWORD" new-password}}]))))
(<defn <sign-up [opts username password]
(::aws/data
(<? (aws/<aws
(::aws/AWS opts)
opts
"CognitoIdentityServiceProvider"
"signUp"
[{:ClientId (::client-id opts)
:Username username
:Password PI:PASSWORD:<PASSWORD>END_PI}]))))
(<defn <create-user [opts username password]
(let [res (<? (aws/<aws
(::aws/AWS opts)
opts
"CognitoIdentityServiceProvider"
"adminCreateUser"
[{:UserPoolId (::user-pool-id opts)
:Username username
:MessageAction "SUPPRESS"
:TemporaryPassword (ks/uuid)}]))
res (<? (aws/<aws
(::aws/AWS opts)
opts
"CognitoIdentityServiceProvider"
"adminSetUserPassword"
[{:UserPoolId (::user-pool-id opts)
:Password PI:PASSWORD:<PASSWORD>END_PI
:Username username
:Permanent true}]))]
res))
|
[
{
"context": ":host \"localhost\"\n :port \"8998\"\n :access-key \"dragon\"\n :secret \"dragon\"\n :db-name \"dragon\"})\n\n(def",
"end": 186,
"score": 0.998125433921814,
"start": 180,
"tag": "KEY",
"value": "dragon"
},
{
"context": " :port \"8998\"\n :access-key \"dragon\"\n :secret \"dragon\"\n :db-name \"dragon\"})\n\n(def ^:private start\n {",
"end": 206,
"score": 0.9981387257575989,
"start": 200,
"tag": "KEY",
"value": "dragon"
}
] | src/dragon/config/datomic.clj | clojusc/dragon | 2 | (ns dragon.config.datomic
(:require
[datomic.client :as datomic]))
(def ^:private base-config
{:version "0.9.5561.62"
:host "localhost"
:port "8998"
:access-key "dragon"
:secret "dragon"
:db-name "dragon"})
(def ^:private start
{:delay 5000
:retry-delay 500
:retry-timeout 10000
:home (str "/opt/datomic/" (:version base-config))
:executable "bin/run"
:entry-point "datomic.peer-server"
:host (:host base-config)
:port (:port base-config)
:db (format "%s,datomic:mem://%s" (:db-name base-config)
(:db-name base-config))
:auth (format "%s,%s" (:access-key base-config)
(:secret base-config))})
(def ^:private start-args
[(:executable start)
"-m" (:entry-point start)
"-h" (:host start)
"-p" (:port start)
"-d" (:db start)
"-a" (:auth start)])
(def config
{:version (:version base-config)
:start (assoc start :args start-args)
:conn {
:account-id datomic/PRO_ACCOUNT
:region datomic/PRO_REGION
:service "peer-server"
:endpoint (format "%s:%s" (:host base-config)
(:port base-config))
:db-name (:db-name base-config)
:access-key (:access-key base-config)
:secret (:secret base-config)}})
| 97618 | (ns dragon.config.datomic
(:require
[datomic.client :as datomic]))
(def ^:private base-config
{:version "0.9.5561.62"
:host "localhost"
:port "8998"
:access-key "<KEY>"
:secret "<KEY>"
:db-name "dragon"})
(def ^:private start
{:delay 5000
:retry-delay 500
:retry-timeout 10000
:home (str "/opt/datomic/" (:version base-config))
:executable "bin/run"
:entry-point "datomic.peer-server"
:host (:host base-config)
:port (:port base-config)
:db (format "%s,datomic:mem://%s" (:db-name base-config)
(:db-name base-config))
:auth (format "%s,%s" (:access-key base-config)
(:secret base-config))})
(def ^:private start-args
[(:executable start)
"-m" (:entry-point start)
"-h" (:host start)
"-p" (:port start)
"-d" (:db start)
"-a" (:auth start)])
(def config
{:version (:version base-config)
:start (assoc start :args start-args)
:conn {
:account-id datomic/PRO_ACCOUNT
:region datomic/PRO_REGION
:service "peer-server"
:endpoint (format "%s:%s" (:host base-config)
(:port base-config))
:db-name (:db-name base-config)
:access-key (:access-key base-config)
:secret (:secret base-config)}})
| true | (ns dragon.config.datomic
(:require
[datomic.client :as datomic]))
(def ^:private base-config
{:version "0.9.5561.62"
:host "localhost"
:port "8998"
:access-key "PI:KEY:<KEY>END_PI"
:secret "PI:KEY:<KEY>END_PI"
:db-name "dragon"})
(def ^:private start
{:delay 5000
:retry-delay 500
:retry-timeout 10000
:home (str "/opt/datomic/" (:version base-config))
:executable "bin/run"
:entry-point "datomic.peer-server"
:host (:host base-config)
:port (:port base-config)
:db (format "%s,datomic:mem://%s" (:db-name base-config)
(:db-name base-config))
:auth (format "%s,%s" (:access-key base-config)
(:secret base-config))})
(def ^:private start-args
[(:executable start)
"-m" (:entry-point start)
"-h" (:host start)
"-p" (:port start)
"-d" (:db start)
"-a" (:auth start)])
(def config
{:version (:version base-config)
:start (assoc start :args start-args)
:conn {
:account-id datomic/PRO_ACCOUNT
:region datomic/PRO_REGION
:service "peer-server"
:endpoint (format "%s:%s" (:host base-config)
(:port base-config))
:db-name (:db-name base-config)
:access-key (:access-key base-config)
:secret (:secret base-config)}})
|
[
{
"context": "'s concurrency model, which is\n;; based on work by Tony Hoare in \"Communicating Sequential Processes\" and is\n;;",
"end": 10278,
"score": 0.9998929500579834,
"start": 10268,
"tag": "NAME",
"value": "Tony Hoare"
},
{
"context": "s\n;; available at:\n;; http://www.usingcsp.com/\n\n;; Rob Pike, co-creater of Go, has a great talk about concurr",
"end": 10383,
"score": 0.9998777508735657,
"start": 10375,
"tag": "NAME",
"value": "Rob Pike"
}
] | Concurrent-Processes-With-CoreAsync-Library/core_async.clj | bashhack/BraveClojure | 0 |
;;;; ---------------------------------------------------------------------------
;;;; --------------- Concurrent Processes With `core.async` --------------------
;;;; ---------------------------------------------------------------------------
;; Clojure's `core.async` library allows us to create multiple independent
;; processes within a single program. We'll cover this style of programming
;; in-depth and learn how to actually write code that takes advantage of
;; its benefits.
;; We'll learn how:
;; 1) channels (like Rob Pike's Go language) communicate between independent
;; processes created by go blocks and `thread`,
;; 2) how Clojure manages threads with parking and blocking,
;; 3) how to use `alts!!`
;; 4) how to create a more straightforward method of writing queues
;; 5) how to avoid callback hell with proces pipelines
; ------------------------------------------------------------------------------
; Gettings Started with Processes
;; The `core.async` library is built around the idea of processes, a concurrent
;; unit of logic that responds to events. Processes are analogous to our
;; understanding of the world: entities interact with and respond to each other
;; independently without a central control mechanism behind the scenes.
;; This notion is a little different from our view of concurrency as we've seen
;; it so far, where we defined tasks as extensions of the main thread of control
;; (`pmap`) and where we created tasks that have no interest in communicating
;; (`future`).
;; When we think of the process itself, we should be thinking:
;; Can I define a given thing's essence as the set of the events it
;; recognizes and how it responds?
;; NOTE: My core.async project is in the directory titled `playsync`
; ------------------------------------------------------------------------------
; Buffering
;; Our example used in the `playsync` project contained two processes - one we
;; created with `go` and the REPL process. These processes don't have explicit
;; knowledge of each other, and they act independently.
;; Managing our processes becomes easier with buffers, we can specify the type
;; of buffer, invoking a simple buffer, `sliding-buffer`, or `dropping-buffer`.
;; A Simple Buffer
(def echo-buffer (chan 2))
(>!! echo-buffer "ketchup")
; => true
(>!! echo-buffer "ketchup")
; => true
(>!! echo-buffer "ketchup")
; => This blocks because the channel buffer is full
;; A `sliding-buffer` will drop values in a first-in, first-out fashion
;; A `dropping-buffer` will discard values in a last-in, first-out fashion
;; Neither of these buffers will ever cause `>!!` to block.
; ------------------------------------------------------------------------------
; Blocking and Parking
; -----------------------------------------------
; | Inside `go` block | Outside `go` block
; -----------------------------------------------
; put | >! or >!! | >!!
; -----------------------------------------------
; take | <! or <!! | <!!
; -----------------------------------------------
;; Because `go` blocks use a thrad pool with a fixed sie, you can create 1K
;; `go` processes but use only a handful of threads:
(def hi-chan (chan))
(doseq [n (range 1000)]
(go (>! hi-chan (str "hi " n))))
;; How is this possible? Because of how processes "wait" - "put" waits until
;; another process does a "take" on the same channel and vice versa - in the
;; example, 1K processes are waiting for another process to take from `hi-chan`.
;; When we talk about "waiting" we have to types: "parking" and "blocking"
;; We are familiar with blocking as this is when a thread stops execution until
;; a task is complete. We think of blocking being related to some kind of
;; I/O operation. The thread is alive, but does no work, so you have to create
;; a new thread to continue working - we learned how to accomplish this with
;; `future` in Chapter 9.
;; Parking frees up the thread so it can keep doing work. So, let's imagine you
;; have one thread and two processes, Process A and Process B. Process A runs
;; on the thread and then waits for a put or take. Clojure moves A off the thread
;; and moves B onto the thread. If B starts waiting and A's put or take has
;; finished, Clojure moves B off and puts A back on.
;; In this way, parking allows instructions from multiple processes to
;; interleave on a single thread, similar to the way that using multiple threads
;; allows interleaving on a single core.
;; NOTE: While the implementation of parking isn't key, it is ONLY possible
;; within `go` blocks, and it's only possible when you use `>!` and `<!`,
;; which we call "parking put" and "parking take". `>!!` and `<!!` are
;; "blocking put" and "blocking take".
; ------------------------------------------------------------------------------
; `thread`
;; When we do need to use blocking instead of parking, perhaps when a process
;; will take a long time before putting or taking, we should use `thread`:
(thread (println (<!! echo-chan)))
(>!! echo-chan "mustard")
; => true
; => "mustard"
;; `thread` acts almost exactly like `future`: it creates a new thread and
;; executes a process on that thread. However, unlike `future`, which returns
;; an object that you can deref, `thread` returns a channel. When `thread`'s
;; process stops, the process return values is put on the channel that `thread`
;; returns:
(let [t (thread "chili")]
(<!! t))
; => "chili"
;; You should use `thread` instead of a go block when performing a long-running
;; task so you don't clog your thread pool.
; ------------------------------------------------------------------------------
; Hot Dog Machine
;; NOTE: Code for the project is in the directory title `hotdogmachine`
; ------------------------------------------------------------------------------
; `alts!!`
;; The function `alts!!` lets us use the result of the first successful channel
;; operation among a collection of operations.
;; Let's recreate our delays and futures headshot program using `alts!!`:
(defn upload
[headshot c]
(go (Thread/sleep (rand 100))
(>! c heashot)))
(let [c1 (chan)
c2 (chan)
c3 (chan)]
(upload "pic1.jpg" c1)
(upload "pic2.jpg" c2)
(upload "pic3.jpg" c3)
(let [[headshot channel] (alts!! [c1 c2 c3])]
(println "Sending headshot notification for" headshot)))
;; Here, the `alts!!` function acts like: "Try to do a blocking take on each of
;; the channels in the vector simultaneously. As soon as a take succeeds, return
;; a vector whose first element is the value taken and whose second element is
;; the winning channel.
;; We can also provide `alts!!` with a timeout channel, which waits the
;; specified number of ms and then closes. It's a succinct way of putting a time
;; limit on concurrent operations:
(let [c1 (chan)]
(upload "pic1.jpg" c1)
(let [[headshot channel] (alts!! [c1 (timeout 20)])]
(if headshot
(println "Sending headshot notification for" headshot)
(println "Timed out!"))))
; => Timed out!
;; We can also use `alts!!` to specify put operations:
(let [c1 (chan)
c2 (chan)]
(go (<! c2))
(let [[value channel] (alts!! [c1 [c2 "put!"]])]
(println value)
(= channel c2)))
; => true
; => true
;; NOTE: Just like take and put, there is a variant for placement
;; in `go` blocks, `alts!`
; ------------------------------------------------------------------------------
; Queues
;; Just as we wrote our macro to queue futures, we could use processes to do
;; this in a more straightforward manner.
;; Here, we'll grab a collection of random quotes from a website and write them
;; to a single file. We want to ensure that only one quote is written at a time,
;; this preventing our text from being interleaved. To accomplish this, we need
;; a queue:
;; NOTE: `spit` (spit f content & options) - the opposite of `slurp`, opens f
;; with writer, writes content, then closes f
(defn append-to-file
"Write a string to the end of a file"
[filename s]
(spit filename s :append true))
(defn format-quote
"Delineate the beginning and end of a quote because it's convenient"
[quote]
(str "=== BEGIN QUOTE ===\n" quote "=== END QUOTE ===\n\n"))
(defn random-quote
"Retrieve a random quote and format it"
[]
(format-quote (slurp "http://www.braveclojure.com/random-quote")))
(defn snag-quotes
[filename num-quotes]
(let [c (chan)]
(go (while true (append-to-file filename (<! c))))
(dotimes [n num-quotes] (go (>! c (random-quote))))))
(snag-quotes "quotes" 2)
; ------------------------------------------------------------------------------
; Pipelines
;; In a language without channels, we need to still express "when x happens,
;; do y" but we must do so using `callbacks`.
;; It's all to easy to create dependencies among all the layers of callbacks
;; that aren't exactly easy to detect - this we, of course, call "callback hell".
;; They also end up sharing state, making it difficult to reason about the
;; overall state of the system as the callbacks get triggered.
;; We can manage this by creating a process pipeline, where each unit of logic
;; is in an isolated process, and all communication between these units
;; occurs through explicit input and output channels.
;; In the following, let's create three infinitely looping processes connected
;; through channels, passing the out of one process to the in of the next:
(defn upper-caser
[in]
(let [out (chan)]
(go (while true (>! out (clojure.string/upper-case (<! in)))))
out))
(defn reverser
[in]
(let [out (chan)]
(go (while true (>! out (clojure.string/reverse (<! in)))))
out))
(defn printer
[in]
(go (while true (println (<! in)))))
(def in-chan (chan))
(def upper-caser-out (upper-caser in-chan))
(def reverser-out (reverser upper-caser-out))
(printer reverser-out)
(>!! in-chan "redrum")
; => MURDER
(>!! in-chan "repaid")
; => DIAPER
; -----------------------------------------------------------------------------
; Additional Resources
; -----------------------------------------------------------------------------
;; Clojure's core.async library is based on Go's concurrency model, which is
;; based on work by Tony Hoare in "Communicating Sequential Processes" and is
;; available at:
;; http://www.usingcsp.com/
;; Rob Pike, co-creater of Go, has a great talk about concurrency:
;; https://www.youtube.com/watch?v=f6kdp27TYZs
| 3542 |
;;;; ---------------------------------------------------------------------------
;;;; --------------- Concurrent Processes With `core.async` --------------------
;;;; ---------------------------------------------------------------------------
;; Clojure's `core.async` library allows us to create multiple independent
;; processes within a single program. We'll cover this style of programming
;; in-depth and learn how to actually write code that takes advantage of
;; its benefits.
;; We'll learn how:
;; 1) channels (like Rob Pike's Go language) communicate between independent
;; processes created by go blocks and `thread`,
;; 2) how Clojure manages threads with parking and blocking,
;; 3) how to use `alts!!`
;; 4) how to create a more straightforward method of writing queues
;; 5) how to avoid callback hell with proces pipelines
; ------------------------------------------------------------------------------
; Gettings Started with Processes
;; The `core.async` library is built around the idea of processes, a concurrent
;; unit of logic that responds to events. Processes are analogous to our
;; understanding of the world: entities interact with and respond to each other
;; independently without a central control mechanism behind the scenes.
;; This notion is a little different from our view of concurrency as we've seen
;; it so far, where we defined tasks as extensions of the main thread of control
;; (`pmap`) and where we created tasks that have no interest in communicating
;; (`future`).
;; When we think of the process itself, we should be thinking:
;; Can I define a given thing's essence as the set of the events it
;; recognizes and how it responds?
;; NOTE: My core.async project is in the directory titled `playsync`
; ------------------------------------------------------------------------------
; Buffering
;; Our example used in the `playsync` project contained two processes - one we
;; created with `go` and the REPL process. These processes don't have explicit
;; knowledge of each other, and they act independently.
;; Managing our processes becomes easier with buffers, we can specify the type
;; of buffer, invoking a simple buffer, `sliding-buffer`, or `dropping-buffer`.
;; A Simple Buffer
(def echo-buffer (chan 2))
(>!! echo-buffer "ketchup")
; => true
(>!! echo-buffer "ketchup")
; => true
(>!! echo-buffer "ketchup")
; => This blocks because the channel buffer is full
;; A `sliding-buffer` will drop values in a first-in, first-out fashion
;; A `dropping-buffer` will discard values in a last-in, first-out fashion
;; Neither of these buffers will ever cause `>!!` to block.
; ------------------------------------------------------------------------------
; Blocking and Parking
; -----------------------------------------------
; | Inside `go` block | Outside `go` block
; -----------------------------------------------
; put | >! or >!! | >!!
; -----------------------------------------------
; take | <! or <!! | <!!
; -----------------------------------------------
;; Because `go` blocks use a thrad pool with a fixed sie, you can create 1K
;; `go` processes but use only a handful of threads:
(def hi-chan (chan))
(doseq [n (range 1000)]
(go (>! hi-chan (str "hi " n))))
;; How is this possible? Because of how processes "wait" - "put" waits until
;; another process does a "take" on the same channel and vice versa - in the
;; example, 1K processes are waiting for another process to take from `hi-chan`.
;; When we talk about "waiting" we have to types: "parking" and "blocking"
;; We are familiar with blocking as this is when a thread stops execution until
;; a task is complete. We think of blocking being related to some kind of
;; I/O operation. The thread is alive, but does no work, so you have to create
;; a new thread to continue working - we learned how to accomplish this with
;; `future` in Chapter 9.
;; Parking frees up the thread so it can keep doing work. So, let's imagine you
;; have one thread and two processes, Process A and Process B. Process A runs
;; on the thread and then waits for a put or take. Clojure moves A off the thread
;; and moves B onto the thread. If B starts waiting and A's put or take has
;; finished, Clojure moves B off and puts A back on.
;; In this way, parking allows instructions from multiple processes to
;; interleave on a single thread, similar to the way that using multiple threads
;; allows interleaving on a single core.
;; NOTE: While the implementation of parking isn't key, it is ONLY possible
;; within `go` blocks, and it's only possible when you use `>!` and `<!`,
;; which we call "parking put" and "parking take". `>!!` and `<!!` are
;; "blocking put" and "blocking take".
; ------------------------------------------------------------------------------
; `thread`
;; When we do need to use blocking instead of parking, perhaps when a process
;; will take a long time before putting or taking, we should use `thread`:
(thread (println (<!! echo-chan)))
(>!! echo-chan "mustard")
; => true
; => "mustard"
;; `thread` acts almost exactly like `future`: it creates a new thread and
;; executes a process on that thread. However, unlike `future`, which returns
;; an object that you can deref, `thread` returns a channel. When `thread`'s
;; process stops, the process return values is put on the channel that `thread`
;; returns:
(let [t (thread "chili")]
(<!! t))
; => "chili"
;; You should use `thread` instead of a go block when performing a long-running
;; task so you don't clog your thread pool.
; ------------------------------------------------------------------------------
; Hot Dog Machine
;; NOTE: Code for the project is in the directory title `hotdogmachine`
; ------------------------------------------------------------------------------
; `alts!!`
;; The function `alts!!` lets us use the result of the first successful channel
;; operation among a collection of operations.
;; Let's recreate our delays and futures headshot program using `alts!!`:
(defn upload
[headshot c]
(go (Thread/sleep (rand 100))
(>! c heashot)))
(let [c1 (chan)
c2 (chan)
c3 (chan)]
(upload "pic1.jpg" c1)
(upload "pic2.jpg" c2)
(upload "pic3.jpg" c3)
(let [[headshot channel] (alts!! [c1 c2 c3])]
(println "Sending headshot notification for" headshot)))
;; Here, the `alts!!` function acts like: "Try to do a blocking take on each of
;; the channels in the vector simultaneously. As soon as a take succeeds, return
;; a vector whose first element is the value taken and whose second element is
;; the winning channel.
;; We can also provide `alts!!` with a timeout channel, which waits the
;; specified number of ms and then closes. It's a succinct way of putting a time
;; limit on concurrent operations:
(let [c1 (chan)]
(upload "pic1.jpg" c1)
(let [[headshot channel] (alts!! [c1 (timeout 20)])]
(if headshot
(println "Sending headshot notification for" headshot)
(println "Timed out!"))))
; => Timed out!
;; We can also use `alts!!` to specify put operations:
(let [c1 (chan)
c2 (chan)]
(go (<! c2))
(let [[value channel] (alts!! [c1 [c2 "put!"]])]
(println value)
(= channel c2)))
; => true
; => true
;; NOTE: Just like take and put, there is a variant for placement
;; in `go` blocks, `alts!`
; ------------------------------------------------------------------------------
; Queues
;; Just as we wrote our macro to queue futures, we could use processes to do
;; this in a more straightforward manner.
;; Here, we'll grab a collection of random quotes from a website and write them
;; to a single file. We want to ensure that only one quote is written at a time,
;; this preventing our text from being interleaved. To accomplish this, we need
;; a queue:
;; NOTE: `spit` (spit f content & options) - the opposite of `slurp`, opens f
;; with writer, writes content, then closes f
(defn append-to-file
"Write a string to the end of a file"
[filename s]
(spit filename s :append true))
(defn format-quote
"Delineate the beginning and end of a quote because it's convenient"
[quote]
(str "=== BEGIN QUOTE ===\n" quote "=== END QUOTE ===\n\n"))
(defn random-quote
"Retrieve a random quote and format it"
[]
(format-quote (slurp "http://www.braveclojure.com/random-quote")))
(defn snag-quotes
[filename num-quotes]
(let [c (chan)]
(go (while true (append-to-file filename (<! c))))
(dotimes [n num-quotes] (go (>! c (random-quote))))))
(snag-quotes "quotes" 2)
; ------------------------------------------------------------------------------
; Pipelines
;; In a language without channels, we need to still express "when x happens,
;; do y" but we must do so using `callbacks`.
;; It's all to easy to create dependencies among all the layers of callbacks
;; that aren't exactly easy to detect - this we, of course, call "callback hell".
;; They also end up sharing state, making it difficult to reason about the
;; overall state of the system as the callbacks get triggered.
;; We can manage this by creating a process pipeline, where each unit of logic
;; is in an isolated process, and all communication between these units
;; occurs through explicit input and output channels.
;; In the following, let's create three infinitely looping processes connected
;; through channels, passing the out of one process to the in of the next:
(defn upper-caser
[in]
(let [out (chan)]
(go (while true (>! out (clojure.string/upper-case (<! in)))))
out))
(defn reverser
[in]
(let [out (chan)]
(go (while true (>! out (clojure.string/reverse (<! in)))))
out))
(defn printer
[in]
(go (while true (println (<! in)))))
(def in-chan (chan))
(def upper-caser-out (upper-caser in-chan))
(def reverser-out (reverser upper-caser-out))
(printer reverser-out)
(>!! in-chan "redrum")
; => MURDER
(>!! in-chan "repaid")
; => DIAPER
; -----------------------------------------------------------------------------
; Additional Resources
; -----------------------------------------------------------------------------
;; Clojure's core.async library is based on Go's concurrency model, which is
;; based on work by <NAME> in "Communicating Sequential Processes" and is
;; available at:
;; http://www.usingcsp.com/
;; <NAME>, co-creater of Go, has a great talk about concurrency:
;; https://www.youtube.com/watch?v=f6kdp27TYZs
| true |
;;;; ---------------------------------------------------------------------------
;;;; --------------- Concurrent Processes With `core.async` --------------------
;;;; ---------------------------------------------------------------------------
;; Clojure's `core.async` library allows us to create multiple independent
;; processes within a single program. We'll cover this style of programming
;; in-depth and learn how to actually write code that takes advantage of
;; its benefits.
;; We'll learn how:
;; 1) channels (like Rob Pike's Go language) communicate between independent
;; processes created by go blocks and `thread`,
;; 2) how Clojure manages threads with parking and blocking,
;; 3) how to use `alts!!`
;; 4) how to create a more straightforward method of writing queues
;; 5) how to avoid callback hell with proces pipelines
; ------------------------------------------------------------------------------
; Gettings Started with Processes
;; The `core.async` library is built around the idea of processes, a concurrent
;; unit of logic that responds to events. Processes are analogous to our
;; understanding of the world: entities interact with and respond to each other
;; independently without a central control mechanism behind the scenes.
;; This notion is a little different from our view of concurrency as we've seen
;; it so far, where we defined tasks as extensions of the main thread of control
;; (`pmap`) and where we created tasks that have no interest in communicating
;; (`future`).
;; When we think of the process itself, we should be thinking:
;; Can I define a given thing's essence as the set of the events it
;; recognizes and how it responds?
;; NOTE: My core.async project is in the directory titled `playsync`
; ------------------------------------------------------------------------------
; Buffering
;; Our example used in the `playsync` project contained two processes - one we
;; created with `go` and the REPL process. These processes don't have explicit
;; knowledge of each other, and they act independently.
;; Managing our processes becomes easier with buffers, we can specify the type
;; of buffer, invoking a simple buffer, `sliding-buffer`, or `dropping-buffer`.
;; A Simple Buffer
(def echo-buffer (chan 2))
(>!! echo-buffer "ketchup")
; => true
(>!! echo-buffer "ketchup")
; => true
(>!! echo-buffer "ketchup")
; => This blocks because the channel buffer is full
;; A `sliding-buffer` will drop values in a first-in, first-out fashion
;; A `dropping-buffer` will discard values in a last-in, first-out fashion
;; Neither of these buffers will ever cause `>!!` to block.
; ------------------------------------------------------------------------------
; Blocking and Parking
; -----------------------------------------------
; | Inside `go` block | Outside `go` block
; -----------------------------------------------
; put | >! or >!! | >!!
; -----------------------------------------------
; take | <! or <!! | <!!
; -----------------------------------------------
;; Because `go` blocks use a thrad pool with a fixed sie, you can create 1K
;; `go` processes but use only a handful of threads:
(def hi-chan (chan))
(doseq [n (range 1000)]
(go (>! hi-chan (str "hi " n))))
;; How is this possible? Because of how processes "wait" - "put" waits until
;; another process does a "take" on the same channel and vice versa - in the
;; example, 1K processes are waiting for another process to take from `hi-chan`.
;; When we talk about "waiting" we have to types: "parking" and "blocking"
;; We are familiar with blocking as this is when a thread stops execution until
;; a task is complete. We think of blocking being related to some kind of
;; I/O operation. The thread is alive, but does no work, so you have to create
;; a new thread to continue working - we learned how to accomplish this with
;; `future` in Chapter 9.
;; Parking frees up the thread so it can keep doing work. So, let's imagine you
;; have one thread and two processes, Process A and Process B. Process A runs
;; on the thread and then waits for a put or take. Clojure moves A off the thread
;; and moves B onto the thread. If B starts waiting and A's put or take has
;; finished, Clojure moves B off and puts A back on.
;; In this way, parking allows instructions from multiple processes to
;; interleave on a single thread, similar to the way that using multiple threads
;; allows interleaving on a single core.
;; NOTE: While the implementation of parking isn't key, it is ONLY possible
;; within `go` blocks, and it's only possible when you use `>!` and `<!`,
;; which we call "parking put" and "parking take". `>!!` and `<!!` are
;; "blocking put" and "blocking take".
; ------------------------------------------------------------------------------
; `thread`
;; When we do need to use blocking instead of parking, perhaps when a process
;; will take a long time before putting or taking, we should use `thread`:
(thread (println (<!! echo-chan)))
(>!! echo-chan "mustard")
; => true
; => "mustard"
;; `thread` acts almost exactly like `future`: it creates a new thread and
;; executes a process on that thread. However, unlike `future`, which returns
;; an object that you can deref, `thread` returns a channel. When `thread`'s
;; process stops, the process return values is put on the channel that `thread`
;; returns:
(let [t (thread "chili")]
(<!! t))
; => "chili"
;; You should use `thread` instead of a go block when performing a long-running
;; task so you don't clog your thread pool.
; ------------------------------------------------------------------------------
; Hot Dog Machine
;; NOTE: Code for the project is in the directory title `hotdogmachine`
; ------------------------------------------------------------------------------
; `alts!!`
;; The function `alts!!` lets us use the result of the first successful channel
;; operation among a collection of operations.
;; Let's recreate our delays and futures headshot program using `alts!!`:
(defn upload
[headshot c]
(go (Thread/sleep (rand 100))
(>! c heashot)))
(let [c1 (chan)
c2 (chan)
c3 (chan)]
(upload "pic1.jpg" c1)
(upload "pic2.jpg" c2)
(upload "pic3.jpg" c3)
(let [[headshot channel] (alts!! [c1 c2 c3])]
(println "Sending headshot notification for" headshot)))
;; Here, the `alts!!` function acts like: "Try to do a blocking take on each of
;; the channels in the vector simultaneously. As soon as a take succeeds, return
;; a vector whose first element is the value taken and whose second element is
;; the winning channel.
;; We can also provide `alts!!` with a timeout channel, which waits the
;; specified number of ms and then closes. It's a succinct way of putting a time
;; limit on concurrent operations:
(let [c1 (chan)]
(upload "pic1.jpg" c1)
(let [[headshot channel] (alts!! [c1 (timeout 20)])]
(if headshot
(println "Sending headshot notification for" headshot)
(println "Timed out!"))))
; => Timed out!
;; We can also use `alts!!` to specify put operations:
(let [c1 (chan)
c2 (chan)]
(go (<! c2))
(let [[value channel] (alts!! [c1 [c2 "put!"]])]
(println value)
(= channel c2)))
; => true
; => true
;; NOTE: Just like take and put, there is a variant for placement
;; in `go` blocks, `alts!`
; ------------------------------------------------------------------------------
; Queues
;; Just as we wrote our macro to queue futures, we could use processes to do
;; this in a more straightforward manner.
;; Here, we'll grab a collection of random quotes from a website and write them
;; to a single file. We want to ensure that only one quote is written at a time,
;; this preventing our text from being interleaved. To accomplish this, we need
;; a queue:
;; NOTE: `spit` (spit f content & options) - the opposite of `slurp`, opens f
;; with writer, writes content, then closes f
(defn append-to-file
"Write a string to the end of a file"
[filename s]
(spit filename s :append true))
(defn format-quote
"Delineate the beginning and end of a quote because it's convenient"
[quote]
(str "=== BEGIN QUOTE ===\n" quote "=== END QUOTE ===\n\n"))
(defn random-quote
"Retrieve a random quote and format it"
[]
(format-quote (slurp "http://www.braveclojure.com/random-quote")))
(defn snag-quotes
[filename num-quotes]
(let [c (chan)]
(go (while true (append-to-file filename (<! c))))
(dotimes [n num-quotes] (go (>! c (random-quote))))))
(snag-quotes "quotes" 2)
; ------------------------------------------------------------------------------
; Pipelines
;; In a language without channels, we need to still express "when x happens,
;; do y" but we must do so using `callbacks`.
;; It's all to easy to create dependencies among all the layers of callbacks
;; that aren't exactly easy to detect - this we, of course, call "callback hell".
;; They also end up sharing state, making it difficult to reason about the
;; overall state of the system as the callbacks get triggered.
;; We can manage this by creating a process pipeline, where each unit of logic
;; is in an isolated process, and all communication between these units
;; occurs through explicit input and output channels.
;; In the following, let's create three infinitely looping processes connected
;; through channels, passing the out of one process to the in of the next:
(defn upper-caser
[in]
(let [out (chan)]
(go (while true (>! out (clojure.string/upper-case (<! in)))))
out))
(defn reverser
[in]
(let [out (chan)]
(go (while true (>! out (clojure.string/reverse (<! in)))))
out))
(defn printer
[in]
(go (while true (println (<! in)))))
(def in-chan (chan))
(def upper-caser-out (upper-caser in-chan))
(def reverser-out (reverser upper-caser-out))
(printer reverser-out)
(>!! in-chan "redrum")
; => MURDER
(>!! in-chan "repaid")
; => DIAPER
; -----------------------------------------------------------------------------
; Additional Resources
; -----------------------------------------------------------------------------
;; Clojure's core.async library is based on Go's concurrency model, which is
;; based on work by PI:NAME:<NAME>END_PI in "Communicating Sequential Processes" and is
;; available at:
;; http://www.usingcsp.com/
;; PI:NAME:<NAME>END_PI, co-creater of Go, has a great talk about concurrency:
;; https://www.youtube.com/watch?v=f6kdp27TYZs
|
[
{
"context": " for a transaction\"\n (let [customer {:pulic-key \"123\"}\n tx {:from \"Alice\", :to \"Bob\", :amount 1",
"end": 487,
"score": 0.9967761039733887,
"start": 484,
"tag": "KEY",
"value": "123"
},
{
"context": "t [customer {:pulic-key \"123\"}\n tx {:from \"Alice\", :to \"Bob\", :amount 10, :currency \"usd\"} \n ",
"end": 514,
"score": 0.9996610879898071,
"start": 509,
"tag": "NAME",
"value": "Alice"
},
{
"context": ":pulic-key \"123\"}\n tx {:from \"Alice\", :to \"Bob\", :amount 10, :currency \"usd\"} \n from-bala",
"end": 525,
"score": 0.9997270107269287,
"start": 522,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ance {:from \"Genesis\",\n :to \"Alice\",\n :amount 100,\n ",
"end": 629,
"score": 0.9997716546058655,
"start": 624,
"tag": "NAME",
"value": "Alice"
},
{
"context": "urrency \"usd\",\n :public-key \"123\"}\n context {:tx tx\n :fro",
"end": 780,
"score": 0.9961513876914978,
"start": 777,
"tag": "KEY",
"value": "123"
},
{
"context": "ance {:public-key nil, :currency \"usd\", :account \"Bob\"}) nil]\n (if-let [result (tx/ha",
"end": 1006,
"score": 0.9994438886642456,
"start": 1003,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ance {:public-key nil, :currency \"usd\", :account \"Bob\"})\n {:from \"Matt\",\n ",
"end": 1726,
"score": 0.9995458126068115,
"start": 1723,
"tag": "NAME",
"value": "Bob"
},
{
"context": "sd\", :account \"Bob\"})\n {:from \"Matt\",\n :to \"Bob\",\n ",
"end": 1762,
"score": 0.9996676445007324,
"start": 1758,
"tag": "NAME",
"value": "Matt"
},
{
"context": " {:from \"Matt\",\n :to \"Bob\",\n :amount 100,\n ",
"end": 1794,
"score": 0.9997932314872742,
"start": 1791,
"tag": "NAME",
"value": "Bob"
},
{
"context": " :date \"123\"\n :public-key \"123\"}]\n (if-let [result (tx/hash-tx",
"end": 1974,
"score": 0.9682960510253906,
"start": 1971,
"tag": "KEY",
"value": "123"
}
] | test/decimals/transactions_test.clj | Jumanjii/sequence | 337 | (ns decimals.transactions-test
(:require [clojure.test :refer :all]
[clojure.spec.alpha :as s]
[clojure.data.json :as json]
[mockfn.macros :as mfn]
[clojure.spec.gen.alpha :as gen]
[decimals.dynamodb :as db]
[decimals.balances :as b]
[decimals.specs]
[decimals.transactions :as tx]))
(deftest hash-txs-test
"assert that values add up for a transaction"
(let [customer {:pulic-key "123"}
tx {:from "Alice", :to "Bob", :amount 10, :currency "usd"}
from-balance {:from "Genesis",
:to "Alice",
:amount 100,
:balance 100,
:currency "usd",
:public-key "123"}
context {:tx tx
:from { :balance from-balance}
:customer customer}]
; new destination balance
(mfn/providing [(b/balance {:public-key nil, :currency "usd", :account "Bob"}) nil]
(if-let [result (tx/hash-txs context)]
(let [tx-amount (get-in result [:tx :amount])
from-balance (get-in result [:from :balance :balance])
from-tx (get-in result [:from :tx :balance])
to-balance (get-in result [:to :balance :balance])
to-tx (get-in result [:to :tx :balance])]
(is (= from-tx (- from-balance tx-amount)))
(is (= to-tx (+ to-balance tx-amount))))
(is true false)))
; existing destination balance
(mfn/providing [(b/balance {:public-key nil, :currency "usd", :account "Bob"})
{:from "Matt",
:to "Bob",
:amount 100,
:balance 100,
:currency "usd",
:date "123"
:public-key "123"}]
(if-let [result (tx/hash-txs context)]
(let [tx-amount (get-in result [:tx :amount])
from-balance (get-in result [:from :balance :balance])
from-tx (get-in result [:from :tx :balance])
to-balance (get-in result [:to :balance :balance])
to-tx (get-in result [:to :tx :balance])]
(is (= from-tx (- from-balance tx-amount)))
(is (= to-tx (+ to-balance tx-amount))))
(is true false)))))
| 65424 | (ns decimals.transactions-test
(:require [clojure.test :refer :all]
[clojure.spec.alpha :as s]
[clojure.data.json :as json]
[mockfn.macros :as mfn]
[clojure.spec.gen.alpha :as gen]
[decimals.dynamodb :as db]
[decimals.balances :as b]
[decimals.specs]
[decimals.transactions :as tx]))
(deftest hash-txs-test
"assert that values add up for a transaction"
(let [customer {:pulic-key "<KEY>"}
tx {:from "<NAME>", :to "<NAME>", :amount 10, :currency "usd"}
from-balance {:from "Genesis",
:to "<NAME>",
:amount 100,
:balance 100,
:currency "usd",
:public-key "<KEY>"}
context {:tx tx
:from { :balance from-balance}
:customer customer}]
; new destination balance
(mfn/providing [(b/balance {:public-key nil, :currency "usd", :account "<NAME>"}) nil]
(if-let [result (tx/hash-txs context)]
(let [tx-amount (get-in result [:tx :amount])
from-balance (get-in result [:from :balance :balance])
from-tx (get-in result [:from :tx :balance])
to-balance (get-in result [:to :balance :balance])
to-tx (get-in result [:to :tx :balance])]
(is (= from-tx (- from-balance tx-amount)))
(is (= to-tx (+ to-balance tx-amount))))
(is true false)))
; existing destination balance
(mfn/providing [(b/balance {:public-key nil, :currency "usd", :account "<NAME>"})
{:from "<NAME>",
:to "<NAME>",
:amount 100,
:balance 100,
:currency "usd",
:date "123"
:public-key "<KEY>"}]
(if-let [result (tx/hash-txs context)]
(let [tx-amount (get-in result [:tx :amount])
from-balance (get-in result [:from :balance :balance])
from-tx (get-in result [:from :tx :balance])
to-balance (get-in result [:to :balance :balance])
to-tx (get-in result [:to :tx :balance])]
(is (= from-tx (- from-balance tx-amount)))
(is (= to-tx (+ to-balance tx-amount))))
(is true false)))))
| true | (ns decimals.transactions-test
(:require [clojure.test :refer :all]
[clojure.spec.alpha :as s]
[clojure.data.json :as json]
[mockfn.macros :as mfn]
[clojure.spec.gen.alpha :as gen]
[decimals.dynamodb :as db]
[decimals.balances :as b]
[decimals.specs]
[decimals.transactions :as tx]))
(deftest hash-txs-test
"assert that values add up for a transaction"
(let [customer {:pulic-key "PI:KEY:<KEY>END_PI"}
tx {:from "PI:NAME:<NAME>END_PI", :to "PI:NAME:<NAME>END_PI", :amount 10, :currency "usd"}
from-balance {:from "Genesis",
:to "PI:NAME:<NAME>END_PI",
:amount 100,
:balance 100,
:currency "usd",
:public-key "PI:KEY:<KEY>END_PI"}
context {:tx tx
:from { :balance from-balance}
:customer customer}]
; new destination balance
(mfn/providing [(b/balance {:public-key nil, :currency "usd", :account "PI:NAME:<NAME>END_PI"}) nil]
(if-let [result (tx/hash-txs context)]
(let [tx-amount (get-in result [:tx :amount])
from-balance (get-in result [:from :balance :balance])
from-tx (get-in result [:from :tx :balance])
to-balance (get-in result [:to :balance :balance])
to-tx (get-in result [:to :tx :balance])]
(is (= from-tx (- from-balance tx-amount)))
(is (= to-tx (+ to-balance tx-amount))))
(is true false)))
; existing destination balance
(mfn/providing [(b/balance {:public-key nil, :currency "usd", :account "PI:NAME:<NAME>END_PI"})
{:from "PI:NAME:<NAME>END_PI",
:to "PI:NAME:<NAME>END_PI",
:amount 100,
:balance 100,
:currency "usd",
:date "123"
:public-key "PI:KEY:<KEY>END_PI"}]
(if-let [result (tx/hash-txs context)]
(let [tx-amount (get-in result [:tx :amount])
from-balance (get-in result [:from :balance :balance])
from-tx (get-in result [:from :tx :balance])
to-balance (get-in result [:to :balance :balance])
to-tx (get-in result [:to :tx :balance])]
(is (= from-tx (- from-balance tx-amount)))
(is (= to-tx (+ to-balance tx-amount))))
(is true false)))))
|
[
{
"context": ";;\n;; Author:: Adam Jacob (<adam@opscode.com>)\n;; Author:: Christopher Brow",
"end": 25,
"score": 0.9998517036437988,
"start": 15,
"tag": "NAME",
"value": "Adam Jacob"
},
{
"context": ";;\n;; Author:: Adam Jacob (<adam@opscode.com>)\n;; Author:: Christopher Brown (<cb@opscode.com>",
"end": 44,
"score": 0.9999331831932068,
"start": 28,
"tag": "EMAIL",
"value": "adam@opscode.com"
},
{
"context": "thor:: Adam Jacob (<adam@opscode.com>)\n;; Author:: Christopher Brown (<cb@opscode.com>)\n;; Copyright:: Copyright (c) 2",
"end": 76,
"score": 0.9997743964195251,
"start": 59,
"tag": "NAME",
"value": "Christopher Brown"
},
{
"context": "dam@opscode.com>)\n;; Author:: Christopher Brown (<cb@opscode.com>)\n;; Copyright:: Copyright (c) 2010 Opscode, Inc.",
"end": 93,
"score": 0.9999337196350098,
"start": 79,
"tag": "EMAIL",
"value": "cb@opscode.com"
}
] | config/software/chef-server.clj | racker/omnibus | 2 | ;;
;; Author:: Adam Jacob (<adam@opscode.com>)
;; Author:: Christopher Brown (<cb@opscode.com>)
;; Copyright:: Copyright (c) 2010 Opscode, Inc.
;; License:: Apache License, Version 2.0
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(software "chef-server" :source "chef"
:steps [
{:command "/opt/opscode/embedded/bin/gem"
:args ["install" "chef-server" "chef-server-webui" "chef-server-api" "chef-solr" "--version" "10.12.0" "-n" "/opt/opscode/bin"
"--no-rdoc" "--no-ri"
"--" "--with-xml2-include=/opt/opscode/embedded/include/libxml2"
"--with-xml2-lib=/opt/opscode/embedded/lib"]}
{:command "/opt/opscode/embedded/bin/gem"
:args ["install" "unicorn" "-n" "/opt/opscode/bin"
"--no-rdoc" "--no-ri"
"--" "--with-xml2-include=/opt/opscode/embedded/include/libxml2"
"--with-xml2-lib=/opt/opscode/embedded/lib"]}
{:command "chown"
:args ["-R" (cond
(is-os? "darwin")
"root:wheel"
true "root:root") "/opt/opscode"]}])
| 73501 | ;;
;; Author:: <NAME> (<<EMAIL>>)
;; Author:: <NAME> (<<EMAIL>>)
;; Copyright:: Copyright (c) 2010 Opscode, Inc.
;; License:: Apache License, Version 2.0
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(software "chef-server" :source "chef"
:steps [
{:command "/opt/opscode/embedded/bin/gem"
:args ["install" "chef-server" "chef-server-webui" "chef-server-api" "chef-solr" "--version" "10.12.0" "-n" "/opt/opscode/bin"
"--no-rdoc" "--no-ri"
"--" "--with-xml2-include=/opt/opscode/embedded/include/libxml2"
"--with-xml2-lib=/opt/opscode/embedded/lib"]}
{:command "/opt/opscode/embedded/bin/gem"
:args ["install" "unicorn" "-n" "/opt/opscode/bin"
"--no-rdoc" "--no-ri"
"--" "--with-xml2-include=/opt/opscode/embedded/include/libxml2"
"--with-xml2-lib=/opt/opscode/embedded/lib"]}
{:command "chown"
:args ["-R" (cond
(is-os? "darwin")
"root:wheel"
true "root:root") "/opt/opscode"]}])
| true | ;;
;; Author:: PI:NAME:<NAME>END_PI (<PI:EMAIL:<EMAIL>END_PI>)
;; Author:: PI:NAME:<NAME>END_PI (<PI:EMAIL:<EMAIL>END_PI>)
;; Copyright:: Copyright (c) 2010 Opscode, Inc.
;; License:: Apache License, Version 2.0
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(software "chef-server" :source "chef"
:steps [
{:command "/opt/opscode/embedded/bin/gem"
:args ["install" "chef-server" "chef-server-webui" "chef-server-api" "chef-solr" "--version" "10.12.0" "-n" "/opt/opscode/bin"
"--no-rdoc" "--no-ri"
"--" "--with-xml2-include=/opt/opscode/embedded/include/libxml2"
"--with-xml2-lib=/opt/opscode/embedded/lib"]}
{:command "/opt/opscode/embedded/bin/gem"
:args ["install" "unicorn" "-n" "/opt/opscode/bin"
"--no-rdoc" "--no-ri"
"--" "--with-xml2-include=/opt/opscode/embedded/include/libxml2"
"--with-xml2-lib=/opt/opscode/embedded/lib"]}
{:command "chown"
:args ["-R" (cond
(is-os? "darwin")
"root:wheel"
true "root:root") "/opt/opscode"]}])
|
[
{
"context": "cassandra-keyspace)]\n [nil \"--cassandra-password PASSWORD\"\n (str \"Cassandra Password. Default: \" mstore/",
"end": 11143,
"score": 0.9929519891738892,
"start": 11135,
"tag": "PASSWORD",
"value": "PASSWORD"
}
] | src/cyanite_remover/cli.clj | vsonone/cyanite-remover | 0 | (ns cyanite-remover.cli
(:require [clojure.string :as str]
[clojure.tools.cli :as cli]
[cyanite-remover.logging :as clog]
[cyanite-remover.metric-store :as mstore]
[cyanite-remover.path-store :as pstore]
[cyanite-remover.core :as core]
[org.spootnik.logconfig :as logconfig])
(:gen-class))
(def cli-commands #{"remove-metrics" "remove-paths" "remove-obsolete-data"
"remove-empty-paths" "list-metrics" "list-paths"
"list-obsolete-data" "list-empty-paths" "help"})
(defn- parse-rollups
"Parse rollups."
[rollups]
(->> (str/split rollups #",")
(map #(re-matches #"^((\d+):(\d+))$" %))
(map #(if %
(let [seconds-per-point (Integer/parseInt (nth % 2))
retention (Integer/parseInt (nth % 3))
period (/ retention seconds-per-point)]
[seconds-per-point period])
%))))
(defn- usage
"Construct usage message."
[options-summary]
(->> ["A Cyanite data removal tool"
""
"Usage: "
" cyanite-remover [options] remove-metrics <tenant> <rollup,...> <path,...> <cassandra_host,...> <elasticsearch_url>"
" cyanite-remover [options] remove-paths <tenant> <path,...> <elasticsearch_url>"
" cyanite-remover [options] remove-obsolete-data <tenant> <rollup,...> <path,...> <cassandra_host,...> <elasticsearch_url>"
" cyanite-remover [options] remove-empty-paths <tenant> <path,...> <elasticsearch_url>"
" cyanite-remover [options] list-metrics <tenant> <rollup,...> <path,...> <cassandra_host,...> <elasticsearch_url>"
" cyanite-remover [options] list-paths <tenant> <path,...> <elasticsearch_url>"
" cyanite-remover [options] list-obsolete-data <tenant> <rollup,...> <path,...> <cassandra_host,...> <elasticsearch_url>"
" cyanite-remover [options] list-empty-paths <tenant> <path,...> <elasticsearch_url>"
" cyanite-remover help"
""
"Options:"
options-summary]
(str/join \newline)))
(defn- error-msg
"Combine error messages."
[errors]
(str "The following errors occurred while parsing your command:\n\n"
(str/join \newline errors)))
(defn- exit
"Print message and exit with status."
[status msg]
(if (= status 0)
(println msg)
(binding [*out* *err*]
(println msg)))
(System/exit status))
(defn- check-arguments
"Check arguments."
[command arguments min max]
(let [n-args (count arguments)]
(when (or (< n-args min) (> n-args max))
(exit 1 (error-msg
[(format "Invalid number of arguments for the command \"%s\""
command)])))))
(defn- check-options
"Check options."
[command valid-options options]
(doseq [option (keys options)]
(when (and (not (contains? valid-options option))
(not (= option :raw-arguments)))
(exit 1 (error-msg
[(format "Option \"--%s\" conflicts with the command \"%s\""
(name option) command)])))))
(defn- prepare-metrics-args
"Prepare metrics arguments."
[arguments options]
(let [tenant (nth arguments 0)
rollups (->> (nth arguments 1)
(parse-rollups)
(filter #(not (nil? %)))
(flatten)
(apply hash-map))
paths (str/split (nth arguments 2) #";")
cass-hosts (str/split (nth arguments 3) #",")
es-url (nth arguments 4)]
{:tenant tenant :rollups rollups :paths paths :cass-hosts cass-hosts
:es-url es-url :options options}))
(defn- prepare-paths-args
"Prepare paths arguments."
[arguments options]
(let [tenant (nth arguments 0)
paths (str/split (nth arguments 1) #",")
es-url (nth arguments 2)]
{:tenant tenant :paths paths :es-url es-url :options options}))
(defn- run-remove-metrics
"Run command 'remove-metrics'."
[command arguments options summary]
(check-arguments "remove-metrics" arguments 5 5)
(check-options command #{:from :to :run :exclude-paths :jobs :sort
:cassandra-keyspace :cassandra-options
:cassandra-user :cassandra-password :cassandra-tablename
:cassandra-channel-size :cassandra-batch-size
:cassandra-batch-rate :elasticsearch-index
:elasticsearch-scroll-batch-size
:elasticsearch-scroll-batch-rate
:log-file :log-level :disable-log :stop-on-error
:disable-progress}
options)
(when (and (:jobs options) (not (or (:from options) (:to options))))
(exit 1 (error-msg
["Option \"--jobs\" requires \"--from\" and/or \"--to\""])))
(let [{:keys [tenant rollups paths cass-hosts es-url
options]} (prepare-metrics-args arguments options)]
(core/remove-metrics tenant rollups paths cass-hosts es-url options)))
(defn- run-remove-paths
"Run command 'remove-paths'."
[command arguments options summary]
(check-arguments "remove-paths" arguments 3 3)
(check-options command #{:run :exclude-paths :sort :jobs :elasticsearch-index
:elasticsearch-scroll-batch-size
:elasticsearch-scroll-batch-rate
:elasticsearch-delete-request-rate :log-file
:log-level :disable-log :disable-progress}
options)
(let [{:keys [tenant paths es-url
options]} (prepare-paths-args arguments options)]
(core/remove-paths tenant paths es-url options)))
(defn- run-remove-obsolete-data
"Run command 'remove-obsolete-data'."
[command arguments options summary]
(check-arguments "remove-obsolete-data" arguments 5 5)
(check-options command #{:threshold :run :exclude-paths :sort :jobs
:cassandra-keyspace :cassandra-options
:cassandra-user :cassandra-password :cassandra-tablename
:cassandra-channel-size :cassandra-batch-size
:cassandra-batch-rate :elasticsearch-index
:elasticsearch-scroll-batch-size
:elasticsearch-scroll-batch-rate
:elasticsearch-delete-request-rate
:log-file :log-level :disable-log :stop-on-error
:disable-progress}
options)
(let [{:keys [tenant rollups paths cass-hosts es-url
options]} (prepare-metrics-args arguments options)]
(core/remove-obsolete-data tenant rollups paths cass-hosts es-url options)))
(defn- run-remove-empty-paths
"Run command 'remove-empty-paths'."
[command arguments options summary]
(check-arguments "remove-paths" arguments 3 3)
(check-options command #{:run :jobs :sort :elasticsearch-index
:elasticsearch-scroll-batch-size
:elasticsearch-scroll-batch-rate
:elasticsearch-delete-request-rate :log-file
:log-level :disable-log :stop-on-error
:disable-progress} options)
(let [{:keys [tenant paths es-url
options]} (prepare-paths-args arguments options)]
(core/remove-empty-paths tenant paths es-url options)))
(defn- run-list-metrics
"Run command 'list-metrics'."
[command arguments options summary]
(check-arguments "list-metrics" arguments 5 5)
(check-options command #{:from :to :exclude-paths :sort :cassandra-keyspace
:cassandra-options :elasticsearch-index
:cassandra-user :cassandra-password :cassandra-tablename
:elasticsearch-scroll-batch-size
:elasticsearch-scroll-batch-rate}
options)
(let [{:keys [tenant rollups paths cass-hosts es-url
options]} (prepare-metrics-args arguments options)]
(core/list-metrics tenant rollups paths cass-hosts es-url options)))
(defn- run-list-paths
"Run command 'list-paths'."
[command arguments options summary]
(check-arguments "list-paths" arguments 3 3)
(check-options command #{:exclude-paths :sort :elasticsearch-index
:elasticsearch-scroll-batch-size
:elasticsearch-scroll-batch-rate} options)
(let [{:keys [tenant paths es-url
options]} (prepare-paths-args arguments options)]
(core/list-paths tenant paths es-url options)))
(defn- run-list-obsolete-data
"Run command 'list-obsolete-data'."
[command arguments options summary]
(check-arguments "list-obsolete-data" arguments 5 5)
(check-options command #{:threshold :exclude-paths :sort :jobs
:cassandra-keyspace :cassandra-options
:cassandra-user :cassandra-password :cassandra-tablename
:elasticsearch-index :elasticsearch-scroll-batch-size
:elasticsearch-scroll-batch-rate}
options)
(let [{:keys [tenant rollups paths cass-hosts es-url
options]} (prepare-metrics-args arguments options)]
(core/list-obsolete-data tenant rollups paths cass-hosts es-url options)))
(defn- run-list-empty-paths
"Run command 'list-empty-paths'."
[command arguments options summary]
(check-arguments "list-paths" arguments 3 3)
(check-options command #{:jobs :sort :elasticsearch-index
:elasticsearch-scroll-batch-size
:elasticsearch-scroll-batch-rate} options)
(let [{:keys [tenant paths es-url
options]} (prepare-paths-args arguments options)]
(core/list-empty-paths tenant paths es-url options)))
(defn- run-help
"Run command 'help'."
[command arguments options summary]
(exit 0 (usage summary)))
(def cli-options
[["-f" "--from FROM" "From time (Unix epoch)"
:parse-fn #(Integer/parseInt %)
:validate [#(<= 0 %) "Must be a number >= 0"]]
["-t" "--to TO" "To time (Unix epoch)"
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
["-T" "--threshold THRESHOLD" (str "Threshold in seconds. Default: "
core/default-obsolete-metrics-threshold)
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
["-r" "--run" "Force normal run (dry run using on default)"]
["-e" "--exclude-paths PATHS"
"Exclude path. Example: \"requests.apache.*;sum.cpu.?\""
:parse-fn #(str/split % #";")]
["-s" "--sort" "Sort paths in alphabetical order"]
["-j" "--jobs JOBS" "Number of jobs to run simultaneously"
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
[nil "--cassandra-keyspace KEYSPACE"
(str "Cassandra keyspace. Default: " mstore/default-cassandra-keyspace)]
[nil "--cassandra-password PASSWORD"
(str "Cassandra Password. Default: " mstore/default-cassandra-password)]
[nil "--cassandra-user USER"
(str "Cassandra User. Default: " mstore/default-cassandra-user)]
[nil "--cassandra-tablename TABLENAME"
(str "Cassandra tablename. Default: " mstore/default-cassandra-tableName)]
["-O" "--cassandra-options OPTIONS"
"Cassandra options. Example: \"{:compression :lz4}\""
:parse-fn #(read-string %)
:validate [#(= clojure.lang.PersistentArrayMap (type %))]]
[nil "--cassandra-channel-size SIZE"
(str "Cassandra channel size. Default: "
mstore/default-cassandra-channel-size)
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
[nil "--cassandra-batch-size SIZE"
(str "Cassandra batch size. Default: " mstore/default-cassandra-batch-size)
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
[nil "--cassandra-batch-rate RATE" "Cassandra batch rate (batches per second)"
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
[nil "--elasticsearch-index INDEX"
(str "Elasticsearch index. Default: " pstore/default-es-index)]
[nil "--elasticsearch-scroll-batch-size SIZE"
(str "Elasticsearch scroll batch size. Default: "
pstore/default-es-scroll-batch-size)
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
[nil "--elasticsearch-scroll-batch-rate RATE"
"Elasticsearch scroll batch rate (batches per second)"
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
[nil "--elasticsearch-delete-request-rate RATE"
"Elasticsearch delete request rate (requests per second)"
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
["-l" "--log-file FILE" (str "Log file. Default: " clog/default-log-file)]
["-L" "--log-level LEVEL"
(str "Log level (all, trace, debug, info, warn, error, fatal, off). "
"Default: " clog/default-log-level)
:validate [#(or (= (count %) 0)
(not= (get logconfig/levels % :not-found) :not-found))
"Invalid log level"]]
["-S" "--stop-on-error" "Stop on first non-fatal error"]
["-P" "--disable-progress" "Disable progress bar"]
["-h" "--help" "Show this help"]])
(defn- run-command
"Run command."
[arguments options summary]
(let [command (first arguments)]
(when (not (contains? cli-commands command))
(exit 1 (error-msg [(format "Unknown command: \"%s\"" command)])))
(apply (resolve (symbol (str "cyanite-remover.cli/run-" command)))
[command (drop 1 arguments) options summary])))
(defn -main
"Main function."
[& args]
(let [{:keys [options arguments errors summary]}
(cli/parse-opts args cli-options)]
;; Handle help and error conditions
(cond
(or (< (count args) 1) (contains? options :help)) (exit 0 (usage summary))
errors (exit 1 (error-msg errors)))
;; Add raw arguments to options
(let [options (assoc options :raw-arguments args)]
;; Run command
(run-command arguments options summary))
(clog/exit 0)))
| 115398 | (ns cyanite-remover.cli
(:require [clojure.string :as str]
[clojure.tools.cli :as cli]
[cyanite-remover.logging :as clog]
[cyanite-remover.metric-store :as mstore]
[cyanite-remover.path-store :as pstore]
[cyanite-remover.core :as core]
[org.spootnik.logconfig :as logconfig])
(:gen-class))
(def cli-commands #{"remove-metrics" "remove-paths" "remove-obsolete-data"
"remove-empty-paths" "list-metrics" "list-paths"
"list-obsolete-data" "list-empty-paths" "help"})
(defn- parse-rollups
"Parse rollups."
[rollups]
(->> (str/split rollups #",")
(map #(re-matches #"^((\d+):(\d+))$" %))
(map #(if %
(let [seconds-per-point (Integer/parseInt (nth % 2))
retention (Integer/parseInt (nth % 3))
period (/ retention seconds-per-point)]
[seconds-per-point period])
%))))
(defn- usage
"Construct usage message."
[options-summary]
(->> ["A Cyanite data removal tool"
""
"Usage: "
" cyanite-remover [options] remove-metrics <tenant> <rollup,...> <path,...> <cassandra_host,...> <elasticsearch_url>"
" cyanite-remover [options] remove-paths <tenant> <path,...> <elasticsearch_url>"
" cyanite-remover [options] remove-obsolete-data <tenant> <rollup,...> <path,...> <cassandra_host,...> <elasticsearch_url>"
" cyanite-remover [options] remove-empty-paths <tenant> <path,...> <elasticsearch_url>"
" cyanite-remover [options] list-metrics <tenant> <rollup,...> <path,...> <cassandra_host,...> <elasticsearch_url>"
" cyanite-remover [options] list-paths <tenant> <path,...> <elasticsearch_url>"
" cyanite-remover [options] list-obsolete-data <tenant> <rollup,...> <path,...> <cassandra_host,...> <elasticsearch_url>"
" cyanite-remover [options] list-empty-paths <tenant> <path,...> <elasticsearch_url>"
" cyanite-remover help"
""
"Options:"
options-summary]
(str/join \newline)))
(defn- error-msg
"Combine error messages."
[errors]
(str "The following errors occurred while parsing your command:\n\n"
(str/join \newline errors)))
(defn- exit
"Print message and exit with status."
[status msg]
(if (= status 0)
(println msg)
(binding [*out* *err*]
(println msg)))
(System/exit status))
(defn- check-arguments
"Check arguments."
[command arguments min max]
(let [n-args (count arguments)]
(when (or (< n-args min) (> n-args max))
(exit 1 (error-msg
[(format "Invalid number of arguments for the command \"%s\""
command)])))))
(defn- check-options
"Check options."
[command valid-options options]
(doseq [option (keys options)]
(when (and (not (contains? valid-options option))
(not (= option :raw-arguments)))
(exit 1 (error-msg
[(format "Option \"--%s\" conflicts with the command \"%s\""
(name option) command)])))))
(defn- prepare-metrics-args
"Prepare metrics arguments."
[arguments options]
(let [tenant (nth arguments 0)
rollups (->> (nth arguments 1)
(parse-rollups)
(filter #(not (nil? %)))
(flatten)
(apply hash-map))
paths (str/split (nth arguments 2) #";")
cass-hosts (str/split (nth arguments 3) #",")
es-url (nth arguments 4)]
{:tenant tenant :rollups rollups :paths paths :cass-hosts cass-hosts
:es-url es-url :options options}))
(defn- prepare-paths-args
"Prepare paths arguments."
[arguments options]
(let [tenant (nth arguments 0)
paths (str/split (nth arguments 1) #",")
es-url (nth arguments 2)]
{:tenant tenant :paths paths :es-url es-url :options options}))
(defn- run-remove-metrics
"Run command 'remove-metrics'."
[command arguments options summary]
(check-arguments "remove-metrics" arguments 5 5)
(check-options command #{:from :to :run :exclude-paths :jobs :sort
:cassandra-keyspace :cassandra-options
:cassandra-user :cassandra-password :cassandra-tablename
:cassandra-channel-size :cassandra-batch-size
:cassandra-batch-rate :elasticsearch-index
:elasticsearch-scroll-batch-size
:elasticsearch-scroll-batch-rate
:log-file :log-level :disable-log :stop-on-error
:disable-progress}
options)
(when (and (:jobs options) (not (or (:from options) (:to options))))
(exit 1 (error-msg
["Option \"--jobs\" requires \"--from\" and/or \"--to\""])))
(let [{:keys [tenant rollups paths cass-hosts es-url
options]} (prepare-metrics-args arguments options)]
(core/remove-metrics tenant rollups paths cass-hosts es-url options)))
(defn- run-remove-paths
"Run command 'remove-paths'."
[command arguments options summary]
(check-arguments "remove-paths" arguments 3 3)
(check-options command #{:run :exclude-paths :sort :jobs :elasticsearch-index
:elasticsearch-scroll-batch-size
:elasticsearch-scroll-batch-rate
:elasticsearch-delete-request-rate :log-file
:log-level :disable-log :disable-progress}
options)
(let [{:keys [tenant paths es-url
options]} (prepare-paths-args arguments options)]
(core/remove-paths tenant paths es-url options)))
(defn- run-remove-obsolete-data
"Run command 'remove-obsolete-data'."
[command arguments options summary]
(check-arguments "remove-obsolete-data" arguments 5 5)
(check-options command #{:threshold :run :exclude-paths :sort :jobs
:cassandra-keyspace :cassandra-options
:cassandra-user :cassandra-password :cassandra-tablename
:cassandra-channel-size :cassandra-batch-size
:cassandra-batch-rate :elasticsearch-index
:elasticsearch-scroll-batch-size
:elasticsearch-scroll-batch-rate
:elasticsearch-delete-request-rate
:log-file :log-level :disable-log :stop-on-error
:disable-progress}
options)
(let [{:keys [tenant rollups paths cass-hosts es-url
options]} (prepare-metrics-args arguments options)]
(core/remove-obsolete-data tenant rollups paths cass-hosts es-url options)))
(defn- run-remove-empty-paths
"Run command 'remove-empty-paths'."
[command arguments options summary]
(check-arguments "remove-paths" arguments 3 3)
(check-options command #{:run :jobs :sort :elasticsearch-index
:elasticsearch-scroll-batch-size
:elasticsearch-scroll-batch-rate
:elasticsearch-delete-request-rate :log-file
:log-level :disable-log :stop-on-error
:disable-progress} options)
(let [{:keys [tenant paths es-url
options]} (prepare-paths-args arguments options)]
(core/remove-empty-paths tenant paths es-url options)))
(defn- run-list-metrics
"Run command 'list-metrics'."
[command arguments options summary]
(check-arguments "list-metrics" arguments 5 5)
(check-options command #{:from :to :exclude-paths :sort :cassandra-keyspace
:cassandra-options :elasticsearch-index
:cassandra-user :cassandra-password :cassandra-tablename
:elasticsearch-scroll-batch-size
:elasticsearch-scroll-batch-rate}
options)
(let [{:keys [tenant rollups paths cass-hosts es-url
options]} (prepare-metrics-args arguments options)]
(core/list-metrics tenant rollups paths cass-hosts es-url options)))
(defn- run-list-paths
"Run command 'list-paths'."
[command arguments options summary]
(check-arguments "list-paths" arguments 3 3)
(check-options command #{:exclude-paths :sort :elasticsearch-index
:elasticsearch-scroll-batch-size
:elasticsearch-scroll-batch-rate} options)
(let [{:keys [tenant paths es-url
options]} (prepare-paths-args arguments options)]
(core/list-paths tenant paths es-url options)))
(defn- run-list-obsolete-data
"Run command 'list-obsolete-data'."
[command arguments options summary]
(check-arguments "list-obsolete-data" arguments 5 5)
(check-options command #{:threshold :exclude-paths :sort :jobs
:cassandra-keyspace :cassandra-options
:cassandra-user :cassandra-password :cassandra-tablename
:elasticsearch-index :elasticsearch-scroll-batch-size
:elasticsearch-scroll-batch-rate}
options)
(let [{:keys [tenant rollups paths cass-hosts es-url
options]} (prepare-metrics-args arguments options)]
(core/list-obsolete-data tenant rollups paths cass-hosts es-url options)))
(defn- run-list-empty-paths
"Run command 'list-empty-paths'."
[command arguments options summary]
(check-arguments "list-paths" arguments 3 3)
(check-options command #{:jobs :sort :elasticsearch-index
:elasticsearch-scroll-batch-size
:elasticsearch-scroll-batch-rate} options)
(let [{:keys [tenant paths es-url
options]} (prepare-paths-args arguments options)]
(core/list-empty-paths tenant paths es-url options)))
(defn- run-help
"Run command 'help'."
[command arguments options summary]
(exit 0 (usage summary)))
(def cli-options
[["-f" "--from FROM" "From time (Unix epoch)"
:parse-fn #(Integer/parseInt %)
:validate [#(<= 0 %) "Must be a number >= 0"]]
["-t" "--to TO" "To time (Unix epoch)"
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
["-T" "--threshold THRESHOLD" (str "Threshold in seconds. Default: "
core/default-obsolete-metrics-threshold)
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
["-r" "--run" "Force normal run (dry run using on default)"]
["-e" "--exclude-paths PATHS"
"Exclude path. Example: \"requests.apache.*;sum.cpu.?\""
:parse-fn #(str/split % #";")]
["-s" "--sort" "Sort paths in alphabetical order"]
["-j" "--jobs JOBS" "Number of jobs to run simultaneously"
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
[nil "--cassandra-keyspace KEYSPACE"
(str "Cassandra keyspace. Default: " mstore/default-cassandra-keyspace)]
[nil "--cassandra-password <PASSWORD>"
(str "Cassandra Password. Default: " mstore/default-cassandra-password)]
[nil "--cassandra-user USER"
(str "Cassandra User. Default: " mstore/default-cassandra-user)]
[nil "--cassandra-tablename TABLENAME"
(str "Cassandra tablename. Default: " mstore/default-cassandra-tableName)]
["-O" "--cassandra-options OPTIONS"
"Cassandra options. Example: \"{:compression :lz4}\""
:parse-fn #(read-string %)
:validate [#(= clojure.lang.PersistentArrayMap (type %))]]
[nil "--cassandra-channel-size SIZE"
(str "Cassandra channel size. Default: "
mstore/default-cassandra-channel-size)
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
[nil "--cassandra-batch-size SIZE"
(str "Cassandra batch size. Default: " mstore/default-cassandra-batch-size)
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
[nil "--cassandra-batch-rate RATE" "Cassandra batch rate (batches per second)"
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
[nil "--elasticsearch-index INDEX"
(str "Elasticsearch index. Default: " pstore/default-es-index)]
[nil "--elasticsearch-scroll-batch-size SIZE"
(str "Elasticsearch scroll batch size. Default: "
pstore/default-es-scroll-batch-size)
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
[nil "--elasticsearch-scroll-batch-rate RATE"
"Elasticsearch scroll batch rate (batches per second)"
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
[nil "--elasticsearch-delete-request-rate RATE"
"Elasticsearch delete request rate (requests per second)"
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
["-l" "--log-file FILE" (str "Log file. Default: " clog/default-log-file)]
["-L" "--log-level LEVEL"
(str "Log level (all, trace, debug, info, warn, error, fatal, off). "
"Default: " clog/default-log-level)
:validate [#(or (= (count %) 0)
(not= (get logconfig/levels % :not-found) :not-found))
"Invalid log level"]]
["-S" "--stop-on-error" "Stop on first non-fatal error"]
["-P" "--disable-progress" "Disable progress bar"]
["-h" "--help" "Show this help"]])
(defn- run-command
"Run command."
[arguments options summary]
(let [command (first arguments)]
(when (not (contains? cli-commands command))
(exit 1 (error-msg [(format "Unknown command: \"%s\"" command)])))
(apply (resolve (symbol (str "cyanite-remover.cli/run-" command)))
[command (drop 1 arguments) options summary])))
(defn -main
"Main function."
[& args]
(let [{:keys [options arguments errors summary]}
(cli/parse-opts args cli-options)]
;; Handle help and error conditions
(cond
(or (< (count args) 1) (contains? options :help)) (exit 0 (usage summary))
errors (exit 1 (error-msg errors)))
;; Add raw arguments to options
(let [options (assoc options :raw-arguments args)]
;; Run command
(run-command arguments options summary))
(clog/exit 0)))
| true | (ns cyanite-remover.cli
(:require [clojure.string :as str]
[clojure.tools.cli :as cli]
[cyanite-remover.logging :as clog]
[cyanite-remover.metric-store :as mstore]
[cyanite-remover.path-store :as pstore]
[cyanite-remover.core :as core]
[org.spootnik.logconfig :as logconfig])
(:gen-class))
(def cli-commands #{"remove-metrics" "remove-paths" "remove-obsolete-data"
"remove-empty-paths" "list-metrics" "list-paths"
"list-obsolete-data" "list-empty-paths" "help"})
(defn- parse-rollups
"Parse rollups."
[rollups]
(->> (str/split rollups #",")
(map #(re-matches #"^((\d+):(\d+))$" %))
(map #(if %
(let [seconds-per-point (Integer/parseInt (nth % 2))
retention (Integer/parseInt (nth % 3))
period (/ retention seconds-per-point)]
[seconds-per-point period])
%))))
(defn- usage
"Construct usage message."
[options-summary]
(->> ["A Cyanite data removal tool"
""
"Usage: "
" cyanite-remover [options] remove-metrics <tenant> <rollup,...> <path,...> <cassandra_host,...> <elasticsearch_url>"
" cyanite-remover [options] remove-paths <tenant> <path,...> <elasticsearch_url>"
" cyanite-remover [options] remove-obsolete-data <tenant> <rollup,...> <path,...> <cassandra_host,...> <elasticsearch_url>"
" cyanite-remover [options] remove-empty-paths <tenant> <path,...> <elasticsearch_url>"
" cyanite-remover [options] list-metrics <tenant> <rollup,...> <path,...> <cassandra_host,...> <elasticsearch_url>"
" cyanite-remover [options] list-paths <tenant> <path,...> <elasticsearch_url>"
" cyanite-remover [options] list-obsolete-data <tenant> <rollup,...> <path,...> <cassandra_host,...> <elasticsearch_url>"
" cyanite-remover [options] list-empty-paths <tenant> <path,...> <elasticsearch_url>"
" cyanite-remover help"
""
"Options:"
options-summary]
(str/join \newline)))
(defn- error-msg
"Combine error messages."
[errors]
(str "The following errors occurred while parsing your command:\n\n"
(str/join \newline errors)))
(defn- exit
"Print message and exit with status."
[status msg]
(if (= status 0)
(println msg)
(binding [*out* *err*]
(println msg)))
(System/exit status))
(defn- check-arguments
"Check arguments."
[command arguments min max]
(let [n-args (count arguments)]
(when (or (< n-args min) (> n-args max))
(exit 1 (error-msg
[(format "Invalid number of arguments for the command \"%s\""
command)])))))
(defn- check-options
"Check options."
[command valid-options options]
(doseq [option (keys options)]
(when (and (not (contains? valid-options option))
(not (= option :raw-arguments)))
(exit 1 (error-msg
[(format "Option \"--%s\" conflicts with the command \"%s\""
(name option) command)])))))
(defn- prepare-metrics-args
"Prepare metrics arguments."
[arguments options]
(let [tenant (nth arguments 0)
rollups (->> (nth arguments 1)
(parse-rollups)
(filter #(not (nil? %)))
(flatten)
(apply hash-map))
paths (str/split (nth arguments 2) #";")
cass-hosts (str/split (nth arguments 3) #",")
es-url (nth arguments 4)]
{:tenant tenant :rollups rollups :paths paths :cass-hosts cass-hosts
:es-url es-url :options options}))
(defn- prepare-paths-args
"Prepare paths arguments."
[arguments options]
(let [tenant (nth arguments 0)
paths (str/split (nth arguments 1) #",")
es-url (nth arguments 2)]
{:tenant tenant :paths paths :es-url es-url :options options}))
(defn- run-remove-metrics
"Run command 'remove-metrics'."
[command arguments options summary]
(check-arguments "remove-metrics" arguments 5 5)
(check-options command #{:from :to :run :exclude-paths :jobs :sort
:cassandra-keyspace :cassandra-options
:cassandra-user :cassandra-password :cassandra-tablename
:cassandra-channel-size :cassandra-batch-size
:cassandra-batch-rate :elasticsearch-index
:elasticsearch-scroll-batch-size
:elasticsearch-scroll-batch-rate
:log-file :log-level :disable-log :stop-on-error
:disable-progress}
options)
(when (and (:jobs options) (not (or (:from options) (:to options))))
(exit 1 (error-msg
["Option \"--jobs\" requires \"--from\" and/or \"--to\""])))
(let [{:keys [tenant rollups paths cass-hosts es-url
options]} (prepare-metrics-args arguments options)]
(core/remove-metrics tenant rollups paths cass-hosts es-url options)))
(defn- run-remove-paths
"Run command 'remove-paths'."
[command arguments options summary]
(check-arguments "remove-paths" arguments 3 3)
(check-options command #{:run :exclude-paths :sort :jobs :elasticsearch-index
:elasticsearch-scroll-batch-size
:elasticsearch-scroll-batch-rate
:elasticsearch-delete-request-rate :log-file
:log-level :disable-log :disable-progress}
options)
(let [{:keys [tenant paths es-url
options]} (prepare-paths-args arguments options)]
(core/remove-paths tenant paths es-url options)))
(defn- run-remove-obsolete-data
"Run command 'remove-obsolete-data'."
[command arguments options summary]
(check-arguments "remove-obsolete-data" arguments 5 5)
(check-options command #{:threshold :run :exclude-paths :sort :jobs
:cassandra-keyspace :cassandra-options
:cassandra-user :cassandra-password :cassandra-tablename
:cassandra-channel-size :cassandra-batch-size
:cassandra-batch-rate :elasticsearch-index
:elasticsearch-scroll-batch-size
:elasticsearch-scroll-batch-rate
:elasticsearch-delete-request-rate
:log-file :log-level :disable-log :stop-on-error
:disable-progress}
options)
(let [{:keys [tenant rollups paths cass-hosts es-url
options]} (prepare-metrics-args arguments options)]
(core/remove-obsolete-data tenant rollups paths cass-hosts es-url options)))
(defn- run-remove-empty-paths
"Run command 'remove-empty-paths'."
[command arguments options summary]
(check-arguments "remove-paths" arguments 3 3)
(check-options command #{:run :jobs :sort :elasticsearch-index
:elasticsearch-scroll-batch-size
:elasticsearch-scroll-batch-rate
:elasticsearch-delete-request-rate :log-file
:log-level :disable-log :stop-on-error
:disable-progress} options)
(let [{:keys [tenant paths es-url
options]} (prepare-paths-args arguments options)]
(core/remove-empty-paths tenant paths es-url options)))
(defn- run-list-metrics
"Run command 'list-metrics'."
[command arguments options summary]
(check-arguments "list-metrics" arguments 5 5)
(check-options command #{:from :to :exclude-paths :sort :cassandra-keyspace
:cassandra-options :elasticsearch-index
:cassandra-user :cassandra-password :cassandra-tablename
:elasticsearch-scroll-batch-size
:elasticsearch-scroll-batch-rate}
options)
(let [{:keys [tenant rollups paths cass-hosts es-url
options]} (prepare-metrics-args arguments options)]
(core/list-metrics tenant rollups paths cass-hosts es-url options)))
(defn- run-list-paths
"Run command 'list-paths'."
[command arguments options summary]
(check-arguments "list-paths" arguments 3 3)
(check-options command #{:exclude-paths :sort :elasticsearch-index
:elasticsearch-scroll-batch-size
:elasticsearch-scroll-batch-rate} options)
(let [{:keys [tenant paths es-url
options]} (prepare-paths-args arguments options)]
(core/list-paths tenant paths es-url options)))
(defn- run-list-obsolete-data
"Run command 'list-obsolete-data'."
[command arguments options summary]
(check-arguments "list-obsolete-data" arguments 5 5)
(check-options command #{:threshold :exclude-paths :sort :jobs
:cassandra-keyspace :cassandra-options
:cassandra-user :cassandra-password :cassandra-tablename
:elasticsearch-index :elasticsearch-scroll-batch-size
:elasticsearch-scroll-batch-rate}
options)
(let [{:keys [tenant rollups paths cass-hosts es-url
options]} (prepare-metrics-args arguments options)]
(core/list-obsolete-data tenant rollups paths cass-hosts es-url options)))
(defn- run-list-empty-paths
"Run command 'list-empty-paths'."
[command arguments options summary]
(check-arguments "list-paths" arguments 3 3)
(check-options command #{:jobs :sort :elasticsearch-index
:elasticsearch-scroll-batch-size
:elasticsearch-scroll-batch-rate} options)
(let [{:keys [tenant paths es-url
options]} (prepare-paths-args arguments options)]
(core/list-empty-paths tenant paths es-url options)))
(defn- run-help
"Run command 'help'."
[command arguments options summary]
(exit 0 (usage summary)))
(def cli-options
[["-f" "--from FROM" "From time (Unix epoch)"
:parse-fn #(Integer/parseInt %)
:validate [#(<= 0 %) "Must be a number >= 0"]]
["-t" "--to TO" "To time (Unix epoch)"
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
["-T" "--threshold THRESHOLD" (str "Threshold in seconds. Default: "
core/default-obsolete-metrics-threshold)
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
["-r" "--run" "Force normal run (dry run using on default)"]
["-e" "--exclude-paths PATHS"
"Exclude path. Example: \"requests.apache.*;sum.cpu.?\""
:parse-fn #(str/split % #";")]
["-s" "--sort" "Sort paths in alphabetical order"]
["-j" "--jobs JOBS" "Number of jobs to run simultaneously"
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
[nil "--cassandra-keyspace KEYSPACE"
(str "Cassandra keyspace. Default: " mstore/default-cassandra-keyspace)]
[nil "--cassandra-password PI:PASSWORD:<PASSWORD>END_PI"
(str "Cassandra Password. Default: " mstore/default-cassandra-password)]
[nil "--cassandra-user USER"
(str "Cassandra User. Default: " mstore/default-cassandra-user)]
[nil "--cassandra-tablename TABLENAME"
(str "Cassandra tablename. Default: " mstore/default-cassandra-tableName)]
["-O" "--cassandra-options OPTIONS"
"Cassandra options. Example: \"{:compression :lz4}\""
:parse-fn #(read-string %)
:validate [#(= clojure.lang.PersistentArrayMap (type %))]]
[nil "--cassandra-channel-size SIZE"
(str "Cassandra channel size. Default: "
mstore/default-cassandra-channel-size)
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
[nil "--cassandra-batch-size SIZE"
(str "Cassandra batch size. Default: " mstore/default-cassandra-batch-size)
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
[nil "--cassandra-batch-rate RATE" "Cassandra batch rate (batches per second)"
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
[nil "--elasticsearch-index INDEX"
(str "Elasticsearch index. Default: " pstore/default-es-index)]
[nil "--elasticsearch-scroll-batch-size SIZE"
(str "Elasticsearch scroll batch size. Default: "
pstore/default-es-scroll-batch-size)
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
[nil "--elasticsearch-scroll-batch-rate RATE"
"Elasticsearch scroll batch rate (batches per second)"
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
[nil "--elasticsearch-delete-request-rate RATE"
"Elasticsearch delete request rate (requests per second)"
:parse-fn #(Integer/parseInt %)
:validate [#(< 0 %) "Must be a number > 0"]]
["-l" "--log-file FILE" (str "Log file. Default: " clog/default-log-file)]
["-L" "--log-level LEVEL"
(str "Log level (all, trace, debug, info, warn, error, fatal, off). "
"Default: " clog/default-log-level)
:validate [#(or (= (count %) 0)
(not= (get logconfig/levels % :not-found) :not-found))
"Invalid log level"]]
["-S" "--stop-on-error" "Stop on first non-fatal error"]
["-P" "--disable-progress" "Disable progress bar"]
["-h" "--help" "Show this help"]])
(defn- run-command
"Run command."
[arguments options summary]
(let [command (first arguments)]
(when (not (contains? cli-commands command))
(exit 1 (error-msg [(format "Unknown command: \"%s\"" command)])))
(apply (resolve (symbol (str "cyanite-remover.cli/run-" command)))
[command (drop 1 arguments) options summary])))
(defn -main
"Main function."
[& args]
(let [{:keys [options arguments errors summary]}
(cli/parse-opts args cli-options)]
;; Handle help and error conditions
(cond
(or (< (count args) 1) (contains? options :help)) (exit 0 (usage summary))
errors (exit 1 (error-msg errors)))
;; Add raw arguments to options
(let [options (assoc options :raw-arguments args)]
;; Run command
(run-command arguments options summary))
(clog/exit 0)))
|
[
{
"context": "is (= #{\"Building Search Applications is author by Manu Konchady.\"\n \"Manu Konchady is the author of Bu",
"end": 2625,
"score": 0.9993900060653687,
"start": 2612,
"tag": "NAME",
"value": "Manu Konchady"
},
{
"context": "ations is author by Manu Konchady.\"\n \"Manu Konchady is the author of Building Search Applications.\"} ",
"end": 2655,
"score": 0.9542611241340637,
"start": 2642,
"tag": "NAME",
"value": "Manu Konchady"
},
{
"context": " {\"9780307743657\" {:title \"The Shinning\" :author \"Stephen King\"}\n \"9780575099999\" {:title \"Horns\" ",
"end": 3048,
"score": 0.9998084902763367,
"start": 3036,
"tag": "NAME",
"value": "Stephen King"
},
{
"context": " \"9780575099999\" {:title \"Horns\" :author \"Joe Hill\"}\n \"9780099765219\" {:title \"Fight Cl",
"end": 3121,
"score": 0.9997625946998596,
"start": 3113,
"tag": "NAME",
"value": "Joe Hill"
},
{
"context": " \"9780099765219\" {:title \"Fight Club\" :author \"Chuck Palahniuk\"}}\n {{result-id :resultId} :body status :s",
"end": 3201,
"score": 0.9998714327812195,
"start": 3186,
"tag": "NAME",
"value": "Chuck Palahniuk"
},
{
"context": "is (= #{\"Building Search Applications is author by Manu Konchady.\"\n ;; \"Manu Konchady is the author of",
"end": 3416,
"score": 0.9410041570663452,
"start": 3403,
"tag": "NAME",
"value": "Manu Konchady"
},
{
"context": "ons is author by Manu Konchady.\"\n ;; \"Manu Konchady is the author of Building Search Applications.\"} ",
"end": 3449,
"score": 0.8790190815925598,
"start": 3436,
"tag": "NAME",
"value": "Manu Konchady"
},
{
"context": " (some? result-id))\n (is (= #{\"Noted author Manu Konchady.\"} (-> result-id (get-variants) :sample)))))\n\n(de",
"end": 5297,
"score": 0.999358057975769,
"start": 5287,
"tag": "NAME",
"value": "u Konchady"
},
{
"context": "ion bug at the moment, TODO: fix it\n (is (= #{\"Manu Konchady is the author of Building Search Applications . R",
"end": 6518,
"score": 0.9997153282165527,
"start": 6505,
"tag": "NAME",
"value": "Manu Konchady"
},
{
"context": " \"Building Search Applications is written by Manu Konchady . Rarely is so much learning displayed with so mu",
"end": 6705,
"score": 0.9997345209121704,
"start": 6692,
"tag": "NAME",
"value": "Manu Konchady"
}
] | api/test/api/end_to_end_test.clj | zorrock/accelerated-text | 1 | (ns api.end-to-end-test
(:require [api.db-fixtures :as fixtures]
[api.test-utils :refer [q load-test-document-plan]]
[clojure.test :refer [deftest is use-fixtures]]
[data.entities.document-plan :as dp]
[data.entities.data-files :as data-files]
[data.entities.dictionary :as dictionary]))
(defn prepare-environment [f]
(dictionary/create-dictionary-item {:key "cut"
:name "cut"
:phrases ["cut"]
:partOfSpeech :VB})
(f))
(use-fixtures :each fixtures/clean-db prepare-environment)
(defn add-document-plan [document-plan-id]
(:id (dp/add-document-plan {:uid document-plan-id
:name document-plan-id
:documentPlan (load-test-document-plan document-plan-id)}
document-plan-id)))
(defn store-data-file [filename]
(data-files/store!
{:filename filename
:content (slurp (format "test/resources/accelerated-text-data-files/%s" filename))}))
(defn generate [document-plan-id filename]
(q "/nlg/" :post {:documentPlanId (add-document-plan document-plan-id)
:readerFlagValues {}
:dataId (store-data-file filename)}))
(defn generate-bulk [document-plan-id rows]
(q "/nlg/_bulk/" :post {:documentPlanId (add-document-plan document-plan-id)
:readerFlagValues {}
:dataRows rows}))
(defn wait-for-results [result-id]
(while (false? (get-in (q (str "/nlg/" result-id) :get nil {:format "raw"}) [:body :ready]))
(Thread/sleep 100)))
(defn get-variants [result-id]
(when (some? result-id)
(wait-for-results result-id)
(let [response (q (str "/nlg/" result-id) :get nil {:format "raw"})
variants (get-in response [:body :variants])]
(into {} (map (fn [item] (let [[k v] item] {(keyword k) (set v)})) variants)))))
(deftest ^:integration single-element-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "title-only" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Building Search Applications."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration authorship-document-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "authorship" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Building Search Applications is author by Manu Konchady."
"Manu Konchady is the author of Building Search Applications."} (-> result-id
(get-variants)
:sample)))))
(deftest ^:integration authorship-document-plan-bulk-generation
(let [data {"9780307743657" {:title "The Shinning" :author "Stephen King"}
"9780575099999" {:title "Horns" :author "Joe Hill"}
"9780099765219" {:title "Fight Club" :author "Chuck Palahniuk"}}
{{result-id :resultId} :body status :status} (generate-bulk "authorship" data)]
(is (= 200 status))
(is (some? result-id))
;; (is (= #{"Building Search Applications is author by Manu Konchady."
;; "Manu Konchady is the author of Building Search Applications."} (get-variants result-id)))
))
(deftest ^:integration adjective-phrase-document-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "adjective-phrase" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Good Building Search Applications."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration author-amr-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "author-amr" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"{{Agent}} is the author of {{co-Agent}}."
"{{co-Agent}} is {{...}} by {{Agent}}."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration single-quote-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "single-quote" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"This is a very good book: Building Search Applications."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration single-modifier-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "single-modifier" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Good."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration complex-amr-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "cut-amr" "carol.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Carol cut envelope into pieces with knife."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration multiple-modifier-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "multiple-modifiers" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Noted author Manu Konchady."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration sequence-block-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "sequence-block" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"1 2 3."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration random-sequence-block-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "random-sequence-block" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"1 2 3." "1 3 2." "2 1 3." "2 3 1." "3 2 1." "3 1 2."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration one-of-synonyms-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "one-of-synonyms" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Good." "Excellent."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration multiple-segments-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "multiple-segments" "books.csv")]
(is (= 200 status))
(is (some? result-id))
;; Spaces before dot - our generation bug at the moment, TODO: fix it
(is (= #{"Manu Konchady is the author of Building Search Applications . Rarely is so much learning displayed with so much grace and charm."
"Building Search Applications is written by Manu Konchady . Rarely is so much learning displayed with so much grace and charm."}
(-> result-id (get-variants) :sample)))))
(deftest ^:integration sequence-with-empty-shuffle-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "sequence-with-empty-shuffle" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"1."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration sequence-with-shuffle-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "sequence-with-shuffle" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"1 3 2." "1 2 3."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration sequence-with-shuffle-and-empty-synonyms-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "sequence-with-shuffle-and-empty-synonyms" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"1 3 2." "1 2 3."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration sequence-with-shuffle-and-synonyms-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "sequence-with-shuffle-and-synonyms" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"1 2 3 4." "1 2 3 5." "1 2 4 3." "1 2 5 3." "1 3 2 4." "1 3 2 5."
"1 3 4 2." "1 3 5 2." "1 4 2 3." "1 4 3 2." "1 5 2 3." "1 5 3 2."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration if-equal-condition-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "if-equal-condition" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"The book was published in 2008."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration if-with-and-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "if-with-and" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"The book was published in 2008 and is about Lucene."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration if-not-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "if-not" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"The book is about computers."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration if-xor-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "if-xor" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Either the book is written in English or it is less than 50 pages long."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration variable-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "variable" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Some text."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration variable-multi-def-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "variable-multi-def" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"X." "Y."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration variable-undefined-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "variable-undefined" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{""} (-> result-id (get-variants) :sample)))))
(deftest ^:integration variable-unused-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "variable-unused" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Some text."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration modifier-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "modifier" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Nice text."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration cell-modifier-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "modifier-cell" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Computers book."} (-> result-id (get-variants) :sample)))))
| 88363 | (ns api.end-to-end-test
(:require [api.db-fixtures :as fixtures]
[api.test-utils :refer [q load-test-document-plan]]
[clojure.test :refer [deftest is use-fixtures]]
[data.entities.document-plan :as dp]
[data.entities.data-files :as data-files]
[data.entities.dictionary :as dictionary]))
(defn prepare-environment [f]
(dictionary/create-dictionary-item {:key "cut"
:name "cut"
:phrases ["cut"]
:partOfSpeech :VB})
(f))
(use-fixtures :each fixtures/clean-db prepare-environment)
(defn add-document-plan [document-plan-id]
(:id (dp/add-document-plan {:uid document-plan-id
:name document-plan-id
:documentPlan (load-test-document-plan document-plan-id)}
document-plan-id)))
(defn store-data-file [filename]
(data-files/store!
{:filename filename
:content (slurp (format "test/resources/accelerated-text-data-files/%s" filename))}))
(defn generate [document-plan-id filename]
(q "/nlg/" :post {:documentPlanId (add-document-plan document-plan-id)
:readerFlagValues {}
:dataId (store-data-file filename)}))
(defn generate-bulk [document-plan-id rows]
(q "/nlg/_bulk/" :post {:documentPlanId (add-document-plan document-plan-id)
:readerFlagValues {}
:dataRows rows}))
(defn wait-for-results [result-id]
(while (false? (get-in (q (str "/nlg/" result-id) :get nil {:format "raw"}) [:body :ready]))
(Thread/sleep 100)))
(defn get-variants [result-id]
(when (some? result-id)
(wait-for-results result-id)
(let [response (q (str "/nlg/" result-id) :get nil {:format "raw"})
variants (get-in response [:body :variants])]
(into {} (map (fn [item] (let [[k v] item] {(keyword k) (set v)})) variants)))))
(deftest ^:integration single-element-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "title-only" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Building Search Applications."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration authorship-document-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "authorship" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Building Search Applications is author by <NAME>."
"<NAME> is the author of Building Search Applications."} (-> result-id
(get-variants)
:sample)))))
(deftest ^:integration authorship-document-plan-bulk-generation
(let [data {"9780307743657" {:title "The Shinning" :author "<NAME>"}
"9780575099999" {:title "Horns" :author "<NAME>"}
"9780099765219" {:title "Fight Club" :author "<NAME>"}}
{{result-id :resultId} :body status :status} (generate-bulk "authorship" data)]
(is (= 200 status))
(is (some? result-id))
;; (is (= #{"Building Search Applications is author by <NAME>."
;; "<NAME> is the author of Building Search Applications."} (get-variants result-id)))
))
(deftest ^:integration adjective-phrase-document-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "adjective-phrase" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Good Building Search Applications."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration author-amr-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "author-amr" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"{{Agent}} is the author of {{co-Agent}}."
"{{co-Agent}} is {{...}} by {{Agent}}."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration single-quote-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "single-quote" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"This is a very good book: Building Search Applications."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration single-modifier-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "single-modifier" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Good."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration complex-amr-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "cut-amr" "carol.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Carol cut envelope into pieces with knife."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration multiple-modifier-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "multiple-modifiers" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Noted author Man<NAME>."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration sequence-block-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "sequence-block" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"1 2 3."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration random-sequence-block-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "random-sequence-block" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"1 2 3." "1 3 2." "2 1 3." "2 3 1." "3 2 1." "3 1 2."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration one-of-synonyms-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "one-of-synonyms" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Good." "Excellent."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration multiple-segments-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "multiple-segments" "books.csv")]
(is (= 200 status))
(is (some? result-id))
;; Spaces before dot - our generation bug at the moment, TODO: fix it
(is (= #{"<NAME> is the author of Building Search Applications . Rarely is so much learning displayed with so much grace and charm."
"Building Search Applications is written by <NAME> . Rarely is so much learning displayed with so much grace and charm."}
(-> result-id (get-variants) :sample)))))
(deftest ^:integration sequence-with-empty-shuffle-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "sequence-with-empty-shuffle" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"1."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration sequence-with-shuffle-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "sequence-with-shuffle" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"1 3 2." "1 2 3."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration sequence-with-shuffle-and-empty-synonyms-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "sequence-with-shuffle-and-empty-synonyms" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"1 3 2." "1 2 3."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration sequence-with-shuffle-and-synonyms-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "sequence-with-shuffle-and-synonyms" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"1 2 3 4." "1 2 3 5." "1 2 4 3." "1 2 5 3." "1 3 2 4." "1 3 2 5."
"1 3 4 2." "1 3 5 2." "1 4 2 3." "1 4 3 2." "1 5 2 3." "1 5 3 2."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration if-equal-condition-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "if-equal-condition" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"The book was published in 2008."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration if-with-and-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "if-with-and" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"The book was published in 2008 and is about Lucene."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration if-not-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "if-not" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"The book is about computers."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration if-xor-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "if-xor" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Either the book is written in English or it is less than 50 pages long."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration variable-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "variable" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Some text."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration variable-multi-def-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "variable-multi-def" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"X." "Y."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration variable-undefined-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "variable-undefined" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{""} (-> result-id (get-variants) :sample)))))
(deftest ^:integration variable-unused-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "variable-unused" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Some text."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration modifier-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "modifier" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Nice text."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration cell-modifier-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "modifier-cell" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Computers book."} (-> result-id (get-variants) :sample)))))
| true | (ns api.end-to-end-test
(:require [api.db-fixtures :as fixtures]
[api.test-utils :refer [q load-test-document-plan]]
[clojure.test :refer [deftest is use-fixtures]]
[data.entities.document-plan :as dp]
[data.entities.data-files :as data-files]
[data.entities.dictionary :as dictionary]))
(defn prepare-environment [f]
(dictionary/create-dictionary-item {:key "cut"
:name "cut"
:phrases ["cut"]
:partOfSpeech :VB})
(f))
(use-fixtures :each fixtures/clean-db prepare-environment)
(defn add-document-plan [document-plan-id]
(:id (dp/add-document-plan {:uid document-plan-id
:name document-plan-id
:documentPlan (load-test-document-plan document-plan-id)}
document-plan-id)))
(defn store-data-file [filename]
(data-files/store!
{:filename filename
:content (slurp (format "test/resources/accelerated-text-data-files/%s" filename))}))
(defn generate [document-plan-id filename]
(q "/nlg/" :post {:documentPlanId (add-document-plan document-plan-id)
:readerFlagValues {}
:dataId (store-data-file filename)}))
(defn generate-bulk [document-plan-id rows]
(q "/nlg/_bulk/" :post {:documentPlanId (add-document-plan document-plan-id)
:readerFlagValues {}
:dataRows rows}))
(defn wait-for-results [result-id]
(while (false? (get-in (q (str "/nlg/" result-id) :get nil {:format "raw"}) [:body :ready]))
(Thread/sleep 100)))
(defn get-variants [result-id]
(when (some? result-id)
(wait-for-results result-id)
(let [response (q (str "/nlg/" result-id) :get nil {:format "raw"})
variants (get-in response [:body :variants])]
(into {} (map (fn [item] (let [[k v] item] {(keyword k) (set v)})) variants)))))
(deftest ^:integration single-element-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "title-only" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Building Search Applications."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration authorship-document-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "authorship" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Building Search Applications is author by PI:NAME:<NAME>END_PI."
"PI:NAME:<NAME>END_PI is the author of Building Search Applications."} (-> result-id
(get-variants)
:sample)))))
(deftest ^:integration authorship-document-plan-bulk-generation
(let [data {"9780307743657" {:title "The Shinning" :author "PI:NAME:<NAME>END_PI"}
"9780575099999" {:title "Horns" :author "PI:NAME:<NAME>END_PI"}
"9780099765219" {:title "Fight Club" :author "PI:NAME:<NAME>END_PI"}}
{{result-id :resultId} :body status :status} (generate-bulk "authorship" data)]
(is (= 200 status))
(is (some? result-id))
;; (is (= #{"Building Search Applications is author by PI:NAME:<NAME>END_PI."
;; "PI:NAME:<NAME>END_PI is the author of Building Search Applications."} (get-variants result-id)))
))
(deftest ^:integration adjective-phrase-document-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "adjective-phrase" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Good Building Search Applications."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration author-amr-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "author-amr" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"{{Agent}} is the author of {{co-Agent}}."
"{{co-Agent}} is {{...}} by {{Agent}}."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration single-quote-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "single-quote" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"This is a very good book: Building Search Applications."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration single-modifier-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "single-modifier" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Good."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration complex-amr-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "cut-amr" "carol.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Carol cut envelope into pieces with knife."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration multiple-modifier-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "multiple-modifiers" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Noted author ManPI:NAME:<NAME>END_PI."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration sequence-block-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "sequence-block" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"1 2 3."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration random-sequence-block-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "random-sequence-block" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"1 2 3." "1 3 2." "2 1 3." "2 3 1." "3 2 1." "3 1 2."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration one-of-synonyms-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "one-of-synonyms" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Good." "Excellent."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration multiple-segments-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "multiple-segments" "books.csv")]
(is (= 200 status))
(is (some? result-id))
;; Spaces before dot - our generation bug at the moment, TODO: fix it
(is (= #{"PI:NAME:<NAME>END_PI is the author of Building Search Applications . Rarely is so much learning displayed with so much grace and charm."
"Building Search Applications is written by PI:NAME:<NAME>END_PI . Rarely is so much learning displayed with so much grace and charm."}
(-> result-id (get-variants) :sample)))))
(deftest ^:integration sequence-with-empty-shuffle-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "sequence-with-empty-shuffle" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"1."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration sequence-with-shuffle-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "sequence-with-shuffle" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"1 3 2." "1 2 3."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration sequence-with-shuffle-and-empty-synonyms-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "sequence-with-shuffle-and-empty-synonyms" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"1 3 2." "1 2 3."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration sequence-with-shuffle-and-synonyms-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "sequence-with-shuffle-and-synonyms" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"1 2 3 4." "1 2 3 5." "1 2 4 3." "1 2 5 3." "1 3 2 4." "1 3 2 5."
"1 3 4 2." "1 3 5 2." "1 4 2 3." "1 4 3 2." "1 5 2 3." "1 5 3 2."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration if-equal-condition-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "if-equal-condition" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"The book was published in 2008."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration if-with-and-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "if-with-and" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"The book was published in 2008 and is about Lucene."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration if-not-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "if-not" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"The book is about computers."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration if-xor-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "if-xor" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Either the book is written in English or it is less than 50 pages long."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration variable-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "variable" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Some text."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration variable-multi-def-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "variable-multi-def" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"X." "Y."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration variable-undefined-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "variable-undefined" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{""} (-> result-id (get-variants) :sample)))))
(deftest ^:integration variable-unused-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "variable-unused" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Some text."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration modifier-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "modifier" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Nice text."} (-> result-id (get-variants) :sample)))))
(deftest ^:integration cell-modifier-plan-generation
(let [{{result-id :resultId} :body status :status} (generate "modifier-cell" "books.csv")]
(is (= 200 status))
(is (some? result-id))
(is (= #{"Computers book."} (-> result-id (get-variants) :sample)))))
|
[
{
"context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li",
"end": 111,
"score": 0.9998103976249695,
"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.9998093247413635,
"start": 113,
"tag": "NAME",
"value": "Christian Murray"
}
] | editor/src/clj/editor/gl/texture.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.gl.texture
"Functions for creating and using textures"
(:require [editor.image-util :as image-util]
[editor.gl.protocols :refer [GlBind]]
[editor.gl :as gl]
[internal.util :as util]
[editor.scene-cache :as scene-cache]
[dynamo.graph :as g])
(:import [java.awt.image BufferedImage DataBuffer DataBufferByte]
[java.nio Buffer IntBuffer ByteBuffer]
[com.dynamo.graphics.proto Graphics$TextureImage Graphics$TextureImage$Image Graphics$TextureImage$TextureFormat]
[com.jogamp.opengl GL GL2 GL3 GLContext GLProfile]
[com.jogamp.common.nio Buffers]
[com.jogamp.opengl.util.texture Texture TextureIO TextureData]
[com.jogamp.opengl.util.awt ImageUtil]))
(set! *warn-on-reflection* true)
(def
^{:doc "This map translates Clojure keywords into OpenGL constants.
You can use the keywords in texture parameter maps."}
texture-params
{:base-level GL2/GL_TEXTURE_BASE_LEVEL
:border-color GL2/GL_TEXTURE_BORDER_COLOR
:compare-func GL2/GL_TEXTURE_COMPARE_FUNC
:compare-mode GL2/GL_TEXTURE_COMPARE_MODE
:lod-bias GL2/GL_TEXTURE_LOD_BIAS
:min-filter GL/GL_TEXTURE_MIN_FILTER
:mag-filter GL/GL_TEXTURE_MAG_FILTER
:min-lod GL2/GL_TEXTURE_MIN_LOD
:max-lod GL2/GL_TEXTURE_MAX_LOD
:max-level GL2/GL_TEXTURE_MAX_LEVEL
:swizzle-r GL3/GL_TEXTURE_SWIZZLE_R
:swizzle-g GL3/GL_TEXTURE_SWIZZLE_G
:swizzle-b GL3/GL_TEXTURE_SWIZZLE_B
:swizzle-a GL3/GL_TEXTURE_SWIZZLE_A
:wrap-s GL2/GL_TEXTURE_WRAP_S
:wrap-t GL2/GL_TEXTURE_WRAP_T
:wrap-r GL2/GL_TEXTURE_WRAP_R})
(defn- apply-params!
[^GL2 gl ^long texture-target params]
(let [params (if-let [sampler-name (:name params)]
(when-let [program (gl/gl-current-program gl)]
(if (= -1 (.glGetUniformLocation gl program sampler-name))
(:default-tex-params params)
params))
params)]
(doseq [[p v] params]
(if-let [pname (texture-params p)]
(.glTexParameteri gl texture-target pname v)
(cond
(integer? p) (.glTexParameteri gl texture-target p v)
;; Silently ignore extra sampler data
(= :name p) nil
(= :default-tex-params p) nil
:else (println "WARNING: ignoring unknown texture parameter " p))))))
(defprotocol TextureProxy
(->texture ^Texture [this ^GL2 gl]))
(defrecord TextureLifecycle [request-id cache-id unit params texture-data]
TextureProxy
(->texture [this gl]
(scene-cache/request-object! cache-id request-id gl texture-data))
GlBind
(bind [this gl _render-args]
(let [tex (->texture this gl)
tgt (.getTarget tex)]
(.enable tex gl) ; Enable the type of texturing e.g. GL_TEXTURE_2D or GL_TEXTURE_CUBE_MAP
(.glActiveTexture ^GL2 gl unit) ; Set the active texture unit. Implicit parameter to (.bind ...)
(.bind tex gl) ; Bind our texture to the active texture unit. Used for subsequent render calls. Also implicit parameter to (apply-params! ...)
(apply-params! gl tgt params))) ; Apply filtering settings to the bound texture
(unbind [this gl _render-args]
(let [tex (->texture this gl)
tgt (.getTarget tex)]
(.glActiveTexture ^GL2 gl unit) ; Set the active texture unit. Implicit parameter to (.glBindTexture ...)
(.glBindTexture ^GL2 gl tgt 0) ; Re-bind default "no-texture" to the active texture unit
(.glActiveTexture ^GL2 gl GL/GL_TEXTURE0) ; Set TEXTURE0 as the active texture unit in case anything outside of the bind / unbind cycle forgets to call (.glActiveTexture ...)
(.disable tex gl)))) ; Disable the type of texturing e.g. GL_TEXTURE_2D or GL_TEXTURE_CUBE_MAP
(defn set-params [^TextureLifecycle tlc params]
(update tlc :params merge params))
(def
^{:doc "If you do not supply parameters to `image-texture`, these will be used as defaults."}
default-image-texture-params
{:min-filter gl/linear-mipmap-linear
:mag-filter gl/linear
:wrap-s gl/clamp
:wrap-t gl/clamp})
(defn- data-format->internal-format [data-format]
;; Internal format signifies only color content, not channel order.
(case data-format
:gray GL2/GL_LUMINANCE
:bgr GL2/GL_RGB
:abgr GL2/GL_RGBA
:rgb GL2/GL_RGB
:rgba GL2/GL_RGBA))
(defn- data-format->pixel-format [data-format]
;; Pixel format signifies channel order.
(case data-format
:gray GL2/GL_LUMINANCE
:bgr GL2/GL_BGR
:abgr GL2/GL_RGBA ;; There is no GL_ABGR, so this is swizzled into ABGR by the GL_UNSIGNED_INT_8_8_8_8 type returned by data-format->type.
:rgb GL2/GL_RGB
:rgba GL2/GL_RGBA))
(defn- data-format->type [data-format]
;; Type signifies packing / endian order.
(case data-format
:gray GL2/GL_UNSIGNED_BYTE
:bgr GL2/GL_UNSIGNED_BYTE
:abgr GL2/GL_UNSIGNED_INT_8_8_8_8
:rgb GL2/GL_UNSIGNED_BYTE
:rgba GL2/GL_UNSIGNED_BYTE))
(defn- image-type->data-format [^long image-type]
(condp = image-type
BufferedImage/TYPE_BYTE_GRAY :gray
BufferedImage/TYPE_3BYTE_BGR :bgr
BufferedImage/TYPE_4BYTE_ABGR :abgr
BufferedImage/TYPE_4BYTE_ABGR_PRE :abgr))
(defn- ->texture-data [width height data-format data mipmap]
(let [internal-format (data-format->internal-format data-format)
pixel-format (data-format->pixel-format data-format)
type (data-format->type data-format)
border 0]
(TextureData. (GLProfile/getGL2GL3) internal-format width height border pixel-format type mipmap false false data nil)))
(defn- image->texture-data ^TextureData [img mipmap]
(let [channels (image-util/image-color-components img)
type (case channels
4 BufferedImage/TYPE_4BYTE_ABGR_PRE
3 BufferedImage/TYPE_3BYTE_BGR
1 BufferedImage/TYPE_BYTE_GRAY)
img (image-util/image-convert-type img type)
data-type (image-type->data-format type)
data (ByteBuffer/wrap (.getData ^DataBufferByte (.getDataBuffer (.getRaster img))))]
(->texture-data (.getWidth img) (.getHeight img) data-type data mipmap)))
(defn- flip-y [^BufferedImage img]
;; Flip the image before we create a OGL texture, to mimic how UVs are handled in engine.
;; We do this since all our generated UVs are based on bottom-left being texture coord (0,0).
(let [cm (.getColorModel img)
raster (.copyData img nil)]
(doto (BufferedImage. cm raster (.isAlphaPremultiplied cm) nil)
(ImageUtil/flipImageVertically))))
(defn image-texture
"Create an image texture from a BufferedImage. The returned value
supports GlBind and GlEnable. You can use it in do-gl and with-gl-bindings.
If supplied, the params argument must be a map of parameter name to value. Parameter names
can be OpenGL constants (e.g., GL_TEXTURE_WRAP_S) or their keyword equivalents from
`texture-params` (e.g., :wrap-s).
If you supply parameters, then those parameters are used. If you do not supply parameters,
then defaults in `default-image-texture-params` are used.
If supplied, the unit is the offset of GL_TEXTURE0, i.e. 0 => GL_TEXTURE0. The default is 0."
([request-id img]
(image-texture request-id img default-image-texture-params 0))
([request-id img params]
(image-texture request-id img params 0))
([request-id ^BufferedImage img params unit-index]
(let [texture-data (image->texture-data (flip-y (or img (:contents image-util/placeholder-image))) true)
unit (+ unit-index GL2/GL_TEXTURE0)]
(->TextureLifecycle request-id ::texture unit params texture-data))))
(def format->gl-format
{Graphics$TextureImage$TextureFormat/TEXTURE_FORMAT_LUMINANCE
GL2/GL_LUMINANCE
Graphics$TextureImage$TextureFormat/TEXTURE_FORMAT_RGB
GL2/GL_RGB
Graphics$TextureImage$TextureFormat/TEXTURE_FORMAT_RGBA
GL2/GL_RGBA})
(defn- select-texture-image-image
^Graphics$TextureImage$Image [^Graphics$TextureImage texture-image]
(first (filter #(format->gl-format (.getFormat ^Graphics$TextureImage$Image %))
(.getAlternativesList texture-image))))
(defn- image->mipmap-buffers
^"[Ljava.nio.Buffer;" [^Graphics$TextureImage$Image image]
(assert (= (.getMipMapSizeCount image) (.getMipMapOffsetCount image)))
(let [mipmap-count (.getMipMapSizeCount image)
data (.toByteArray (.getData image))
^"[Ljava.nio.Buffer;" bufs (make-array Buffer mipmap-count)]
(loop [i 0]
(if (< i mipmap-count)
(let [buf (ByteBuffer/wrap data (.getMipMapOffset image i) (.getMipMapSize image i))]
(aset bufs i buf)
(recur (inc i)))
bufs))))
(defn- texture-image->texture-data
^TextureData [^Graphics$TextureImage texture-image]
(let [image (select-texture-image-image texture-image)
gl-profile (GLProfile/getGL2GL3)
gl-format (int (format->gl-format (.getFormat image)))
mipmap-buffers (image->mipmap-buffers image)]
(TextureData. gl-profile
gl-format
(.getWidth image)
(.getHeight image)
0 ; border
gl-format
GL/GL_UNSIGNED_BYTE ; gl type
false ; compressed?
false ; flip vertically?
mipmap-buffers
nil)))
(defn texture-image->gpu-texture
"Create an image texture from a generated `TextureImage`. The returned value
supports GlBind and GlEnable. You can use it in do-gl and with-gl-bindings.
If supplied, the params argument must be a map of parameter name to value.
Parameter names can be OpenGL constants (e.g., GL_TEXTURE_WRAP_S) or their
keyword equivalents from `texture-params` (e.g., :wrap-s).
If you supply parameters, then those parameters are used. If you do not supply
parameters, then defaults in `default-image-texture-params` are used.
If supplied, the unit is the offset of GL_TEXTURE0, i.e. 0 => GL_TEXTURE0. The
default is 0."
([request-id img]
(texture-image->gpu-texture request-id img default-image-texture-params 0))
([request-id img params]
(texture-image->gpu-texture request-id img params 0))
([request-id ^Graphics$TextureImage img params unit-index]
(let [texture-data (texture-image->texture-data img)
unit (+ unit-index GL2/GL_TEXTURE0)]
(->TextureLifecycle request-id ::texture unit params texture-data))))
(defn empty-texture [request-id width height data-format params unit-index]
(let [unit (+ unit-index GL2/GL_TEXTURE0)]
(->TextureLifecycle request-id ::texture unit params (->texture-data width height data-format nil false))))
(def white-pixel (image-texture ::white (-> (image-util/blank-image 1 1) (image-util/flood 1.0 1.0 1.0)) (assoc default-image-texture-params
:min-filter GL2/GL_NEAREST
:mag-filter GL2/GL_NEAREST)))
(defn tex-sub-image [^GL2 gl ^TextureLifecycle texture data x y w h data-format]
(let [tex (->texture texture gl)
data (->texture-data w h data-format data false)]
(.updateSubImage tex gl data 0 x y)))
(def default-cubemap-texture-params
^{:doc "If you do not supply parameters to `cubemap-texture-images->gpu-texture`, these will be used as defaults."}
{:min-filter gl/linear
:mag-filter gl/linear
:wrap-s gl/clamp-to-edge
:wrap-t gl/clamp-to-edge})
(defn cubemap-texture-images->gpu-texture
([request-id texture-images]
(cubemap-texture-images->gpu-texture request-id texture-images default-cubemap-texture-params))
([request-id texture-images params]
(cubemap-texture-images->gpu-texture request-id texture-images params 0))
([request-id texture-images params unit-index]
(let [texture-datas (util/map-vals texture-image->texture-data texture-images)
unit (+ unit-index GL2/GL_TEXTURE0)]
(->TextureLifecycle request-id ::cubemap-texture unit params texture-datas))))
(defn- make-texture [^GL2 gl ^TextureData texture-data]
(Texture. gl texture-data))
(defn- update-texture [^GL2 gl ^Texture texture ^TextureData texture-data]
(.updateImage texture gl texture-data)
texture)
(defn- destroy-textures [^GL2 gl textures _]
(doseq [^Texture texture textures]
(.destroy texture gl)))
(scene-cache/register-object-cache! ::texture make-texture update-texture destroy-textures)
(def ^:private cubemap-targets
{:px GL/GL_TEXTURE_CUBE_MAP_POSITIVE_X
:nx GL/GL_TEXTURE_CUBE_MAP_NEGATIVE_X
:py GL/GL_TEXTURE_CUBE_MAP_POSITIVE_Y
:ny GL/GL_TEXTURE_CUBE_MAP_NEGATIVE_Y
:pz GL/GL_TEXTURE_CUBE_MAP_POSITIVE_Z
:nz GL/GL_TEXTURE_CUBE_MAP_NEGATIVE_Z})
(defn- update-cubemap-texture [^GL2 gl ^Texture texture texture-datas]
(doseq [[target-key target] cubemap-targets]
(.updateImage texture gl ^TextureData (target-key texture-datas) target))
texture)
(defn- make-cubemap-texture [^GL2 gl texture-datas]
(let [^Texture texture (TextureIO/newTexture GL/GL_TEXTURE_CUBE_MAP)]
(update-cubemap-texture gl texture texture-datas)))
(scene-cache/register-object-cache! ::cubemap-texture make-cubemap-texture update-cubemap-texture destroy-textures)
| 2468 | ;; 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.gl.texture
"Functions for creating and using textures"
(:require [editor.image-util :as image-util]
[editor.gl.protocols :refer [GlBind]]
[editor.gl :as gl]
[internal.util :as util]
[editor.scene-cache :as scene-cache]
[dynamo.graph :as g])
(:import [java.awt.image BufferedImage DataBuffer DataBufferByte]
[java.nio Buffer IntBuffer ByteBuffer]
[com.dynamo.graphics.proto Graphics$TextureImage Graphics$TextureImage$Image Graphics$TextureImage$TextureFormat]
[com.jogamp.opengl GL GL2 GL3 GLContext GLProfile]
[com.jogamp.common.nio Buffers]
[com.jogamp.opengl.util.texture Texture TextureIO TextureData]
[com.jogamp.opengl.util.awt ImageUtil]))
(set! *warn-on-reflection* true)
(def
^{:doc "This map translates Clojure keywords into OpenGL constants.
You can use the keywords in texture parameter maps."}
texture-params
{:base-level GL2/GL_TEXTURE_BASE_LEVEL
:border-color GL2/GL_TEXTURE_BORDER_COLOR
:compare-func GL2/GL_TEXTURE_COMPARE_FUNC
:compare-mode GL2/GL_TEXTURE_COMPARE_MODE
:lod-bias GL2/GL_TEXTURE_LOD_BIAS
:min-filter GL/GL_TEXTURE_MIN_FILTER
:mag-filter GL/GL_TEXTURE_MAG_FILTER
:min-lod GL2/GL_TEXTURE_MIN_LOD
:max-lod GL2/GL_TEXTURE_MAX_LOD
:max-level GL2/GL_TEXTURE_MAX_LEVEL
:swizzle-r GL3/GL_TEXTURE_SWIZZLE_R
:swizzle-g GL3/GL_TEXTURE_SWIZZLE_G
:swizzle-b GL3/GL_TEXTURE_SWIZZLE_B
:swizzle-a GL3/GL_TEXTURE_SWIZZLE_A
:wrap-s GL2/GL_TEXTURE_WRAP_S
:wrap-t GL2/GL_TEXTURE_WRAP_T
:wrap-r GL2/GL_TEXTURE_WRAP_R})
(defn- apply-params!
[^GL2 gl ^long texture-target params]
(let [params (if-let [sampler-name (:name params)]
(when-let [program (gl/gl-current-program gl)]
(if (= -1 (.glGetUniformLocation gl program sampler-name))
(:default-tex-params params)
params))
params)]
(doseq [[p v] params]
(if-let [pname (texture-params p)]
(.glTexParameteri gl texture-target pname v)
(cond
(integer? p) (.glTexParameteri gl texture-target p v)
;; Silently ignore extra sampler data
(= :name p) nil
(= :default-tex-params p) nil
:else (println "WARNING: ignoring unknown texture parameter " p))))))
(defprotocol TextureProxy
(->texture ^Texture [this ^GL2 gl]))
(defrecord TextureLifecycle [request-id cache-id unit params texture-data]
TextureProxy
(->texture [this gl]
(scene-cache/request-object! cache-id request-id gl texture-data))
GlBind
(bind [this gl _render-args]
(let [tex (->texture this gl)
tgt (.getTarget tex)]
(.enable tex gl) ; Enable the type of texturing e.g. GL_TEXTURE_2D or GL_TEXTURE_CUBE_MAP
(.glActiveTexture ^GL2 gl unit) ; Set the active texture unit. Implicit parameter to (.bind ...)
(.bind tex gl) ; Bind our texture to the active texture unit. Used for subsequent render calls. Also implicit parameter to (apply-params! ...)
(apply-params! gl tgt params))) ; Apply filtering settings to the bound texture
(unbind [this gl _render-args]
(let [tex (->texture this gl)
tgt (.getTarget tex)]
(.glActiveTexture ^GL2 gl unit) ; Set the active texture unit. Implicit parameter to (.glBindTexture ...)
(.glBindTexture ^GL2 gl tgt 0) ; Re-bind default "no-texture" to the active texture unit
(.glActiveTexture ^GL2 gl GL/GL_TEXTURE0) ; Set TEXTURE0 as the active texture unit in case anything outside of the bind / unbind cycle forgets to call (.glActiveTexture ...)
(.disable tex gl)))) ; Disable the type of texturing e.g. GL_TEXTURE_2D or GL_TEXTURE_CUBE_MAP
(defn set-params [^TextureLifecycle tlc params]
(update tlc :params merge params))
(def
^{:doc "If you do not supply parameters to `image-texture`, these will be used as defaults."}
default-image-texture-params
{:min-filter gl/linear-mipmap-linear
:mag-filter gl/linear
:wrap-s gl/clamp
:wrap-t gl/clamp})
(defn- data-format->internal-format [data-format]
;; Internal format signifies only color content, not channel order.
(case data-format
:gray GL2/GL_LUMINANCE
:bgr GL2/GL_RGB
:abgr GL2/GL_RGBA
:rgb GL2/GL_RGB
:rgba GL2/GL_RGBA))
(defn- data-format->pixel-format [data-format]
;; Pixel format signifies channel order.
(case data-format
:gray GL2/GL_LUMINANCE
:bgr GL2/GL_BGR
:abgr GL2/GL_RGBA ;; There is no GL_ABGR, so this is swizzled into ABGR by the GL_UNSIGNED_INT_8_8_8_8 type returned by data-format->type.
:rgb GL2/GL_RGB
:rgba GL2/GL_RGBA))
(defn- data-format->type [data-format]
;; Type signifies packing / endian order.
(case data-format
:gray GL2/GL_UNSIGNED_BYTE
:bgr GL2/GL_UNSIGNED_BYTE
:abgr GL2/GL_UNSIGNED_INT_8_8_8_8
:rgb GL2/GL_UNSIGNED_BYTE
:rgba GL2/GL_UNSIGNED_BYTE))
(defn- image-type->data-format [^long image-type]
(condp = image-type
BufferedImage/TYPE_BYTE_GRAY :gray
BufferedImage/TYPE_3BYTE_BGR :bgr
BufferedImage/TYPE_4BYTE_ABGR :abgr
BufferedImage/TYPE_4BYTE_ABGR_PRE :abgr))
(defn- ->texture-data [width height data-format data mipmap]
(let [internal-format (data-format->internal-format data-format)
pixel-format (data-format->pixel-format data-format)
type (data-format->type data-format)
border 0]
(TextureData. (GLProfile/getGL2GL3) internal-format width height border pixel-format type mipmap false false data nil)))
(defn- image->texture-data ^TextureData [img mipmap]
(let [channels (image-util/image-color-components img)
type (case channels
4 BufferedImage/TYPE_4BYTE_ABGR_PRE
3 BufferedImage/TYPE_3BYTE_BGR
1 BufferedImage/TYPE_BYTE_GRAY)
img (image-util/image-convert-type img type)
data-type (image-type->data-format type)
data (ByteBuffer/wrap (.getData ^DataBufferByte (.getDataBuffer (.getRaster img))))]
(->texture-data (.getWidth img) (.getHeight img) data-type data mipmap)))
(defn- flip-y [^BufferedImage img]
;; Flip the image before we create a OGL texture, to mimic how UVs are handled in engine.
;; We do this since all our generated UVs are based on bottom-left being texture coord (0,0).
(let [cm (.getColorModel img)
raster (.copyData img nil)]
(doto (BufferedImage. cm raster (.isAlphaPremultiplied cm) nil)
(ImageUtil/flipImageVertically))))
(defn image-texture
"Create an image texture from a BufferedImage. The returned value
supports GlBind and GlEnable. You can use it in do-gl and with-gl-bindings.
If supplied, the params argument must be a map of parameter name to value. Parameter names
can be OpenGL constants (e.g., GL_TEXTURE_WRAP_S) or their keyword equivalents from
`texture-params` (e.g., :wrap-s).
If you supply parameters, then those parameters are used. If you do not supply parameters,
then defaults in `default-image-texture-params` are used.
If supplied, the unit is the offset of GL_TEXTURE0, i.e. 0 => GL_TEXTURE0. The default is 0."
([request-id img]
(image-texture request-id img default-image-texture-params 0))
([request-id img params]
(image-texture request-id img params 0))
([request-id ^BufferedImage img params unit-index]
(let [texture-data (image->texture-data (flip-y (or img (:contents image-util/placeholder-image))) true)
unit (+ unit-index GL2/GL_TEXTURE0)]
(->TextureLifecycle request-id ::texture unit params texture-data))))
(def format->gl-format
{Graphics$TextureImage$TextureFormat/TEXTURE_FORMAT_LUMINANCE
GL2/GL_LUMINANCE
Graphics$TextureImage$TextureFormat/TEXTURE_FORMAT_RGB
GL2/GL_RGB
Graphics$TextureImage$TextureFormat/TEXTURE_FORMAT_RGBA
GL2/GL_RGBA})
(defn- select-texture-image-image
^Graphics$TextureImage$Image [^Graphics$TextureImage texture-image]
(first (filter #(format->gl-format (.getFormat ^Graphics$TextureImage$Image %))
(.getAlternativesList texture-image))))
(defn- image->mipmap-buffers
^"[Ljava.nio.Buffer;" [^Graphics$TextureImage$Image image]
(assert (= (.getMipMapSizeCount image) (.getMipMapOffsetCount image)))
(let [mipmap-count (.getMipMapSizeCount image)
data (.toByteArray (.getData image))
^"[Ljava.nio.Buffer;" bufs (make-array Buffer mipmap-count)]
(loop [i 0]
(if (< i mipmap-count)
(let [buf (ByteBuffer/wrap data (.getMipMapOffset image i) (.getMipMapSize image i))]
(aset bufs i buf)
(recur (inc i)))
bufs))))
(defn- texture-image->texture-data
^TextureData [^Graphics$TextureImage texture-image]
(let [image (select-texture-image-image texture-image)
gl-profile (GLProfile/getGL2GL3)
gl-format (int (format->gl-format (.getFormat image)))
mipmap-buffers (image->mipmap-buffers image)]
(TextureData. gl-profile
gl-format
(.getWidth image)
(.getHeight image)
0 ; border
gl-format
GL/GL_UNSIGNED_BYTE ; gl type
false ; compressed?
false ; flip vertically?
mipmap-buffers
nil)))
(defn texture-image->gpu-texture
"Create an image texture from a generated `TextureImage`. The returned value
supports GlBind and GlEnable. You can use it in do-gl and with-gl-bindings.
If supplied, the params argument must be a map of parameter name to value.
Parameter names can be OpenGL constants (e.g., GL_TEXTURE_WRAP_S) or their
keyword equivalents from `texture-params` (e.g., :wrap-s).
If you supply parameters, then those parameters are used. If you do not supply
parameters, then defaults in `default-image-texture-params` are used.
If supplied, the unit is the offset of GL_TEXTURE0, i.e. 0 => GL_TEXTURE0. The
default is 0."
([request-id img]
(texture-image->gpu-texture request-id img default-image-texture-params 0))
([request-id img params]
(texture-image->gpu-texture request-id img params 0))
([request-id ^Graphics$TextureImage img params unit-index]
(let [texture-data (texture-image->texture-data img)
unit (+ unit-index GL2/GL_TEXTURE0)]
(->TextureLifecycle request-id ::texture unit params texture-data))))
(defn empty-texture [request-id width height data-format params unit-index]
(let [unit (+ unit-index GL2/GL_TEXTURE0)]
(->TextureLifecycle request-id ::texture unit params (->texture-data width height data-format nil false))))
(def white-pixel (image-texture ::white (-> (image-util/blank-image 1 1) (image-util/flood 1.0 1.0 1.0)) (assoc default-image-texture-params
:min-filter GL2/GL_NEAREST
:mag-filter GL2/GL_NEAREST)))
(defn tex-sub-image [^GL2 gl ^TextureLifecycle texture data x y w h data-format]
(let [tex (->texture texture gl)
data (->texture-data w h data-format data false)]
(.updateSubImage tex gl data 0 x y)))
(def default-cubemap-texture-params
^{:doc "If you do not supply parameters to `cubemap-texture-images->gpu-texture`, these will be used as defaults."}
{:min-filter gl/linear
:mag-filter gl/linear
:wrap-s gl/clamp-to-edge
:wrap-t gl/clamp-to-edge})
(defn cubemap-texture-images->gpu-texture
([request-id texture-images]
(cubemap-texture-images->gpu-texture request-id texture-images default-cubemap-texture-params))
([request-id texture-images params]
(cubemap-texture-images->gpu-texture request-id texture-images params 0))
([request-id texture-images params unit-index]
(let [texture-datas (util/map-vals texture-image->texture-data texture-images)
unit (+ unit-index GL2/GL_TEXTURE0)]
(->TextureLifecycle request-id ::cubemap-texture unit params texture-datas))))
(defn- make-texture [^GL2 gl ^TextureData texture-data]
(Texture. gl texture-data))
(defn- update-texture [^GL2 gl ^Texture texture ^TextureData texture-data]
(.updateImage texture gl texture-data)
texture)
(defn- destroy-textures [^GL2 gl textures _]
(doseq [^Texture texture textures]
(.destroy texture gl)))
(scene-cache/register-object-cache! ::texture make-texture update-texture destroy-textures)
(def ^:private cubemap-targets
{:px GL/GL_TEXTURE_CUBE_MAP_POSITIVE_X
:nx GL/GL_TEXTURE_CUBE_MAP_NEGATIVE_X
:py GL/GL_TEXTURE_CUBE_MAP_POSITIVE_Y
:ny GL/GL_TEXTURE_CUBE_MAP_NEGATIVE_Y
:pz GL/GL_TEXTURE_CUBE_MAP_POSITIVE_Z
:nz GL/GL_TEXTURE_CUBE_MAP_NEGATIVE_Z})
(defn- update-cubemap-texture [^GL2 gl ^Texture texture texture-datas]
(doseq [[target-key target] cubemap-targets]
(.updateImage texture gl ^TextureData (target-key texture-datas) target))
texture)
(defn- make-cubemap-texture [^GL2 gl texture-datas]
(let [^Texture texture (TextureIO/newTexture GL/GL_TEXTURE_CUBE_MAP)]
(update-cubemap-texture gl texture texture-datas)))
(scene-cache/register-object-cache! ::cubemap-texture make-cubemap-texture update-cubemap-texture destroy-textures)
| 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.gl.texture
"Functions for creating and using textures"
(:require [editor.image-util :as image-util]
[editor.gl.protocols :refer [GlBind]]
[editor.gl :as gl]
[internal.util :as util]
[editor.scene-cache :as scene-cache]
[dynamo.graph :as g])
(:import [java.awt.image BufferedImage DataBuffer DataBufferByte]
[java.nio Buffer IntBuffer ByteBuffer]
[com.dynamo.graphics.proto Graphics$TextureImage Graphics$TextureImage$Image Graphics$TextureImage$TextureFormat]
[com.jogamp.opengl GL GL2 GL3 GLContext GLProfile]
[com.jogamp.common.nio Buffers]
[com.jogamp.opengl.util.texture Texture TextureIO TextureData]
[com.jogamp.opengl.util.awt ImageUtil]))
(set! *warn-on-reflection* true)
(def
^{:doc "This map translates Clojure keywords into OpenGL constants.
You can use the keywords in texture parameter maps."}
texture-params
{:base-level GL2/GL_TEXTURE_BASE_LEVEL
:border-color GL2/GL_TEXTURE_BORDER_COLOR
:compare-func GL2/GL_TEXTURE_COMPARE_FUNC
:compare-mode GL2/GL_TEXTURE_COMPARE_MODE
:lod-bias GL2/GL_TEXTURE_LOD_BIAS
:min-filter GL/GL_TEXTURE_MIN_FILTER
:mag-filter GL/GL_TEXTURE_MAG_FILTER
:min-lod GL2/GL_TEXTURE_MIN_LOD
:max-lod GL2/GL_TEXTURE_MAX_LOD
:max-level GL2/GL_TEXTURE_MAX_LEVEL
:swizzle-r GL3/GL_TEXTURE_SWIZZLE_R
:swizzle-g GL3/GL_TEXTURE_SWIZZLE_G
:swizzle-b GL3/GL_TEXTURE_SWIZZLE_B
:swizzle-a GL3/GL_TEXTURE_SWIZZLE_A
:wrap-s GL2/GL_TEXTURE_WRAP_S
:wrap-t GL2/GL_TEXTURE_WRAP_T
:wrap-r GL2/GL_TEXTURE_WRAP_R})
(defn- apply-params!
[^GL2 gl ^long texture-target params]
(let [params (if-let [sampler-name (:name params)]
(when-let [program (gl/gl-current-program gl)]
(if (= -1 (.glGetUniformLocation gl program sampler-name))
(:default-tex-params params)
params))
params)]
(doseq [[p v] params]
(if-let [pname (texture-params p)]
(.glTexParameteri gl texture-target pname v)
(cond
(integer? p) (.glTexParameteri gl texture-target p v)
;; Silently ignore extra sampler data
(= :name p) nil
(= :default-tex-params p) nil
:else (println "WARNING: ignoring unknown texture parameter " p))))))
(defprotocol TextureProxy
(->texture ^Texture [this ^GL2 gl]))
(defrecord TextureLifecycle [request-id cache-id unit params texture-data]
TextureProxy
(->texture [this gl]
(scene-cache/request-object! cache-id request-id gl texture-data))
GlBind
(bind [this gl _render-args]
(let [tex (->texture this gl)
tgt (.getTarget tex)]
(.enable tex gl) ; Enable the type of texturing e.g. GL_TEXTURE_2D or GL_TEXTURE_CUBE_MAP
(.glActiveTexture ^GL2 gl unit) ; Set the active texture unit. Implicit parameter to (.bind ...)
(.bind tex gl) ; Bind our texture to the active texture unit. Used for subsequent render calls. Also implicit parameter to (apply-params! ...)
(apply-params! gl tgt params))) ; Apply filtering settings to the bound texture
(unbind [this gl _render-args]
(let [tex (->texture this gl)
tgt (.getTarget tex)]
(.glActiveTexture ^GL2 gl unit) ; Set the active texture unit. Implicit parameter to (.glBindTexture ...)
(.glBindTexture ^GL2 gl tgt 0) ; Re-bind default "no-texture" to the active texture unit
(.glActiveTexture ^GL2 gl GL/GL_TEXTURE0) ; Set TEXTURE0 as the active texture unit in case anything outside of the bind / unbind cycle forgets to call (.glActiveTexture ...)
(.disable tex gl)))) ; Disable the type of texturing e.g. GL_TEXTURE_2D or GL_TEXTURE_CUBE_MAP
(defn set-params [^TextureLifecycle tlc params]
(update tlc :params merge params))
(def
^{:doc "If you do not supply parameters to `image-texture`, these will be used as defaults."}
default-image-texture-params
{:min-filter gl/linear-mipmap-linear
:mag-filter gl/linear
:wrap-s gl/clamp
:wrap-t gl/clamp})
(defn- data-format->internal-format [data-format]
;; Internal format signifies only color content, not channel order.
(case data-format
:gray GL2/GL_LUMINANCE
:bgr GL2/GL_RGB
:abgr GL2/GL_RGBA
:rgb GL2/GL_RGB
:rgba GL2/GL_RGBA))
(defn- data-format->pixel-format [data-format]
;; Pixel format signifies channel order.
(case data-format
:gray GL2/GL_LUMINANCE
:bgr GL2/GL_BGR
:abgr GL2/GL_RGBA ;; There is no GL_ABGR, so this is swizzled into ABGR by the GL_UNSIGNED_INT_8_8_8_8 type returned by data-format->type.
:rgb GL2/GL_RGB
:rgba GL2/GL_RGBA))
(defn- data-format->type [data-format]
;; Type signifies packing / endian order.
(case data-format
:gray GL2/GL_UNSIGNED_BYTE
:bgr GL2/GL_UNSIGNED_BYTE
:abgr GL2/GL_UNSIGNED_INT_8_8_8_8
:rgb GL2/GL_UNSIGNED_BYTE
:rgba GL2/GL_UNSIGNED_BYTE))
(defn- image-type->data-format [^long image-type]
(condp = image-type
BufferedImage/TYPE_BYTE_GRAY :gray
BufferedImage/TYPE_3BYTE_BGR :bgr
BufferedImage/TYPE_4BYTE_ABGR :abgr
BufferedImage/TYPE_4BYTE_ABGR_PRE :abgr))
(defn- ->texture-data [width height data-format data mipmap]
(let [internal-format (data-format->internal-format data-format)
pixel-format (data-format->pixel-format data-format)
type (data-format->type data-format)
border 0]
(TextureData. (GLProfile/getGL2GL3) internal-format width height border pixel-format type mipmap false false data nil)))
(defn- image->texture-data ^TextureData [img mipmap]
(let [channels (image-util/image-color-components img)
type (case channels
4 BufferedImage/TYPE_4BYTE_ABGR_PRE
3 BufferedImage/TYPE_3BYTE_BGR
1 BufferedImage/TYPE_BYTE_GRAY)
img (image-util/image-convert-type img type)
data-type (image-type->data-format type)
data (ByteBuffer/wrap (.getData ^DataBufferByte (.getDataBuffer (.getRaster img))))]
(->texture-data (.getWidth img) (.getHeight img) data-type data mipmap)))
(defn- flip-y [^BufferedImage img]
;; Flip the image before we create a OGL texture, to mimic how UVs are handled in engine.
;; We do this since all our generated UVs are based on bottom-left being texture coord (0,0).
(let [cm (.getColorModel img)
raster (.copyData img nil)]
(doto (BufferedImage. cm raster (.isAlphaPremultiplied cm) nil)
(ImageUtil/flipImageVertically))))
(defn image-texture
"Create an image texture from a BufferedImage. The returned value
supports GlBind and GlEnable. You can use it in do-gl and with-gl-bindings.
If supplied, the params argument must be a map of parameter name to value. Parameter names
can be OpenGL constants (e.g., GL_TEXTURE_WRAP_S) or their keyword equivalents from
`texture-params` (e.g., :wrap-s).
If you supply parameters, then those parameters are used. If you do not supply parameters,
then defaults in `default-image-texture-params` are used.
If supplied, the unit is the offset of GL_TEXTURE0, i.e. 0 => GL_TEXTURE0. The default is 0."
([request-id img]
(image-texture request-id img default-image-texture-params 0))
([request-id img params]
(image-texture request-id img params 0))
([request-id ^BufferedImage img params unit-index]
(let [texture-data (image->texture-data (flip-y (or img (:contents image-util/placeholder-image))) true)
unit (+ unit-index GL2/GL_TEXTURE0)]
(->TextureLifecycle request-id ::texture unit params texture-data))))
(def format->gl-format
{Graphics$TextureImage$TextureFormat/TEXTURE_FORMAT_LUMINANCE
GL2/GL_LUMINANCE
Graphics$TextureImage$TextureFormat/TEXTURE_FORMAT_RGB
GL2/GL_RGB
Graphics$TextureImage$TextureFormat/TEXTURE_FORMAT_RGBA
GL2/GL_RGBA})
(defn- select-texture-image-image
^Graphics$TextureImage$Image [^Graphics$TextureImage texture-image]
(first (filter #(format->gl-format (.getFormat ^Graphics$TextureImage$Image %))
(.getAlternativesList texture-image))))
(defn- image->mipmap-buffers
^"[Ljava.nio.Buffer;" [^Graphics$TextureImage$Image image]
(assert (= (.getMipMapSizeCount image) (.getMipMapOffsetCount image)))
(let [mipmap-count (.getMipMapSizeCount image)
data (.toByteArray (.getData image))
^"[Ljava.nio.Buffer;" bufs (make-array Buffer mipmap-count)]
(loop [i 0]
(if (< i mipmap-count)
(let [buf (ByteBuffer/wrap data (.getMipMapOffset image i) (.getMipMapSize image i))]
(aset bufs i buf)
(recur (inc i)))
bufs))))
(defn- texture-image->texture-data
^TextureData [^Graphics$TextureImage texture-image]
(let [image (select-texture-image-image texture-image)
gl-profile (GLProfile/getGL2GL3)
gl-format (int (format->gl-format (.getFormat image)))
mipmap-buffers (image->mipmap-buffers image)]
(TextureData. gl-profile
gl-format
(.getWidth image)
(.getHeight image)
0 ; border
gl-format
GL/GL_UNSIGNED_BYTE ; gl type
false ; compressed?
false ; flip vertically?
mipmap-buffers
nil)))
(defn texture-image->gpu-texture
"Create an image texture from a generated `TextureImage`. The returned value
supports GlBind and GlEnable. You can use it in do-gl and with-gl-bindings.
If supplied, the params argument must be a map of parameter name to value.
Parameter names can be OpenGL constants (e.g., GL_TEXTURE_WRAP_S) or their
keyword equivalents from `texture-params` (e.g., :wrap-s).
If you supply parameters, then those parameters are used. If you do not supply
parameters, then defaults in `default-image-texture-params` are used.
If supplied, the unit is the offset of GL_TEXTURE0, i.e. 0 => GL_TEXTURE0. The
default is 0."
([request-id img]
(texture-image->gpu-texture request-id img default-image-texture-params 0))
([request-id img params]
(texture-image->gpu-texture request-id img params 0))
([request-id ^Graphics$TextureImage img params unit-index]
(let [texture-data (texture-image->texture-data img)
unit (+ unit-index GL2/GL_TEXTURE0)]
(->TextureLifecycle request-id ::texture unit params texture-data))))
(defn empty-texture [request-id width height data-format params unit-index]
(let [unit (+ unit-index GL2/GL_TEXTURE0)]
(->TextureLifecycle request-id ::texture unit params (->texture-data width height data-format nil false))))
(def white-pixel (image-texture ::white (-> (image-util/blank-image 1 1) (image-util/flood 1.0 1.0 1.0)) (assoc default-image-texture-params
:min-filter GL2/GL_NEAREST
:mag-filter GL2/GL_NEAREST)))
(defn tex-sub-image [^GL2 gl ^TextureLifecycle texture data x y w h data-format]
(let [tex (->texture texture gl)
data (->texture-data w h data-format data false)]
(.updateSubImage tex gl data 0 x y)))
(def default-cubemap-texture-params
^{:doc "If you do not supply parameters to `cubemap-texture-images->gpu-texture`, these will be used as defaults."}
{:min-filter gl/linear
:mag-filter gl/linear
:wrap-s gl/clamp-to-edge
:wrap-t gl/clamp-to-edge})
(defn cubemap-texture-images->gpu-texture
([request-id texture-images]
(cubemap-texture-images->gpu-texture request-id texture-images default-cubemap-texture-params))
([request-id texture-images params]
(cubemap-texture-images->gpu-texture request-id texture-images params 0))
([request-id texture-images params unit-index]
(let [texture-datas (util/map-vals texture-image->texture-data texture-images)
unit (+ unit-index GL2/GL_TEXTURE0)]
(->TextureLifecycle request-id ::cubemap-texture unit params texture-datas))))
(defn- make-texture [^GL2 gl ^TextureData texture-data]
(Texture. gl texture-data))
(defn- update-texture [^GL2 gl ^Texture texture ^TextureData texture-data]
(.updateImage texture gl texture-data)
texture)
(defn- destroy-textures [^GL2 gl textures _]
(doseq [^Texture texture textures]
(.destroy texture gl)))
(scene-cache/register-object-cache! ::texture make-texture update-texture destroy-textures)
(def ^:private cubemap-targets
{:px GL/GL_TEXTURE_CUBE_MAP_POSITIVE_X
:nx GL/GL_TEXTURE_CUBE_MAP_NEGATIVE_X
:py GL/GL_TEXTURE_CUBE_MAP_POSITIVE_Y
:ny GL/GL_TEXTURE_CUBE_MAP_NEGATIVE_Y
:pz GL/GL_TEXTURE_CUBE_MAP_POSITIVE_Z
:nz GL/GL_TEXTURE_CUBE_MAP_NEGATIVE_Z})
(defn- update-cubemap-texture [^GL2 gl ^Texture texture texture-datas]
(doseq [[target-key target] cubemap-targets]
(.updateImage texture gl ^TextureData (target-key texture-datas) target))
texture)
(defn- make-cubemap-texture [^GL2 gl texture-datas]
(let [^Texture texture (TextureIO/newTexture GL/GL_TEXTURE_CUBE_MAP)]
(update-cubemap-texture gl texture texture-datas)))
(scene-cache/register-object-cache! ::cubemap-texture make-cubemap-texture update-cubemap-texture destroy-textures)
|
[
{
"context": ";; Original author Hirokuni Kim\n;; Modifications by Kevin Kredit\n;; Licensed unde",
"end": 31,
"score": 0.9997779726982117,
"start": 19,
"tag": "NAME",
"value": "Hirokuni Kim"
},
{
"context": "; Original author Hirokuni Kim\n;; Modifications by Kevin Kredit\n;; Licensed under https://www.apache.org/licenses",
"end": 64,
"score": 0.9998801350593567,
"start": 52,
"tag": "NAME",
"value": "Kevin Kredit"
}
] | clojure/p01-symbol/src/p01_symbol/core.clj | kkredit/pl-study | 0 | ;; Original author Hirokuni Kim
;; Modifications by Kevin Kredit
;; Licensed under https://www.apache.org/licenses/LICENSE-2.0
;; See https://kimh.github.io/clojure-by-example/#symbol
(ns p01-symbol.core)
(defn -main
"Main"
[]
(do
(println (type 'a))
(println (type 'b))
(println (type 'my-cool-function))
(println (type 'nyncat))
(println (def a "aaaaa"))
(println a)))
; (println b))) -- Exception!
| 83164 | ;; Original author <NAME>
;; Modifications by <NAME>
;; Licensed under https://www.apache.org/licenses/LICENSE-2.0
;; See https://kimh.github.io/clojure-by-example/#symbol
(ns p01-symbol.core)
(defn -main
"Main"
[]
(do
(println (type 'a))
(println (type 'b))
(println (type 'my-cool-function))
(println (type 'nyncat))
(println (def a "aaaaa"))
(println a)))
; (println b))) -- Exception!
| true | ;; Original author PI:NAME:<NAME>END_PI
;; Modifications by PI:NAME:<NAME>END_PI
;; Licensed under https://www.apache.org/licenses/LICENSE-2.0
;; See https://kimh.github.io/clojure-by-example/#symbol
(ns p01-symbol.core)
(defn -main
"Main"
[]
(do
(println (type 'a))
(println (type 'b))
(println (type 'my-cool-function))
(println (type 'nyncat))
(println (def a "aaaaa"))
(println a)))
; (println b))) -- Exception!
|
[
{
"context": "(dosync\n (alter names conj name)))\n\n(add-name \"zack\")\n;;[\"zack\"]\n\n(add-name \"shelley\")\n;;[\"zack\" \"",
"end": 969,
"score": 0.5901634693145752,
"start": 968,
"tag": "NAME",
"value": "z"
},
{
"context": "dosync\n (alter names conj name)))\n\n(add-name \"zack\")\n;;[\"zack\"]\n\n(add-name \"shelley\")\n;;[\"zack\" \"she",
"end": 972,
"score": 0.6630889177322388,
"start": 969,
"tag": "USERNAME",
"value": "ack"
},
{
"context": " (alter names conj name)))\n\n(add-name \"zack\")\n;;[\"zack\"]\n\n(add-name \"shelley\")\n;;[\"zack\" \"shelley\"]\n\n@na",
"end": 983,
"score": 0.8610309958457947,
"start": 979,
"tag": "USERNAME",
"value": "zack"
},
{
"context": "name)))\n\n(add-name \"zack\")\n;;[\"zack\"]\n\n(add-name \"shelley\")\n;;[\"zack\" \"shelley\"]\n\n@names\n;;[\"zack\" \"shelley",
"end": 1005,
"score": 0.9733665585517883,
"start": 998,
"tag": "USERNAME",
"value": "shelley"
},
{
"context": "name \"zack\")\n;;[\"zack\"]\n\n(add-name \"shelley\")\n;;[\"zack\" \"shelley\"]\n\n@names\n;;[\"zack\" \"shelley\"]",
"end": 1016,
"score": 0.779845118522644,
"start": 1012,
"tag": "USERNAME",
"value": "zack"
},
{
"context": "ack\")\n;;[\"zack\"]\n\n(add-name \"shelley\")\n;;[\"zack\" \"shelley\"]\n\n@names\n;;[\"zack\" \"shelley\"]",
"end": 1020,
"score": 0.7865697741508484,
"start": 1019,
"tag": "NAME",
"value": "s"
},
{
"context": "ck\")\n;;[\"zack\"]\n\n(add-name \"shelley\")\n;;[\"zack\" \"shelley\"]\n\n@names\n;;[\"zack\" \"shelley\"]",
"end": 1026,
"score": 0.5798653364181519,
"start": 1020,
"tag": "USERNAME",
"value": "helley"
},
{
"context": "-name \"shelley\")\n;;[\"zack\" \"shelley\"]\n\n@names\n;;[\"zack\" \"shelley\"]",
"end": 1045,
"score": 0.9081569910049438,
"start": 1041,
"tag": "USERNAME",
"value": "zack"
},
{
"context": "shelley\")\n;;[\"zack\" \"shelley\"]\n\n@names\n;;[\"zack\" \"shelley\"]",
"end": 1055,
"score": 0.8703873753547668,
"start": 1048,
"tag": "USERNAME",
"value": "shelley"
}
] | src/clojure_tutorial/api/core/alter.clj | edgar615/clojure-tutorial | 1 | (ns clojure-tutorial.api.core.alter)
;alter
;(alter ref fun & args)
;Must be called in a transaction. Sets the in-transaction-value of ref to:
;(apply fun in-transaction-value-of-ref args)
;and returns the in-transaction-value of ref.
;alter函数
;参数:要被修改的ref、一个函数f以及这个函数所需要的其他参数。当alter函数返回的时候,ref在这个“事务内的值”会被改变成函数f的返回结果
;所有对于ref的状态进行修改的函数是在一个独立的时间线上执行的,这个时间线开始的时间是这个ref第一次被修改的时候。
;接下来对于ref的所有修改、访问都是在这个独立的时间线上进行的,而这个时间线只在这个事务内存在,而且只能在这个事务中被访问。
;当控制流要离开这个事务的时候,STM会尝试提交这个事务,在最乐观的情况下,提交会成功,ref的状态被修改成这个事务内ref的新值
;而这个新值会对所有的线程/事务可见——不只是在某个事务内可见了。但是如果外部的时间线已经对ref的状态进行了修改,并且已经提交了,那么事务提交就会跟它发生冲突,
;这会导致整个事务重试,利用ref的新值来重新执行一遍。
;在这个过程中,任何只读线程(比如解引用)不会被阻塞住或者需要等待。而且那些对ref的值进行修改的线程直到成功提交之后,它们对于ref的修改才会对其他线程可见,
;也就不会影响其他线程对于ref的只读操作了。
;alter的独特语义是,当一个事务要提交的时候,ref的全局值必须跟这个事务内第一次调用alter时候的值一样,否则整个事务会被重启,从头再执行一遍。
;Clojure的STM可以这样理解:它是一个乐观地尝试对并发的修改操作进行重新排序,以使得它们可以顺序地执行的一个过程。
(def names (ref []))
(defn add-name
[name]
(dosync
(alter names conj name)))
(add-name "zack")
;;["zack"]
(add-name "shelley")
;;["zack" "shelley"]
@names
;;["zack" "shelley"] | 3819 | (ns clojure-tutorial.api.core.alter)
;alter
;(alter ref fun & args)
;Must be called in a transaction. Sets the in-transaction-value of ref to:
;(apply fun in-transaction-value-of-ref args)
;and returns the in-transaction-value of ref.
;alter函数
;参数:要被修改的ref、一个函数f以及这个函数所需要的其他参数。当alter函数返回的时候,ref在这个“事务内的值”会被改变成函数f的返回结果
;所有对于ref的状态进行修改的函数是在一个独立的时间线上执行的,这个时间线开始的时间是这个ref第一次被修改的时候。
;接下来对于ref的所有修改、访问都是在这个独立的时间线上进行的,而这个时间线只在这个事务内存在,而且只能在这个事务中被访问。
;当控制流要离开这个事务的时候,STM会尝试提交这个事务,在最乐观的情况下,提交会成功,ref的状态被修改成这个事务内ref的新值
;而这个新值会对所有的线程/事务可见——不只是在某个事务内可见了。但是如果外部的时间线已经对ref的状态进行了修改,并且已经提交了,那么事务提交就会跟它发生冲突,
;这会导致整个事务重试,利用ref的新值来重新执行一遍。
;在这个过程中,任何只读线程(比如解引用)不会被阻塞住或者需要等待。而且那些对ref的值进行修改的线程直到成功提交之后,它们对于ref的修改才会对其他线程可见,
;也就不会影响其他线程对于ref的只读操作了。
;alter的独特语义是,当一个事务要提交的时候,ref的全局值必须跟这个事务内第一次调用alter时候的值一样,否则整个事务会被重启,从头再执行一遍。
;Clojure的STM可以这样理解:它是一个乐观地尝试对并发的修改操作进行重新排序,以使得它们可以顺序地执行的一个过程。
(def names (ref []))
(defn add-name
[name]
(dosync
(alter names conj name)))
(add-name "<NAME>ack")
;;["zack"]
(add-name "shelley")
;;["zack" "<NAME>helley"]
@names
;;["zack" "shelley"] | true | (ns clojure-tutorial.api.core.alter)
;alter
;(alter ref fun & args)
;Must be called in a transaction. Sets the in-transaction-value of ref to:
;(apply fun in-transaction-value-of-ref args)
;and returns the in-transaction-value of ref.
;alter函数
;参数:要被修改的ref、一个函数f以及这个函数所需要的其他参数。当alter函数返回的时候,ref在这个“事务内的值”会被改变成函数f的返回结果
;所有对于ref的状态进行修改的函数是在一个独立的时间线上执行的,这个时间线开始的时间是这个ref第一次被修改的时候。
;接下来对于ref的所有修改、访问都是在这个独立的时间线上进行的,而这个时间线只在这个事务内存在,而且只能在这个事务中被访问。
;当控制流要离开这个事务的时候,STM会尝试提交这个事务,在最乐观的情况下,提交会成功,ref的状态被修改成这个事务内ref的新值
;而这个新值会对所有的线程/事务可见——不只是在某个事务内可见了。但是如果外部的时间线已经对ref的状态进行了修改,并且已经提交了,那么事务提交就会跟它发生冲突,
;这会导致整个事务重试,利用ref的新值来重新执行一遍。
;在这个过程中,任何只读线程(比如解引用)不会被阻塞住或者需要等待。而且那些对ref的值进行修改的线程直到成功提交之后,它们对于ref的修改才会对其他线程可见,
;也就不会影响其他线程对于ref的只读操作了。
;alter的独特语义是,当一个事务要提交的时候,ref的全局值必须跟这个事务内第一次调用alter时候的值一样,否则整个事务会被重启,从头再执行一遍。
;Clojure的STM可以这样理解:它是一个乐观地尝试对并发的修改操作进行重新排序,以使得它们可以顺序地执行的一个过程。
(def names (ref []))
(defn add-name
[name]
(dosync
(alter names conj name)))
(add-name "PI:NAME:<NAME>END_PIack")
;;["zack"]
(add-name "shelley")
;;["zack" "PI:NAME:<NAME>END_PIhelley"]
@names
;;["zack" "shelley"] |
[
{
"context": "metric-defaults\n {:name \"Costa Rica\"\n :creator_id (mt/user->id :r",
"end": 6583,
"score": 0.9998136758804321,
"start": 6573,
"tag": "NAME",
"value": "Costa Rica"
},
{
"context": " id\n :name \"Costa Rica\"\n :description nil\n ",
"end": 7089,
"score": 0.9998399615287781,
"start": 7079,
"tag": "NAME",
"value": "Costa Rica"
},
{
"context": "tric [{:keys [id]} {:creator_id (mt/user->id :crowberto)\n :t",
"end": 10714,
"score": 0.9395391941070557,
"start": 10705,
"tag": "USERNAME",
"value": "crowberto"
},
{
"context": "eberry\"\n :creator_id (mt/user->id :crowberto)\n :creator (user-details (mt/fe",
"end": 10997,
"score": 0.9193544387817383,
"start": 10988,
"tag": "USERNAME",
"value": "crowberto"
},
{
"context": "s [id]} {:creator_id (mt/user->id :crowberto)\n :t",
"end": 11969,
"score": 0.9493269324302673,
"start": 11960,
"tag": "USERNAME",
"value": "crowberto"
},
{
"context": " :user_id (mt/user->id :crowberto)\n :o",
"end": 13395,
"score": 0.9962124228477478,
"start": 13386,
"tag": "USERNAME",
"value": "crowberto"
},
{
"context": " :user (-> (user-details (mt/fetch-user :crowberto))\n (dissoc :",
"end": 13812,
"score": 0.5686664581298828,
"start": 13809,
"tag": "USERNAME",
"value": "row"
},
{
"context": "id]} {:creator_id (mt/user->id :crowberto)\n :",
"end": 15613,
"score": 0.9952783584594727,
"start": 15604,
"tag": "USERNAME",
"value": "crowberto"
},
{
"context": " {:creator_id (mt/user->id :crowberto)\n ",
"end": 16387,
"score": 0.989992082118988,
"start": 16378,
"tag": "USERNAME",
"value": "crowberto"
},
{
"context": "ject {:creator_id (mt/user->id :crowberto)\n ",
"end": 17630,
"score": 0.9976199269294739,
"start": 17621,
"tag": "USERNAME",
"value": "crowberto"
},
{
"context": " :user_id (mt/user->id :crowberto)\n :",
"end": 18888,
"score": 0.9994731545448303,
"start": 18879,
"tag": "USERNAME",
"value": "crowberto"
},
{
"context": ":object {:creator_id (mt/user->id :crowberto)\n ",
"end": 18996,
"score": 0.9993245005607605,
"start": 18987,
"tag": "USERNAME",
"value": "crowberto"
},
{
"context": "ser (dissoc (user-details (mt/fetch-user :crowberto)) :email :date_joined :last_login :is_superuser :",
"end": 20191,
"score": 0.999290943145752,
"start": 20182,
"tag": "USERNAME",
"value": "crowberto"
},
{
"context": "ser (dissoc (user-details (mt/fetch-user :crowberto)) :email :date_joined :last_login :is_superuser :",
"end": 21017,
"score": 0.9993748664855957,
"start": 21008,
"tag": "USERNAME",
"value": "crowberto"
},
{
"context": "ser (dissoc (user-details (mt/fetch-user :crowberto)) :email :date_joined :last_login :is_superuser :",
"end": 21578,
"score": 0.9936570525169373,
"start": 21569,
"tag": "USERNAME",
"value": "crowberto"
}
] | c#-metabase/test/metabase/api/metric_test.clj | hanakhry/Crime_Admin | 0 | (ns metabase.api.metric-test
"Tests for /api/metric endpoints."
(:require [clojure.test :refer :all]
[metabase.http-client :as http]
[metabase.models.database :refer [Database]]
[metabase.models.metric :as metric :refer [Metric]]
[metabase.models.permissions :as perms]
[metabase.models.permissions-group :as group]
[metabase.models.revision :refer [Revision]]
[metabase.models.table :refer [Table]]
[metabase.server.middleware.util :as middleware.u]
[metabase.test :as mt]
[metabase.test.data :as data]
[metabase.util :as u]
[toucan.db :as db]
[toucan.hydrate :refer [hydrate]]))
;; ## Helper Fns
(def ^:private metric-defaults
{:description nil
:show_in_getting_started false
:caveats nil
:points_of_interest nil
:how_is_this_calculated nil
:created_at true
:updated_at true
:archived false
:definition nil})
(defn- user-details [user]
(select-keys
user
[:id :email :date_joined :first_name :last_name :last_login :is_superuser :is_qbnewb :common_name :locale]))
(defn- metric-response [{:keys [created_at updated_at], :as metric}]
(-> (into {} metric)
(dissoc :id :table_id)
(update :creator #(into {} %))
(assoc :created_at (some? created_at)
:updated_at (some? updated_at))))
(deftest auth-tests
(testing "AUTHENTICATION"
;; We assume that all endpoints for a given context are enforced by the same middleware, so we don't run the same
;; authentication test on every single individual endpoint
(is (= (get middleware.u/response-unauthentic :body)
(http/client :get 401 "metric")))
(is (= (get middleware.u/response-unauthentic :body)
(http/client :put 401 "metric/13")))))
(deftest create-test
(testing "POST /api/metric"
(testing "test security. Requires superuser perms"
(is (= "You don't have permissions to do that."
(mt/user-http-request
:rasta :post 403 "metric" {:name "abc"
:table_id 123
:definition {}}))))
(testing "test validations"
(is (= {:errors {:name "value must be a non-blank string."}}
(mt/user-http-request
:crowberto :post 400 "metric" {})))
(is (= {:errors {:table_id "value must be an integer greater than zero."}}
(mt/user-http-request
:crowberto :post 400 "metric" {:name "abc"})))
(is (= {:errors {:table_id "value must be an integer greater than zero."}}
(mt/user-http-request
:crowberto :post 400 "metric" {:name "abc"
:table_id "foobar"})))
(is (= {:errors {:definition "value must be a map."}}
(mt/user-http-request
:crowberto :post 400 "metric" {:name "abc"
:table_id 123})))
(is (= {:errors {:definition "value must be a map."}}
(mt/user-http-request
:crowberto :post 400 "metric" {:name "abc"
:table_id 123
:definition "foobar"}))))
(mt/with-temp* [Database [{database-id :id}]
Table [{:keys [id]} {:db_id database-id}]]
(is (= (merge metric-defaults
{:name "A Metric"
:description "I did it!"
:creator_id (mt/user->id :crowberto)
:creator (user-details (mt/fetch-user :crowberto))
:definition {:database 21
:query {:filter ["abc"]}}})
(metric-response (mt/user-http-request
:crowberto :post 200 "metric" {:name "A Metric"
:description "I did it!"
:show_in_getting_started false
:caveats nil
:points_of_interest nil
:how_is_this_calculated nil
:table_id id
:definition {:database 21
:query {:filter ["abc"]}}})))))))
(deftest update-test
(testing "PUT /api/metric"
(testing "test security. Requires superuser perms"
(mt/with-temp Metric [metric]
(is (= "You don't have permissions to do that."
(mt/user-http-request
:rasta :put 403 (str "metric/" (u/the-id metric))
{:name "abc"
:definition {}
:revision_message "something different"})))))
(testing "test validations"
(is (= {:errors {:revision_message "value must be a non-blank string."}}
(mt/user-http-request
:crowberto :put 400 "metric/1" {})))
(is (= {:errors {:name "value may be nil, or if non-nil, value must be a non-blank string."}}
(mt/user-http-request
:crowberto :put 400 "metric/1" {:revision_message "Wow", :name ""})))
(is (= {:errors {:revision_message "value must be a non-blank string."}}
(mt/user-http-request
:crowberto :put 400 "metric/1" {:name "abc"
:revision_message ""})))
(is (= {:errors {:definition "value may be nil, or if non-nil, value must be a map."}}
(mt/user-http-request
:crowberto :put 400 "metric/1" {:name "abc"
:revision_message "123"
:definition "foobar"}))))
(mt/with-temp* [Database [{database-id :id}]
Table [{table-id :id} {:db_id database-id}]
Metric [{:keys [id]} {:table_id table-id}]]
(is (= (merge metric-defaults
{:name "Costa Rica"
:creator_id (mt/user->id :rasta)
:creator (user-details (mt/fetch-user :rasta))
:definition {:database 2
:query {:filter ["not" ["=" "field" "the toucans you're looking for"]]}}})
(metric-response
(mt/user-http-request
:crowberto :put 200 (format "metric/%d" id)
{:id id
:name "Costa Rica"
:description nil
:show_in_getting_started false
:caveats nil
:points_of_interest nil
:how_is_this_calculated nil
:table_id 456
:revision_message "I got me some revisions"
:definition {:database 2
:query {:filter ["not" ["=" "field" "the toucans you're looking for"]]}}})))))))
(deftest archive-test
(testing "Can we archive a Metric with the PUT endpoint?"
(mt/with-temp Metric [{:keys [id]}]
(is (some? (mt/user-http-request
:crowberto :put 200 (str "metric/" id)
{:archived true, :revision_message "Archive the Metric"})))
(is (= true
(db/select-one-field :archived Metric :id id))))))
(deftest unarchive-test
(testing "Can we unarchive a Metric with the PUT endpoint?"
(mt/with-temp Metric [{:keys [id]} {:archived true}]
(is (some? (mt/user-http-request
:crowberto :put 200 (str "metric/" id)
{:archived false, :revision_message "Unarchive the Metric"})))
(is (= false (db/select-one-field :archived Metric :id id))))))
(deftest delete-test
(testing "DELETE /api/metric/:id"
(testing "test security. Requires superuser perms"
(mt/with-temp Metric [{:keys [id]}]
(is (= "You don't have permissions to do that."
(mt/user-http-request
:rasta :delete 403 (str "metric/" id) :revision_message "yeeeehaw!")))))
(testing "test validations"
(is (= {:errors {:revision_message "value must be a non-blank string."}}
(mt/user-http-request
:crowberto :delete 400 "metric/1" {:name "abc"})))
(is (= {:errors {:revision_message "value must be a non-blank string."}}
(mt/user-http-request
:crowberto :delete 400 "metric/1" :revision_message ""))))))
(deftest fetch-archived-test
(testing "should still be able to fetch the archived Metric"
(mt/with-temp* [Database [{database-id :id}]
Table [{table-id :id} {:db_id database-id}]
Metric [{:keys [id]} {:table_id table-id}]]
(mt/user-http-request
:crowberto :delete 204 (format "metric/%d" id) :revision_message "carryon")
(is (= (merge
metric-defaults
{:name "Toucans in the rainforest"
:description "Lookin' for a blueberry"
:creator_id (mt/user->id :rasta)
:creator (user-details (mt/fetch-user :rasta))
:archived true})
(-> (metric-response
(mt/user-http-request
:crowberto :get 200 (format "metric/%d" id)))
(dissoc :query_description)))))))
(deftest fetch-metric-test
(testing "GET /api/metric/:id"
(testing "test security. Requires perms for the Table it references"
(mt/with-temp* [Database [db]
Table [table {:db_id (u/the-id db)}]
Metric [metric {:table_id (u/the-id table)}]]
(perms/revoke-permissions! (group/all-users) db)
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :get 403 (str "metric/" (u/the-id metric)))))))
(mt/with-temp* [Database [{database-id :id}]
Table [{table-id :id} {:db_id database-id}]
Metric [{:keys [id]} {:creator_id (mt/user->id :crowberto)
:table_id table-id}]]
(is (= (merge
metric-defaults
{:name "Toucans in the rainforest"
:description "Lookin' for a blueberry"
:creator_id (mt/user->id :crowberto)
:creator (user-details (mt/fetch-user :crowberto))})
(-> (metric-response (mt/user-http-request :rasta :get 200 (format "metric/%d" id)))
(dissoc :query_description)))))))
(deftest metric-revisions-test
(testing "GET /api/metric/:id/revisions"
(testing "test security. Requires read perms for Table it references"
(mt/with-temp* [Database [db]
Table [table {:db_id (u/the-id db)}]
Metric [metric {:table_id (u/the-id table)}]]
(perms/revoke-permissions! (group/all-users) db)
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :get 403 (format "metric/%d/revisions" (u/the-id metric)))))))
(mt/with-temp* [Database [{database-id :id}]
Table [{table-id :id} {:db_id database-id}]
Metric [{:keys [id]} {:creator_id (mt/user->id :crowberto)
:table_id table-id
:name "One Metric to rule them all, one metric to define them"
:description "One metric to bring them all, and in the DataModel bind them"
:show_in_getting_started false
:caveats nil
:points_of_interest nil
:how_is_this_calculated nil
:definition {:database 123
:query {:filter [:= [:field 10 nil] 20]}}}]
Revision [_ {:model "Metric"
:model_id id
:object {:name "b"
:definition {:filter [:and [:> 1 25]]}}
:is_creation true}]
Revision [_ {:model "Metric"
:model_id id
:user_id (mt/user->id :crowberto)
:object {:name "c"
:definition {:filter [:and [:> 1 25]]}}
:message "updated"}]]
(is (= [{:is_reversion false
:is_creation false
:message "updated"
:user (-> (user-details (mt/fetch-user :crowberto))
(dissoc :email :date_joined :last_login :is_superuser :is_qbnewb))
:diff {:name {:before "b" :after "c"}}
:description "renamed this Metric from \"b\" to \"c\"."}
{:is_reversion false
:is_creation true
:message nil
:user (-> (user-details (mt/fetch-user :rasta))
(dissoc :email :date_joined :last_login :is_superuser :is_qbnewb))
:diff {:name {:after "b"}
:definition {:after {:filter [">" ["field" 1 nil] 25]}}}
:description nil}]
(for [revision (mt/user-http-request :rasta :get 200 (format "metric/%d/revisions" id))]
(dissoc revision :timestamp :id)))))))
(deftest revert-metric-test
(testing "POST /api/metric/:id/revert"
(testing "test security. Requires superuser perms"
(mt/with-temp Metric [{:keys [id]}]
(is (= "You don't have permissions to do that."
(mt/user-http-request
:rasta :post 403 (format "metric/%d/revert" id)
{:revision_id 56})))))
(is (= {:errors {:revision_id "value must be an integer greater than zero."}}
(mt/user-http-request :crowberto :post 400 "metric/1/revert" {})))
(is (= {:errors {:revision_id "value must be an integer greater than zero."}}
(mt/user-http-request :crowberto :post 400 "metric/1/revert" {:revision_id "foobar"})))))
(deftest metric-revisions-test-2
(mt/with-temp* [Database [{database-id :id}]
Table [{table-id :id} {:db_id database-id}]
Metric [{:keys [id]} {:creator_id (mt/user->id :crowberto)
:table_id table-id
:name "One Metric to rule them all, one metric to define them"
:description "One metric to bring them all, and in the DataModel bind them"
:show_in_getting_started false
:caveats nil
:points_of_interest nil
:how_is_this_calculated nil
:definition {:creator_id (mt/user->id :crowberto)
:table_id table-id
:name "Reverted Metric Name"
:description nil
:show_in_getting_started false
:caveats nil
:points_of_interest nil
:how_is_this_calculated nil
:definition {:database 123
:query {:filter [:= [:field 10 nil] 20]}}}}]
Revision [{revision-id :id} {:model "Metric"
:model_id id
:object {:creator_id (mt/user->id :crowberto)
:table_id table-id
:name "One Metric to rule them all, one metric to define them"
:description "One metric to bring them all, and in the DataModel bind them"
:show_in_getting_started false
:caveats nil
:points_of_interest nil
:how_is_this_calculated nil
:definition {:database 123
:query {:filter [:= [:field 10 nil] 20]}}}
:is_creation true}]
Revision [_ {:model "Metric"
:model_id id
:user_id (mt/user->id :crowberto)
:object {:creator_id (mt/user->id :crowberto)
:table_id table-id
:name "Changed Metric Name"
:description "One metric to bring them all, and in the DataModel bind them"
:show_in_getting_started false
:caveats nil
:points_of_interest nil
:how_is_this_calculated nil
:definition {:database 123
:query {:filter [:= [:field 10 nil] 20]}}}
:message "updated"}]]
(testing "API response"
(is (= {:is_reversion true
:is_creation false
:message nil
:user (dissoc (user-details (mt/fetch-user :crowberto)) :email :date_joined :last_login :is_superuser :is_qbnewb)
:diff {:name {:before "Changed Metric Name"
:after "One Metric to rule them all, one metric to define them"}}
:description "renamed this Metric from \"Changed Metric Name\" to \"One Metric to rule them all, one metric to define them\"."}
(dissoc (mt/user-http-request
:crowberto :post 200 (format "metric/%d/revert" id) {:revision_id revision-id}) :id :timestamp))))
(testing "full list of final revisions, first one should be same as the revision returned by the endpoint"
(is (= [{:is_reversion true
:is_creation false
:message nil
:user (dissoc (user-details (mt/fetch-user :crowberto)) :email :date_joined :last_login :is_superuser :is_qbnewb)
:diff {:name {:before "Changed Metric Name"
:after "One Metric to rule them all, one metric to define them"}}
:description "renamed this Metric from \"Changed Metric Name\" to \"One Metric to rule them all, one metric to define them\"."}
{:is_reversion false
:is_creation false
:message "updated"
:user (dissoc (user-details (mt/fetch-user :crowberto)) :email :date_joined :last_login :is_superuser :is_qbnewb)
:diff {:name {:after "Changed Metric Name"
:before "One Metric to rule them all, one metric to define them"}}
:description "renamed this Metric from \"One Metric to rule them all, one metric to define them\" to \"Changed Metric Name\"."}
{:is_reversion false
:is_creation true
:message nil
:user (dissoc (user-details (mt/fetch-user :rasta)) :email :date_joined :last_login :is_superuser :is_qbnewb)
:diff {:name {:after "One Metric to rule them all, one metric to define them"}
:description {:after "One metric to bring them all, and in the DataModel bind them"}
:definition {:after {:database 123
:query {:filter ["=" ["field" 10 nil] 20]}}}}
:description nil}]
(for [revision (mt/user-http-request
:crowberto :get 200 (format "metric/%d/revisions" id))]
(dissoc revision :timestamp :id)))))))
(deftest list-metrics-test
(testing "GET /api/metric/"
(mt/with-temp* [Metric [metric-1 {:name "Metric A"}]
Metric [metric-2 {:name "Metric B"}]
;; inactive metrics shouldn't show up
Metric [_ {:archived true}]]
(is (= (mt/derecordize (hydrate [(assoc metric-1 :database_id (data/id))
(assoc metric-2 :database_id (data/id))]
:creator))
(map #(dissoc % :query_description) (mt/user-http-request
:rasta :get 200 "metric/"))))))
(is (= []
(mt/user-http-request :rasta :get 200 "metric/"))))
(deftest metric-related-entities-test
(testing "Test related/recommended entities"
(mt/with-temp Metric [{metric-id :id}]
(is (= #{:table :metrics :segments}
(-> (mt/user-http-request :crowberto :get 200 (format "metric/%s/related" metric-id)) keys set))))))
| 91452 | (ns metabase.api.metric-test
"Tests for /api/metric endpoints."
(:require [clojure.test :refer :all]
[metabase.http-client :as http]
[metabase.models.database :refer [Database]]
[metabase.models.metric :as metric :refer [Metric]]
[metabase.models.permissions :as perms]
[metabase.models.permissions-group :as group]
[metabase.models.revision :refer [Revision]]
[metabase.models.table :refer [Table]]
[metabase.server.middleware.util :as middleware.u]
[metabase.test :as mt]
[metabase.test.data :as data]
[metabase.util :as u]
[toucan.db :as db]
[toucan.hydrate :refer [hydrate]]))
;; ## Helper Fns
(def ^:private metric-defaults
{:description nil
:show_in_getting_started false
:caveats nil
:points_of_interest nil
:how_is_this_calculated nil
:created_at true
:updated_at true
:archived false
:definition nil})
(defn- user-details [user]
(select-keys
user
[:id :email :date_joined :first_name :last_name :last_login :is_superuser :is_qbnewb :common_name :locale]))
(defn- metric-response [{:keys [created_at updated_at], :as metric}]
(-> (into {} metric)
(dissoc :id :table_id)
(update :creator #(into {} %))
(assoc :created_at (some? created_at)
:updated_at (some? updated_at))))
(deftest auth-tests
(testing "AUTHENTICATION"
;; We assume that all endpoints for a given context are enforced by the same middleware, so we don't run the same
;; authentication test on every single individual endpoint
(is (= (get middleware.u/response-unauthentic :body)
(http/client :get 401 "metric")))
(is (= (get middleware.u/response-unauthentic :body)
(http/client :put 401 "metric/13")))))
(deftest create-test
(testing "POST /api/metric"
(testing "test security. Requires superuser perms"
(is (= "You don't have permissions to do that."
(mt/user-http-request
:rasta :post 403 "metric" {:name "abc"
:table_id 123
:definition {}}))))
(testing "test validations"
(is (= {:errors {:name "value must be a non-blank string."}}
(mt/user-http-request
:crowberto :post 400 "metric" {})))
(is (= {:errors {:table_id "value must be an integer greater than zero."}}
(mt/user-http-request
:crowberto :post 400 "metric" {:name "abc"})))
(is (= {:errors {:table_id "value must be an integer greater than zero."}}
(mt/user-http-request
:crowberto :post 400 "metric" {:name "abc"
:table_id "foobar"})))
(is (= {:errors {:definition "value must be a map."}}
(mt/user-http-request
:crowberto :post 400 "metric" {:name "abc"
:table_id 123})))
(is (= {:errors {:definition "value must be a map."}}
(mt/user-http-request
:crowberto :post 400 "metric" {:name "abc"
:table_id 123
:definition "foobar"}))))
(mt/with-temp* [Database [{database-id :id}]
Table [{:keys [id]} {:db_id database-id}]]
(is (= (merge metric-defaults
{:name "A Metric"
:description "I did it!"
:creator_id (mt/user->id :crowberto)
:creator (user-details (mt/fetch-user :crowberto))
:definition {:database 21
:query {:filter ["abc"]}}})
(metric-response (mt/user-http-request
:crowberto :post 200 "metric" {:name "A Metric"
:description "I did it!"
:show_in_getting_started false
:caveats nil
:points_of_interest nil
:how_is_this_calculated nil
:table_id id
:definition {:database 21
:query {:filter ["abc"]}}})))))))
(deftest update-test
(testing "PUT /api/metric"
(testing "test security. Requires superuser perms"
(mt/with-temp Metric [metric]
(is (= "You don't have permissions to do that."
(mt/user-http-request
:rasta :put 403 (str "metric/" (u/the-id metric))
{:name "abc"
:definition {}
:revision_message "something different"})))))
(testing "test validations"
(is (= {:errors {:revision_message "value must be a non-blank string."}}
(mt/user-http-request
:crowberto :put 400 "metric/1" {})))
(is (= {:errors {:name "value may be nil, or if non-nil, value must be a non-blank string."}}
(mt/user-http-request
:crowberto :put 400 "metric/1" {:revision_message "Wow", :name ""})))
(is (= {:errors {:revision_message "value must be a non-blank string."}}
(mt/user-http-request
:crowberto :put 400 "metric/1" {:name "abc"
:revision_message ""})))
(is (= {:errors {:definition "value may be nil, or if non-nil, value must be a map."}}
(mt/user-http-request
:crowberto :put 400 "metric/1" {:name "abc"
:revision_message "123"
:definition "foobar"}))))
(mt/with-temp* [Database [{database-id :id}]
Table [{table-id :id} {:db_id database-id}]
Metric [{:keys [id]} {:table_id table-id}]]
(is (= (merge metric-defaults
{:name "<NAME>"
:creator_id (mt/user->id :rasta)
:creator (user-details (mt/fetch-user :rasta))
:definition {:database 2
:query {:filter ["not" ["=" "field" "the toucans you're looking for"]]}}})
(metric-response
(mt/user-http-request
:crowberto :put 200 (format "metric/%d" id)
{:id id
:name "<NAME>"
:description nil
:show_in_getting_started false
:caveats nil
:points_of_interest nil
:how_is_this_calculated nil
:table_id 456
:revision_message "I got me some revisions"
:definition {:database 2
:query {:filter ["not" ["=" "field" "the toucans you're looking for"]]}}})))))))
(deftest archive-test
(testing "Can we archive a Metric with the PUT endpoint?"
(mt/with-temp Metric [{:keys [id]}]
(is (some? (mt/user-http-request
:crowberto :put 200 (str "metric/" id)
{:archived true, :revision_message "Archive the Metric"})))
(is (= true
(db/select-one-field :archived Metric :id id))))))
(deftest unarchive-test
(testing "Can we unarchive a Metric with the PUT endpoint?"
(mt/with-temp Metric [{:keys [id]} {:archived true}]
(is (some? (mt/user-http-request
:crowberto :put 200 (str "metric/" id)
{:archived false, :revision_message "Unarchive the Metric"})))
(is (= false (db/select-one-field :archived Metric :id id))))))
(deftest delete-test
(testing "DELETE /api/metric/:id"
(testing "test security. Requires superuser perms"
(mt/with-temp Metric [{:keys [id]}]
(is (= "You don't have permissions to do that."
(mt/user-http-request
:rasta :delete 403 (str "metric/" id) :revision_message "yeeeehaw!")))))
(testing "test validations"
(is (= {:errors {:revision_message "value must be a non-blank string."}}
(mt/user-http-request
:crowberto :delete 400 "metric/1" {:name "abc"})))
(is (= {:errors {:revision_message "value must be a non-blank string."}}
(mt/user-http-request
:crowberto :delete 400 "metric/1" :revision_message ""))))))
(deftest fetch-archived-test
(testing "should still be able to fetch the archived Metric"
(mt/with-temp* [Database [{database-id :id}]
Table [{table-id :id} {:db_id database-id}]
Metric [{:keys [id]} {:table_id table-id}]]
(mt/user-http-request
:crowberto :delete 204 (format "metric/%d" id) :revision_message "carryon")
(is (= (merge
metric-defaults
{:name "Toucans in the rainforest"
:description "Lookin' for a blueberry"
:creator_id (mt/user->id :rasta)
:creator (user-details (mt/fetch-user :rasta))
:archived true})
(-> (metric-response
(mt/user-http-request
:crowberto :get 200 (format "metric/%d" id)))
(dissoc :query_description)))))))
(deftest fetch-metric-test
(testing "GET /api/metric/:id"
(testing "test security. Requires perms for the Table it references"
(mt/with-temp* [Database [db]
Table [table {:db_id (u/the-id db)}]
Metric [metric {:table_id (u/the-id table)}]]
(perms/revoke-permissions! (group/all-users) db)
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :get 403 (str "metric/" (u/the-id metric)))))))
(mt/with-temp* [Database [{database-id :id}]
Table [{table-id :id} {:db_id database-id}]
Metric [{:keys [id]} {:creator_id (mt/user->id :crowberto)
:table_id table-id}]]
(is (= (merge
metric-defaults
{:name "Toucans in the rainforest"
:description "Lookin' for a blueberry"
:creator_id (mt/user->id :crowberto)
:creator (user-details (mt/fetch-user :crowberto))})
(-> (metric-response (mt/user-http-request :rasta :get 200 (format "metric/%d" id)))
(dissoc :query_description)))))))
(deftest metric-revisions-test
(testing "GET /api/metric/:id/revisions"
(testing "test security. Requires read perms for Table it references"
(mt/with-temp* [Database [db]
Table [table {:db_id (u/the-id db)}]
Metric [metric {:table_id (u/the-id table)}]]
(perms/revoke-permissions! (group/all-users) db)
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :get 403 (format "metric/%d/revisions" (u/the-id metric)))))))
(mt/with-temp* [Database [{database-id :id}]
Table [{table-id :id} {:db_id database-id}]
Metric [{:keys [id]} {:creator_id (mt/user->id :crowberto)
:table_id table-id
:name "One Metric to rule them all, one metric to define them"
:description "One metric to bring them all, and in the DataModel bind them"
:show_in_getting_started false
:caveats nil
:points_of_interest nil
:how_is_this_calculated nil
:definition {:database 123
:query {:filter [:= [:field 10 nil] 20]}}}]
Revision [_ {:model "Metric"
:model_id id
:object {:name "b"
:definition {:filter [:and [:> 1 25]]}}
:is_creation true}]
Revision [_ {:model "Metric"
:model_id id
:user_id (mt/user->id :crowberto)
:object {:name "c"
:definition {:filter [:and [:> 1 25]]}}
:message "updated"}]]
(is (= [{:is_reversion false
:is_creation false
:message "updated"
:user (-> (user-details (mt/fetch-user :crowberto))
(dissoc :email :date_joined :last_login :is_superuser :is_qbnewb))
:diff {:name {:before "b" :after "c"}}
:description "renamed this Metric from \"b\" to \"c\"."}
{:is_reversion false
:is_creation true
:message nil
:user (-> (user-details (mt/fetch-user :rasta))
(dissoc :email :date_joined :last_login :is_superuser :is_qbnewb))
:diff {:name {:after "b"}
:definition {:after {:filter [">" ["field" 1 nil] 25]}}}
:description nil}]
(for [revision (mt/user-http-request :rasta :get 200 (format "metric/%d/revisions" id))]
(dissoc revision :timestamp :id)))))))
(deftest revert-metric-test
(testing "POST /api/metric/:id/revert"
(testing "test security. Requires superuser perms"
(mt/with-temp Metric [{:keys [id]}]
(is (= "You don't have permissions to do that."
(mt/user-http-request
:rasta :post 403 (format "metric/%d/revert" id)
{:revision_id 56})))))
(is (= {:errors {:revision_id "value must be an integer greater than zero."}}
(mt/user-http-request :crowberto :post 400 "metric/1/revert" {})))
(is (= {:errors {:revision_id "value must be an integer greater than zero."}}
(mt/user-http-request :crowberto :post 400 "metric/1/revert" {:revision_id "foobar"})))))
(deftest metric-revisions-test-2
(mt/with-temp* [Database [{database-id :id}]
Table [{table-id :id} {:db_id database-id}]
Metric [{:keys [id]} {:creator_id (mt/user->id :crowberto)
:table_id table-id
:name "One Metric to rule them all, one metric to define them"
:description "One metric to bring them all, and in the DataModel bind them"
:show_in_getting_started false
:caveats nil
:points_of_interest nil
:how_is_this_calculated nil
:definition {:creator_id (mt/user->id :crowberto)
:table_id table-id
:name "Reverted Metric Name"
:description nil
:show_in_getting_started false
:caveats nil
:points_of_interest nil
:how_is_this_calculated nil
:definition {:database 123
:query {:filter [:= [:field 10 nil] 20]}}}}]
Revision [{revision-id :id} {:model "Metric"
:model_id id
:object {:creator_id (mt/user->id :crowberto)
:table_id table-id
:name "One Metric to rule them all, one metric to define them"
:description "One metric to bring them all, and in the DataModel bind them"
:show_in_getting_started false
:caveats nil
:points_of_interest nil
:how_is_this_calculated nil
:definition {:database 123
:query {:filter [:= [:field 10 nil] 20]}}}
:is_creation true}]
Revision [_ {:model "Metric"
:model_id id
:user_id (mt/user->id :crowberto)
:object {:creator_id (mt/user->id :crowberto)
:table_id table-id
:name "Changed Metric Name"
:description "One metric to bring them all, and in the DataModel bind them"
:show_in_getting_started false
:caveats nil
:points_of_interest nil
:how_is_this_calculated nil
:definition {:database 123
:query {:filter [:= [:field 10 nil] 20]}}}
:message "updated"}]]
(testing "API response"
(is (= {:is_reversion true
:is_creation false
:message nil
:user (dissoc (user-details (mt/fetch-user :crowberto)) :email :date_joined :last_login :is_superuser :is_qbnewb)
:diff {:name {:before "Changed Metric Name"
:after "One Metric to rule them all, one metric to define them"}}
:description "renamed this Metric from \"Changed Metric Name\" to \"One Metric to rule them all, one metric to define them\"."}
(dissoc (mt/user-http-request
:crowberto :post 200 (format "metric/%d/revert" id) {:revision_id revision-id}) :id :timestamp))))
(testing "full list of final revisions, first one should be same as the revision returned by the endpoint"
(is (= [{:is_reversion true
:is_creation false
:message nil
:user (dissoc (user-details (mt/fetch-user :crowberto)) :email :date_joined :last_login :is_superuser :is_qbnewb)
:diff {:name {:before "Changed Metric Name"
:after "One Metric to rule them all, one metric to define them"}}
:description "renamed this Metric from \"Changed Metric Name\" to \"One Metric to rule them all, one metric to define them\"."}
{:is_reversion false
:is_creation false
:message "updated"
:user (dissoc (user-details (mt/fetch-user :crowberto)) :email :date_joined :last_login :is_superuser :is_qbnewb)
:diff {:name {:after "Changed Metric Name"
:before "One Metric to rule them all, one metric to define them"}}
:description "renamed this Metric from \"One Metric to rule them all, one metric to define them\" to \"Changed Metric Name\"."}
{:is_reversion false
:is_creation true
:message nil
:user (dissoc (user-details (mt/fetch-user :rasta)) :email :date_joined :last_login :is_superuser :is_qbnewb)
:diff {:name {:after "One Metric to rule them all, one metric to define them"}
:description {:after "One metric to bring them all, and in the DataModel bind them"}
:definition {:after {:database 123
:query {:filter ["=" ["field" 10 nil] 20]}}}}
:description nil}]
(for [revision (mt/user-http-request
:crowberto :get 200 (format "metric/%d/revisions" id))]
(dissoc revision :timestamp :id)))))))
(deftest list-metrics-test
(testing "GET /api/metric/"
(mt/with-temp* [Metric [metric-1 {:name "Metric A"}]
Metric [metric-2 {:name "Metric B"}]
;; inactive metrics shouldn't show up
Metric [_ {:archived true}]]
(is (= (mt/derecordize (hydrate [(assoc metric-1 :database_id (data/id))
(assoc metric-2 :database_id (data/id))]
:creator))
(map #(dissoc % :query_description) (mt/user-http-request
:rasta :get 200 "metric/"))))))
(is (= []
(mt/user-http-request :rasta :get 200 "metric/"))))
(deftest metric-related-entities-test
(testing "Test related/recommended entities"
(mt/with-temp Metric [{metric-id :id}]
(is (= #{:table :metrics :segments}
(-> (mt/user-http-request :crowberto :get 200 (format "metric/%s/related" metric-id)) keys set))))))
| true | (ns metabase.api.metric-test
"Tests for /api/metric endpoints."
(:require [clojure.test :refer :all]
[metabase.http-client :as http]
[metabase.models.database :refer [Database]]
[metabase.models.metric :as metric :refer [Metric]]
[metabase.models.permissions :as perms]
[metabase.models.permissions-group :as group]
[metabase.models.revision :refer [Revision]]
[metabase.models.table :refer [Table]]
[metabase.server.middleware.util :as middleware.u]
[metabase.test :as mt]
[metabase.test.data :as data]
[metabase.util :as u]
[toucan.db :as db]
[toucan.hydrate :refer [hydrate]]))
;; ## Helper Fns
(def ^:private metric-defaults
{:description nil
:show_in_getting_started false
:caveats nil
:points_of_interest nil
:how_is_this_calculated nil
:created_at true
:updated_at true
:archived false
:definition nil})
(defn- user-details [user]
(select-keys
user
[:id :email :date_joined :first_name :last_name :last_login :is_superuser :is_qbnewb :common_name :locale]))
(defn- metric-response [{:keys [created_at updated_at], :as metric}]
(-> (into {} metric)
(dissoc :id :table_id)
(update :creator #(into {} %))
(assoc :created_at (some? created_at)
:updated_at (some? updated_at))))
(deftest auth-tests
(testing "AUTHENTICATION"
;; We assume that all endpoints for a given context are enforced by the same middleware, so we don't run the same
;; authentication test on every single individual endpoint
(is (= (get middleware.u/response-unauthentic :body)
(http/client :get 401 "metric")))
(is (= (get middleware.u/response-unauthentic :body)
(http/client :put 401 "metric/13")))))
(deftest create-test
(testing "POST /api/metric"
(testing "test security. Requires superuser perms"
(is (= "You don't have permissions to do that."
(mt/user-http-request
:rasta :post 403 "metric" {:name "abc"
:table_id 123
:definition {}}))))
(testing "test validations"
(is (= {:errors {:name "value must be a non-blank string."}}
(mt/user-http-request
:crowberto :post 400 "metric" {})))
(is (= {:errors {:table_id "value must be an integer greater than zero."}}
(mt/user-http-request
:crowberto :post 400 "metric" {:name "abc"})))
(is (= {:errors {:table_id "value must be an integer greater than zero."}}
(mt/user-http-request
:crowberto :post 400 "metric" {:name "abc"
:table_id "foobar"})))
(is (= {:errors {:definition "value must be a map."}}
(mt/user-http-request
:crowberto :post 400 "metric" {:name "abc"
:table_id 123})))
(is (= {:errors {:definition "value must be a map."}}
(mt/user-http-request
:crowberto :post 400 "metric" {:name "abc"
:table_id 123
:definition "foobar"}))))
(mt/with-temp* [Database [{database-id :id}]
Table [{:keys [id]} {:db_id database-id}]]
(is (= (merge metric-defaults
{:name "A Metric"
:description "I did it!"
:creator_id (mt/user->id :crowberto)
:creator (user-details (mt/fetch-user :crowberto))
:definition {:database 21
:query {:filter ["abc"]}}})
(metric-response (mt/user-http-request
:crowberto :post 200 "metric" {:name "A Metric"
:description "I did it!"
:show_in_getting_started false
:caveats nil
:points_of_interest nil
:how_is_this_calculated nil
:table_id id
:definition {:database 21
:query {:filter ["abc"]}}})))))))
(deftest update-test
(testing "PUT /api/metric"
(testing "test security. Requires superuser perms"
(mt/with-temp Metric [metric]
(is (= "You don't have permissions to do that."
(mt/user-http-request
:rasta :put 403 (str "metric/" (u/the-id metric))
{:name "abc"
:definition {}
:revision_message "something different"})))))
(testing "test validations"
(is (= {:errors {:revision_message "value must be a non-blank string."}}
(mt/user-http-request
:crowberto :put 400 "metric/1" {})))
(is (= {:errors {:name "value may be nil, or if non-nil, value must be a non-blank string."}}
(mt/user-http-request
:crowberto :put 400 "metric/1" {:revision_message "Wow", :name ""})))
(is (= {:errors {:revision_message "value must be a non-blank string."}}
(mt/user-http-request
:crowberto :put 400 "metric/1" {:name "abc"
:revision_message ""})))
(is (= {:errors {:definition "value may be nil, or if non-nil, value must be a map."}}
(mt/user-http-request
:crowberto :put 400 "metric/1" {:name "abc"
:revision_message "123"
:definition "foobar"}))))
(mt/with-temp* [Database [{database-id :id}]
Table [{table-id :id} {:db_id database-id}]
Metric [{:keys [id]} {:table_id table-id}]]
(is (= (merge metric-defaults
{:name "PI:NAME:<NAME>END_PI"
:creator_id (mt/user->id :rasta)
:creator (user-details (mt/fetch-user :rasta))
:definition {:database 2
:query {:filter ["not" ["=" "field" "the toucans you're looking for"]]}}})
(metric-response
(mt/user-http-request
:crowberto :put 200 (format "metric/%d" id)
{:id id
:name "PI:NAME:<NAME>END_PI"
:description nil
:show_in_getting_started false
:caveats nil
:points_of_interest nil
:how_is_this_calculated nil
:table_id 456
:revision_message "I got me some revisions"
:definition {:database 2
:query {:filter ["not" ["=" "field" "the toucans you're looking for"]]}}})))))))
(deftest archive-test
(testing "Can we archive a Metric with the PUT endpoint?"
(mt/with-temp Metric [{:keys [id]}]
(is (some? (mt/user-http-request
:crowberto :put 200 (str "metric/" id)
{:archived true, :revision_message "Archive the Metric"})))
(is (= true
(db/select-one-field :archived Metric :id id))))))
(deftest unarchive-test
(testing "Can we unarchive a Metric with the PUT endpoint?"
(mt/with-temp Metric [{:keys [id]} {:archived true}]
(is (some? (mt/user-http-request
:crowberto :put 200 (str "metric/" id)
{:archived false, :revision_message "Unarchive the Metric"})))
(is (= false (db/select-one-field :archived Metric :id id))))))
(deftest delete-test
(testing "DELETE /api/metric/:id"
(testing "test security. Requires superuser perms"
(mt/with-temp Metric [{:keys [id]}]
(is (= "You don't have permissions to do that."
(mt/user-http-request
:rasta :delete 403 (str "metric/" id) :revision_message "yeeeehaw!")))))
(testing "test validations"
(is (= {:errors {:revision_message "value must be a non-blank string."}}
(mt/user-http-request
:crowberto :delete 400 "metric/1" {:name "abc"})))
(is (= {:errors {:revision_message "value must be a non-blank string."}}
(mt/user-http-request
:crowberto :delete 400 "metric/1" :revision_message ""))))))
(deftest fetch-archived-test
(testing "should still be able to fetch the archived Metric"
(mt/with-temp* [Database [{database-id :id}]
Table [{table-id :id} {:db_id database-id}]
Metric [{:keys [id]} {:table_id table-id}]]
(mt/user-http-request
:crowberto :delete 204 (format "metric/%d" id) :revision_message "carryon")
(is (= (merge
metric-defaults
{:name "Toucans in the rainforest"
:description "Lookin' for a blueberry"
:creator_id (mt/user->id :rasta)
:creator (user-details (mt/fetch-user :rasta))
:archived true})
(-> (metric-response
(mt/user-http-request
:crowberto :get 200 (format "metric/%d" id)))
(dissoc :query_description)))))))
(deftest fetch-metric-test
(testing "GET /api/metric/:id"
(testing "test security. Requires perms for the Table it references"
(mt/with-temp* [Database [db]
Table [table {:db_id (u/the-id db)}]
Metric [metric {:table_id (u/the-id table)}]]
(perms/revoke-permissions! (group/all-users) db)
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :get 403 (str "metric/" (u/the-id metric)))))))
(mt/with-temp* [Database [{database-id :id}]
Table [{table-id :id} {:db_id database-id}]
Metric [{:keys [id]} {:creator_id (mt/user->id :crowberto)
:table_id table-id}]]
(is (= (merge
metric-defaults
{:name "Toucans in the rainforest"
:description "Lookin' for a blueberry"
:creator_id (mt/user->id :crowberto)
:creator (user-details (mt/fetch-user :crowberto))})
(-> (metric-response (mt/user-http-request :rasta :get 200 (format "metric/%d" id)))
(dissoc :query_description)))))))
(deftest metric-revisions-test
(testing "GET /api/metric/:id/revisions"
(testing "test security. Requires read perms for Table it references"
(mt/with-temp* [Database [db]
Table [table {:db_id (u/the-id db)}]
Metric [metric {:table_id (u/the-id table)}]]
(perms/revoke-permissions! (group/all-users) db)
(is (= "You don't have permissions to do that."
(mt/user-http-request :rasta :get 403 (format "metric/%d/revisions" (u/the-id metric)))))))
(mt/with-temp* [Database [{database-id :id}]
Table [{table-id :id} {:db_id database-id}]
Metric [{:keys [id]} {:creator_id (mt/user->id :crowberto)
:table_id table-id
:name "One Metric to rule them all, one metric to define them"
:description "One metric to bring them all, and in the DataModel bind them"
:show_in_getting_started false
:caveats nil
:points_of_interest nil
:how_is_this_calculated nil
:definition {:database 123
:query {:filter [:= [:field 10 nil] 20]}}}]
Revision [_ {:model "Metric"
:model_id id
:object {:name "b"
:definition {:filter [:and [:> 1 25]]}}
:is_creation true}]
Revision [_ {:model "Metric"
:model_id id
:user_id (mt/user->id :crowberto)
:object {:name "c"
:definition {:filter [:and [:> 1 25]]}}
:message "updated"}]]
(is (= [{:is_reversion false
:is_creation false
:message "updated"
:user (-> (user-details (mt/fetch-user :crowberto))
(dissoc :email :date_joined :last_login :is_superuser :is_qbnewb))
:diff {:name {:before "b" :after "c"}}
:description "renamed this Metric from \"b\" to \"c\"."}
{:is_reversion false
:is_creation true
:message nil
:user (-> (user-details (mt/fetch-user :rasta))
(dissoc :email :date_joined :last_login :is_superuser :is_qbnewb))
:diff {:name {:after "b"}
:definition {:after {:filter [">" ["field" 1 nil] 25]}}}
:description nil}]
(for [revision (mt/user-http-request :rasta :get 200 (format "metric/%d/revisions" id))]
(dissoc revision :timestamp :id)))))))
(deftest revert-metric-test
(testing "POST /api/metric/:id/revert"
(testing "test security. Requires superuser perms"
(mt/with-temp Metric [{:keys [id]}]
(is (= "You don't have permissions to do that."
(mt/user-http-request
:rasta :post 403 (format "metric/%d/revert" id)
{:revision_id 56})))))
(is (= {:errors {:revision_id "value must be an integer greater than zero."}}
(mt/user-http-request :crowberto :post 400 "metric/1/revert" {})))
(is (= {:errors {:revision_id "value must be an integer greater than zero."}}
(mt/user-http-request :crowberto :post 400 "metric/1/revert" {:revision_id "foobar"})))))
(deftest metric-revisions-test-2
(mt/with-temp* [Database [{database-id :id}]
Table [{table-id :id} {:db_id database-id}]
Metric [{:keys [id]} {:creator_id (mt/user->id :crowberto)
:table_id table-id
:name "One Metric to rule them all, one metric to define them"
:description "One metric to bring them all, and in the DataModel bind them"
:show_in_getting_started false
:caveats nil
:points_of_interest nil
:how_is_this_calculated nil
:definition {:creator_id (mt/user->id :crowberto)
:table_id table-id
:name "Reverted Metric Name"
:description nil
:show_in_getting_started false
:caveats nil
:points_of_interest nil
:how_is_this_calculated nil
:definition {:database 123
:query {:filter [:= [:field 10 nil] 20]}}}}]
Revision [{revision-id :id} {:model "Metric"
:model_id id
:object {:creator_id (mt/user->id :crowberto)
:table_id table-id
:name "One Metric to rule them all, one metric to define them"
:description "One metric to bring them all, and in the DataModel bind them"
:show_in_getting_started false
:caveats nil
:points_of_interest nil
:how_is_this_calculated nil
:definition {:database 123
:query {:filter [:= [:field 10 nil] 20]}}}
:is_creation true}]
Revision [_ {:model "Metric"
:model_id id
:user_id (mt/user->id :crowberto)
:object {:creator_id (mt/user->id :crowberto)
:table_id table-id
:name "Changed Metric Name"
:description "One metric to bring them all, and in the DataModel bind them"
:show_in_getting_started false
:caveats nil
:points_of_interest nil
:how_is_this_calculated nil
:definition {:database 123
:query {:filter [:= [:field 10 nil] 20]}}}
:message "updated"}]]
(testing "API response"
(is (= {:is_reversion true
:is_creation false
:message nil
:user (dissoc (user-details (mt/fetch-user :crowberto)) :email :date_joined :last_login :is_superuser :is_qbnewb)
:diff {:name {:before "Changed Metric Name"
:after "One Metric to rule them all, one metric to define them"}}
:description "renamed this Metric from \"Changed Metric Name\" to \"One Metric to rule them all, one metric to define them\"."}
(dissoc (mt/user-http-request
:crowberto :post 200 (format "metric/%d/revert" id) {:revision_id revision-id}) :id :timestamp))))
(testing "full list of final revisions, first one should be same as the revision returned by the endpoint"
(is (= [{:is_reversion true
:is_creation false
:message nil
:user (dissoc (user-details (mt/fetch-user :crowberto)) :email :date_joined :last_login :is_superuser :is_qbnewb)
:diff {:name {:before "Changed Metric Name"
:after "One Metric to rule them all, one metric to define them"}}
:description "renamed this Metric from \"Changed Metric Name\" to \"One Metric to rule them all, one metric to define them\"."}
{:is_reversion false
:is_creation false
:message "updated"
:user (dissoc (user-details (mt/fetch-user :crowberto)) :email :date_joined :last_login :is_superuser :is_qbnewb)
:diff {:name {:after "Changed Metric Name"
:before "One Metric to rule them all, one metric to define them"}}
:description "renamed this Metric from \"One Metric to rule them all, one metric to define them\" to \"Changed Metric Name\"."}
{:is_reversion false
:is_creation true
:message nil
:user (dissoc (user-details (mt/fetch-user :rasta)) :email :date_joined :last_login :is_superuser :is_qbnewb)
:diff {:name {:after "One Metric to rule them all, one metric to define them"}
:description {:after "One metric to bring them all, and in the DataModel bind them"}
:definition {:after {:database 123
:query {:filter ["=" ["field" 10 nil] 20]}}}}
:description nil}]
(for [revision (mt/user-http-request
:crowberto :get 200 (format "metric/%d/revisions" id))]
(dissoc revision :timestamp :id)))))))
(deftest list-metrics-test
(testing "GET /api/metric/"
(mt/with-temp* [Metric [metric-1 {:name "Metric A"}]
Metric [metric-2 {:name "Metric B"}]
;; inactive metrics shouldn't show up
Metric [_ {:archived true}]]
(is (= (mt/derecordize (hydrate [(assoc metric-1 :database_id (data/id))
(assoc metric-2 :database_id (data/id))]
:creator))
(map #(dissoc % :query_description) (mt/user-http-request
:rasta :get 200 "metric/"))))))
(is (= []
(mt/user-http-request :rasta :get 200 "metric/"))))
(deftest metric-related-entities-test
(testing "Test related/recommended entities"
(mt/with-temp Metric [{metric-id :id}]
(is (= #{:table :metrics :segments}
(-> (mt/user-http-request :crowberto :get 200 (format "metric/%s/related" metric-id)) keys set))))))
|
[
{
"context": "org/a-package/tarball.tgz\")\n(def test-map {:name \"Victor\"})\n(def test-list [{:a 1} {:b 2}])\n(def test-smal",
"end": 598,
"score": 0.9947652220726013,
"start": 592,
"tag": "NAME",
"value": "Victor"
},
{
"context": " (= (count res) 1))\n (is (= res [{:name \"hello-lol\", :type 0, :size 0, :hash \"\"}])))\n (files/",
"end": 4783,
"score": 0.9760148525238037,
"start": 4774,
"tag": "USERNAME",
"value": "hello-lol"
}
] | test/ipfs_api/files_test.clj | open-services/clj-ipfs-api | 5 | (ns ipfs-api.files-test
(:require [clojure.test :refer :all]
[ipfs-api.test-utils :refer [with-daemon]]
[ipfs-api.daemon :as daemon]
[ipfs-api.files :as files]
[clojure.java.io :as io]))
;; (deftest version
;; (testing "Getting version from daemon"
;; (with-daemon
;; (is (= expected-version (misc/version daemon))))))
(def test-string "hello world")
(def test-file-path "/my-file")
(def test-nested-path "/my-directory/1/2/3/4/5/my-file")
(def test-another-nested-path "/npmjs.org/a-package/tarball.tgz")
(def test-map {:name "Victor"})
(def test-list [{:a 1} {:b 2}])
(def test-small-file-path "test/fixtures/dir/file-a.md")
(def test-big-file-path "test/fixtures/big.file")
(defn file->byte-array [path]
(let [f (java.io.File. path)
ary (byte-array (.length f))
is (java.io.FileInputStream. f)]
(.read is ary)
(.close is)
ary))
(defn test-create-file [daemon path content]
;; Create new file
(files/write daemon path content)
;; Read created file
(is (= (files/read daemon path) content))
;; Remove the file
(files/rm daemon path)
;; File doesn't exists anymore
(is (thrown? Exception (files/read daemon path))))
(defn test-create-edn [daemon path structure]
;; Create new file
(files/write-edn daemon path structure)
;; Read created file
(is (= (files/read-edn daemon path) structure))
;; Remove the file
(files/rm daemon path)
;; File doesn't exists anymore
(is (thrown? Exception (files/read-edn daemon path))))
(deftest files-create
(with-daemon
(testing "create file"
(test-create-file daemon test-file-path test-string))
(testing "create nested file"
(test-create-file daemon test-nested-path test-string)
(test-create-file daemon test-another-nested-path test-string))
(testing "create file with clojure data in it"
(test-create-edn daemon test-nested-path test-map)
(test-create-edn daemon test-nested-path test-list))
(testing "create file with a InputStream"
(let [stream (io/input-stream (.getBytes "hello world"))]
(files/write daemon "/hello" stream)
(is (= (files/read daemon "/hello") "hello world"))
(files/rm daemon "/hello")))
(testing "create file with byte-array"
(let [b (.getBytes "hello world")]
(files/write daemon "/hello" b)
(is (= (files/read daemon "/hello") "hello world"))
(files/rm daemon "/hello")))
(testing "create from file with byte-array"
(let [b (file->byte-array test-small-file-path)]
(files/write daemon "/hello-lol/world" b)
(is (= (count (files/read daemon "/hello-lol/world")) (count b)))
(is (= (files/read daemon "/hello-lol/world") (String. b)))
(files/rm daemon "/hello-lol/world")))))
;; (testing "create big file with byte-array"
;; (let [b (file->byte-array test-big-file-path)]
;; (files/write daemon "/hello" b)
;; (is (= (count (files/read daemon "/hello")) (count b)))
;; (files/rm daemon "/hello")))
;; (testing "create big file with byte-array"
;; (let [b (file->byte-array test-big-file-path)]
;; (files/write daemon "/dir-lol/world" b)
;; (is (= (count (files/read daemon "/dir-lol/world")) (count b)))
;; (is (= b (files/read daemon "/dir-lol/world")))
;; (files/rm daemon "/dir-lol/world")))
(deftest files-read
(with-daemon
(testing "read a file as byte-array"
(let [b (file->byte-array test-small-file-path)]
(files/write daemon "/hello-lol/world" b)
(is (= (count (files/read daemon "/hello-lol/world")) (count b)))
(is (= (String. (files/read daemon "/hello-lol/world" {:as :byte-array}))
(String. b)))
(files/rm daemon "/hello-lol/world")))))
(deftest files-create
(with-daemon
(testing "stat a directory"
(let [_ (files/write daemon "/hello-lol/world" (file->byte-array test-small-file-path))
res (files/stat daemon "/hello-lol")]
(is (= (:hash res) "Qmcf3v3DpHUBTM5bEQ46bqbCrNKKnZmGc7WbGYwGgT3a8p"))
(is (= (:size res) 0))
(is (= (:cumulativesize res) 120))
(is (= (:blocks res) 1))
(is (= (:type res) "directory"))))))
(deftest files-ls
(with-daemon
(testing "ls a directory"
(let [b (file->byte-array test-small-file-path)]
(files/write daemon "/hello-lol/hello" b)
(files/write daemon "/hello-lol/world" b)
(let [res (files/ls daemon "/hello-lol")]
(is (= (count res) 2))
(is (= res [{:name "hello", :type 0, :size 0, :hash ""}
{:name "world", :type 0, :size 0, :hash ""}])))
(let [res (files/ls daemon "/")]
(is (= (count res) 1))
(is (= res [{:name "hello-lol", :type 0, :size 0, :hash ""}])))
(files/rm daemon "/hello-lol/hello")
(files/rm daemon "/hello-lol/world")))))
| 32616 | (ns ipfs-api.files-test
(:require [clojure.test :refer :all]
[ipfs-api.test-utils :refer [with-daemon]]
[ipfs-api.daemon :as daemon]
[ipfs-api.files :as files]
[clojure.java.io :as io]))
;; (deftest version
;; (testing "Getting version from daemon"
;; (with-daemon
;; (is (= expected-version (misc/version daemon))))))
(def test-string "hello world")
(def test-file-path "/my-file")
(def test-nested-path "/my-directory/1/2/3/4/5/my-file")
(def test-another-nested-path "/npmjs.org/a-package/tarball.tgz")
(def test-map {:name "<NAME>"})
(def test-list [{:a 1} {:b 2}])
(def test-small-file-path "test/fixtures/dir/file-a.md")
(def test-big-file-path "test/fixtures/big.file")
(defn file->byte-array [path]
(let [f (java.io.File. path)
ary (byte-array (.length f))
is (java.io.FileInputStream. f)]
(.read is ary)
(.close is)
ary))
(defn test-create-file [daemon path content]
;; Create new file
(files/write daemon path content)
;; Read created file
(is (= (files/read daemon path) content))
;; Remove the file
(files/rm daemon path)
;; File doesn't exists anymore
(is (thrown? Exception (files/read daemon path))))
(defn test-create-edn [daemon path structure]
;; Create new file
(files/write-edn daemon path structure)
;; Read created file
(is (= (files/read-edn daemon path) structure))
;; Remove the file
(files/rm daemon path)
;; File doesn't exists anymore
(is (thrown? Exception (files/read-edn daemon path))))
(deftest files-create
(with-daemon
(testing "create file"
(test-create-file daemon test-file-path test-string))
(testing "create nested file"
(test-create-file daemon test-nested-path test-string)
(test-create-file daemon test-another-nested-path test-string))
(testing "create file with clojure data in it"
(test-create-edn daemon test-nested-path test-map)
(test-create-edn daemon test-nested-path test-list))
(testing "create file with a InputStream"
(let [stream (io/input-stream (.getBytes "hello world"))]
(files/write daemon "/hello" stream)
(is (= (files/read daemon "/hello") "hello world"))
(files/rm daemon "/hello")))
(testing "create file with byte-array"
(let [b (.getBytes "hello world")]
(files/write daemon "/hello" b)
(is (= (files/read daemon "/hello") "hello world"))
(files/rm daemon "/hello")))
(testing "create from file with byte-array"
(let [b (file->byte-array test-small-file-path)]
(files/write daemon "/hello-lol/world" b)
(is (= (count (files/read daemon "/hello-lol/world")) (count b)))
(is (= (files/read daemon "/hello-lol/world") (String. b)))
(files/rm daemon "/hello-lol/world")))))
;; (testing "create big file with byte-array"
;; (let [b (file->byte-array test-big-file-path)]
;; (files/write daemon "/hello" b)
;; (is (= (count (files/read daemon "/hello")) (count b)))
;; (files/rm daemon "/hello")))
;; (testing "create big file with byte-array"
;; (let [b (file->byte-array test-big-file-path)]
;; (files/write daemon "/dir-lol/world" b)
;; (is (= (count (files/read daemon "/dir-lol/world")) (count b)))
;; (is (= b (files/read daemon "/dir-lol/world")))
;; (files/rm daemon "/dir-lol/world")))
(deftest files-read
(with-daemon
(testing "read a file as byte-array"
(let [b (file->byte-array test-small-file-path)]
(files/write daemon "/hello-lol/world" b)
(is (= (count (files/read daemon "/hello-lol/world")) (count b)))
(is (= (String. (files/read daemon "/hello-lol/world" {:as :byte-array}))
(String. b)))
(files/rm daemon "/hello-lol/world")))))
(deftest files-create
(with-daemon
(testing "stat a directory"
(let [_ (files/write daemon "/hello-lol/world" (file->byte-array test-small-file-path))
res (files/stat daemon "/hello-lol")]
(is (= (:hash res) "Qmcf3v3DpHUBTM5bEQ46bqbCrNKKnZmGc7WbGYwGgT3a8p"))
(is (= (:size res) 0))
(is (= (:cumulativesize res) 120))
(is (= (:blocks res) 1))
(is (= (:type res) "directory"))))))
(deftest files-ls
(with-daemon
(testing "ls a directory"
(let [b (file->byte-array test-small-file-path)]
(files/write daemon "/hello-lol/hello" b)
(files/write daemon "/hello-lol/world" b)
(let [res (files/ls daemon "/hello-lol")]
(is (= (count res) 2))
(is (= res [{:name "hello", :type 0, :size 0, :hash ""}
{:name "world", :type 0, :size 0, :hash ""}])))
(let [res (files/ls daemon "/")]
(is (= (count res) 1))
(is (= res [{:name "hello-lol", :type 0, :size 0, :hash ""}])))
(files/rm daemon "/hello-lol/hello")
(files/rm daemon "/hello-lol/world")))))
| true | (ns ipfs-api.files-test
(:require [clojure.test :refer :all]
[ipfs-api.test-utils :refer [with-daemon]]
[ipfs-api.daemon :as daemon]
[ipfs-api.files :as files]
[clojure.java.io :as io]))
;; (deftest version
;; (testing "Getting version from daemon"
;; (with-daemon
;; (is (= expected-version (misc/version daemon))))))
(def test-string "hello world")
(def test-file-path "/my-file")
(def test-nested-path "/my-directory/1/2/3/4/5/my-file")
(def test-another-nested-path "/npmjs.org/a-package/tarball.tgz")
(def test-map {:name "PI:NAME:<NAME>END_PI"})
(def test-list [{:a 1} {:b 2}])
(def test-small-file-path "test/fixtures/dir/file-a.md")
(def test-big-file-path "test/fixtures/big.file")
(defn file->byte-array [path]
(let [f (java.io.File. path)
ary (byte-array (.length f))
is (java.io.FileInputStream. f)]
(.read is ary)
(.close is)
ary))
(defn test-create-file [daemon path content]
;; Create new file
(files/write daemon path content)
;; Read created file
(is (= (files/read daemon path) content))
;; Remove the file
(files/rm daemon path)
;; File doesn't exists anymore
(is (thrown? Exception (files/read daemon path))))
(defn test-create-edn [daemon path structure]
;; Create new file
(files/write-edn daemon path structure)
;; Read created file
(is (= (files/read-edn daemon path) structure))
;; Remove the file
(files/rm daemon path)
;; File doesn't exists anymore
(is (thrown? Exception (files/read-edn daemon path))))
(deftest files-create
(with-daemon
(testing "create file"
(test-create-file daemon test-file-path test-string))
(testing "create nested file"
(test-create-file daemon test-nested-path test-string)
(test-create-file daemon test-another-nested-path test-string))
(testing "create file with clojure data in it"
(test-create-edn daemon test-nested-path test-map)
(test-create-edn daemon test-nested-path test-list))
(testing "create file with a InputStream"
(let [stream (io/input-stream (.getBytes "hello world"))]
(files/write daemon "/hello" stream)
(is (= (files/read daemon "/hello") "hello world"))
(files/rm daemon "/hello")))
(testing "create file with byte-array"
(let [b (.getBytes "hello world")]
(files/write daemon "/hello" b)
(is (= (files/read daemon "/hello") "hello world"))
(files/rm daemon "/hello")))
(testing "create from file with byte-array"
(let [b (file->byte-array test-small-file-path)]
(files/write daemon "/hello-lol/world" b)
(is (= (count (files/read daemon "/hello-lol/world")) (count b)))
(is (= (files/read daemon "/hello-lol/world") (String. b)))
(files/rm daemon "/hello-lol/world")))))
;; (testing "create big file with byte-array"
;; (let [b (file->byte-array test-big-file-path)]
;; (files/write daemon "/hello" b)
;; (is (= (count (files/read daemon "/hello")) (count b)))
;; (files/rm daemon "/hello")))
;; (testing "create big file with byte-array"
;; (let [b (file->byte-array test-big-file-path)]
;; (files/write daemon "/dir-lol/world" b)
;; (is (= (count (files/read daemon "/dir-lol/world")) (count b)))
;; (is (= b (files/read daemon "/dir-lol/world")))
;; (files/rm daemon "/dir-lol/world")))
(deftest files-read
(with-daemon
(testing "read a file as byte-array"
(let [b (file->byte-array test-small-file-path)]
(files/write daemon "/hello-lol/world" b)
(is (= (count (files/read daemon "/hello-lol/world")) (count b)))
(is (= (String. (files/read daemon "/hello-lol/world" {:as :byte-array}))
(String. b)))
(files/rm daemon "/hello-lol/world")))))
(deftest files-create
(with-daemon
(testing "stat a directory"
(let [_ (files/write daemon "/hello-lol/world" (file->byte-array test-small-file-path))
res (files/stat daemon "/hello-lol")]
(is (= (:hash res) "Qmcf3v3DpHUBTM5bEQ46bqbCrNKKnZmGc7WbGYwGgT3a8p"))
(is (= (:size res) 0))
(is (= (:cumulativesize res) 120))
(is (= (:blocks res) 1))
(is (= (:type res) "directory"))))))
(deftest files-ls
(with-daemon
(testing "ls a directory"
(let [b (file->byte-array test-small-file-path)]
(files/write daemon "/hello-lol/hello" b)
(files/write daemon "/hello-lol/world" b)
(let [res (files/ls daemon "/hello-lol")]
(is (= (count res) 2))
(is (= res [{:name "hello", :type 0, :size 0, :hash ""}
{:name "world", :type 0, :size 0, :hash ""}])))
(let [res (files/ls daemon "/")]
(is (= (count res) 1))
(is (= res [{:name "hello-lol", :type 0, :size 0, :hash ""}])))
(files/rm daemon "/hello-lol/hello")
(files/rm daemon "/hello-lol/world")))))
|
[
{
"context": "))\n\n(def ^:private program-liaison-email-address \"program-liaison@finos.org\")\n\n(defn- send-email\n \"Sends a UTF8 HTML email t",
"end": 2123,
"score": 0.9999262690544128,
"start": 2098,
"tag": "EMAIL",
"value": "program-liaison@finos.org"
},
{
"context": " \"https://raw.githubusercontent.com/finos/reports-job/master/active-participation-reports/\"",
"end": 4486,
"score": 0.9984594583511353,
"start": 4481,
"tag": "USERNAME",
"value": "finos"
}
] | src/metadata_tool/tools/reports.clj | pmonks/metadata-tool | 0 | ;
; Copyright 2017 Fintech Open Source Foundation
; SPDX-License-Identifier: Apache-2.0
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
(ns metadata-tool.tools.reports
(:require [clojure.string :as s]
[clojure.tools.logging :as log]
[clj-http.client :as http]
[clojure.set :as set]
[mount.core :as mnt :refer [defstate]]
[clj-time.core :as tm]
[clj-time.format :as tf]
[postal.core :as email]
[metadata-tool.config :as cfg]
[metadata-tool.template :as tem]
[metadata-tool.sources.github :as gh]
[metadata-tool.sources.metadata :as md]
[metadata-tool.sources.bitergia :as bi]
[metadata-tool.sources.joins :as j]))
(def ^:private inactive-project-threshold-days 180) ; The threshold (days) at which a project is considered "inactive"
(def ^:private old-pr-threshold-days 60) ; The threshold (days) at which a PR is considered "old"
(def ^:private old-issue-threshold-days 90) ; The threshold (days) at which an issue is considered "old"
(defstate email-config
:start (:email cfg/config))
(defstate email-user
:start (:user email-config))
(defstate email-override
:start (:email-override cfg/config))
(defstate test-email-address
:start (:test-email-address email-config))
(def ^:private program-liaison-email-address "program-liaison@finos.org")
(defn- send-email
"Sends a UTF8 HTML email to the given to-addresses (which can be either a string or a vector of strings)."
[to-addresses subject body & { :keys [ cc-addresses from-address reply-to-address ]
:or { from-address email-user
reply-to-address email-user }}]
(let [[to-addresses cc-addresses from-address reply-to-address]
(if email-override
[to-addresses cc-addresses from-address reply-to-address] ; Only use the passed in values if the --email-override switch has been provided
[test-email-address nil test-email-address test-email-address])] ; Otherwise use the test email address throughout
(log/info "Sending email to" to-addresses "with subject:" subject)
(email/send-message email-config
{ :from from-address
:reply-to reply-to-address
:to to-addresses
:cc cc-addresses
:subject subject
:body [{ :type "text/html; charset=\"UTF-8\""
:content body }] } )))
(defn- activity-stale?
[activity stale-date]
(let [program-id (:program cfg/config)
activity-date (tf/parse (tf/formatters :date) (:contribution-date activity))
compare-date (compare stale-date activity-date)]
(and (pos? compare-date) (= "INCUBATING" (:state activity)))))
(defn- send-email-to-pmc
[program-id subject body]
; TODO - enable code below and comment out print commands!
; (println "===========================")
; (println subject)
; (println "---------------------------")
; (println body)
; (println "==========================="))
(if-not (s/blank? program-id)
(send-email (:pmc-mailing-list-address (md/program-metadata program-id))
subject
body
:cc-addresses program-liaison-email-address
:reply-to-address program-liaison-email-address)))
(defn participation-img
[type program]
(let [program-id (:id program)
short-name (:program-short-name program)
img-url (str
"https://raw.githubusercontent.com/finos/reports-job/master/active-participation-reports/"
(s/lower-case short-name)
"-"
type
".png")]
(try
(http/get img-url)
img-url
(catch Exception e
(println (str "Warn - URL '" img-url "' returns 404"))))))
(defn email-pmc-reports
[]
(let [now-str (tf/unparse (tf/formatter "yyyy-MM-dd h:mmaa ZZZ") (tm/now))
all-programs (md/programs-metadata)
six-months-ago (tm/minus (tm/now) (tm/months 6))
unarchived-activities-without-leads (group-by :program-id
(remove #(= "ARCHIVED" (:state %))
(filter #(s/blank? (:lead-or-chair-person-id %))
(md/activities-metadata))))
inactive-unarchived-activities-metadata (group-by :program-id
(remove #(= "ARCHIVED" (:state %))
(remove nil?
(map md/activity-metadata-by-name
(bi/inactive-projects inactive-project-threshold-days)))))
stale-incubating-activities-metadata (group-by :program-id
(filter #(activity-stale? % six-months-ago)
(md/activities-metadata)))
unarchived-activities-with-unactioned-prs (group-by :program-id
(remove #(= "ARCHIVED" (:state %))
(remove nil?
(map md/activity-metadata-by-name
(bi/projects-with-old-prs old-pr-threshold-days)))))
unarchived-activities-with-unactioned-issues (group-by :program-id
(remove #(= "ARCHIVED" (:state %))
(remove nil?
(map md/activity-metadata-by-name
(bi/projects-with-old-issues old-issue-threshold-days)))))
unarchived-activities-with-non-standard-licenses (group-by :program-id
(filter #(some identity (map (fn [gh-url]
(let [gh-repo-license (s/lower-case (str (:spdx_id (:license (gh/repo gh-url)))))] ; Note underscore in :spdx_id!
(and (not= gh-repo-license "apache-2.0")
(not= gh-repo-license "cc-by-4.0" ))))
(:github-urls %)))
(remove #(= "ARCHIVED" (:state %)) (md/activities-metadata))))
archived-activities-that-arent-github-archived (group-by :program-id
(remove #(some identity
(map (fn [gh-url] (:archived (gh/repo gh-url)))
(:github-urls %)))
(filter #(and (= "ARCHIVED" (:state %))
(pos? (count (:github-urls %))))
(md/activities-metadata))))
activities-with-repos-without-issues-support (group-by :program-id
(filter #(some identity (map (fn [gh-url] (not (:has_issues (gh/repo gh-url)))) ; Note underscore in :has_issues!
(:github-urls %)))
(md/activities-metadata)))
]
(doall (map #(send-email-to-pmc (:program-id %)
(str (:program-short-name %) " PMC Report as at " now-str)
(tem/render "emails/pmc-report.ftl"
{ :now now-str
:inactive-days inactive-project-threshold-days
:old-pr-threshold-days old-pr-threshold-days
:old-issue-threshold-days old-issue-threshold-days
:program %
:wg-participation-img (participation-img "working_group" %)
:project-participation-img (participation-img "project" %)
:working-groups (md/activities % "WORKING_GROUP")
:projects (md/activities % "PROJECT")
:pmc-lead (md/pmc-lead %)
:orgs-in-pmc (md/orgs-in-pmc %)
:pmc-list (md/pmc-list %)
:unarchived-activities-without-leads (seq (sort-by :activity-name (get unarchived-activities-without-leads (:program-id %))))
:inactive-activities (seq (sort-by :activity-name (get inactive-unarchived-activities-metadata (:program-id %))))
:stale-activities (seq (sort-by :activity-name (get stale-incubating-activities-metadata (:program-id %))))
:activities-with-unactioned-prs (seq (sort-by :activity-name (get unarchived-activities-with-unactioned-prs (:program-id %))))
:activities-with-unactioned-issues (seq (sort-by :activity-name (get unarchived-activities-with-unactioned-issues (:program-id %))))
:unarchived-activities-with-non-standard-licenses (seq (sort-by :activity-name (get unarchived-activities-with-non-standard-licenses (:program-id %))))
:archived-activities-that-arent-github-archived (seq (sort-by :activity-name (get archived-activities-that-arent-github-archived (:program-id %))))
:activities-with-repos-without-issues-support (seq (sort-by :activity-name (get activities-with-repos-without-issues-support (:program-id %))))
} ))
all-programs))))
| 116391 | ;
; Copyright 2017 Fintech Open Source Foundation
; SPDX-License-Identifier: Apache-2.0
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
(ns metadata-tool.tools.reports
(:require [clojure.string :as s]
[clojure.tools.logging :as log]
[clj-http.client :as http]
[clojure.set :as set]
[mount.core :as mnt :refer [defstate]]
[clj-time.core :as tm]
[clj-time.format :as tf]
[postal.core :as email]
[metadata-tool.config :as cfg]
[metadata-tool.template :as tem]
[metadata-tool.sources.github :as gh]
[metadata-tool.sources.metadata :as md]
[metadata-tool.sources.bitergia :as bi]
[metadata-tool.sources.joins :as j]))
(def ^:private inactive-project-threshold-days 180) ; The threshold (days) at which a project is considered "inactive"
(def ^:private old-pr-threshold-days 60) ; The threshold (days) at which a PR is considered "old"
(def ^:private old-issue-threshold-days 90) ; The threshold (days) at which an issue is considered "old"
(defstate email-config
:start (:email cfg/config))
(defstate email-user
:start (:user email-config))
(defstate email-override
:start (:email-override cfg/config))
(defstate test-email-address
:start (:test-email-address email-config))
(def ^:private program-liaison-email-address "<EMAIL>")
(defn- send-email
"Sends a UTF8 HTML email to the given to-addresses (which can be either a string or a vector of strings)."
[to-addresses subject body & { :keys [ cc-addresses from-address reply-to-address ]
:or { from-address email-user
reply-to-address email-user }}]
(let [[to-addresses cc-addresses from-address reply-to-address]
(if email-override
[to-addresses cc-addresses from-address reply-to-address] ; Only use the passed in values if the --email-override switch has been provided
[test-email-address nil test-email-address test-email-address])] ; Otherwise use the test email address throughout
(log/info "Sending email to" to-addresses "with subject:" subject)
(email/send-message email-config
{ :from from-address
:reply-to reply-to-address
:to to-addresses
:cc cc-addresses
:subject subject
:body [{ :type "text/html; charset=\"UTF-8\""
:content body }] } )))
(defn- activity-stale?
[activity stale-date]
(let [program-id (:program cfg/config)
activity-date (tf/parse (tf/formatters :date) (:contribution-date activity))
compare-date (compare stale-date activity-date)]
(and (pos? compare-date) (= "INCUBATING" (:state activity)))))
(defn- send-email-to-pmc
[program-id subject body]
; TODO - enable code below and comment out print commands!
; (println "===========================")
; (println subject)
; (println "---------------------------")
; (println body)
; (println "==========================="))
(if-not (s/blank? program-id)
(send-email (:pmc-mailing-list-address (md/program-metadata program-id))
subject
body
:cc-addresses program-liaison-email-address
:reply-to-address program-liaison-email-address)))
(defn participation-img
[type program]
(let [program-id (:id program)
short-name (:program-short-name program)
img-url (str
"https://raw.githubusercontent.com/finos/reports-job/master/active-participation-reports/"
(s/lower-case short-name)
"-"
type
".png")]
(try
(http/get img-url)
img-url
(catch Exception e
(println (str "Warn - URL '" img-url "' returns 404"))))))
(defn email-pmc-reports
[]
(let [now-str (tf/unparse (tf/formatter "yyyy-MM-dd h:mmaa ZZZ") (tm/now))
all-programs (md/programs-metadata)
six-months-ago (tm/minus (tm/now) (tm/months 6))
unarchived-activities-without-leads (group-by :program-id
(remove #(= "ARCHIVED" (:state %))
(filter #(s/blank? (:lead-or-chair-person-id %))
(md/activities-metadata))))
inactive-unarchived-activities-metadata (group-by :program-id
(remove #(= "ARCHIVED" (:state %))
(remove nil?
(map md/activity-metadata-by-name
(bi/inactive-projects inactive-project-threshold-days)))))
stale-incubating-activities-metadata (group-by :program-id
(filter #(activity-stale? % six-months-ago)
(md/activities-metadata)))
unarchived-activities-with-unactioned-prs (group-by :program-id
(remove #(= "ARCHIVED" (:state %))
(remove nil?
(map md/activity-metadata-by-name
(bi/projects-with-old-prs old-pr-threshold-days)))))
unarchived-activities-with-unactioned-issues (group-by :program-id
(remove #(= "ARCHIVED" (:state %))
(remove nil?
(map md/activity-metadata-by-name
(bi/projects-with-old-issues old-issue-threshold-days)))))
unarchived-activities-with-non-standard-licenses (group-by :program-id
(filter #(some identity (map (fn [gh-url]
(let [gh-repo-license (s/lower-case (str (:spdx_id (:license (gh/repo gh-url)))))] ; Note underscore in :spdx_id!
(and (not= gh-repo-license "apache-2.0")
(not= gh-repo-license "cc-by-4.0" ))))
(:github-urls %)))
(remove #(= "ARCHIVED" (:state %)) (md/activities-metadata))))
archived-activities-that-arent-github-archived (group-by :program-id
(remove #(some identity
(map (fn [gh-url] (:archived (gh/repo gh-url)))
(:github-urls %)))
(filter #(and (= "ARCHIVED" (:state %))
(pos? (count (:github-urls %))))
(md/activities-metadata))))
activities-with-repos-without-issues-support (group-by :program-id
(filter #(some identity (map (fn [gh-url] (not (:has_issues (gh/repo gh-url)))) ; Note underscore in :has_issues!
(:github-urls %)))
(md/activities-metadata)))
]
(doall (map #(send-email-to-pmc (:program-id %)
(str (:program-short-name %) " PMC Report as at " now-str)
(tem/render "emails/pmc-report.ftl"
{ :now now-str
:inactive-days inactive-project-threshold-days
:old-pr-threshold-days old-pr-threshold-days
:old-issue-threshold-days old-issue-threshold-days
:program %
:wg-participation-img (participation-img "working_group" %)
:project-participation-img (participation-img "project" %)
:working-groups (md/activities % "WORKING_GROUP")
:projects (md/activities % "PROJECT")
:pmc-lead (md/pmc-lead %)
:orgs-in-pmc (md/orgs-in-pmc %)
:pmc-list (md/pmc-list %)
:unarchived-activities-without-leads (seq (sort-by :activity-name (get unarchived-activities-without-leads (:program-id %))))
:inactive-activities (seq (sort-by :activity-name (get inactive-unarchived-activities-metadata (:program-id %))))
:stale-activities (seq (sort-by :activity-name (get stale-incubating-activities-metadata (:program-id %))))
:activities-with-unactioned-prs (seq (sort-by :activity-name (get unarchived-activities-with-unactioned-prs (:program-id %))))
:activities-with-unactioned-issues (seq (sort-by :activity-name (get unarchived-activities-with-unactioned-issues (:program-id %))))
:unarchived-activities-with-non-standard-licenses (seq (sort-by :activity-name (get unarchived-activities-with-non-standard-licenses (:program-id %))))
:archived-activities-that-arent-github-archived (seq (sort-by :activity-name (get archived-activities-that-arent-github-archived (:program-id %))))
:activities-with-repos-without-issues-support (seq (sort-by :activity-name (get activities-with-repos-without-issues-support (:program-id %))))
} ))
all-programs))))
| true | ;
; Copyright 2017 Fintech Open Source Foundation
; SPDX-License-Identifier: Apache-2.0
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
(ns metadata-tool.tools.reports
(:require [clojure.string :as s]
[clojure.tools.logging :as log]
[clj-http.client :as http]
[clojure.set :as set]
[mount.core :as mnt :refer [defstate]]
[clj-time.core :as tm]
[clj-time.format :as tf]
[postal.core :as email]
[metadata-tool.config :as cfg]
[metadata-tool.template :as tem]
[metadata-tool.sources.github :as gh]
[metadata-tool.sources.metadata :as md]
[metadata-tool.sources.bitergia :as bi]
[metadata-tool.sources.joins :as j]))
(def ^:private inactive-project-threshold-days 180) ; The threshold (days) at which a project is considered "inactive"
(def ^:private old-pr-threshold-days 60) ; The threshold (days) at which a PR is considered "old"
(def ^:private old-issue-threshold-days 90) ; The threshold (days) at which an issue is considered "old"
(defstate email-config
:start (:email cfg/config))
(defstate email-user
:start (:user email-config))
(defstate email-override
:start (:email-override cfg/config))
(defstate test-email-address
:start (:test-email-address email-config))
(def ^:private program-liaison-email-address "PI:EMAIL:<EMAIL>END_PI")
(defn- send-email
"Sends a UTF8 HTML email to the given to-addresses (which can be either a string or a vector of strings)."
[to-addresses subject body & { :keys [ cc-addresses from-address reply-to-address ]
:or { from-address email-user
reply-to-address email-user }}]
(let [[to-addresses cc-addresses from-address reply-to-address]
(if email-override
[to-addresses cc-addresses from-address reply-to-address] ; Only use the passed in values if the --email-override switch has been provided
[test-email-address nil test-email-address test-email-address])] ; Otherwise use the test email address throughout
(log/info "Sending email to" to-addresses "with subject:" subject)
(email/send-message email-config
{ :from from-address
:reply-to reply-to-address
:to to-addresses
:cc cc-addresses
:subject subject
:body [{ :type "text/html; charset=\"UTF-8\""
:content body }] } )))
(defn- activity-stale?
[activity stale-date]
(let [program-id (:program cfg/config)
activity-date (tf/parse (tf/formatters :date) (:contribution-date activity))
compare-date (compare stale-date activity-date)]
(and (pos? compare-date) (= "INCUBATING" (:state activity)))))
(defn- send-email-to-pmc
[program-id subject body]
; TODO - enable code below and comment out print commands!
; (println "===========================")
; (println subject)
; (println "---------------------------")
; (println body)
; (println "==========================="))
(if-not (s/blank? program-id)
(send-email (:pmc-mailing-list-address (md/program-metadata program-id))
subject
body
:cc-addresses program-liaison-email-address
:reply-to-address program-liaison-email-address)))
(defn participation-img
[type program]
(let [program-id (:id program)
short-name (:program-short-name program)
img-url (str
"https://raw.githubusercontent.com/finos/reports-job/master/active-participation-reports/"
(s/lower-case short-name)
"-"
type
".png")]
(try
(http/get img-url)
img-url
(catch Exception e
(println (str "Warn - URL '" img-url "' returns 404"))))))
(defn email-pmc-reports
[]
(let [now-str (tf/unparse (tf/formatter "yyyy-MM-dd h:mmaa ZZZ") (tm/now))
all-programs (md/programs-metadata)
six-months-ago (tm/minus (tm/now) (tm/months 6))
unarchived-activities-without-leads (group-by :program-id
(remove #(= "ARCHIVED" (:state %))
(filter #(s/blank? (:lead-or-chair-person-id %))
(md/activities-metadata))))
inactive-unarchived-activities-metadata (group-by :program-id
(remove #(= "ARCHIVED" (:state %))
(remove nil?
(map md/activity-metadata-by-name
(bi/inactive-projects inactive-project-threshold-days)))))
stale-incubating-activities-metadata (group-by :program-id
(filter #(activity-stale? % six-months-ago)
(md/activities-metadata)))
unarchived-activities-with-unactioned-prs (group-by :program-id
(remove #(= "ARCHIVED" (:state %))
(remove nil?
(map md/activity-metadata-by-name
(bi/projects-with-old-prs old-pr-threshold-days)))))
unarchived-activities-with-unactioned-issues (group-by :program-id
(remove #(= "ARCHIVED" (:state %))
(remove nil?
(map md/activity-metadata-by-name
(bi/projects-with-old-issues old-issue-threshold-days)))))
unarchived-activities-with-non-standard-licenses (group-by :program-id
(filter #(some identity (map (fn [gh-url]
(let [gh-repo-license (s/lower-case (str (:spdx_id (:license (gh/repo gh-url)))))] ; Note underscore in :spdx_id!
(and (not= gh-repo-license "apache-2.0")
(not= gh-repo-license "cc-by-4.0" ))))
(:github-urls %)))
(remove #(= "ARCHIVED" (:state %)) (md/activities-metadata))))
archived-activities-that-arent-github-archived (group-by :program-id
(remove #(some identity
(map (fn [gh-url] (:archived (gh/repo gh-url)))
(:github-urls %)))
(filter #(and (= "ARCHIVED" (:state %))
(pos? (count (:github-urls %))))
(md/activities-metadata))))
activities-with-repos-without-issues-support (group-by :program-id
(filter #(some identity (map (fn [gh-url] (not (:has_issues (gh/repo gh-url)))) ; Note underscore in :has_issues!
(:github-urls %)))
(md/activities-metadata)))
]
(doall (map #(send-email-to-pmc (:program-id %)
(str (:program-short-name %) " PMC Report as at " now-str)
(tem/render "emails/pmc-report.ftl"
{ :now now-str
:inactive-days inactive-project-threshold-days
:old-pr-threshold-days old-pr-threshold-days
:old-issue-threshold-days old-issue-threshold-days
:program %
:wg-participation-img (participation-img "working_group" %)
:project-participation-img (participation-img "project" %)
:working-groups (md/activities % "WORKING_GROUP")
:projects (md/activities % "PROJECT")
:pmc-lead (md/pmc-lead %)
:orgs-in-pmc (md/orgs-in-pmc %)
:pmc-list (md/pmc-list %)
:unarchived-activities-without-leads (seq (sort-by :activity-name (get unarchived-activities-without-leads (:program-id %))))
:inactive-activities (seq (sort-by :activity-name (get inactive-unarchived-activities-metadata (:program-id %))))
:stale-activities (seq (sort-by :activity-name (get stale-incubating-activities-metadata (:program-id %))))
:activities-with-unactioned-prs (seq (sort-by :activity-name (get unarchived-activities-with-unactioned-prs (:program-id %))))
:activities-with-unactioned-issues (seq (sort-by :activity-name (get unarchived-activities-with-unactioned-issues (:program-id %))))
:unarchived-activities-with-non-standard-licenses (seq (sort-by :activity-name (get unarchived-activities-with-non-standard-licenses (:program-id %))))
:archived-activities-that-arent-github-archived (seq (sort-by :activity-name (get archived-activities-that-arent-github-archived (:program-id %))))
:activities-with-repos-without-issues-support (seq (sort-by :activity-name (get activities-with-repos-without-issues-support (:program-id %))))
} ))
all-programs))))
|
[
{
"context": "] (str/split fst-snd #\"-\")]\n {:password password\n :letter (first letter)\n :fst (Integ",
"end": 339,
"score": 0.9979432821273804,
"start": 331,
"tag": "PASSWORD",
"value": "password"
}
] | src/aoc_2020/day_2/utils.clj | Camsbury/aoc-2020 | 2 | (ns aoc-2020.day-2.utils
(:require
[clojure.string :as str]))
(defn process-entry
"parses each entry into a password and policy details"
[entry]
(let [[policy password] (str/split entry #": ")
[fst-snd letter] (str/split policy #" ")
[fst snd] (str/split fst-snd #"-")]
{:password password
:letter (first letter)
:fst (Integer/parseInt fst)
:snd (Integer/parseInt snd)}))
| 82000 | (ns aoc-2020.day-2.utils
(:require
[clojure.string :as str]))
(defn process-entry
"parses each entry into a password and policy details"
[entry]
(let [[policy password] (str/split entry #": ")
[fst-snd letter] (str/split policy #" ")
[fst snd] (str/split fst-snd #"-")]
{:password <PASSWORD>
:letter (first letter)
:fst (Integer/parseInt fst)
:snd (Integer/parseInt snd)}))
| true | (ns aoc-2020.day-2.utils
(:require
[clojure.string :as str]))
(defn process-entry
"parses each entry into a password and policy details"
[entry]
(let [[policy password] (str/split entry #": ")
[fst-snd letter] (str/split policy #" ")
[fst snd] (str/split fst-snd #"-")]
{:password PI:PASSWORD:<PASSWORD>END_PI
:letter (first letter)
:fst (Integer/parseInt fst)
:snd (Integer/parseInt snd)}))
|
[
{
"context": "Pics LocatedPictures]\n (if (empty? SortedPics)\n\t; trues\n\tLocatedPictures \n\t;false\t\n (let [nextPic (first ",
"end": 3843,
"score": 0.9686373472213745,
"start": 3838,
"tag": "NAME",
"value": "trues"
}
] | data/test/clojure/b45bd7c530e451a6d3d0477a5a0f4a2d42be3322manageImages.clj | harshp8l/deep-learning-lang-detection | 84 | (ns NewCssSprite.manageImages
(:use NewCssSprite.strTools)
(:import (javax.imageio ImageIO)
(java.awt Color
image.BufferedImage)))
(defn SumPicsHeight1
[initialSum SortedPictures]
"returns the sum of all the pictures height"
(if (empty? SortedPictures)
initialSum
(recur (+ initialSum (last (:dimensions (first SortedPictures)))) (rest SortedPictures))
) )
(defn getMaxPicWidth [SortedPictures]
"gets the max width of a picture"
(first ( :dimensions (first SortedPictures)))
)
(defn collecte-imgs
"Given a directory, return a map of all png images with a buffered image and dimensions"
[dir]
(let [dir-name (file-str dir)] "get the dir name"
(map
(fn [image]
(let [imgIO (ImageIO/read image)]
{:buffered-image imgIO :path (.replaceAll (.getPath image) dir "") :dimensions [(.getWidth imgIO) (.getHeight imgIO)] :x 0 ,:y 0}))
(filter
#(re-matches #"(?i).*\.png$" (.getName %1))
(file-seq dir-name)))))
(defn DoesPicFit[ x pic]
(and (>= ( x :width) (first (pic :dimensions))) (>= (x :height) (last (pic :dimensions)))))
(defn combine-images
"Given the images , create a sprite png at the output location"
[images output]
(let [MaxYPic (:bottomY (last (sort-by :bottomY images )) )
hi (+ 0 ( :y (last (sort-by :y images))) (last ( :dimensions (last (sort-by :dimensions images)))))
output-image (BufferedImage. (getMaxPicWidth images) MaxYPic BufferedImage/TYPE_INT_ARGB)
graphics (.createGraphics output-image)]
(doseq [image images]
(.drawImage graphics (:buffered-image image) (:x image) (:y image) nil))
(ImageIO/write output-image "png" (file-str output)) images))
(defn GetBestSpace [pic spacesList]
(let [currspace (first spacesList)]
(do
(if (DoesPicFit currspace pic)
(conj nil currspace );true
(recur pic (rest spacesList));false
))))
(defn PlacePic [pic BestSpace]
(
let[ SpaceA {:x(BestSpace :x)
:y(+ (BestSpace :y) (last (pic :dimensions)) )
:width (BestSpace :width )
:height (- (BestSpace :height ) (last (pic :dimensions)))}
SpaceB {:x (+(BestSpace :x) (first (pic :dimensions)))
:y (BestSpace :y)
:width (-(BestSpace :width)(first (pic :dimensions)))
:height (last (pic :dimensions))}
NewPic (assoc pic
:x(BestSpace :x)
:y(BestSpace :y)
:bottomY (+ (BestSpace :y) (last (pic :dimensions) )))
returnMap {:Pic NewPic :SpaceA nil :SpaceB nil}]
(assoc returnMap
:SpaceA (if(and (< 0 (SpaceA :height ))(< 0 (SpaceA :width) )) SpaceA nil)
:SpaceB (if(and (< 0 (SpaceB :height ))(< 0 (SpaceB :width))) SpaceB nil))
)
)
(defn updatList [OldList newSpaceA newSpaceB BestOpenSpace]
"delets the used space and return a new list with the new spaces "
(let [
;filter the current best space out of the space list. it is no longer a valid space
ChangedList (filter (fn [space]
(and
(not= (space :x )(BestOpenSpace :x ))
(not= (space :y )(BestOpenSpace :y )))
)OldList) ]
; add the new spaces into the spacelist , sort out the nils if they exist
(sort-by :width (filter (fn [space]
(not (nil? space)))
(conj ChangedList newSpaceA newSpaceB)))
))
( defn getBounds [SpaceList SortedPics LocatedPictures]
(if (empty? SortedPics)
; trues
LocatedPictures
;false
(let [nextPic (first SortedPics )
;gets the best open space , set the used flag to 1
BestOpenSpace (first (GetBestSpace nextPic SpaceList))
newSpacesNpic (PlacePic nextPic BestOpenSpace)
newSpaceA(:SpaceA newSpacesNpic)
newSpaceB(:SpaceB newSpacesNpic)
updatedSPaceList(updatList SpaceList newSpaceA newSpaceB BestOpenSpace) ]
(recur updatedSPaceList (rest SortedPics) (conj LocatedPictures (:Pic newSpacesNpic)) )
)
)
)
| 23025 | (ns NewCssSprite.manageImages
(:use NewCssSprite.strTools)
(:import (javax.imageio ImageIO)
(java.awt Color
image.BufferedImage)))
(defn SumPicsHeight1
[initialSum SortedPictures]
"returns the sum of all the pictures height"
(if (empty? SortedPictures)
initialSum
(recur (+ initialSum (last (:dimensions (first SortedPictures)))) (rest SortedPictures))
) )
(defn getMaxPicWidth [SortedPictures]
"gets the max width of a picture"
(first ( :dimensions (first SortedPictures)))
)
(defn collecte-imgs
"Given a directory, return a map of all png images with a buffered image and dimensions"
[dir]
(let [dir-name (file-str dir)] "get the dir name"
(map
(fn [image]
(let [imgIO (ImageIO/read image)]
{:buffered-image imgIO :path (.replaceAll (.getPath image) dir "") :dimensions [(.getWidth imgIO) (.getHeight imgIO)] :x 0 ,:y 0}))
(filter
#(re-matches #"(?i).*\.png$" (.getName %1))
(file-seq dir-name)))))
(defn DoesPicFit[ x pic]
(and (>= ( x :width) (first (pic :dimensions))) (>= (x :height) (last (pic :dimensions)))))
(defn combine-images
"Given the images , create a sprite png at the output location"
[images output]
(let [MaxYPic (:bottomY (last (sort-by :bottomY images )) )
hi (+ 0 ( :y (last (sort-by :y images))) (last ( :dimensions (last (sort-by :dimensions images)))))
output-image (BufferedImage. (getMaxPicWidth images) MaxYPic BufferedImage/TYPE_INT_ARGB)
graphics (.createGraphics output-image)]
(doseq [image images]
(.drawImage graphics (:buffered-image image) (:x image) (:y image) nil))
(ImageIO/write output-image "png" (file-str output)) images))
(defn GetBestSpace [pic spacesList]
(let [currspace (first spacesList)]
(do
(if (DoesPicFit currspace pic)
(conj nil currspace );true
(recur pic (rest spacesList));false
))))
(defn PlacePic [pic BestSpace]
(
let[ SpaceA {:x(BestSpace :x)
:y(+ (BestSpace :y) (last (pic :dimensions)) )
:width (BestSpace :width )
:height (- (BestSpace :height ) (last (pic :dimensions)))}
SpaceB {:x (+(BestSpace :x) (first (pic :dimensions)))
:y (BestSpace :y)
:width (-(BestSpace :width)(first (pic :dimensions)))
:height (last (pic :dimensions))}
NewPic (assoc pic
:x(BestSpace :x)
:y(BestSpace :y)
:bottomY (+ (BestSpace :y) (last (pic :dimensions) )))
returnMap {:Pic NewPic :SpaceA nil :SpaceB nil}]
(assoc returnMap
:SpaceA (if(and (< 0 (SpaceA :height ))(< 0 (SpaceA :width) )) SpaceA nil)
:SpaceB (if(and (< 0 (SpaceB :height ))(< 0 (SpaceB :width))) SpaceB nil))
)
)
(defn updatList [OldList newSpaceA newSpaceB BestOpenSpace]
"delets the used space and return a new list with the new spaces "
(let [
;filter the current best space out of the space list. it is no longer a valid space
ChangedList (filter (fn [space]
(and
(not= (space :x )(BestOpenSpace :x ))
(not= (space :y )(BestOpenSpace :y )))
)OldList) ]
; add the new spaces into the spacelist , sort out the nils if they exist
(sort-by :width (filter (fn [space]
(not (nil? space)))
(conj ChangedList newSpaceA newSpaceB)))
))
( defn getBounds [SpaceList SortedPics LocatedPictures]
(if (empty? SortedPics)
; <NAME>
LocatedPictures
;false
(let [nextPic (first SortedPics )
;gets the best open space , set the used flag to 1
BestOpenSpace (first (GetBestSpace nextPic SpaceList))
newSpacesNpic (PlacePic nextPic BestOpenSpace)
newSpaceA(:SpaceA newSpacesNpic)
newSpaceB(:SpaceB newSpacesNpic)
updatedSPaceList(updatList SpaceList newSpaceA newSpaceB BestOpenSpace) ]
(recur updatedSPaceList (rest SortedPics) (conj LocatedPictures (:Pic newSpacesNpic)) )
)
)
)
| true | (ns NewCssSprite.manageImages
(:use NewCssSprite.strTools)
(:import (javax.imageio ImageIO)
(java.awt Color
image.BufferedImage)))
(defn SumPicsHeight1
[initialSum SortedPictures]
"returns the sum of all the pictures height"
(if (empty? SortedPictures)
initialSum
(recur (+ initialSum (last (:dimensions (first SortedPictures)))) (rest SortedPictures))
) )
(defn getMaxPicWidth [SortedPictures]
"gets the max width of a picture"
(first ( :dimensions (first SortedPictures)))
)
(defn collecte-imgs
"Given a directory, return a map of all png images with a buffered image and dimensions"
[dir]
(let [dir-name (file-str dir)] "get the dir name"
(map
(fn [image]
(let [imgIO (ImageIO/read image)]
{:buffered-image imgIO :path (.replaceAll (.getPath image) dir "") :dimensions [(.getWidth imgIO) (.getHeight imgIO)] :x 0 ,:y 0}))
(filter
#(re-matches #"(?i).*\.png$" (.getName %1))
(file-seq dir-name)))))
(defn DoesPicFit[ x pic]
(and (>= ( x :width) (first (pic :dimensions))) (>= (x :height) (last (pic :dimensions)))))
(defn combine-images
"Given the images , create a sprite png at the output location"
[images output]
(let [MaxYPic (:bottomY (last (sort-by :bottomY images )) )
hi (+ 0 ( :y (last (sort-by :y images))) (last ( :dimensions (last (sort-by :dimensions images)))))
output-image (BufferedImage. (getMaxPicWidth images) MaxYPic BufferedImage/TYPE_INT_ARGB)
graphics (.createGraphics output-image)]
(doseq [image images]
(.drawImage graphics (:buffered-image image) (:x image) (:y image) nil))
(ImageIO/write output-image "png" (file-str output)) images))
(defn GetBestSpace [pic spacesList]
(let [currspace (first spacesList)]
(do
(if (DoesPicFit currspace pic)
(conj nil currspace );true
(recur pic (rest spacesList));false
))))
(defn PlacePic [pic BestSpace]
(
let[ SpaceA {:x(BestSpace :x)
:y(+ (BestSpace :y) (last (pic :dimensions)) )
:width (BestSpace :width )
:height (- (BestSpace :height ) (last (pic :dimensions)))}
SpaceB {:x (+(BestSpace :x) (first (pic :dimensions)))
:y (BestSpace :y)
:width (-(BestSpace :width)(first (pic :dimensions)))
:height (last (pic :dimensions))}
NewPic (assoc pic
:x(BestSpace :x)
:y(BestSpace :y)
:bottomY (+ (BestSpace :y) (last (pic :dimensions) )))
returnMap {:Pic NewPic :SpaceA nil :SpaceB nil}]
(assoc returnMap
:SpaceA (if(and (< 0 (SpaceA :height ))(< 0 (SpaceA :width) )) SpaceA nil)
:SpaceB (if(and (< 0 (SpaceB :height ))(< 0 (SpaceB :width))) SpaceB nil))
)
)
(defn updatList [OldList newSpaceA newSpaceB BestOpenSpace]
"delets the used space and return a new list with the new spaces "
(let [
;filter the current best space out of the space list. it is no longer a valid space
ChangedList (filter (fn [space]
(and
(not= (space :x )(BestOpenSpace :x ))
(not= (space :y )(BestOpenSpace :y )))
)OldList) ]
; add the new spaces into the spacelist , sort out the nils if they exist
(sort-by :width (filter (fn [space]
(not (nil? space)))
(conj ChangedList newSpaceA newSpaceB)))
))
( defn getBounds [SpaceList SortedPics LocatedPictures]
(if (empty? SortedPics)
; PI:NAME:<NAME>END_PI
LocatedPictures
;false
(let [nextPic (first SortedPics )
;gets the best open space , set the used flag to 1
BestOpenSpace (first (GetBestSpace nextPic SpaceList))
newSpacesNpic (PlacePic nextPic BestOpenSpace)
newSpaceA(:SpaceA newSpacesNpic)
newSpaceB(:SpaceB newSpacesNpic)
updatedSPaceList(updatList SpaceList newSpaceA newSpaceB BestOpenSpace) ]
(recur updatedSPaceList (rest SortedPics) (conj LocatedPictures (:Pic newSpacesNpic)) )
)
)
)
|
[
{
"context": "tabase.clj (clojure-firefly)\n;; Copyright (c) 2014 Austin Zheng\n;; Released under the terms of the MIT License\n\n(",
"end": 68,
"score": 0.9997857809066772,
"start": 56,
"tag": "NAME",
"value": "Austin Zheng"
}
] | src/clojure_blog/database.clj | austinzheng/clojure-firefly | 1 | ;; database.clj (clojure-firefly)
;; Copyright (c) 2014 Austin Zheng
;; Released under the terms of the MIT License
(ns clojure-blog.database
(:require
[taoensso.carmine :as car :refer (wcar)]))
;; NOTE: Don't require this file directly. It contains shared definitions and functionality used by the module-specific
;; database handlers.
;; Database initialization
(def server1-conn {:pool {} :spec {}})
(defmacro wcar* [& body] `(car/wcar server1-conn ~@body))
;; Convenience macros
; TODO: Make these even better.
(defmacro op-get-or-nil* [operation]
"Perform a checked get-type operation and return the result, or nil if the operation fails"
`(try ~operation (catch Exception e# nil)))
(defmacro op-set-or-false* [operation]
"Perform a checked set-type operation and return true if it succeeded, false if an exception was thrown"
`(try (do ~operation true) (catch Exception e# false)))
| 31146 | ;; database.clj (clojure-firefly)
;; Copyright (c) 2014 <NAME>
;; Released under the terms of the MIT License
(ns clojure-blog.database
(:require
[taoensso.carmine :as car :refer (wcar)]))
;; NOTE: Don't require this file directly. It contains shared definitions and functionality used by the module-specific
;; database handlers.
;; Database initialization
(def server1-conn {:pool {} :spec {}})
(defmacro wcar* [& body] `(car/wcar server1-conn ~@body))
;; Convenience macros
; TODO: Make these even better.
(defmacro op-get-or-nil* [operation]
"Perform a checked get-type operation and return the result, or nil if the operation fails"
`(try ~operation (catch Exception e# nil)))
(defmacro op-set-or-false* [operation]
"Perform a checked set-type operation and return true if it succeeded, false if an exception was thrown"
`(try (do ~operation true) (catch Exception e# false)))
| true | ;; database.clj (clojure-firefly)
;; Copyright (c) 2014 PI:NAME:<NAME>END_PI
;; Released under the terms of the MIT License
(ns clojure-blog.database
(:require
[taoensso.carmine :as car :refer (wcar)]))
;; NOTE: Don't require this file directly. It contains shared definitions and functionality used by the module-specific
;; database handlers.
;; Database initialization
(def server1-conn {:pool {} :spec {}})
(defmacro wcar* [& body] `(car/wcar server1-conn ~@body))
;; Convenience macros
; TODO: Make these even better.
(defmacro op-get-or-nil* [operation]
"Perform a checked get-type operation and return the result, or nil if the operation fails"
`(try ~operation (catch Exception e# nil)))
(defmacro op-set-or-false* [operation]
"Perform a checked set-type operation and return true if it succeeded, false if an exception was thrown"
`(try (do ~operation true) (catch Exception e# false)))
|
[
{
"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.9998754262924194,
"start": 584,
"tag": "NAME",
"value": "Kenneth Leung"
},
{
"context": "ll rights reserved.\n\n(ns ^{:doc \"\"\n :author \"Kenneth Leung\"}\n\n czlab.loki.game.room\n\n (:require [czlab.lok",
"end": 663,
"score": 0.9998823404312134,
"start": 650,
"tag": "NAME",
"value": "Kenneth Leung"
}
] | src/main/clojure/czlab/loki/game/room.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.room
(:require [czlab.loki.xpis :as loki]
[czlab.basal.core :as c]
[czlab.basal.util :as bu]
[czlab.loki.util :as u]
[czlab.niou.core :as cc]
[czlab.loki.session :as ss]
[czlab.loki.net.core :as nc]
[czlab.loki.game.arena :as ga])
(:use [flatland.ordered.map])
(:import [clojure.lang Keyword]
[java.util.concurrent.atomic AtomicInteger]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* true)
(def ^:private _room-mutex_ (Object.))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; {game-id -> map
;; { room-id -> room }}
(def ^:private free-rooms (atom (ordered-map)))
(def ^:private game-rooms (atom (ordered-map)))
(def ^:private vacancy 1000)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn count-free-rooms
""
^long [gameid]
(count (get @free-rooms gameid)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn count-game-rooms
""
^long [gameid]
(count (get @game-rooms gameid)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn clear-free-rooms
"Internal only"
{:no-doc true}
[gameid]
(locking _room-mutex_
(swap! free-rooms assoc gameid (ordered-map))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn clear-game-rooms
"Internal only"
{:no-doc true}
[gameid]
(locking _room-mutex_
(swap! game-rooms assoc gameid (ordered-map))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- remove-xxx-room
""
[gameid roomid db dbtxt]
(locking _room-mutex_
(when-some [r (-> (@db gameid)
(get roomid))]
(c/debug "remove %s: %s, game: %s" dbtxt roomid gameid)
(swap! db update-in [gameid] dissoc roomid)
r)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn remove-game-room
"Remove an active room"
[gameid roomid]
(remove-xxx-room gameid roomid game-rooms "room(A)"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn remove-free-room
"Remove a waiting room"
[gameid roomid]
(remove-xxx-room gameid roomid free-rooms "room(F)"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- add-xxx-room
""
[room db dbt]
{:pre [(some? room)]}
(locking _room-mutex_
(let [gid (c/id (:game @room))
rid (c/id room)
m? (contains? @db gid)]
(c/debug "adding a %s: %s, game: %s" dbt rid gid)
(if m?
(swap! db update-in [gid] assoc rid room)
(swap! db assoc gid (ordered-map rid room)))
room)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- add-free-room
"Add a new partially filled room into the pending set"
[room]
(add-xxx-room room free-rooms "room(F)"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- add-game-room
"Move room into the active set"
[room]
(add-xxx-room room game-rooms "room(A)"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- detach-free-room
""
[gameid roomid]
(c/debug "%s: %s, game: %s"
"found a room(F)" roomid gameid)
(swap! free-rooms update-in [gameid] dissoc roomid))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- get-free-room
"Returns a free room which is detached from the pending set"
([gameid roomid]
(locking _room-mutex_
(when-some [r (get (@free-rooms gameid) roomid)]
(detach-free-room gameid (c/id?? r))
r)))
([gameid]
(locking _room-mutex_
(when-some [[_ r] (first (@free-rooms gameid))]
(detach-free-room gameid (c/id?? r))
r))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn lookup-free-room
""
[gameid roomid]
(c/debug "looking for room(F): %s, game: %s" roomid gameid)
(get (@free-rooms gameid) roomid))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn lookup-game-room
""
[gameid roomid]
(c/debug "looking for room(A): %s, game: %s" roomid gameid)
(get (@game-rooms gameid) roomid))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- new-free-room
""
[game {:keys [source] :as options}]
(let [p (partial remove-game-room (:id game))
room (ga/arena<> game p source)]
(c/debug "created a new room(F): %s" (:id room))
room))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn connect
"Connect a player to a romm"
[room player arg]
(locking room
(let [{:keys [conns numctr]}
@room
n (. ^AtomicInteger
numctr
incrementAndGet)
s (ss/session<> room
player
(merge arg {:number n}))]
(swap! room assoc :conns (assoc conns (:id s) s))
(doto s ss/add-session))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn disconnect
"Disconnect a player from room"
[room session]
(let [{:keys [player]} @session
{:keys [conns disp]} @room]
(swap! room assoc :conns (dissoc conns (:id session)))
(ss/remove-session session)
(loki/unsub-if-session disp session)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn open-room
""
[game plyr arg]
(locking _room-mutex_
(let [room (or (get-free-room (c/id game))
(new-free-room game arg))
s (get-in arg [:body :settings])
pss (some-> room (connect plyr s))]
(when (some? pss)
(let
[ch (:socket arg)
src {:gameid (c/sname (:id game))
:roomid (:id room)
:puid (:id plyr)
:pnum (:number @pss)}
evt (nc/private-event<> loki/playreq-ok src)]
(c/open pss arg)
(cc/setattr ch u/RMSN {:room room :session pss})
(c/debug "replying msg to user: %s" (nc/pretty-event evt))
(nc/reply-event ch evt)
(nc/bcast! room
loki/player-joined
(select-keys src [:pnum :puid]))
(if (loki/can-open-room? room)
(do
(c/debug "room has enough players, can open")
(c/debug "room.canOpen = true")
(add-game-room room)
(c/open room))
(add-free-room room))))
pss)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn join-room
""
[plyr gameid roomid arg]
{:pre [(some? plyr)]}
(locking _room-mutex_
(let [room (or (lookup-game-room gameid roomid)
(get-free-room gameid roomid))
s (get-in arg [:body :settings])
game (:game (some-> room deref))
ch (:socket arg)]
(when (and room
(< (loki/count-players room)
(:maxPlayers game)))
(let [pss (connect room plyr s)
src {:gameid (c/sname (:id game))
:roomid (:id room)
:puid (:id plyr)
:pnum (:number @pss)}
evt (nc/private-event<> loki/joinreq-ok src)]
(c/open pss arg)
(cc/setattr ch u/RMSN {:room room :session pss})
(nc/reply-event ch evt)
(c/debug "replying back to user: %s" (nc/pretty-event evt))
(if (loki/can-open-room? room)
(do
(c/debug "room has enough players, can open")
(c/debug "room.canOpen = true")
(add-game-room room)
(c/open room {})
(add-free-room room))
pss))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
| 114502 | ;; 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.room
(:require [czlab.loki.xpis :as loki]
[czlab.basal.core :as c]
[czlab.basal.util :as bu]
[czlab.loki.util :as u]
[czlab.niou.core :as cc]
[czlab.loki.session :as ss]
[czlab.loki.net.core :as nc]
[czlab.loki.game.arena :as ga])
(:use [flatland.ordered.map])
(:import [clojure.lang Keyword]
[java.util.concurrent.atomic AtomicInteger]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* true)
(def ^:private _room-mutex_ (Object.))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; {game-id -> map
;; { room-id -> room }}
(def ^:private free-rooms (atom (ordered-map)))
(def ^:private game-rooms (atom (ordered-map)))
(def ^:private vacancy 1000)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn count-free-rooms
""
^long [gameid]
(count (get @free-rooms gameid)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn count-game-rooms
""
^long [gameid]
(count (get @game-rooms gameid)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn clear-free-rooms
"Internal only"
{:no-doc true}
[gameid]
(locking _room-mutex_
(swap! free-rooms assoc gameid (ordered-map))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn clear-game-rooms
"Internal only"
{:no-doc true}
[gameid]
(locking _room-mutex_
(swap! game-rooms assoc gameid (ordered-map))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- remove-xxx-room
""
[gameid roomid db dbtxt]
(locking _room-mutex_
(when-some [r (-> (@db gameid)
(get roomid))]
(c/debug "remove %s: %s, game: %s" dbtxt roomid gameid)
(swap! db update-in [gameid] dissoc roomid)
r)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn remove-game-room
"Remove an active room"
[gameid roomid]
(remove-xxx-room gameid roomid game-rooms "room(A)"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn remove-free-room
"Remove a waiting room"
[gameid roomid]
(remove-xxx-room gameid roomid free-rooms "room(F)"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- add-xxx-room
""
[room db dbt]
{:pre [(some? room)]}
(locking _room-mutex_
(let [gid (c/id (:game @room))
rid (c/id room)
m? (contains? @db gid)]
(c/debug "adding a %s: %s, game: %s" dbt rid gid)
(if m?
(swap! db update-in [gid] assoc rid room)
(swap! db assoc gid (ordered-map rid room)))
room)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- add-free-room
"Add a new partially filled room into the pending set"
[room]
(add-xxx-room room free-rooms "room(F)"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- add-game-room
"Move room into the active set"
[room]
(add-xxx-room room game-rooms "room(A)"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- detach-free-room
""
[gameid roomid]
(c/debug "%s: %s, game: %s"
"found a room(F)" roomid gameid)
(swap! free-rooms update-in [gameid] dissoc roomid))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- get-free-room
"Returns a free room which is detached from the pending set"
([gameid roomid]
(locking _room-mutex_
(when-some [r (get (@free-rooms gameid) roomid)]
(detach-free-room gameid (c/id?? r))
r)))
([gameid]
(locking _room-mutex_
(when-some [[_ r] (first (@free-rooms gameid))]
(detach-free-room gameid (c/id?? r))
r))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn lookup-free-room
""
[gameid roomid]
(c/debug "looking for room(F): %s, game: %s" roomid gameid)
(get (@free-rooms gameid) roomid))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn lookup-game-room
""
[gameid roomid]
(c/debug "looking for room(A): %s, game: %s" roomid gameid)
(get (@game-rooms gameid) roomid))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- new-free-room
""
[game {:keys [source] :as options}]
(let [p (partial remove-game-room (:id game))
room (ga/arena<> game p source)]
(c/debug "created a new room(F): %s" (:id room))
room))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn connect
"Connect a player to a romm"
[room player arg]
(locking room
(let [{:keys [conns numctr]}
@room
n (. ^AtomicInteger
numctr
incrementAndGet)
s (ss/session<> room
player
(merge arg {:number n}))]
(swap! room assoc :conns (assoc conns (:id s) s))
(doto s ss/add-session))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn disconnect
"Disconnect a player from room"
[room session]
(let [{:keys [player]} @session
{:keys [conns disp]} @room]
(swap! room assoc :conns (dissoc conns (:id session)))
(ss/remove-session session)
(loki/unsub-if-session disp session)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn open-room
""
[game plyr arg]
(locking _room-mutex_
(let [room (or (get-free-room (c/id game))
(new-free-room game arg))
s (get-in arg [:body :settings])
pss (some-> room (connect plyr s))]
(when (some? pss)
(let
[ch (:socket arg)
src {:gameid (c/sname (:id game))
:roomid (:id room)
:puid (:id plyr)
:pnum (:number @pss)}
evt (nc/private-event<> loki/playreq-ok src)]
(c/open pss arg)
(cc/setattr ch u/RMSN {:room room :session pss})
(c/debug "replying msg to user: %s" (nc/pretty-event evt))
(nc/reply-event ch evt)
(nc/bcast! room
loki/player-joined
(select-keys src [:pnum :puid]))
(if (loki/can-open-room? room)
(do
(c/debug "room has enough players, can open")
(c/debug "room.canOpen = true")
(add-game-room room)
(c/open room))
(add-free-room room))))
pss)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn join-room
""
[plyr gameid roomid arg]
{:pre [(some? plyr)]}
(locking _room-mutex_
(let [room (or (lookup-game-room gameid roomid)
(get-free-room gameid roomid))
s (get-in arg [:body :settings])
game (:game (some-> room deref))
ch (:socket arg)]
(when (and room
(< (loki/count-players room)
(:maxPlayers game)))
(let [pss (connect room plyr s)
src {:gameid (c/sname (:id game))
:roomid (:id room)
:puid (:id plyr)
:pnum (:number @pss)}
evt (nc/private-event<> loki/joinreq-ok src)]
(c/open pss arg)
(cc/setattr ch u/RMSN {:room room :session pss})
(nc/reply-event ch evt)
(c/debug "replying back to user: %s" (nc/pretty-event evt))
(if (loki/can-open-room? room)
(do
(c/debug "room has enough players, can open")
(c/debug "room.canOpen = true")
(add-game-room room)
(c/open room {})
(add-free-room room))
pss))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;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.room
(:require [czlab.loki.xpis :as loki]
[czlab.basal.core :as c]
[czlab.basal.util :as bu]
[czlab.loki.util :as u]
[czlab.niou.core :as cc]
[czlab.loki.session :as ss]
[czlab.loki.net.core :as nc]
[czlab.loki.game.arena :as ga])
(:use [flatland.ordered.map])
(:import [clojure.lang Keyword]
[java.util.concurrent.atomic AtomicInteger]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* true)
(def ^:private _room-mutex_ (Object.))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; {game-id -> map
;; { room-id -> room }}
(def ^:private free-rooms (atom (ordered-map)))
(def ^:private game-rooms (atom (ordered-map)))
(def ^:private vacancy 1000)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn count-free-rooms
""
^long [gameid]
(count (get @free-rooms gameid)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn count-game-rooms
""
^long [gameid]
(count (get @game-rooms gameid)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn clear-free-rooms
"Internal only"
{:no-doc true}
[gameid]
(locking _room-mutex_
(swap! free-rooms assoc gameid (ordered-map))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn clear-game-rooms
"Internal only"
{:no-doc true}
[gameid]
(locking _room-mutex_
(swap! game-rooms assoc gameid (ordered-map))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- remove-xxx-room
""
[gameid roomid db dbtxt]
(locking _room-mutex_
(when-some [r (-> (@db gameid)
(get roomid))]
(c/debug "remove %s: %s, game: %s" dbtxt roomid gameid)
(swap! db update-in [gameid] dissoc roomid)
r)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn remove-game-room
"Remove an active room"
[gameid roomid]
(remove-xxx-room gameid roomid game-rooms "room(A)"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn remove-free-room
"Remove a waiting room"
[gameid roomid]
(remove-xxx-room gameid roomid free-rooms "room(F)"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- add-xxx-room
""
[room db dbt]
{:pre [(some? room)]}
(locking _room-mutex_
(let [gid (c/id (:game @room))
rid (c/id room)
m? (contains? @db gid)]
(c/debug "adding a %s: %s, game: %s" dbt rid gid)
(if m?
(swap! db update-in [gid] assoc rid room)
(swap! db assoc gid (ordered-map rid room)))
room)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- add-free-room
"Add a new partially filled room into the pending set"
[room]
(add-xxx-room room free-rooms "room(F)"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- add-game-room
"Move room into the active set"
[room]
(add-xxx-room room game-rooms "room(A)"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- detach-free-room
""
[gameid roomid]
(c/debug "%s: %s, game: %s"
"found a room(F)" roomid gameid)
(swap! free-rooms update-in [gameid] dissoc roomid))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- get-free-room
"Returns a free room which is detached from the pending set"
([gameid roomid]
(locking _room-mutex_
(when-some [r (get (@free-rooms gameid) roomid)]
(detach-free-room gameid (c/id?? r))
r)))
([gameid]
(locking _room-mutex_
(when-some [[_ r] (first (@free-rooms gameid))]
(detach-free-room gameid (c/id?? r))
r))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn lookup-free-room
""
[gameid roomid]
(c/debug "looking for room(F): %s, game: %s" roomid gameid)
(get (@free-rooms gameid) roomid))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn lookup-game-room
""
[gameid roomid]
(c/debug "looking for room(A): %s, game: %s" roomid gameid)
(get (@game-rooms gameid) roomid))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- new-free-room
""
[game {:keys [source] :as options}]
(let [p (partial remove-game-room (:id game))
room (ga/arena<> game p source)]
(c/debug "created a new room(F): %s" (:id room))
room))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn connect
"Connect a player to a romm"
[room player arg]
(locking room
(let [{:keys [conns numctr]}
@room
n (. ^AtomicInteger
numctr
incrementAndGet)
s (ss/session<> room
player
(merge arg {:number n}))]
(swap! room assoc :conns (assoc conns (:id s) s))
(doto s ss/add-session))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn disconnect
"Disconnect a player from room"
[room session]
(let [{:keys [player]} @session
{:keys [conns disp]} @room]
(swap! room assoc :conns (dissoc conns (:id session)))
(ss/remove-session session)
(loki/unsub-if-session disp session)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn open-room
""
[game plyr arg]
(locking _room-mutex_
(let [room (or (get-free-room (c/id game))
(new-free-room game arg))
s (get-in arg [:body :settings])
pss (some-> room (connect plyr s))]
(when (some? pss)
(let
[ch (:socket arg)
src {:gameid (c/sname (:id game))
:roomid (:id room)
:puid (:id plyr)
:pnum (:number @pss)}
evt (nc/private-event<> loki/playreq-ok src)]
(c/open pss arg)
(cc/setattr ch u/RMSN {:room room :session pss})
(c/debug "replying msg to user: %s" (nc/pretty-event evt))
(nc/reply-event ch evt)
(nc/bcast! room
loki/player-joined
(select-keys src [:pnum :puid]))
(if (loki/can-open-room? room)
(do
(c/debug "room has enough players, can open")
(c/debug "room.canOpen = true")
(add-game-room room)
(c/open room))
(add-free-room room))))
pss)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn join-room
""
[plyr gameid roomid arg]
{:pre [(some? plyr)]}
(locking _room-mutex_
(let [room (or (lookup-game-room gameid roomid)
(get-free-room gameid roomid))
s (get-in arg [:body :settings])
game (:game (some-> room deref))
ch (:socket arg)]
(when (and room
(< (loki/count-players room)
(:maxPlayers game)))
(let [pss (connect room plyr s)
src {:gameid (c/sname (:id game))
:roomid (:id room)
:puid (:id plyr)
:pnum (:number @pss)}
evt (nc/private-event<> loki/joinreq-ok src)]
(c/open pss arg)
(cc/setattr ch u/RMSN {:room room :session pss})
(nc/reply-event ch evt)
(c/debug "replying back to user: %s" (nc/pretty-event evt))
(if (loki/can-open-room? room)
(do
(c/debug "room has enough players, can open")
(c/debug "room.canOpen = true")
(add-game-room room)
(c/open room {})
(add-free-room room))
pss))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
|
[
{
"context": ";; Copyright Fabian Schneider and Gunnar Völkel © 2014-2020\n;;\n;; Permission is",
"end": 29,
"score": 0.9998418688774109,
"start": 13,
"tag": "NAME",
"value": "Fabian Schneider"
},
{
"context": ";; Copyright Fabian Schneider and Gunnar Völkel © 2014-2020\n;;\n;; Permission is hereby granted, f",
"end": 47,
"score": 0.9998360276222229,
"start": 34,
"tag": "NAME",
"value": "Gunnar Völkel"
}
] | src/traqbio/routes.clj | sysbio-bioinf/iBioTraq | 2 | ;; Copyright Fabian Schneider and Gunnar Völkel © 2014-2020
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
;; THE SOFTWARE.
(ns traqbio.routes
(:require
[clojure.string :as str]
[ring.util.response :as response]
[ring.middleware.json :as json]
[ring.middleware.multipart-params :as mp]
[ring.middleware.content-type :refer [wrap-content-type]]
[ring.middleware.not-modified :refer [wrap-not-modified]]
[compojure.core :as core]
[compojure.route :as route]
[cemerick.friend :as friend]
[selmer.parser :as parser]
[clojure.tools.logging :as log]
[clojure.stacktrace :refer [print-cause-trace]]
[traqbio.templates :as templates]
[traqbio.api :as api]
[traqbio.db.crud :as db]
[traqbio.actions.user :as user-action]
[traqbio.actions.project :as project-action]
[traqbio.config :as c]
[traqbio.actions.templates :as templ-api]
[traqbio.runtime :as runtime])
(:gen-class))
(defn shutdown-page
[]
{:status 503
:headers {"Content-Type" "text/html"}
:body (parser/render-file "templates/shutdown.html" (templates/add-server-root {}))})
; Define routes
(core/defroutes system-routes
(core/POST "/stop" req
(runtime/stop-server)
(shutdown-page)))
(core/defroutes user-routes
(core/GET "/" request (templates/user-list request (db/read-users)))
(core/PUT ["/:name"] [name :as request] (user-action/update-user (:body request)))
(core/POST "/" request (user-action/create-user (:body request)))
(core/DELETE ["/:name"] [name] (user-action/delete-user name))
(core/GET ["/:name"] [name :as request] (templates/get-user request (db/read-user name))))
(core/defroutes project-routes
(core/context "/edit" []
(core/GET "/" request (templates/project-edit-list request (db/read-current-projects)))
(core/GET "/" request (templates/textmodule-list request (db/read-text-modules))) ;using "/1" breaks rendering of steps
(core/GET ["/:id", :id #"[0-9]+"] [id :as request]
(if-let [project (db/read-project id)]
(if (= (:done project) 1)
(ring.util.response/redirect (c/server-location (format "/prj/view/%s" id)))
(templates/project-edit request, project))
(templates/not-found)))
(core/PUT ["/:id", :id #"[0-9]+"] [id :as request] (project-action/update-project (:body request)))
(core/DELETE ["/:id", :id #"[0-9]+"] [id] (project-action/delete-project id)));end of /edit context
(core/context "/view" []
(core/GET "/" request (templates/finished-project-list request (db/read-finished-projects)))
(core/GET ["/:pId", :pId #"[0-9]+"] [pId :as request]
(templates/finished-project request (db/read-project pId))))
(core/context "/create" []
(core/GET "/" request (templates/project-create request (db/read-templates)))
(core/POST "/" request (project-action/create-project (:body request)))
(mp/wrap-multipart-params
(core/POST "/upload" {params :params} (project-action/upload (:file params) (:trackingnr params))))))
(core/defroutes template-api-routes
(core/GET ["/:tmplId", :tmplId #"[0-9]+"] [tmplId]
(templ-api/get-template tmplId))
(core/PUT ["/:tmplId", :tmplId #"[0-9]+"] [tmplId :as request]
(templ-api/update-template (:body request)))
(core/DELETE ["/:tmplId", :tmplId #"[0-9]+"] [tmplId]
(templ-api/delete-template tmplId))
(core/context "/edit" []
(core/GET ["/:tmplId", :tmplId #"[0-9]+"] [tmplId :as request]
(if-let [template (db/read-template tmplId)]
(templates/template-edit request, template)
(templates/not-found))))
(core/context "/create" []
(core/GET "/" request
(templates/template-create request (db/read-templates)))
(core/POST "/" request
(templ-api/create-template (:body request))))
(core/GET "/list" request (templates/template-list request (db/read-templates)))
)
(core/defroutes api-routes
(core/context "/prj" []
(friend/wrap-authorize project-routes, #{::c/user}))
(core/context "/template" []
(friend/wrap-authorize template-api-routes, #{::c/user}))
(core/context "/usr" []
(friend/wrap-authorize user-routes, #{::c/admin}))
(core/context "/system" []
(friend/wrap-authorize system-routes, #{::c/admin})))
(core/defroutes script-api-routes
(core/context "/api" []
(friend/wrap-authorize
(core/routes
(core/GET "/active-project-list" []
(api/active-projects))
(core/context "/project/:project-id" [project-id]
(core/GET "/is-active-step" request
(api/is-active-step project-id, request))
(core/GET "/sample-sheet" []
(api/sample-sheet project-id))
(core/POST "/finish-step/:step-id" [step-id :as request]
(api/finish-step project-id, step-id, request))))
#{::c/user})))
(defn wrap-cache-control
[handler]
(fn [request]
(let [response (handler request)]
(some-> response
(update-in [:headers]
#(merge {"Cache-Control" "max-age=60, must-revalidate"} %))))))
; Compose routes
(defn app-routes
[]
(core/routes
(core/GET ["/track/:trackingNr"] [trackingNr :as request] (templates/tracking request, trackingNr))
(wrap-cache-control (wrap-not-modified (wrap-content-type (route/resources "/"))))
(core/GET "/resetrequest" request (templates/reset-request-view request))
(core/POST "/resetrequest" request (templates/reset-request-view request,
(merge
{:reset-requested? true}
(user-action/request-password-reset request))))
(core/GET ["/reset/:resetId", :resetId #"[-0-9A-F]+"] [resetId :as request]
(when-let [reset-data (db/password-reset-data-by-id resetId)]
(templates/reset-password-view reset-data)))
(core/POST ["/reset/:resetId", :resetId #"[-0-9A-F]+"], [resetId :as request]
(when-let [reset-data (db/password-reset-data-by-id resetId)]
(templates/reset-password-view reset-data,
(assoc (user-action/reset-password request, reset-data)
:reset-completed? true))))
(core/GET "/login" request (templates/login request))
(friend/logout (core/ANY "/logout" request (ring.util.response/redirect (c/server-location "/"))))
(core/context "/timeline" []
(friend/wrap-authorize
(core/routes
(core/GET "/" request (templates/timeline request))),
#{::c/user}))
(core/context "/doc" []
(friend/wrap-authorize
(core/routes
(core/GET "/:trackingnr/:filename"
[trackingnr filename]
(response/file-response (str (c/upload-path) trackingnr "/" filename)))),
#{::c/user}))
(json/wrap-json-response
(json/wrap-json-body api-routes {:keywords? true}))
script-api-routes
(core/GET "/" request (ring.util.response/redirect (c/server-location "/timeline")))
(route/not-found (templates/not-found))))
(defn unauthorized-handler
[req]
{:status 401
:headers {"Content-Type" "text/html"}
:body (parser/render-file "templates/unauthorized.html" (templates/add-server-root {}))})
(defn shutdown-routes
[]
(core/routes
(route/resources "/")
(route/not-found (shutdown-page))))
(defn use-server-root
"If a server root directory is given, then use this as prefix for all routes."
[server-root, routes]
(if (str/blank? server-root)
routes
(core/routes
(core/context (c/server-location "", true) [] routes)
(route/not-found (templates/not-found)))))
(defn wrap-uncaught-exception-logging
"The given handler will be wrapped in a try catch that logs all exceptions."
[handler]
(fn [request]
(try
(handler request)
(catch Throwable t
(let [{:keys [uri, request-method]} request]
(log/errorf "Caught exception for request \"%s %s\":\n%s"
(some-> request-method name str/upper-case)
uri
(with-out-str (print-cause-trace t)))
{:status 500,
:headers {"Content-Type" "text/html"}
:body (templates/error)})))))
| 33016 | ;; Copyright <NAME> and <NAME> © 2014-2020
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
;; THE SOFTWARE.
(ns traqbio.routes
(:require
[clojure.string :as str]
[ring.util.response :as response]
[ring.middleware.json :as json]
[ring.middleware.multipart-params :as mp]
[ring.middleware.content-type :refer [wrap-content-type]]
[ring.middleware.not-modified :refer [wrap-not-modified]]
[compojure.core :as core]
[compojure.route :as route]
[cemerick.friend :as friend]
[selmer.parser :as parser]
[clojure.tools.logging :as log]
[clojure.stacktrace :refer [print-cause-trace]]
[traqbio.templates :as templates]
[traqbio.api :as api]
[traqbio.db.crud :as db]
[traqbio.actions.user :as user-action]
[traqbio.actions.project :as project-action]
[traqbio.config :as c]
[traqbio.actions.templates :as templ-api]
[traqbio.runtime :as runtime])
(:gen-class))
(defn shutdown-page
[]
{:status 503
:headers {"Content-Type" "text/html"}
:body (parser/render-file "templates/shutdown.html" (templates/add-server-root {}))})
; Define routes
(core/defroutes system-routes
(core/POST "/stop" req
(runtime/stop-server)
(shutdown-page)))
(core/defroutes user-routes
(core/GET "/" request (templates/user-list request (db/read-users)))
(core/PUT ["/:name"] [name :as request] (user-action/update-user (:body request)))
(core/POST "/" request (user-action/create-user (:body request)))
(core/DELETE ["/:name"] [name] (user-action/delete-user name))
(core/GET ["/:name"] [name :as request] (templates/get-user request (db/read-user name))))
(core/defroutes project-routes
(core/context "/edit" []
(core/GET "/" request (templates/project-edit-list request (db/read-current-projects)))
(core/GET "/" request (templates/textmodule-list request (db/read-text-modules))) ;using "/1" breaks rendering of steps
(core/GET ["/:id", :id #"[0-9]+"] [id :as request]
(if-let [project (db/read-project id)]
(if (= (:done project) 1)
(ring.util.response/redirect (c/server-location (format "/prj/view/%s" id)))
(templates/project-edit request, project))
(templates/not-found)))
(core/PUT ["/:id", :id #"[0-9]+"] [id :as request] (project-action/update-project (:body request)))
(core/DELETE ["/:id", :id #"[0-9]+"] [id] (project-action/delete-project id)));end of /edit context
(core/context "/view" []
(core/GET "/" request (templates/finished-project-list request (db/read-finished-projects)))
(core/GET ["/:pId", :pId #"[0-9]+"] [pId :as request]
(templates/finished-project request (db/read-project pId))))
(core/context "/create" []
(core/GET "/" request (templates/project-create request (db/read-templates)))
(core/POST "/" request (project-action/create-project (:body request)))
(mp/wrap-multipart-params
(core/POST "/upload" {params :params} (project-action/upload (:file params) (:trackingnr params))))))
(core/defroutes template-api-routes
(core/GET ["/:tmplId", :tmplId #"[0-9]+"] [tmplId]
(templ-api/get-template tmplId))
(core/PUT ["/:tmplId", :tmplId #"[0-9]+"] [tmplId :as request]
(templ-api/update-template (:body request)))
(core/DELETE ["/:tmplId", :tmplId #"[0-9]+"] [tmplId]
(templ-api/delete-template tmplId))
(core/context "/edit" []
(core/GET ["/:tmplId", :tmplId #"[0-9]+"] [tmplId :as request]
(if-let [template (db/read-template tmplId)]
(templates/template-edit request, template)
(templates/not-found))))
(core/context "/create" []
(core/GET "/" request
(templates/template-create request (db/read-templates)))
(core/POST "/" request
(templ-api/create-template (:body request))))
(core/GET "/list" request (templates/template-list request (db/read-templates)))
)
(core/defroutes api-routes
(core/context "/prj" []
(friend/wrap-authorize project-routes, #{::c/user}))
(core/context "/template" []
(friend/wrap-authorize template-api-routes, #{::c/user}))
(core/context "/usr" []
(friend/wrap-authorize user-routes, #{::c/admin}))
(core/context "/system" []
(friend/wrap-authorize system-routes, #{::c/admin})))
(core/defroutes script-api-routes
(core/context "/api" []
(friend/wrap-authorize
(core/routes
(core/GET "/active-project-list" []
(api/active-projects))
(core/context "/project/:project-id" [project-id]
(core/GET "/is-active-step" request
(api/is-active-step project-id, request))
(core/GET "/sample-sheet" []
(api/sample-sheet project-id))
(core/POST "/finish-step/:step-id" [step-id :as request]
(api/finish-step project-id, step-id, request))))
#{::c/user})))
(defn wrap-cache-control
[handler]
(fn [request]
(let [response (handler request)]
(some-> response
(update-in [:headers]
#(merge {"Cache-Control" "max-age=60, must-revalidate"} %))))))
; Compose routes
(defn app-routes
[]
(core/routes
(core/GET ["/track/:trackingNr"] [trackingNr :as request] (templates/tracking request, trackingNr))
(wrap-cache-control (wrap-not-modified (wrap-content-type (route/resources "/"))))
(core/GET "/resetrequest" request (templates/reset-request-view request))
(core/POST "/resetrequest" request (templates/reset-request-view request,
(merge
{:reset-requested? true}
(user-action/request-password-reset request))))
(core/GET ["/reset/:resetId", :resetId #"[-0-9A-F]+"] [resetId :as request]
(when-let [reset-data (db/password-reset-data-by-id resetId)]
(templates/reset-password-view reset-data)))
(core/POST ["/reset/:resetId", :resetId #"[-0-9A-F]+"], [resetId :as request]
(when-let [reset-data (db/password-reset-data-by-id resetId)]
(templates/reset-password-view reset-data,
(assoc (user-action/reset-password request, reset-data)
:reset-completed? true))))
(core/GET "/login" request (templates/login request))
(friend/logout (core/ANY "/logout" request (ring.util.response/redirect (c/server-location "/"))))
(core/context "/timeline" []
(friend/wrap-authorize
(core/routes
(core/GET "/" request (templates/timeline request))),
#{::c/user}))
(core/context "/doc" []
(friend/wrap-authorize
(core/routes
(core/GET "/:trackingnr/:filename"
[trackingnr filename]
(response/file-response (str (c/upload-path) trackingnr "/" filename)))),
#{::c/user}))
(json/wrap-json-response
(json/wrap-json-body api-routes {:keywords? true}))
script-api-routes
(core/GET "/" request (ring.util.response/redirect (c/server-location "/timeline")))
(route/not-found (templates/not-found))))
(defn unauthorized-handler
[req]
{:status 401
:headers {"Content-Type" "text/html"}
:body (parser/render-file "templates/unauthorized.html" (templates/add-server-root {}))})
(defn shutdown-routes
[]
(core/routes
(route/resources "/")
(route/not-found (shutdown-page))))
(defn use-server-root
"If a server root directory is given, then use this as prefix for all routes."
[server-root, routes]
(if (str/blank? server-root)
routes
(core/routes
(core/context (c/server-location "", true) [] routes)
(route/not-found (templates/not-found)))))
(defn wrap-uncaught-exception-logging
"The given handler will be wrapped in a try catch that logs all exceptions."
[handler]
(fn [request]
(try
(handler request)
(catch Throwable t
(let [{:keys [uri, request-method]} request]
(log/errorf "Caught exception for request \"%s %s\":\n%s"
(some-> request-method name str/upper-case)
uri
(with-out-str (print-cause-trace t)))
{:status 500,
:headers {"Content-Type" "text/html"}
:body (templates/error)})))))
| true | ;; Copyright PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI © 2014-2020
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in
;; all copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
;; THE SOFTWARE.
(ns traqbio.routes
(:require
[clojure.string :as str]
[ring.util.response :as response]
[ring.middleware.json :as json]
[ring.middleware.multipart-params :as mp]
[ring.middleware.content-type :refer [wrap-content-type]]
[ring.middleware.not-modified :refer [wrap-not-modified]]
[compojure.core :as core]
[compojure.route :as route]
[cemerick.friend :as friend]
[selmer.parser :as parser]
[clojure.tools.logging :as log]
[clojure.stacktrace :refer [print-cause-trace]]
[traqbio.templates :as templates]
[traqbio.api :as api]
[traqbio.db.crud :as db]
[traqbio.actions.user :as user-action]
[traqbio.actions.project :as project-action]
[traqbio.config :as c]
[traqbio.actions.templates :as templ-api]
[traqbio.runtime :as runtime])
(:gen-class))
(defn shutdown-page
[]
{:status 503
:headers {"Content-Type" "text/html"}
:body (parser/render-file "templates/shutdown.html" (templates/add-server-root {}))})
; Define routes
(core/defroutes system-routes
(core/POST "/stop" req
(runtime/stop-server)
(shutdown-page)))
(core/defroutes user-routes
(core/GET "/" request (templates/user-list request (db/read-users)))
(core/PUT ["/:name"] [name :as request] (user-action/update-user (:body request)))
(core/POST "/" request (user-action/create-user (:body request)))
(core/DELETE ["/:name"] [name] (user-action/delete-user name))
(core/GET ["/:name"] [name :as request] (templates/get-user request (db/read-user name))))
(core/defroutes project-routes
(core/context "/edit" []
(core/GET "/" request (templates/project-edit-list request (db/read-current-projects)))
(core/GET "/" request (templates/textmodule-list request (db/read-text-modules))) ;using "/1" breaks rendering of steps
(core/GET ["/:id", :id #"[0-9]+"] [id :as request]
(if-let [project (db/read-project id)]
(if (= (:done project) 1)
(ring.util.response/redirect (c/server-location (format "/prj/view/%s" id)))
(templates/project-edit request, project))
(templates/not-found)))
(core/PUT ["/:id", :id #"[0-9]+"] [id :as request] (project-action/update-project (:body request)))
(core/DELETE ["/:id", :id #"[0-9]+"] [id] (project-action/delete-project id)));end of /edit context
(core/context "/view" []
(core/GET "/" request (templates/finished-project-list request (db/read-finished-projects)))
(core/GET ["/:pId", :pId #"[0-9]+"] [pId :as request]
(templates/finished-project request (db/read-project pId))))
(core/context "/create" []
(core/GET "/" request (templates/project-create request (db/read-templates)))
(core/POST "/" request (project-action/create-project (:body request)))
(mp/wrap-multipart-params
(core/POST "/upload" {params :params} (project-action/upload (:file params) (:trackingnr params))))))
(core/defroutes template-api-routes
(core/GET ["/:tmplId", :tmplId #"[0-9]+"] [tmplId]
(templ-api/get-template tmplId))
(core/PUT ["/:tmplId", :tmplId #"[0-9]+"] [tmplId :as request]
(templ-api/update-template (:body request)))
(core/DELETE ["/:tmplId", :tmplId #"[0-9]+"] [tmplId]
(templ-api/delete-template tmplId))
(core/context "/edit" []
(core/GET ["/:tmplId", :tmplId #"[0-9]+"] [tmplId :as request]
(if-let [template (db/read-template tmplId)]
(templates/template-edit request, template)
(templates/not-found))))
(core/context "/create" []
(core/GET "/" request
(templates/template-create request (db/read-templates)))
(core/POST "/" request
(templ-api/create-template (:body request))))
(core/GET "/list" request (templates/template-list request (db/read-templates)))
)
(core/defroutes api-routes
(core/context "/prj" []
(friend/wrap-authorize project-routes, #{::c/user}))
(core/context "/template" []
(friend/wrap-authorize template-api-routes, #{::c/user}))
(core/context "/usr" []
(friend/wrap-authorize user-routes, #{::c/admin}))
(core/context "/system" []
(friend/wrap-authorize system-routes, #{::c/admin})))
(core/defroutes script-api-routes
(core/context "/api" []
(friend/wrap-authorize
(core/routes
(core/GET "/active-project-list" []
(api/active-projects))
(core/context "/project/:project-id" [project-id]
(core/GET "/is-active-step" request
(api/is-active-step project-id, request))
(core/GET "/sample-sheet" []
(api/sample-sheet project-id))
(core/POST "/finish-step/:step-id" [step-id :as request]
(api/finish-step project-id, step-id, request))))
#{::c/user})))
(defn wrap-cache-control
[handler]
(fn [request]
(let [response (handler request)]
(some-> response
(update-in [:headers]
#(merge {"Cache-Control" "max-age=60, must-revalidate"} %))))))
; Compose routes
(defn app-routes
[]
(core/routes
(core/GET ["/track/:trackingNr"] [trackingNr :as request] (templates/tracking request, trackingNr))
(wrap-cache-control (wrap-not-modified (wrap-content-type (route/resources "/"))))
(core/GET "/resetrequest" request (templates/reset-request-view request))
(core/POST "/resetrequest" request (templates/reset-request-view request,
(merge
{:reset-requested? true}
(user-action/request-password-reset request))))
(core/GET ["/reset/:resetId", :resetId #"[-0-9A-F]+"] [resetId :as request]
(when-let [reset-data (db/password-reset-data-by-id resetId)]
(templates/reset-password-view reset-data)))
(core/POST ["/reset/:resetId", :resetId #"[-0-9A-F]+"], [resetId :as request]
(when-let [reset-data (db/password-reset-data-by-id resetId)]
(templates/reset-password-view reset-data,
(assoc (user-action/reset-password request, reset-data)
:reset-completed? true))))
(core/GET "/login" request (templates/login request))
(friend/logout (core/ANY "/logout" request (ring.util.response/redirect (c/server-location "/"))))
(core/context "/timeline" []
(friend/wrap-authorize
(core/routes
(core/GET "/" request (templates/timeline request))),
#{::c/user}))
(core/context "/doc" []
(friend/wrap-authorize
(core/routes
(core/GET "/:trackingnr/:filename"
[trackingnr filename]
(response/file-response (str (c/upload-path) trackingnr "/" filename)))),
#{::c/user}))
(json/wrap-json-response
(json/wrap-json-body api-routes {:keywords? true}))
script-api-routes
(core/GET "/" request (ring.util.response/redirect (c/server-location "/timeline")))
(route/not-found (templates/not-found))))
(defn unauthorized-handler
[req]
{:status 401
:headers {"Content-Type" "text/html"}
:body (parser/render-file "templates/unauthorized.html" (templates/add-server-root {}))})
(defn shutdown-routes
[]
(core/routes
(route/resources "/")
(route/not-found (shutdown-page))))
(defn use-server-root
"If a server root directory is given, then use this as prefix for all routes."
[server-root, routes]
(if (str/blank? server-root)
routes
(core/routes
(core/context (c/server-location "", true) [] routes)
(route/not-found (templates/not-found)))))
(defn wrap-uncaught-exception-logging
"The given handler will be wrapped in a try catch that logs all exceptions."
[handler]
(fn [request]
(try
(handler request)
(catch Throwable t
(let [{:keys [uri, request-method]} request]
(log/errorf "Caught exception for request \"%s %s\":\n%s"
(some-> request-method name str/upper-case)
uri
(with-out-str (print-cause-trace t)))
{:status 500,
:headers {"Content-Type" "text/html"}
:body (templates/error)})))))
|
[
{
"context": "hal/add-link :ea:admin {:href \"/admins/2\" :title \"Fred\"})\n (hal/add-link :ea:admin {:href \"/a",
"end": 691,
"score": 0.999713659286499,
"start": 687,
"tag": "NAME",
"value": "Fred"
},
{
"context": "hal/add-link :ea:admin {:href \"/admins/5\" :title \"Kate\"})\n (hal/add-resource :ea:order (-> (h",
"end": 762,
"score": 0.9996219873428345,
"start": 758,
"tag": "NAME",
"value": "Kate"
},
{
"context": " :ea:admin [{:href \"/admins/2\" :title \"Fred\"}\n {:",
"end": 2520,
"score": 0.9997918605804443,
"start": 2516,
"tag": "NAME",
"value": "Fred"
},
{
"context": " {:href \"/admins/5\" :title \"Kate\"}]}\n :_embedded {:ea:order [",
"end": 2599,
"score": 0.999822735786438,
"start": 2595,
"tag": "NAME",
"value": "Kate"
}
] | test/halboy/json_test.clj | alexparlett/halboy | 0 | (ns halboy.json-test
(:require
[clojure.test :refer :all]
[halboy.resource :as hal]
[halboy.json :as haljson]
[cheshire.core :as json]))
(deftest halboy-json
(let [resource
(-> (hal/new-resource)
(hal/add-link :self "/orders")
(hal/add-link :curies {:name "ea",
:href "http://example.com/docs/rels/{rel}",
:templated true})
(hal/add-link :next "/orders?page=2")
(hal/add-link :ea:find {:href "/orders{?id}",
:templated true})
(hal/add-link :ea:admin {:href "/admins/2" :title "Fred"})
(hal/add-link :ea:admin {:href "/admins/5" :title "Kate"})
(hal/add-resource :ea:order (-> (hal/new-resource "/orders/123")
(hal/add-links {:ea:basket "/baskets/98712"
:ea:customer "/customers/7809"})
(hal/add-properties {:total 30.0
:currency "USD"
:status "shipped"})))
(hal/add-resource :ea:order (-> (hal/new-resource "/orders/124")
(hal/add-links {:ea:basket "/baskets/97213"
:ea:customer "/customers/12369"})
(hal/add-properties {:total 20.0,
:currency "USD",
:status "processing"})))
(hal/add-property :currently-processing 14)
(hal/add-property :shipped-today 20))
json-representation
(json/generate-string
{:_links {:self {:href "/orders"},
:curies {:name "ea",
:href "http://example.com/docs/rels/{rel}",
:templated true},
:next {:href "/orders?page=2"},
:ea:find {:href "/orders{?id}",
:templated true},
:ea:admin [{:href "/admins/2" :title "Fred"}
{:href "/admins/5" :title "Kate"}]}
:_embedded {:ea:order [(merge
{:_links {:self {:href "/orders/123"},
:ea:basket {:href "/baskets/98712"},
:ea:customer {:href "/customers/7809"}}}
{:total 30.0,
:currency "USD",
:status "shipped"})
(merge
{:_links {:self {:href "/orders/124"},
:ea:basket {:href "/baskets/97213"},
:ea:customer {:href "/customers/12369"}}}
{:total 20.0,
:currency "USD",
:status "processing"})]}
:currently-processing 14
:shipped-today 20})]
(testing "resource->json should marshal a resource into some json"
(is (= json-representation
(haljson/resource->json resource))))
(testing "json->resource should parse some json into a resource"
(is (= resource
(haljson/json->resource json-representation)))))
(testing "map->resource should parse links"
(is (= (hal/new-resource "/orders")
(haljson/map->resource {:_links {:self {:href "/orders"}}}))))
(testing "map->resource should include all information about a link"
(is (= (-> (hal/new-resource)
(hal/add-link :ea:find {:href "/orders{?id}",
:templated true}))
(haljson/map->resource {:_links {:ea:find {:href "/orders{?id}",
:templated true}}}))))
(testing "map->resource should parse arrays of links"
(is (= (-> (hal/new-resource)
(hal/add-links :ea:admin "/admins/2"
:ea:admin "/admins/5"))
(haljson/map->resource {:_links {:ea:admin [{:href "/admins/2"}
{:href "/admins/5"}]}}))))
(testing "map->resource should parse embedded resources"
(let [order-resource (hal/new-resource "/orders/123")]
(is (= (-> (hal/new-resource)
(hal/add-resource :ea:order order-resource))
(haljson/map->resource {:_embedded {:ea:order {:_links {:self {:href "/orders/123"}}}}})))))
(testing "map->resource should parse doubly embedded resources"
(let [purchaser-resource (hal/new-resource "/customers/1")
order-resource (-> (hal/new-resource "/orders/123")
(hal/add-resource :customer purchaser-resource))]
(is (= (-> (hal/new-resource)
(hal/add-resource :ea:order order-resource))
(haljson/map->resource {:_embedded {:ea:order {:_links {:self {:href "/orders/123"}}
:_embedded {:customer {:_links {:self {:href "/customers/1"}}}}}}})))))
(testing "map->resource should parse arrays of embedded resources"
(let [first-order (hal/new-resource "/orders/123")
second-order (hal/new-resource "/orders/124")]
(is (= (-> (hal/new-resource)
(hal/add-resources :ea:order first-order
:ea:order second-order))
(haljson/map->resource {:_embedded {:ea:order [{:_links {:self {:href "/orders/123"}}}
{:_links {:self {:href "/orders/124"}}}]}})))))
(testing "map->resource should parse properties"
(is (= (-> (hal/new-resource)
(hal/add-property :total 20.0))
(haljson/map->resource {:total 20.0}))))
(testing "resource->map should render doubly embedded resources"
(let [purchaser-resource (hal/new-resource "/customers/1")
order-resource (-> (hal/new-resource "/orders/123")
(hal/add-resource :customer purchaser-resource))]
(is (= (-> (hal/new-resource)
(hal/add-resource :ea:order order-resource)
(haljson/resource->map))
{:_embedded {:ea:order {:_links {:self {:href "/orders/123"}}
:_embedded {:customer {:_links {:self {:href "/customers/1"}}}}}}}))))
(testing "json->resource should throw an exception when the string is not valid json"
(is (thrown? clojure.lang.ExceptionInfo
(haljson/json->resource
"Not valid JSON!"))))) | 121471 | (ns halboy.json-test
(:require
[clojure.test :refer :all]
[halboy.resource :as hal]
[halboy.json :as haljson]
[cheshire.core :as json]))
(deftest halboy-json
(let [resource
(-> (hal/new-resource)
(hal/add-link :self "/orders")
(hal/add-link :curies {:name "ea",
:href "http://example.com/docs/rels/{rel}",
:templated true})
(hal/add-link :next "/orders?page=2")
(hal/add-link :ea:find {:href "/orders{?id}",
:templated true})
(hal/add-link :ea:admin {:href "/admins/2" :title "<NAME>"})
(hal/add-link :ea:admin {:href "/admins/5" :title "<NAME>"})
(hal/add-resource :ea:order (-> (hal/new-resource "/orders/123")
(hal/add-links {:ea:basket "/baskets/98712"
:ea:customer "/customers/7809"})
(hal/add-properties {:total 30.0
:currency "USD"
:status "shipped"})))
(hal/add-resource :ea:order (-> (hal/new-resource "/orders/124")
(hal/add-links {:ea:basket "/baskets/97213"
:ea:customer "/customers/12369"})
(hal/add-properties {:total 20.0,
:currency "USD",
:status "processing"})))
(hal/add-property :currently-processing 14)
(hal/add-property :shipped-today 20))
json-representation
(json/generate-string
{:_links {:self {:href "/orders"},
:curies {:name "ea",
:href "http://example.com/docs/rels/{rel}",
:templated true},
:next {:href "/orders?page=2"},
:ea:find {:href "/orders{?id}",
:templated true},
:ea:admin [{:href "/admins/2" :title "<NAME>"}
{:href "/admins/5" :title "<NAME>"}]}
:_embedded {:ea:order [(merge
{:_links {:self {:href "/orders/123"},
:ea:basket {:href "/baskets/98712"},
:ea:customer {:href "/customers/7809"}}}
{:total 30.0,
:currency "USD",
:status "shipped"})
(merge
{:_links {:self {:href "/orders/124"},
:ea:basket {:href "/baskets/97213"},
:ea:customer {:href "/customers/12369"}}}
{:total 20.0,
:currency "USD",
:status "processing"})]}
:currently-processing 14
:shipped-today 20})]
(testing "resource->json should marshal a resource into some json"
(is (= json-representation
(haljson/resource->json resource))))
(testing "json->resource should parse some json into a resource"
(is (= resource
(haljson/json->resource json-representation)))))
(testing "map->resource should parse links"
(is (= (hal/new-resource "/orders")
(haljson/map->resource {:_links {:self {:href "/orders"}}}))))
(testing "map->resource should include all information about a link"
(is (= (-> (hal/new-resource)
(hal/add-link :ea:find {:href "/orders{?id}",
:templated true}))
(haljson/map->resource {:_links {:ea:find {:href "/orders{?id}",
:templated true}}}))))
(testing "map->resource should parse arrays of links"
(is (= (-> (hal/new-resource)
(hal/add-links :ea:admin "/admins/2"
:ea:admin "/admins/5"))
(haljson/map->resource {:_links {:ea:admin [{:href "/admins/2"}
{:href "/admins/5"}]}}))))
(testing "map->resource should parse embedded resources"
(let [order-resource (hal/new-resource "/orders/123")]
(is (= (-> (hal/new-resource)
(hal/add-resource :ea:order order-resource))
(haljson/map->resource {:_embedded {:ea:order {:_links {:self {:href "/orders/123"}}}}})))))
(testing "map->resource should parse doubly embedded resources"
(let [purchaser-resource (hal/new-resource "/customers/1")
order-resource (-> (hal/new-resource "/orders/123")
(hal/add-resource :customer purchaser-resource))]
(is (= (-> (hal/new-resource)
(hal/add-resource :ea:order order-resource))
(haljson/map->resource {:_embedded {:ea:order {:_links {:self {:href "/orders/123"}}
:_embedded {:customer {:_links {:self {:href "/customers/1"}}}}}}})))))
(testing "map->resource should parse arrays of embedded resources"
(let [first-order (hal/new-resource "/orders/123")
second-order (hal/new-resource "/orders/124")]
(is (= (-> (hal/new-resource)
(hal/add-resources :ea:order first-order
:ea:order second-order))
(haljson/map->resource {:_embedded {:ea:order [{:_links {:self {:href "/orders/123"}}}
{:_links {:self {:href "/orders/124"}}}]}})))))
(testing "map->resource should parse properties"
(is (= (-> (hal/new-resource)
(hal/add-property :total 20.0))
(haljson/map->resource {:total 20.0}))))
(testing "resource->map should render doubly embedded resources"
(let [purchaser-resource (hal/new-resource "/customers/1")
order-resource (-> (hal/new-resource "/orders/123")
(hal/add-resource :customer purchaser-resource))]
(is (= (-> (hal/new-resource)
(hal/add-resource :ea:order order-resource)
(haljson/resource->map))
{:_embedded {:ea:order {:_links {:self {:href "/orders/123"}}
:_embedded {:customer {:_links {:self {:href "/customers/1"}}}}}}}))))
(testing "json->resource should throw an exception when the string is not valid json"
(is (thrown? clojure.lang.ExceptionInfo
(haljson/json->resource
"Not valid JSON!"))))) | true | (ns halboy.json-test
(:require
[clojure.test :refer :all]
[halboy.resource :as hal]
[halboy.json :as haljson]
[cheshire.core :as json]))
(deftest halboy-json
(let [resource
(-> (hal/new-resource)
(hal/add-link :self "/orders")
(hal/add-link :curies {:name "ea",
:href "http://example.com/docs/rels/{rel}",
:templated true})
(hal/add-link :next "/orders?page=2")
(hal/add-link :ea:find {:href "/orders{?id}",
:templated true})
(hal/add-link :ea:admin {:href "/admins/2" :title "PI:NAME:<NAME>END_PI"})
(hal/add-link :ea:admin {:href "/admins/5" :title "PI:NAME:<NAME>END_PI"})
(hal/add-resource :ea:order (-> (hal/new-resource "/orders/123")
(hal/add-links {:ea:basket "/baskets/98712"
:ea:customer "/customers/7809"})
(hal/add-properties {:total 30.0
:currency "USD"
:status "shipped"})))
(hal/add-resource :ea:order (-> (hal/new-resource "/orders/124")
(hal/add-links {:ea:basket "/baskets/97213"
:ea:customer "/customers/12369"})
(hal/add-properties {:total 20.0,
:currency "USD",
:status "processing"})))
(hal/add-property :currently-processing 14)
(hal/add-property :shipped-today 20))
json-representation
(json/generate-string
{:_links {:self {:href "/orders"},
:curies {:name "ea",
:href "http://example.com/docs/rels/{rel}",
:templated true},
:next {:href "/orders?page=2"},
:ea:find {:href "/orders{?id}",
:templated true},
:ea:admin [{:href "/admins/2" :title "PI:NAME:<NAME>END_PI"}
{:href "/admins/5" :title "PI:NAME:<NAME>END_PI"}]}
:_embedded {:ea:order [(merge
{:_links {:self {:href "/orders/123"},
:ea:basket {:href "/baskets/98712"},
:ea:customer {:href "/customers/7809"}}}
{:total 30.0,
:currency "USD",
:status "shipped"})
(merge
{:_links {:self {:href "/orders/124"},
:ea:basket {:href "/baskets/97213"},
:ea:customer {:href "/customers/12369"}}}
{:total 20.0,
:currency "USD",
:status "processing"})]}
:currently-processing 14
:shipped-today 20})]
(testing "resource->json should marshal a resource into some json"
(is (= json-representation
(haljson/resource->json resource))))
(testing "json->resource should parse some json into a resource"
(is (= resource
(haljson/json->resource json-representation)))))
(testing "map->resource should parse links"
(is (= (hal/new-resource "/orders")
(haljson/map->resource {:_links {:self {:href "/orders"}}}))))
(testing "map->resource should include all information about a link"
(is (= (-> (hal/new-resource)
(hal/add-link :ea:find {:href "/orders{?id}",
:templated true}))
(haljson/map->resource {:_links {:ea:find {:href "/orders{?id}",
:templated true}}}))))
(testing "map->resource should parse arrays of links"
(is (= (-> (hal/new-resource)
(hal/add-links :ea:admin "/admins/2"
:ea:admin "/admins/5"))
(haljson/map->resource {:_links {:ea:admin [{:href "/admins/2"}
{:href "/admins/5"}]}}))))
(testing "map->resource should parse embedded resources"
(let [order-resource (hal/new-resource "/orders/123")]
(is (= (-> (hal/new-resource)
(hal/add-resource :ea:order order-resource))
(haljson/map->resource {:_embedded {:ea:order {:_links {:self {:href "/orders/123"}}}}})))))
(testing "map->resource should parse doubly embedded resources"
(let [purchaser-resource (hal/new-resource "/customers/1")
order-resource (-> (hal/new-resource "/orders/123")
(hal/add-resource :customer purchaser-resource))]
(is (= (-> (hal/new-resource)
(hal/add-resource :ea:order order-resource))
(haljson/map->resource {:_embedded {:ea:order {:_links {:self {:href "/orders/123"}}
:_embedded {:customer {:_links {:self {:href "/customers/1"}}}}}}})))))
(testing "map->resource should parse arrays of embedded resources"
(let [first-order (hal/new-resource "/orders/123")
second-order (hal/new-resource "/orders/124")]
(is (= (-> (hal/new-resource)
(hal/add-resources :ea:order first-order
:ea:order second-order))
(haljson/map->resource {:_embedded {:ea:order [{:_links {:self {:href "/orders/123"}}}
{:_links {:self {:href "/orders/124"}}}]}})))))
(testing "map->resource should parse properties"
(is (= (-> (hal/new-resource)
(hal/add-property :total 20.0))
(haljson/map->resource {:total 20.0}))))
(testing "resource->map should render doubly embedded resources"
(let [purchaser-resource (hal/new-resource "/customers/1")
order-resource (-> (hal/new-resource "/orders/123")
(hal/add-resource :customer purchaser-resource))]
(is (= (-> (hal/new-resource)
(hal/add-resource :ea:order order-resource)
(haljson/resource->map))
{:_embedded {:ea:order {:_links {:self {:href "/orders/123"}}
:_embedded {:customer {:_links {:self {:href "/customers/1"}}}}}}}))))
(testing "json->resource should throw an exception when the string is not valid json"
(is (thrown? clojure.lang.ExceptionInfo
(haljson/json->resource
"Not valid JSON!"))))) |
[
{
"context": "ri\n :credentialTemplate {:key \"foo\"\n :secret \"b",
"end": 816,
"score": 0.9693970084190369,
"start": 813,
"tag": "KEY",
"value": "foo"
},
{
"context": "o\"\n :secret \"bar\"\n :quota 7\n",
"end": 868,
"score": 0.9799803495407104,
"start": 865,
"tag": "KEY",
"value": "bar"
},
{
"context": " ctco/method\n :key \"foo\"\n :secret \"bar\"\n ",
"end": 1781,
"score": 0.76301109790802,
"start": 1778,
"tag": "KEY",
"value": "foo"
},
{
"context": "ey \"foo\"\n :secret \"bar\"\n :quota 7\n ",
"end": 1819,
"score": 0.996212363243103,
"start": 1816,
"tag": "KEY",
"value": "bar"
}
] | opennebula/config/test/com/sixsq/slipstream/ssclj/resources/spec/credential_cloud_opennebula_test.cljc | jolorenzo/SlipStreamConnectors | 0 | (ns com.sixsq.slipstream.ssclj.resources.spec.credential-cloud-opennebula-test
(:require
[clojure.test :refer :all]
[com.sixsq.slipstream.ssclj.resources.spec.credential-cloud-opennebula]
[com.sixsq.slipstream.ssclj.resources.spec.credential-template-cloud-opennebula]
[com.sixsq.slipstream.ssclj.resources.credential-template-cloud :as ctc]
[com.sixsq.slipstream.ssclj.resources.credential-template-cloud-opennebula :as ctco]
[com.sixsq.slipstream.ssclj.resources.credential-template :as ct]
[clojure.spec.alpha :as s]
[com.sixsq.slipstream.ssclj.resources.credential :as p]))
(def valid-acl ctc/resource-acl-default)
(deftest test-credential-cloud-opennebula-create-schema-check
(let [root {:resourceURI p/resource-uri
:credentialTemplate {:key "foo"
:secret "bar"
:quota 7
:connector {:href "connector/xyz"}}}]
(is (s/valid? :cimi/credential.cloud-opennebula.create root))
(is (s/valid? :cimi.credential-template.cloud-opennebula/credentialTemplate (:credentialTemplate root)))
(doseq [k (into #{} (keys (dissoc root :resourceURI)))]
(is (not (s/valid? :cimi/credential.cloud-opennebula.create (dissoc root k)))))))
(deftest test-credential-cloud-opennebula-schema-check
(let [timestamp "1972-10-08T10:00:00.0Z"
root {:id (str ct/resource-url "/uuid")
:resourceURI p/resource-uri
:created timestamp
:updated timestamp
:acl valid-acl
:type ctco/credential-type
:method ctco/method
:key "foo"
:secret "bar"
:quota 7
:connector {:href "connector/xyz"}}]
(is (s/valid? :cimi/credential.cloud-opennebula root))
(doseq [k (into #{} (keys root))]
(is (not (s/valid? :cimi/credential.cloud-opennebula (dissoc root k)))))))
| 8202 | (ns com.sixsq.slipstream.ssclj.resources.spec.credential-cloud-opennebula-test
(:require
[clojure.test :refer :all]
[com.sixsq.slipstream.ssclj.resources.spec.credential-cloud-opennebula]
[com.sixsq.slipstream.ssclj.resources.spec.credential-template-cloud-opennebula]
[com.sixsq.slipstream.ssclj.resources.credential-template-cloud :as ctc]
[com.sixsq.slipstream.ssclj.resources.credential-template-cloud-opennebula :as ctco]
[com.sixsq.slipstream.ssclj.resources.credential-template :as ct]
[clojure.spec.alpha :as s]
[com.sixsq.slipstream.ssclj.resources.credential :as p]))
(def valid-acl ctc/resource-acl-default)
(deftest test-credential-cloud-opennebula-create-schema-check
(let [root {:resourceURI p/resource-uri
:credentialTemplate {:key "<KEY>"
:secret "<KEY>"
:quota 7
:connector {:href "connector/xyz"}}}]
(is (s/valid? :cimi/credential.cloud-opennebula.create root))
(is (s/valid? :cimi.credential-template.cloud-opennebula/credentialTemplate (:credentialTemplate root)))
(doseq [k (into #{} (keys (dissoc root :resourceURI)))]
(is (not (s/valid? :cimi/credential.cloud-opennebula.create (dissoc root k)))))))
(deftest test-credential-cloud-opennebula-schema-check
(let [timestamp "1972-10-08T10:00:00.0Z"
root {:id (str ct/resource-url "/uuid")
:resourceURI p/resource-uri
:created timestamp
:updated timestamp
:acl valid-acl
:type ctco/credential-type
:method ctco/method
:key "<KEY>"
:secret "<KEY>"
:quota 7
:connector {:href "connector/xyz"}}]
(is (s/valid? :cimi/credential.cloud-opennebula root))
(doseq [k (into #{} (keys root))]
(is (not (s/valid? :cimi/credential.cloud-opennebula (dissoc root k)))))))
| true | (ns com.sixsq.slipstream.ssclj.resources.spec.credential-cloud-opennebula-test
(:require
[clojure.test :refer :all]
[com.sixsq.slipstream.ssclj.resources.spec.credential-cloud-opennebula]
[com.sixsq.slipstream.ssclj.resources.spec.credential-template-cloud-opennebula]
[com.sixsq.slipstream.ssclj.resources.credential-template-cloud :as ctc]
[com.sixsq.slipstream.ssclj.resources.credential-template-cloud-opennebula :as ctco]
[com.sixsq.slipstream.ssclj.resources.credential-template :as ct]
[clojure.spec.alpha :as s]
[com.sixsq.slipstream.ssclj.resources.credential :as p]))
(def valid-acl ctc/resource-acl-default)
(deftest test-credential-cloud-opennebula-create-schema-check
(let [root {:resourceURI p/resource-uri
:credentialTemplate {:key "PI:KEY:<KEY>END_PI"
:secret "PI:KEY:<KEY>END_PI"
:quota 7
:connector {:href "connector/xyz"}}}]
(is (s/valid? :cimi/credential.cloud-opennebula.create root))
(is (s/valid? :cimi.credential-template.cloud-opennebula/credentialTemplate (:credentialTemplate root)))
(doseq [k (into #{} (keys (dissoc root :resourceURI)))]
(is (not (s/valid? :cimi/credential.cloud-opennebula.create (dissoc root k)))))))
(deftest test-credential-cloud-opennebula-schema-check
(let [timestamp "1972-10-08T10:00:00.0Z"
root {:id (str ct/resource-url "/uuid")
:resourceURI p/resource-uri
:created timestamp
:updated timestamp
:acl valid-acl
:type ctco/credential-type
:method ctco/method
:key "PI:KEY:<KEY>END_PI"
:secret "PI:KEY:<KEY>END_PI"
:quota 7
:connector {:href "connector/xyz"}}]
(is (s/valid? :cimi/credential.cloud-opennebula root))
(doseq [k (into #{} (keys root))]
(is (not (s/valid? :cimi/credential.cloud-opennebula (dissoc root k)))))))
|
[
{
"context": "na.no-select\n [:div.setup-wrapper\n [:h1 \"Chronverna\"]\n [:h4 \"Player Select\"]\n [:div.player-",
"end": 2050,
"score": 0.9991123676300049,
"start": 2040,
"tag": "NAME",
"value": "Chronverna"
}
] | src/chronverna/setup_components.cljs | dphilipson/chronverna | 2 | (ns chronverna.setup-components
(:require
[chronverna.constants :as constants]
[chronverna.util :as util]))
; Player select
(defn value-from-change-event [e]
(-> e .-target .-value))
(defn wrap-on-change-for-event
"Takes a handler which receives the new faction/color value and transforms it to receive an
on-change event instead."
[on-change]
(fn [e] (on-change (value-from-change-event e))))
(defn color-select [player on-change]
[:select.color-select.form-control
{:value (util/title (:color player))
:on-change (wrap-on-change-for-event (comp on-change util/from-title))}
(for [color constants/colors]
(let [color-title (util/title color)]
^{:key color-title} [:option {:value color-title} color-title]))])
(defn player-select [i state {:keys [on-set-player-name on-set-player-color on-remove-player]}]
(let [player (get-in state [:players i])]
[:div.player-select-row
[:input.name-input.form-control
{:type "text"
:placeholder (str "Player " (inc i))
:value (:name player)
:on-change (wrap-on-change-for-event (partial on-set-player-name i))}]
[color-select player (partial on-set-player-color i)]
[:button.remove-player-button.btn.btn-default {:on-click (partial on-remove-player i)
:disabled (= (count (:players state)) 1)}
[:span.glyphicon.glyphicon-remove]]]))
; Add player button
(defn add-player-button [on-add-player]
[:div.add-player-button-container>button.add-player-button.btn.btn-default
{:on-click on-add-player}
[:span.glyphicon.glyphicon-plus]
" Add player"])
; Start button
(defn start-game-button [on-start-game]
[:div.start-game-button-container>button.btn.btn-primary.btn-lg
{:on-click on-start-game}
"Start Game"])
; Main component
(defn main [state {:keys [on-add-player on-start-game] :as actions}]
(let [player-count (count (:players state))]
[:div.chroverna.no-select
[:div.setup-wrapper
[:h1 "Chronverna"]
[:h4 "Player Select"]
[:div.player-select-area
(for [i (range player-count)]
^{:key i} [player-select i state actions])]
(when (< player-count constants/max-players)
[add-player-button on-add-player])
[start-game-button on-start-game]]]))
| 25607 | (ns chronverna.setup-components
(:require
[chronverna.constants :as constants]
[chronverna.util :as util]))
; Player select
(defn value-from-change-event [e]
(-> e .-target .-value))
(defn wrap-on-change-for-event
"Takes a handler which receives the new faction/color value and transforms it to receive an
on-change event instead."
[on-change]
(fn [e] (on-change (value-from-change-event e))))
(defn color-select [player on-change]
[:select.color-select.form-control
{:value (util/title (:color player))
:on-change (wrap-on-change-for-event (comp on-change util/from-title))}
(for [color constants/colors]
(let [color-title (util/title color)]
^{:key color-title} [:option {:value color-title} color-title]))])
(defn player-select [i state {:keys [on-set-player-name on-set-player-color on-remove-player]}]
(let [player (get-in state [:players i])]
[:div.player-select-row
[:input.name-input.form-control
{:type "text"
:placeholder (str "Player " (inc i))
:value (:name player)
:on-change (wrap-on-change-for-event (partial on-set-player-name i))}]
[color-select player (partial on-set-player-color i)]
[:button.remove-player-button.btn.btn-default {:on-click (partial on-remove-player i)
:disabled (= (count (:players state)) 1)}
[:span.glyphicon.glyphicon-remove]]]))
; Add player button
(defn add-player-button [on-add-player]
[:div.add-player-button-container>button.add-player-button.btn.btn-default
{:on-click on-add-player}
[:span.glyphicon.glyphicon-plus]
" Add player"])
; Start button
(defn start-game-button [on-start-game]
[:div.start-game-button-container>button.btn.btn-primary.btn-lg
{:on-click on-start-game}
"Start Game"])
; Main component
(defn main [state {:keys [on-add-player on-start-game] :as actions}]
(let [player-count (count (:players state))]
[:div.chroverna.no-select
[:div.setup-wrapper
[:h1 "<NAME>"]
[:h4 "Player Select"]
[:div.player-select-area
(for [i (range player-count)]
^{:key i} [player-select i state actions])]
(when (< player-count constants/max-players)
[add-player-button on-add-player])
[start-game-button on-start-game]]]))
| true | (ns chronverna.setup-components
(:require
[chronverna.constants :as constants]
[chronverna.util :as util]))
; Player select
(defn value-from-change-event [e]
(-> e .-target .-value))
(defn wrap-on-change-for-event
"Takes a handler which receives the new faction/color value and transforms it to receive an
on-change event instead."
[on-change]
(fn [e] (on-change (value-from-change-event e))))
(defn color-select [player on-change]
[:select.color-select.form-control
{:value (util/title (:color player))
:on-change (wrap-on-change-for-event (comp on-change util/from-title))}
(for [color constants/colors]
(let [color-title (util/title color)]
^{:key color-title} [:option {:value color-title} color-title]))])
(defn player-select [i state {:keys [on-set-player-name on-set-player-color on-remove-player]}]
(let [player (get-in state [:players i])]
[:div.player-select-row
[:input.name-input.form-control
{:type "text"
:placeholder (str "Player " (inc i))
:value (:name player)
:on-change (wrap-on-change-for-event (partial on-set-player-name i))}]
[color-select player (partial on-set-player-color i)]
[:button.remove-player-button.btn.btn-default {:on-click (partial on-remove-player i)
:disabled (= (count (:players state)) 1)}
[:span.glyphicon.glyphicon-remove]]]))
; Add player button
(defn add-player-button [on-add-player]
[:div.add-player-button-container>button.add-player-button.btn.btn-default
{:on-click on-add-player}
[:span.glyphicon.glyphicon-plus]
" Add player"])
; Start button
(defn start-game-button [on-start-game]
[:div.start-game-button-container>button.btn.btn-primary.btn-lg
{:on-click on-start-game}
"Start Game"])
; Main component
(defn main [state {:keys [on-add-player on-start-game] :as actions}]
(let [player-count (count (:players state))]
[:div.chroverna.no-select
[:div.setup-wrapper
[:h1 "PI:NAME:<NAME>END_PI"]
[:h4 "Player Select"]
[:div.player-select-area
(for [i (range player-count)]
^{:key i} [player-select i state actions])]
(when (< player-count constants/max-players)
[add-player-button on-add-player])
[start-game-button on-start-game]]]))
|
[
{
"context": "preferences \"Preferences\"\n :password \"Change Password\"}\n :preferences {:lang \"Language\"\n ",
"end": 6317,
"score": 0.9992636442184448,
"start": 6302,
"tag": "PASSWORD",
"value": "Change Password"
},
{
"context": "ow \"Refresh Now\"}\n :account {:current-password \"Current Password\"\n :new-password \"New Password\"\n ",
"end": 7067,
"score": 0.9991544485092163,
"start": 7051,
"tag": "PASSWORD",
"value": "Current Password"
},
{
"context": "rd \"Current Password\"\n :new-password \"New Password\"\n :saved \"Your account has been saved",
"end": 7109,
"score": 0.9992272853851318,
"start": 7097,
"tag": "PASSWORD",
"value": "New Password"
},
{
"context": "\n :users \"Users\"}\n :users {:username \"Username\"\n :fullname \"Name\"\n :email \"E",
"end": 7430,
"score": 0.9953631162643433,
"start": 7422,
"tag": "USERNAME",
"value": "Username"
},
{
"context": "users {:username \"Username\"\n :fullname \"Name\"\n :email \"Email\"\n :admin \"Adm",
"end": 7458,
"score": 0.9965841770172119,
"start": 7454,
"tag": "NAME",
"value": "Name"
},
{
"context": "\"\n :admin \"Admin\"\n :password \"Password\"\n :password-confirmation \"Password Conf",
"end": 7542,
"score": 0.9992515444755554,
"start": 7534,
"tag": "PASSWORD",
"value": "Password"
},
{
"context": "ord \"Password\"\n :password-confirmation \"Password Confirmation\"\n :invalid-credentials \"Invalid usernam",
"end": 7600,
"score": 0.9990318417549133,
"start": 7579,
"tag": "PASSWORD",
"value": "Password Confirmation"
},
{
"context": "a valid email address\"\n :password \"must have a combination of at least 7 letters and numbers (or symbols)\"\n ",
"end": 10261,
"score": 0.8108917474746704,
"start": 10238,
"tag": "PASSWORD",
"value": "must have a combination"
}
] | src/cljs/shevek/locales/en.cljs | eeng/shevek | 6 | (ns shevek.locales.en)
(def translations
{:sessions {:logout "Log out"}
:home {:menu "Home"
:title "Welcome!"
:subtitle "What would you like to analyze today?"}
:cubes {:title "Cubes"
:subtitle "Available data cubes"
:name "Name"
:description "Description"
:missing "There are no cubes defined."
:data-range "Available data range"
:unauthorized-title "Missing Cube"
:unauthorized "This cube is no longer available or you are not authorized to view it. Please contact the administrator for more information."}
:dashboards {:title "Dashboards"
:subtitle "Manage your dashboards"
:search-hint "Filter by name or description"
:missing "You have no dashboards yet."
:deleted "Dashboard '{1}' deleted!"
:updated-at "Last updated"
:new "New Dashboard"
:name "Name"
:description "Description"}
:dashboard {:add-panel "Add Panel"
:edit-panel "Edit Panel"
:duplicate-panel "Duplicate Panel"
:fullscreen-panel "Toggle Fullscreen"
:remove-panel "Remove Panel"
:select-cube "Select a cube for the report"
:saved "Dashboard saved!"
:share-disabled "<b>Sharing is disabled</b><br/>You must first save the dashboard in order to be able to share it."
:share-hint "This link is a read-only reference to your dashboard. Any changes you make after sharing it, will be visible by the users who have the link."
:import "Import Dashboard"
:import-as-link "Import as a Link"
:import-as-link-desc "The dashboard will be stored as a link to the original so any subsequent changes made by the owner will be reflected. You will not be able to make modifications though (don't worry, you can make a copy afterwards)."
:import-as-copy "Import as a Copy"
:import-as-copy-desc "The dashboard will be an independent copy of the original, allowing you to make changes but it will not receive subsequent updates by the owner."
:import-name "Give it another name if you like"
:imported "Dashboard imported!"}
:reports {:title "Reports"
:subtitle "Manage your reports"
:recent "Recent Reports"
:missing "You haven't created any reports yet. Click on a cube to design a new one and then save it."
:name "Name"
:description "Description"
:updated-at "Last updated"
:saved "Report saved!"
:deleted "Report '{1}' deleted!"
:download-csv "Download as CSV"
:new "New Report"
:share-hint "This is a point-in-time snapshot of your report. Any changes made afterward, will not be reflected on shared report."}
:designer {:dimensions "Dimensions"
:measures "Measures"
:filters "Filters"
:splits "Splits"
:split-on "Split On"
:rows "Rows"
:columns "Columns"
:pinboard "Pinboard"
:limit "Limit"
:sort-by "Sort By"
:granularity "Granularity"
:no-pinned "Drag dimensions here to pin them for quick access"
:no-measures "Please select at least one measure"
:no-results "No results were found that match the specified search criteria"
:split-required "At least one split is required for the {1} visualization"
:too-many-splits-for-chart "A maximum of two splits may be provided for chart visualization"
:chart-with-second-split-on-rows "The second split must be on the columns to be able to generate the chart"
:maximize "Maximize Results Panel"
:minimize "Minimize Results Panel"
:grand-total "Grand Total"
:go-back "Go Back to Dashboard"}
:designer.period {:relative "Relative"
:specific "Specific"
:latest "Latest"
:latest-hour "Latest Hour"
:latest-day "Latest Day"
:latest-7days "Latest 7 Days"
:latest-30days "Latest 30 Days"
:latest-90days "Latest 90 Days"
:current "Current"
:current-day "Current Day"
:current-week "Current Week"
:current-month "Current Month"
:current-quarter "Current Quarter"
:current-year "Current Year"
:previous "Previous"
:previous-day "Previous Day"
:previous-week "Previous Week"
:previous-month "Previous Month"
:previous-quarter "Previous Quarter"
:previous-year "Previous Year"
:from "From"
:to "To"}
:designer.operator {:include "Include"
:exclude "Exclude"}
:designer.viztype {:totals "totals"
:table "table"
:bar-chart "bar chart"
:line-chart "line chart"
:pie-chart "pie chart"}
:send-to-dashboard {:title "Send to Dashboard"
:label "Choose the destination dashboard"
:desc "This action will insert a copy of the current report into the selected dashboard."
:success "The report was sent to the dashboard"}
:share {:title "Share"
:label "Link to share"
:copy "Copy"
:copied "Link copied!"}
:raw-data {:title "Raw Event Data"
:showing "Showing the first {1} events matching: "
:button "Raw Data"}
:configuration {:menu "Application Configuration, Manage Users"
:title "Configuration"
:subtitle "Application level settings"
:users "Users"}
:profile {:menu "User preferences, Change Password"
:preferences "Preferences"
:password "Change Password"}
:preferences {:lang "Language"
:abbreviations "Number Abbreviations"
:abbreviations-opts (fn [] [["Use default settings" "default"] ["Don't use abbreviations" "no"] ["Use abbreviations" "yes"]])
:saved "Preferences saved!"
:refresh-every "Refresh every"
:refresh-every-opts (fn [] {0 "Never"
10 "10s"
30 "30s"
60 "1m"
600 "10m"
1800 "30m"})
:refresh-now "Refresh Now"}
:account {:current-password "Current Password"
:new-password "New Password"
:saved "Your account has been saved"
:invalid-current-password "is incorrect"}
:admin {:menu "Manage Users"
:title "Management"
:subtitle "Configure the users who will be using the system and their permissions"
:users "Users"}
:users {:username "Username"
:fullname "Name"
:email "Email"
:admin "Admin"
:password "Password"
:password-confirmation "Password Confirmation"
:invalid-credentials "Invalid username or password"
:session-expired "Session expired, please login again"
:password-hint "Leave blank if you don't want to change it"
:unauthorized "Sorry but you are not allowed to execute this action. Please contact the administrator for more information."
:basic-info "Basic Information"
:permissions "Permissions"
:search-hint "Filter by username or fullname"
:deleted "User deleted!"}
:permissions {:allowed-cubes "Allowed Cubes"
:admin-all-cubes "Admin users view everything"
:all-cubes "Can view all cubes"
:no-cubes "Can view no cubes"
:only-cubes-selected "Can view only the following cubes"
:all-measures "All measures will be visible"
:only-measures-selected "Only the following measures will be visible"
:select-measures "Please select the allowed measures"
:no-measures "None"
:add-filter "Add Filter"}
:date-formats {:second "yyyy-MM-dd HH:mm:ss"
:minute "MMM d, h:mma"
:hour "MMM d, yyyy ha"
:day "MMM d, yyyy"
:month "MMM yyyy"
:file "yyMMdd_HHmm"}
:calendar {:days ["S" "M" "T" "W" "T" "F" "S"]
:months ["January" "February" "March" "April" "May" "June" "July" "August" "September" "October" "November" "December"]
:monthsShort ["Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"]
:today "Today"
:now "Now"
:am "AM"
:pm "PM"
:dayNames ["Sunday" "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday"]} ; Not used by the calendar but for :format "dow" dimensions
:actions {:ok "Accept"
:cancel "Cancel"
:edit "Modify"
:save "Save"
:save-as "Save As"
:new "Create"
:delete "Delete"
:close "Close"
:select "Select"
:hold-delete "You must click the button and hold for one second to confirm"
:search "Search"
:header "Actions"
:confirm "Confirm"
:manage "Manage"
:refresh "Refresh"
:import "Import"
:double-click-edit "Double click to edit"}
:validation {:required "can't be blank"
:regex "doesn't match pattern"
:email "is not a valid email address"
:password "must have a combination of at least 7 letters and numbers (or symbols)"
:confirmation "doesn't match the previous value"}
:boolean {:true "Yes"
:false "No"}
:errors {:no-results "No results where found."
:no-desc "No description"
:bad-gateway "The system is not available right now. Please try again later."
:unexpected "We're sorry but something went wrong. We've been notified about this issue and we'll take a look at it shortly."
:page-not-found "The requested page was not found. Make sure the web address is correct."}})
| 112929 | (ns shevek.locales.en)
(def translations
{:sessions {:logout "Log out"}
:home {:menu "Home"
:title "Welcome!"
:subtitle "What would you like to analyze today?"}
:cubes {:title "Cubes"
:subtitle "Available data cubes"
:name "Name"
:description "Description"
:missing "There are no cubes defined."
:data-range "Available data range"
:unauthorized-title "Missing Cube"
:unauthorized "This cube is no longer available or you are not authorized to view it. Please contact the administrator for more information."}
:dashboards {:title "Dashboards"
:subtitle "Manage your dashboards"
:search-hint "Filter by name or description"
:missing "You have no dashboards yet."
:deleted "Dashboard '{1}' deleted!"
:updated-at "Last updated"
:new "New Dashboard"
:name "Name"
:description "Description"}
:dashboard {:add-panel "Add Panel"
:edit-panel "Edit Panel"
:duplicate-panel "Duplicate Panel"
:fullscreen-panel "Toggle Fullscreen"
:remove-panel "Remove Panel"
:select-cube "Select a cube for the report"
:saved "Dashboard saved!"
:share-disabled "<b>Sharing is disabled</b><br/>You must first save the dashboard in order to be able to share it."
:share-hint "This link is a read-only reference to your dashboard. Any changes you make after sharing it, will be visible by the users who have the link."
:import "Import Dashboard"
:import-as-link "Import as a Link"
:import-as-link-desc "The dashboard will be stored as a link to the original so any subsequent changes made by the owner will be reflected. You will not be able to make modifications though (don't worry, you can make a copy afterwards)."
:import-as-copy "Import as a Copy"
:import-as-copy-desc "The dashboard will be an independent copy of the original, allowing you to make changes but it will not receive subsequent updates by the owner."
:import-name "Give it another name if you like"
:imported "Dashboard imported!"}
:reports {:title "Reports"
:subtitle "Manage your reports"
:recent "Recent Reports"
:missing "You haven't created any reports yet. Click on a cube to design a new one and then save it."
:name "Name"
:description "Description"
:updated-at "Last updated"
:saved "Report saved!"
:deleted "Report '{1}' deleted!"
:download-csv "Download as CSV"
:new "New Report"
:share-hint "This is a point-in-time snapshot of your report. Any changes made afterward, will not be reflected on shared report."}
:designer {:dimensions "Dimensions"
:measures "Measures"
:filters "Filters"
:splits "Splits"
:split-on "Split On"
:rows "Rows"
:columns "Columns"
:pinboard "Pinboard"
:limit "Limit"
:sort-by "Sort By"
:granularity "Granularity"
:no-pinned "Drag dimensions here to pin them for quick access"
:no-measures "Please select at least one measure"
:no-results "No results were found that match the specified search criteria"
:split-required "At least one split is required for the {1} visualization"
:too-many-splits-for-chart "A maximum of two splits may be provided for chart visualization"
:chart-with-second-split-on-rows "The second split must be on the columns to be able to generate the chart"
:maximize "Maximize Results Panel"
:minimize "Minimize Results Panel"
:grand-total "Grand Total"
:go-back "Go Back to Dashboard"}
:designer.period {:relative "Relative"
:specific "Specific"
:latest "Latest"
:latest-hour "Latest Hour"
:latest-day "Latest Day"
:latest-7days "Latest 7 Days"
:latest-30days "Latest 30 Days"
:latest-90days "Latest 90 Days"
:current "Current"
:current-day "Current Day"
:current-week "Current Week"
:current-month "Current Month"
:current-quarter "Current Quarter"
:current-year "Current Year"
:previous "Previous"
:previous-day "Previous Day"
:previous-week "Previous Week"
:previous-month "Previous Month"
:previous-quarter "Previous Quarter"
:previous-year "Previous Year"
:from "From"
:to "To"}
:designer.operator {:include "Include"
:exclude "Exclude"}
:designer.viztype {:totals "totals"
:table "table"
:bar-chart "bar chart"
:line-chart "line chart"
:pie-chart "pie chart"}
:send-to-dashboard {:title "Send to Dashboard"
:label "Choose the destination dashboard"
:desc "This action will insert a copy of the current report into the selected dashboard."
:success "The report was sent to the dashboard"}
:share {:title "Share"
:label "Link to share"
:copy "Copy"
:copied "Link copied!"}
:raw-data {:title "Raw Event Data"
:showing "Showing the first {1} events matching: "
:button "Raw Data"}
:configuration {:menu "Application Configuration, Manage Users"
:title "Configuration"
:subtitle "Application level settings"
:users "Users"}
:profile {:menu "User preferences, Change Password"
:preferences "Preferences"
:password "<PASSWORD>"}
:preferences {:lang "Language"
:abbreviations "Number Abbreviations"
:abbreviations-opts (fn [] [["Use default settings" "default"] ["Don't use abbreviations" "no"] ["Use abbreviations" "yes"]])
:saved "Preferences saved!"
:refresh-every "Refresh every"
:refresh-every-opts (fn [] {0 "Never"
10 "10s"
30 "30s"
60 "1m"
600 "10m"
1800 "30m"})
:refresh-now "Refresh Now"}
:account {:current-password "<PASSWORD>"
:new-password "<PASSWORD>"
:saved "Your account has been saved"
:invalid-current-password "is incorrect"}
:admin {:menu "Manage Users"
:title "Management"
:subtitle "Configure the users who will be using the system and their permissions"
:users "Users"}
:users {:username "Username"
:fullname "<NAME>"
:email "Email"
:admin "Admin"
:password "<PASSWORD>"
:password-confirmation "<PASSWORD>"
:invalid-credentials "Invalid username or password"
:session-expired "Session expired, please login again"
:password-hint "Leave blank if you don't want to change it"
:unauthorized "Sorry but you are not allowed to execute this action. Please contact the administrator for more information."
:basic-info "Basic Information"
:permissions "Permissions"
:search-hint "Filter by username or fullname"
:deleted "User deleted!"}
:permissions {:allowed-cubes "Allowed Cubes"
:admin-all-cubes "Admin users view everything"
:all-cubes "Can view all cubes"
:no-cubes "Can view no cubes"
:only-cubes-selected "Can view only the following cubes"
:all-measures "All measures will be visible"
:only-measures-selected "Only the following measures will be visible"
:select-measures "Please select the allowed measures"
:no-measures "None"
:add-filter "Add Filter"}
:date-formats {:second "yyyy-MM-dd HH:mm:ss"
:minute "MMM d, h:mma"
:hour "MMM d, yyyy ha"
:day "MMM d, yyyy"
:month "MMM yyyy"
:file "yyMMdd_HHmm"}
:calendar {:days ["S" "M" "T" "W" "T" "F" "S"]
:months ["January" "February" "March" "April" "May" "June" "July" "August" "September" "October" "November" "December"]
:monthsShort ["Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"]
:today "Today"
:now "Now"
:am "AM"
:pm "PM"
:dayNames ["Sunday" "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday"]} ; Not used by the calendar but for :format "dow" dimensions
:actions {:ok "Accept"
:cancel "Cancel"
:edit "Modify"
:save "Save"
:save-as "Save As"
:new "Create"
:delete "Delete"
:close "Close"
:select "Select"
:hold-delete "You must click the button and hold for one second to confirm"
:search "Search"
:header "Actions"
:confirm "Confirm"
:manage "Manage"
:refresh "Refresh"
:import "Import"
:double-click-edit "Double click to edit"}
:validation {:required "can't be blank"
:regex "doesn't match pattern"
:email "is not a valid email address"
:password "<PASSWORD> of at least 7 letters and numbers (or symbols)"
:confirmation "doesn't match the previous value"}
:boolean {:true "Yes"
:false "No"}
:errors {:no-results "No results where found."
:no-desc "No description"
:bad-gateway "The system is not available right now. Please try again later."
:unexpected "We're sorry but something went wrong. We've been notified about this issue and we'll take a look at it shortly."
:page-not-found "The requested page was not found. Make sure the web address is correct."}})
| true | (ns shevek.locales.en)
(def translations
{:sessions {:logout "Log out"}
:home {:menu "Home"
:title "Welcome!"
:subtitle "What would you like to analyze today?"}
:cubes {:title "Cubes"
:subtitle "Available data cubes"
:name "Name"
:description "Description"
:missing "There are no cubes defined."
:data-range "Available data range"
:unauthorized-title "Missing Cube"
:unauthorized "This cube is no longer available or you are not authorized to view it. Please contact the administrator for more information."}
:dashboards {:title "Dashboards"
:subtitle "Manage your dashboards"
:search-hint "Filter by name or description"
:missing "You have no dashboards yet."
:deleted "Dashboard '{1}' deleted!"
:updated-at "Last updated"
:new "New Dashboard"
:name "Name"
:description "Description"}
:dashboard {:add-panel "Add Panel"
:edit-panel "Edit Panel"
:duplicate-panel "Duplicate Panel"
:fullscreen-panel "Toggle Fullscreen"
:remove-panel "Remove Panel"
:select-cube "Select a cube for the report"
:saved "Dashboard saved!"
:share-disabled "<b>Sharing is disabled</b><br/>You must first save the dashboard in order to be able to share it."
:share-hint "This link is a read-only reference to your dashboard. Any changes you make after sharing it, will be visible by the users who have the link."
:import "Import Dashboard"
:import-as-link "Import as a Link"
:import-as-link-desc "The dashboard will be stored as a link to the original so any subsequent changes made by the owner will be reflected. You will not be able to make modifications though (don't worry, you can make a copy afterwards)."
:import-as-copy "Import as a Copy"
:import-as-copy-desc "The dashboard will be an independent copy of the original, allowing you to make changes but it will not receive subsequent updates by the owner."
:import-name "Give it another name if you like"
:imported "Dashboard imported!"}
:reports {:title "Reports"
:subtitle "Manage your reports"
:recent "Recent Reports"
:missing "You haven't created any reports yet. Click on a cube to design a new one and then save it."
:name "Name"
:description "Description"
:updated-at "Last updated"
:saved "Report saved!"
:deleted "Report '{1}' deleted!"
:download-csv "Download as CSV"
:new "New Report"
:share-hint "This is a point-in-time snapshot of your report. Any changes made afterward, will not be reflected on shared report."}
:designer {:dimensions "Dimensions"
:measures "Measures"
:filters "Filters"
:splits "Splits"
:split-on "Split On"
:rows "Rows"
:columns "Columns"
:pinboard "Pinboard"
:limit "Limit"
:sort-by "Sort By"
:granularity "Granularity"
:no-pinned "Drag dimensions here to pin them for quick access"
:no-measures "Please select at least one measure"
:no-results "No results were found that match the specified search criteria"
:split-required "At least one split is required for the {1} visualization"
:too-many-splits-for-chart "A maximum of two splits may be provided for chart visualization"
:chart-with-second-split-on-rows "The second split must be on the columns to be able to generate the chart"
:maximize "Maximize Results Panel"
:minimize "Minimize Results Panel"
:grand-total "Grand Total"
:go-back "Go Back to Dashboard"}
:designer.period {:relative "Relative"
:specific "Specific"
:latest "Latest"
:latest-hour "Latest Hour"
:latest-day "Latest Day"
:latest-7days "Latest 7 Days"
:latest-30days "Latest 30 Days"
:latest-90days "Latest 90 Days"
:current "Current"
:current-day "Current Day"
:current-week "Current Week"
:current-month "Current Month"
:current-quarter "Current Quarter"
:current-year "Current Year"
:previous "Previous"
:previous-day "Previous Day"
:previous-week "Previous Week"
:previous-month "Previous Month"
:previous-quarter "Previous Quarter"
:previous-year "Previous Year"
:from "From"
:to "To"}
:designer.operator {:include "Include"
:exclude "Exclude"}
:designer.viztype {:totals "totals"
:table "table"
:bar-chart "bar chart"
:line-chart "line chart"
:pie-chart "pie chart"}
:send-to-dashboard {:title "Send to Dashboard"
:label "Choose the destination dashboard"
:desc "This action will insert a copy of the current report into the selected dashboard."
:success "The report was sent to the dashboard"}
:share {:title "Share"
:label "Link to share"
:copy "Copy"
:copied "Link copied!"}
:raw-data {:title "Raw Event Data"
:showing "Showing the first {1} events matching: "
:button "Raw Data"}
:configuration {:menu "Application Configuration, Manage Users"
:title "Configuration"
:subtitle "Application level settings"
:users "Users"}
:profile {:menu "User preferences, Change Password"
:preferences "Preferences"
:password "PI:PASSWORD:<PASSWORD>END_PI"}
:preferences {:lang "Language"
:abbreviations "Number Abbreviations"
:abbreviations-opts (fn [] [["Use default settings" "default"] ["Don't use abbreviations" "no"] ["Use abbreviations" "yes"]])
:saved "Preferences saved!"
:refresh-every "Refresh every"
:refresh-every-opts (fn [] {0 "Never"
10 "10s"
30 "30s"
60 "1m"
600 "10m"
1800 "30m"})
:refresh-now "Refresh Now"}
:account {:current-password "PI:PASSWORD:<PASSWORD>END_PI"
:new-password "PI:PASSWORD:<PASSWORD>END_PI"
:saved "Your account has been saved"
:invalid-current-password "is incorrect"}
:admin {:menu "Manage Users"
:title "Management"
:subtitle "Configure the users who will be using the system and their permissions"
:users "Users"}
:users {:username "Username"
:fullname "PI:NAME:<NAME>END_PI"
:email "Email"
:admin "Admin"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:password-confirmation "PI:PASSWORD:<PASSWORD>END_PI"
:invalid-credentials "Invalid username or password"
:session-expired "Session expired, please login again"
:password-hint "Leave blank if you don't want to change it"
:unauthorized "Sorry but you are not allowed to execute this action. Please contact the administrator for more information."
:basic-info "Basic Information"
:permissions "Permissions"
:search-hint "Filter by username or fullname"
:deleted "User deleted!"}
:permissions {:allowed-cubes "Allowed Cubes"
:admin-all-cubes "Admin users view everything"
:all-cubes "Can view all cubes"
:no-cubes "Can view no cubes"
:only-cubes-selected "Can view only the following cubes"
:all-measures "All measures will be visible"
:only-measures-selected "Only the following measures will be visible"
:select-measures "Please select the allowed measures"
:no-measures "None"
:add-filter "Add Filter"}
:date-formats {:second "yyyy-MM-dd HH:mm:ss"
:minute "MMM d, h:mma"
:hour "MMM d, yyyy ha"
:day "MMM d, yyyy"
:month "MMM yyyy"
:file "yyMMdd_HHmm"}
:calendar {:days ["S" "M" "T" "W" "T" "F" "S"]
:months ["January" "February" "March" "April" "May" "June" "July" "August" "September" "October" "November" "December"]
:monthsShort ["Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"]
:today "Today"
:now "Now"
:am "AM"
:pm "PM"
:dayNames ["Sunday" "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday"]} ; Not used by the calendar but for :format "dow" dimensions
:actions {:ok "Accept"
:cancel "Cancel"
:edit "Modify"
:save "Save"
:save-as "Save As"
:new "Create"
:delete "Delete"
:close "Close"
:select "Select"
:hold-delete "You must click the button and hold for one second to confirm"
:search "Search"
:header "Actions"
:confirm "Confirm"
:manage "Manage"
:refresh "Refresh"
:import "Import"
:double-click-edit "Double click to edit"}
:validation {:required "can't be blank"
:regex "doesn't match pattern"
:email "is not a valid email address"
:password "PI:PASSWORD:<PASSWORD>END_PI of at least 7 letters and numbers (or symbols)"
:confirmation "doesn't match the previous value"}
:boolean {:true "Yes"
:false "No"}
:errors {:no-results "No results where found."
:no-desc "No description"
:bad-gateway "The system is not available right now. Please try again later."
:unexpected "We're sorry but something went wrong. We've been notified about this issue and we'll take a look at it shortly."
:page-not-found "The requested page was not found. Make sure the web address is correct."}})
|
[
{
"context": ";\n; Copyright © 2021 Peter Monks\n;\n; Licensed under the Apache License, Version 2.",
"end": 32,
"score": 0.9997401833534241,
"start": 21,
"tag": "NAME",
"value": "Peter Monks"
}
] | src/lice_comb/data.clj | pmonks/lice-comb | 3 | ;
; Copyright © 2021 Peter Monks
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; SPDX-License-Identifier: Apache-2.0
;
(ns lice-comb.data
"Data handling functionality."
(:require [lice-comb.utils :as u]))
(defn uri-for-data
"Returns a URI (as a string) for the given data file. May be a local file path or a URI to a remote resource."
[file]
(when file
(str (u/getenv "LICE_COMB_DATA_DIR" "https://raw.githubusercontent.com/pmonks/lice-comb/data") file)))
| 83060 | ;
; Copyright © 2021 <NAME>
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; SPDX-License-Identifier: Apache-2.0
;
(ns lice-comb.data
"Data handling functionality."
(:require [lice-comb.utils :as u]))
(defn uri-for-data
"Returns a URI (as a string) for the given data file. May be a local file path or a URI to a remote resource."
[file]
(when file
(str (u/getenv "LICE_COMB_DATA_DIR" "https://raw.githubusercontent.com/pmonks/lice-comb/data") file)))
| true | ;
; Copyright © 2021 PI:NAME:<NAME>END_PI
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;
; SPDX-License-Identifier: Apache-2.0
;
(ns lice-comb.data
"Data handling functionality."
(:require [lice-comb.utils :as u]))
(defn uri-for-data
"Returns a URI (as a string) for the given data file. May be a local file path or a URI to a remote resource."
[file]
(when file
(str (u/getenv "LICE_COMB_DATA_DIR" "https://raw.githubusercontent.com/pmonks/lice-comb/data") file)))
|
[
{
"context": "{:surname \"Pither\"\n :firstname \"Jon\"\n :phone \"1235\"}})\n\n(defn creat",
"end": 784,
"score": 0.9440869092941284,
"start": 781,
"tag": "NAME",
"value": "Jon"
},
{
"context": "ost \"/phonebook\" {\"surname\" \"Pither\" \"firstname\" \"Jon\" \"phone\" \"1235\"})\n (update :header",
"end": 1566,
"score": 0.8210505843162537,
"start": 1563,
"tag": "NAME",
"value": "Jon"
}
] | examples/phonebook/test/phonebook/resources_test.clj | Frozenlock/yada | 780 | ;; Copyright © 2014-2017, JUXT LTD.
(ns phonebook.resources-test
(:require
[byte-streams :as b]
[bidi.bidi :as bidi]
[bidi.vhosts :refer [make-handler vhosts-model]]
[clojure.java.io :as io]
[clojure.set :as set]
[clojure.test :refer :all]
[clojure.edn :as edn]
[clojure.data.codec.base64 :as base64]
[ring.mock.request :refer [request]]
[phonebook.util :refer [to-string]]
[phonebook.db :as db]
[phonebook.api :refer [api]]))
(defn encode-basic-authorization [user password]
(str "Basic " (b/to-string (base64/encode (.getBytes (str user ":" password))))))
(def full-seed {1 {:surname "Sparks"
:firstname "Malcolm"
:phone "1234"}
2 {:surname "Pither"
:firstname "Jon"
:phone "1235"}})
(defn create-api [db]
(let [api (api db)]
(vhosts-model [{:scheme :http :host "localhost"} api])))
(deftest list-all-entries
(let [db (db/create-db full-seed)
h (make-handler (create-api db))
req (merge-with merge
(request :get "/phonebook")
{:headers {"accept" "application/edn"}})
response @(h req)]
(is (= 200 (:status response)))
(let [body (-> response :body to-string edn/read-string)]
(is (= 2 (count body)))
(is (= "Malcolm" (get-in body [1 :firstname]))))))
(deftest create-entry
(let [db (db/create-db {})
h (make-handler (create-api db))
req (-> (request :post "/phonebook" {"surname" "Pither" "firstname" "Jon" "phone" "1235"})
(update :headers assoc
"authorization" (encode-basic-authorization "tom" "watson")))
response @(h req)]
(is (= 201 (:status response)))
#_(is (set/superset? (set (keys (:headers response)))
#{"location" "content-length"}))
#_(is (nil? (:body response)))))
(deftest update-entry
(let [db (db/create-db full-seed)
h (make-handler (create-api db))]
(is (= (db/count-entries db) 2))
(let [req (->
(request :put "/phonebook/2" (slurp (io/resource "phonebook/update-data")))
(update :headers assoc
"content-type" "multipart/form-data; boundary=ABCD"
"authorization" (encode-basic-authorization "tom" "watson")))
response @(h req)]
(is (= 204 (:status response)))
(is (nil? (:body response)))
(is (= (db/count-entries db) 2))
(is (= "8888" (:phone (db/get-entry db 2)))))))
(deftest delete-entry
(let [db (db/create-db full-seed)
h (make-handler (create-api db))]
(is (= (db/count-entries db) 2))
(let [req (-> (request :delete "/phonebook/1")
(update :headers assoc
"accept" "text/plain"
"authorization" (encode-basic-authorization "tom" "watson")))
response @(h req)]
(is (= 200 (:status response)))
(is (= "Entry 1 has been removed\n" (b/to-string (:body response))))
(is (= (db/count-entries db) 1)))))
| 95278 | ;; Copyright © 2014-2017, JUXT LTD.
(ns phonebook.resources-test
(:require
[byte-streams :as b]
[bidi.bidi :as bidi]
[bidi.vhosts :refer [make-handler vhosts-model]]
[clojure.java.io :as io]
[clojure.set :as set]
[clojure.test :refer :all]
[clojure.edn :as edn]
[clojure.data.codec.base64 :as base64]
[ring.mock.request :refer [request]]
[phonebook.util :refer [to-string]]
[phonebook.db :as db]
[phonebook.api :refer [api]]))
(defn encode-basic-authorization [user password]
(str "Basic " (b/to-string (base64/encode (.getBytes (str user ":" password))))))
(def full-seed {1 {:surname "Sparks"
:firstname "Malcolm"
:phone "1234"}
2 {:surname "Pither"
:firstname "<NAME>"
:phone "1235"}})
(defn create-api [db]
(let [api (api db)]
(vhosts-model [{:scheme :http :host "localhost"} api])))
(deftest list-all-entries
(let [db (db/create-db full-seed)
h (make-handler (create-api db))
req (merge-with merge
(request :get "/phonebook")
{:headers {"accept" "application/edn"}})
response @(h req)]
(is (= 200 (:status response)))
(let [body (-> response :body to-string edn/read-string)]
(is (= 2 (count body)))
(is (= "Malcolm" (get-in body [1 :firstname]))))))
(deftest create-entry
(let [db (db/create-db {})
h (make-handler (create-api db))
req (-> (request :post "/phonebook" {"surname" "Pither" "firstname" "<NAME>" "phone" "1235"})
(update :headers assoc
"authorization" (encode-basic-authorization "tom" "watson")))
response @(h req)]
(is (= 201 (:status response)))
#_(is (set/superset? (set (keys (:headers response)))
#{"location" "content-length"}))
#_(is (nil? (:body response)))))
(deftest update-entry
(let [db (db/create-db full-seed)
h (make-handler (create-api db))]
(is (= (db/count-entries db) 2))
(let [req (->
(request :put "/phonebook/2" (slurp (io/resource "phonebook/update-data")))
(update :headers assoc
"content-type" "multipart/form-data; boundary=ABCD"
"authorization" (encode-basic-authorization "tom" "watson")))
response @(h req)]
(is (= 204 (:status response)))
(is (nil? (:body response)))
(is (= (db/count-entries db) 2))
(is (= "8888" (:phone (db/get-entry db 2)))))))
(deftest delete-entry
(let [db (db/create-db full-seed)
h (make-handler (create-api db))]
(is (= (db/count-entries db) 2))
(let [req (-> (request :delete "/phonebook/1")
(update :headers assoc
"accept" "text/plain"
"authorization" (encode-basic-authorization "tom" "watson")))
response @(h req)]
(is (= 200 (:status response)))
(is (= "Entry 1 has been removed\n" (b/to-string (:body response))))
(is (= (db/count-entries db) 1)))))
| true | ;; Copyright © 2014-2017, JUXT LTD.
(ns phonebook.resources-test
(:require
[byte-streams :as b]
[bidi.bidi :as bidi]
[bidi.vhosts :refer [make-handler vhosts-model]]
[clojure.java.io :as io]
[clojure.set :as set]
[clojure.test :refer :all]
[clojure.edn :as edn]
[clojure.data.codec.base64 :as base64]
[ring.mock.request :refer [request]]
[phonebook.util :refer [to-string]]
[phonebook.db :as db]
[phonebook.api :refer [api]]))
(defn encode-basic-authorization [user password]
(str "Basic " (b/to-string (base64/encode (.getBytes (str user ":" password))))))
(def full-seed {1 {:surname "Sparks"
:firstname "Malcolm"
:phone "1234"}
2 {:surname "Pither"
:firstname "PI:NAME:<NAME>END_PI"
:phone "1235"}})
(defn create-api [db]
(let [api (api db)]
(vhosts-model [{:scheme :http :host "localhost"} api])))
(deftest list-all-entries
(let [db (db/create-db full-seed)
h (make-handler (create-api db))
req (merge-with merge
(request :get "/phonebook")
{:headers {"accept" "application/edn"}})
response @(h req)]
(is (= 200 (:status response)))
(let [body (-> response :body to-string edn/read-string)]
(is (= 2 (count body)))
(is (= "Malcolm" (get-in body [1 :firstname]))))))
(deftest create-entry
(let [db (db/create-db {})
h (make-handler (create-api db))
req (-> (request :post "/phonebook" {"surname" "Pither" "firstname" "PI:NAME:<NAME>END_PI" "phone" "1235"})
(update :headers assoc
"authorization" (encode-basic-authorization "tom" "watson")))
response @(h req)]
(is (= 201 (:status response)))
#_(is (set/superset? (set (keys (:headers response)))
#{"location" "content-length"}))
#_(is (nil? (:body response)))))
(deftest update-entry
(let [db (db/create-db full-seed)
h (make-handler (create-api db))]
(is (= (db/count-entries db) 2))
(let [req (->
(request :put "/phonebook/2" (slurp (io/resource "phonebook/update-data")))
(update :headers assoc
"content-type" "multipart/form-data; boundary=ABCD"
"authorization" (encode-basic-authorization "tom" "watson")))
response @(h req)]
(is (= 204 (:status response)))
(is (nil? (:body response)))
(is (= (db/count-entries db) 2))
(is (= "8888" (:phone (db/get-entry db 2)))))))
(deftest delete-entry
(let [db (db/create-db full-seed)
h (make-handler (create-api db))]
(is (= (db/count-entries db) 2))
(let [req (-> (request :delete "/phonebook/1")
(update :headers assoc
"accept" "text/plain"
"authorization" (encode-basic-authorization "tom" "watson")))
response @(h req)]
(is (= 200 (:status response)))
(is (= "Entry 1 has been removed\n" (b/to-string (:body response))))
(is (= (db/count-entries db) 1)))))
|
[
{
"context": ";;;\n;;; Copyright 2020 David Edwards\n;;;\n;;; Licensed under the Apache License, Versio",
"end": 36,
"score": 0.9997910857200623,
"start": 23,
"tag": "NAME",
"value": "David Edwards"
}
] | test/rpn/tools.clj | davidledwards/rpn-clojure | 1 | ;;;
;;; Copyright 2020 David Edwards
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
;;;
(ns rpn.tools
"Tools for automatically generating random conformant expressions.
Note that these expressions are generated for testing purposes only and may
appear to be senseless when visually inspected. However, they do conform to
the specified grammar and are sufficient for detecting regressions.
The output of each test generation is formatted such that it can be
literally cut and pasted into the unit test itself."
(:require [clojure.string :as string])
(:require [rpn.expressions :as expr])
(:require [rpn.token :as token])
(:require [rpn.lexer :as lexer])
(:require [rpn.parser :as parser])
(:require [rpn.ast :as ast])
(:require [rpn.generator :as gen])
(:require [rpn.code :as code])
(:require [rpn.evaluator :as evaluator]))
(defn name-hash [name]
(/ (reduce #(+ %1 (/ (int %2) 100.0)) 0.0 name) 10.0))
(defn- tab [n]
(string/join (repeat (* n 2) \space)))
(defn parser-tests
"Produces a sequence of `n` pairs of a random expression and its corresponding AST."
[n]
(print "(list")
(doseq [_ (range n)]
(let [[e _] (expr/generate)]
(print (str "\n" (tab 1) "[\"" e "\""))
(let [ast (parser/parser (lexer/lexer e))]
((fn emit
([ast-fn depth l r]
(print ast-fn)
(emit l (inc depth))
(emit r (inc depth)))
([ast depth]
(print (str "\n" (tab depth) "("))
(case (ast/kind ast)
:symbol
(print (str "rpn.ast/symbol-AST \"" (ast :name) "\""))
:number
(print (str "rpn.ast/number-AST " (ast :value)))
:add
(emit "rpn.ast/add-AST" depth (ast :left) (ast :right))
:subtract
(emit "rpn.ast/subtract-AST" depth (ast :left) (ast :right))
:multiply
(emit "rpn.ast/multiply-AST" depth (ast :left) (ast :right))
:divide
(emit "rpn.ast/divide-AST" depth (ast :left) (ast :right))
:modulo
(emit "rpn.ast/modulo-AST" depth (ast :left) (ast :right))
:power
(emit "rpn.ast/power-AST" depth (ast :left) (ast :right))
:min
(emit "rpn.ast/min-AST" depth (ast :left) (ast :right))
:max
(emit "rpn.ast/max-AST" depth (ast :left) (ast :right)))
(print ")")))
ast 2))
(print "]")))
(println ")"))
(defn generator-tests
"Produces a sequence of `n` pairs of a random expression and its corresponding
unoptimized instruction sequence."
[n]
(print "(list")
(doseq [_ (range n)]
(let [[e _] (expr/generate)]
(println (str "\n" (tab 1) "[\"" e "\""))
(print (str (tab 2) "(list"))
(doseq [c (gen/generator (parser/parser (lexer/lexer e)))]
(print
(str "\n" (tab 3)
(case (code/kind c)
:declare-symbol
(str "(rpn.code/declare-symbol-code \"" (c :name) "\")")
:push-symbol
(str "(rpn.code/push-symbol-code \"" (c :name) "\")")
:push
(str "(rpn.code/push-code " (c :value) ")")
:add
(str "(rpn.code/add-code " (c :argn) ")")
:subtract
(str "(rpn.code/subtract-code " (c :argn) ")")
:multiply
(str "(rpn.code/multiply-code " (c :argn) ")")
:divide
(str "(rpn.code/divide-code " (c :argn) ")")
:min
(str "(rpn.code/min-code " (c :argn) ")")
:max
(str "(rpn.code/max-code " (c :argn) ")")
:modulo
"rpn.code/modulo-code"
:power
"rpn.code/power-code"))))
(print ")]")))
(println ")"))
(defn optimizer-tests
"Produces a sequence of at least `n` pairs of instructions with a computed
value.
The computed value is possible due to a method of assigning values to each
symbol during evalation using a deterministic hash. Since symbol names are
stable, an optimization of the instruction sequence should produce the
same value.
Note that in some cases, the precomputed value is `##NaN`, which gets quietly
ignored and does not appear in the final output, hence the reason for
possibly fewer than `n` pairs."
[n]
(print "(list")
(doseq [_ (range n)]
(let [[e _] (expr/generate)
cs (gen/generator (parser/parser (lexer/lexer e)))
r (evaluator/evaluator #(name-hash %) cs)]
(if-not (Double/isNaN r)
(do
(print (str "\n" (tab 1) "["))
(println r)
(print (str (tab 2) "(list"))
(doseq [c cs]
(print
(str "\n" (tab 3)
(case (code/kind c)
:declare-symbol
(str "(rpn.code/declare-symbol-code \"" (c :name) "\")")
:push-symbol
(str "(rpn.code/push-symbol-code \"" (c :name) "\")")
:push
(str "(rpn.code/push-code " (c :value) ")")
:add
(str "(rpn.code/add-code " (c :argn) ")")
:subtract
(str "(rpn.code/subtract-code " (c :argn) ")")
:multiply
(str "(rpn.code/multiply-code " (c :argn) ")")
:divide
(str "(rpn.code/divide-code " (c :argn) ")")
:min
(str "(rpn.code/min-code " (c :argn) ")")
:max
(str "(rpn.code/max-code " (c :argn) ")")
:modulo
"rpn.code/modulo-code"
:power
"rpn.code/power-code"))))
(print ")]")))))
(println ")"))
(defn- get-count [arg]
(if arg (Integer/parseInt arg) 100))
(defn -main [& args]
(try
(case (first args)
"-p"
(parser-tests (get-count (second args)))
"-g"
(generator-tests (get-count (second args)))
"-o"
(optimizer-tests (get-count (second args)))
(do
(println "Generate random expressions for inclusion in unit tests.")
(println " -p COUNT generate parser tests")
(println " -g COUNT generate generator tests")
(println " -o COUNT generate optimizer tests")))
(catch Exception e
(println e))))
| 10832 | ;;;
;;; Copyright 2020 <NAME>
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
;;;
(ns rpn.tools
"Tools for automatically generating random conformant expressions.
Note that these expressions are generated for testing purposes only and may
appear to be senseless when visually inspected. However, they do conform to
the specified grammar and are sufficient for detecting regressions.
The output of each test generation is formatted such that it can be
literally cut and pasted into the unit test itself."
(:require [clojure.string :as string])
(:require [rpn.expressions :as expr])
(:require [rpn.token :as token])
(:require [rpn.lexer :as lexer])
(:require [rpn.parser :as parser])
(:require [rpn.ast :as ast])
(:require [rpn.generator :as gen])
(:require [rpn.code :as code])
(:require [rpn.evaluator :as evaluator]))
(defn name-hash [name]
(/ (reduce #(+ %1 (/ (int %2) 100.0)) 0.0 name) 10.0))
(defn- tab [n]
(string/join (repeat (* n 2) \space)))
(defn parser-tests
"Produces a sequence of `n` pairs of a random expression and its corresponding AST."
[n]
(print "(list")
(doseq [_ (range n)]
(let [[e _] (expr/generate)]
(print (str "\n" (tab 1) "[\"" e "\""))
(let [ast (parser/parser (lexer/lexer e))]
((fn emit
([ast-fn depth l r]
(print ast-fn)
(emit l (inc depth))
(emit r (inc depth)))
([ast depth]
(print (str "\n" (tab depth) "("))
(case (ast/kind ast)
:symbol
(print (str "rpn.ast/symbol-AST \"" (ast :name) "\""))
:number
(print (str "rpn.ast/number-AST " (ast :value)))
:add
(emit "rpn.ast/add-AST" depth (ast :left) (ast :right))
:subtract
(emit "rpn.ast/subtract-AST" depth (ast :left) (ast :right))
:multiply
(emit "rpn.ast/multiply-AST" depth (ast :left) (ast :right))
:divide
(emit "rpn.ast/divide-AST" depth (ast :left) (ast :right))
:modulo
(emit "rpn.ast/modulo-AST" depth (ast :left) (ast :right))
:power
(emit "rpn.ast/power-AST" depth (ast :left) (ast :right))
:min
(emit "rpn.ast/min-AST" depth (ast :left) (ast :right))
:max
(emit "rpn.ast/max-AST" depth (ast :left) (ast :right)))
(print ")")))
ast 2))
(print "]")))
(println ")"))
(defn generator-tests
"Produces a sequence of `n` pairs of a random expression and its corresponding
unoptimized instruction sequence."
[n]
(print "(list")
(doseq [_ (range n)]
(let [[e _] (expr/generate)]
(println (str "\n" (tab 1) "[\"" e "\""))
(print (str (tab 2) "(list"))
(doseq [c (gen/generator (parser/parser (lexer/lexer e)))]
(print
(str "\n" (tab 3)
(case (code/kind c)
:declare-symbol
(str "(rpn.code/declare-symbol-code \"" (c :name) "\")")
:push-symbol
(str "(rpn.code/push-symbol-code \"" (c :name) "\")")
:push
(str "(rpn.code/push-code " (c :value) ")")
:add
(str "(rpn.code/add-code " (c :argn) ")")
:subtract
(str "(rpn.code/subtract-code " (c :argn) ")")
:multiply
(str "(rpn.code/multiply-code " (c :argn) ")")
:divide
(str "(rpn.code/divide-code " (c :argn) ")")
:min
(str "(rpn.code/min-code " (c :argn) ")")
:max
(str "(rpn.code/max-code " (c :argn) ")")
:modulo
"rpn.code/modulo-code"
:power
"rpn.code/power-code"))))
(print ")]")))
(println ")"))
(defn optimizer-tests
"Produces a sequence of at least `n` pairs of instructions with a computed
value.
The computed value is possible due to a method of assigning values to each
symbol during evalation using a deterministic hash. Since symbol names are
stable, an optimization of the instruction sequence should produce the
same value.
Note that in some cases, the precomputed value is `##NaN`, which gets quietly
ignored and does not appear in the final output, hence the reason for
possibly fewer than `n` pairs."
[n]
(print "(list")
(doseq [_ (range n)]
(let [[e _] (expr/generate)
cs (gen/generator (parser/parser (lexer/lexer e)))
r (evaluator/evaluator #(name-hash %) cs)]
(if-not (Double/isNaN r)
(do
(print (str "\n" (tab 1) "["))
(println r)
(print (str (tab 2) "(list"))
(doseq [c cs]
(print
(str "\n" (tab 3)
(case (code/kind c)
:declare-symbol
(str "(rpn.code/declare-symbol-code \"" (c :name) "\")")
:push-symbol
(str "(rpn.code/push-symbol-code \"" (c :name) "\")")
:push
(str "(rpn.code/push-code " (c :value) ")")
:add
(str "(rpn.code/add-code " (c :argn) ")")
:subtract
(str "(rpn.code/subtract-code " (c :argn) ")")
:multiply
(str "(rpn.code/multiply-code " (c :argn) ")")
:divide
(str "(rpn.code/divide-code " (c :argn) ")")
:min
(str "(rpn.code/min-code " (c :argn) ")")
:max
(str "(rpn.code/max-code " (c :argn) ")")
:modulo
"rpn.code/modulo-code"
:power
"rpn.code/power-code"))))
(print ")]")))))
(println ")"))
(defn- get-count [arg]
(if arg (Integer/parseInt arg) 100))
(defn -main [& args]
(try
(case (first args)
"-p"
(parser-tests (get-count (second args)))
"-g"
(generator-tests (get-count (second args)))
"-o"
(optimizer-tests (get-count (second args)))
(do
(println "Generate random expressions for inclusion in unit tests.")
(println " -p COUNT generate parser tests")
(println " -g COUNT generate generator tests")
(println " -o COUNT generate optimizer tests")))
(catch Exception e
(println e))))
| true | ;;;
;;; Copyright 2020 PI:NAME:<NAME>END_PI
;;;
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
;;;
(ns rpn.tools
"Tools for automatically generating random conformant expressions.
Note that these expressions are generated for testing purposes only and may
appear to be senseless when visually inspected. However, they do conform to
the specified grammar and are sufficient for detecting regressions.
The output of each test generation is formatted such that it can be
literally cut and pasted into the unit test itself."
(:require [clojure.string :as string])
(:require [rpn.expressions :as expr])
(:require [rpn.token :as token])
(:require [rpn.lexer :as lexer])
(:require [rpn.parser :as parser])
(:require [rpn.ast :as ast])
(:require [rpn.generator :as gen])
(:require [rpn.code :as code])
(:require [rpn.evaluator :as evaluator]))
(defn name-hash [name]
(/ (reduce #(+ %1 (/ (int %2) 100.0)) 0.0 name) 10.0))
(defn- tab [n]
(string/join (repeat (* n 2) \space)))
(defn parser-tests
"Produces a sequence of `n` pairs of a random expression and its corresponding AST."
[n]
(print "(list")
(doseq [_ (range n)]
(let [[e _] (expr/generate)]
(print (str "\n" (tab 1) "[\"" e "\""))
(let [ast (parser/parser (lexer/lexer e))]
((fn emit
([ast-fn depth l r]
(print ast-fn)
(emit l (inc depth))
(emit r (inc depth)))
([ast depth]
(print (str "\n" (tab depth) "("))
(case (ast/kind ast)
:symbol
(print (str "rpn.ast/symbol-AST \"" (ast :name) "\""))
:number
(print (str "rpn.ast/number-AST " (ast :value)))
:add
(emit "rpn.ast/add-AST" depth (ast :left) (ast :right))
:subtract
(emit "rpn.ast/subtract-AST" depth (ast :left) (ast :right))
:multiply
(emit "rpn.ast/multiply-AST" depth (ast :left) (ast :right))
:divide
(emit "rpn.ast/divide-AST" depth (ast :left) (ast :right))
:modulo
(emit "rpn.ast/modulo-AST" depth (ast :left) (ast :right))
:power
(emit "rpn.ast/power-AST" depth (ast :left) (ast :right))
:min
(emit "rpn.ast/min-AST" depth (ast :left) (ast :right))
:max
(emit "rpn.ast/max-AST" depth (ast :left) (ast :right)))
(print ")")))
ast 2))
(print "]")))
(println ")"))
(defn generator-tests
"Produces a sequence of `n` pairs of a random expression and its corresponding
unoptimized instruction sequence."
[n]
(print "(list")
(doseq [_ (range n)]
(let [[e _] (expr/generate)]
(println (str "\n" (tab 1) "[\"" e "\""))
(print (str (tab 2) "(list"))
(doseq [c (gen/generator (parser/parser (lexer/lexer e)))]
(print
(str "\n" (tab 3)
(case (code/kind c)
:declare-symbol
(str "(rpn.code/declare-symbol-code \"" (c :name) "\")")
:push-symbol
(str "(rpn.code/push-symbol-code \"" (c :name) "\")")
:push
(str "(rpn.code/push-code " (c :value) ")")
:add
(str "(rpn.code/add-code " (c :argn) ")")
:subtract
(str "(rpn.code/subtract-code " (c :argn) ")")
:multiply
(str "(rpn.code/multiply-code " (c :argn) ")")
:divide
(str "(rpn.code/divide-code " (c :argn) ")")
:min
(str "(rpn.code/min-code " (c :argn) ")")
:max
(str "(rpn.code/max-code " (c :argn) ")")
:modulo
"rpn.code/modulo-code"
:power
"rpn.code/power-code"))))
(print ")]")))
(println ")"))
(defn optimizer-tests
"Produces a sequence of at least `n` pairs of instructions with a computed
value.
The computed value is possible due to a method of assigning values to each
symbol during evalation using a deterministic hash. Since symbol names are
stable, an optimization of the instruction sequence should produce the
same value.
Note that in some cases, the precomputed value is `##NaN`, which gets quietly
ignored and does not appear in the final output, hence the reason for
possibly fewer than `n` pairs."
[n]
(print "(list")
(doseq [_ (range n)]
(let [[e _] (expr/generate)
cs (gen/generator (parser/parser (lexer/lexer e)))
r (evaluator/evaluator #(name-hash %) cs)]
(if-not (Double/isNaN r)
(do
(print (str "\n" (tab 1) "["))
(println r)
(print (str (tab 2) "(list"))
(doseq [c cs]
(print
(str "\n" (tab 3)
(case (code/kind c)
:declare-symbol
(str "(rpn.code/declare-symbol-code \"" (c :name) "\")")
:push-symbol
(str "(rpn.code/push-symbol-code \"" (c :name) "\")")
:push
(str "(rpn.code/push-code " (c :value) ")")
:add
(str "(rpn.code/add-code " (c :argn) ")")
:subtract
(str "(rpn.code/subtract-code " (c :argn) ")")
:multiply
(str "(rpn.code/multiply-code " (c :argn) ")")
:divide
(str "(rpn.code/divide-code " (c :argn) ")")
:min
(str "(rpn.code/min-code " (c :argn) ")")
:max
(str "(rpn.code/max-code " (c :argn) ")")
:modulo
"rpn.code/modulo-code"
:power
"rpn.code/power-code"))))
(print ")]")))))
(println ")"))
(defn- get-count [arg]
(if arg (Integer/parseInt arg) 100))
(defn -main [& args]
(try
(case (first args)
"-p"
(parser-tests (get-count (second args)))
"-g"
(generator-tests (get-count (second args)))
"-o"
(optimizer-tests (get-count (second args)))
(do
(println "Generate random expressions for inclusion in unit tests.")
(println " -p COUNT generate parser tests")
(println " -g COUNT generate generator tests")
(println " -o COUNT generate optimizer tests")))
(catch Exception e
(println e))))
|
[
{
"context": " :remote-addr \"127.0.0.1\"})\n => {:remote-addr \"example.com\" :headers ",
"end": 2911,
"score": 0.9997642040252686,
"start": 2902,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " ((wrap-x-forwarded-for identity) {:remote-addr \"123.123.123.123\"})\n => {:remote-addr \"123.123.123.123\"})\n\n(f",
"end": 3143,
"score": 0.9997430443763733,
"start": 3128,
"tag": "IP_ADDRESS",
"value": "123.123.123.123"
},
{
"context": "-addr \"123.123.123.123\"})\n => {:remote-addr \"123.123.123.123\"})\n\n(fact \"wrap-identity does not change request\"",
"end": 3186,
"score": 0.9997400045394897,
"start": 3171,
"tag": "IP_ADDRESS",
"value": "123.123.123.123"
}
] | test/ruuvi_server/util_test.clj | RuuviTracker/ruuvitracker_server | 1 | (ns ruuvi-server.util-test
(:use ruuvi-server.util)
(:use midje.sweet)
(:require [clojure.java.io :as io])
)
;; map handling
(fact "remove-nil-values returns nil as nil"
(remove-nil-values nil) => nil)
(fact "remove-nil-values removes nils and empty values from top level"
(remove-nil-values
{nil :x :a false :b nil :c 2 :d {} :e [] :f [1 2] :g {:a1 1 :b2 {} }})
=> {nil :x :a false :c 2 :f [1 2] :g {:a1 1 :b2 {} }})
(fact (modify-map {:a 1 :b 2} nil nil) => {:a 1 :b 2})
(fact (modify-map {:a 1 :b 2} {:x 1 :y 2} {:x 1 :y 1}) => {:a 1 :b 2})
(fact (modify-map {:a 1 :b 2} {:a :X :b :Y} {:a 42 :b 41}) => {:X 42 :Y 41})
(fact (modify-map {:a 1 :b 2}
{:a str :b (fn [x] (str x))}
{:a (fn [x] (+ x 1)) :b (fn [x] (+ x 1))})
=> {":a" 2 ":b" 3})
(fact (stringify-id-fields {}) => {})
(fact (stringify-id-fields {:a 1 :b 2}) => {:a 1 :b 2})
(fact (stringify-id-fields {:id 1 :foo_id 2 :bar_id 42 :foo "bar"})
=> {:id "1" :foo_id "2" :bar_id "42" :foo "bar"})
(fact (stringify-id-fields {:id nil :foo_id nil :bar_id false :foo "bar"})
=> {:id nil :foo_id nil :bar_id false :foo "bar"})
;; wrap-dir-index
(fact "wrap-dir-index appends index.html to end of :uri that ends with /"
((wrap-dir-index identity) {:uri "/"} ) => {:uri "/index.html"}
((wrap-dir-index identity) {:uri "/some/path/"} ) => {:uri "/some/path/index.html"}
)
(fact "wrap-dir-index leaves untouched :uri's that do not end with /"
((wrap-dir-index identity) {:uri "/path."} ) => {:uri "/path."}
((wrap-dir-index identity) {:uri "/some/path"} ) => {:uri "/some/path"}
((wrap-dir-index identity) {:uri "/some/path/index.html"} ) => {:uri "/some/path/index.html"})
;; wrap-add-html-suffix
(fact "wrap-add-html-suffix leaves untouched :uri's ending with /"
((wrap-add-html-suffix identity) {:uri "/"} ) => {:uri "/" }
((wrap-add-html-suffix identity) {:uri "/foo/"} ) => {:uri "/foo/" }
)
(fact "wrap-add-html-suffix leaves untouched :uri's containing a dot"
((wrap-add-html-suffix identity) {:uri "/foo.html"} ) => {:uri "/foo.html" }
((wrap-add-html-suffix identity) {:uri "/foo/foo.jpg"} ) => {:uri "/foo/foo.jpg" }
)
(fact "wrap-add-html-suffix adds '.html' suffix to :uri's that do not have a suffix"
((wrap-add-html-suffix identity) {:uri "/foo"} ) => {:uri "/foo.html" }
((wrap-add-html-suffix identity) {:uri "/path/foo.html"} ) => {:uri "/path/foo.html" }
)
(fact ":remote-addr value is replaced from x-forwarded-for value"
((wrap-x-forwarded-for identity) {:headers {"x-forwarded-for" "example.com"}})
=> {:remote-addr "example.com" :headers {"x-forwarded-for" "example.com"}}
((wrap-x-forwarded-for identity) {:headers {"x-forwarded-for" "example.com"}
:remote-addr "127.0.0.1"})
=> {:remote-addr "example.com" :headers {"x-forwarded-for" "example.com"}})
(fact ":remote-addr is not changed if x-forwarded-for header is not present"
((wrap-x-forwarded-for identity) {:remote-addr "123.123.123.123"})
=> {:remote-addr "123.123.123.123"})
(fact "wrap-identity does not change request"
((wrap-identity identity) {:a 1}) => {:a 1})
(fact (json-response {:params {}} {:a 1} ) =>
{:status 200, :headers {"Content-Type" "application/json;charset=UTF-8"},
:body "{\"a\":1}"}
(json-response {:params {}} {:a 1} 404) =>
{:status 404, :headers {"Content-Type" "application/json;charset=UTF-8"},
:body "{\"a\":1}"}
(json-response {:params {:jsonp "callb"}} {:a 1} ) =>
{:status 200, :headers {"Content-Type" "application/json;charset=UTF-8"},
:body "callb({\"a\":1})"}
(json-response {:params {:prettyPrint "true"}} {:a 1} ) =>
{:status 200, :headers {"Content-Type" "application/json;charset=UTF-8"},
:body "{\n \"a\" : 1\n}"}
)
(fact (json-error-response {:params {}} "error-msg1" 404) =>
{:status 404, :headers {"Content-Type" "application/json;charset=UTF-8"},
:body "{\"error\":{\"message\":\"error-msg1\"}}"} )
| 37660 | (ns ruuvi-server.util-test
(:use ruuvi-server.util)
(:use midje.sweet)
(:require [clojure.java.io :as io])
)
;; map handling
(fact "remove-nil-values returns nil as nil"
(remove-nil-values nil) => nil)
(fact "remove-nil-values removes nils and empty values from top level"
(remove-nil-values
{nil :x :a false :b nil :c 2 :d {} :e [] :f [1 2] :g {:a1 1 :b2 {} }})
=> {nil :x :a false :c 2 :f [1 2] :g {:a1 1 :b2 {} }})
(fact (modify-map {:a 1 :b 2} nil nil) => {:a 1 :b 2})
(fact (modify-map {:a 1 :b 2} {:x 1 :y 2} {:x 1 :y 1}) => {:a 1 :b 2})
(fact (modify-map {:a 1 :b 2} {:a :X :b :Y} {:a 42 :b 41}) => {:X 42 :Y 41})
(fact (modify-map {:a 1 :b 2}
{:a str :b (fn [x] (str x))}
{:a (fn [x] (+ x 1)) :b (fn [x] (+ x 1))})
=> {":a" 2 ":b" 3})
(fact (stringify-id-fields {}) => {})
(fact (stringify-id-fields {:a 1 :b 2}) => {:a 1 :b 2})
(fact (stringify-id-fields {:id 1 :foo_id 2 :bar_id 42 :foo "bar"})
=> {:id "1" :foo_id "2" :bar_id "42" :foo "bar"})
(fact (stringify-id-fields {:id nil :foo_id nil :bar_id false :foo "bar"})
=> {:id nil :foo_id nil :bar_id false :foo "bar"})
;; wrap-dir-index
(fact "wrap-dir-index appends index.html to end of :uri that ends with /"
((wrap-dir-index identity) {:uri "/"} ) => {:uri "/index.html"}
((wrap-dir-index identity) {:uri "/some/path/"} ) => {:uri "/some/path/index.html"}
)
(fact "wrap-dir-index leaves untouched :uri's that do not end with /"
((wrap-dir-index identity) {:uri "/path."} ) => {:uri "/path."}
((wrap-dir-index identity) {:uri "/some/path"} ) => {:uri "/some/path"}
((wrap-dir-index identity) {:uri "/some/path/index.html"} ) => {:uri "/some/path/index.html"})
;; wrap-add-html-suffix
(fact "wrap-add-html-suffix leaves untouched :uri's ending with /"
((wrap-add-html-suffix identity) {:uri "/"} ) => {:uri "/" }
((wrap-add-html-suffix identity) {:uri "/foo/"} ) => {:uri "/foo/" }
)
(fact "wrap-add-html-suffix leaves untouched :uri's containing a dot"
((wrap-add-html-suffix identity) {:uri "/foo.html"} ) => {:uri "/foo.html" }
((wrap-add-html-suffix identity) {:uri "/foo/foo.jpg"} ) => {:uri "/foo/foo.jpg" }
)
(fact "wrap-add-html-suffix adds '.html' suffix to :uri's that do not have a suffix"
((wrap-add-html-suffix identity) {:uri "/foo"} ) => {:uri "/foo.html" }
((wrap-add-html-suffix identity) {:uri "/path/foo.html"} ) => {:uri "/path/foo.html" }
)
(fact ":remote-addr value is replaced from x-forwarded-for value"
((wrap-x-forwarded-for identity) {:headers {"x-forwarded-for" "example.com"}})
=> {:remote-addr "example.com" :headers {"x-forwarded-for" "example.com"}}
((wrap-x-forwarded-for identity) {:headers {"x-forwarded-for" "example.com"}
:remote-addr "127.0.0.1"})
=> {:remote-addr "example.com" :headers {"x-forwarded-for" "example.com"}})
(fact ":remote-addr is not changed if x-forwarded-for header is not present"
((wrap-x-forwarded-for identity) {:remote-addr "172.16.17.32"})
=> {:remote-addr "172.16.17.32"})
(fact "wrap-identity does not change request"
((wrap-identity identity) {:a 1}) => {:a 1})
(fact (json-response {:params {}} {:a 1} ) =>
{:status 200, :headers {"Content-Type" "application/json;charset=UTF-8"},
:body "{\"a\":1}"}
(json-response {:params {}} {:a 1} 404) =>
{:status 404, :headers {"Content-Type" "application/json;charset=UTF-8"},
:body "{\"a\":1}"}
(json-response {:params {:jsonp "callb"}} {:a 1} ) =>
{:status 200, :headers {"Content-Type" "application/json;charset=UTF-8"},
:body "callb({\"a\":1})"}
(json-response {:params {:prettyPrint "true"}} {:a 1} ) =>
{:status 200, :headers {"Content-Type" "application/json;charset=UTF-8"},
:body "{\n \"a\" : 1\n}"}
)
(fact (json-error-response {:params {}} "error-msg1" 404) =>
{:status 404, :headers {"Content-Type" "application/json;charset=UTF-8"},
:body "{\"error\":{\"message\":\"error-msg1\"}}"} )
| true | (ns ruuvi-server.util-test
(:use ruuvi-server.util)
(:use midje.sweet)
(:require [clojure.java.io :as io])
)
;; map handling
(fact "remove-nil-values returns nil as nil"
(remove-nil-values nil) => nil)
(fact "remove-nil-values removes nils and empty values from top level"
(remove-nil-values
{nil :x :a false :b nil :c 2 :d {} :e [] :f [1 2] :g {:a1 1 :b2 {} }})
=> {nil :x :a false :c 2 :f [1 2] :g {:a1 1 :b2 {} }})
(fact (modify-map {:a 1 :b 2} nil nil) => {:a 1 :b 2})
(fact (modify-map {:a 1 :b 2} {:x 1 :y 2} {:x 1 :y 1}) => {:a 1 :b 2})
(fact (modify-map {:a 1 :b 2} {:a :X :b :Y} {:a 42 :b 41}) => {:X 42 :Y 41})
(fact (modify-map {:a 1 :b 2}
{:a str :b (fn [x] (str x))}
{:a (fn [x] (+ x 1)) :b (fn [x] (+ x 1))})
=> {":a" 2 ":b" 3})
(fact (stringify-id-fields {}) => {})
(fact (stringify-id-fields {:a 1 :b 2}) => {:a 1 :b 2})
(fact (stringify-id-fields {:id 1 :foo_id 2 :bar_id 42 :foo "bar"})
=> {:id "1" :foo_id "2" :bar_id "42" :foo "bar"})
(fact (stringify-id-fields {:id nil :foo_id nil :bar_id false :foo "bar"})
=> {:id nil :foo_id nil :bar_id false :foo "bar"})
;; wrap-dir-index
(fact "wrap-dir-index appends index.html to end of :uri that ends with /"
((wrap-dir-index identity) {:uri "/"} ) => {:uri "/index.html"}
((wrap-dir-index identity) {:uri "/some/path/"} ) => {:uri "/some/path/index.html"}
)
(fact "wrap-dir-index leaves untouched :uri's that do not end with /"
((wrap-dir-index identity) {:uri "/path."} ) => {:uri "/path."}
((wrap-dir-index identity) {:uri "/some/path"} ) => {:uri "/some/path"}
((wrap-dir-index identity) {:uri "/some/path/index.html"} ) => {:uri "/some/path/index.html"})
;; wrap-add-html-suffix
(fact "wrap-add-html-suffix leaves untouched :uri's ending with /"
((wrap-add-html-suffix identity) {:uri "/"} ) => {:uri "/" }
((wrap-add-html-suffix identity) {:uri "/foo/"} ) => {:uri "/foo/" }
)
(fact "wrap-add-html-suffix leaves untouched :uri's containing a dot"
((wrap-add-html-suffix identity) {:uri "/foo.html"} ) => {:uri "/foo.html" }
((wrap-add-html-suffix identity) {:uri "/foo/foo.jpg"} ) => {:uri "/foo/foo.jpg" }
)
(fact "wrap-add-html-suffix adds '.html' suffix to :uri's that do not have a suffix"
((wrap-add-html-suffix identity) {:uri "/foo"} ) => {:uri "/foo.html" }
((wrap-add-html-suffix identity) {:uri "/path/foo.html"} ) => {:uri "/path/foo.html" }
)
(fact ":remote-addr value is replaced from x-forwarded-for value"
((wrap-x-forwarded-for identity) {:headers {"x-forwarded-for" "example.com"}})
=> {:remote-addr "example.com" :headers {"x-forwarded-for" "example.com"}}
((wrap-x-forwarded-for identity) {:headers {"x-forwarded-for" "example.com"}
:remote-addr "127.0.0.1"})
=> {:remote-addr "example.com" :headers {"x-forwarded-for" "example.com"}})
(fact ":remote-addr is not changed if x-forwarded-for header is not present"
((wrap-x-forwarded-for identity) {:remote-addr "PI:IP_ADDRESS:172.16.17.32END_PI"})
=> {:remote-addr "PI:IP_ADDRESS:172.16.17.32END_PI"})
(fact "wrap-identity does not change request"
((wrap-identity identity) {:a 1}) => {:a 1})
(fact (json-response {:params {}} {:a 1} ) =>
{:status 200, :headers {"Content-Type" "application/json;charset=UTF-8"},
:body "{\"a\":1}"}
(json-response {:params {}} {:a 1} 404) =>
{:status 404, :headers {"Content-Type" "application/json;charset=UTF-8"},
:body "{\"a\":1}"}
(json-response {:params {:jsonp "callb"}} {:a 1} ) =>
{:status 200, :headers {"Content-Type" "application/json;charset=UTF-8"},
:body "callb({\"a\":1})"}
(json-response {:params {:prettyPrint "true"}} {:a 1} ) =>
{:status 200, :headers {"Content-Type" "application/json;charset=UTF-8"},
:body "{\n \"a\" : 1\n}"}
)
(fact (json-error-response {:params {}} "error-msg1" 404) =>
{:status 404, :headers {"Content-Type" "application/json;charset=UTF-8"},
:body "{\"error\":{\"message\":\"error-msg1\"}}"} )
|
[
{
"context": "opensource.org/licenses/MIT\"\n :author \"Yannick Scherer\"\n :year 2016\n :key \"mit\"}\n ",
"end": 278,
"score": 0.9998650550842285,
"start": 263,
"tag": "NAME",
"value": "Yannick Scherer"
}
] | project.clj | xsc/alumbra.parser | 16 | (defproject alumbra/parser "0.1.8-SNAPSHOT"
:description "A GraphQL parser for Clojure using ANTLR4."
:url "https://github.com/alumbra/alumbra.parser"
:license {:name "MIT License"
:url "https://opensource.org/licenses/MIT"
:author "Yannick Scherer"
:year 2016
:key "mit"}
:dependencies [[org.clojure/clojure "1.9.0-alpha14" :scope "provided"]
[alumbra/spec "0.1.7" :scope "provided"]
[clj-antlr "0.2.4"]]
:profiles {:dev {:dependencies [[org.clojure/test.check "0.9.0"]
[alumbra/generators "0.2.2"]]}
:codox {:plugins [[lein-codox "0.10.0"]]
:dependencies [[codox-theme-rdash "0.1.2"]]
:codox {:project {:name "alumbra.parser"}
:metadata {:doc/format :markdown}
:themes [:rdash]
:source-uri "https://github.com/alumbra/alumbra.parser/blob/v{version}/{filepath}#L{line}"
:namespaces [alumbra.parser]}}}
:aliases {"codox" ["with-profile" "+codox" "codox"]}
:pedantic? :abort)
| 63573 | (defproject alumbra/parser "0.1.8-SNAPSHOT"
:description "A GraphQL parser for Clojure using ANTLR4."
:url "https://github.com/alumbra/alumbra.parser"
:license {:name "MIT License"
:url "https://opensource.org/licenses/MIT"
:author "<NAME>"
:year 2016
:key "mit"}
:dependencies [[org.clojure/clojure "1.9.0-alpha14" :scope "provided"]
[alumbra/spec "0.1.7" :scope "provided"]
[clj-antlr "0.2.4"]]
:profiles {:dev {:dependencies [[org.clojure/test.check "0.9.0"]
[alumbra/generators "0.2.2"]]}
:codox {:plugins [[lein-codox "0.10.0"]]
:dependencies [[codox-theme-rdash "0.1.2"]]
:codox {:project {:name "alumbra.parser"}
:metadata {:doc/format :markdown}
:themes [:rdash]
:source-uri "https://github.com/alumbra/alumbra.parser/blob/v{version}/{filepath}#L{line}"
:namespaces [alumbra.parser]}}}
:aliases {"codox" ["with-profile" "+codox" "codox"]}
:pedantic? :abort)
| true | (defproject alumbra/parser "0.1.8-SNAPSHOT"
:description "A GraphQL parser for Clojure using ANTLR4."
:url "https://github.com/alumbra/alumbra.parser"
:license {:name "MIT License"
:url "https://opensource.org/licenses/MIT"
:author "PI:NAME:<NAME>END_PI"
:year 2016
:key "mit"}
:dependencies [[org.clojure/clojure "1.9.0-alpha14" :scope "provided"]
[alumbra/spec "0.1.7" :scope "provided"]
[clj-antlr "0.2.4"]]
:profiles {:dev {:dependencies [[org.clojure/test.check "0.9.0"]
[alumbra/generators "0.2.2"]]}
:codox {:plugins [[lein-codox "0.10.0"]]
:dependencies [[codox-theme-rdash "0.1.2"]]
:codox {:project {:name "alumbra.parser"}
:metadata {:doc/format :markdown}
:themes [:rdash]
:source-uri "https://github.com/alumbra/alumbra.parser/blob/v{version}/{filepath}#L{line}"
:namespaces [alumbra.parser]}}}
:aliases {"codox" ["with-profile" "+codox" "codox"]}
:pedantic? :abort)
|
[
{
"context": "maps asset 'keys' to local files.\"\n :author \"Kevin Neaton\"}\n overtone.libs.asset.store\n (:use [clojure.j",
"end": 144,
"score": 0.9998731017112732,
"start": 132,
"tag": "NAME",
"value": "Kevin Neaton"
}
] | src/overtone/libs/asset/store.clj | ABaldwinHunter/overtone | 1 | (ns
^{:doc "Local asset registry mechanism. Maintains a live file-store which maps asset 'keys' to local files."
:author "Kevin Neaton"}
overtone.libs.asset.store
(:use [clojure.java.io :only [file]]
[clojure.walk :only [postwalk]]
[overtone.helpers file]
[overtone.config.store :only [OVERTONE-ASSETS-FILE]]
[overtone.config.file-store]))
(defn- ensure-assets-file
"Creates empty assets file if one doesn't already exist"
[]
(when-not (file-exists? OVERTONE-ASSETS-FILE)
(write-file-store OVERTONE-ASSETS-FILE {})))
(defonce __ENSURE-LIVE-ASSET-STORE__
(ensure-assets-file))
(defonce assets* (live-file-store OVERTONE-ASSETS-FILE))
(defn- vectorize
"Returns a flat vector from the given args."
[& args]
(vec (flatten args)))
(defn- vectorize-values
"Flatten and vectorize the value of each map-entry."
[assets]
(map (fn [[k v]] [k (vectorize v)])
assets))
(defn- prune-assets
"Prunes map-entries containing empty or nil keys or vals."
[assets]
(remove (fn [[k v]]
(or (nil? k) (and (coll? k) (empty? k))
(nil? v) (and (coll? v) (empty? v))))
assets))
(defn- normalize-assets
"Normalize assets* to ensure that reading and writing works as expected."
[assets]
(->> assets
(prune-assets)
(vectorize-values)
(into {})))
(defn- update-assets*
"Modify the in-transaction-value of assets* with the provided fn and
args and normalizes the results before returning."
[assets fun & args]
(normalize-assets (apply fun assets args)))
(defn- resolve-paths
"Returns a seq of canonical path strings. Relative paths, directory paths,
tilde-paths, and glob strings will all be expanded relative to the current
project's root directory, resulting in a list of canonical file paths."
[paths]
(->> (mapcat ls* paths)
(filter #(.isFile %))
(map #(.getCanonicalPath %))))
(defn register-assets!
"Register the asset(s) at the given path(s) with the key provided. Directory
paths, tilde paths, and glob strings will all be expanded. Asset(s) previously
registered with the same key will be replaced. Returns the resulting entry."
[key & paths]
(let [paths (resolve-paths paths)]
(assert (every? file-exists? paths))
(let [new-assets (swap! assets* update-assets* assoc key paths)]
(select-keys new-assets [key]))))
(defn unregister-assets!
"Unregister all asset(s) registered with a given key. If paths are supplied
only those paths will be unregistered. Returns the resulting entry."
([key]
(swap! assets* dissoc key))
([key & paths]
(let [new-assets (swap! assets* update-assets* update-in [key] #(when % (remove (set paths) %)))]
(select-keys new-assets [key]))))
(defn registered-assets
"Get all of the asset paths registered with the given key. Provide a name to
filter by filename. Returns a seq of path strings or nil."
([key]
(get @assets* key))
([key name]
(when-let [paths (registered-assets key)]
(if name
(filter #(. % (endsWith (str (file-separator) name)))
paths)
paths))))
| 77180 | (ns
^{:doc "Local asset registry mechanism. Maintains a live file-store which maps asset 'keys' to local files."
:author "<NAME>"}
overtone.libs.asset.store
(:use [clojure.java.io :only [file]]
[clojure.walk :only [postwalk]]
[overtone.helpers file]
[overtone.config.store :only [OVERTONE-ASSETS-FILE]]
[overtone.config.file-store]))
(defn- ensure-assets-file
"Creates empty assets file if one doesn't already exist"
[]
(when-not (file-exists? OVERTONE-ASSETS-FILE)
(write-file-store OVERTONE-ASSETS-FILE {})))
(defonce __ENSURE-LIVE-ASSET-STORE__
(ensure-assets-file))
(defonce assets* (live-file-store OVERTONE-ASSETS-FILE))
(defn- vectorize
"Returns a flat vector from the given args."
[& args]
(vec (flatten args)))
(defn- vectorize-values
"Flatten and vectorize the value of each map-entry."
[assets]
(map (fn [[k v]] [k (vectorize v)])
assets))
(defn- prune-assets
"Prunes map-entries containing empty or nil keys or vals."
[assets]
(remove (fn [[k v]]
(or (nil? k) (and (coll? k) (empty? k))
(nil? v) (and (coll? v) (empty? v))))
assets))
(defn- normalize-assets
"Normalize assets* to ensure that reading and writing works as expected."
[assets]
(->> assets
(prune-assets)
(vectorize-values)
(into {})))
(defn- update-assets*
"Modify the in-transaction-value of assets* with the provided fn and
args and normalizes the results before returning."
[assets fun & args]
(normalize-assets (apply fun assets args)))
(defn- resolve-paths
"Returns a seq of canonical path strings. Relative paths, directory paths,
tilde-paths, and glob strings will all be expanded relative to the current
project's root directory, resulting in a list of canonical file paths."
[paths]
(->> (mapcat ls* paths)
(filter #(.isFile %))
(map #(.getCanonicalPath %))))
(defn register-assets!
"Register the asset(s) at the given path(s) with the key provided. Directory
paths, tilde paths, and glob strings will all be expanded. Asset(s) previously
registered with the same key will be replaced. Returns the resulting entry."
[key & paths]
(let [paths (resolve-paths paths)]
(assert (every? file-exists? paths))
(let [new-assets (swap! assets* update-assets* assoc key paths)]
(select-keys new-assets [key]))))
(defn unregister-assets!
"Unregister all asset(s) registered with a given key. If paths are supplied
only those paths will be unregistered. Returns the resulting entry."
([key]
(swap! assets* dissoc key))
([key & paths]
(let [new-assets (swap! assets* update-assets* update-in [key] #(when % (remove (set paths) %)))]
(select-keys new-assets [key]))))
(defn registered-assets
"Get all of the asset paths registered with the given key. Provide a name to
filter by filename. Returns a seq of path strings or nil."
([key]
(get @assets* key))
([key name]
(when-let [paths (registered-assets key)]
(if name
(filter #(. % (endsWith (str (file-separator) name)))
paths)
paths))))
| true | (ns
^{:doc "Local asset registry mechanism. Maintains a live file-store which maps asset 'keys' to local files."
:author "PI:NAME:<NAME>END_PI"}
overtone.libs.asset.store
(:use [clojure.java.io :only [file]]
[clojure.walk :only [postwalk]]
[overtone.helpers file]
[overtone.config.store :only [OVERTONE-ASSETS-FILE]]
[overtone.config.file-store]))
(defn- ensure-assets-file
"Creates empty assets file if one doesn't already exist"
[]
(when-not (file-exists? OVERTONE-ASSETS-FILE)
(write-file-store OVERTONE-ASSETS-FILE {})))
(defonce __ENSURE-LIVE-ASSET-STORE__
(ensure-assets-file))
(defonce assets* (live-file-store OVERTONE-ASSETS-FILE))
(defn- vectorize
"Returns a flat vector from the given args."
[& args]
(vec (flatten args)))
(defn- vectorize-values
"Flatten and vectorize the value of each map-entry."
[assets]
(map (fn [[k v]] [k (vectorize v)])
assets))
(defn- prune-assets
"Prunes map-entries containing empty or nil keys or vals."
[assets]
(remove (fn [[k v]]
(or (nil? k) (and (coll? k) (empty? k))
(nil? v) (and (coll? v) (empty? v))))
assets))
(defn- normalize-assets
"Normalize assets* to ensure that reading and writing works as expected."
[assets]
(->> assets
(prune-assets)
(vectorize-values)
(into {})))
(defn- update-assets*
"Modify the in-transaction-value of assets* with the provided fn and
args and normalizes the results before returning."
[assets fun & args]
(normalize-assets (apply fun assets args)))
(defn- resolve-paths
"Returns a seq of canonical path strings. Relative paths, directory paths,
tilde-paths, and glob strings will all be expanded relative to the current
project's root directory, resulting in a list of canonical file paths."
[paths]
(->> (mapcat ls* paths)
(filter #(.isFile %))
(map #(.getCanonicalPath %))))
(defn register-assets!
"Register the asset(s) at the given path(s) with the key provided. Directory
paths, tilde paths, and glob strings will all be expanded. Asset(s) previously
registered with the same key will be replaced. Returns the resulting entry."
[key & paths]
(let [paths (resolve-paths paths)]
(assert (every? file-exists? paths))
(let [new-assets (swap! assets* update-assets* assoc key paths)]
(select-keys new-assets [key]))))
(defn unregister-assets!
"Unregister all asset(s) registered with a given key. If paths are supplied
only those paths will be unregistered. Returns the resulting entry."
([key]
(swap! assets* dissoc key))
([key & paths]
(let [new-assets (swap! assets* update-assets* update-in [key] #(when % (remove (set paths) %)))]
(select-keys new-assets [key]))))
(defn registered-assets
"Get all of the asset paths registered with the given key. Provide a name to
filter by filename. Returns a seq of path strings or nil."
([key]
(get @assets* key))
([key name]
(when-let [paths (registered-assets key)]
(if name
(filter #(. % (endsWith (str (file-separator) name)))
paths)
paths))))
|
[
{
"context": "ue on valid email address\"\n (is (= (is-email? \"lady@example.com\") true)))\n (testing \"Returns false on invalid em",
"end": 225,
"score": 0.9999222755432129,
"start": 209,
"tag": "EMAIL",
"value": "lady@example.com"
},
{
"context": "Returns true on valid name\"\n (is (= (is-name? \"Lady\") true)))\n (testing \"Returns false on invalid na",
"end": 423,
"score": 0.9678584337234497,
"start": 419,
"tag": "NAME",
"value": "Lady"
},
{
"context": "lidate passes valid data\"\n (let [data {:email \"dude@example.com\"\n :first_name \"Dude\"\n ",
"end": 810,
"score": 0.9999131560325623,
"start": 794,
"tag": "EMAIL",
"value": "dude@example.com"
},
{
"context": "l \"dude@example.com\"\n :first_name \"Dude\"\n :last_name \"Dudeson\"}\n ",
"end": 845,
"score": 0.999780535697937,
"start": 841,
"tag": "NAME",
"value": "Dude"
},
{
"context": " :first_name \"Dude\"\n :last_name \"Dudeson\"}\n form (validate data)]\n (is (= (:",
"end": 882,
"score": 0.9997909069061279,
"start": 875,
"tag": "NAME",
"value": "Dudeson"
},
{
"context": "ors form) []))\n (is (= (:data form) {:email \"dude@example.com\"\n :first-name \"Dude\"\n ",
"end": 1032,
"score": 0.9999117255210876,
"start": 1016,
"tag": "EMAIL",
"value": "dude@example.com"
},
{
"context": "mple.com\"\n :first-name \"Dude\"\n :last-name \"Dudeson\"}",
"end": 1078,
"score": 0.9997478723526001,
"start": 1074,
"tag": "NAME",
"value": "Dude"
},
{
"context": "ame \"Dude\"\n :last-name \"Dudeson\"}))))\n (testing \"Validate fails invalid data\"\n ",
"end": 1126,
"score": 0.9998012185096741,
"start": 1119,
"tag": "NAME",
"value": "Dudeson"
},
{
"context": "idate fails invalid data\"\n (let [data {:email \"lady\"\n :first_name \"L\"\n ",
"end": 1202,
"score": 0.7984073162078857,
"start": 1198,
"tag": "NAME",
"value": "lady"
},
{
"context": "ors form))) 3)\n (is (= (:data form) {:email \"lady\"\n :first_name \"L\"\n ",
"end": 1482,
"score": 0.9241594076156616,
"start": 1478,
"tag": "NAME",
"value": "lady"
}
] | test/slack_signup/core_test.clj | jayzawrotny/clj-slack-signup | 0 | (ns slack-signup.core-test
(:require [clojure.test :refer :all]
[slack-signup.core :refer :all]))
(deftest is-email?-test
(testing "Returns true on valid email address"
(is (= (is-email? "lady@example.com") true)))
(testing "Returns false on invalid email address"
(is (= (is-email? "dude.fail") false))))
(deftest is-name?-test
(testing "Returns true on valid name"
(is (= (is-name? "Lady") true)))
(testing "Returns false on invalid name"
(is (= (is-name? "D") false))))
(deftest is-valid?-test
(testing "Returns true on valid data"
(is (= (is-valid? {:ok true}) true)))
(testing "Returns false on valid data"
(is (= (is-valid? {:ok false}) false))))
(deftest validate-test
(testing "Validate passes valid data"
(let [data {:email "dude@example.com"
:first_name "Dude"
:last_name "Dudeson"}
form (validate data)]
(is (= (:ok form) true))
(is (= (:errors form) []))
(is (= (:data form) {:email "dude@example.com"
:first-name "Dude"
:last-name "Dudeson"}))))
(testing "Validate fails invalid data"
(let [data {:email "lady"
:first_name "L"
:last_name " "}
form (validate data)]
(is (= (:ok form) false))
(is (= (keys (first (:errors form))) [:name :label :message]))
(is (= (count (:errors form))) 3)
(is (= (:data form) {:email "lady"
:first_name "L"
:last_name " "})))))
(deftest fork-test
(testing "Fork applies :then fn on success"
(is (= (fork {:ok true :data 1}
:ok
:then #(update % :data inc)
:else #(update % :data dec))
{:ok true :data 2})))
(testing "Fork applies :else fn on fail"
(is (= (fork {:ok false :data 1}
:ok
:then #(update % :data inc)
:else #(update % :data dec))
{:ok false :data 0}))))
| 88984 | (ns slack-signup.core-test
(:require [clojure.test :refer :all]
[slack-signup.core :refer :all]))
(deftest is-email?-test
(testing "Returns true on valid email address"
(is (= (is-email? "<EMAIL>") true)))
(testing "Returns false on invalid email address"
(is (= (is-email? "dude.fail") false))))
(deftest is-name?-test
(testing "Returns true on valid name"
(is (= (is-name? "<NAME>") true)))
(testing "Returns false on invalid name"
(is (= (is-name? "D") false))))
(deftest is-valid?-test
(testing "Returns true on valid data"
(is (= (is-valid? {:ok true}) true)))
(testing "Returns false on valid data"
(is (= (is-valid? {:ok false}) false))))
(deftest validate-test
(testing "Validate passes valid data"
(let [data {:email "<EMAIL>"
:first_name "<NAME>"
:last_name "<NAME>"}
form (validate data)]
(is (= (:ok form) true))
(is (= (:errors form) []))
(is (= (:data form) {:email "<EMAIL>"
:first-name "<NAME>"
:last-name "<NAME>"}))))
(testing "Validate fails invalid data"
(let [data {:email "<NAME>"
:first_name "L"
:last_name " "}
form (validate data)]
(is (= (:ok form) false))
(is (= (keys (first (:errors form))) [:name :label :message]))
(is (= (count (:errors form))) 3)
(is (= (:data form) {:email "<NAME>"
:first_name "L"
:last_name " "})))))
(deftest fork-test
(testing "Fork applies :then fn on success"
(is (= (fork {:ok true :data 1}
:ok
:then #(update % :data inc)
:else #(update % :data dec))
{:ok true :data 2})))
(testing "Fork applies :else fn on fail"
(is (= (fork {:ok false :data 1}
:ok
:then #(update % :data inc)
:else #(update % :data dec))
{:ok false :data 0}))))
| true | (ns slack-signup.core-test
(:require [clojure.test :refer :all]
[slack-signup.core :refer :all]))
(deftest is-email?-test
(testing "Returns true on valid email address"
(is (= (is-email? "PI:EMAIL:<EMAIL>END_PI") true)))
(testing "Returns false on invalid email address"
(is (= (is-email? "dude.fail") false))))
(deftest is-name?-test
(testing "Returns true on valid name"
(is (= (is-name? "PI:NAME:<NAME>END_PI") true)))
(testing "Returns false on invalid name"
(is (= (is-name? "D") false))))
(deftest is-valid?-test
(testing "Returns true on valid data"
(is (= (is-valid? {:ok true}) true)))
(testing "Returns false on valid data"
(is (= (is-valid? {:ok false}) false))))
(deftest validate-test
(testing "Validate passes valid data"
(let [data {:email "PI:EMAIL:<EMAIL>END_PI"
:first_name "PI:NAME:<NAME>END_PI"
:last_name "PI:NAME:<NAME>END_PI"}
form (validate data)]
(is (= (:ok form) true))
(is (= (:errors form) []))
(is (= (:data form) {:email "PI:EMAIL:<EMAIL>END_PI"
:first-name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"}))))
(testing "Validate fails invalid data"
(let [data {:email "PI:NAME:<NAME>END_PI"
:first_name "L"
:last_name " "}
form (validate data)]
(is (= (:ok form) false))
(is (= (keys (first (:errors form))) [:name :label :message]))
(is (= (count (:errors form))) 3)
(is (= (:data form) {:email "PI:NAME:<NAME>END_PI"
:first_name "L"
:last_name " "})))))
(deftest fork-test
(testing "Fork applies :then fn on success"
(is (= (fork {:ok true :data 1}
:ok
:then #(update % :data inc)
:else #(update % :data dec))
{:ok true :data 2})))
(testing "Fork applies :else fn on fail"
(is (= (fork {:ok false :data 1}
:ok
:then #(update % :data inc)
:else #(update % :data dec))
{:ok false :data 0}))))
|
[
{
"context": "he pretty printer for Clojure\r\n\r\n; Copyright (c) Rich Hickey. All rights reserved.\r\n; The use and distributi",
"end": 93,
"score": 0.9998617172241211,
"start": 82,
"tag": "NAME",
"value": "Rich Hickey"
},
{
"context": "e, or any other, from this software.\r\n\r\n;; Author: Tom Faulhaber\r\n;; April 3, 2009\r\n\r\n\r\n;; This module implements ",
"end": 560,
"score": 0.9998911619186401,
"start": 547,
"tag": "NAME",
"value": "Tom Faulhaber"
}
] | Internal/clojure/pprint/cl_format.clj | sonelliot/Arcadia | 3 | ;;; cl_format.clj -- part of the pretty printer for Clojure
; 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: Tom Faulhaber
;; April 3, 2009
;; This module implements the Common Lisp compatible format function as documented
;; in "Common Lisp the Language, 2nd edition", Chapter 22 (available online at:
;; http://www.cs.cmu.edu/afs/cs.cmu.edu/project/ai-repository/ai/html/cltl/clm/node200.html#SECTION002633000000000000000)
(in-ns 'clojure.pprint)
;;; Forward references
(declare compile-format)
(declare execute-format)
(declare init-navigator)
;;; End forward references
(defn cl-format
"An implementation of a Common Lisp compatible format function. cl-format formats its
arguments to an output stream or string based on the format control string given. It
supports sophisticated formatting of structured data.
Writer is an instance of java.io.Writer, true to output to *out* or nil to output
to a string, format-in is the format control string and the remaining arguments
are the data to be formatted.
The format control string is a string to be output with embedded 'format directives'
describing how to format the various arguments passed in.
If writer is nil, cl-format returns the formatted result string. Otherwise, cl-format
returns nil.
For example:
(let [results [46 38 22]]
(cl-format true \"There ~[are~;is~:;are~]~:* ~d result~:p: ~{~d~^, ~}~%\"
(count results) results))
Prints to *out*:
There are 3 results: 46, 38, 22
Detailed documentation on format control strings is available in the \"Common Lisp the
Language, 2nd edition\", Chapter 22 (available online at:
http://www.cs.cmu.edu/afs/cs.cmu.edu/project/ai-repository/ai/html/cltl/clm/node200.html#SECTION002633000000000000000)
and in the Common Lisp HyperSpec at
http://www.lispworks.com/documentation/HyperSpec/Body/22_c.htm
"
{:added "1.2",
:see-also [["http://www.cs.cmu.edu/afs/cs.cmu.edu/project/ai-repository/ai/html/cltl/clm/node200.html#SECTION002633000000000000000"
"Common Lisp the Language"]
["http://www.lispworks.com/documentation/HyperSpec/Body/22_c.htm"
"Common Lisp HyperSpec"]]}
[writer format-in & args]
(let [compiled-format (if (string? format-in) (compile-format format-in) format-in)
navigator (init-navigator args)]
(execute-format writer compiled-format navigator)))
(def ^:dynamic ^{:private true} *format-str* nil)
(defn- format-error [message offset]
(let [full-message (str message \newline *format-str* \newline
(apply str (repeat offset \space)) "^" \newline)]
(throw (Exception. full-message)))) ;;; RuntimeException
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Argument navigators manage the argument list
;;; as the format statement moves through the list
;;; (possibly going forwards and backwards as it does so)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defstruct ^{:private true}
arg-navigator :seq :rest :pos )
(defn- init-navigator
"Create a new arg-navigator from the sequence with the position set to 0"
{:skip-wiki true}
[s]
(let [s (seq s)]
(struct arg-navigator s s 0)))
;; TODO call format-error with offset
(defn- next-arg [ navigator ]
(let [ rst (:rest navigator) ]
(if rst
[(first rst) (struct arg-navigator (:seq navigator ) (next rst) (inc (:pos navigator)))]
(throw (new Exception "Not enough arguments for format definition")))))
(defn- next-arg-or-nil [navigator]
(let [rst (:rest navigator)]
(if rst
[(first rst) (struct arg-navigator (:seq navigator ) (next rst) (inc (:pos navigator)))]
[nil navigator])))
;; Get an argument off the arg list and compile it if it's not already compiled
(defn- get-format-arg [navigator]
(let [[raw-format navigator] (next-arg navigator)
compiled-format (if (instance? String raw-format)
(compile-format raw-format)
raw-format)]
[compiled-format navigator]))
(declare relative-reposition)
(defn- absolute-reposition [navigator position]
(if (>= position (:pos navigator))
(relative-reposition navigator (- (:pos navigator) position))
(struct arg-navigator (:seq navigator) (drop position (:seq navigator)) position)))
(defn- relative-reposition [navigator position]
(let [newpos (+ (:pos navigator) position)]
(if (neg? position)
(absolute-reposition navigator newpos)
(struct arg-navigator (:seq navigator) (drop position (:rest navigator)) newpos))))
(defstruct ^{:private true}
compiled-directive :func :def :params :offset)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; When looking at the parameter list, we may need to manipulate
;;; the argument list as well (for 'V' and '#' parameter types).
;;; We hide all of this behind a function, but clients need to
;;; manage changing arg navigator
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; TODO: validate parameters when they come from arg list
(defn- realize-parameter [[param [raw-val offset]] navigator]
(let [[real-param new-navigator]
(cond
(contains? #{ :at :colon } param) ;pass flags through unchanged - this really isn't necessary
[raw-val navigator]
(= raw-val :parameter-from-args)
(next-arg navigator)
(= raw-val :remaining-arg-count)
[(count (:rest navigator)) navigator]
true
[raw-val navigator])]
[[param [real-param offset]] new-navigator]))
(defn- realize-parameter-list [parameter-map navigator]
(let [[pairs new-navigator]
(map-passing-context realize-parameter navigator parameter-map)]
[(into {} pairs) new-navigator]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Functions that support individual directives
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Common handling code for ~A and ~S
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(declare opt-base-str)
(def ^{:private true}
special-radix-markers {2 "#b" 8 "#o", 16 "#x"})
(defn- format-simple-number [n]
(cond
(integer? n) (if (= *print-base* 10)
(str n (if *print-radix* "."))
(str
(if *print-radix* (or (get special-radix-markers *print-base*) (str "#" *print-base* "r")))
(opt-base-str *print-base* n)))
(ratio? n) (str
(if *print-radix* (or (get special-radix-markers *print-base*) (str "#" *print-base* "r")))
(opt-base-str *print-base* (.numerator n))
"/"
(opt-base-str *print-base* (.denominator n)))
:else nil))
(defn- format-ascii [print-func params arg-navigator offsets]
(let [ [arg arg-navigator] (next-arg arg-navigator)
^String base-output (or (format-simple-number arg) (print-func arg))
base-width (.Length base-output) ;;; length
min-width (+ base-width (:minpad params))
width (if (>= min-width (:mincol params))
min-width
(+ min-width
(* (+ (quot (- (:mincol params) min-width 1)
(:colinc params) )
1)
(:colinc params))))
chars (apply str (repeat (- width base-width) (:padchar params)))]
(if (:at params)
(print (str chars base-output))
(print (str base-output chars)))
arg-navigator))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for the integer directives ~D, ~X, ~O, ~B and some
;;; of ~R
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- integral?
"returns true if a number is actually an integer (that is, has no fractional part)"
[x]
(cond
(integer? x) true
(decimal? x) true ;;; TODO: FIX THIS (>= (.ulp (.stripTrailingZeros (bigdec 0))) 1) ; true iff no fractional part DM: ??????? doesn't mention x!!!
(float? x) (= x (Math/Floor x)) ;;; Math/floor
(ratio? x) (let [^clojure.lang.Ratio r x]
(= 0 (rem (.numerator r) (.denominator r))))
:else false))
(defn- remainders
"Return the list of remainders (essentially the 'digits') of val in the given base"
[base val]
(reverse
(first
(consume #(if (pos? %)
[(rem % base) (quot % base)]
[nil nil])
val))))
;;; TODO: xlated-val does not seem to be used here. ---- ;;;; I had to use it to prevent the call to remainders from returning a Double instead of an integer in the last position
(defn- base-str
"Return val as a string in the given base"
[base val]
(if (zero? val)
"0"
(let [xlated-val (cond
(float? val) (bigdec val)
(ratio? val) (let [^clojure.lang.Ratio r val]
(/ (.numerator r) (.denominator r)))
:else val)]
(apply str
(map
#(if (< % 10) (char (+ (int \0) %)) (char (+ (int \a) (- % 10))))
(remainders base xlated-val))))))
(def ^{:private true}
java-base-formats {8 "%o", 10 "%d", 16 "%x"})
(defn- opt-base-str
"Return val as a string in the given base, using clojure.core/format if supported
for improved performance"
[base val]
(let [format-str (get java-base-formats base)]
(if (and format-str (integer? val) (not (instance? clojure.lang.BigInt val)))
(clojure.core/format format-str val)
(base-str base val))))
(defn- group-by* [unit lis]
(reverse
(first
(consume (fn [x] [(seq (reverse (take unit x))) (seq (drop unit x))]) (reverse lis)))))
(defn- format-integer [base params arg-navigator offsets]
(let [[arg arg-navigator] (next-arg arg-navigator)]
(if (integral? arg)
(let [neg (neg? arg)
pos-arg (if neg (- arg) arg)
raw-str (opt-base-str base pos-arg)
group-str (if (:colon params)
(let [groups (map #(apply str %) (group-by* (:commainterval params) raw-str))
commas (repeat (count groups) (:commachar params))]
(apply str (next (interleave commas groups))))
raw-str)
^String signed-str (cond
neg (str "-" group-str)
(:at params) (str "+" group-str)
true group-str)
padded-str (if (< (.Length signed-str) (:mincol params)) ;;; length
(str (apply str (repeat (- (:mincol params) (.Length signed-str)) ;;; length
(:padchar params)))
signed-str)
signed-str)]
(print padded-str))
(format-ascii print-str {:mincol (:mincol params) :colinc 1 :minpad 0
:padchar (:padchar params) :at true}
(init-navigator [arg]) nil))
arg-navigator))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for english formats (~R and ~:R)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^{:private true}
english-cardinal-units
["zero" "one" "two" "three" "four" "five" "six" "seven" "eight" "nine"
"ten" "eleven" "twelve" "thirteen" "fourteen"
"fifteen" "sixteen" "seventeen" "eighteen" "nineteen"])
(def ^{:private true}
english-ordinal-units
["zeroth" "first" "second" "third" "fourth" "fifth" "sixth" "seventh" "eighth" "ninth"
"tenth" "eleventh" "twelfth" "thirteenth" "fourteenth"
"fifteenth" "sixteenth" "seventeenth" "eighteenth" "nineteenth"])
(def ^{:private true}
english-cardinal-tens
["" "" "twenty" "thirty" "forty" "fifty" "sixty" "seventy" "eighty" "ninety"])
(def ^{:private true}
english-ordinal-tens
["" "" "twentieth" "thirtieth" "fortieth" "fiftieth"
"sixtieth" "seventieth" "eightieth" "ninetieth"])
;; We use "short scale" for our units (see http://en.wikipedia.org/wiki/Long_and_short_scales)
;; Number names from http://www.jimloy.com/math/billion.htm
;; We follow the rules for writing numbers from the Blue Book
;; (http://www.grammarbook.com/numbers/numbers.asp)
(def ^{:private true}
english-scale-numbers
["" "thousand" "million" "billion" "trillion" "quadrillion" "quintillion"
"sextillion" "septillion" "octillion" "nonillion" "decillion"
"undecillion" "duodecillion" "tredecillion" "quattuordecillion"
"quindecillion" "sexdecillion" "septendecillion"
"octodecillion" "novemdecillion" "vigintillion"])
(defn- format-simple-cardinal
"Convert a number less than 1000 to a cardinal english string"
[num]
(let [hundreds (quot num 100)
tens (rem num 100)]
(str
(if (pos? hundreds) (str (nth english-cardinal-units hundreds) " hundred"))
(if (and (pos? hundreds) (pos? tens)) " ")
(if (pos? tens)
(if (< tens 20)
(nth english-cardinal-units tens)
(let [ten-digit (quot tens 10)
unit-digit (rem tens 10)]
(str
(if (pos? ten-digit) (nth english-cardinal-tens ten-digit))
(if (and (pos? ten-digit) (pos? unit-digit)) "-")
(if (pos? unit-digit) (nth english-cardinal-units unit-digit)))))))))
(defn- add-english-scales
"Take a sequence of parts, add scale numbers (e.g., million) and combine into a string
offset is a factor of 10^3 to multiply by"
[parts offset]
(let [cnt (count parts)]
(loop [acc []
pos (dec cnt)
this (first parts)
remainder (next parts)]
(if (nil? remainder)
(str (apply str (interpose ", " acc))
(if (and (not (empty? this)) (not (empty? acc))) ", ")
this
(if (and (not (empty? this)) (pos? (+ pos offset)))
(str " " (nth english-scale-numbers (+ pos offset)))))
(recur
(if (empty? this)
acc
(conj acc (str this " " (nth english-scale-numbers (+ pos offset)))))
(dec pos)
(first remainder)
(next remainder))))))
(defn- format-cardinal-english [params navigator offsets]
(let [[arg navigator] (next-arg navigator)]
(if (= 0 arg)
(print "zero")
(let [abs-arg (if (neg? arg) (- arg) arg) ; some numbers are too big for Math/abs
parts (remainders 1000 abs-arg)]
(if (<= (count parts) (count english-scale-numbers))
(let [parts-strs (map format-simple-cardinal parts)
full-str (add-english-scales parts-strs 0)]
(print (str (if (neg? arg) "minus ") full-str)))
(format-integer ;; for numbers > 10^63, we fall back on ~D
10
{ :mincol 0, :padchar \space, :commachar \, :commainterval 3, :colon true}
(init-navigator [arg])
{ :mincol 0, :padchar 0, :commachar 0 :commainterval 0}))))
navigator))
(defn- format-simple-ordinal
"Convert a number less than 1000 to a ordinal english string
Note this should only be used for the last one in the sequence"
[num]
(let [hundreds (quot num 100)
tens (rem num 100)]
(str
(if (pos? hundreds) (str (nth english-cardinal-units hundreds) " hundred"))
(if (and (pos? hundreds) (pos? tens)) " ")
(if (pos? tens)
(if (< tens 20)
(nth english-ordinal-units tens)
(let [ten-digit (quot tens 10)
unit-digit (rem tens 10)]
(if (and (pos? ten-digit) (not (pos? unit-digit)))
(nth english-ordinal-tens ten-digit)
(str
(if (pos? ten-digit) (nth english-cardinal-tens ten-digit))
(if (and (pos? ten-digit) (pos? unit-digit)) "-")
(if (pos? unit-digit) (nth english-ordinal-units unit-digit))))))
(if (pos? hundreds) "th")))))
(defn- format-ordinal-english [params navigator offsets]
(let [[arg navigator] (next-arg navigator)]
(if (= 0 arg)
(print "zeroth")
(let [abs-arg (if (neg? arg) (- arg) arg) ; some numbers are too big for Math/abs
parts (remainders 1000 abs-arg)]
(if (<= (count parts) (count english-scale-numbers))
(let [parts-strs (map format-simple-cardinal (drop-last parts))
head-str (add-english-scales parts-strs 1)
tail-str (format-simple-ordinal (last parts))]
(print (str (if (neg? arg) "minus ")
(cond
(and (not (empty? head-str)) (not (empty? tail-str)))
(str head-str ", " tail-str)
(not (empty? head-str)) (str head-str "th")
:else tail-str))))
(do (format-integer ;; for numbers > 10^63, we fall back on ~D
10
{ :mincol 0, :padchar \space, :commachar \, :commainterval 3, :colon true}
(init-navigator [arg])
{ :mincol 0, :padchar 0, :commachar 0 :commainterval 0})
(let [low-two-digits (rem arg 100)
not-teens (or (< 11 low-two-digits) (> 19 low-two-digits))
low-digit (rem low-two-digits 10)]
(print (cond
(and (== low-digit 1) not-teens) "st"
(and (== low-digit 2) not-teens) "nd"
(and (== low-digit 3) not-teens) "rd"
:else "th")))))))
navigator))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for roman numeral formats (~@R and ~@:R)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^{:private true}
old-roman-table
[[ "I" "II" "III" "IIII" "V" "VI" "VII" "VIII" "VIIII"]
[ "X" "XX" "XXX" "XXXX" "L" "LX" "LXX" "LXXX" "LXXXX"]
[ "C" "CC" "CCC" "CCCC" "D" "DC" "DCC" "DCCC" "DCCCC"]
[ "M" "MM" "MMM"]])
(def ^{:private true}
new-roman-table
[[ "I" "II" "III" "IV" "V" "VI" "VII" "VIII" "IX"]
[ "X" "XX" "XXX" "XL" "L" "LX" "LXX" "LXXX" "XC"]
[ "C" "CC" "CCC" "CD" "D" "DC" "DCC" "DCCC" "CM"]
[ "M" "MM" "MMM"]])
(defn- format-roman
"Format a roman numeral using the specified look-up table"
[table params navigator offsets]
(let [[arg navigator] (next-arg navigator)]
(if (and (number? arg) (> arg 0) (< arg 4000))
(let [digits (remainders 10 arg)]
(loop [acc []
pos (dec (count digits))
digits digits]
(if (empty? digits)
(print (apply str acc))
(let [digit (first digits)]
(recur (if (= 0 digit)
acc
(conj acc (nth (nth table pos) (dec digit))))
(dec pos)
(next digits))))))
(format-integer ;; for anything <= 0 or > 3999, we fall back on ~D
10
{ :mincol 0, :padchar \space, :commachar \, :commainterval 3, :colon true}
(init-navigator [arg])
{ :mincol 0, :padchar 0, :commachar 0 :commainterval 0}))
navigator))
(defn- format-old-roman [params navigator offsets]
(format-roman old-roman-table params navigator offsets))
(defn- format-new-roman [params navigator offsets]
(format-roman new-roman-table params navigator offsets))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for character formats (~C)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^{:private true}
special-chars { 8 "Backspace", 9 "Tab", 10 "Newline", 13 "Return", 32 "Space"})
(defn- pretty-character [params navigator offsets]
(let [[c navigator] (next-arg navigator)
as-int (int c)
base-char (bit-and as-int 127)
meta (bit-and as-int 128)
special (get special-chars base-char)]
(if (> meta 0) (print "Meta-"))
(print (cond
special special
(< base-char 32) (str "Control-" (char (+ base-char 64)))
(= base-char 127) "Control-?"
:else (char base-char)))
navigator))
(defn- readable-character [params navigator offsets]
(let [[c navigator] (next-arg navigator)]
(condp = (:char-format params)
\o (cl-format true "\\o~3,'0o" (int c))
\u (cl-format true "\\u~4,'0x" (int c))
nil (pr c))
navigator))
(defn- plain-character [params navigator offsets]
(let [[char navigator] (next-arg navigator)]
(print char)
navigator))
;; Check to see if a result is an abort (~^) construct
;; TODO: move these funcs somewhere more appropriate
(defn- abort? [context]
(let [token (first context)]
(or (= :up-arrow token) (= :colon-up-arrow token))))
;; Handle the execution of "sub-clauses" in bracket constructions
(defn- execute-sub-format [format args base-args]
(second
(map-passing-context
(fn [element context]
(if (abort? context)
[nil context] ; just keep passing it along
(let [[params args] (realize-parameter-list (:params element) context)
[params offsets] (unzip-map params)
params (assoc params :base-args base-args)]
[nil (apply (:func element) [params args offsets])])))
args
format)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for real number formats
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; TODO - return exponent as int to eliminate double conversion
(defn- float-parts-base
"Produce string parts for the mantissa (normalized 1-9) and exponent"
[^Object f]
(let [^String s (.ToLower (.ToString f)) ;;; .toLowerCase .toString
exploc (.IndexOf s \e) ;;; .indexOf (int \e)
dotloc (.IndexOf s \.)] ;;; .indexOf (int \.)
(if (neg? exploc)
(if (neg? dotloc)
[s (str (dec (count s)))]
[(str (subs s 0 dotloc) (subs s (inc dotloc))) (str (dec dotloc))])
(if (neg? dotloc)
[(subs s 0 exploc) (subs s (inc exploc))]
[(str (subs s 0 1) (subs s 2 exploc)) (subs s (inc exploc))]))))
(defn- float-parts
"Take care of leading and trailing zeros in decomposed floats"
[f]
(let [[m ^String e] (float-parts-base f)
m1 (rtrim m \0)
m2 (ltrim m1 \0)
delta (- (count m1) (count m2))
^String e (if (and (pos? (count e)) (= (nth e 0) \+)) (subs e 1) e)]
(if (empty? m2)
["0" 0]
[m2 (- (Int32/Parse e) delta)]))) ;;; (Integer/valueOf e)
(defn- ^String inc-s
"Assumption: The input string consists of one or more decimal digits,
and no other characters. Return a string containing one or more
decimal digits containing a decimal number one larger than the input
string. The output string will always be the same length as the input
string, or one character longer."
[^String s]
(let [len-1 (dec (count s))]
(loop [i (int len-1)]
(cond
(neg? i) (apply str "1" (repeat (inc len-1) "0"))
(= \9 (.get_Chars s i)) (recur (dec i)) ;;; .charAt
:else (apply str (subs s 0 i)
(char (inc (int (.get_Chars s i)))) ;;; .charAt
(repeat (- len-1 i) "0"))))))
(defn- round-str [m e d w]
(if (or d w)
(let [len (count m)
;; Every formatted floating point number should include at
;; least one decimal digit and a decimal point.
w (if w (max 2 w))
round-pos (cond
;; If d was given, that forces the rounding
;; position, regardless of any width that may
;; have been specified.
d (+ e d 1)
;; Otherwise w was specified, so pick round-pos
;; based upon that.
;; If e>=0, then abs value of number is >= 1.0,
;; and e+1 is number of decimal digits before the
;; decimal point when the number is written
;; without scientific notation. Never round the
;; number before the decimal point.
(>= e 0) (max (inc e) (dec w))
;; e < 0, so number abs value < 1.0
:else (+ w e))
[m1 e1 round-pos len] (if (= round-pos 0)
[(str "0" m) (inc e) 1 (inc len)]
[m e round-pos len])]
(if round-pos
(if (neg? round-pos)
["0" 0 false]
(if (> len round-pos)
(let [round-char (nth m1 round-pos)
^String result (subs m1 0 round-pos)]
(if (>= (int round-char) (int \5))
(let [round-up-result (inc-s result)
expanded (> (count round-up-result) (count result))]
[(if expanded
(subs round-up-result 0 (dec (count round-up-result)))
round-up-result)
e1 expanded])
[result e1 false]))
[m e false]))
[m e false]))
[m e false]))
(defn- expand-fixed [m e d]
(let [[m1 e1] (if (neg? e)
[(str (apply str (repeat (dec (- e)) \0)) m) -1]
[m e])
len (count m1)
target-len (if d (+ e1 d 1) (inc e1))]
(if (< len target-len)
(str m1 (apply str (repeat (- target-len len) \0)))
m1)))
(defn- insert-decimal
"Insert the decimal point at the right spot in the number to match an exponent"
[m e]
(if (neg? e)
(str "." m)
(let [loc (inc e)]
(str (subs m 0 loc) "." (subs m loc)))))
(defn- get-fixed [m e d]
(insert-decimal (expand-fixed m e d) e))
(defn- insert-scaled-decimal
"Insert the decimal point at the right spot in the number to match an exponent"
[m k]
(if (neg? k)
(str "." m)
(str (subs m 0 k) "." (subs m k))))
(defn- convert-ratio [x]
(if (ratio? x)
;; Usually convert to a double, only resorting to the slower
;; bigdec conversion if the result does not fit within the range
;; of a double.
(let [d (double x)]
(if (== d 0.0)
(if (not= x 0)
(bigdec x)
d)
(if (or (== d Double/PositiveInfinity) (== d Double/NegativeInfinity)) ;;; Double/POSITIVE_INFINITY Double/NEGATIVE_INFINITY
(bigdec x)
d)))
x))
;; the function to render ~F directives
;; TODO: support rationals. Back off to ~D/~A is the appropriate cases
(defn- fixed-float [params navigator offsets]
(let [w (:w params)
d (:d params)
[arg navigator] (next-arg navigator)
[sign abs] (if (neg? arg) ["-" (- arg)] ["+" arg])
abs (convert-ratio abs)
[mantissa exp] (float-parts abs)
scaled-exp (+ exp (:k params))
add-sign (or (:at params) (neg? arg))
append-zero (and (not d) (<= (dec (count mantissa)) scaled-exp))
[rounded-mantissa scaled-exp expanded] (round-str mantissa scaled-exp
d (if w (- w (if add-sign 1 0))))
fixed-repr (get-fixed rounded-mantissa (if expanded (inc scaled-exp) scaled-exp) d)
fixed-repr (if (and w d
(>= d 1)
(= (.get_Chars fixed-repr 0) \0) ;;; .charAt
(= (.get_Chars fixed-repr 1) \.) ;;; .charAt
(> (count fixed-repr) (- w (if add-sign 1 0))))
(subs fixed-repr 1) ; chop off leading 0
fixed-repr)
prepend-zero (= (first fixed-repr) \.)]
(if w
(let [len (count fixed-repr)
signed-len (if add-sign (inc len) len)
prepend-zero (and prepend-zero (not (>= signed-len w)))
append-zero (and append-zero (not (>= signed-len w)))
full-len (if (or prepend-zero append-zero)
(inc signed-len)
signed-len)]
(if (and (> full-len w) (:overflowchar params))
(print (apply str (repeat w (:overflowchar params))))
(print (str
(apply str (repeat (- w full-len) (:padchar params)))
(if add-sign sign)
(if prepend-zero "0")
fixed-repr
(if append-zero "0")))))
(print (str
(if add-sign sign)
(if prepend-zero "0")
fixed-repr
(if append-zero "0"))))
navigator))
;; the function to render ~E directives
;; TODO: support rationals. Back off to ~D/~A is the appropriate cases
;; TODO: define ~E representation for Infinity
(defn- exponential-float [params navigator offsets]
(let [[arg navigator] (next-arg navigator)
arg (convert-ratio arg)]
(loop [[mantissa exp] (float-parts (if (neg? arg) (- arg) arg))]
(let [w (:w params)
d (:d params)
e (:e params)
k (:k params)
expchar (or (:exponentchar params) \E)
add-sign (or (:at params) (neg? arg))
prepend-zero (<= k 0)
^Int32 scaled-exp (- exp (dec k)) ;;; Integer
scaled-exp-str (str (Math/Abs scaled-exp)) ;;; Math/abs
scaled-exp-str (str expchar (if (neg? scaled-exp) \- \+)
(if e (apply str
(repeat
(- e
(count scaled-exp-str))
\0)))
scaled-exp-str)
exp-width (count scaled-exp-str)
base-mantissa-width (count mantissa)
scaled-mantissa (str (apply str (repeat (- k) \0))
mantissa
(if d
(apply str
(repeat
(- d (dec base-mantissa-width)
(if (neg? k) (- k) 0)) \0))))
w-mantissa (if w (- w exp-width))
[rounded-mantissa _ incr-exp] (round-str
scaled-mantissa 0
(cond
(= k 0) (dec d)
(pos? k) d
(neg? k) (dec d))
(if w-mantissa
(- w-mantissa (if add-sign 1 0))))
full-mantissa (insert-scaled-decimal rounded-mantissa k)
append-zero (and (= k (count rounded-mantissa)) (nil? d))]
(if (not incr-exp)
(if w
(let [len (+ (count full-mantissa) exp-width)
signed-len (if add-sign (inc len) len)
prepend-zero (and prepend-zero (not (= signed-len w)))
full-len (if prepend-zero (inc signed-len) signed-len)
append-zero (and append-zero (< full-len w))]
(if (and (or (> full-len w) (and e (> (- exp-width 2) e)))
(:overflowchar params))
(print (apply str (repeat w (:overflowchar params))))
(print (str
(apply str
(repeat
(- w full-len (if append-zero 1 0) )
(:padchar params)))
(if add-sign (if (neg? arg) \- \+))
(if prepend-zero "0")
full-mantissa
(if append-zero "0")
scaled-exp-str))))
(print (str
(if add-sign (if (neg? arg) \- \+))
(if prepend-zero "0")
full-mantissa
(if append-zero "0")
scaled-exp-str)))
(recur [rounded-mantissa (inc exp)]))))
navigator))
;; the function to render ~G directives
;; This just figures out whether to pass the request off to ~F or ~E based
;; on the algorithm in CLtL.
;; TODO: support rationals. Back off to ~D/~A is the appropriate cases
;; TODO: refactor so that float-parts isn't called twice
(defn- general-float [params navigator offsets]
(let [[arg _] (next-arg navigator)
arg (convert-ratio arg)
[mantissa exp] (float-parts (if (neg? arg) (- arg) arg))
w (:w params)
d (:d params)
e (:e params)
n (if (= arg 0.0) 0 (inc exp))
ee (if e (+ e 2) 4)
ww (if w (- w ee))
d (if d d (max (count mantissa) (min n 7)))
dd (- d n)]
(if (<= 0 dd d)
(let [navigator (fixed-float {:w ww, :d dd, :k 0,
:overflowchar (:overflowchar params),
:padchar (:padchar params), :at (:at params)}
navigator offsets)]
(print (apply str (repeat ee \space)))
navigator)
(exponential-float params navigator offsets))))
;; the function to render ~$ directives
;; TODO: support rationals. Back off to ~D/~A is the appropriate cases
(defn- dollar-float [params navigator offsets]
(let [[^Double arg navigator] (next-arg navigator)
[mantissa exp] (float-parts (Math/Abs arg)) ;;; Math/abs
d (:d params) ; digits after the decimal
n (:n params) ; minimum digits before the decimal
w (:w params) ; minimum field width
add-sign (or (:at params) (neg? arg))
[rounded-mantissa scaled-exp expanded] (round-str mantissa exp d nil)
^String fixed-repr (get-fixed rounded-mantissa (if expanded (inc scaled-exp) scaled-exp) d)
full-repr (str (apply str (repeat (- n (.IndexOf fixed-repr \.)) \0)) fixed-repr) ;;; .indexOf (int \.)
full-len (+ (count full-repr) (if add-sign 1 0))]
(print (str
(if (and (:colon params) add-sign) (if (neg? arg) \- \+))
(apply str (repeat (- w full-len) (:padchar params)))
(if (and (not (:colon params)) add-sign) (if (neg? arg) \- \+))
full-repr))
navigator))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for the '~[...~]' conditional construct in its
;;; different flavors
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ~[...~] without any modifiers chooses one of the clauses based on the param or
;; next argument
;; TODO check arg is positive int
(defn- choice-conditional [params arg-navigator offsets]
(let [arg (:selector params)
[arg navigator] (if arg [arg arg-navigator] (next-arg arg-navigator))
clauses (:clauses params)
clause (if (or (neg? arg) (>= arg (count clauses)))
(first (:else params))
(nth clauses arg))]
(if clause
(execute-sub-format clause navigator (:base-args params))
navigator)))
;; ~:[...~] with the colon reads the next argument treating it as a truth value
(defn- boolean-conditional [params arg-navigator offsets]
(let [[arg navigator] (next-arg arg-navigator)
clauses (:clauses params)
clause (if arg
(second clauses)
(first clauses))]
(if clause
(execute-sub-format clause navigator (:base-args params))
navigator)))
;; ~@[...~] with the at sign executes the conditional if the next arg is not
;; nil/false without consuming the arg
(defn- check-arg-conditional [params arg-navigator offsets]
(let [[arg navigator] (next-arg arg-navigator)
clauses (:clauses params)
clause (if arg (first clauses))]
(if arg
(if clause
(execute-sub-format clause arg-navigator (:base-args params))
arg-navigator)
navigator)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for the '~{...~}' iteration construct in its
;;; different flavors
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ~{...~} without any modifiers uses the next argument as an argument list that
;; is consumed by all the iterations
(defn- iterate-sublist [params navigator offsets]
(let [max-count (:max-iterations params)
param-clause (first (:clauses params))
[clause navigator] (if (empty? param-clause)
(get-format-arg navigator)
[param-clause navigator])
[arg-list navigator] (next-arg navigator)
args (init-navigator arg-list)]
(loop [count 0
args args
last-pos (num -1)]
(if (and (not max-count) (= (:pos args) last-pos) (> count 1))
;; TODO get the offset in here and call format exception
(throw (Exception. "%{ construct not consuming any arguments: Infinite loop!"))) ;;; RuntimeException
(if (or (and (empty? (:rest args))
(or (not (:colon (:right-params params))) (> count 0)))
(and max-count (>= count max-count)))
navigator
(let [iter-result (execute-sub-format clause args (:base-args params))]
(if (= :up-arrow (first iter-result))
navigator
(recur (inc count) iter-result (:pos args))))))))
;; ~:{...~} with the colon treats the next argument as a list of sublists. Each of the
;; sublists is used as the arglist for a single iteration.
(defn- iterate-list-of-sublists [params navigator offsets]
(let [max-count (:max-iterations params)
param-clause (first (:clauses params))
[clause navigator] (if (empty? param-clause)
(get-format-arg navigator)
[param-clause navigator])
[arg-list navigator] (next-arg navigator)]
(loop [count 0
arg-list arg-list]
(if (or (and (empty? arg-list)
(or (not (:colon (:right-params params))) (> count 0)))
(and max-count (>= count max-count)))
navigator
(let [iter-result (execute-sub-format
clause
(init-navigator (first arg-list))
(init-navigator (next arg-list)))]
(if (= :colon-up-arrow (first iter-result))
navigator
(recur (inc count) (next arg-list))))))))
;; ~@{...~} with the at sign uses the main argument list as the arguments to the iterations
;; is consumed by all the iterations
(defn- iterate-main-list [params navigator offsets]
(let [max-count (:max-iterations params)
param-clause (first (:clauses params))
[clause navigator] (if (empty? param-clause)
(get-format-arg navigator)
[param-clause navigator])]
(loop [count 0
navigator navigator
last-pos (num -1)]
(if (and (not max-count) (= (:pos navigator) last-pos) (> count 1))
;; TODO get the offset in here and call format exception
(throw (Exception. "%@{ construct not consuming any arguments: Infinite loop!"))) ;;; RuntimeException
(if (or (and (empty? (:rest navigator))
(or (not (:colon (:right-params params))) (> count 0)))
(and max-count (>= count max-count)))
navigator
(let [iter-result (execute-sub-format clause navigator (:base-args params))]
(if (= :up-arrow (first iter-result))
(second iter-result)
(recur
(inc count) iter-result (:pos navigator))))))))
;; ~@:{...~} with both colon and at sign uses the main argument list as a set of sublists, one
;; of which is consumed with each iteration
(defn- iterate-main-sublists [params navigator offsets]
(let [max-count (:max-iterations params)
param-clause (first (:clauses params))
[clause navigator] (if (empty? param-clause)
(get-format-arg navigator)
[param-clause navigator])
]
(loop [count 0
navigator navigator]
(if (or (and (empty? (:rest navigator))
(or (not (:colon (:right-params params))) (> count 0)))
(and max-count (>= count max-count)))
navigator
(let [[sublist navigator] (next-arg-or-nil navigator)
iter-result (execute-sub-format clause (init-navigator sublist) navigator)]
(if (= :colon-up-arrow (first iter-result))
navigator
(recur (inc count) navigator)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The '~< directive has two completely different meanings
;;; in the '~<...~>' form it does justification, but with
;;; ~<...~:>' it represents the logical block operation of the
;;; pretty printer.
;;;
;;; Unfortunately, the current architecture decides what function
;;; to call at form parsing time before the sub-clauses have been
;;; folded, so it is left to run-time to make the decision.
;;;
;;; TODO: make it possible to make these decisions at compile-time.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(declare format-logical-block)
(declare justify-clauses)
(defn- logical-block-or-justify [params navigator offsets]
(if (:colon (:right-params params))
(format-logical-block params navigator offsets)
(justify-clauses params navigator offsets)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for the '~<...~>' justification directive
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- render-clauses [clauses navigator base-navigator]
(loop [clauses clauses
acc []
navigator navigator]
(if (empty? clauses)
[acc navigator]
(let [clause (first clauses)
[iter-result result-str] (binding [*out* (System.IO.StringWriter.)] ;;; java.io.StringWriter.
[(execute-sub-format clause navigator base-navigator)
(.ToString *out*)])] ;;; toString
(if (= :up-arrow (first iter-result))
[acc (second iter-result)]
(recur (next clauses) (conj acc result-str) iter-result))))))
;; TODO support for ~:; constructions
(defn- justify-clauses [params navigator offsets]
(let [[[eol-str] new-navigator] (when-let [else (:else params)]
(render-clauses else navigator (:base-args params)))
navigator (or new-navigator navigator)
[else-params new-navigator] (when-let [p (:else-params params)]
(realize-parameter-list p navigator))
navigator (or new-navigator navigator)
min-remaining (or (first (:min-remaining else-params)) 0)
max-columns (or (first (:max-columns else-params))
(get-max-column *out*))
clauses (:clauses params)
[strs navigator] (render-clauses clauses navigator (:base-args params))
slots (max 1
(+ (dec (count strs)) (if (:colon params) 1 0) (if (:at params) 1 0)))
chars (reduce + (map count strs))
mincol (:mincol params)
minpad (:minpad params)
colinc (:colinc params)
minout (+ chars (* slots minpad))
result-columns (if (<= minout mincol)
mincol
(+ mincol (* colinc
(+ 1 (quot (- minout mincol 1) colinc)))))
total-pad (- result-columns chars)
pad (max minpad (quot total-pad slots))
extra-pad (- total-pad (* pad slots))
pad-str (apply str (repeat pad (:padchar params)))]
(if (and eol-str (> (+ (get-column (:base @@*out*)) min-remaining result-columns)
max-columns))
(print eol-str))
(loop [slots slots
extra-pad extra-pad
strs strs
pad-only (or (:colon params)
(and (= (count strs) 1) (not (:at params))))]
(if (seq strs)
(do
(print (str (if (not pad-only) (first strs))
(if (or pad-only (next strs) (:at params)) pad-str)
(if (pos? extra-pad) (:padchar params))))
(recur
(dec slots)
(dec extra-pad)
(if pad-only strs (next strs))
false))))
navigator))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for case modification with ~(...~).
;;; We do this by wrapping the underlying writer with
;;; a special writer to do the appropriate modification. This
;;; allows us to support arbitrary-sized output and sources
;;; that may block.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- downcase-writer
"Returns a proxy that wraps writer, converting all characters to lower case"
[^System.IO.TextWriter writer] ;;; java.io.Writer
(proxy [System.IO.TextWriter] [] ;;; java.io.Writer
(Close [] (.Close writer)) ;;; close
(Flush [] (.Flush writer)) ;;; flush
(Write ([^chars cbuf off len] ;;; write ^Integer hint removed from off,len
(.Write writer cbuf ^Int32 off ^Int32 len)) ;;; write, hints added
([x]
(condp = (class x)
String
(let [s ^String x]
(.Write writer (.ToLower s))) ;;; write toLowerCase
Int32 ;;; Integer
(let [c x] ;;; Character hint removoed
(.Write writer (int (Char/ToLower (char c)))))))))) ;;; .write Character/toLowerCase
(defn- upcase-writer
"Returns a proxy that wraps writer, converting all characters to upper case"
[^System.IO.TextWriter writer] ;;; java.io.Writer
(proxy [System.IO.TextWriter] [] ;;; java.io.Writer
(Close [] (.Close writer))
(Flush [] (.Flush writer))
(Write ([^chars cbuf off len] ;;; ^Integer hint removed from off, len
(.Write writer cbuf ^Int32 off ^Int32 len)) ;; Int32 hints added
([x]
(condp = (class x)
String
(let [s ^String x]
(.Write writer (.ToUpper s)))
Int32
(let [c x] ;;; Character hint removed from c
(.Write writer (int (Char/ToUpper (char c))))))))))
(defn- capitalize-string
"Capitalizes the words in a string. If first? is false, don't capitalize the
first character of the string even if it's a letter."
[s first?]
(let [^Char f (first s) ;;; Character
s (if (and first? f (Char/IsLetter f)) ;;; Character/isLetter
(str (Char/ToUpper f) (subs s 1)) ;;; Character/toUpperCase
s)]
(apply str
(first
(consume
(fn [s]
(if (empty? s)
[nil nil]
(let [m (re-matcher #"\W\w" s)
match (re-find m)
offset (and match (inc (.start m)))] ;;; .start
(if offset
[(str (subs s 0 offset)
(Char/ToUpper ^Char (char (nth s offset)))) ;;; Character/toUpperCase Character (char ... ) wrapper added
(subs s (inc offset))]
[s nil]))))
s)))))
(defn- capitalize-word-writer
"Returns a proxy that wraps writer, capitalizing all words"
[^System.IO.TextWriter writer] ;;; java.io.Writer
(let [last-was-whitespace? (ref true)]
(proxy [System.IO.TextWriter] []
(Close [] (.Close writer))
(Flush [] (.Flush writer))
(Write
([^chars cbuf off len] (let [off (int off) len (int len)] ;;; remove ^Integer hints on off, len
(.Write writer cbuf off len)) )
([x]
(condp = (class x)
String
(let [s ^String x]
(.Write writer
^String (capitalize-string (.ToLower s) @last-was-whitespace?)) ;;; toLowerCase
(when (pos? (.Length s)) ;;; .length
(dosync
(ref-set last-was-whitespace?
(Char/IsWhiteSpace ;;; Character/isWhitespace
^Char (nth s (dec (count s)))))))) ;;; ^Character
Int32
(let [c (char x)]
(let [mod-c (if @last-was-whitespace? (Char/ToUpper (char x)) c)]
(.Write writer (int mod-c))
(dosync (ref-set last-was-whitespace? (Char/IsWhiteSpace (char x))))))))))))
(defn- init-cap-writer
"Returns a proxy that wraps writer, capitalizing the first word"
[^System.IO.TextWriter writer] ;;; java.io.Writer
(let [capped (ref false)]
(proxy [System.IO.TextWriter] []
(Close [] (.Close writer))
(Flush [] (.Flush writer))
(Write ([^chars cbuf off len] (let [off (int off) len (int len)] ;;; remove ^Integer hints on off, len
(.Write writer cbuf off len)) )
([x]
(condp = (class x)
String
(let [s (.ToLower ^String x)]
(if (not @capped)
(let [m (re-matcher #"\S" s)
match (re-find m)
offset (and match (.start m))] ;;; start
(if offset
(do (.Write writer
(str (subs s 0 offset)
(Char/ToUpper ^Char (char (nth s offset))) ;; added (char ... )
(.ToLower ^String (subs s (inc offset)))))
(dosync (ref-set capped true)))
(.Write writer s)))
(.Write writer (.ToLower s))))
Int32
(let [c ^Char (char x)]
(if (and (not @capped) (Char/IsLetter c))
(do
(dosync (ref-set capped true))
(.Write writer (int (Char/ToUpper c))))
(.Write writer (int (Char/ToLower c)))))))))))
(defn- modify-case [make-writer params navigator offsets]
(let [clause (first (:clauses params))]
(binding [*out* (make-writer *out*)]
(execute-sub-format clause navigator (:base-args params)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; If necessary, wrap the writer in a PrettyWriter object
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn get-pretty-writer
"Returns the java.io.Writer passed in wrapped in a pretty writer proxy, unless it's
already a pretty writer. Generally, it is unnecessary to call this function, since pprint,
write, and cl-format all call it if they need to. However if you want the state to be
preserved across calls, you will want to wrap them with this.
For example, when you want to generate column-aware output with multiple calls to cl-format,
do it like in this example:
(defn print-table [aseq column-width]
(binding [*out* (get-pretty-writer *out*)]
(doseq [row aseq]
(doseq [col row]
(cl-format true \"~4D~7,vT\" col column-width))
(prn))))
Now when you run:
user> (print-table (map #(vector % (* % %) (* % % %)) (range 1 11)) 8)
It prints a table of squares and cubes for the numbers from 1 to 10:
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000"
{:added "1.2"}
[writer]
(if (pretty-writer? writer)
writer
(pretty-writer writer *print-right-margin* *print-miser-width*)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for column-aware operations ~&, ~T
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn fresh-line
"Make a newline if *out* is not already at the beginning of the line. If *out* is
not a pretty writer (which keeps track of columns), this function always outputs a newline."
{:added "1.2"}
[]
(if (instance? clojure.lang.IDeref *out*)
(if (not (= 0 (get-column (:base @@*out*))))
(prn))
(prn)))
(defn- absolute-tabulation [params navigator offsets]
(let [colnum (:colnum params)
colinc (:colinc params)
current (get-column (:base @@*out*))
space-count (cond
(< current colnum) (- colnum current)
(= colinc 0) 0
:else (- colinc (rem (- current colnum) colinc)))]
(print (apply str (repeat space-count \space))))
navigator)
(defn- relative-tabulation [params navigator offsets]
(let [colrel (:colnum params)
colinc (:colinc params)
start-col (+ colrel (get-column (:base @@*out*)))
offset (if (pos? colinc) (rem start-col colinc) 0)
space-count (+ colrel (if (= 0 offset) 0 (- colinc offset)))]
(print (apply str (repeat space-count \space))))
navigator)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for accessing the pretty printer from a format
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; TODO: support ~@; per-line-prefix separator
;; TODO: get the whole format wrapped so we can start the lb at any column
(defn- format-logical-block [params navigator offsets]
(let [clauses (:clauses params)
clause-count (count clauses)
prefix (cond
(> clause-count 1) (:string (:params (first (first clauses))))
(:colon params) "(")
body (nth clauses (if (> clause-count 1) 1 0))
suffix (cond
(> clause-count 2) (:string (:params (first (nth clauses 2))))
(:colon params) ")")
[arg navigator] (next-arg navigator)]
(pprint-logical-block :prefix prefix :suffix suffix
(execute-sub-format
body
(init-navigator arg)
(:base-args params)))
navigator))
(defn- set-indent [params navigator offsets]
(let [relative-to (if (:colon params) :current :block)]
(pprint-indent relative-to (:n params))
navigator))
;;; TODO: support ~:T section options for ~T
(defn- conditional-newline [params navigator offsets]
(let [kind (if (:colon params)
(if (:at params) :mandatory :fill)
(if (:at params) :miser :linear))]
(pprint-newline kind)
navigator))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The table of directives we support, each with its params,
;;; properties, and the compilation function
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; We start with a couple of helpers
(defn- process-directive-table-element [ [ char params flags bracket-info & generator-fn ] ]
[char,
{:directive char,
:params `(array-map ~@params),
:flags flags,
:bracket-info bracket-info,
:generator-fn (concat '(fn [ params offset]) generator-fn) }])
(defmacro ^{:private true}
defdirectives
[ & directives ]
`(def ^{:private true}
directive-table (hash-map ~@(mapcat process-directive-table-element directives))))
(defdirectives
(\A
[ :mincol [0 Int32] :colinc [1 Int32] :minpad [0 Int32] :padchar [\space Char] ]
#{ :at :colon :both} {}
#(format-ascii print-str %1 %2 %3))
(\S
[ :mincol [0 Int32] :colinc [1 Int32] :minpad [0 Int32] :padchar [\space Char] ]
#{ :at :colon :both} {}
#(format-ascii pr-str %1 %2 %3))
(\D
[ :mincol [0 Int32] :padchar [\space Char] :commachar [\, Char]
:commainterval [ 3 Int32]]
#{ :at :colon :both } {}
#(format-integer 10 %1 %2 %3))
(\B
[ :mincol [0 Int32] :padchar [\space Char] :commachar [\, Char]
:commainterval [ 3 Int32]]
#{ :at :colon :both } {}
#(format-integer 2 %1 %2 %3))
(\O
[ :mincol [0 Int32] :padchar [\space Char] :commachar [\, Char]
:commainterval [ 3 Int32]]
#{ :at :colon :both } {}
#(format-integer 8 %1 %2 %3))
(\X
[ :mincol [0 Int32] :padchar [\space Char] :commachar [\, Char]
:commainterval [ 3 Int32]]
#{ :at :colon :both } {}
#(format-integer 16 %1 %2 %3))
(\R
[:base [nil Int32] :mincol [0 Int32] :padchar [\space Char] :commachar [\, Char]
:commainterval [ 3 Int32]]
#{ :at :colon :both } {}
(do
(cond ; ~R is overloaded with bizareness
(first (:base params)) #(format-integer (:base %1) %1 %2 %3)
(and (:at params) (:colon params)) #(format-old-roman %1 %2 %3)
(:at params) #(format-new-roman %1 %2 %3)
(:colon params) #(format-ordinal-english %1 %2 %3)
true #(format-cardinal-english %1 %2 %3))))
(\P
[ ]
#{ :at :colon :both } {}
(fn [params navigator offsets]
(let [navigator (if (:colon params) (relative-reposition navigator -1) navigator)
strs (if (:at params) ["y" "ies"] ["" "s"])
[arg navigator] (next-arg navigator)]
(print (if (= arg 1) (first strs) (second strs)))
navigator)))
(\C
[:char-format [nil Char]]
#{ :at :colon :both } {}
(cond
(:colon params) pretty-character
(:at params) readable-character
:else plain-character))
(\F
[ :w [nil Int32] :d [nil Int32] :k [0 Int32] :overflowchar [nil Char]
:padchar [\space Char] ]
#{ :at } {}
fixed-float)
(\E
[ :w [nil Int32] :d [nil Int32] :e [nil Int32] :k [1 Int32]
:overflowchar [nil Char] :padchar [\space Char]
:exponentchar [nil Char] ]
#{ :at } {}
exponential-float)
(\G
[ :w [nil Int32] :d [nil Int32] :e [nil Int32] :k [1 Int32]
:overflowchar [nil Char] :padchar [\space Char]
:exponentchar [nil Char] ]
#{ :at } {}
general-float)
(\$
[ :d [2 Int32] :n [1 Int32] :w [0 Int32] :padchar [\space Char]]
#{ :at :colon :both} {}
dollar-float)
(\%
[ :count [1 Int32] ]
#{ } {}
(fn [params arg-navigator offsets]
(dotimes [i (:count params)]
(prn))
arg-navigator))
(\&
[ :count [1 Int32] ]
#{ :pretty } {}
(fn [params arg-navigator offsets]
(let [cnt (:count params)]
(if (pos? cnt) (fresh-line))
(dotimes [i (dec cnt)]
(prn)))
arg-navigator))
(\|
[ :count [1 Int32] ]
#{ } {}
(fn [params arg-navigator offsets]
(dotimes [i (:count params)]
(print \formfeed))
arg-navigator))
(\~
[ :n [1 Int32] ]
#{ } {}
(fn [params arg-navigator offsets]
(let [n (:n params)]
(print (apply str (repeat n \~)))
arg-navigator)))
(\newline ;; Whitespace supression is handled in the compilation loop
[ ]
#{:colon :at} {}
(fn [params arg-navigator offsets]
(if (:at params)
(prn))
arg-navigator))
(\T
[ :colnum [1 Int32] :colinc [1 Int32] ]
#{ :at :pretty } {}
(if (:at params)
#(relative-tabulation %1 %2 %3)
#(absolute-tabulation %1 %2 %3)))
(\*
[ :n [1 Int32] ]
#{ :colon :at } {}
(fn [params navigator offsets]
(let [n (:n params)]
(if (:at params)
(absolute-reposition navigator n)
(relative-reposition navigator (if (:colon params) (- n) n)))
)))
(\?
[ ]
#{ :at } {}
(if (:at params)
(fn [params navigator offsets] ; args from main arg list
(let [[subformat navigator] (get-format-arg navigator)]
(execute-sub-format subformat navigator (:base-args params))))
(fn [params navigator offsets] ; args from sub-list
(let [[subformat navigator] (get-format-arg navigator)
[subargs navigator] (next-arg navigator)
sub-navigator (init-navigator subargs)]
(execute-sub-format subformat sub-navigator (:base-args params))
navigator))))
(\(
[ ]
#{ :colon :at :both} { :right \), :allows-separator nil, :else nil }
(let [mod-case-writer (cond
(and (:at params) (:colon params))
upcase-writer
(:colon params)
capitalize-word-writer
(:at params)
init-cap-writer
:else
downcase-writer)]
#(modify-case mod-case-writer %1 %2 %3)))
(\) [] #{} {} nil)
(\[
[ :selector [nil Int32] ]
#{ :colon :at } { :right \], :allows-separator true, :else :last }
(cond
(:colon params)
boolean-conditional
(:at params)
check-arg-conditional
true
choice-conditional))
(\; [:min-remaining [nil Int32] :max-columns [nil Int32]]
#{ :colon } { :separator true } nil)
(\] [] #{} {} nil)
(\{
[ :max-iterations [nil Int32] ]
#{ :colon :at :both} { :right \}, :allows-separator false }
(cond
(and (:at params) (:colon params))
iterate-main-sublists
(:colon params)
iterate-list-of-sublists
(:at params)
iterate-main-list
true
iterate-sublist))
(\} [] #{:colon} {} nil)
(\<
[:mincol [0 Int32] :colinc [1 Int32] :minpad [0 Int32] :padchar [\space Char]]
#{:colon :at :both :pretty} { :right \>, :allows-separator true, :else :first }
logical-block-or-justify)
(\> [] #{:colon} {} nil)
;; TODO: detect errors in cases where colon not allowed
(\^ [:arg1 [nil Int32] :arg2 [nil Int32] :arg3 [nil Int32]]
#{:colon} {}
(fn [params navigator offsets]
(let [arg1 (:arg1 params)
arg2 (:arg2 params)
arg3 (:arg3 params)
exit (if (:colon params) :colon-up-arrow :up-arrow)]
(cond
(and arg1 arg2 arg3)
(if (<= arg1 arg2 arg3) [exit navigator] navigator)
(and arg1 arg2)
(if (= arg1 arg2) [exit navigator] navigator)
arg1
(if (= arg1 0) [exit navigator] navigator)
true ; TODO: handle looking up the arglist stack for info
(if (if (:colon params)
(empty? (:rest (:base-args params)))
(empty? (:rest navigator)))
[exit navigator] navigator)))))
(\W
[]
#{:at :colon :both :pretty} {}
(if (or (:at params) (:colon params))
(let [bindings (concat
(if (:at params) [:level nil :length nil] [])
(if (:colon params) [:pretty true] []))]
(fn [params navigator offsets]
(let [[arg navigator] (next-arg navigator)]
(if (apply write arg bindings)
[:up-arrow navigator]
navigator))))
(fn [params navigator offsets]
(let [[arg navigator] (next-arg navigator)]
(if (write-out arg)
[:up-arrow navigator]
navigator)))))
(\_
[]
#{:at :colon :both} {}
conditional-newline)
(\I
[:n [0 Int32]]
#{:colon} {}
set-indent)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Code to manage the parameters and flags associated with each
;;; directive in the format string.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^{:private true}
param-pattern #"^([vV]|#|('.)|([+-]?\d+)|(?=,))")
(def ^{:private true}
special-params #{ :parameter-from-args :remaining-arg-count })
(defn- extract-param [[s offset saw-comma]]
(let [m (re-matcher param-pattern s)
param (re-find m)]
(if param
(let [token-str (first (re-groups m))
remainder (subs s (.end m)) ;;; end
new-offset (+ offset (.end m))]
(if (not (= \, (nth remainder 0)))
[ [token-str offset] [remainder new-offset false]]
[ [token-str offset] [(subs remainder 1) (inc new-offset) true]]))
(if saw-comma
(format-error "Badly formed parameters in format directive" offset)
[ nil [s offset]]))))
(defn- extract-params [s offset]
(consume extract-param [s offset false]))
(defn- translate-param
"Translate the string representation of a param to the internalized
representation"
[[^String p offset]]
[(cond
(= (.Length p) 0) nil
(and (= (.Length p) 1) (contains? #{\v \V} (nth p 0))) :parameter-from-args ;;; length
(and (= (.Length p) 1) (= \# (nth p 0))) :remaining-arg-count
(and (= (.Length p) 2) (= \' (nth p 0))) (nth p 1)
true (Int32/Parse p)) ;;; (new Integer p)
offset])
(def ^{:private true}
flag-defs { \: :colon, \@ :at })
(defn- extract-flags [s offset]
(consume
(fn [[s offset flags]]
(if (empty? s)
[nil [s offset flags]]
(let [flag (get flag-defs (first s))]
(if flag
(if (contains? flags flag)
(format-error
(str "Flag \"" (first s) "\" appears more than once in a directive")
offset)
[true [(subs s 1) (inc offset) (assoc flags flag [true offset])]])
[nil [s offset flags]]))))
[s offset {}]))
(defn- check-flags [def flags]
(let [allowed (:flags def)]
(if (and (not (:at allowed)) (:at flags))
(format-error (str "\"@\" is an illegal flag for format directive \"" (:directive def) "\"")
(nth (:at flags) 1)))
(if (and (not (:colon allowed)) (:colon flags))
(format-error (str "\":\" is an illegal flag for format directive \"" (:directive def) "\"")
(nth (:colon flags) 1)))
(if (and (not (:both allowed)) (:at flags) (:colon flags))
(format-error (str "Cannot combine \"@\" and \":\" flags for format directive \""
(:directive def) "\"")
(min (nth (:colon flags) 1) (nth (:at flags) 1))))))
(defn- map-params
"Takes a directive definition and the list of actual parameters and
a map of flags and returns a map of the parameters and flags with defaults
filled in. We check to make sure that there are the right types and number
of parameters as well."
[def params flags offset]
(check-flags def flags)
(if (> (count params) (count (:params def)))
(format-error
(cl-format
nil
"Too many parameters for directive \"~C\": ~D~:* ~[were~;was~:;were~] specified but only ~D~:* ~[are~;is~:;are~] allowed"
(:directive def) (count params) (count (:params def)))
(second (first params))))
(doall
(map #(let [val (first %1)]
(if (not (or (nil? val) (contains? special-params val)
(instance? (second (second %2)) val)))
(format-error (str "Parameter " (name (first %2))
" has bad type in directive \"" (:directive def) "\": "
(class val))
(second %1))) )
params (:params def)))
(merge ; create the result map
(into (array-map) ; start with the default values, make sure the order is right
(reverse (for [[name [default]] (:params def)] [name [default offset]])))
(reduce #(apply assoc %1 %2) {} (filter #(first (nth % 1)) (zipmap (keys (:params def)) params))) ; add the specified parameters, filtering out nils
flags)) ; and finally add the flags
(defn- compile-directive [s offset]
(let [[raw-params [rest offset]] (extract-params s offset)
[_ [rest offset flags]] (extract-flags rest offset)
directive (first rest)
def (get directive-table (Char/ToUpper ^Char directive)) ;;; Character/toUpperCase
params (if def (map-params def (map translate-param raw-params) flags offset))]
(if (not directive)
(format-error "Format string ended in the middle of a directive" offset))
(if (not def)
(format-error (str "Directive \"" directive "\" is undefined") offset))
[(struct compiled-directive ((:generator-fn def) params offset) def params offset)
(let [remainder (subs rest 1)
offset (inc offset)
trim? (and (= \newline (:directive def))
(not (:colon params)))
trim-count (if trim? (prefix-count remainder [\space \tab]) 0)
remainder (subs remainder trim-count)
offset (+ offset trim-count)]
[remainder offset])]))
(defn- compile-raw-string [s offset]
(struct compiled-directive (fn [_ a _] (print s) a) nil { :string s } offset))
(defn- right-bracket [this] (:right (:bracket-info (:def this))))
(defn- separator? [this] (:separator (:bracket-info (:def this))))
(defn- else-separator? [this]
(and (:separator (:bracket-info (:def this)))
(:colon (:params this))))
(declare collect-clauses)
(defn- process-bracket [this remainder]
(let [[subex remainder] (collect-clauses (:bracket-info (:def this))
(:offset this) remainder)]
[(struct compiled-directive
(:func this) (:def this)
(merge (:params this) (tuple-map subex (:offset this)))
(:offset this))
remainder]))
(defn- process-clause [bracket-info offset remainder]
(consume
(fn [remainder]
(if (empty? remainder)
(format-error "No closing bracket found." offset)
(let [this (first remainder)
remainder (next remainder)]
(cond
(right-bracket this)
(process-bracket this remainder)
(= (:right bracket-info) (:directive (:def this)))
[ nil [:right-bracket (:params this) nil remainder]]
(else-separator? this)
[nil [:else nil (:params this) remainder]]
(separator? this)
[nil [:separator nil nil remainder]] ;; TODO: check to make sure that there are no params on ~;
true
[this remainder]))))
remainder))
(defn- collect-clauses [bracket-info offset remainder]
(second
(consume
(fn [[clause-map saw-else remainder]]
(let [[clause [type right-params else-params remainder]]
(process-clause bracket-info offset remainder)]
(cond
(= type :right-bracket)
[nil [(merge-with concat clause-map
{(if saw-else :else :clauses) [clause]
:right-params right-params})
remainder]]
(= type :else)
(cond
(:else clause-map)
(format-error "Two else clauses (\"~:;\") inside bracket construction." offset)
(not (:else bracket-info))
(format-error "An else clause (\"~:;\") is in a bracket type that doesn't support it."
offset)
(and (= :first (:else bracket-info)) (seq (:clauses clause-map)))
(format-error
"The else clause (\"~:;\") is only allowed in the first position for this directive."
offset)
true ; if the ~:; is in the last position, the else clause
; is next, this was a regular clause
(if (= :first (:else bracket-info))
[true [(merge-with concat clause-map { :else [clause] :else-params else-params})
false remainder]]
[true [(merge-with concat clause-map { :clauses [clause] })
true remainder]]))
(= type :separator)
(cond
saw-else
(format-error "A plain clause (with \"~;\") follows an else clause (\"~:;\") inside bracket construction." offset)
(not (:allows-separator bracket-info))
(format-error "A separator (\"~;\") is in a bracket type that doesn't support it."
offset)
true
[true [(merge-with concat clause-map { :clauses [clause] })
false remainder]]))))
[{ :clauses [] } false remainder])))
(defn- process-nesting
"Take a linearly compiled format and process the bracket directives to give it
the appropriate tree structure"
[format]
(first
(consume
(fn [remainder]
(let [this (first remainder)
remainder (next remainder)
bracket (:bracket-info (:def this))]
(if (:right bracket)
(process-bracket this remainder)
[this remainder])))
format)))
(defn- compile-format
"Compiles format-str into a compiled format which can be used as an argument
to cl-format just like a plain format string. Use this function for improved
performance when you're using the same format string repeatedly"
[ format-str ]
; (prlabel compiling format-str)
(binding [*format-str* format-str]
(process-nesting
(first
(consume
(fn [[^String s offset]]
(if (empty? s)
[nil s]
(let [tilde (.IndexOf s \~)] ;;; indexOf (int \~)
(cond
(neg? tilde) [(compile-raw-string s offset) ["" (+ offset (.Length s))]] ;;; length
(zero? tilde) (compile-directive (subs s 1) (inc offset))
true
[(compile-raw-string (subs s 0 tilde) offset) [(subs s tilde) (+ tilde offset)]]))))
[format-str 0])))))
(defn- needs-pretty
"determine whether a given compiled format has any directives that depend on the
column number or pretty printing"
[format]
(loop [format format]
(if (empty? format)
false
(if (or (:pretty (:flags (:def (first format))))
(some needs-pretty (first (:clauses (:params (first format)))))
(some needs-pretty (first (:else (:params (first format))))))
true
(recur (next format))))))
(defn- execute-format
"Executes the format with the arguments."
{:skip-wiki true}
([stream format args]
(let [^System.IO.TextWriter real-stream (cond ;;; java.io.Writer
(not stream) (System.IO.StringWriter.) ;;; java.io.StringWriter
(true? stream) *out*
:else stream)
^System.IO.TextWriter wrapped-stream (if (and (needs-pretty format) ;;; java.io.Writer
(not (pretty-writer? real-stream)))
(get-pretty-writer real-stream)
real-stream)]
(binding [*out* wrapped-stream]
(try
(execute-format format args)
(finally
(if-not (identical? real-stream wrapped-stream)
(.Flush wrapped-stream)))) ;;; flush
(if (not stream) (.ToString real-stream))))) ;;; toString
([format args]
(map-passing-context
(fn [element context]
(if (abort? context)
[nil context]
(let [[params args] (realize-parameter-list
(:params element) context)
[params offsets] (unzip-map params)
params (assoc params :base-args args)]
[nil (apply (:func element) [params args offsets])])))
args
format)
nil))
;;; This is a bad idea, but it prevents us from leaking private symbols
;;; This should all be replaced by really compiled formats anyway.
(def ^{:private true} cached-compile (memoize compile-format))
(defmacro formatter
"Makes a function which can directly run format-in. The function is
fn [stream & args] ... and returns nil unless the stream is nil (meaning
output to a string) in which case it returns the resulting string.
format-in can be either a control string or a previously compiled format."
{:added "1.2"}
[format-in]
`(let [format-in# ~format-in
my-c-c# (var-get (get (ns-interns (the-ns 'clojure.pprint))
'~'cached-compile))
my-e-f# (var-get (get (ns-interns (the-ns 'clojure.pprint))
'~'execute-format))
my-i-n# (var-get (get (ns-interns (the-ns 'clojure.pprint))
'~'init-navigator))
cf# (if (string? format-in#) (my-c-c# format-in#) format-in#)]
(fn [stream# & args#]
(let [navigator# (my-i-n# args#)]
(my-e-f# stream# cf# navigator#)))))
(defmacro formatter-out
"Makes a function which can directly run format-in. The function is
fn [& args] ... and returns nil. This version of the formatter macro is
designed to be used with *out* set to an appropriate Writer. In particular,
this is meant to be used as part of a pretty printer dispatch method.
format-in can be either a control string or a previously compiled format."
{:added "1.2"}
[format-in]
`(let [format-in# ~format-in
cf# (if (string? format-in#) (#'clojure.pprint/cached-compile format-in#) format-in#)]
(fn [& args#]
(let [navigator# (#'clojure.pprint/init-navigator args#)]
(#'clojure.pprint/execute-format cf# navigator#))))) | 29447 | ;;; cl_format.clj -- part of the pretty printer for Clojure
; 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>
;; April 3, 2009
;; This module implements the Common Lisp compatible format function as documented
;; in "Common Lisp the Language, 2nd edition", Chapter 22 (available online at:
;; http://www.cs.cmu.edu/afs/cs.cmu.edu/project/ai-repository/ai/html/cltl/clm/node200.html#SECTION002633000000000000000)
(in-ns 'clojure.pprint)
;;; Forward references
(declare compile-format)
(declare execute-format)
(declare init-navigator)
;;; End forward references
(defn cl-format
"An implementation of a Common Lisp compatible format function. cl-format formats its
arguments to an output stream or string based on the format control string given. It
supports sophisticated formatting of structured data.
Writer is an instance of java.io.Writer, true to output to *out* or nil to output
to a string, format-in is the format control string and the remaining arguments
are the data to be formatted.
The format control string is a string to be output with embedded 'format directives'
describing how to format the various arguments passed in.
If writer is nil, cl-format returns the formatted result string. Otherwise, cl-format
returns nil.
For example:
(let [results [46 38 22]]
(cl-format true \"There ~[are~;is~:;are~]~:* ~d result~:p: ~{~d~^, ~}~%\"
(count results) results))
Prints to *out*:
There are 3 results: 46, 38, 22
Detailed documentation on format control strings is available in the \"Common Lisp the
Language, 2nd edition\", Chapter 22 (available online at:
http://www.cs.cmu.edu/afs/cs.cmu.edu/project/ai-repository/ai/html/cltl/clm/node200.html#SECTION002633000000000000000)
and in the Common Lisp HyperSpec at
http://www.lispworks.com/documentation/HyperSpec/Body/22_c.htm
"
{:added "1.2",
:see-also [["http://www.cs.cmu.edu/afs/cs.cmu.edu/project/ai-repository/ai/html/cltl/clm/node200.html#SECTION002633000000000000000"
"Common Lisp the Language"]
["http://www.lispworks.com/documentation/HyperSpec/Body/22_c.htm"
"Common Lisp HyperSpec"]]}
[writer format-in & args]
(let [compiled-format (if (string? format-in) (compile-format format-in) format-in)
navigator (init-navigator args)]
(execute-format writer compiled-format navigator)))
(def ^:dynamic ^{:private true} *format-str* nil)
(defn- format-error [message offset]
(let [full-message (str message \newline *format-str* \newline
(apply str (repeat offset \space)) "^" \newline)]
(throw (Exception. full-message)))) ;;; RuntimeException
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Argument navigators manage the argument list
;;; as the format statement moves through the list
;;; (possibly going forwards and backwards as it does so)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defstruct ^{:private true}
arg-navigator :seq :rest :pos )
(defn- init-navigator
"Create a new arg-navigator from the sequence with the position set to 0"
{:skip-wiki true}
[s]
(let [s (seq s)]
(struct arg-navigator s s 0)))
;; TODO call format-error with offset
(defn- next-arg [ navigator ]
(let [ rst (:rest navigator) ]
(if rst
[(first rst) (struct arg-navigator (:seq navigator ) (next rst) (inc (:pos navigator)))]
(throw (new Exception "Not enough arguments for format definition")))))
(defn- next-arg-or-nil [navigator]
(let [rst (:rest navigator)]
(if rst
[(first rst) (struct arg-navigator (:seq navigator ) (next rst) (inc (:pos navigator)))]
[nil navigator])))
;; Get an argument off the arg list and compile it if it's not already compiled
(defn- get-format-arg [navigator]
(let [[raw-format navigator] (next-arg navigator)
compiled-format (if (instance? String raw-format)
(compile-format raw-format)
raw-format)]
[compiled-format navigator]))
(declare relative-reposition)
(defn- absolute-reposition [navigator position]
(if (>= position (:pos navigator))
(relative-reposition navigator (- (:pos navigator) position))
(struct arg-navigator (:seq navigator) (drop position (:seq navigator)) position)))
(defn- relative-reposition [navigator position]
(let [newpos (+ (:pos navigator) position)]
(if (neg? position)
(absolute-reposition navigator newpos)
(struct arg-navigator (:seq navigator) (drop position (:rest navigator)) newpos))))
(defstruct ^{:private true}
compiled-directive :func :def :params :offset)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; When looking at the parameter list, we may need to manipulate
;;; the argument list as well (for 'V' and '#' parameter types).
;;; We hide all of this behind a function, but clients need to
;;; manage changing arg navigator
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; TODO: validate parameters when they come from arg list
(defn- realize-parameter [[param [raw-val offset]] navigator]
(let [[real-param new-navigator]
(cond
(contains? #{ :at :colon } param) ;pass flags through unchanged - this really isn't necessary
[raw-val navigator]
(= raw-val :parameter-from-args)
(next-arg navigator)
(= raw-val :remaining-arg-count)
[(count (:rest navigator)) navigator]
true
[raw-val navigator])]
[[param [real-param offset]] new-navigator]))
(defn- realize-parameter-list [parameter-map navigator]
(let [[pairs new-navigator]
(map-passing-context realize-parameter navigator parameter-map)]
[(into {} pairs) new-navigator]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Functions that support individual directives
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Common handling code for ~A and ~S
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(declare opt-base-str)
(def ^{:private true}
special-radix-markers {2 "#b" 8 "#o", 16 "#x"})
(defn- format-simple-number [n]
(cond
(integer? n) (if (= *print-base* 10)
(str n (if *print-radix* "."))
(str
(if *print-radix* (or (get special-radix-markers *print-base*) (str "#" *print-base* "r")))
(opt-base-str *print-base* n)))
(ratio? n) (str
(if *print-radix* (or (get special-radix-markers *print-base*) (str "#" *print-base* "r")))
(opt-base-str *print-base* (.numerator n))
"/"
(opt-base-str *print-base* (.denominator n)))
:else nil))
(defn- format-ascii [print-func params arg-navigator offsets]
(let [ [arg arg-navigator] (next-arg arg-navigator)
^String base-output (or (format-simple-number arg) (print-func arg))
base-width (.Length base-output) ;;; length
min-width (+ base-width (:minpad params))
width (if (>= min-width (:mincol params))
min-width
(+ min-width
(* (+ (quot (- (:mincol params) min-width 1)
(:colinc params) )
1)
(:colinc params))))
chars (apply str (repeat (- width base-width) (:padchar params)))]
(if (:at params)
(print (str chars base-output))
(print (str base-output chars)))
arg-navigator))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for the integer directives ~D, ~X, ~O, ~B and some
;;; of ~R
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- integral?
"returns true if a number is actually an integer (that is, has no fractional part)"
[x]
(cond
(integer? x) true
(decimal? x) true ;;; TODO: FIX THIS (>= (.ulp (.stripTrailingZeros (bigdec 0))) 1) ; true iff no fractional part DM: ??????? doesn't mention x!!!
(float? x) (= x (Math/Floor x)) ;;; Math/floor
(ratio? x) (let [^clojure.lang.Ratio r x]
(= 0 (rem (.numerator r) (.denominator r))))
:else false))
(defn- remainders
"Return the list of remainders (essentially the 'digits') of val in the given base"
[base val]
(reverse
(first
(consume #(if (pos? %)
[(rem % base) (quot % base)]
[nil nil])
val))))
;;; TODO: xlated-val does not seem to be used here. ---- ;;;; I had to use it to prevent the call to remainders from returning a Double instead of an integer in the last position
(defn- base-str
"Return val as a string in the given base"
[base val]
(if (zero? val)
"0"
(let [xlated-val (cond
(float? val) (bigdec val)
(ratio? val) (let [^clojure.lang.Ratio r val]
(/ (.numerator r) (.denominator r)))
:else val)]
(apply str
(map
#(if (< % 10) (char (+ (int \0) %)) (char (+ (int \a) (- % 10))))
(remainders base xlated-val))))))
(def ^{:private true}
java-base-formats {8 "%o", 10 "%d", 16 "%x"})
(defn- opt-base-str
"Return val as a string in the given base, using clojure.core/format if supported
for improved performance"
[base val]
(let [format-str (get java-base-formats base)]
(if (and format-str (integer? val) (not (instance? clojure.lang.BigInt val)))
(clojure.core/format format-str val)
(base-str base val))))
(defn- group-by* [unit lis]
(reverse
(first
(consume (fn [x] [(seq (reverse (take unit x))) (seq (drop unit x))]) (reverse lis)))))
(defn- format-integer [base params arg-navigator offsets]
(let [[arg arg-navigator] (next-arg arg-navigator)]
(if (integral? arg)
(let [neg (neg? arg)
pos-arg (if neg (- arg) arg)
raw-str (opt-base-str base pos-arg)
group-str (if (:colon params)
(let [groups (map #(apply str %) (group-by* (:commainterval params) raw-str))
commas (repeat (count groups) (:commachar params))]
(apply str (next (interleave commas groups))))
raw-str)
^String signed-str (cond
neg (str "-" group-str)
(:at params) (str "+" group-str)
true group-str)
padded-str (if (< (.Length signed-str) (:mincol params)) ;;; length
(str (apply str (repeat (- (:mincol params) (.Length signed-str)) ;;; length
(:padchar params)))
signed-str)
signed-str)]
(print padded-str))
(format-ascii print-str {:mincol (:mincol params) :colinc 1 :minpad 0
:padchar (:padchar params) :at true}
(init-navigator [arg]) nil))
arg-navigator))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for english formats (~R and ~:R)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^{:private true}
english-cardinal-units
["zero" "one" "two" "three" "four" "five" "six" "seven" "eight" "nine"
"ten" "eleven" "twelve" "thirteen" "fourteen"
"fifteen" "sixteen" "seventeen" "eighteen" "nineteen"])
(def ^{:private true}
english-ordinal-units
["zeroth" "first" "second" "third" "fourth" "fifth" "sixth" "seventh" "eighth" "ninth"
"tenth" "eleventh" "twelfth" "thirteenth" "fourteenth"
"fifteenth" "sixteenth" "seventeenth" "eighteenth" "nineteenth"])
(def ^{:private true}
english-cardinal-tens
["" "" "twenty" "thirty" "forty" "fifty" "sixty" "seventy" "eighty" "ninety"])
(def ^{:private true}
english-ordinal-tens
["" "" "twentieth" "thirtieth" "fortieth" "fiftieth"
"sixtieth" "seventieth" "eightieth" "ninetieth"])
;; We use "short scale" for our units (see http://en.wikipedia.org/wiki/Long_and_short_scales)
;; Number names from http://www.jimloy.com/math/billion.htm
;; We follow the rules for writing numbers from the Blue Book
;; (http://www.grammarbook.com/numbers/numbers.asp)
(def ^{:private true}
english-scale-numbers
["" "thousand" "million" "billion" "trillion" "quadrillion" "quintillion"
"sextillion" "septillion" "octillion" "nonillion" "decillion"
"undecillion" "duodecillion" "tredecillion" "quattuordecillion"
"quindecillion" "sexdecillion" "septendecillion"
"octodecillion" "novemdecillion" "vigintillion"])
(defn- format-simple-cardinal
"Convert a number less than 1000 to a cardinal english string"
[num]
(let [hundreds (quot num 100)
tens (rem num 100)]
(str
(if (pos? hundreds) (str (nth english-cardinal-units hundreds) " hundred"))
(if (and (pos? hundreds) (pos? tens)) " ")
(if (pos? tens)
(if (< tens 20)
(nth english-cardinal-units tens)
(let [ten-digit (quot tens 10)
unit-digit (rem tens 10)]
(str
(if (pos? ten-digit) (nth english-cardinal-tens ten-digit))
(if (and (pos? ten-digit) (pos? unit-digit)) "-")
(if (pos? unit-digit) (nth english-cardinal-units unit-digit)))))))))
(defn- add-english-scales
"Take a sequence of parts, add scale numbers (e.g., million) and combine into a string
offset is a factor of 10^3 to multiply by"
[parts offset]
(let [cnt (count parts)]
(loop [acc []
pos (dec cnt)
this (first parts)
remainder (next parts)]
(if (nil? remainder)
(str (apply str (interpose ", " acc))
(if (and (not (empty? this)) (not (empty? acc))) ", ")
this
(if (and (not (empty? this)) (pos? (+ pos offset)))
(str " " (nth english-scale-numbers (+ pos offset)))))
(recur
(if (empty? this)
acc
(conj acc (str this " " (nth english-scale-numbers (+ pos offset)))))
(dec pos)
(first remainder)
(next remainder))))))
(defn- format-cardinal-english [params navigator offsets]
(let [[arg navigator] (next-arg navigator)]
(if (= 0 arg)
(print "zero")
(let [abs-arg (if (neg? arg) (- arg) arg) ; some numbers are too big for Math/abs
parts (remainders 1000 abs-arg)]
(if (<= (count parts) (count english-scale-numbers))
(let [parts-strs (map format-simple-cardinal parts)
full-str (add-english-scales parts-strs 0)]
(print (str (if (neg? arg) "minus ") full-str)))
(format-integer ;; for numbers > 10^63, we fall back on ~D
10
{ :mincol 0, :padchar \space, :commachar \, :commainterval 3, :colon true}
(init-navigator [arg])
{ :mincol 0, :padchar 0, :commachar 0 :commainterval 0}))))
navigator))
(defn- format-simple-ordinal
"Convert a number less than 1000 to a ordinal english string
Note this should only be used for the last one in the sequence"
[num]
(let [hundreds (quot num 100)
tens (rem num 100)]
(str
(if (pos? hundreds) (str (nth english-cardinal-units hundreds) " hundred"))
(if (and (pos? hundreds) (pos? tens)) " ")
(if (pos? tens)
(if (< tens 20)
(nth english-ordinal-units tens)
(let [ten-digit (quot tens 10)
unit-digit (rem tens 10)]
(if (and (pos? ten-digit) (not (pos? unit-digit)))
(nth english-ordinal-tens ten-digit)
(str
(if (pos? ten-digit) (nth english-cardinal-tens ten-digit))
(if (and (pos? ten-digit) (pos? unit-digit)) "-")
(if (pos? unit-digit) (nth english-ordinal-units unit-digit))))))
(if (pos? hundreds) "th")))))
(defn- format-ordinal-english [params navigator offsets]
(let [[arg navigator] (next-arg navigator)]
(if (= 0 arg)
(print "zeroth")
(let [abs-arg (if (neg? arg) (- arg) arg) ; some numbers are too big for Math/abs
parts (remainders 1000 abs-arg)]
(if (<= (count parts) (count english-scale-numbers))
(let [parts-strs (map format-simple-cardinal (drop-last parts))
head-str (add-english-scales parts-strs 1)
tail-str (format-simple-ordinal (last parts))]
(print (str (if (neg? arg) "minus ")
(cond
(and (not (empty? head-str)) (not (empty? tail-str)))
(str head-str ", " tail-str)
(not (empty? head-str)) (str head-str "th")
:else tail-str))))
(do (format-integer ;; for numbers > 10^63, we fall back on ~D
10
{ :mincol 0, :padchar \space, :commachar \, :commainterval 3, :colon true}
(init-navigator [arg])
{ :mincol 0, :padchar 0, :commachar 0 :commainterval 0})
(let [low-two-digits (rem arg 100)
not-teens (or (< 11 low-two-digits) (> 19 low-two-digits))
low-digit (rem low-two-digits 10)]
(print (cond
(and (== low-digit 1) not-teens) "st"
(and (== low-digit 2) not-teens) "nd"
(and (== low-digit 3) not-teens) "rd"
:else "th")))))))
navigator))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for roman numeral formats (~@R and ~@:R)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^{:private true}
old-roman-table
[[ "I" "II" "III" "IIII" "V" "VI" "VII" "VIII" "VIIII"]
[ "X" "XX" "XXX" "XXXX" "L" "LX" "LXX" "LXXX" "LXXXX"]
[ "C" "CC" "CCC" "CCCC" "D" "DC" "DCC" "DCCC" "DCCCC"]
[ "M" "MM" "MMM"]])
(def ^{:private true}
new-roman-table
[[ "I" "II" "III" "IV" "V" "VI" "VII" "VIII" "IX"]
[ "X" "XX" "XXX" "XL" "L" "LX" "LXX" "LXXX" "XC"]
[ "C" "CC" "CCC" "CD" "D" "DC" "DCC" "DCCC" "CM"]
[ "M" "MM" "MMM"]])
(defn- format-roman
"Format a roman numeral using the specified look-up table"
[table params navigator offsets]
(let [[arg navigator] (next-arg navigator)]
(if (and (number? arg) (> arg 0) (< arg 4000))
(let [digits (remainders 10 arg)]
(loop [acc []
pos (dec (count digits))
digits digits]
(if (empty? digits)
(print (apply str acc))
(let [digit (first digits)]
(recur (if (= 0 digit)
acc
(conj acc (nth (nth table pos) (dec digit))))
(dec pos)
(next digits))))))
(format-integer ;; for anything <= 0 or > 3999, we fall back on ~D
10
{ :mincol 0, :padchar \space, :commachar \, :commainterval 3, :colon true}
(init-navigator [arg])
{ :mincol 0, :padchar 0, :commachar 0 :commainterval 0}))
navigator))
(defn- format-old-roman [params navigator offsets]
(format-roman old-roman-table params navigator offsets))
(defn- format-new-roman [params navigator offsets]
(format-roman new-roman-table params navigator offsets))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for character formats (~C)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^{:private true}
special-chars { 8 "Backspace", 9 "Tab", 10 "Newline", 13 "Return", 32 "Space"})
(defn- pretty-character [params navigator offsets]
(let [[c navigator] (next-arg navigator)
as-int (int c)
base-char (bit-and as-int 127)
meta (bit-and as-int 128)
special (get special-chars base-char)]
(if (> meta 0) (print "Meta-"))
(print (cond
special special
(< base-char 32) (str "Control-" (char (+ base-char 64)))
(= base-char 127) "Control-?"
:else (char base-char)))
navigator))
(defn- readable-character [params navigator offsets]
(let [[c navigator] (next-arg navigator)]
(condp = (:char-format params)
\o (cl-format true "\\o~3,'0o" (int c))
\u (cl-format true "\\u~4,'0x" (int c))
nil (pr c))
navigator))
(defn- plain-character [params navigator offsets]
(let [[char navigator] (next-arg navigator)]
(print char)
navigator))
;; Check to see if a result is an abort (~^) construct
;; TODO: move these funcs somewhere more appropriate
(defn- abort? [context]
(let [token (first context)]
(or (= :up-arrow token) (= :colon-up-arrow token))))
;; Handle the execution of "sub-clauses" in bracket constructions
(defn- execute-sub-format [format args base-args]
(second
(map-passing-context
(fn [element context]
(if (abort? context)
[nil context] ; just keep passing it along
(let [[params args] (realize-parameter-list (:params element) context)
[params offsets] (unzip-map params)
params (assoc params :base-args base-args)]
[nil (apply (:func element) [params args offsets])])))
args
format)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for real number formats
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; TODO - return exponent as int to eliminate double conversion
(defn- float-parts-base
"Produce string parts for the mantissa (normalized 1-9) and exponent"
[^Object f]
(let [^String s (.ToLower (.ToString f)) ;;; .toLowerCase .toString
exploc (.IndexOf s \e) ;;; .indexOf (int \e)
dotloc (.IndexOf s \.)] ;;; .indexOf (int \.)
(if (neg? exploc)
(if (neg? dotloc)
[s (str (dec (count s)))]
[(str (subs s 0 dotloc) (subs s (inc dotloc))) (str (dec dotloc))])
(if (neg? dotloc)
[(subs s 0 exploc) (subs s (inc exploc))]
[(str (subs s 0 1) (subs s 2 exploc)) (subs s (inc exploc))]))))
(defn- float-parts
"Take care of leading and trailing zeros in decomposed floats"
[f]
(let [[m ^String e] (float-parts-base f)
m1 (rtrim m \0)
m2 (ltrim m1 \0)
delta (- (count m1) (count m2))
^String e (if (and (pos? (count e)) (= (nth e 0) \+)) (subs e 1) e)]
(if (empty? m2)
["0" 0]
[m2 (- (Int32/Parse e) delta)]))) ;;; (Integer/valueOf e)
(defn- ^String inc-s
"Assumption: The input string consists of one or more decimal digits,
and no other characters. Return a string containing one or more
decimal digits containing a decimal number one larger than the input
string. The output string will always be the same length as the input
string, or one character longer."
[^String s]
(let [len-1 (dec (count s))]
(loop [i (int len-1)]
(cond
(neg? i) (apply str "1" (repeat (inc len-1) "0"))
(= \9 (.get_Chars s i)) (recur (dec i)) ;;; .charAt
:else (apply str (subs s 0 i)
(char (inc (int (.get_Chars s i)))) ;;; .charAt
(repeat (- len-1 i) "0"))))))
(defn- round-str [m e d w]
(if (or d w)
(let [len (count m)
;; Every formatted floating point number should include at
;; least one decimal digit and a decimal point.
w (if w (max 2 w))
round-pos (cond
;; If d was given, that forces the rounding
;; position, regardless of any width that may
;; have been specified.
d (+ e d 1)
;; Otherwise w was specified, so pick round-pos
;; based upon that.
;; If e>=0, then abs value of number is >= 1.0,
;; and e+1 is number of decimal digits before the
;; decimal point when the number is written
;; without scientific notation. Never round the
;; number before the decimal point.
(>= e 0) (max (inc e) (dec w))
;; e < 0, so number abs value < 1.0
:else (+ w e))
[m1 e1 round-pos len] (if (= round-pos 0)
[(str "0" m) (inc e) 1 (inc len)]
[m e round-pos len])]
(if round-pos
(if (neg? round-pos)
["0" 0 false]
(if (> len round-pos)
(let [round-char (nth m1 round-pos)
^String result (subs m1 0 round-pos)]
(if (>= (int round-char) (int \5))
(let [round-up-result (inc-s result)
expanded (> (count round-up-result) (count result))]
[(if expanded
(subs round-up-result 0 (dec (count round-up-result)))
round-up-result)
e1 expanded])
[result e1 false]))
[m e false]))
[m e false]))
[m e false]))
(defn- expand-fixed [m e d]
(let [[m1 e1] (if (neg? e)
[(str (apply str (repeat (dec (- e)) \0)) m) -1]
[m e])
len (count m1)
target-len (if d (+ e1 d 1) (inc e1))]
(if (< len target-len)
(str m1 (apply str (repeat (- target-len len) \0)))
m1)))
(defn- insert-decimal
"Insert the decimal point at the right spot in the number to match an exponent"
[m e]
(if (neg? e)
(str "." m)
(let [loc (inc e)]
(str (subs m 0 loc) "." (subs m loc)))))
(defn- get-fixed [m e d]
(insert-decimal (expand-fixed m e d) e))
(defn- insert-scaled-decimal
"Insert the decimal point at the right spot in the number to match an exponent"
[m k]
(if (neg? k)
(str "." m)
(str (subs m 0 k) "." (subs m k))))
(defn- convert-ratio [x]
(if (ratio? x)
;; Usually convert to a double, only resorting to the slower
;; bigdec conversion if the result does not fit within the range
;; of a double.
(let [d (double x)]
(if (== d 0.0)
(if (not= x 0)
(bigdec x)
d)
(if (or (== d Double/PositiveInfinity) (== d Double/NegativeInfinity)) ;;; Double/POSITIVE_INFINITY Double/NEGATIVE_INFINITY
(bigdec x)
d)))
x))
;; the function to render ~F directives
;; TODO: support rationals. Back off to ~D/~A is the appropriate cases
(defn- fixed-float [params navigator offsets]
(let [w (:w params)
d (:d params)
[arg navigator] (next-arg navigator)
[sign abs] (if (neg? arg) ["-" (- arg)] ["+" arg])
abs (convert-ratio abs)
[mantissa exp] (float-parts abs)
scaled-exp (+ exp (:k params))
add-sign (or (:at params) (neg? arg))
append-zero (and (not d) (<= (dec (count mantissa)) scaled-exp))
[rounded-mantissa scaled-exp expanded] (round-str mantissa scaled-exp
d (if w (- w (if add-sign 1 0))))
fixed-repr (get-fixed rounded-mantissa (if expanded (inc scaled-exp) scaled-exp) d)
fixed-repr (if (and w d
(>= d 1)
(= (.get_Chars fixed-repr 0) \0) ;;; .charAt
(= (.get_Chars fixed-repr 1) \.) ;;; .charAt
(> (count fixed-repr) (- w (if add-sign 1 0))))
(subs fixed-repr 1) ; chop off leading 0
fixed-repr)
prepend-zero (= (first fixed-repr) \.)]
(if w
(let [len (count fixed-repr)
signed-len (if add-sign (inc len) len)
prepend-zero (and prepend-zero (not (>= signed-len w)))
append-zero (and append-zero (not (>= signed-len w)))
full-len (if (or prepend-zero append-zero)
(inc signed-len)
signed-len)]
(if (and (> full-len w) (:overflowchar params))
(print (apply str (repeat w (:overflowchar params))))
(print (str
(apply str (repeat (- w full-len) (:padchar params)))
(if add-sign sign)
(if prepend-zero "0")
fixed-repr
(if append-zero "0")))))
(print (str
(if add-sign sign)
(if prepend-zero "0")
fixed-repr
(if append-zero "0"))))
navigator))
;; the function to render ~E directives
;; TODO: support rationals. Back off to ~D/~A is the appropriate cases
;; TODO: define ~E representation for Infinity
(defn- exponential-float [params navigator offsets]
(let [[arg navigator] (next-arg navigator)
arg (convert-ratio arg)]
(loop [[mantissa exp] (float-parts (if (neg? arg) (- arg) arg))]
(let [w (:w params)
d (:d params)
e (:e params)
k (:k params)
expchar (or (:exponentchar params) \E)
add-sign (or (:at params) (neg? arg))
prepend-zero (<= k 0)
^Int32 scaled-exp (- exp (dec k)) ;;; Integer
scaled-exp-str (str (Math/Abs scaled-exp)) ;;; Math/abs
scaled-exp-str (str expchar (if (neg? scaled-exp) \- \+)
(if e (apply str
(repeat
(- e
(count scaled-exp-str))
\0)))
scaled-exp-str)
exp-width (count scaled-exp-str)
base-mantissa-width (count mantissa)
scaled-mantissa (str (apply str (repeat (- k) \0))
mantissa
(if d
(apply str
(repeat
(- d (dec base-mantissa-width)
(if (neg? k) (- k) 0)) \0))))
w-mantissa (if w (- w exp-width))
[rounded-mantissa _ incr-exp] (round-str
scaled-mantissa 0
(cond
(= k 0) (dec d)
(pos? k) d
(neg? k) (dec d))
(if w-mantissa
(- w-mantissa (if add-sign 1 0))))
full-mantissa (insert-scaled-decimal rounded-mantissa k)
append-zero (and (= k (count rounded-mantissa)) (nil? d))]
(if (not incr-exp)
(if w
(let [len (+ (count full-mantissa) exp-width)
signed-len (if add-sign (inc len) len)
prepend-zero (and prepend-zero (not (= signed-len w)))
full-len (if prepend-zero (inc signed-len) signed-len)
append-zero (and append-zero (< full-len w))]
(if (and (or (> full-len w) (and e (> (- exp-width 2) e)))
(:overflowchar params))
(print (apply str (repeat w (:overflowchar params))))
(print (str
(apply str
(repeat
(- w full-len (if append-zero 1 0) )
(:padchar params)))
(if add-sign (if (neg? arg) \- \+))
(if prepend-zero "0")
full-mantissa
(if append-zero "0")
scaled-exp-str))))
(print (str
(if add-sign (if (neg? arg) \- \+))
(if prepend-zero "0")
full-mantissa
(if append-zero "0")
scaled-exp-str)))
(recur [rounded-mantissa (inc exp)]))))
navigator))
;; the function to render ~G directives
;; This just figures out whether to pass the request off to ~F or ~E based
;; on the algorithm in CLtL.
;; TODO: support rationals. Back off to ~D/~A is the appropriate cases
;; TODO: refactor so that float-parts isn't called twice
(defn- general-float [params navigator offsets]
(let [[arg _] (next-arg navigator)
arg (convert-ratio arg)
[mantissa exp] (float-parts (if (neg? arg) (- arg) arg))
w (:w params)
d (:d params)
e (:e params)
n (if (= arg 0.0) 0 (inc exp))
ee (if e (+ e 2) 4)
ww (if w (- w ee))
d (if d d (max (count mantissa) (min n 7)))
dd (- d n)]
(if (<= 0 dd d)
(let [navigator (fixed-float {:w ww, :d dd, :k 0,
:overflowchar (:overflowchar params),
:padchar (:padchar params), :at (:at params)}
navigator offsets)]
(print (apply str (repeat ee \space)))
navigator)
(exponential-float params navigator offsets))))
;; the function to render ~$ directives
;; TODO: support rationals. Back off to ~D/~A is the appropriate cases
(defn- dollar-float [params navigator offsets]
(let [[^Double arg navigator] (next-arg navigator)
[mantissa exp] (float-parts (Math/Abs arg)) ;;; Math/abs
d (:d params) ; digits after the decimal
n (:n params) ; minimum digits before the decimal
w (:w params) ; minimum field width
add-sign (or (:at params) (neg? arg))
[rounded-mantissa scaled-exp expanded] (round-str mantissa exp d nil)
^String fixed-repr (get-fixed rounded-mantissa (if expanded (inc scaled-exp) scaled-exp) d)
full-repr (str (apply str (repeat (- n (.IndexOf fixed-repr \.)) \0)) fixed-repr) ;;; .indexOf (int \.)
full-len (+ (count full-repr) (if add-sign 1 0))]
(print (str
(if (and (:colon params) add-sign) (if (neg? arg) \- \+))
(apply str (repeat (- w full-len) (:padchar params)))
(if (and (not (:colon params)) add-sign) (if (neg? arg) \- \+))
full-repr))
navigator))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for the '~[...~]' conditional construct in its
;;; different flavors
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ~[...~] without any modifiers chooses one of the clauses based on the param or
;; next argument
;; TODO check arg is positive int
(defn- choice-conditional [params arg-navigator offsets]
(let [arg (:selector params)
[arg navigator] (if arg [arg arg-navigator] (next-arg arg-navigator))
clauses (:clauses params)
clause (if (or (neg? arg) (>= arg (count clauses)))
(first (:else params))
(nth clauses arg))]
(if clause
(execute-sub-format clause navigator (:base-args params))
navigator)))
;; ~:[...~] with the colon reads the next argument treating it as a truth value
(defn- boolean-conditional [params arg-navigator offsets]
(let [[arg navigator] (next-arg arg-navigator)
clauses (:clauses params)
clause (if arg
(second clauses)
(first clauses))]
(if clause
(execute-sub-format clause navigator (:base-args params))
navigator)))
;; ~@[...~] with the at sign executes the conditional if the next arg is not
;; nil/false without consuming the arg
(defn- check-arg-conditional [params arg-navigator offsets]
(let [[arg navigator] (next-arg arg-navigator)
clauses (:clauses params)
clause (if arg (first clauses))]
(if arg
(if clause
(execute-sub-format clause arg-navigator (:base-args params))
arg-navigator)
navigator)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for the '~{...~}' iteration construct in its
;;; different flavors
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ~{...~} without any modifiers uses the next argument as an argument list that
;; is consumed by all the iterations
(defn- iterate-sublist [params navigator offsets]
(let [max-count (:max-iterations params)
param-clause (first (:clauses params))
[clause navigator] (if (empty? param-clause)
(get-format-arg navigator)
[param-clause navigator])
[arg-list navigator] (next-arg navigator)
args (init-navigator arg-list)]
(loop [count 0
args args
last-pos (num -1)]
(if (and (not max-count) (= (:pos args) last-pos) (> count 1))
;; TODO get the offset in here and call format exception
(throw (Exception. "%{ construct not consuming any arguments: Infinite loop!"))) ;;; RuntimeException
(if (or (and (empty? (:rest args))
(or (not (:colon (:right-params params))) (> count 0)))
(and max-count (>= count max-count)))
navigator
(let [iter-result (execute-sub-format clause args (:base-args params))]
(if (= :up-arrow (first iter-result))
navigator
(recur (inc count) iter-result (:pos args))))))))
;; ~:{...~} with the colon treats the next argument as a list of sublists. Each of the
;; sublists is used as the arglist for a single iteration.
(defn- iterate-list-of-sublists [params navigator offsets]
(let [max-count (:max-iterations params)
param-clause (first (:clauses params))
[clause navigator] (if (empty? param-clause)
(get-format-arg navigator)
[param-clause navigator])
[arg-list navigator] (next-arg navigator)]
(loop [count 0
arg-list arg-list]
(if (or (and (empty? arg-list)
(or (not (:colon (:right-params params))) (> count 0)))
(and max-count (>= count max-count)))
navigator
(let [iter-result (execute-sub-format
clause
(init-navigator (first arg-list))
(init-navigator (next arg-list)))]
(if (= :colon-up-arrow (first iter-result))
navigator
(recur (inc count) (next arg-list))))))))
;; ~@{...~} with the at sign uses the main argument list as the arguments to the iterations
;; is consumed by all the iterations
(defn- iterate-main-list [params navigator offsets]
(let [max-count (:max-iterations params)
param-clause (first (:clauses params))
[clause navigator] (if (empty? param-clause)
(get-format-arg navigator)
[param-clause navigator])]
(loop [count 0
navigator navigator
last-pos (num -1)]
(if (and (not max-count) (= (:pos navigator) last-pos) (> count 1))
;; TODO get the offset in here and call format exception
(throw (Exception. "%@{ construct not consuming any arguments: Infinite loop!"))) ;;; RuntimeException
(if (or (and (empty? (:rest navigator))
(or (not (:colon (:right-params params))) (> count 0)))
(and max-count (>= count max-count)))
navigator
(let [iter-result (execute-sub-format clause navigator (:base-args params))]
(if (= :up-arrow (first iter-result))
(second iter-result)
(recur
(inc count) iter-result (:pos navigator))))))))
;; ~@:{...~} with both colon and at sign uses the main argument list as a set of sublists, one
;; of which is consumed with each iteration
(defn- iterate-main-sublists [params navigator offsets]
(let [max-count (:max-iterations params)
param-clause (first (:clauses params))
[clause navigator] (if (empty? param-clause)
(get-format-arg navigator)
[param-clause navigator])
]
(loop [count 0
navigator navigator]
(if (or (and (empty? (:rest navigator))
(or (not (:colon (:right-params params))) (> count 0)))
(and max-count (>= count max-count)))
navigator
(let [[sublist navigator] (next-arg-or-nil navigator)
iter-result (execute-sub-format clause (init-navigator sublist) navigator)]
(if (= :colon-up-arrow (first iter-result))
navigator
(recur (inc count) navigator)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The '~< directive has two completely different meanings
;;; in the '~<...~>' form it does justification, but with
;;; ~<...~:>' it represents the logical block operation of the
;;; pretty printer.
;;;
;;; Unfortunately, the current architecture decides what function
;;; to call at form parsing time before the sub-clauses have been
;;; folded, so it is left to run-time to make the decision.
;;;
;;; TODO: make it possible to make these decisions at compile-time.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(declare format-logical-block)
(declare justify-clauses)
(defn- logical-block-or-justify [params navigator offsets]
(if (:colon (:right-params params))
(format-logical-block params navigator offsets)
(justify-clauses params navigator offsets)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for the '~<...~>' justification directive
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- render-clauses [clauses navigator base-navigator]
(loop [clauses clauses
acc []
navigator navigator]
(if (empty? clauses)
[acc navigator]
(let [clause (first clauses)
[iter-result result-str] (binding [*out* (System.IO.StringWriter.)] ;;; java.io.StringWriter.
[(execute-sub-format clause navigator base-navigator)
(.ToString *out*)])] ;;; toString
(if (= :up-arrow (first iter-result))
[acc (second iter-result)]
(recur (next clauses) (conj acc result-str) iter-result))))))
;; TODO support for ~:; constructions
(defn- justify-clauses [params navigator offsets]
(let [[[eol-str] new-navigator] (when-let [else (:else params)]
(render-clauses else navigator (:base-args params)))
navigator (or new-navigator navigator)
[else-params new-navigator] (when-let [p (:else-params params)]
(realize-parameter-list p navigator))
navigator (or new-navigator navigator)
min-remaining (or (first (:min-remaining else-params)) 0)
max-columns (or (first (:max-columns else-params))
(get-max-column *out*))
clauses (:clauses params)
[strs navigator] (render-clauses clauses navigator (:base-args params))
slots (max 1
(+ (dec (count strs)) (if (:colon params) 1 0) (if (:at params) 1 0)))
chars (reduce + (map count strs))
mincol (:mincol params)
minpad (:minpad params)
colinc (:colinc params)
minout (+ chars (* slots minpad))
result-columns (if (<= minout mincol)
mincol
(+ mincol (* colinc
(+ 1 (quot (- minout mincol 1) colinc)))))
total-pad (- result-columns chars)
pad (max minpad (quot total-pad slots))
extra-pad (- total-pad (* pad slots))
pad-str (apply str (repeat pad (:padchar params)))]
(if (and eol-str (> (+ (get-column (:base @@*out*)) min-remaining result-columns)
max-columns))
(print eol-str))
(loop [slots slots
extra-pad extra-pad
strs strs
pad-only (or (:colon params)
(and (= (count strs) 1) (not (:at params))))]
(if (seq strs)
(do
(print (str (if (not pad-only) (first strs))
(if (or pad-only (next strs) (:at params)) pad-str)
(if (pos? extra-pad) (:padchar params))))
(recur
(dec slots)
(dec extra-pad)
(if pad-only strs (next strs))
false))))
navigator))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for case modification with ~(...~).
;;; We do this by wrapping the underlying writer with
;;; a special writer to do the appropriate modification. This
;;; allows us to support arbitrary-sized output and sources
;;; that may block.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- downcase-writer
"Returns a proxy that wraps writer, converting all characters to lower case"
[^System.IO.TextWriter writer] ;;; java.io.Writer
(proxy [System.IO.TextWriter] [] ;;; java.io.Writer
(Close [] (.Close writer)) ;;; close
(Flush [] (.Flush writer)) ;;; flush
(Write ([^chars cbuf off len] ;;; write ^Integer hint removed from off,len
(.Write writer cbuf ^Int32 off ^Int32 len)) ;;; write, hints added
([x]
(condp = (class x)
String
(let [s ^String x]
(.Write writer (.ToLower s))) ;;; write toLowerCase
Int32 ;;; Integer
(let [c x] ;;; Character hint removoed
(.Write writer (int (Char/ToLower (char c)))))))))) ;;; .write Character/toLowerCase
(defn- upcase-writer
"Returns a proxy that wraps writer, converting all characters to upper case"
[^System.IO.TextWriter writer] ;;; java.io.Writer
(proxy [System.IO.TextWriter] [] ;;; java.io.Writer
(Close [] (.Close writer))
(Flush [] (.Flush writer))
(Write ([^chars cbuf off len] ;;; ^Integer hint removed from off, len
(.Write writer cbuf ^Int32 off ^Int32 len)) ;; Int32 hints added
([x]
(condp = (class x)
String
(let [s ^String x]
(.Write writer (.ToUpper s)))
Int32
(let [c x] ;;; Character hint removed from c
(.Write writer (int (Char/ToUpper (char c))))))))))
(defn- capitalize-string
"Capitalizes the words in a string. If first? is false, don't capitalize the
first character of the string even if it's a letter."
[s first?]
(let [^Char f (first s) ;;; Character
s (if (and first? f (Char/IsLetter f)) ;;; Character/isLetter
(str (Char/ToUpper f) (subs s 1)) ;;; Character/toUpperCase
s)]
(apply str
(first
(consume
(fn [s]
(if (empty? s)
[nil nil]
(let [m (re-matcher #"\W\w" s)
match (re-find m)
offset (and match (inc (.start m)))] ;;; .start
(if offset
[(str (subs s 0 offset)
(Char/ToUpper ^Char (char (nth s offset)))) ;;; Character/toUpperCase Character (char ... ) wrapper added
(subs s (inc offset))]
[s nil]))))
s)))))
(defn- capitalize-word-writer
"Returns a proxy that wraps writer, capitalizing all words"
[^System.IO.TextWriter writer] ;;; java.io.Writer
(let [last-was-whitespace? (ref true)]
(proxy [System.IO.TextWriter] []
(Close [] (.Close writer))
(Flush [] (.Flush writer))
(Write
([^chars cbuf off len] (let [off (int off) len (int len)] ;;; remove ^Integer hints on off, len
(.Write writer cbuf off len)) )
([x]
(condp = (class x)
String
(let [s ^String x]
(.Write writer
^String (capitalize-string (.ToLower s) @last-was-whitespace?)) ;;; toLowerCase
(when (pos? (.Length s)) ;;; .length
(dosync
(ref-set last-was-whitespace?
(Char/IsWhiteSpace ;;; Character/isWhitespace
^Char (nth s (dec (count s)))))))) ;;; ^Character
Int32
(let [c (char x)]
(let [mod-c (if @last-was-whitespace? (Char/ToUpper (char x)) c)]
(.Write writer (int mod-c))
(dosync (ref-set last-was-whitespace? (Char/IsWhiteSpace (char x))))))))))))
(defn- init-cap-writer
"Returns a proxy that wraps writer, capitalizing the first word"
[^System.IO.TextWriter writer] ;;; java.io.Writer
(let [capped (ref false)]
(proxy [System.IO.TextWriter] []
(Close [] (.Close writer))
(Flush [] (.Flush writer))
(Write ([^chars cbuf off len] (let [off (int off) len (int len)] ;;; remove ^Integer hints on off, len
(.Write writer cbuf off len)) )
([x]
(condp = (class x)
String
(let [s (.ToLower ^String x)]
(if (not @capped)
(let [m (re-matcher #"\S" s)
match (re-find m)
offset (and match (.start m))] ;;; start
(if offset
(do (.Write writer
(str (subs s 0 offset)
(Char/ToUpper ^Char (char (nth s offset))) ;; added (char ... )
(.ToLower ^String (subs s (inc offset)))))
(dosync (ref-set capped true)))
(.Write writer s)))
(.Write writer (.ToLower s))))
Int32
(let [c ^Char (char x)]
(if (and (not @capped) (Char/IsLetter c))
(do
(dosync (ref-set capped true))
(.Write writer (int (Char/ToUpper c))))
(.Write writer (int (Char/ToLower c)))))))))))
(defn- modify-case [make-writer params navigator offsets]
(let [clause (first (:clauses params))]
(binding [*out* (make-writer *out*)]
(execute-sub-format clause navigator (:base-args params)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; If necessary, wrap the writer in a PrettyWriter object
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn get-pretty-writer
"Returns the java.io.Writer passed in wrapped in a pretty writer proxy, unless it's
already a pretty writer. Generally, it is unnecessary to call this function, since pprint,
write, and cl-format all call it if they need to. However if you want the state to be
preserved across calls, you will want to wrap them with this.
For example, when you want to generate column-aware output with multiple calls to cl-format,
do it like in this example:
(defn print-table [aseq column-width]
(binding [*out* (get-pretty-writer *out*)]
(doseq [row aseq]
(doseq [col row]
(cl-format true \"~4D~7,vT\" col column-width))
(prn))))
Now when you run:
user> (print-table (map #(vector % (* % %) (* % % %)) (range 1 11)) 8)
It prints a table of squares and cubes for the numbers from 1 to 10:
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000"
{:added "1.2"}
[writer]
(if (pretty-writer? writer)
writer
(pretty-writer writer *print-right-margin* *print-miser-width*)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for column-aware operations ~&, ~T
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn fresh-line
"Make a newline if *out* is not already at the beginning of the line. If *out* is
not a pretty writer (which keeps track of columns), this function always outputs a newline."
{:added "1.2"}
[]
(if (instance? clojure.lang.IDeref *out*)
(if (not (= 0 (get-column (:base @@*out*))))
(prn))
(prn)))
(defn- absolute-tabulation [params navigator offsets]
(let [colnum (:colnum params)
colinc (:colinc params)
current (get-column (:base @@*out*))
space-count (cond
(< current colnum) (- colnum current)
(= colinc 0) 0
:else (- colinc (rem (- current colnum) colinc)))]
(print (apply str (repeat space-count \space))))
navigator)
(defn- relative-tabulation [params navigator offsets]
(let [colrel (:colnum params)
colinc (:colinc params)
start-col (+ colrel (get-column (:base @@*out*)))
offset (if (pos? colinc) (rem start-col colinc) 0)
space-count (+ colrel (if (= 0 offset) 0 (- colinc offset)))]
(print (apply str (repeat space-count \space))))
navigator)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for accessing the pretty printer from a format
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; TODO: support ~@; per-line-prefix separator
;; TODO: get the whole format wrapped so we can start the lb at any column
(defn- format-logical-block [params navigator offsets]
(let [clauses (:clauses params)
clause-count (count clauses)
prefix (cond
(> clause-count 1) (:string (:params (first (first clauses))))
(:colon params) "(")
body (nth clauses (if (> clause-count 1) 1 0))
suffix (cond
(> clause-count 2) (:string (:params (first (nth clauses 2))))
(:colon params) ")")
[arg navigator] (next-arg navigator)]
(pprint-logical-block :prefix prefix :suffix suffix
(execute-sub-format
body
(init-navigator arg)
(:base-args params)))
navigator))
(defn- set-indent [params navigator offsets]
(let [relative-to (if (:colon params) :current :block)]
(pprint-indent relative-to (:n params))
navigator))
;;; TODO: support ~:T section options for ~T
(defn- conditional-newline [params navigator offsets]
(let [kind (if (:colon params)
(if (:at params) :mandatory :fill)
(if (:at params) :miser :linear))]
(pprint-newline kind)
navigator))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The table of directives we support, each with its params,
;;; properties, and the compilation function
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; We start with a couple of helpers
(defn- process-directive-table-element [ [ char params flags bracket-info & generator-fn ] ]
[char,
{:directive char,
:params `(array-map ~@params),
:flags flags,
:bracket-info bracket-info,
:generator-fn (concat '(fn [ params offset]) generator-fn) }])
(defmacro ^{:private true}
defdirectives
[ & directives ]
`(def ^{:private true}
directive-table (hash-map ~@(mapcat process-directive-table-element directives))))
(defdirectives
(\A
[ :mincol [0 Int32] :colinc [1 Int32] :minpad [0 Int32] :padchar [\space Char] ]
#{ :at :colon :both} {}
#(format-ascii print-str %1 %2 %3))
(\S
[ :mincol [0 Int32] :colinc [1 Int32] :minpad [0 Int32] :padchar [\space Char] ]
#{ :at :colon :both} {}
#(format-ascii pr-str %1 %2 %3))
(\D
[ :mincol [0 Int32] :padchar [\space Char] :commachar [\, Char]
:commainterval [ 3 Int32]]
#{ :at :colon :both } {}
#(format-integer 10 %1 %2 %3))
(\B
[ :mincol [0 Int32] :padchar [\space Char] :commachar [\, Char]
:commainterval [ 3 Int32]]
#{ :at :colon :both } {}
#(format-integer 2 %1 %2 %3))
(\O
[ :mincol [0 Int32] :padchar [\space Char] :commachar [\, Char]
:commainterval [ 3 Int32]]
#{ :at :colon :both } {}
#(format-integer 8 %1 %2 %3))
(\X
[ :mincol [0 Int32] :padchar [\space Char] :commachar [\, Char]
:commainterval [ 3 Int32]]
#{ :at :colon :both } {}
#(format-integer 16 %1 %2 %3))
(\R
[:base [nil Int32] :mincol [0 Int32] :padchar [\space Char] :commachar [\, Char]
:commainterval [ 3 Int32]]
#{ :at :colon :both } {}
(do
(cond ; ~R is overloaded with bizareness
(first (:base params)) #(format-integer (:base %1) %1 %2 %3)
(and (:at params) (:colon params)) #(format-old-roman %1 %2 %3)
(:at params) #(format-new-roman %1 %2 %3)
(:colon params) #(format-ordinal-english %1 %2 %3)
true #(format-cardinal-english %1 %2 %3))))
(\P
[ ]
#{ :at :colon :both } {}
(fn [params navigator offsets]
(let [navigator (if (:colon params) (relative-reposition navigator -1) navigator)
strs (if (:at params) ["y" "ies"] ["" "s"])
[arg navigator] (next-arg navigator)]
(print (if (= arg 1) (first strs) (second strs)))
navigator)))
(\C
[:char-format [nil Char]]
#{ :at :colon :both } {}
(cond
(:colon params) pretty-character
(:at params) readable-character
:else plain-character))
(\F
[ :w [nil Int32] :d [nil Int32] :k [0 Int32] :overflowchar [nil Char]
:padchar [\space Char] ]
#{ :at } {}
fixed-float)
(\E
[ :w [nil Int32] :d [nil Int32] :e [nil Int32] :k [1 Int32]
:overflowchar [nil Char] :padchar [\space Char]
:exponentchar [nil Char] ]
#{ :at } {}
exponential-float)
(\G
[ :w [nil Int32] :d [nil Int32] :e [nil Int32] :k [1 Int32]
:overflowchar [nil Char] :padchar [\space Char]
:exponentchar [nil Char] ]
#{ :at } {}
general-float)
(\$
[ :d [2 Int32] :n [1 Int32] :w [0 Int32] :padchar [\space Char]]
#{ :at :colon :both} {}
dollar-float)
(\%
[ :count [1 Int32] ]
#{ } {}
(fn [params arg-navigator offsets]
(dotimes [i (:count params)]
(prn))
arg-navigator))
(\&
[ :count [1 Int32] ]
#{ :pretty } {}
(fn [params arg-navigator offsets]
(let [cnt (:count params)]
(if (pos? cnt) (fresh-line))
(dotimes [i (dec cnt)]
(prn)))
arg-navigator))
(\|
[ :count [1 Int32] ]
#{ } {}
(fn [params arg-navigator offsets]
(dotimes [i (:count params)]
(print \formfeed))
arg-navigator))
(\~
[ :n [1 Int32] ]
#{ } {}
(fn [params arg-navigator offsets]
(let [n (:n params)]
(print (apply str (repeat n \~)))
arg-navigator)))
(\newline ;; Whitespace supression is handled in the compilation loop
[ ]
#{:colon :at} {}
(fn [params arg-navigator offsets]
(if (:at params)
(prn))
arg-navigator))
(\T
[ :colnum [1 Int32] :colinc [1 Int32] ]
#{ :at :pretty } {}
(if (:at params)
#(relative-tabulation %1 %2 %3)
#(absolute-tabulation %1 %2 %3)))
(\*
[ :n [1 Int32] ]
#{ :colon :at } {}
(fn [params navigator offsets]
(let [n (:n params)]
(if (:at params)
(absolute-reposition navigator n)
(relative-reposition navigator (if (:colon params) (- n) n)))
)))
(\?
[ ]
#{ :at } {}
(if (:at params)
(fn [params navigator offsets] ; args from main arg list
(let [[subformat navigator] (get-format-arg navigator)]
(execute-sub-format subformat navigator (:base-args params))))
(fn [params navigator offsets] ; args from sub-list
(let [[subformat navigator] (get-format-arg navigator)
[subargs navigator] (next-arg navigator)
sub-navigator (init-navigator subargs)]
(execute-sub-format subformat sub-navigator (:base-args params))
navigator))))
(\(
[ ]
#{ :colon :at :both} { :right \), :allows-separator nil, :else nil }
(let [mod-case-writer (cond
(and (:at params) (:colon params))
upcase-writer
(:colon params)
capitalize-word-writer
(:at params)
init-cap-writer
:else
downcase-writer)]
#(modify-case mod-case-writer %1 %2 %3)))
(\) [] #{} {} nil)
(\[
[ :selector [nil Int32] ]
#{ :colon :at } { :right \], :allows-separator true, :else :last }
(cond
(:colon params)
boolean-conditional
(:at params)
check-arg-conditional
true
choice-conditional))
(\; [:min-remaining [nil Int32] :max-columns [nil Int32]]
#{ :colon } { :separator true } nil)
(\] [] #{} {} nil)
(\{
[ :max-iterations [nil Int32] ]
#{ :colon :at :both} { :right \}, :allows-separator false }
(cond
(and (:at params) (:colon params))
iterate-main-sublists
(:colon params)
iterate-list-of-sublists
(:at params)
iterate-main-list
true
iterate-sublist))
(\} [] #{:colon} {} nil)
(\<
[:mincol [0 Int32] :colinc [1 Int32] :minpad [0 Int32] :padchar [\space Char]]
#{:colon :at :both :pretty} { :right \>, :allows-separator true, :else :first }
logical-block-or-justify)
(\> [] #{:colon} {} nil)
;; TODO: detect errors in cases where colon not allowed
(\^ [:arg1 [nil Int32] :arg2 [nil Int32] :arg3 [nil Int32]]
#{:colon} {}
(fn [params navigator offsets]
(let [arg1 (:arg1 params)
arg2 (:arg2 params)
arg3 (:arg3 params)
exit (if (:colon params) :colon-up-arrow :up-arrow)]
(cond
(and arg1 arg2 arg3)
(if (<= arg1 arg2 arg3) [exit navigator] navigator)
(and arg1 arg2)
(if (= arg1 arg2) [exit navigator] navigator)
arg1
(if (= arg1 0) [exit navigator] navigator)
true ; TODO: handle looking up the arglist stack for info
(if (if (:colon params)
(empty? (:rest (:base-args params)))
(empty? (:rest navigator)))
[exit navigator] navigator)))))
(\W
[]
#{:at :colon :both :pretty} {}
(if (or (:at params) (:colon params))
(let [bindings (concat
(if (:at params) [:level nil :length nil] [])
(if (:colon params) [:pretty true] []))]
(fn [params navigator offsets]
(let [[arg navigator] (next-arg navigator)]
(if (apply write arg bindings)
[:up-arrow navigator]
navigator))))
(fn [params navigator offsets]
(let [[arg navigator] (next-arg navigator)]
(if (write-out arg)
[:up-arrow navigator]
navigator)))))
(\_
[]
#{:at :colon :both} {}
conditional-newline)
(\I
[:n [0 Int32]]
#{:colon} {}
set-indent)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Code to manage the parameters and flags associated with each
;;; directive in the format string.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^{:private true}
param-pattern #"^([vV]|#|('.)|([+-]?\d+)|(?=,))")
(def ^{:private true}
special-params #{ :parameter-from-args :remaining-arg-count })
(defn- extract-param [[s offset saw-comma]]
(let [m (re-matcher param-pattern s)
param (re-find m)]
(if param
(let [token-str (first (re-groups m))
remainder (subs s (.end m)) ;;; end
new-offset (+ offset (.end m))]
(if (not (= \, (nth remainder 0)))
[ [token-str offset] [remainder new-offset false]]
[ [token-str offset] [(subs remainder 1) (inc new-offset) true]]))
(if saw-comma
(format-error "Badly formed parameters in format directive" offset)
[ nil [s offset]]))))
(defn- extract-params [s offset]
(consume extract-param [s offset false]))
(defn- translate-param
"Translate the string representation of a param to the internalized
representation"
[[^String p offset]]
[(cond
(= (.Length p) 0) nil
(and (= (.Length p) 1) (contains? #{\v \V} (nth p 0))) :parameter-from-args ;;; length
(and (= (.Length p) 1) (= \# (nth p 0))) :remaining-arg-count
(and (= (.Length p) 2) (= \' (nth p 0))) (nth p 1)
true (Int32/Parse p)) ;;; (new Integer p)
offset])
(def ^{:private true}
flag-defs { \: :colon, \@ :at })
(defn- extract-flags [s offset]
(consume
(fn [[s offset flags]]
(if (empty? s)
[nil [s offset flags]]
(let [flag (get flag-defs (first s))]
(if flag
(if (contains? flags flag)
(format-error
(str "Flag \"" (first s) "\" appears more than once in a directive")
offset)
[true [(subs s 1) (inc offset) (assoc flags flag [true offset])]])
[nil [s offset flags]]))))
[s offset {}]))
(defn- check-flags [def flags]
(let [allowed (:flags def)]
(if (and (not (:at allowed)) (:at flags))
(format-error (str "\"@\" is an illegal flag for format directive \"" (:directive def) "\"")
(nth (:at flags) 1)))
(if (and (not (:colon allowed)) (:colon flags))
(format-error (str "\":\" is an illegal flag for format directive \"" (:directive def) "\"")
(nth (:colon flags) 1)))
(if (and (not (:both allowed)) (:at flags) (:colon flags))
(format-error (str "Cannot combine \"@\" and \":\" flags for format directive \""
(:directive def) "\"")
(min (nth (:colon flags) 1) (nth (:at flags) 1))))))
(defn- map-params
"Takes a directive definition and the list of actual parameters and
a map of flags and returns a map of the parameters and flags with defaults
filled in. We check to make sure that there are the right types and number
of parameters as well."
[def params flags offset]
(check-flags def flags)
(if (> (count params) (count (:params def)))
(format-error
(cl-format
nil
"Too many parameters for directive \"~C\": ~D~:* ~[were~;was~:;were~] specified but only ~D~:* ~[are~;is~:;are~] allowed"
(:directive def) (count params) (count (:params def)))
(second (first params))))
(doall
(map #(let [val (first %1)]
(if (not (or (nil? val) (contains? special-params val)
(instance? (second (second %2)) val)))
(format-error (str "Parameter " (name (first %2))
" has bad type in directive \"" (:directive def) "\": "
(class val))
(second %1))) )
params (:params def)))
(merge ; create the result map
(into (array-map) ; start with the default values, make sure the order is right
(reverse (for [[name [default]] (:params def)] [name [default offset]])))
(reduce #(apply assoc %1 %2) {} (filter #(first (nth % 1)) (zipmap (keys (:params def)) params))) ; add the specified parameters, filtering out nils
flags)) ; and finally add the flags
(defn- compile-directive [s offset]
(let [[raw-params [rest offset]] (extract-params s offset)
[_ [rest offset flags]] (extract-flags rest offset)
directive (first rest)
def (get directive-table (Char/ToUpper ^Char directive)) ;;; Character/toUpperCase
params (if def (map-params def (map translate-param raw-params) flags offset))]
(if (not directive)
(format-error "Format string ended in the middle of a directive" offset))
(if (not def)
(format-error (str "Directive \"" directive "\" is undefined") offset))
[(struct compiled-directive ((:generator-fn def) params offset) def params offset)
(let [remainder (subs rest 1)
offset (inc offset)
trim? (and (= \newline (:directive def))
(not (:colon params)))
trim-count (if trim? (prefix-count remainder [\space \tab]) 0)
remainder (subs remainder trim-count)
offset (+ offset trim-count)]
[remainder offset])]))
(defn- compile-raw-string [s offset]
(struct compiled-directive (fn [_ a _] (print s) a) nil { :string s } offset))
(defn- right-bracket [this] (:right (:bracket-info (:def this))))
(defn- separator? [this] (:separator (:bracket-info (:def this))))
(defn- else-separator? [this]
(and (:separator (:bracket-info (:def this)))
(:colon (:params this))))
(declare collect-clauses)
(defn- process-bracket [this remainder]
(let [[subex remainder] (collect-clauses (:bracket-info (:def this))
(:offset this) remainder)]
[(struct compiled-directive
(:func this) (:def this)
(merge (:params this) (tuple-map subex (:offset this)))
(:offset this))
remainder]))
(defn- process-clause [bracket-info offset remainder]
(consume
(fn [remainder]
(if (empty? remainder)
(format-error "No closing bracket found." offset)
(let [this (first remainder)
remainder (next remainder)]
(cond
(right-bracket this)
(process-bracket this remainder)
(= (:right bracket-info) (:directive (:def this)))
[ nil [:right-bracket (:params this) nil remainder]]
(else-separator? this)
[nil [:else nil (:params this) remainder]]
(separator? this)
[nil [:separator nil nil remainder]] ;; TODO: check to make sure that there are no params on ~;
true
[this remainder]))))
remainder))
(defn- collect-clauses [bracket-info offset remainder]
(second
(consume
(fn [[clause-map saw-else remainder]]
(let [[clause [type right-params else-params remainder]]
(process-clause bracket-info offset remainder)]
(cond
(= type :right-bracket)
[nil [(merge-with concat clause-map
{(if saw-else :else :clauses) [clause]
:right-params right-params})
remainder]]
(= type :else)
(cond
(:else clause-map)
(format-error "Two else clauses (\"~:;\") inside bracket construction." offset)
(not (:else bracket-info))
(format-error "An else clause (\"~:;\") is in a bracket type that doesn't support it."
offset)
(and (= :first (:else bracket-info)) (seq (:clauses clause-map)))
(format-error
"The else clause (\"~:;\") is only allowed in the first position for this directive."
offset)
true ; if the ~:; is in the last position, the else clause
; is next, this was a regular clause
(if (= :first (:else bracket-info))
[true [(merge-with concat clause-map { :else [clause] :else-params else-params})
false remainder]]
[true [(merge-with concat clause-map { :clauses [clause] })
true remainder]]))
(= type :separator)
(cond
saw-else
(format-error "A plain clause (with \"~;\") follows an else clause (\"~:;\") inside bracket construction." offset)
(not (:allows-separator bracket-info))
(format-error "A separator (\"~;\") is in a bracket type that doesn't support it."
offset)
true
[true [(merge-with concat clause-map { :clauses [clause] })
false remainder]]))))
[{ :clauses [] } false remainder])))
(defn- process-nesting
"Take a linearly compiled format and process the bracket directives to give it
the appropriate tree structure"
[format]
(first
(consume
(fn [remainder]
(let [this (first remainder)
remainder (next remainder)
bracket (:bracket-info (:def this))]
(if (:right bracket)
(process-bracket this remainder)
[this remainder])))
format)))
(defn- compile-format
"Compiles format-str into a compiled format which can be used as an argument
to cl-format just like a plain format string. Use this function for improved
performance when you're using the same format string repeatedly"
[ format-str ]
; (prlabel compiling format-str)
(binding [*format-str* format-str]
(process-nesting
(first
(consume
(fn [[^String s offset]]
(if (empty? s)
[nil s]
(let [tilde (.IndexOf s \~)] ;;; indexOf (int \~)
(cond
(neg? tilde) [(compile-raw-string s offset) ["" (+ offset (.Length s))]] ;;; length
(zero? tilde) (compile-directive (subs s 1) (inc offset))
true
[(compile-raw-string (subs s 0 tilde) offset) [(subs s tilde) (+ tilde offset)]]))))
[format-str 0])))))
(defn- needs-pretty
"determine whether a given compiled format has any directives that depend on the
column number or pretty printing"
[format]
(loop [format format]
(if (empty? format)
false
(if (or (:pretty (:flags (:def (first format))))
(some needs-pretty (first (:clauses (:params (first format)))))
(some needs-pretty (first (:else (:params (first format))))))
true
(recur (next format))))))
(defn- execute-format
"Executes the format with the arguments."
{:skip-wiki true}
([stream format args]
(let [^System.IO.TextWriter real-stream (cond ;;; java.io.Writer
(not stream) (System.IO.StringWriter.) ;;; java.io.StringWriter
(true? stream) *out*
:else stream)
^System.IO.TextWriter wrapped-stream (if (and (needs-pretty format) ;;; java.io.Writer
(not (pretty-writer? real-stream)))
(get-pretty-writer real-stream)
real-stream)]
(binding [*out* wrapped-stream]
(try
(execute-format format args)
(finally
(if-not (identical? real-stream wrapped-stream)
(.Flush wrapped-stream)))) ;;; flush
(if (not stream) (.ToString real-stream))))) ;;; toString
([format args]
(map-passing-context
(fn [element context]
(if (abort? context)
[nil context]
(let [[params args] (realize-parameter-list
(:params element) context)
[params offsets] (unzip-map params)
params (assoc params :base-args args)]
[nil (apply (:func element) [params args offsets])])))
args
format)
nil))
;;; This is a bad idea, but it prevents us from leaking private symbols
;;; This should all be replaced by really compiled formats anyway.
(def ^{:private true} cached-compile (memoize compile-format))
(defmacro formatter
"Makes a function which can directly run format-in. The function is
fn [stream & args] ... and returns nil unless the stream is nil (meaning
output to a string) in which case it returns the resulting string.
format-in can be either a control string or a previously compiled format."
{:added "1.2"}
[format-in]
`(let [format-in# ~format-in
my-c-c# (var-get (get (ns-interns (the-ns 'clojure.pprint))
'~'cached-compile))
my-e-f# (var-get (get (ns-interns (the-ns 'clojure.pprint))
'~'execute-format))
my-i-n# (var-get (get (ns-interns (the-ns 'clojure.pprint))
'~'init-navigator))
cf# (if (string? format-in#) (my-c-c# format-in#) format-in#)]
(fn [stream# & args#]
(let [navigator# (my-i-n# args#)]
(my-e-f# stream# cf# navigator#)))))
(defmacro formatter-out
"Makes a function which can directly run format-in. The function is
fn [& args] ... and returns nil. This version of the formatter macro is
designed to be used with *out* set to an appropriate Writer. In particular,
this is meant to be used as part of a pretty printer dispatch method.
format-in can be either a control string or a previously compiled format."
{:added "1.2"}
[format-in]
`(let [format-in# ~format-in
cf# (if (string? format-in#) (#'clojure.pprint/cached-compile format-in#) format-in#)]
(fn [& args#]
(let [navigator# (#'clojure.pprint/init-navigator args#)]
(#'clojure.pprint/execute-format cf# navigator#))))) | true | ;;; cl_format.clj -- part of the pretty printer for Clojure
; 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
;; April 3, 2009
;; This module implements the Common Lisp compatible format function as documented
;; in "Common Lisp the Language, 2nd edition", Chapter 22 (available online at:
;; http://www.cs.cmu.edu/afs/cs.cmu.edu/project/ai-repository/ai/html/cltl/clm/node200.html#SECTION002633000000000000000)
(in-ns 'clojure.pprint)
;;; Forward references
(declare compile-format)
(declare execute-format)
(declare init-navigator)
;;; End forward references
(defn cl-format
"An implementation of a Common Lisp compatible format function. cl-format formats its
arguments to an output stream or string based on the format control string given. It
supports sophisticated formatting of structured data.
Writer is an instance of java.io.Writer, true to output to *out* or nil to output
to a string, format-in is the format control string and the remaining arguments
are the data to be formatted.
The format control string is a string to be output with embedded 'format directives'
describing how to format the various arguments passed in.
If writer is nil, cl-format returns the formatted result string. Otherwise, cl-format
returns nil.
For example:
(let [results [46 38 22]]
(cl-format true \"There ~[are~;is~:;are~]~:* ~d result~:p: ~{~d~^, ~}~%\"
(count results) results))
Prints to *out*:
There are 3 results: 46, 38, 22
Detailed documentation on format control strings is available in the \"Common Lisp the
Language, 2nd edition\", Chapter 22 (available online at:
http://www.cs.cmu.edu/afs/cs.cmu.edu/project/ai-repository/ai/html/cltl/clm/node200.html#SECTION002633000000000000000)
and in the Common Lisp HyperSpec at
http://www.lispworks.com/documentation/HyperSpec/Body/22_c.htm
"
{:added "1.2",
:see-also [["http://www.cs.cmu.edu/afs/cs.cmu.edu/project/ai-repository/ai/html/cltl/clm/node200.html#SECTION002633000000000000000"
"Common Lisp the Language"]
["http://www.lispworks.com/documentation/HyperSpec/Body/22_c.htm"
"Common Lisp HyperSpec"]]}
[writer format-in & args]
(let [compiled-format (if (string? format-in) (compile-format format-in) format-in)
navigator (init-navigator args)]
(execute-format writer compiled-format navigator)))
(def ^:dynamic ^{:private true} *format-str* nil)
(defn- format-error [message offset]
(let [full-message (str message \newline *format-str* \newline
(apply str (repeat offset \space)) "^" \newline)]
(throw (Exception. full-message)))) ;;; RuntimeException
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Argument navigators manage the argument list
;;; as the format statement moves through the list
;;; (possibly going forwards and backwards as it does so)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defstruct ^{:private true}
arg-navigator :seq :rest :pos )
(defn- init-navigator
"Create a new arg-navigator from the sequence with the position set to 0"
{:skip-wiki true}
[s]
(let [s (seq s)]
(struct arg-navigator s s 0)))
;; TODO call format-error with offset
(defn- next-arg [ navigator ]
(let [ rst (:rest navigator) ]
(if rst
[(first rst) (struct arg-navigator (:seq navigator ) (next rst) (inc (:pos navigator)))]
(throw (new Exception "Not enough arguments for format definition")))))
(defn- next-arg-or-nil [navigator]
(let [rst (:rest navigator)]
(if rst
[(first rst) (struct arg-navigator (:seq navigator ) (next rst) (inc (:pos navigator)))]
[nil navigator])))
;; Get an argument off the arg list and compile it if it's not already compiled
(defn- get-format-arg [navigator]
(let [[raw-format navigator] (next-arg navigator)
compiled-format (if (instance? String raw-format)
(compile-format raw-format)
raw-format)]
[compiled-format navigator]))
(declare relative-reposition)
(defn- absolute-reposition [navigator position]
(if (>= position (:pos navigator))
(relative-reposition navigator (- (:pos navigator) position))
(struct arg-navigator (:seq navigator) (drop position (:seq navigator)) position)))
(defn- relative-reposition [navigator position]
(let [newpos (+ (:pos navigator) position)]
(if (neg? position)
(absolute-reposition navigator newpos)
(struct arg-navigator (:seq navigator) (drop position (:rest navigator)) newpos))))
(defstruct ^{:private true}
compiled-directive :func :def :params :offset)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; When looking at the parameter list, we may need to manipulate
;;; the argument list as well (for 'V' and '#' parameter types).
;;; We hide all of this behind a function, but clients need to
;;; manage changing arg navigator
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; TODO: validate parameters when they come from arg list
(defn- realize-parameter [[param [raw-val offset]] navigator]
(let [[real-param new-navigator]
(cond
(contains? #{ :at :colon } param) ;pass flags through unchanged - this really isn't necessary
[raw-val navigator]
(= raw-val :parameter-from-args)
(next-arg navigator)
(= raw-val :remaining-arg-count)
[(count (:rest navigator)) navigator]
true
[raw-val navigator])]
[[param [real-param offset]] new-navigator]))
(defn- realize-parameter-list [parameter-map navigator]
(let [[pairs new-navigator]
(map-passing-context realize-parameter navigator parameter-map)]
[(into {} pairs) new-navigator]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Functions that support individual directives
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Common handling code for ~A and ~S
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(declare opt-base-str)
(def ^{:private true}
special-radix-markers {2 "#b" 8 "#o", 16 "#x"})
(defn- format-simple-number [n]
(cond
(integer? n) (if (= *print-base* 10)
(str n (if *print-radix* "."))
(str
(if *print-radix* (or (get special-radix-markers *print-base*) (str "#" *print-base* "r")))
(opt-base-str *print-base* n)))
(ratio? n) (str
(if *print-radix* (or (get special-radix-markers *print-base*) (str "#" *print-base* "r")))
(opt-base-str *print-base* (.numerator n))
"/"
(opt-base-str *print-base* (.denominator n)))
:else nil))
(defn- format-ascii [print-func params arg-navigator offsets]
(let [ [arg arg-navigator] (next-arg arg-navigator)
^String base-output (or (format-simple-number arg) (print-func arg))
base-width (.Length base-output) ;;; length
min-width (+ base-width (:minpad params))
width (if (>= min-width (:mincol params))
min-width
(+ min-width
(* (+ (quot (- (:mincol params) min-width 1)
(:colinc params) )
1)
(:colinc params))))
chars (apply str (repeat (- width base-width) (:padchar params)))]
(if (:at params)
(print (str chars base-output))
(print (str base-output chars)))
arg-navigator))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for the integer directives ~D, ~X, ~O, ~B and some
;;; of ~R
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- integral?
"returns true if a number is actually an integer (that is, has no fractional part)"
[x]
(cond
(integer? x) true
(decimal? x) true ;;; TODO: FIX THIS (>= (.ulp (.stripTrailingZeros (bigdec 0))) 1) ; true iff no fractional part DM: ??????? doesn't mention x!!!
(float? x) (= x (Math/Floor x)) ;;; Math/floor
(ratio? x) (let [^clojure.lang.Ratio r x]
(= 0 (rem (.numerator r) (.denominator r))))
:else false))
(defn- remainders
"Return the list of remainders (essentially the 'digits') of val in the given base"
[base val]
(reverse
(first
(consume #(if (pos? %)
[(rem % base) (quot % base)]
[nil nil])
val))))
;;; TODO: xlated-val does not seem to be used here. ---- ;;;; I had to use it to prevent the call to remainders from returning a Double instead of an integer in the last position
(defn- base-str
"Return val as a string in the given base"
[base val]
(if (zero? val)
"0"
(let [xlated-val (cond
(float? val) (bigdec val)
(ratio? val) (let [^clojure.lang.Ratio r val]
(/ (.numerator r) (.denominator r)))
:else val)]
(apply str
(map
#(if (< % 10) (char (+ (int \0) %)) (char (+ (int \a) (- % 10))))
(remainders base xlated-val))))))
(def ^{:private true}
java-base-formats {8 "%o", 10 "%d", 16 "%x"})
(defn- opt-base-str
"Return val as a string in the given base, using clojure.core/format if supported
for improved performance"
[base val]
(let [format-str (get java-base-formats base)]
(if (and format-str (integer? val) (not (instance? clojure.lang.BigInt val)))
(clojure.core/format format-str val)
(base-str base val))))
(defn- group-by* [unit lis]
(reverse
(first
(consume (fn [x] [(seq (reverse (take unit x))) (seq (drop unit x))]) (reverse lis)))))
(defn- format-integer [base params arg-navigator offsets]
(let [[arg arg-navigator] (next-arg arg-navigator)]
(if (integral? arg)
(let [neg (neg? arg)
pos-arg (if neg (- arg) arg)
raw-str (opt-base-str base pos-arg)
group-str (if (:colon params)
(let [groups (map #(apply str %) (group-by* (:commainterval params) raw-str))
commas (repeat (count groups) (:commachar params))]
(apply str (next (interleave commas groups))))
raw-str)
^String signed-str (cond
neg (str "-" group-str)
(:at params) (str "+" group-str)
true group-str)
padded-str (if (< (.Length signed-str) (:mincol params)) ;;; length
(str (apply str (repeat (- (:mincol params) (.Length signed-str)) ;;; length
(:padchar params)))
signed-str)
signed-str)]
(print padded-str))
(format-ascii print-str {:mincol (:mincol params) :colinc 1 :minpad 0
:padchar (:padchar params) :at true}
(init-navigator [arg]) nil))
arg-navigator))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for english formats (~R and ~:R)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^{:private true}
english-cardinal-units
["zero" "one" "two" "three" "four" "five" "six" "seven" "eight" "nine"
"ten" "eleven" "twelve" "thirteen" "fourteen"
"fifteen" "sixteen" "seventeen" "eighteen" "nineteen"])
(def ^{:private true}
english-ordinal-units
["zeroth" "first" "second" "third" "fourth" "fifth" "sixth" "seventh" "eighth" "ninth"
"tenth" "eleventh" "twelfth" "thirteenth" "fourteenth"
"fifteenth" "sixteenth" "seventeenth" "eighteenth" "nineteenth"])
(def ^{:private true}
english-cardinal-tens
["" "" "twenty" "thirty" "forty" "fifty" "sixty" "seventy" "eighty" "ninety"])
(def ^{:private true}
english-ordinal-tens
["" "" "twentieth" "thirtieth" "fortieth" "fiftieth"
"sixtieth" "seventieth" "eightieth" "ninetieth"])
;; We use "short scale" for our units (see http://en.wikipedia.org/wiki/Long_and_short_scales)
;; Number names from http://www.jimloy.com/math/billion.htm
;; We follow the rules for writing numbers from the Blue Book
;; (http://www.grammarbook.com/numbers/numbers.asp)
(def ^{:private true}
english-scale-numbers
["" "thousand" "million" "billion" "trillion" "quadrillion" "quintillion"
"sextillion" "septillion" "octillion" "nonillion" "decillion"
"undecillion" "duodecillion" "tredecillion" "quattuordecillion"
"quindecillion" "sexdecillion" "septendecillion"
"octodecillion" "novemdecillion" "vigintillion"])
(defn- format-simple-cardinal
"Convert a number less than 1000 to a cardinal english string"
[num]
(let [hundreds (quot num 100)
tens (rem num 100)]
(str
(if (pos? hundreds) (str (nth english-cardinal-units hundreds) " hundred"))
(if (and (pos? hundreds) (pos? tens)) " ")
(if (pos? tens)
(if (< tens 20)
(nth english-cardinal-units tens)
(let [ten-digit (quot tens 10)
unit-digit (rem tens 10)]
(str
(if (pos? ten-digit) (nth english-cardinal-tens ten-digit))
(if (and (pos? ten-digit) (pos? unit-digit)) "-")
(if (pos? unit-digit) (nth english-cardinal-units unit-digit)))))))))
(defn- add-english-scales
"Take a sequence of parts, add scale numbers (e.g., million) and combine into a string
offset is a factor of 10^3 to multiply by"
[parts offset]
(let [cnt (count parts)]
(loop [acc []
pos (dec cnt)
this (first parts)
remainder (next parts)]
(if (nil? remainder)
(str (apply str (interpose ", " acc))
(if (and (not (empty? this)) (not (empty? acc))) ", ")
this
(if (and (not (empty? this)) (pos? (+ pos offset)))
(str " " (nth english-scale-numbers (+ pos offset)))))
(recur
(if (empty? this)
acc
(conj acc (str this " " (nth english-scale-numbers (+ pos offset)))))
(dec pos)
(first remainder)
(next remainder))))))
(defn- format-cardinal-english [params navigator offsets]
(let [[arg navigator] (next-arg navigator)]
(if (= 0 arg)
(print "zero")
(let [abs-arg (if (neg? arg) (- arg) arg) ; some numbers are too big for Math/abs
parts (remainders 1000 abs-arg)]
(if (<= (count parts) (count english-scale-numbers))
(let [parts-strs (map format-simple-cardinal parts)
full-str (add-english-scales parts-strs 0)]
(print (str (if (neg? arg) "minus ") full-str)))
(format-integer ;; for numbers > 10^63, we fall back on ~D
10
{ :mincol 0, :padchar \space, :commachar \, :commainterval 3, :colon true}
(init-navigator [arg])
{ :mincol 0, :padchar 0, :commachar 0 :commainterval 0}))))
navigator))
(defn- format-simple-ordinal
"Convert a number less than 1000 to a ordinal english string
Note this should only be used for the last one in the sequence"
[num]
(let [hundreds (quot num 100)
tens (rem num 100)]
(str
(if (pos? hundreds) (str (nth english-cardinal-units hundreds) " hundred"))
(if (and (pos? hundreds) (pos? tens)) " ")
(if (pos? tens)
(if (< tens 20)
(nth english-ordinal-units tens)
(let [ten-digit (quot tens 10)
unit-digit (rem tens 10)]
(if (and (pos? ten-digit) (not (pos? unit-digit)))
(nth english-ordinal-tens ten-digit)
(str
(if (pos? ten-digit) (nth english-cardinal-tens ten-digit))
(if (and (pos? ten-digit) (pos? unit-digit)) "-")
(if (pos? unit-digit) (nth english-ordinal-units unit-digit))))))
(if (pos? hundreds) "th")))))
(defn- format-ordinal-english [params navigator offsets]
(let [[arg navigator] (next-arg navigator)]
(if (= 0 arg)
(print "zeroth")
(let [abs-arg (if (neg? arg) (- arg) arg) ; some numbers are too big for Math/abs
parts (remainders 1000 abs-arg)]
(if (<= (count parts) (count english-scale-numbers))
(let [parts-strs (map format-simple-cardinal (drop-last parts))
head-str (add-english-scales parts-strs 1)
tail-str (format-simple-ordinal (last parts))]
(print (str (if (neg? arg) "minus ")
(cond
(and (not (empty? head-str)) (not (empty? tail-str)))
(str head-str ", " tail-str)
(not (empty? head-str)) (str head-str "th")
:else tail-str))))
(do (format-integer ;; for numbers > 10^63, we fall back on ~D
10
{ :mincol 0, :padchar \space, :commachar \, :commainterval 3, :colon true}
(init-navigator [arg])
{ :mincol 0, :padchar 0, :commachar 0 :commainterval 0})
(let [low-two-digits (rem arg 100)
not-teens (or (< 11 low-two-digits) (> 19 low-two-digits))
low-digit (rem low-two-digits 10)]
(print (cond
(and (== low-digit 1) not-teens) "st"
(and (== low-digit 2) not-teens) "nd"
(and (== low-digit 3) not-teens) "rd"
:else "th")))))))
navigator))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for roman numeral formats (~@R and ~@:R)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^{:private true}
old-roman-table
[[ "I" "II" "III" "IIII" "V" "VI" "VII" "VIII" "VIIII"]
[ "X" "XX" "XXX" "XXXX" "L" "LX" "LXX" "LXXX" "LXXXX"]
[ "C" "CC" "CCC" "CCCC" "D" "DC" "DCC" "DCCC" "DCCCC"]
[ "M" "MM" "MMM"]])
(def ^{:private true}
new-roman-table
[[ "I" "II" "III" "IV" "V" "VI" "VII" "VIII" "IX"]
[ "X" "XX" "XXX" "XL" "L" "LX" "LXX" "LXXX" "XC"]
[ "C" "CC" "CCC" "CD" "D" "DC" "DCC" "DCCC" "CM"]
[ "M" "MM" "MMM"]])
(defn- format-roman
"Format a roman numeral using the specified look-up table"
[table params navigator offsets]
(let [[arg navigator] (next-arg navigator)]
(if (and (number? arg) (> arg 0) (< arg 4000))
(let [digits (remainders 10 arg)]
(loop [acc []
pos (dec (count digits))
digits digits]
(if (empty? digits)
(print (apply str acc))
(let [digit (first digits)]
(recur (if (= 0 digit)
acc
(conj acc (nth (nth table pos) (dec digit))))
(dec pos)
(next digits))))))
(format-integer ;; for anything <= 0 or > 3999, we fall back on ~D
10
{ :mincol 0, :padchar \space, :commachar \, :commainterval 3, :colon true}
(init-navigator [arg])
{ :mincol 0, :padchar 0, :commachar 0 :commainterval 0}))
navigator))
(defn- format-old-roman [params navigator offsets]
(format-roman old-roman-table params navigator offsets))
(defn- format-new-roman [params navigator offsets]
(format-roman new-roman-table params navigator offsets))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for character formats (~C)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^{:private true}
special-chars { 8 "Backspace", 9 "Tab", 10 "Newline", 13 "Return", 32 "Space"})
(defn- pretty-character [params navigator offsets]
(let [[c navigator] (next-arg navigator)
as-int (int c)
base-char (bit-and as-int 127)
meta (bit-and as-int 128)
special (get special-chars base-char)]
(if (> meta 0) (print "Meta-"))
(print (cond
special special
(< base-char 32) (str "Control-" (char (+ base-char 64)))
(= base-char 127) "Control-?"
:else (char base-char)))
navigator))
(defn- readable-character [params navigator offsets]
(let [[c navigator] (next-arg navigator)]
(condp = (:char-format params)
\o (cl-format true "\\o~3,'0o" (int c))
\u (cl-format true "\\u~4,'0x" (int c))
nil (pr c))
navigator))
(defn- plain-character [params navigator offsets]
(let [[char navigator] (next-arg navigator)]
(print char)
navigator))
;; Check to see if a result is an abort (~^) construct
;; TODO: move these funcs somewhere more appropriate
(defn- abort? [context]
(let [token (first context)]
(or (= :up-arrow token) (= :colon-up-arrow token))))
;; Handle the execution of "sub-clauses" in bracket constructions
(defn- execute-sub-format [format args base-args]
(second
(map-passing-context
(fn [element context]
(if (abort? context)
[nil context] ; just keep passing it along
(let [[params args] (realize-parameter-list (:params element) context)
[params offsets] (unzip-map params)
params (assoc params :base-args base-args)]
[nil (apply (:func element) [params args offsets])])))
args
format)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for real number formats
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; TODO - return exponent as int to eliminate double conversion
(defn- float-parts-base
"Produce string parts for the mantissa (normalized 1-9) and exponent"
[^Object f]
(let [^String s (.ToLower (.ToString f)) ;;; .toLowerCase .toString
exploc (.IndexOf s \e) ;;; .indexOf (int \e)
dotloc (.IndexOf s \.)] ;;; .indexOf (int \.)
(if (neg? exploc)
(if (neg? dotloc)
[s (str (dec (count s)))]
[(str (subs s 0 dotloc) (subs s (inc dotloc))) (str (dec dotloc))])
(if (neg? dotloc)
[(subs s 0 exploc) (subs s (inc exploc))]
[(str (subs s 0 1) (subs s 2 exploc)) (subs s (inc exploc))]))))
(defn- float-parts
"Take care of leading and trailing zeros in decomposed floats"
[f]
(let [[m ^String e] (float-parts-base f)
m1 (rtrim m \0)
m2 (ltrim m1 \0)
delta (- (count m1) (count m2))
^String e (if (and (pos? (count e)) (= (nth e 0) \+)) (subs e 1) e)]
(if (empty? m2)
["0" 0]
[m2 (- (Int32/Parse e) delta)]))) ;;; (Integer/valueOf e)
(defn- ^String inc-s
"Assumption: The input string consists of one or more decimal digits,
and no other characters. Return a string containing one or more
decimal digits containing a decimal number one larger than the input
string. The output string will always be the same length as the input
string, or one character longer."
[^String s]
(let [len-1 (dec (count s))]
(loop [i (int len-1)]
(cond
(neg? i) (apply str "1" (repeat (inc len-1) "0"))
(= \9 (.get_Chars s i)) (recur (dec i)) ;;; .charAt
:else (apply str (subs s 0 i)
(char (inc (int (.get_Chars s i)))) ;;; .charAt
(repeat (- len-1 i) "0"))))))
(defn- round-str [m e d w]
(if (or d w)
(let [len (count m)
;; Every formatted floating point number should include at
;; least one decimal digit and a decimal point.
w (if w (max 2 w))
round-pos (cond
;; If d was given, that forces the rounding
;; position, regardless of any width that may
;; have been specified.
d (+ e d 1)
;; Otherwise w was specified, so pick round-pos
;; based upon that.
;; If e>=0, then abs value of number is >= 1.0,
;; and e+1 is number of decimal digits before the
;; decimal point when the number is written
;; without scientific notation. Never round the
;; number before the decimal point.
(>= e 0) (max (inc e) (dec w))
;; e < 0, so number abs value < 1.0
:else (+ w e))
[m1 e1 round-pos len] (if (= round-pos 0)
[(str "0" m) (inc e) 1 (inc len)]
[m e round-pos len])]
(if round-pos
(if (neg? round-pos)
["0" 0 false]
(if (> len round-pos)
(let [round-char (nth m1 round-pos)
^String result (subs m1 0 round-pos)]
(if (>= (int round-char) (int \5))
(let [round-up-result (inc-s result)
expanded (> (count round-up-result) (count result))]
[(if expanded
(subs round-up-result 0 (dec (count round-up-result)))
round-up-result)
e1 expanded])
[result e1 false]))
[m e false]))
[m e false]))
[m e false]))
(defn- expand-fixed [m e d]
(let [[m1 e1] (if (neg? e)
[(str (apply str (repeat (dec (- e)) \0)) m) -1]
[m e])
len (count m1)
target-len (if d (+ e1 d 1) (inc e1))]
(if (< len target-len)
(str m1 (apply str (repeat (- target-len len) \0)))
m1)))
(defn- insert-decimal
"Insert the decimal point at the right spot in the number to match an exponent"
[m e]
(if (neg? e)
(str "." m)
(let [loc (inc e)]
(str (subs m 0 loc) "." (subs m loc)))))
(defn- get-fixed [m e d]
(insert-decimal (expand-fixed m e d) e))
(defn- insert-scaled-decimal
"Insert the decimal point at the right spot in the number to match an exponent"
[m k]
(if (neg? k)
(str "." m)
(str (subs m 0 k) "." (subs m k))))
(defn- convert-ratio [x]
(if (ratio? x)
;; Usually convert to a double, only resorting to the slower
;; bigdec conversion if the result does not fit within the range
;; of a double.
(let [d (double x)]
(if (== d 0.0)
(if (not= x 0)
(bigdec x)
d)
(if (or (== d Double/PositiveInfinity) (== d Double/NegativeInfinity)) ;;; Double/POSITIVE_INFINITY Double/NEGATIVE_INFINITY
(bigdec x)
d)))
x))
;; the function to render ~F directives
;; TODO: support rationals. Back off to ~D/~A is the appropriate cases
(defn- fixed-float [params navigator offsets]
(let [w (:w params)
d (:d params)
[arg navigator] (next-arg navigator)
[sign abs] (if (neg? arg) ["-" (- arg)] ["+" arg])
abs (convert-ratio abs)
[mantissa exp] (float-parts abs)
scaled-exp (+ exp (:k params))
add-sign (or (:at params) (neg? arg))
append-zero (and (not d) (<= (dec (count mantissa)) scaled-exp))
[rounded-mantissa scaled-exp expanded] (round-str mantissa scaled-exp
d (if w (- w (if add-sign 1 0))))
fixed-repr (get-fixed rounded-mantissa (if expanded (inc scaled-exp) scaled-exp) d)
fixed-repr (if (and w d
(>= d 1)
(= (.get_Chars fixed-repr 0) \0) ;;; .charAt
(= (.get_Chars fixed-repr 1) \.) ;;; .charAt
(> (count fixed-repr) (- w (if add-sign 1 0))))
(subs fixed-repr 1) ; chop off leading 0
fixed-repr)
prepend-zero (= (first fixed-repr) \.)]
(if w
(let [len (count fixed-repr)
signed-len (if add-sign (inc len) len)
prepend-zero (and prepend-zero (not (>= signed-len w)))
append-zero (and append-zero (not (>= signed-len w)))
full-len (if (or prepend-zero append-zero)
(inc signed-len)
signed-len)]
(if (and (> full-len w) (:overflowchar params))
(print (apply str (repeat w (:overflowchar params))))
(print (str
(apply str (repeat (- w full-len) (:padchar params)))
(if add-sign sign)
(if prepend-zero "0")
fixed-repr
(if append-zero "0")))))
(print (str
(if add-sign sign)
(if prepend-zero "0")
fixed-repr
(if append-zero "0"))))
navigator))
;; the function to render ~E directives
;; TODO: support rationals. Back off to ~D/~A is the appropriate cases
;; TODO: define ~E representation for Infinity
(defn- exponential-float [params navigator offsets]
(let [[arg navigator] (next-arg navigator)
arg (convert-ratio arg)]
(loop [[mantissa exp] (float-parts (if (neg? arg) (- arg) arg))]
(let [w (:w params)
d (:d params)
e (:e params)
k (:k params)
expchar (or (:exponentchar params) \E)
add-sign (or (:at params) (neg? arg))
prepend-zero (<= k 0)
^Int32 scaled-exp (- exp (dec k)) ;;; Integer
scaled-exp-str (str (Math/Abs scaled-exp)) ;;; Math/abs
scaled-exp-str (str expchar (if (neg? scaled-exp) \- \+)
(if e (apply str
(repeat
(- e
(count scaled-exp-str))
\0)))
scaled-exp-str)
exp-width (count scaled-exp-str)
base-mantissa-width (count mantissa)
scaled-mantissa (str (apply str (repeat (- k) \0))
mantissa
(if d
(apply str
(repeat
(- d (dec base-mantissa-width)
(if (neg? k) (- k) 0)) \0))))
w-mantissa (if w (- w exp-width))
[rounded-mantissa _ incr-exp] (round-str
scaled-mantissa 0
(cond
(= k 0) (dec d)
(pos? k) d
(neg? k) (dec d))
(if w-mantissa
(- w-mantissa (if add-sign 1 0))))
full-mantissa (insert-scaled-decimal rounded-mantissa k)
append-zero (and (= k (count rounded-mantissa)) (nil? d))]
(if (not incr-exp)
(if w
(let [len (+ (count full-mantissa) exp-width)
signed-len (if add-sign (inc len) len)
prepend-zero (and prepend-zero (not (= signed-len w)))
full-len (if prepend-zero (inc signed-len) signed-len)
append-zero (and append-zero (< full-len w))]
(if (and (or (> full-len w) (and e (> (- exp-width 2) e)))
(:overflowchar params))
(print (apply str (repeat w (:overflowchar params))))
(print (str
(apply str
(repeat
(- w full-len (if append-zero 1 0) )
(:padchar params)))
(if add-sign (if (neg? arg) \- \+))
(if prepend-zero "0")
full-mantissa
(if append-zero "0")
scaled-exp-str))))
(print (str
(if add-sign (if (neg? arg) \- \+))
(if prepend-zero "0")
full-mantissa
(if append-zero "0")
scaled-exp-str)))
(recur [rounded-mantissa (inc exp)]))))
navigator))
;; the function to render ~G directives
;; This just figures out whether to pass the request off to ~F or ~E based
;; on the algorithm in CLtL.
;; TODO: support rationals. Back off to ~D/~A is the appropriate cases
;; TODO: refactor so that float-parts isn't called twice
(defn- general-float [params navigator offsets]
(let [[arg _] (next-arg navigator)
arg (convert-ratio arg)
[mantissa exp] (float-parts (if (neg? arg) (- arg) arg))
w (:w params)
d (:d params)
e (:e params)
n (if (= arg 0.0) 0 (inc exp))
ee (if e (+ e 2) 4)
ww (if w (- w ee))
d (if d d (max (count mantissa) (min n 7)))
dd (- d n)]
(if (<= 0 dd d)
(let [navigator (fixed-float {:w ww, :d dd, :k 0,
:overflowchar (:overflowchar params),
:padchar (:padchar params), :at (:at params)}
navigator offsets)]
(print (apply str (repeat ee \space)))
navigator)
(exponential-float params navigator offsets))))
;; the function to render ~$ directives
;; TODO: support rationals. Back off to ~D/~A is the appropriate cases
(defn- dollar-float [params navigator offsets]
(let [[^Double arg navigator] (next-arg navigator)
[mantissa exp] (float-parts (Math/Abs arg)) ;;; Math/abs
d (:d params) ; digits after the decimal
n (:n params) ; minimum digits before the decimal
w (:w params) ; minimum field width
add-sign (or (:at params) (neg? arg))
[rounded-mantissa scaled-exp expanded] (round-str mantissa exp d nil)
^String fixed-repr (get-fixed rounded-mantissa (if expanded (inc scaled-exp) scaled-exp) d)
full-repr (str (apply str (repeat (- n (.IndexOf fixed-repr \.)) \0)) fixed-repr) ;;; .indexOf (int \.)
full-len (+ (count full-repr) (if add-sign 1 0))]
(print (str
(if (and (:colon params) add-sign) (if (neg? arg) \- \+))
(apply str (repeat (- w full-len) (:padchar params)))
(if (and (not (:colon params)) add-sign) (if (neg? arg) \- \+))
full-repr))
navigator))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for the '~[...~]' conditional construct in its
;;; different flavors
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ~[...~] without any modifiers chooses one of the clauses based on the param or
;; next argument
;; TODO check arg is positive int
(defn- choice-conditional [params arg-navigator offsets]
(let [arg (:selector params)
[arg navigator] (if arg [arg arg-navigator] (next-arg arg-navigator))
clauses (:clauses params)
clause (if (or (neg? arg) (>= arg (count clauses)))
(first (:else params))
(nth clauses arg))]
(if clause
(execute-sub-format clause navigator (:base-args params))
navigator)))
;; ~:[...~] with the colon reads the next argument treating it as a truth value
(defn- boolean-conditional [params arg-navigator offsets]
(let [[arg navigator] (next-arg arg-navigator)
clauses (:clauses params)
clause (if arg
(second clauses)
(first clauses))]
(if clause
(execute-sub-format clause navigator (:base-args params))
navigator)))
;; ~@[...~] with the at sign executes the conditional if the next arg is not
;; nil/false without consuming the arg
(defn- check-arg-conditional [params arg-navigator offsets]
(let [[arg navigator] (next-arg arg-navigator)
clauses (:clauses params)
clause (if arg (first clauses))]
(if arg
(if clause
(execute-sub-format clause arg-navigator (:base-args params))
arg-navigator)
navigator)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for the '~{...~}' iteration construct in its
;;; different flavors
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ~{...~} without any modifiers uses the next argument as an argument list that
;; is consumed by all the iterations
(defn- iterate-sublist [params navigator offsets]
(let [max-count (:max-iterations params)
param-clause (first (:clauses params))
[clause navigator] (if (empty? param-clause)
(get-format-arg navigator)
[param-clause navigator])
[arg-list navigator] (next-arg navigator)
args (init-navigator arg-list)]
(loop [count 0
args args
last-pos (num -1)]
(if (and (not max-count) (= (:pos args) last-pos) (> count 1))
;; TODO get the offset in here and call format exception
(throw (Exception. "%{ construct not consuming any arguments: Infinite loop!"))) ;;; RuntimeException
(if (or (and (empty? (:rest args))
(or (not (:colon (:right-params params))) (> count 0)))
(and max-count (>= count max-count)))
navigator
(let [iter-result (execute-sub-format clause args (:base-args params))]
(if (= :up-arrow (first iter-result))
navigator
(recur (inc count) iter-result (:pos args))))))))
;; ~:{...~} with the colon treats the next argument as a list of sublists. Each of the
;; sublists is used as the arglist for a single iteration.
(defn- iterate-list-of-sublists [params navigator offsets]
(let [max-count (:max-iterations params)
param-clause (first (:clauses params))
[clause navigator] (if (empty? param-clause)
(get-format-arg navigator)
[param-clause navigator])
[arg-list navigator] (next-arg navigator)]
(loop [count 0
arg-list arg-list]
(if (or (and (empty? arg-list)
(or (not (:colon (:right-params params))) (> count 0)))
(and max-count (>= count max-count)))
navigator
(let [iter-result (execute-sub-format
clause
(init-navigator (first arg-list))
(init-navigator (next arg-list)))]
(if (= :colon-up-arrow (first iter-result))
navigator
(recur (inc count) (next arg-list))))))))
;; ~@{...~} with the at sign uses the main argument list as the arguments to the iterations
;; is consumed by all the iterations
(defn- iterate-main-list [params navigator offsets]
(let [max-count (:max-iterations params)
param-clause (first (:clauses params))
[clause navigator] (if (empty? param-clause)
(get-format-arg navigator)
[param-clause navigator])]
(loop [count 0
navigator navigator
last-pos (num -1)]
(if (and (not max-count) (= (:pos navigator) last-pos) (> count 1))
;; TODO get the offset in here and call format exception
(throw (Exception. "%@{ construct not consuming any arguments: Infinite loop!"))) ;;; RuntimeException
(if (or (and (empty? (:rest navigator))
(or (not (:colon (:right-params params))) (> count 0)))
(and max-count (>= count max-count)))
navigator
(let [iter-result (execute-sub-format clause navigator (:base-args params))]
(if (= :up-arrow (first iter-result))
(second iter-result)
(recur
(inc count) iter-result (:pos navigator))))))))
;; ~@:{...~} with both colon and at sign uses the main argument list as a set of sublists, one
;; of which is consumed with each iteration
(defn- iterate-main-sublists [params navigator offsets]
(let [max-count (:max-iterations params)
param-clause (first (:clauses params))
[clause navigator] (if (empty? param-clause)
(get-format-arg navigator)
[param-clause navigator])
]
(loop [count 0
navigator navigator]
(if (or (and (empty? (:rest navigator))
(or (not (:colon (:right-params params))) (> count 0)))
(and max-count (>= count max-count)))
navigator
(let [[sublist navigator] (next-arg-or-nil navigator)
iter-result (execute-sub-format clause (init-navigator sublist) navigator)]
(if (= :colon-up-arrow (first iter-result))
navigator
(recur (inc count) navigator)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The '~< directive has two completely different meanings
;;; in the '~<...~>' form it does justification, but with
;;; ~<...~:>' it represents the logical block operation of the
;;; pretty printer.
;;;
;;; Unfortunately, the current architecture decides what function
;;; to call at form parsing time before the sub-clauses have been
;;; folded, so it is left to run-time to make the decision.
;;;
;;; TODO: make it possible to make these decisions at compile-time.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(declare format-logical-block)
(declare justify-clauses)
(defn- logical-block-or-justify [params navigator offsets]
(if (:colon (:right-params params))
(format-logical-block params navigator offsets)
(justify-clauses params navigator offsets)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for the '~<...~>' justification directive
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- render-clauses [clauses navigator base-navigator]
(loop [clauses clauses
acc []
navigator navigator]
(if (empty? clauses)
[acc navigator]
(let [clause (first clauses)
[iter-result result-str] (binding [*out* (System.IO.StringWriter.)] ;;; java.io.StringWriter.
[(execute-sub-format clause navigator base-navigator)
(.ToString *out*)])] ;;; toString
(if (= :up-arrow (first iter-result))
[acc (second iter-result)]
(recur (next clauses) (conj acc result-str) iter-result))))))
;; TODO support for ~:; constructions
(defn- justify-clauses [params navigator offsets]
(let [[[eol-str] new-navigator] (when-let [else (:else params)]
(render-clauses else navigator (:base-args params)))
navigator (or new-navigator navigator)
[else-params new-navigator] (when-let [p (:else-params params)]
(realize-parameter-list p navigator))
navigator (or new-navigator navigator)
min-remaining (or (first (:min-remaining else-params)) 0)
max-columns (or (first (:max-columns else-params))
(get-max-column *out*))
clauses (:clauses params)
[strs navigator] (render-clauses clauses navigator (:base-args params))
slots (max 1
(+ (dec (count strs)) (if (:colon params) 1 0) (if (:at params) 1 0)))
chars (reduce + (map count strs))
mincol (:mincol params)
minpad (:minpad params)
colinc (:colinc params)
minout (+ chars (* slots minpad))
result-columns (if (<= minout mincol)
mincol
(+ mincol (* colinc
(+ 1 (quot (- minout mincol 1) colinc)))))
total-pad (- result-columns chars)
pad (max minpad (quot total-pad slots))
extra-pad (- total-pad (* pad slots))
pad-str (apply str (repeat pad (:padchar params)))]
(if (and eol-str (> (+ (get-column (:base @@*out*)) min-remaining result-columns)
max-columns))
(print eol-str))
(loop [slots slots
extra-pad extra-pad
strs strs
pad-only (or (:colon params)
(and (= (count strs) 1) (not (:at params))))]
(if (seq strs)
(do
(print (str (if (not pad-only) (first strs))
(if (or pad-only (next strs) (:at params)) pad-str)
(if (pos? extra-pad) (:padchar params))))
(recur
(dec slots)
(dec extra-pad)
(if pad-only strs (next strs))
false))))
navigator))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for case modification with ~(...~).
;;; We do this by wrapping the underlying writer with
;;; a special writer to do the appropriate modification. This
;;; allows us to support arbitrary-sized output and sources
;;; that may block.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- downcase-writer
"Returns a proxy that wraps writer, converting all characters to lower case"
[^System.IO.TextWriter writer] ;;; java.io.Writer
(proxy [System.IO.TextWriter] [] ;;; java.io.Writer
(Close [] (.Close writer)) ;;; close
(Flush [] (.Flush writer)) ;;; flush
(Write ([^chars cbuf off len] ;;; write ^Integer hint removed from off,len
(.Write writer cbuf ^Int32 off ^Int32 len)) ;;; write, hints added
([x]
(condp = (class x)
String
(let [s ^String x]
(.Write writer (.ToLower s))) ;;; write toLowerCase
Int32 ;;; Integer
(let [c x] ;;; Character hint removoed
(.Write writer (int (Char/ToLower (char c)))))))))) ;;; .write Character/toLowerCase
(defn- upcase-writer
"Returns a proxy that wraps writer, converting all characters to upper case"
[^System.IO.TextWriter writer] ;;; java.io.Writer
(proxy [System.IO.TextWriter] [] ;;; java.io.Writer
(Close [] (.Close writer))
(Flush [] (.Flush writer))
(Write ([^chars cbuf off len] ;;; ^Integer hint removed from off, len
(.Write writer cbuf ^Int32 off ^Int32 len)) ;; Int32 hints added
([x]
(condp = (class x)
String
(let [s ^String x]
(.Write writer (.ToUpper s)))
Int32
(let [c x] ;;; Character hint removed from c
(.Write writer (int (Char/ToUpper (char c))))))))))
(defn- capitalize-string
"Capitalizes the words in a string. If first? is false, don't capitalize the
first character of the string even if it's a letter."
[s first?]
(let [^Char f (first s) ;;; Character
s (if (and first? f (Char/IsLetter f)) ;;; Character/isLetter
(str (Char/ToUpper f) (subs s 1)) ;;; Character/toUpperCase
s)]
(apply str
(first
(consume
(fn [s]
(if (empty? s)
[nil nil]
(let [m (re-matcher #"\W\w" s)
match (re-find m)
offset (and match (inc (.start m)))] ;;; .start
(if offset
[(str (subs s 0 offset)
(Char/ToUpper ^Char (char (nth s offset)))) ;;; Character/toUpperCase Character (char ... ) wrapper added
(subs s (inc offset))]
[s nil]))))
s)))))
(defn- capitalize-word-writer
"Returns a proxy that wraps writer, capitalizing all words"
[^System.IO.TextWriter writer] ;;; java.io.Writer
(let [last-was-whitespace? (ref true)]
(proxy [System.IO.TextWriter] []
(Close [] (.Close writer))
(Flush [] (.Flush writer))
(Write
([^chars cbuf off len] (let [off (int off) len (int len)] ;;; remove ^Integer hints on off, len
(.Write writer cbuf off len)) )
([x]
(condp = (class x)
String
(let [s ^String x]
(.Write writer
^String (capitalize-string (.ToLower s) @last-was-whitespace?)) ;;; toLowerCase
(when (pos? (.Length s)) ;;; .length
(dosync
(ref-set last-was-whitespace?
(Char/IsWhiteSpace ;;; Character/isWhitespace
^Char (nth s (dec (count s)))))))) ;;; ^Character
Int32
(let [c (char x)]
(let [mod-c (if @last-was-whitespace? (Char/ToUpper (char x)) c)]
(.Write writer (int mod-c))
(dosync (ref-set last-was-whitespace? (Char/IsWhiteSpace (char x))))))))))))
(defn- init-cap-writer
"Returns a proxy that wraps writer, capitalizing the first word"
[^System.IO.TextWriter writer] ;;; java.io.Writer
(let [capped (ref false)]
(proxy [System.IO.TextWriter] []
(Close [] (.Close writer))
(Flush [] (.Flush writer))
(Write ([^chars cbuf off len] (let [off (int off) len (int len)] ;;; remove ^Integer hints on off, len
(.Write writer cbuf off len)) )
([x]
(condp = (class x)
String
(let [s (.ToLower ^String x)]
(if (not @capped)
(let [m (re-matcher #"\S" s)
match (re-find m)
offset (and match (.start m))] ;;; start
(if offset
(do (.Write writer
(str (subs s 0 offset)
(Char/ToUpper ^Char (char (nth s offset))) ;; added (char ... )
(.ToLower ^String (subs s (inc offset)))))
(dosync (ref-set capped true)))
(.Write writer s)))
(.Write writer (.ToLower s))))
Int32
(let [c ^Char (char x)]
(if (and (not @capped) (Char/IsLetter c))
(do
(dosync (ref-set capped true))
(.Write writer (int (Char/ToUpper c))))
(.Write writer (int (Char/ToLower c)))))))))))
(defn- modify-case [make-writer params navigator offsets]
(let [clause (first (:clauses params))]
(binding [*out* (make-writer *out*)]
(execute-sub-format clause navigator (:base-args params)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; If necessary, wrap the writer in a PrettyWriter object
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn get-pretty-writer
"Returns the java.io.Writer passed in wrapped in a pretty writer proxy, unless it's
already a pretty writer. Generally, it is unnecessary to call this function, since pprint,
write, and cl-format all call it if they need to. However if you want the state to be
preserved across calls, you will want to wrap them with this.
For example, when you want to generate column-aware output with multiple calls to cl-format,
do it like in this example:
(defn print-table [aseq column-width]
(binding [*out* (get-pretty-writer *out*)]
(doseq [row aseq]
(doseq [col row]
(cl-format true \"~4D~7,vT\" col column-width))
(prn))))
Now when you run:
user> (print-table (map #(vector % (* % %) (* % % %)) (range 1 11)) 8)
It prints a table of squares and cubes for the numbers from 1 to 10:
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000"
{:added "1.2"}
[writer]
(if (pretty-writer? writer)
writer
(pretty-writer writer *print-right-margin* *print-miser-width*)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for column-aware operations ~&, ~T
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn fresh-line
"Make a newline if *out* is not already at the beginning of the line. If *out* is
not a pretty writer (which keeps track of columns), this function always outputs a newline."
{:added "1.2"}
[]
(if (instance? clojure.lang.IDeref *out*)
(if (not (= 0 (get-column (:base @@*out*))))
(prn))
(prn)))
(defn- absolute-tabulation [params navigator offsets]
(let [colnum (:colnum params)
colinc (:colinc params)
current (get-column (:base @@*out*))
space-count (cond
(< current colnum) (- colnum current)
(= colinc 0) 0
:else (- colinc (rem (- current colnum) colinc)))]
(print (apply str (repeat space-count \space))))
navigator)
(defn- relative-tabulation [params navigator offsets]
(let [colrel (:colnum params)
colinc (:colinc params)
start-col (+ colrel (get-column (:base @@*out*)))
offset (if (pos? colinc) (rem start-col colinc) 0)
space-count (+ colrel (if (= 0 offset) 0 (- colinc offset)))]
(print (apply str (repeat space-count \space))))
navigator)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Support for accessing the pretty printer from a format
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; TODO: support ~@; per-line-prefix separator
;; TODO: get the whole format wrapped so we can start the lb at any column
(defn- format-logical-block [params navigator offsets]
(let [clauses (:clauses params)
clause-count (count clauses)
prefix (cond
(> clause-count 1) (:string (:params (first (first clauses))))
(:colon params) "(")
body (nth clauses (if (> clause-count 1) 1 0))
suffix (cond
(> clause-count 2) (:string (:params (first (nth clauses 2))))
(:colon params) ")")
[arg navigator] (next-arg navigator)]
(pprint-logical-block :prefix prefix :suffix suffix
(execute-sub-format
body
(init-navigator arg)
(:base-args params)))
navigator))
(defn- set-indent [params navigator offsets]
(let [relative-to (if (:colon params) :current :block)]
(pprint-indent relative-to (:n params))
navigator))
;;; TODO: support ~:T section options for ~T
(defn- conditional-newline [params navigator offsets]
(let [kind (if (:colon params)
(if (:at params) :mandatory :fill)
(if (:at params) :miser :linear))]
(pprint-newline kind)
navigator))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The table of directives we support, each with its params,
;;; properties, and the compilation function
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; We start with a couple of helpers
(defn- process-directive-table-element [ [ char params flags bracket-info & generator-fn ] ]
[char,
{:directive char,
:params `(array-map ~@params),
:flags flags,
:bracket-info bracket-info,
:generator-fn (concat '(fn [ params offset]) generator-fn) }])
(defmacro ^{:private true}
defdirectives
[ & directives ]
`(def ^{:private true}
directive-table (hash-map ~@(mapcat process-directive-table-element directives))))
(defdirectives
(\A
[ :mincol [0 Int32] :colinc [1 Int32] :minpad [0 Int32] :padchar [\space Char] ]
#{ :at :colon :both} {}
#(format-ascii print-str %1 %2 %3))
(\S
[ :mincol [0 Int32] :colinc [1 Int32] :minpad [0 Int32] :padchar [\space Char] ]
#{ :at :colon :both} {}
#(format-ascii pr-str %1 %2 %3))
(\D
[ :mincol [0 Int32] :padchar [\space Char] :commachar [\, Char]
:commainterval [ 3 Int32]]
#{ :at :colon :both } {}
#(format-integer 10 %1 %2 %3))
(\B
[ :mincol [0 Int32] :padchar [\space Char] :commachar [\, Char]
:commainterval [ 3 Int32]]
#{ :at :colon :both } {}
#(format-integer 2 %1 %2 %3))
(\O
[ :mincol [0 Int32] :padchar [\space Char] :commachar [\, Char]
:commainterval [ 3 Int32]]
#{ :at :colon :both } {}
#(format-integer 8 %1 %2 %3))
(\X
[ :mincol [0 Int32] :padchar [\space Char] :commachar [\, Char]
:commainterval [ 3 Int32]]
#{ :at :colon :both } {}
#(format-integer 16 %1 %2 %3))
(\R
[:base [nil Int32] :mincol [0 Int32] :padchar [\space Char] :commachar [\, Char]
:commainterval [ 3 Int32]]
#{ :at :colon :both } {}
(do
(cond ; ~R is overloaded with bizareness
(first (:base params)) #(format-integer (:base %1) %1 %2 %3)
(and (:at params) (:colon params)) #(format-old-roman %1 %2 %3)
(:at params) #(format-new-roman %1 %2 %3)
(:colon params) #(format-ordinal-english %1 %2 %3)
true #(format-cardinal-english %1 %2 %3))))
(\P
[ ]
#{ :at :colon :both } {}
(fn [params navigator offsets]
(let [navigator (if (:colon params) (relative-reposition navigator -1) navigator)
strs (if (:at params) ["y" "ies"] ["" "s"])
[arg navigator] (next-arg navigator)]
(print (if (= arg 1) (first strs) (second strs)))
navigator)))
(\C
[:char-format [nil Char]]
#{ :at :colon :both } {}
(cond
(:colon params) pretty-character
(:at params) readable-character
:else plain-character))
(\F
[ :w [nil Int32] :d [nil Int32] :k [0 Int32] :overflowchar [nil Char]
:padchar [\space Char] ]
#{ :at } {}
fixed-float)
(\E
[ :w [nil Int32] :d [nil Int32] :e [nil Int32] :k [1 Int32]
:overflowchar [nil Char] :padchar [\space Char]
:exponentchar [nil Char] ]
#{ :at } {}
exponential-float)
(\G
[ :w [nil Int32] :d [nil Int32] :e [nil Int32] :k [1 Int32]
:overflowchar [nil Char] :padchar [\space Char]
:exponentchar [nil Char] ]
#{ :at } {}
general-float)
(\$
[ :d [2 Int32] :n [1 Int32] :w [0 Int32] :padchar [\space Char]]
#{ :at :colon :both} {}
dollar-float)
(\%
[ :count [1 Int32] ]
#{ } {}
(fn [params arg-navigator offsets]
(dotimes [i (:count params)]
(prn))
arg-navigator))
(\&
[ :count [1 Int32] ]
#{ :pretty } {}
(fn [params arg-navigator offsets]
(let [cnt (:count params)]
(if (pos? cnt) (fresh-line))
(dotimes [i (dec cnt)]
(prn)))
arg-navigator))
(\|
[ :count [1 Int32] ]
#{ } {}
(fn [params arg-navigator offsets]
(dotimes [i (:count params)]
(print \formfeed))
arg-navigator))
(\~
[ :n [1 Int32] ]
#{ } {}
(fn [params arg-navigator offsets]
(let [n (:n params)]
(print (apply str (repeat n \~)))
arg-navigator)))
(\newline ;; Whitespace supression is handled in the compilation loop
[ ]
#{:colon :at} {}
(fn [params arg-navigator offsets]
(if (:at params)
(prn))
arg-navigator))
(\T
[ :colnum [1 Int32] :colinc [1 Int32] ]
#{ :at :pretty } {}
(if (:at params)
#(relative-tabulation %1 %2 %3)
#(absolute-tabulation %1 %2 %3)))
(\*
[ :n [1 Int32] ]
#{ :colon :at } {}
(fn [params navigator offsets]
(let [n (:n params)]
(if (:at params)
(absolute-reposition navigator n)
(relative-reposition navigator (if (:colon params) (- n) n)))
)))
(\?
[ ]
#{ :at } {}
(if (:at params)
(fn [params navigator offsets] ; args from main arg list
(let [[subformat navigator] (get-format-arg navigator)]
(execute-sub-format subformat navigator (:base-args params))))
(fn [params navigator offsets] ; args from sub-list
(let [[subformat navigator] (get-format-arg navigator)
[subargs navigator] (next-arg navigator)
sub-navigator (init-navigator subargs)]
(execute-sub-format subformat sub-navigator (:base-args params))
navigator))))
(\(
[ ]
#{ :colon :at :both} { :right \), :allows-separator nil, :else nil }
(let [mod-case-writer (cond
(and (:at params) (:colon params))
upcase-writer
(:colon params)
capitalize-word-writer
(:at params)
init-cap-writer
:else
downcase-writer)]
#(modify-case mod-case-writer %1 %2 %3)))
(\) [] #{} {} nil)
(\[
[ :selector [nil Int32] ]
#{ :colon :at } { :right \], :allows-separator true, :else :last }
(cond
(:colon params)
boolean-conditional
(:at params)
check-arg-conditional
true
choice-conditional))
(\; [:min-remaining [nil Int32] :max-columns [nil Int32]]
#{ :colon } { :separator true } nil)
(\] [] #{} {} nil)
(\{
[ :max-iterations [nil Int32] ]
#{ :colon :at :both} { :right \}, :allows-separator false }
(cond
(and (:at params) (:colon params))
iterate-main-sublists
(:colon params)
iterate-list-of-sublists
(:at params)
iterate-main-list
true
iterate-sublist))
(\} [] #{:colon} {} nil)
(\<
[:mincol [0 Int32] :colinc [1 Int32] :minpad [0 Int32] :padchar [\space Char]]
#{:colon :at :both :pretty} { :right \>, :allows-separator true, :else :first }
logical-block-or-justify)
(\> [] #{:colon} {} nil)
;; TODO: detect errors in cases where colon not allowed
(\^ [:arg1 [nil Int32] :arg2 [nil Int32] :arg3 [nil Int32]]
#{:colon} {}
(fn [params navigator offsets]
(let [arg1 (:arg1 params)
arg2 (:arg2 params)
arg3 (:arg3 params)
exit (if (:colon params) :colon-up-arrow :up-arrow)]
(cond
(and arg1 arg2 arg3)
(if (<= arg1 arg2 arg3) [exit navigator] navigator)
(and arg1 arg2)
(if (= arg1 arg2) [exit navigator] navigator)
arg1
(if (= arg1 0) [exit navigator] navigator)
true ; TODO: handle looking up the arglist stack for info
(if (if (:colon params)
(empty? (:rest (:base-args params)))
(empty? (:rest navigator)))
[exit navigator] navigator)))))
(\W
[]
#{:at :colon :both :pretty} {}
(if (or (:at params) (:colon params))
(let [bindings (concat
(if (:at params) [:level nil :length nil] [])
(if (:colon params) [:pretty true] []))]
(fn [params navigator offsets]
(let [[arg navigator] (next-arg navigator)]
(if (apply write arg bindings)
[:up-arrow navigator]
navigator))))
(fn [params navigator offsets]
(let [[arg navigator] (next-arg navigator)]
(if (write-out arg)
[:up-arrow navigator]
navigator)))))
(\_
[]
#{:at :colon :both} {}
conditional-newline)
(\I
[:n [0 Int32]]
#{:colon} {}
set-indent)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Code to manage the parameters and flags associated with each
;;; directive in the format string.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^{:private true}
param-pattern #"^([vV]|#|('.)|([+-]?\d+)|(?=,))")
(def ^{:private true}
special-params #{ :parameter-from-args :remaining-arg-count })
(defn- extract-param [[s offset saw-comma]]
(let [m (re-matcher param-pattern s)
param (re-find m)]
(if param
(let [token-str (first (re-groups m))
remainder (subs s (.end m)) ;;; end
new-offset (+ offset (.end m))]
(if (not (= \, (nth remainder 0)))
[ [token-str offset] [remainder new-offset false]]
[ [token-str offset] [(subs remainder 1) (inc new-offset) true]]))
(if saw-comma
(format-error "Badly formed parameters in format directive" offset)
[ nil [s offset]]))))
(defn- extract-params [s offset]
(consume extract-param [s offset false]))
(defn- translate-param
"Translate the string representation of a param to the internalized
representation"
[[^String p offset]]
[(cond
(= (.Length p) 0) nil
(and (= (.Length p) 1) (contains? #{\v \V} (nth p 0))) :parameter-from-args ;;; length
(and (= (.Length p) 1) (= \# (nth p 0))) :remaining-arg-count
(and (= (.Length p) 2) (= \' (nth p 0))) (nth p 1)
true (Int32/Parse p)) ;;; (new Integer p)
offset])
(def ^{:private true}
flag-defs { \: :colon, \@ :at })
(defn- extract-flags [s offset]
(consume
(fn [[s offset flags]]
(if (empty? s)
[nil [s offset flags]]
(let [flag (get flag-defs (first s))]
(if flag
(if (contains? flags flag)
(format-error
(str "Flag \"" (first s) "\" appears more than once in a directive")
offset)
[true [(subs s 1) (inc offset) (assoc flags flag [true offset])]])
[nil [s offset flags]]))))
[s offset {}]))
(defn- check-flags [def flags]
(let [allowed (:flags def)]
(if (and (not (:at allowed)) (:at flags))
(format-error (str "\"@\" is an illegal flag for format directive \"" (:directive def) "\"")
(nth (:at flags) 1)))
(if (and (not (:colon allowed)) (:colon flags))
(format-error (str "\":\" is an illegal flag for format directive \"" (:directive def) "\"")
(nth (:colon flags) 1)))
(if (and (not (:both allowed)) (:at flags) (:colon flags))
(format-error (str "Cannot combine \"@\" and \":\" flags for format directive \""
(:directive def) "\"")
(min (nth (:colon flags) 1) (nth (:at flags) 1))))))
(defn- map-params
"Takes a directive definition and the list of actual parameters and
a map of flags and returns a map of the parameters and flags with defaults
filled in. We check to make sure that there are the right types and number
of parameters as well."
[def params flags offset]
(check-flags def flags)
(if (> (count params) (count (:params def)))
(format-error
(cl-format
nil
"Too many parameters for directive \"~C\": ~D~:* ~[were~;was~:;were~] specified but only ~D~:* ~[are~;is~:;are~] allowed"
(:directive def) (count params) (count (:params def)))
(second (first params))))
(doall
(map #(let [val (first %1)]
(if (not (or (nil? val) (contains? special-params val)
(instance? (second (second %2)) val)))
(format-error (str "Parameter " (name (first %2))
" has bad type in directive \"" (:directive def) "\": "
(class val))
(second %1))) )
params (:params def)))
(merge ; create the result map
(into (array-map) ; start with the default values, make sure the order is right
(reverse (for [[name [default]] (:params def)] [name [default offset]])))
(reduce #(apply assoc %1 %2) {} (filter #(first (nth % 1)) (zipmap (keys (:params def)) params))) ; add the specified parameters, filtering out nils
flags)) ; and finally add the flags
(defn- compile-directive [s offset]
(let [[raw-params [rest offset]] (extract-params s offset)
[_ [rest offset flags]] (extract-flags rest offset)
directive (first rest)
def (get directive-table (Char/ToUpper ^Char directive)) ;;; Character/toUpperCase
params (if def (map-params def (map translate-param raw-params) flags offset))]
(if (not directive)
(format-error "Format string ended in the middle of a directive" offset))
(if (not def)
(format-error (str "Directive \"" directive "\" is undefined") offset))
[(struct compiled-directive ((:generator-fn def) params offset) def params offset)
(let [remainder (subs rest 1)
offset (inc offset)
trim? (and (= \newline (:directive def))
(not (:colon params)))
trim-count (if trim? (prefix-count remainder [\space \tab]) 0)
remainder (subs remainder trim-count)
offset (+ offset trim-count)]
[remainder offset])]))
(defn- compile-raw-string [s offset]
(struct compiled-directive (fn [_ a _] (print s) a) nil { :string s } offset))
(defn- right-bracket [this] (:right (:bracket-info (:def this))))
(defn- separator? [this] (:separator (:bracket-info (:def this))))
(defn- else-separator? [this]
(and (:separator (:bracket-info (:def this)))
(:colon (:params this))))
(declare collect-clauses)
(defn- process-bracket [this remainder]
(let [[subex remainder] (collect-clauses (:bracket-info (:def this))
(:offset this) remainder)]
[(struct compiled-directive
(:func this) (:def this)
(merge (:params this) (tuple-map subex (:offset this)))
(:offset this))
remainder]))
(defn- process-clause [bracket-info offset remainder]
(consume
(fn [remainder]
(if (empty? remainder)
(format-error "No closing bracket found." offset)
(let [this (first remainder)
remainder (next remainder)]
(cond
(right-bracket this)
(process-bracket this remainder)
(= (:right bracket-info) (:directive (:def this)))
[ nil [:right-bracket (:params this) nil remainder]]
(else-separator? this)
[nil [:else nil (:params this) remainder]]
(separator? this)
[nil [:separator nil nil remainder]] ;; TODO: check to make sure that there are no params on ~;
true
[this remainder]))))
remainder))
(defn- collect-clauses [bracket-info offset remainder]
(second
(consume
(fn [[clause-map saw-else remainder]]
(let [[clause [type right-params else-params remainder]]
(process-clause bracket-info offset remainder)]
(cond
(= type :right-bracket)
[nil [(merge-with concat clause-map
{(if saw-else :else :clauses) [clause]
:right-params right-params})
remainder]]
(= type :else)
(cond
(:else clause-map)
(format-error "Two else clauses (\"~:;\") inside bracket construction." offset)
(not (:else bracket-info))
(format-error "An else clause (\"~:;\") is in a bracket type that doesn't support it."
offset)
(and (= :first (:else bracket-info)) (seq (:clauses clause-map)))
(format-error
"The else clause (\"~:;\") is only allowed in the first position for this directive."
offset)
true ; if the ~:; is in the last position, the else clause
; is next, this was a regular clause
(if (= :first (:else bracket-info))
[true [(merge-with concat clause-map { :else [clause] :else-params else-params})
false remainder]]
[true [(merge-with concat clause-map { :clauses [clause] })
true remainder]]))
(= type :separator)
(cond
saw-else
(format-error "A plain clause (with \"~;\") follows an else clause (\"~:;\") inside bracket construction." offset)
(not (:allows-separator bracket-info))
(format-error "A separator (\"~;\") is in a bracket type that doesn't support it."
offset)
true
[true [(merge-with concat clause-map { :clauses [clause] })
false remainder]]))))
[{ :clauses [] } false remainder])))
(defn- process-nesting
"Take a linearly compiled format and process the bracket directives to give it
the appropriate tree structure"
[format]
(first
(consume
(fn [remainder]
(let [this (first remainder)
remainder (next remainder)
bracket (:bracket-info (:def this))]
(if (:right bracket)
(process-bracket this remainder)
[this remainder])))
format)))
(defn- compile-format
"Compiles format-str into a compiled format which can be used as an argument
to cl-format just like a plain format string. Use this function for improved
performance when you're using the same format string repeatedly"
[ format-str ]
; (prlabel compiling format-str)
(binding [*format-str* format-str]
(process-nesting
(first
(consume
(fn [[^String s offset]]
(if (empty? s)
[nil s]
(let [tilde (.IndexOf s \~)] ;;; indexOf (int \~)
(cond
(neg? tilde) [(compile-raw-string s offset) ["" (+ offset (.Length s))]] ;;; length
(zero? tilde) (compile-directive (subs s 1) (inc offset))
true
[(compile-raw-string (subs s 0 tilde) offset) [(subs s tilde) (+ tilde offset)]]))))
[format-str 0])))))
(defn- needs-pretty
"determine whether a given compiled format has any directives that depend on the
column number or pretty printing"
[format]
(loop [format format]
(if (empty? format)
false
(if (or (:pretty (:flags (:def (first format))))
(some needs-pretty (first (:clauses (:params (first format)))))
(some needs-pretty (first (:else (:params (first format))))))
true
(recur (next format))))))
(defn- execute-format
"Executes the format with the arguments."
{:skip-wiki true}
([stream format args]
(let [^System.IO.TextWriter real-stream (cond ;;; java.io.Writer
(not stream) (System.IO.StringWriter.) ;;; java.io.StringWriter
(true? stream) *out*
:else stream)
^System.IO.TextWriter wrapped-stream (if (and (needs-pretty format) ;;; java.io.Writer
(not (pretty-writer? real-stream)))
(get-pretty-writer real-stream)
real-stream)]
(binding [*out* wrapped-stream]
(try
(execute-format format args)
(finally
(if-not (identical? real-stream wrapped-stream)
(.Flush wrapped-stream)))) ;;; flush
(if (not stream) (.ToString real-stream))))) ;;; toString
([format args]
(map-passing-context
(fn [element context]
(if (abort? context)
[nil context]
(let [[params args] (realize-parameter-list
(:params element) context)
[params offsets] (unzip-map params)
params (assoc params :base-args args)]
[nil (apply (:func element) [params args offsets])])))
args
format)
nil))
;;; This is a bad idea, but it prevents us from leaking private symbols
;;; This should all be replaced by really compiled formats anyway.
(def ^{:private true} cached-compile (memoize compile-format))
(defmacro formatter
"Makes a function which can directly run format-in. The function is
fn [stream & args] ... and returns nil unless the stream is nil (meaning
output to a string) in which case it returns the resulting string.
format-in can be either a control string or a previously compiled format."
{:added "1.2"}
[format-in]
`(let [format-in# ~format-in
my-c-c# (var-get (get (ns-interns (the-ns 'clojure.pprint))
'~'cached-compile))
my-e-f# (var-get (get (ns-interns (the-ns 'clojure.pprint))
'~'execute-format))
my-i-n# (var-get (get (ns-interns (the-ns 'clojure.pprint))
'~'init-navigator))
cf# (if (string? format-in#) (my-c-c# format-in#) format-in#)]
(fn [stream# & args#]
(let [navigator# (my-i-n# args#)]
(my-e-f# stream# cf# navigator#)))))
(defmacro formatter-out
"Makes a function which can directly run format-in. The function is
fn [& args] ... and returns nil. This version of the formatter macro is
designed to be used with *out* set to an appropriate Writer. In particular,
this is meant to be used as part of a pretty printer dispatch method.
format-in can be either a control string or a previously compiled format."
{:added "1.2"}
[format-in]
`(let [format-in# ~format-in
cf# (if (string? format-in#) (#'clojure.pprint/cached-compile format-in#) format-in#)]
(fn [& args#]
(let [navigator# (#'clojure.pprint/init-navigator args#)]
(#'clojure.pprint/execute-format cf# navigator#))))) |
[
{
"context": "--------------------------------\n;; Copyright 2017 Greg Haskins\n;;\n;; SPDX-License-Identifier: Apache-2.0\n;;-----",
"end": 110,
"score": 0.9998250007629395,
"start": 98,
"tag": "NAME",
"value": "Greg Haskins"
}
] | examples/example02/client/cljs/src/fabric_sdk/macros.clj | simonmulser/fabric-chaintool | 138 | ;;-----------------------------------------------------------------------------
;; Copyright 2017 Greg Haskins
;;
;; SPDX-License-Identifier: Apache-2.0
;;-----------------------------------------------------------------------------
(ns fabric-sdk.macros
(:require [promesa.core :as promesa]))
(defmacro wrapped-resolve [expr exec result]
`(do
(comment (println "expr:" ~expr "resolved with" ~result))
(~exec ~result)))
(defmacro wrapped-reject [expr exec result]
`(do
(comment (println "expr:" ~expr "rejected with" ~result))
(~exec ~result)))
(defmacro pwrap
;; Implements an interop wrapper between JS promise and promesa
[expr]
`(promesa/promise
(fn [resolve# reject#]
(-> ~expr
(.then #(wrapped-resolve '~expr resolve# %)
#(wrapped-reject '~expr reject# %))))))
| 33100 | ;;-----------------------------------------------------------------------------
;; Copyright 2017 <NAME>
;;
;; SPDX-License-Identifier: Apache-2.0
;;-----------------------------------------------------------------------------
(ns fabric-sdk.macros
(:require [promesa.core :as promesa]))
(defmacro wrapped-resolve [expr exec result]
`(do
(comment (println "expr:" ~expr "resolved with" ~result))
(~exec ~result)))
(defmacro wrapped-reject [expr exec result]
`(do
(comment (println "expr:" ~expr "rejected with" ~result))
(~exec ~result)))
(defmacro pwrap
;; Implements an interop wrapper between JS promise and promesa
[expr]
`(promesa/promise
(fn [resolve# reject#]
(-> ~expr
(.then #(wrapped-resolve '~expr resolve# %)
#(wrapped-reject '~expr reject# %))))))
| true | ;;-----------------------------------------------------------------------------
;; Copyright 2017 PI:NAME:<NAME>END_PI
;;
;; SPDX-License-Identifier: Apache-2.0
;;-----------------------------------------------------------------------------
(ns fabric-sdk.macros
(:require [promesa.core :as promesa]))
(defmacro wrapped-resolve [expr exec result]
`(do
(comment (println "expr:" ~expr "resolved with" ~result))
(~exec ~result)))
(defmacro wrapped-reject [expr exec result]
`(do
(comment (println "expr:" ~expr "rejected with" ~result))
(~exec ~result)))
(defmacro pwrap
;; Implements an interop wrapper between JS promise and promesa
[expr]
`(promesa/promise
(fn [resolve# reject#]
(-> ~expr
(.then #(wrapped-resolve '~expr resolve# %)
#(wrapped-reject '~expr reject# %))))))
|
[
{
"context": "the name will be tried. For example, if a key is :foo.bar/baz, then the\n function will attempt to load ",
"end": 5745,
"score": 0.6646552681922913,
"start": 5738,
"tag": "KEY",
"value": "foo.bar"
}
] | src/integrant/core.cljc | zilti/integrant | 0 | (ns integrant.core
(:refer-clojure :exclude [ref read-string run!])
(:require #?(:clj [clojure.edn :as edn])
[clojure.walk :as walk]
[clojure.set :as set]
[clojure.spec.alpha :as s]
[clojure.string :as str]
[weavejester.dependency :as dep]))
(defprotocol RefLike
(ref-key [r] "Return the key of the reference."))
(defrecord Ref [key] RefLike (ref-key [_] key))
(defrecord RefSet [key] RefLike (ref-key [_] key))
(defn- composite-key? [keys]
(and (vector? keys) (every? qualified-keyword? keys)))
(defn valid-config-key?
"Returns true if the key is a keyword or valid composite key."
[key]
(or (qualified-keyword? key) (composite-key? key)))
(defn ref
"Create a reference to a top-level key in a config map."
[key]
{:pre [(valid-config-key? key)]}
(->Ref key))
(defn refset
"Create a set of references to all matching top-level keys in a config map."
[key]
{:pre [(valid-config-key? key)]}
(->RefSet key))
(defn ref?
"Return true if its argument is a ref."
[x]
(instance? Ref x))
(defn refset?
"Return true if its argument is a refset."
[x]
(instance? RefSet x))
(defn reflike?
"Return true if its argument is a ref or a refset."
[x]
(satisfies? RefLike x))
(defn- depth-search [pred? coll]
(filter pred? (tree-seq coll? seq coll)))
(defonce
^{:doc "Return a unique keyword that is derived from an ordered collection of
keywords. The function will return the same keyword for the same collection."
:arglists '([kws])}
composite-keyword
(memoize
(fn [kws]
(let [parts (for [kw kws] (str (namespace kw) "." (name kw)))
prefix (str (str/join "+" parts) "_")
composite (keyword "integrant.composite" (str (gensym prefix)))]
(doseq [kw kws] (derive composite kw))
composite))))
(defn- normalize-key [k]
(if (vector? k) (composite-keyword k) k))
(defn- ambiguous-key-exception [config key matching-keys]
(ex-info (str "Ambiguous key: " key " Found multiple candidates: "
(str/join ", " matching-keys))
{:reason ::ambiguous-key
:config config
:key key
:matching-keys matching-keys}))
(defn derived-from?
"Return true if a key is derived from candidate keyword or vector of
keywords."
[key candidate]
(let [key (normalize-key key)]
(if (vector? candidate)
(not (not-any? #(isa? key %) candidate))
(isa? key candidate))))
(defn find-derived
"Return a seq of all entries in a map, m, where the key is derived from the
a candidate key, k. If there are no matching keys, nil is returned. The
candidate key may be a keyword, or vector of keywords."
[m k]
(seq (filter #(or (= (key %) k) (derived-from? (key %) k)) m)))
(defn find-derived-1
"Return the map entry in a map, m, where the key is derived from the keyword,
k. If there are no matching keys, nil is returned. If there is more than one
matching key, an ambiguous key exception is raised."
[m k]
(let [kvs (find-derived m k)]
(when (next kvs)
(throw (ambiguous-key-exception m k (map key kvs))))
(first kvs)))
(defn- find-derived-refs [config v include-refsets?]
(->> (depth-search (if include-refsets? reflike? ref?) v)
(map ref-key)
(mapcat #(map key (find-derived config %)))))
(defn dependency-graph
"Return a dependency graph of all the refs and refsets in a config. Resolves
derived dependencies. Takes the following options:
`:include-refsets?`
: whether to include refsets in the dependency graph (defaults to true)"
([config]
(dependency-graph config {}))
([config {:keys [include-refsets?] :or {include-refsets? true}}]
(letfn [(find-refs [v]
(find-derived-refs config v include-refsets?))]
(reduce-kv (fn [g k v] (reduce #(dep/depend %1 k %2) g (find-refs v)))
(dep/graph)
config))))
(defn key-comparator
"Create a key comparator from the dependency graph of a configuration map.
The comparator is deterministic; it will always result in the same key
order."
[graph]
(dep/topo-comparator #(compare (str %1) (str %2)) graph))
(defn- find-keys [config keys f]
(let [graph (dependency-graph config {:include-refsets? false})
keyset (set (mapcat #(map key (find-derived config %)) keys))]
(->> (f graph keyset)
(set/union keyset)
(sort (key-comparator (dependency-graph config))))))
(defn- dependent-keys [config keys]
(find-keys config keys dep/transitive-dependencies-set))
(defn- reverse-dependent-keys [config keys]
(reverse (find-keys config keys dep/transitive-dependents-set)))
#?(:clj
(def ^:private default-readers {'ig/ref ref, 'ig/refset refset}))
#?(:clj
(defn read-string
"Read a config from a string of edn. Refs may be denotied by tagging keywords
with #ig/ref."
([s]
(read-string {:eof nil} s))
([opts s]
(let [readers (merge default-readers (:readers opts {}))]
(edn/read-string (assoc opts :readers readers) s)))))
#?(:clj
(defn- keyword->namespaces [kw]
(if-let [ns (namespace kw)]
[(symbol ns)
(symbol (str ns "." (name kw)))])))
#?(:clj
(defn- key->namespaces [k]
(if (vector? k)
(mapcat keyword->namespaces k)
(keyword->namespaces k))))
#?(:clj
(defn- try-require [sym]
(try (do (require sym) sym)
(catch java.io.FileNotFoundException _))))
#?(:clj
(defn load-namespaces
"Attempt to load the namespaces referenced by the keys in a configuration.
If a key is namespaced, both the namespace and the namespace concatenated
with the name will be tried. For example, if a key is :foo.bar/baz, then the
function will attempt to load the namespaces foo.bar and foo.bar.baz. Upon
completion, a list of all loaded namespaces will be returned."
([config]
(load-namespaces config (keys config)))
([config keys]
(doall (->> (dependent-keys config keys)
(mapcat #(conj (ancestors %) %))
(mapcat key->namespaces)
(distinct)
(keep try-require))))))
(defn- missing-refs-exception [config refs]
(ex-info (str "Missing definitions for refs: " (str/join ", " refs))
{:reason ::missing-refs
:config config
:missing-refs refs}))
(defn- ambiguous-refs [config]
(->> (depth-search ref? config)
(map ref-key)
(filter #(next (find-derived config %)))))
(defn- missing-refs [config]
(->> (depth-search ref? config)
(map ref-key)
(remove #(find-derived config %))))
(defn- invalid-composite-keys [config]
(->> (keys config) (filter vector?) (remove composite-key?)))
(defn- invalid-composite-key-exception [config key]
(ex-info (str "Invalid composite key: " key ". Every keyword must be namespaced.")
{:reason ::invalid-composite-key
:config config
:key key}))
(defn- resolve-ref [config resolvef ref]
(let [[k v] (first (find-derived config (ref-key ref)))]
(resolvef k v)))
(defn- resolve-refset [config resolvef refset]
(set (for [[k v] (find-derived config (ref-key refset))]
(resolvef k v))))
(defn- expand-key [config resolvef value]
(walk/postwalk
#(cond
(ref? %) (resolve-ref config resolvef %)
(refset? %) (resolve-refset config resolvef %)
:else %)
value))
(defn- run-exception [system completed remaining f k v t]
(ex-info (str "Error on key " k " when running system")
{:reason ::run-threw-exception
:system system
:completed-keys (reverse completed)
:remaining-keys (rest remaining)
:function f
:key k
:value v}
t))
(defn- try-run-action [system completed remaining f k]
(let [v (system k)]
(try (f k v)
(catch #?(:clj Throwable :cljs :default) t
(throw (run-exception system completed remaining f k v t))))))
(defn- run-loop [system keys f]
(loop [completed (), remaining keys]
(when (seq remaining)
(let [k (first remaining)]
(try-run-action system completed remaining f k)
(recur (cons k completed) (rest remaining))))))
(defn- system-origin [system]
(-> system meta ::origin (select-keys (keys system))))
(defn run!
"Apply a side-effectful function f to each key value pair in a system map.
Keys are traversed in dependency order. The function should take two
arguments, a key and value."
[system keys f]
{:pre [(map? system) (some-> system meta ::origin)]}
(run-loop system (dependent-keys (system-origin system) keys) f))
(defn reverse-run!
"Apply a side-effectful function f to each key value pair in a system map.
Keys are traversed in reverse dependency order. The function should take two
arguments, a key and value."
[system keys f]
{:pre [(map? system) (some-> system meta ::origin)]}
(run-loop system (reverse-dependent-keys (system-origin system) keys) f))
(defn fold
"Reduce all the key value pairs in system map in dependency order, starting
from an initial value. The function should take three arguments: the
accumulator, the current key and the current value."
[system f val]
(let [graph (dependency-graph (system-origin system))]
(->> (keys system)
(sort (key-comparator graph))
(reduce #(f %1 %2 (system %2)) val))))
(defn- build-exception [system f k v t]
(ex-info (str "Error on key " k " when building system")
{:reason ::build-threw-exception
:system system
:function f
:key k
:value v}
t))
(defn- try-build-action [system f k v]
(try (f k v)
(catch #?(:clj Throwable :cljs :default) t
(throw (build-exception system f k v t)))))
(defn- build-key [f assertf resolvef system [k v]]
(let [v' (expand-key system resolvef v)]
(assertf system k v')
(-> system
(assoc k (try-build-action system f k v'))
(vary-meta assoc-in [::build k] v'))))
(defn build
"Apply a function f to each key value pair in a configuration map. Keys are
traversed in dependency order, and any references in the value expanded. The
function should take two arguments, a key and value, and return a new value.
An optional fourth argument, assertf, may be supplied to provide an assertion
check on the system, key and expanded value."
([config keys f]
(build config keys f (fn [_ _ _])))
([config keys f assertf]
(build config keys f assertf (fn [_ v] v)))
([config keys f assertf resolvef]
{:pre [(map? config)]}
(let [relevant-keys (dependent-keys config keys)
relevant-config (select-keys config relevant-keys)]
(when-let [invalid-key (first (invalid-composite-keys config))]
(throw (invalid-composite-key-exception config invalid-key)))
(when-let [ref (first (ambiguous-refs relevant-config))]
(throw (ambiguous-key-exception config ref (map key (find-derived config ref)))))
(when-let [refs (seq (missing-refs relevant-config))]
(throw (missing-refs-exception config refs)))
(reduce (partial build-key f assertf resolvef)
(with-meta {} {::origin config})
(map (fn [k] [k (config k)]) relevant-keys)))))
(defmulti resolve-key
"Return a value to substitute for a reference prior to initiation. By default
the value of the key is returned unaltered. This can be used to hide
information that is only necessary to halt or suspend the key."
{:arglists '([key value])}
(fn [key value] (normalize-key key)))
(defmethod resolve-key :default [_ v] v)
(defn expand
"Replace all refs with the values they correspond to."
[config]
(build config (keys config) (fn [_ v] v) (fn [_ _ _]) resolve-key))
(defmulti prep-key
"Prepare the configuration associated with a key for initiation. This is
generally used to add in default values and references. By default the
method returns the value unaltered."
{:arglists '([key value])}
(fn [key value] (normalize-key key)))
(defmethod prep-key :default [_ v] v)
(defmulti init-key
"Turn a config value associated with a key into a concrete implementation.
For example, a database URL might be turned into a database connection."
{:arglists '([key value])}
(fn [key value] (normalize-key key)))
(defmulti halt-key!
"Halt a running or suspended implementation associated with a key. This is
often used for stopping processes or cleaning up resources. For example, a
database connection might be closed. This multimethod must be idempotent.
The return value of this multimethod is discarded."
{:arglists '([key value])}
(fn [key value] (normalize-key key)))
(defmethod halt-key! :default [_ v])
(defmulti resume-key
"Turn a config value associated with a key into a concrete implementation,
but reuse resources (e.g. connections, running threads, etc) from an existing
implementation. By default this multimethod calls init-key and ignores the
additional argument."
{:arglists '([key value old-value old-impl])}
(fn [key value old-value old-impl] (normalize-key key)))
(defmethod resume-key :default [k v _ _]
(init-key k v))
(defmulti suspend-key!
"Suspend a running implementation associated with a key, so that it may be
eventually passed to resume-key. By default this multimethod calls halt-key!,
but it may be customized to do things like keep a server running, but buffer
incoming requests until the server is resumed."
{:arglists '([key value])}
(fn [key value] (normalize-key key)))
(defmethod suspend-key! :default [k v]
(halt-key! k v))
(defmulti pre-init-spec
"Return a spec for the supplied key that is used to check the associated
value before the key is initiated."
normalize-key)
(defmethod pre-init-spec :default [_] nil)
(defn- spec-exception [system k v spec ed]
(ex-info (str "Spec failed on key " k " when building system\n"
(with-out-str (s/explain-out ed)))
{:reason ::build-failed-spec
:system system
:key k
:value v
:spec spec
:explain ed}))
(defn- assert-pre-init-spec [system key value]
(when-let [spec (pre-init-spec key)]
(when-not (s/valid? spec value)
(throw (spec-exception system key value spec (s/explain-data spec value))))))
(defn prep
"Prepare a config map for initiation. The prep-key method is applied to each
entry in the map, and the values replaced with the return value. This is used
for adding default values and references to the configuration."
([config]
(prep config (keys config)))
([config keys]
{:pre [(map? config)]}
(let [keyset (set keys)]
(reduce-kv (fn [m k v] (assoc m k (if (keyset k) (prep-key k v) v))) {} config))))
(defn init
"Turn a config map into an system map. Keys are traversed in dependency
order, initiated via the init-key multimethod, then the refs associated with
the key are expanded."
([config]
(init config (keys config)))
([config keys]
{:pre [(map? config)]}
(build config keys init-key assert-pre-init-spec resolve-key)))
(defn halt!
"Halt a system map by applying halt-key! in reverse dependency order."
([system]
(halt! system (keys system)))
([system keys]
{:pre [(map? system) (some-> system meta ::origin)]}
(reverse-run! system keys halt-key!)))
(defn- missing-keys [system ks]
(remove (set ks) (keys system)))
(defn- halt-missing-keys! [config system keys]
(let [graph (-> system meta ::origin dependency-graph)
missing-keys (missing-keys system (dependent-keys config keys))]
(doseq [k (sort (key-comparator graph) missing-keys)]
(halt-key! k (system k)))))
(defn resume
"Turn a config map into a system map, reusing resources from an existing
system when it's possible to do so. Keys are traversed in dependency order,
resumed with the resume-key multimethod, then the refs associated with the
key are expanded."
([config system]
(resume config system (keys config)))
([config system keys]
{:pre [(map? config) (map? system) (some-> system meta ::origin)]}
(halt-missing-keys! config system keys)
(build config keys
(fn [k v]
(if (contains? system k)
(resume-key k v (-> system meta ::build (get k)) (system k))
(init-key k v)))
assert-pre-init-spec
resolve-key)))
(defn suspend!
"Suspend a system map by applying `suspend-key!` in reverse dependency order."
([system]
(suspend! system (keys system)))
([system keys]
{:pre [(map? system) (some-> system meta ::origin)]}
(reverse-run! system keys suspend-key!)))
| 60117 | (ns integrant.core
(:refer-clojure :exclude [ref read-string run!])
(:require #?(:clj [clojure.edn :as edn])
[clojure.walk :as walk]
[clojure.set :as set]
[clojure.spec.alpha :as s]
[clojure.string :as str]
[weavejester.dependency :as dep]))
(defprotocol RefLike
(ref-key [r] "Return the key of the reference."))
(defrecord Ref [key] RefLike (ref-key [_] key))
(defrecord RefSet [key] RefLike (ref-key [_] key))
(defn- composite-key? [keys]
(and (vector? keys) (every? qualified-keyword? keys)))
(defn valid-config-key?
"Returns true if the key is a keyword or valid composite key."
[key]
(or (qualified-keyword? key) (composite-key? key)))
(defn ref
"Create a reference to a top-level key in a config map."
[key]
{:pre [(valid-config-key? key)]}
(->Ref key))
(defn refset
"Create a set of references to all matching top-level keys in a config map."
[key]
{:pre [(valid-config-key? key)]}
(->RefSet key))
(defn ref?
"Return true if its argument is a ref."
[x]
(instance? Ref x))
(defn refset?
"Return true if its argument is a refset."
[x]
(instance? RefSet x))
(defn reflike?
"Return true if its argument is a ref or a refset."
[x]
(satisfies? RefLike x))
(defn- depth-search [pred? coll]
(filter pred? (tree-seq coll? seq coll)))
(defonce
^{:doc "Return a unique keyword that is derived from an ordered collection of
keywords. The function will return the same keyword for the same collection."
:arglists '([kws])}
composite-keyword
(memoize
(fn [kws]
(let [parts (for [kw kws] (str (namespace kw) "." (name kw)))
prefix (str (str/join "+" parts) "_")
composite (keyword "integrant.composite" (str (gensym prefix)))]
(doseq [kw kws] (derive composite kw))
composite))))
(defn- normalize-key [k]
(if (vector? k) (composite-keyword k) k))
(defn- ambiguous-key-exception [config key matching-keys]
(ex-info (str "Ambiguous key: " key " Found multiple candidates: "
(str/join ", " matching-keys))
{:reason ::ambiguous-key
:config config
:key key
:matching-keys matching-keys}))
(defn derived-from?
"Return true if a key is derived from candidate keyword or vector of
keywords."
[key candidate]
(let [key (normalize-key key)]
(if (vector? candidate)
(not (not-any? #(isa? key %) candidate))
(isa? key candidate))))
(defn find-derived
"Return a seq of all entries in a map, m, where the key is derived from the
a candidate key, k. If there are no matching keys, nil is returned. The
candidate key may be a keyword, or vector of keywords."
[m k]
(seq (filter #(or (= (key %) k) (derived-from? (key %) k)) m)))
(defn find-derived-1
"Return the map entry in a map, m, where the key is derived from the keyword,
k. If there are no matching keys, nil is returned. If there is more than one
matching key, an ambiguous key exception is raised."
[m k]
(let [kvs (find-derived m k)]
(when (next kvs)
(throw (ambiguous-key-exception m k (map key kvs))))
(first kvs)))
(defn- find-derived-refs [config v include-refsets?]
(->> (depth-search (if include-refsets? reflike? ref?) v)
(map ref-key)
(mapcat #(map key (find-derived config %)))))
(defn dependency-graph
"Return a dependency graph of all the refs and refsets in a config. Resolves
derived dependencies. Takes the following options:
`:include-refsets?`
: whether to include refsets in the dependency graph (defaults to true)"
([config]
(dependency-graph config {}))
([config {:keys [include-refsets?] :or {include-refsets? true}}]
(letfn [(find-refs [v]
(find-derived-refs config v include-refsets?))]
(reduce-kv (fn [g k v] (reduce #(dep/depend %1 k %2) g (find-refs v)))
(dep/graph)
config))))
(defn key-comparator
"Create a key comparator from the dependency graph of a configuration map.
The comparator is deterministic; it will always result in the same key
order."
[graph]
(dep/topo-comparator #(compare (str %1) (str %2)) graph))
(defn- find-keys [config keys f]
(let [graph (dependency-graph config {:include-refsets? false})
keyset (set (mapcat #(map key (find-derived config %)) keys))]
(->> (f graph keyset)
(set/union keyset)
(sort (key-comparator (dependency-graph config))))))
(defn- dependent-keys [config keys]
(find-keys config keys dep/transitive-dependencies-set))
(defn- reverse-dependent-keys [config keys]
(reverse (find-keys config keys dep/transitive-dependents-set)))
#?(:clj
(def ^:private default-readers {'ig/ref ref, 'ig/refset refset}))
#?(:clj
(defn read-string
"Read a config from a string of edn. Refs may be denotied by tagging keywords
with #ig/ref."
([s]
(read-string {:eof nil} s))
([opts s]
(let [readers (merge default-readers (:readers opts {}))]
(edn/read-string (assoc opts :readers readers) s)))))
#?(:clj
(defn- keyword->namespaces [kw]
(if-let [ns (namespace kw)]
[(symbol ns)
(symbol (str ns "." (name kw)))])))
#?(:clj
(defn- key->namespaces [k]
(if (vector? k)
(mapcat keyword->namespaces k)
(keyword->namespaces k))))
#?(:clj
(defn- try-require [sym]
(try (do (require sym) sym)
(catch java.io.FileNotFoundException _))))
#?(:clj
(defn load-namespaces
"Attempt to load the namespaces referenced by the keys in a configuration.
If a key is namespaced, both the namespace and the namespace concatenated
with the name will be tried. For example, if a key is :<KEY>/baz, then the
function will attempt to load the namespaces foo.bar and foo.bar.baz. Upon
completion, a list of all loaded namespaces will be returned."
([config]
(load-namespaces config (keys config)))
([config keys]
(doall (->> (dependent-keys config keys)
(mapcat #(conj (ancestors %) %))
(mapcat key->namespaces)
(distinct)
(keep try-require))))))
(defn- missing-refs-exception [config refs]
(ex-info (str "Missing definitions for refs: " (str/join ", " refs))
{:reason ::missing-refs
:config config
:missing-refs refs}))
(defn- ambiguous-refs [config]
(->> (depth-search ref? config)
(map ref-key)
(filter #(next (find-derived config %)))))
(defn- missing-refs [config]
(->> (depth-search ref? config)
(map ref-key)
(remove #(find-derived config %))))
(defn- invalid-composite-keys [config]
(->> (keys config) (filter vector?) (remove composite-key?)))
(defn- invalid-composite-key-exception [config key]
(ex-info (str "Invalid composite key: " key ". Every keyword must be namespaced.")
{:reason ::invalid-composite-key
:config config
:key key}))
(defn- resolve-ref [config resolvef ref]
(let [[k v] (first (find-derived config (ref-key ref)))]
(resolvef k v)))
(defn- resolve-refset [config resolvef refset]
(set (for [[k v] (find-derived config (ref-key refset))]
(resolvef k v))))
(defn- expand-key [config resolvef value]
(walk/postwalk
#(cond
(ref? %) (resolve-ref config resolvef %)
(refset? %) (resolve-refset config resolvef %)
:else %)
value))
(defn- run-exception [system completed remaining f k v t]
(ex-info (str "Error on key " k " when running system")
{:reason ::run-threw-exception
:system system
:completed-keys (reverse completed)
:remaining-keys (rest remaining)
:function f
:key k
:value v}
t))
(defn- try-run-action [system completed remaining f k]
(let [v (system k)]
(try (f k v)
(catch #?(:clj Throwable :cljs :default) t
(throw (run-exception system completed remaining f k v t))))))
(defn- run-loop [system keys f]
(loop [completed (), remaining keys]
(when (seq remaining)
(let [k (first remaining)]
(try-run-action system completed remaining f k)
(recur (cons k completed) (rest remaining))))))
(defn- system-origin [system]
(-> system meta ::origin (select-keys (keys system))))
(defn run!
"Apply a side-effectful function f to each key value pair in a system map.
Keys are traversed in dependency order. The function should take two
arguments, a key and value."
[system keys f]
{:pre [(map? system) (some-> system meta ::origin)]}
(run-loop system (dependent-keys (system-origin system) keys) f))
(defn reverse-run!
"Apply a side-effectful function f to each key value pair in a system map.
Keys are traversed in reverse dependency order. The function should take two
arguments, a key and value."
[system keys f]
{:pre [(map? system) (some-> system meta ::origin)]}
(run-loop system (reverse-dependent-keys (system-origin system) keys) f))
(defn fold
"Reduce all the key value pairs in system map in dependency order, starting
from an initial value. The function should take three arguments: the
accumulator, the current key and the current value."
[system f val]
(let [graph (dependency-graph (system-origin system))]
(->> (keys system)
(sort (key-comparator graph))
(reduce #(f %1 %2 (system %2)) val))))
(defn- build-exception [system f k v t]
(ex-info (str "Error on key " k " when building system")
{:reason ::build-threw-exception
:system system
:function f
:key k
:value v}
t))
(defn- try-build-action [system f k v]
(try (f k v)
(catch #?(:clj Throwable :cljs :default) t
(throw (build-exception system f k v t)))))
(defn- build-key [f assertf resolvef system [k v]]
(let [v' (expand-key system resolvef v)]
(assertf system k v')
(-> system
(assoc k (try-build-action system f k v'))
(vary-meta assoc-in [::build k] v'))))
(defn build
"Apply a function f to each key value pair in a configuration map. Keys are
traversed in dependency order, and any references in the value expanded. The
function should take two arguments, a key and value, and return a new value.
An optional fourth argument, assertf, may be supplied to provide an assertion
check on the system, key and expanded value."
([config keys f]
(build config keys f (fn [_ _ _])))
([config keys f assertf]
(build config keys f assertf (fn [_ v] v)))
([config keys f assertf resolvef]
{:pre [(map? config)]}
(let [relevant-keys (dependent-keys config keys)
relevant-config (select-keys config relevant-keys)]
(when-let [invalid-key (first (invalid-composite-keys config))]
(throw (invalid-composite-key-exception config invalid-key)))
(when-let [ref (first (ambiguous-refs relevant-config))]
(throw (ambiguous-key-exception config ref (map key (find-derived config ref)))))
(when-let [refs (seq (missing-refs relevant-config))]
(throw (missing-refs-exception config refs)))
(reduce (partial build-key f assertf resolvef)
(with-meta {} {::origin config})
(map (fn [k] [k (config k)]) relevant-keys)))))
(defmulti resolve-key
"Return a value to substitute for a reference prior to initiation. By default
the value of the key is returned unaltered. This can be used to hide
information that is only necessary to halt or suspend the key."
{:arglists '([key value])}
(fn [key value] (normalize-key key)))
(defmethod resolve-key :default [_ v] v)
(defn expand
"Replace all refs with the values they correspond to."
[config]
(build config (keys config) (fn [_ v] v) (fn [_ _ _]) resolve-key))
(defmulti prep-key
"Prepare the configuration associated with a key for initiation. This is
generally used to add in default values and references. By default the
method returns the value unaltered."
{:arglists '([key value])}
(fn [key value] (normalize-key key)))
(defmethod prep-key :default [_ v] v)
(defmulti init-key
"Turn a config value associated with a key into a concrete implementation.
For example, a database URL might be turned into a database connection."
{:arglists '([key value])}
(fn [key value] (normalize-key key)))
(defmulti halt-key!
"Halt a running or suspended implementation associated with a key. This is
often used for stopping processes or cleaning up resources. For example, a
database connection might be closed. This multimethod must be idempotent.
The return value of this multimethod is discarded."
{:arglists '([key value])}
(fn [key value] (normalize-key key)))
(defmethod halt-key! :default [_ v])
(defmulti resume-key
"Turn a config value associated with a key into a concrete implementation,
but reuse resources (e.g. connections, running threads, etc) from an existing
implementation. By default this multimethod calls init-key and ignores the
additional argument."
{:arglists '([key value old-value old-impl])}
(fn [key value old-value old-impl] (normalize-key key)))
(defmethod resume-key :default [k v _ _]
(init-key k v))
(defmulti suspend-key!
"Suspend a running implementation associated with a key, so that it may be
eventually passed to resume-key. By default this multimethod calls halt-key!,
but it may be customized to do things like keep a server running, but buffer
incoming requests until the server is resumed."
{:arglists '([key value])}
(fn [key value] (normalize-key key)))
(defmethod suspend-key! :default [k v]
(halt-key! k v))
(defmulti pre-init-spec
"Return a spec for the supplied key that is used to check the associated
value before the key is initiated."
normalize-key)
(defmethod pre-init-spec :default [_] nil)
(defn- spec-exception [system k v spec ed]
(ex-info (str "Spec failed on key " k " when building system\n"
(with-out-str (s/explain-out ed)))
{:reason ::build-failed-spec
:system system
:key k
:value v
:spec spec
:explain ed}))
(defn- assert-pre-init-spec [system key value]
(when-let [spec (pre-init-spec key)]
(when-not (s/valid? spec value)
(throw (spec-exception system key value spec (s/explain-data spec value))))))
(defn prep
"Prepare a config map for initiation. The prep-key method is applied to each
entry in the map, and the values replaced with the return value. This is used
for adding default values and references to the configuration."
([config]
(prep config (keys config)))
([config keys]
{:pre [(map? config)]}
(let [keyset (set keys)]
(reduce-kv (fn [m k v] (assoc m k (if (keyset k) (prep-key k v) v))) {} config))))
(defn init
"Turn a config map into an system map. Keys are traversed in dependency
order, initiated via the init-key multimethod, then the refs associated with
the key are expanded."
([config]
(init config (keys config)))
([config keys]
{:pre [(map? config)]}
(build config keys init-key assert-pre-init-spec resolve-key)))
(defn halt!
"Halt a system map by applying halt-key! in reverse dependency order."
([system]
(halt! system (keys system)))
([system keys]
{:pre [(map? system) (some-> system meta ::origin)]}
(reverse-run! system keys halt-key!)))
(defn- missing-keys [system ks]
(remove (set ks) (keys system)))
(defn- halt-missing-keys! [config system keys]
(let [graph (-> system meta ::origin dependency-graph)
missing-keys (missing-keys system (dependent-keys config keys))]
(doseq [k (sort (key-comparator graph) missing-keys)]
(halt-key! k (system k)))))
(defn resume
"Turn a config map into a system map, reusing resources from an existing
system when it's possible to do so. Keys are traversed in dependency order,
resumed with the resume-key multimethod, then the refs associated with the
key are expanded."
([config system]
(resume config system (keys config)))
([config system keys]
{:pre [(map? config) (map? system) (some-> system meta ::origin)]}
(halt-missing-keys! config system keys)
(build config keys
(fn [k v]
(if (contains? system k)
(resume-key k v (-> system meta ::build (get k)) (system k))
(init-key k v)))
assert-pre-init-spec
resolve-key)))
(defn suspend!
"Suspend a system map by applying `suspend-key!` in reverse dependency order."
([system]
(suspend! system (keys system)))
([system keys]
{:pre [(map? system) (some-> system meta ::origin)]}
(reverse-run! system keys suspend-key!)))
| true | (ns integrant.core
(:refer-clojure :exclude [ref read-string run!])
(:require #?(:clj [clojure.edn :as edn])
[clojure.walk :as walk]
[clojure.set :as set]
[clojure.spec.alpha :as s]
[clojure.string :as str]
[weavejester.dependency :as dep]))
(defprotocol RefLike
(ref-key [r] "Return the key of the reference."))
(defrecord Ref [key] RefLike (ref-key [_] key))
(defrecord RefSet [key] RefLike (ref-key [_] key))
(defn- composite-key? [keys]
(and (vector? keys) (every? qualified-keyword? keys)))
(defn valid-config-key?
"Returns true if the key is a keyword or valid composite key."
[key]
(or (qualified-keyword? key) (composite-key? key)))
(defn ref
"Create a reference to a top-level key in a config map."
[key]
{:pre [(valid-config-key? key)]}
(->Ref key))
(defn refset
"Create a set of references to all matching top-level keys in a config map."
[key]
{:pre [(valid-config-key? key)]}
(->RefSet key))
(defn ref?
"Return true if its argument is a ref."
[x]
(instance? Ref x))
(defn refset?
"Return true if its argument is a refset."
[x]
(instance? RefSet x))
(defn reflike?
"Return true if its argument is a ref or a refset."
[x]
(satisfies? RefLike x))
(defn- depth-search [pred? coll]
(filter pred? (tree-seq coll? seq coll)))
(defonce
^{:doc "Return a unique keyword that is derived from an ordered collection of
keywords. The function will return the same keyword for the same collection."
:arglists '([kws])}
composite-keyword
(memoize
(fn [kws]
(let [parts (for [kw kws] (str (namespace kw) "." (name kw)))
prefix (str (str/join "+" parts) "_")
composite (keyword "integrant.composite" (str (gensym prefix)))]
(doseq [kw kws] (derive composite kw))
composite))))
(defn- normalize-key [k]
(if (vector? k) (composite-keyword k) k))
(defn- ambiguous-key-exception [config key matching-keys]
(ex-info (str "Ambiguous key: " key " Found multiple candidates: "
(str/join ", " matching-keys))
{:reason ::ambiguous-key
:config config
:key key
:matching-keys matching-keys}))
(defn derived-from?
"Return true if a key is derived from candidate keyword or vector of
keywords."
[key candidate]
(let [key (normalize-key key)]
(if (vector? candidate)
(not (not-any? #(isa? key %) candidate))
(isa? key candidate))))
(defn find-derived
"Return a seq of all entries in a map, m, where the key is derived from the
a candidate key, k. If there are no matching keys, nil is returned. The
candidate key may be a keyword, or vector of keywords."
[m k]
(seq (filter #(or (= (key %) k) (derived-from? (key %) k)) m)))
(defn find-derived-1
"Return the map entry in a map, m, where the key is derived from the keyword,
k. If there are no matching keys, nil is returned. If there is more than one
matching key, an ambiguous key exception is raised."
[m k]
(let [kvs (find-derived m k)]
(when (next kvs)
(throw (ambiguous-key-exception m k (map key kvs))))
(first kvs)))
(defn- find-derived-refs [config v include-refsets?]
(->> (depth-search (if include-refsets? reflike? ref?) v)
(map ref-key)
(mapcat #(map key (find-derived config %)))))
(defn dependency-graph
"Return a dependency graph of all the refs and refsets in a config. Resolves
derived dependencies. Takes the following options:
`:include-refsets?`
: whether to include refsets in the dependency graph (defaults to true)"
([config]
(dependency-graph config {}))
([config {:keys [include-refsets?] :or {include-refsets? true}}]
(letfn [(find-refs [v]
(find-derived-refs config v include-refsets?))]
(reduce-kv (fn [g k v] (reduce #(dep/depend %1 k %2) g (find-refs v)))
(dep/graph)
config))))
(defn key-comparator
"Create a key comparator from the dependency graph of a configuration map.
The comparator is deterministic; it will always result in the same key
order."
[graph]
(dep/topo-comparator #(compare (str %1) (str %2)) graph))
(defn- find-keys [config keys f]
(let [graph (dependency-graph config {:include-refsets? false})
keyset (set (mapcat #(map key (find-derived config %)) keys))]
(->> (f graph keyset)
(set/union keyset)
(sort (key-comparator (dependency-graph config))))))
(defn- dependent-keys [config keys]
(find-keys config keys dep/transitive-dependencies-set))
(defn- reverse-dependent-keys [config keys]
(reverse (find-keys config keys dep/transitive-dependents-set)))
#?(:clj
(def ^:private default-readers {'ig/ref ref, 'ig/refset refset}))
#?(:clj
(defn read-string
"Read a config from a string of edn. Refs may be denotied by tagging keywords
with #ig/ref."
([s]
(read-string {:eof nil} s))
([opts s]
(let [readers (merge default-readers (:readers opts {}))]
(edn/read-string (assoc opts :readers readers) s)))))
#?(:clj
(defn- keyword->namespaces [kw]
(if-let [ns (namespace kw)]
[(symbol ns)
(symbol (str ns "." (name kw)))])))
#?(:clj
(defn- key->namespaces [k]
(if (vector? k)
(mapcat keyword->namespaces k)
(keyword->namespaces k))))
#?(:clj
(defn- try-require [sym]
(try (do (require sym) sym)
(catch java.io.FileNotFoundException _))))
#?(:clj
(defn load-namespaces
"Attempt to load the namespaces referenced by the keys in a configuration.
If a key is namespaced, both the namespace and the namespace concatenated
with the name will be tried. For example, if a key is :PI:KEY:<KEY>END_PI/baz, then the
function will attempt to load the namespaces foo.bar and foo.bar.baz. Upon
completion, a list of all loaded namespaces will be returned."
([config]
(load-namespaces config (keys config)))
([config keys]
(doall (->> (dependent-keys config keys)
(mapcat #(conj (ancestors %) %))
(mapcat key->namespaces)
(distinct)
(keep try-require))))))
(defn- missing-refs-exception [config refs]
(ex-info (str "Missing definitions for refs: " (str/join ", " refs))
{:reason ::missing-refs
:config config
:missing-refs refs}))
(defn- ambiguous-refs [config]
(->> (depth-search ref? config)
(map ref-key)
(filter #(next (find-derived config %)))))
(defn- missing-refs [config]
(->> (depth-search ref? config)
(map ref-key)
(remove #(find-derived config %))))
(defn- invalid-composite-keys [config]
(->> (keys config) (filter vector?) (remove composite-key?)))
(defn- invalid-composite-key-exception [config key]
(ex-info (str "Invalid composite key: " key ". Every keyword must be namespaced.")
{:reason ::invalid-composite-key
:config config
:key key}))
(defn- resolve-ref [config resolvef ref]
(let [[k v] (first (find-derived config (ref-key ref)))]
(resolvef k v)))
(defn- resolve-refset [config resolvef refset]
(set (for [[k v] (find-derived config (ref-key refset))]
(resolvef k v))))
(defn- expand-key [config resolvef value]
(walk/postwalk
#(cond
(ref? %) (resolve-ref config resolvef %)
(refset? %) (resolve-refset config resolvef %)
:else %)
value))
(defn- run-exception [system completed remaining f k v t]
(ex-info (str "Error on key " k " when running system")
{:reason ::run-threw-exception
:system system
:completed-keys (reverse completed)
:remaining-keys (rest remaining)
:function f
:key k
:value v}
t))
(defn- try-run-action [system completed remaining f k]
(let [v (system k)]
(try (f k v)
(catch #?(:clj Throwable :cljs :default) t
(throw (run-exception system completed remaining f k v t))))))
(defn- run-loop [system keys f]
(loop [completed (), remaining keys]
(when (seq remaining)
(let [k (first remaining)]
(try-run-action system completed remaining f k)
(recur (cons k completed) (rest remaining))))))
(defn- system-origin [system]
(-> system meta ::origin (select-keys (keys system))))
(defn run!
"Apply a side-effectful function f to each key value pair in a system map.
Keys are traversed in dependency order. The function should take two
arguments, a key and value."
[system keys f]
{:pre [(map? system) (some-> system meta ::origin)]}
(run-loop system (dependent-keys (system-origin system) keys) f))
(defn reverse-run!
"Apply a side-effectful function f to each key value pair in a system map.
Keys are traversed in reverse dependency order. The function should take two
arguments, a key and value."
[system keys f]
{:pre [(map? system) (some-> system meta ::origin)]}
(run-loop system (reverse-dependent-keys (system-origin system) keys) f))
(defn fold
"Reduce all the key value pairs in system map in dependency order, starting
from an initial value. The function should take three arguments: the
accumulator, the current key and the current value."
[system f val]
(let [graph (dependency-graph (system-origin system))]
(->> (keys system)
(sort (key-comparator graph))
(reduce #(f %1 %2 (system %2)) val))))
(defn- build-exception [system f k v t]
(ex-info (str "Error on key " k " when building system")
{:reason ::build-threw-exception
:system system
:function f
:key k
:value v}
t))
(defn- try-build-action [system f k v]
(try (f k v)
(catch #?(:clj Throwable :cljs :default) t
(throw (build-exception system f k v t)))))
(defn- build-key [f assertf resolvef system [k v]]
(let [v' (expand-key system resolvef v)]
(assertf system k v')
(-> system
(assoc k (try-build-action system f k v'))
(vary-meta assoc-in [::build k] v'))))
(defn build
"Apply a function f to each key value pair in a configuration map. Keys are
traversed in dependency order, and any references in the value expanded. The
function should take two arguments, a key and value, and return a new value.
An optional fourth argument, assertf, may be supplied to provide an assertion
check on the system, key and expanded value."
([config keys f]
(build config keys f (fn [_ _ _])))
([config keys f assertf]
(build config keys f assertf (fn [_ v] v)))
([config keys f assertf resolvef]
{:pre [(map? config)]}
(let [relevant-keys (dependent-keys config keys)
relevant-config (select-keys config relevant-keys)]
(when-let [invalid-key (first (invalid-composite-keys config))]
(throw (invalid-composite-key-exception config invalid-key)))
(when-let [ref (first (ambiguous-refs relevant-config))]
(throw (ambiguous-key-exception config ref (map key (find-derived config ref)))))
(when-let [refs (seq (missing-refs relevant-config))]
(throw (missing-refs-exception config refs)))
(reduce (partial build-key f assertf resolvef)
(with-meta {} {::origin config})
(map (fn [k] [k (config k)]) relevant-keys)))))
(defmulti resolve-key
"Return a value to substitute for a reference prior to initiation. By default
the value of the key is returned unaltered. This can be used to hide
information that is only necessary to halt or suspend the key."
{:arglists '([key value])}
(fn [key value] (normalize-key key)))
(defmethod resolve-key :default [_ v] v)
(defn expand
"Replace all refs with the values they correspond to."
[config]
(build config (keys config) (fn [_ v] v) (fn [_ _ _]) resolve-key))
(defmulti prep-key
"Prepare the configuration associated with a key for initiation. This is
generally used to add in default values and references. By default the
method returns the value unaltered."
{:arglists '([key value])}
(fn [key value] (normalize-key key)))
(defmethod prep-key :default [_ v] v)
(defmulti init-key
"Turn a config value associated with a key into a concrete implementation.
For example, a database URL might be turned into a database connection."
{:arglists '([key value])}
(fn [key value] (normalize-key key)))
(defmulti halt-key!
"Halt a running or suspended implementation associated with a key. This is
often used for stopping processes or cleaning up resources. For example, a
database connection might be closed. This multimethod must be idempotent.
The return value of this multimethod is discarded."
{:arglists '([key value])}
(fn [key value] (normalize-key key)))
(defmethod halt-key! :default [_ v])
(defmulti resume-key
"Turn a config value associated with a key into a concrete implementation,
but reuse resources (e.g. connections, running threads, etc) from an existing
implementation. By default this multimethod calls init-key and ignores the
additional argument."
{:arglists '([key value old-value old-impl])}
(fn [key value old-value old-impl] (normalize-key key)))
(defmethod resume-key :default [k v _ _]
(init-key k v))
(defmulti suspend-key!
"Suspend a running implementation associated with a key, so that it may be
eventually passed to resume-key. By default this multimethod calls halt-key!,
but it may be customized to do things like keep a server running, but buffer
incoming requests until the server is resumed."
{:arglists '([key value])}
(fn [key value] (normalize-key key)))
(defmethod suspend-key! :default [k v]
(halt-key! k v))
(defmulti pre-init-spec
"Return a spec for the supplied key that is used to check the associated
value before the key is initiated."
normalize-key)
(defmethod pre-init-spec :default [_] nil)
(defn- spec-exception [system k v spec ed]
(ex-info (str "Spec failed on key " k " when building system\n"
(with-out-str (s/explain-out ed)))
{:reason ::build-failed-spec
:system system
:key k
:value v
:spec spec
:explain ed}))
(defn- assert-pre-init-spec [system key value]
(when-let [spec (pre-init-spec key)]
(when-not (s/valid? spec value)
(throw (spec-exception system key value spec (s/explain-data spec value))))))
(defn prep
"Prepare a config map for initiation. The prep-key method is applied to each
entry in the map, and the values replaced with the return value. This is used
for adding default values and references to the configuration."
([config]
(prep config (keys config)))
([config keys]
{:pre [(map? config)]}
(let [keyset (set keys)]
(reduce-kv (fn [m k v] (assoc m k (if (keyset k) (prep-key k v) v))) {} config))))
(defn init
"Turn a config map into an system map. Keys are traversed in dependency
order, initiated via the init-key multimethod, then the refs associated with
the key are expanded."
([config]
(init config (keys config)))
([config keys]
{:pre [(map? config)]}
(build config keys init-key assert-pre-init-spec resolve-key)))
(defn halt!
"Halt a system map by applying halt-key! in reverse dependency order."
([system]
(halt! system (keys system)))
([system keys]
{:pre [(map? system) (some-> system meta ::origin)]}
(reverse-run! system keys halt-key!)))
(defn- missing-keys [system ks]
(remove (set ks) (keys system)))
(defn- halt-missing-keys! [config system keys]
(let [graph (-> system meta ::origin dependency-graph)
missing-keys (missing-keys system (dependent-keys config keys))]
(doseq [k (sort (key-comparator graph) missing-keys)]
(halt-key! k (system k)))))
(defn resume
"Turn a config map into a system map, reusing resources from an existing
system when it's possible to do so. Keys are traversed in dependency order,
resumed with the resume-key multimethod, then the refs associated with the
key are expanded."
([config system]
(resume config system (keys config)))
([config system keys]
{:pre [(map? config) (map? system) (some-> system meta ::origin)]}
(halt-missing-keys! config system keys)
(build config keys
(fn [k v]
(if (contains? system k)
(resume-key k v (-> system meta ::build (get k)) (system k))
(init-key k v)))
assert-pre-init-spec
resolve-key)))
(defn suspend!
"Suspend a system map by applying `suspend-key!` in reverse dependency order."
([system]
(suspend! system (keys system)))
([system keys]
{:pre [(map? system) (some-> system meta ::origin)]}
(reverse-run! system keys suspend-key!)))
|
[
{
"context": "ee-uuid-1\"\n :title \"Lasers Subtree\"\n :author \"Wes Chow\"\n :email \"wes@demo.com\"\n :short-description \"",
"end": 108,
"score": 0.9998639225959778,
"start": 100,
"tag": "NAME",
"value": "Wes Chow"
},
{
"context": "\"Lasers Subtree\"\n :author \"Wes Chow\"\n :email \"wes@demo.com\"\n :short-description \"Lasers! They are pretty c",
"end": 133,
"score": 0.9999215006828308,
"start": 121,
"tag": "EMAIL",
"value": "wes@demo.com"
},
{
"context": "g-description \"The theory dates back to a paper by Albert Einstein in 1917 which offered a derivation of Planck's",
"end": 534,
"score": 0.6635679006576538,
"start": 522,
"tag": "NAME",
"value": "Albert Einst"
},
{
"context": "d been accumulated by engineers to that time. When Goddard and von Braun began lighting up the heavens, some",
"end": 2644,
"score": 0.9995572566986084,
"start": 2637,
"tag": "NAME",
"value": "Goddard"
},
{
"context": "ulated by engineers to that time. When Goddard and von Braun began lighting up the heavens, something more tha",
"end": 2658,
"score": 0.9996800422668457,
"start": 2649,
"tag": "NAME",
"value": "von Braun"
},
{
"context": " to generate electricity via fusion; another Brit, James Tuck, working at Los Alamos in the United States, buil",
"end": 4038,
"score": 0.9990195631980896,
"start": 4028,
"tag": "NAME",
"value": "James Tuck"
},
{
"context": "526aa\"\n :title \"Flying Car Subtree\"\n :author \"Wes Chow\"\n :email \"wes@demo.com\"\n :description \"Flying",
"end": 5293,
"score": 0.9998286962509155,
"start": 5285,
"tag": "NAME",
"value": "Wes Chow"
},
{
"context": "ing Car Subtree\"\n :author \"Wes Chow\"\n :email \"wes@demo.com\"\n :description \"Flying cars! They're pretty coo",
"end": 5318,
"score": 0.9999292492866516,
"start": 5306,
"tag": "EMAIL",
"value": "wes@demo.com"
},
{
"context": "776322b\"\n :title \"Hovercar Subtree\"\n :author \"Wes Chow\"\n :email \"wes@demo.com\"\n :description \"Hoveri",
"end": 7553,
"score": 0.9998335242271423,
"start": 7545,
"tag": "NAME",
"value": "Wes Chow"
},
{
"context": "overcar Subtree\"\n :author \"Wes Chow\"\n :email \"wes@demo.com\"\n :description \"Hovering cars! They're pretty c",
"end": 7578,
"score": 0.9999291896820068,
"start": 7566,
"tag": "EMAIL",
"value": "wes@demo.com"
}
] | pf-web/src/pf_web/db.cljs | wesc/pathfinder-0 | 0 | (ns pf-web.db)
(def lasers-subtree
{:id "subtree-uuid-1"
:title "Lasers Subtree"
:author "Wes Chow"
:email "wes@demo.com"
:short-description "Lasers! They are pretty cool. This is how we make them."
:tech
{"uuid-lasers"
{:id "uuid-lasers"
:title "Lasers"
:short-description "The term \"laser\" is an acronym for \"light amplification by stimulated emission of radiation,\" which pretty much describes what it happens to be."
:long-description "The theory dates back to a paper by Albert Einstein in 1917 which offered a derivation of Planck's Law concerning stimulated emission of electromagnetic radiation. In 1928, the atomic physicist Rudolf Ladenburg confirmed the phenomena of stimulated emission and negative absorption. By the time of the first true laser, American and Soviet Russian scientists had built masers, amplifying microwave radiation rather than light radiation. So it wasn't long before various others were attempting to build \"optical masers,\" as commonly termed (\"laser\" was coined in 1959). The first functional laser was demonstrated in May 1960 when the Hughes Research Laboratories introduced laser technology capable of storing data on optical devices. Later that same year, the Iranian Ali Javan headed an international team that produced the first gas laser, utilizing helium and neon, capable of continuous operation in the infrared spectrum."
:dependencies ["uuid-nuclear-fission"]
:references []}
"uuid-combined-arms"
{:id "uuid-combined-arms"
:title "Combined Arms"
:short-description "Arms that are combined."
:long-description "The thoughtful combination of different arms in the same army is a very old concept - many generals of the antiquity have tried to supply their archers with pike regiments for defense against cavalry charges, for example. But it takes the chaotic battlefield of modernity, with its artillery shells and air-dropped bombs exploding everywhere, and its tanks rolling through everything, for the concept of combined arms to get true traction."
:dependencies []
:references []}
"uuid-advanced-ballistics"
{:id "uuid-advanced-ballistics"
:title "Advanced Ballistics"
:short-description "Advanced ballistics go boom."
:long-description "Once humans started shooting off rockets, the need for a new understanding of ballistics became clear. The flight of rockets, jets, missiles, spacecraft and such simply couldn't be covered by the current knowledge of internal, transition, external and terminal ballistics that had been accumulated by engineers to that time. When Goddard and von Braun began lighting up the heavens, something more than a gyroscope was required to get the missile to impact where desired. And issues such as escape velocity and orbital reentry began to be of some importance, especially to future cosmonauts and astronauts. Meanwhile, jet aircraft capable of flying at Mach at altitudes of 10-15,000 meters (33-49,000 feet) changed the dynamics of flight into that of ballistics."
:dependencies []
:references []}
"uuid-nuclear-fission"
{:id "uuid-nuclear-fission"
:title "Nuclear Fission"
:short-description "Fission that is nuclear."
:long-description "In contrast to nuclear fission – where energy is generated by the division of a nucleus – nuclear fusion occurs when two or more atomic nuclei slam together hard enough to fuse, which also releases photons in quantity. Fusion reactions power the stars of the universe, giving off lots of light and heat.\n\n
During WW2, research to create a fission bomb subsumed research into nuclear fusion. But in 1946 AD a patent was awarded to two British researchers for a prototype fusion reactor based on the Z-pinch concept, whereby a magnetic field could be generated to contain plasma (akin to that in a star). Commencing the following year, two teams in Britain began a series of ever larger experiments to generate electricity via fusion; another Brit, James Tuck, working at Los Alamos in the United States, built a series of fusion reactors leading to the largest, known derisively as the “Perhapsatron.” As it turned out, the name was apt, for experiments revealed instabilities in all these designs such that fusion was never reached."
:dependencies ["uuid-combined-arms", "uuid-advanced-ballistics"]
:references []}
"uuid-nuclear-warheads"
{:id "uuid-nuclear-warheads"
:title "Nukes"
:short-description "Nuclear warheads, yikes!"
:long-description "You stick a big nuclear bomb on a missle and shoot it around the world."
:dependencies ["uuid-nuclear-fission", "uuid-advanced-ballistics"]
:references []}
}
:comments
{"comment-id-1"
{:id "comment-id-1"
:seq 1
:tech-id "uuid-lasers"
:text "a comment about lasers"}
"a-comment-id-2"
{:id "a-comment-id-2"
:seq 2
:tech-id "uuid-lasers"
:text "another comment about lasers, which are frickin awesome"}
"comment-id-3"
{:id "comment-id-3"
:seq 3
:tech-id "uuid-nuclear-warheads"
:text "not so cool, man"}
}
})
(def flying-car-subtree
{:id "b05d2a50-2f1f-4d72-b007-d4e4e57526aa"
:title "Flying Car Subtree"
:author "Wes Chow"
:email "wes@demo.com"
:description "Flying cars! They're pretty cool. This is how we make them."
:tech
{"4c5205b0-0a68-475f-a7b5-bdcf2950eb55"
{:id "4c5205b0-0a68-475f-a7b5-bdcf2950eb55"
:title "Cars"
:short-description "Cars are vehicles that move around on wheels."
:long-description "A car (or automobile) is a wheeled motor vehicle used for transportation. Most definitions of cars say that they run primarily on roads, seat one to eight people, have four wheels, and mainly transport people rather than goods."
:dependencies []
:references []}
"b52e1c63-1221-43fe-b9c6-07776f9e42d9"
{:id "b52e1c63-1221-43fe-b9c6-07776f9e42d9"
:title "Planes"
:short-description "Planes are vehicles that fly through the air."
:long-description "An airplane or aeroplane (informally plane) is a fixed-wing aircraft that is propelled forward by thrust from a jet engine, propeller, or rocket engine. Airplanes come in a variety of sizes, shapes, and wing configurations. The broad spectrum of uses for airplanes includes recreation, transportation of goods and people, military, and research. Worldwide, commercial aviation transports more than four billion passengers annually on airliners and transports more than 200 billion tonne-kilometers of cargo annually, which is less than 1% of the world's cargo movement. Most airplanes are flown by a pilot on board the aircraft, but some are designed to be remotely or computer-controlled such as drones."
:dependencies []
:references []}
"bdafe7a4-0f2a-427d-b501-5779051850b0"
{:id "bdafe7a4-0f2a-427d-b501-5779051850b0"
:title "Flying Cars"
:short-description "Flying cars are cars that fly."
:long-description "A flying car or roadable aircraft is a type of vehicle which can function as both a personal car and an aircraft. As used here, this includes vehicles which drive as motorcycles when on the road. The term 'flying car' is also sometimes used to include hovercars."
:dependencies ["4c5205b0-0a68-475f-a7b5-bdcf2950eb55" "b52e1c63-1221-43fe-b9c6-07776f9e42d9"]}}
:comments
{}
})
(def hovercar-subtree
{:id "19e564aa-78a5-499a-8349-9e087776322b"
:title "Hovercar Subtree"
:author "Wes Chow"
:email "wes@demo.com"
:description "Hovering cars! They're pretty cool. This is how we make them."
:tech
{"4c5205b0-0a68-475f-a7b5-bdcf2950eb55"
{:id "4c5205b0-0a68-475f-a7b5-bdcf2950eb55"
:title "Cars"
:short-description "Cars are vehicles that move around on wheels."
:long-description "A car (or automobile) is a wheeled motor vehicle used for transportation. Most definitions of cars say that they run primarily on roads, seat one to eight people, have four wheels, and mainly transport people rather than goods."
:dependencies []
:references []}
"6a7c8ca9-1029-4a6a-96fd-ec35d032a480"
{:id "6a7c8ca9-1029-4a6a-96fd-ec35d032a480"
:title "Propellers"
:short-description "Rotating blades that provide lift."
:long-description "A propeller (colloquially often called a screw if on a ship or an airscrew if on an aircraft), is a device with a rotating hub and radiating blades that are set at a pitch to form a helical spiral, that, when rotated, exerts linear thrust upon a working fluid, such as water or air. Propellers are used to pump fluid through a pipe or duct, or to create thrust to propel a boat through water or an aircraft through air. The blades are specially shaped so that their rotational motion through the fluid causes a pressure difference between the two surfaces of the blade by Bernoulli's principle which exerts force on the fluid."
:dependencies []
:references []}
"d2383458-e9f2-492e-b6e2-491181401cc2"
{:id "d2383458-e9f2-492e-b6e2-491181401cc2"
:title "Hovercars"
:short-description "Cars that hover."
:long-description "A hover car is a personal vehicle that flies at a constant altitude of up to few meters (some feet) above the ground and used for personal transportation in the same way a modern automobile is employed. It usually appears in works of science fiction."
:dependencies ["4c5205b0-0a68-475f-a7b5-bdcf2950eb55" "6a7c8ca9-1029-4a6a-96fd-ec35d032a480"]
:references []}
}
:comments
{}
})
(def default-subtree-catalog
{(:id lasers-subtree) lasers-subtree
(:id flying-car-subtree) flying-car-subtree
(:id hovercar-subtree) hovercar-subtree})
(def default-db
{:name "Pathfinder"
:active-panel [:home-panel nil]
:subtree-catalog default-subtree-catalog
:subtree lasers-subtree
:sel-tech "uuid-lasers"
:alert-message nil
:download-link nil})
| 52451 | (ns pf-web.db)
(def lasers-subtree
{:id "subtree-uuid-1"
:title "Lasers Subtree"
:author "<NAME>"
:email "<EMAIL>"
:short-description "Lasers! They are pretty cool. This is how we make them."
:tech
{"uuid-lasers"
{:id "uuid-lasers"
:title "Lasers"
:short-description "The term \"laser\" is an acronym for \"light amplification by stimulated emission of radiation,\" which pretty much describes what it happens to be."
:long-description "The theory dates back to a paper by <NAME>ein in 1917 which offered a derivation of Planck's Law concerning stimulated emission of electromagnetic radiation. In 1928, the atomic physicist Rudolf Ladenburg confirmed the phenomena of stimulated emission and negative absorption. By the time of the first true laser, American and Soviet Russian scientists had built masers, amplifying microwave radiation rather than light radiation. So it wasn't long before various others were attempting to build \"optical masers,\" as commonly termed (\"laser\" was coined in 1959). The first functional laser was demonstrated in May 1960 when the Hughes Research Laboratories introduced laser technology capable of storing data on optical devices. Later that same year, the Iranian Ali Javan headed an international team that produced the first gas laser, utilizing helium and neon, capable of continuous operation in the infrared spectrum."
:dependencies ["uuid-nuclear-fission"]
:references []}
"uuid-combined-arms"
{:id "uuid-combined-arms"
:title "Combined Arms"
:short-description "Arms that are combined."
:long-description "The thoughtful combination of different arms in the same army is a very old concept - many generals of the antiquity have tried to supply their archers with pike regiments for defense against cavalry charges, for example. But it takes the chaotic battlefield of modernity, with its artillery shells and air-dropped bombs exploding everywhere, and its tanks rolling through everything, for the concept of combined arms to get true traction."
:dependencies []
:references []}
"uuid-advanced-ballistics"
{:id "uuid-advanced-ballistics"
:title "Advanced Ballistics"
:short-description "Advanced ballistics go boom."
:long-description "Once humans started shooting off rockets, the need for a new understanding of ballistics became clear. The flight of rockets, jets, missiles, spacecraft and such simply couldn't be covered by the current knowledge of internal, transition, external and terminal ballistics that had been accumulated by engineers to that time. When <NAME> and <NAME> began lighting up the heavens, something more than a gyroscope was required to get the missile to impact where desired. And issues such as escape velocity and orbital reentry began to be of some importance, especially to future cosmonauts and astronauts. Meanwhile, jet aircraft capable of flying at Mach at altitudes of 10-15,000 meters (33-49,000 feet) changed the dynamics of flight into that of ballistics."
:dependencies []
:references []}
"uuid-nuclear-fission"
{:id "uuid-nuclear-fission"
:title "Nuclear Fission"
:short-description "Fission that is nuclear."
:long-description "In contrast to nuclear fission – where energy is generated by the division of a nucleus – nuclear fusion occurs when two or more atomic nuclei slam together hard enough to fuse, which also releases photons in quantity. Fusion reactions power the stars of the universe, giving off lots of light and heat.\n\n
During WW2, research to create a fission bomb subsumed research into nuclear fusion. But in 1946 AD a patent was awarded to two British researchers for a prototype fusion reactor based on the Z-pinch concept, whereby a magnetic field could be generated to contain plasma (akin to that in a star). Commencing the following year, two teams in Britain began a series of ever larger experiments to generate electricity via fusion; another Brit, <NAME>, working at Los Alamos in the United States, built a series of fusion reactors leading to the largest, known derisively as the “Perhapsatron.” As it turned out, the name was apt, for experiments revealed instabilities in all these designs such that fusion was never reached."
:dependencies ["uuid-combined-arms", "uuid-advanced-ballistics"]
:references []}
"uuid-nuclear-warheads"
{:id "uuid-nuclear-warheads"
:title "Nukes"
:short-description "Nuclear warheads, yikes!"
:long-description "You stick a big nuclear bomb on a missle and shoot it around the world."
:dependencies ["uuid-nuclear-fission", "uuid-advanced-ballistics"]
:references []}
}
:comments
{"comment-id-1"
{:id "comment-id-1"
:seq 1
:tech-id "uuid-lasers"
:text "a comment about lasers"}
"a-comment-id-2"
{:id "a-comment-id-2"
:seq 2
:tech-id "uuid-lasers"
:text "another comment about lasers, which are frickin awesome"}
"comment-id-3"
{:id "comment-id-3"
:seq 3
:tech-id "uuid-nuclear-warheads"
:text "not so cool, man"}
}
})
(def flying-car-subtree
{:id "b05d2a50-2f1f-4d72-b007-d4e4e57526aa"
:title "Flying Car Subtree"
:author "<NAME>"
:email "<EMAIL>"
:description "Flying cars! They're pretty cool. This is how we make them."
:tech
{"4c5205b0-0a68-475f-a7b5-bdcf2950eb55"
{:id "4c5205b0-0a68-475f-a7b5-bdcf2950eb55"
:title "Cars"
:short-description "Cars are vehicles that move around on wheels."
:long-description "A car (or automobile) is a wheeled motor vehicle used for transportation. Most definitions of cars say that they run primarily on roads, seat one to eight people, have four wheels, and mainly transport people rather than goods."
:dependencies []
:references []}
"b52e1c63-1221-43fe-b9c6-07776f9e42d9"
{:id "b52e1c63-1221-43fe-b9c6-07776f9e42d9"
:title "Planes"
:short-description "Planes are vehicles that fly through the air."
:long-description "An airplane or aeroplane (informally plane) is a fixed-wing aircraft that is propelled forward by thrust from a jet engine, propeller, or rocket engine. Airplanes come in a variety of sizes, shapes, and wing configurations. The broad spectrum of uses for airplanes includes recreation, transportation of goods and people, military, and research. Worldwide, commercial aviation transports more than four billion passengers annually on airliners and transports more than 200 billion tonne-kilometers of cargo annually, which is less than 1% of the world's cargo movement. Most airplanes are flown by a pilot on board the aircraft, but some are designed to be remotely or computer-controlled such as drones."
:dependencies []
:references []}
"bdafe7a4-0f2a-427d-b501-5779051850b0"
{:id "bdafe7a4-0f2a-427d-b501-5779051850b0"
:title "Flying Cars"
:short-description "Flying cars are cars that fly."
:long-description "A flying car or roadable aircraft is a type of vehicle which can function as both a personal car and an aircraft. As used here, this includes vehicles which drive as motorcycles when on the road. The term 'flying car' is also sometimes used to include hovercars."
:dependencies ["4c5205b0-0a68-475f-a7b5-bdcf2950eb55" "b52e1c63-1221-43fe-b9c6-07776f9e42d9"]}}
:comments
{}
})
(def hovercar-subtree
{:id "19e564aa-78a5-499a-8349-9e087776322b"
:title "Hovercar Subtree"
:author "<NAME>"
:email "<EMAIL>"
:description "Hovering cars! They're pretty cool. This is how we make them."
:tech
{"4c5205b0-0a68-475f-a7b5-bdcf2950eb55"
{:id "4c5205b0-0a68-475f-a7b5-bdcf2950eb55"
:title "Cars"
:short-description "Cars are vehicles that move around on wheels."
:long-description "A car (or automobile) is a wheeled motor vehicle used for transportation. Most definitions of cars say that they run primarily on roads, seat one to eight people, have four wheels, and mainly transport people rather than goods."
:dependencies []
:references []}
"6a7c8ca9-1029-4a6a-96fd-ec35d032a480"
{:id "6a7c8ca9-1029-4a6a-96fd-ec35d032a480"
:title "Propellers"
:short-description "Rotating blades that provide lift."
:long-description "A propeller (colloquially often called a screw if on a ship or an airscrew if on an aircraft), is a device with a rotating hub and radiating blades that are set at a pitch to form a helical spiral, that, when rotated, exerts linear thrust upon a working fluid, such as water or air. Propellers are used to pump fluid through a pipe or duct, or to create thrust to propel a boat through water or an aircraft through air. The blades are specially shaped so that their rotational motion through the fluid causes a pressure difference between the two surfaces of the blade by Bernoulli's principle which exerts force on the fluid."
:dependencies []
:references []}
"d2383458-e9f2-492e-b6e2-491181401cc2"
{:id "d2383458-e9f2-492e-b6e2-491181401cc2"
:title "Hovercars"
:short-description "Cars that hover."
:long-description "A hover car is a personal vehicle that flies at a constant altitude of up to few meters (some feet) above the ground and used for personal transportation in the same way a modern automobile is employed. It usually appears in works of science fiction."
:dependencies ["4c5205b0-0a68-475f-a7b5-bdcf2950eb55" "6a7c8ca9-1029-4a6a-96fd-ec35d032a480"]
:references []}
}
:comments
{}
})
(def default-subtree-catalog
{(:id lasers-subtree) lasers-subtree
(:id flying-car-subtree) flying-car-subtree
(:id hovercar-subtree) hovercar-subtree})
(def default-db
{:name "Pathfinder"
:active-panel [:home-panel nil]
:subtree-catalog default-subtree-catalog
:subtree lasers-subtree
:sel-tech "uuid-lasers"
:alert-message nil
:download-link nil})
| true | (ns pf-web.db)
(def lasers-subtree
{:id "subtree-uuid-1"
:title "Lasers Subtree"
:author "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:short-description "Lasers! They are pretty cool. This is how we make them."
:tech
{"uuid-lasers"
{:id "uuid-lasers"
:title "Lasers"
:short-description "The term \"laser\" is an acronym for \"light amplification by stimulated emission of radiation,\" which pretty much describes what it happens to be."
:long-description "The theory dates back to a paper by PI:NAME:<NAME>END_PIein in 1917 which offered a derivation of Planck's Law concerning stimulated emission of electromagnetic radiation. In 1928, the atomic physicist Rudolf Ladenburg confirmed the phenomena of stimulated emission and negative absorption. By the time of the first true laser, American and Soviet Russian scientists had built masers, amplifying microwave radiation rather than light radiation. So it wasn't long before various others were attempting to build \"optical masers,\" as commonly termed (\"laser\" was coined in 1959). The first functional laser was demonstrated in May 1960 when the Hughes Research Laboratories introduced laser technology capable of storing data on optical devices. Later that same year, the Iranian Ali Javan headed an international team that produced the first gas laser, utilizing helium and neon, capable of continuous operation in the infrared spectrum."
:dependencies ["uuid-nuclear-fission"]
:references []}
"uuid-combined-arms"
{:id "uuid-combined-arms"
:title "Combined Arms"
:short-description "Arms that are combined."
:long-description "The thoughtful combination of different arms in the same army is a very old concept - many generals of the antiquity have tried to supply their archers with pike regiments for defense against cavalry charges, for example. But it takes the chaotic battlefield of modernity, with its artillery shells and air-dropped bombs exploding everywhere, and its tanks rolling through everything, for the concept of combined arms to get true traction."
:dependencies []
:references []}
"uuid-advanced-ballistics"
{:id "uuid-advanced-ballistics"
:title "Advanced Ballistics"
:short-description "Advanced ballistics go boom."
:long-description "Once humans started shooting off rockets, the need for a new understanding of ballistics became clear. The flight of rockets, jets, missiles, spacecraft and such simply couldn't be covered by the current knowledge of internal, transition, external and terminal ballistics that had been accumulated by engineers to that time. When PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI began lighting up the heavens, something more than a gyroscope was required to get the missile to impact where desired. And issues such as escape velocity and orbital reentry began to be of some importance, especially to future cosmonauts and astronauts. Meanwhile, jet aircraft capable of flying at Mach at altitudes of 10-15,000 meters (33-49,000 feet) changed the dynamics of flight into that of ballistics."
:dependencies []
:references []}
"uuid-nuclear-fission"
{:id "uuid-nuclear-fission"
:title "Nuclear Fission"
:short-description "Fission that is nuclear."
:long-description "In contrast to nuclear fission – where energy is generated by the division of a nucleus – nuclear fusion occurs when two or more atomic nuclei slam together hard enough to fuse, which also releases photons in quantity. Fusion reactions power the stars of the universe, giving off lots of light and heat.\n\n
During WW2, research to create a fission bomb subsumed research into nuclear fusion. But in 1946 AD a patent was awarded to two British researchers for a prototype fusion reactor based on the Z-pinch concept, whereby a magnetic field could be generated to contain plasma (akin to that in a star). Commencing the following year, two teams in Britain began a series of ever larger experiments to generate electricity via fusion; another Brit, PI:NAME:<NAME>END_PI, working at Los Alamos in the United States, built a series of fusion reactors leading to the largest, known derisively as the “Perhapsatron.” As it turned out, the name was apt, for experiments revealed instabilities in all these designs such that fusion was never reached."
:dependencies ["uuid-combined-arms", "uuid-advanced-ballistics"]
:references []}
"uuid-nuclear-warheads"
{:id "uuid-nuclear-warheads"
:title "Nukes"
:short-description "Nuclear warheads, yikes!"
:long-description "You stick a big nuclear bomb on a missle and shoot it around the world."
:dependencies ["uuid-nuclear-fission", "uuid-advanced-ballistics"]
:references []}
}
:comments
{"comment-id-1"
{:id "comment-id-1"
:seq 1
:tech-id "uuid-lasers"
:text "a comment about lasers"}
"a-comment-id-2"
{:id "a-comment-id-2"
:seq 2
:tech-id "uuid-lasers"
:text "another comment about lasers, which are frickin awesome"}
"comment-id-3"
{:id "comment-id-3"
:seq 3
:tech-id "uuid-nuclear-warheads"
:text "not so cool, man"}
}
})
(def flying-car-subtree
{:id "b05d2a50-2f1f-4d72-b007-d4e4e57526aa"
:title "Flying Car Subtree"
:author "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:description "Flying cars! They're pretty cool. This is how we make them."
:tech
{"4c5205b0-0a68-475f-a7b5-bdcf2950eb55"
{:id "4c5205b0-0a68-475f-a7b5-bdcf2950eb55"
:title "Cars"
:short-description "Cars are vehicles that move around on wheels."
:long-description "A car (or automobile) is a wheeled motor vehicle used for transportation. Most definitions of cars say that they run primarily on roads, seat one to eight people, have four wheels, and mainly transport people rather than goods."
:dependencies []
:references []}
"b52e1c63-1221-43fe-b9c6-07776f9e42d9"
{:id "b52e1c63-1221-43fe-b9c6-07776f9e42d9"
:title "Planes"
:short-description "Planes are vehicles that fly through the air."
:long-description "An airplane or aeroplane (informally plane) is a fixed-wing aircraft that is propelled forward by thrust from a jet engine, propeller, or rocket engine. Airplanes come in a variety of sizes, shapes, and wing configurations. The broad spectrum of uses for airplanes includes recreation, transportation of goods and people, military, and research. Worldwide, commercial aviation transports more than four billion passengers annually on airliners and transports more than 200 billion tonne-kilometers of cargo annually, which is less than 1% of the world's cargo movement. Most airplanes are flown by a pilot on board the aircraft, but some are designed to be remotely or computer-controlled such as drones."
:dependencies []
:references []}
"bdafe7a4-0f2a-427d-b501-5779051850b0"
{:id "bdafe7a4-0f2a-427d-b501-5779051850b0"
:title "Flying Cars"
:short-description "Flying cars are cars that fly."
:long-description "A flying car or roadable aircraft is a type of vehicle which can function as both a personal car and an aircraft. As used here, this includes vehicles which drive as motorcycles when on the road. The term 'flying car' is also sometimes used to include hovercars."
:dependencies ["4c5205b0-0a68-475f-a7b5-bdcf2950eb55" "b52e1c63-1221-43fe-b9c6-07776f9e42d9"]}}
:comments
{}
})
(def hovercar-subtree
{:id "19e564aa-78a5-499a-8349-9e087776322b"
:title "Hovercar Subtree"
:author "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:description "Hovering cars! They're pretty cool. This is how we make them."
:tech
{"4c5205b0-0a68-475f-a7b5-bdcf2950eb55"
{:id "4c5205b0-0a68-475f-a7b5-bdcf2950eb55"
:title "Cars"
:short-description "Cars are vehicles that move around on wheels."
:long-description "A car (or automobile) is a wheeled motor vehicle used for transportation. Most definitions of cars say that they run primarily on roads, seat one to eight people, have four wheels, and mainly transport people rather than goods."
:dependencies []
:references []}
"6a7c8ca9-1029-4a6a-96fd-ec35d032a480"
{:id "6a7c8ca9-1029-4a6a-96fd-ec35d032a480"
:title "Propellers"
:short-description "Rotating blades that provide lift."
:long-description "A propeller (colloquially often called a screw if on a ship or an airscrew if on an aircraft), is a device with a rotating hub and radiating blades that are set at a pitch to form a helical spiral, that, when rotated, exerts linear thrust upon a working fluid, such as water or air. Propellers are used to pump fluid through a pipe or duct, or to create thrust to propel a boat through water or an aircraft through air. The blades are specially shaped so that their rotational motion through the fluid causes a pressure difference between the two surfaces of the blade by Bernoulli's principle which exerts force on the fluid."
:dependencies []
:references []}
"d2383458-e9f2-492e-b6e2-491181401cc2"
{:id "d2383458-e9f2-492e-b6e2-491181401cc2"
:title "Hovercars"
:short-description "Cars that hover."
:long-description "A hover car is a personal vehicle that flies at a constant altitude of up to few meters (some feet) above the ground and used for personal transportation in the same way a modern automobile is employed. It usually appears in works of science fiction."
:dependencies ["4c5205b0-0a68-475f-a7b5-bdcf2950eb55" "6a7c8ca9-1029-4a6a-96fd-ec35d032a480"]
:references []}
}
:comments
{}
})
(def default-subtree-catalog
{(:id lasers-subtree) lasers-subtree
(:id flying-car-subtree) flying-car-subtree
(:id hovercar-subtree) hovercar-subtree})
(def default-db
{:name "Pathfinder"
:active-panel [:home-panel nil]
:subtree-catalog default-subtree-catalog
:subtree lasers-subtree
:sel-tech "uuid-lasers"
:alert-message nil
:download-link nil})
|
[
{
"context": "rs WordNet functionality\n;;;;\n;;;; @copyright 2020 Dennis Drown et l'Université du Québec à Montréal\n;;;; -------",
"end": 386,
"score": 0.9998742938041687,
"start": 374,
"tag": "NAME",
"value": "Dennis Drown"
}
] | apps/say_sila/priv/fnode/say/src/say/wordnet.clj | dendrown/say_sila | 0 | ;;;; -------------------------------------------------------------------------
;;;;
;;;; _/_/_/ _/_/_/ _/ _/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/ _/ _/ _/_/_/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/
;;;;
;;;; Wrappers WordNet functionality
;;;;
;;;; @copyright 2020 Dennis Drown et l'Université du Québec à Montréal
;;;; -------------------------------------------------------------------------
(ns say.wordnet
(:require [say.genie :refer :all]
[say.config :as cfg]
[say.log :as log]
[wordnet.core :as wnet]
[clojure.set :as set]
[clojure.pprint :refer [pp]]))
(defonce Concept-Synsets
;; These are synsets applicable to climate change concepts as described in the Six Americas
{"cause"
#{"SID-07341157-N" ;gloss "events that provide the generative force that is the origin of something..."
"SID-00007347-N" ;gloss "any entity that produces an effect or is responsible for events or results"
"SID-01649143-V" ;gloss "give rise to; cause to happen or occur, not always intentionally..."
"SID-00772482-V"} ;gloss "cause to do; cause to act in a specified manner"
"human"
#{"SID-02474924-N" ;gloss "any living or extinct member of the family Hominidae characterized by
; superior intelligence, articulate speech, and erect carriage"
"SID-02754015-A" ;gloss "characteristic of humanity; 'human nature'"
"SID-02754145-A" ;gloss "relating to a person; 'the experiment was conducted on 6 monkeys and 2 human subjects'"
"SID-01261689-A"} ;gloss "having human form or attributes as opposed to those of animals or divine beings..."
"nature"
#{"SID-09389659-N"} ;gloss "the natural physical world including plants and animals and landscapes etc."
;; --------------------------------------------------------------------------
"conservagtion"
#{"SID-07434199-N" ;gloss "an occurrence of improvement by virtue of preventing loss or injury or other change"
"SID-00820935-N"} ;gloss "the preservation and careful management of the environment and of natural resources"
"save"
#{"SID-02556565-V" ;gloss "save from ruin, destruction, or harm"
"SID-02557529-V" ;gloss "bring into safety; \"We pulled through most of the victims of the bomb attack\""
"SID-02470006-V"} ;gloss "refrain from harming"
;; --------------------------------------------------------------------------
"carbon"
#{"SID-14657384-N"} ;gloss "an abundant nonmetallic tetravalent element occurring in three allotropic forms..."
;; --------------------------------------------------------------------------
"cut"
#{"SID-00430013-V" ;gloss "cut down on; make a reduction in; 'reduce your daily fat intake'"
"SID-00244786-V"} ;gloss "reduce in scope while retaining essential elements; 'The manuscript must be shortened'"
;; --------------------------------------------------------------------------
"protect"
#{"SID-01130619-V"} ;gloss "shield from danger, injury, destruction, or damage"
"environment"
#{"SID-13957629-N"} ;gloss "the totality of surrounding conditions"
;; --------------------------------------------------------------------------
"economic"
#{"SID-02727475-A" ;gloss "of or relating to an economy, the system of production and management of material wealth"
"SID-02587892-A"} ;gloss "concerned with worldly necessities of life (especially money)"
"growth"
#{"SID-13518338-N"} ;gloss "a process of becoming larger or longer or more numerous or more important"
;; --------------------------------------------------------------------------
"year"
#{"SID-15228587-N" ;gloss "a period of time containing 365 (or 366) days"
"SID-15226340-N"} ;gloss "the period of time that it takes for a planet to make a complete revolution around the sun"
})
;;; --------------------------------------------------------------------------
(set! *warn-on-reflection* true)
;;; Boost survey vocabulary with WordNet, if available
(defonce Dictionary (when-let [dir (cfg/?? :sila :wordnet-dir)]
(wnet/make-dictionary dir)))
;;; --------------------------------------------------------------------------
(defmacro wordnet
"If the application has access to WordNet, this macro executes the body
expression. If not, it logs a warning and returns its argument unchanged."
[arg & body]
`(if Dictionary
(do ~@body)
(do (log/warn "WordNet is not configured.")
~arg)))
;;; --------------------------------------------------------------------------
(defn synsets
"Returns synsets for the specified word. If the word represents a Say-Sila
concept, the caller will only get the synsets wich are applicable climate
change modelling. Otherwise, the synonyms span all associated synsets.
When the caller specified multiple words, the function returns the
intersection of the synsets for these words."
([word]
(wordnet word
(let [syns (get Concept-Synsets word)
use? #(or (nil? syns)
(contains? syns (:id %)))]
(->> (Dictionary word)
(map wnet/synset)
(filter use?)))))
([word & more]
(apply set/intersection (map #(into #{} (synsets %))
(conj more word)))))
;;; --------------------------------------------------------------------------
(defn synonyms
"Returns synonyms (lemmas) of the word. Note that for words representing
Say-Sila concepts, the function will only return synonyms associated with
climate change modelling."
[word]
(when-let [syns (synsets word)]
(->> syns
(mapcat wnet/words)
(map :lemma)
(remove (cfg/?? :wordnet :omit #{}))
(into #{}))))
(def synonyms# (memoize synonyms))
;;; --------------------------------------------------------------------------
(defn synonym-values
"Finds the synonyms for all values in a hashmap."
[wmap]
(wordnet wmap
(update-values wmap #(into #{} (mapcat synonyms# %)))))
| 80988 | ;;;; -------------------------------------------------------------------------
;;;;
;;;; _/_/_/ _/_/_/ _/ _/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/ _/ _/ _/_/_/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/
;;;;
;;;; Wrappers WordNet functionality
;;;;
;;;; @copyright 2020 <NAME> et l'Université du Québec à Montréal
;;;; -------------------------------------------------------------------------
(ns say.wordnet
(:require [say.genie :refer :all]
[say.config :as cfg]
[say.log :as log]
[wordnet.core :as wnet]
[clojure.set :as set]
[clojure.pprint :refer [pp]]))
(defonce Concept-Synsets
;; These are synsets applicable to climate change concepts as described in the Six Americas
{"cause"
#{"SID-07341157-N" ;gloss "events that provide the generative force that is the origin of something..."
"SID-00007347-N" ;gloss "any entity that produces an effect or is responsible for events or results"
"SID-01649143-V" ;gloss "give rise to; cause to happen or occur, not always intentionally..."
"SID-00772482-V"} ;gloss "cause to do; cause to act in a specified manner"
"human"
#{"SID-02474924-N" ;gloss "any living or extinct member of the family Hominidae characterized by
; superior intelligence, articulate speech, and erect carriage"
"SID-02754015-A" ;gloss "characteristic of humanity; 'human nature'"
"SID-02754145-A" ;gloss "relating to a person; 'the experiment was conducted on 6 monkeys and 2 human subjects'"
"SID-01261689-A"} ;gloss "having human form or attributes as opposed to those of animals or divine beings..."
"nature"
#{"SID-09389659-N"} ;gloss "the natural physical world including plants and animals and landscapes etc."
;; --------------------------------------------------------------------------
"conservagtion"
#{"SID-07434199-N" ;gloss "an occurrence of improvement by virtue of preventing loss or injury or other change"
"SID-00820935-N"} ;gloss "the preservation and careful management of the environment and of natural resources"
"save"
#{"SID-02556565-V" ;gloss "save from ruin, destruction, or harm"
"SID-02557529-V" ;gloss "bring into safety; \"We pulled through most of the victims of the bomb attack\""
"SID-02470006-V"} ;gloss "refrain from harming"
;; --------------------------------------------------------------------------
"carbon"
#{"SID-14657384-N"} ;gloss "an abundant nonmetallic tetravalent element occurring in three allotropic forms..."
;; --------------------------------------------------------------------------
"cut"
#{"SID-00430013-V" ;gloss "cut down on; make a reduction in; 'reduce your daily fat intake'"
"SID-00244786-V"} ;gloss "reduce in scope while retaining essential elements; 'The manuscript must be shortened'"
;; --------------------------------------------------------------------------
"protect"
#{"SID-01130619-V"} ;gloss "shield from danger, injury, destruction, or damage"
"environment"
#{"SID-13957629-N"} ;gloss "the totality of surrounding conditions"
;; --------------------------------------------------------------------------
"economic"
#{"SID-02727475-A" ;gloss "of or relating to an economy, the system of production and management of material wealth"
"SID-02587892-A"} ;gloss "concerned with worldly necessities of life (especially money)"
"growth"
#{"SID-13518338-N"} ;gloss "a process of becoming larger or longer or more numerous or more important"
;; --------------------------------------------------------------------------
"year"
#{"SID-15228587-N" ;gloss "a period of time containing 365 (or 366) days"
"SID-15226340-N"} ;gloss "the period of time that it takes for a planet to make a complete revolution around the sun"
})
;;; --------------------------------------------------------------------------
(set! *warn-on-reflection* true)
;;; Boost survey vocabulary with WordNet, if available
(defonce Dictionary (when-let [dir (cfg/?? :sila :wordnet-dir)]
(wnet/make-dictionary dir)))
;;; --------------------------------------------------------------------------
(defmacro wordnet
"If the application has access to WordNet, this macro executes the body
expression. If not, it logs a warning and returns its argument unchanged."
[arg & body]
`(if Dictionary
(do ~@body)
(do (log/warn "WordNet is not configured.")
~arg)))
;;; --------------------------------------------------------------------------
(defn synsets
"Returns synsets for the specified word. If the word represents a Say-Sila
concept, the caller will only get the synsets wich are applicable climate
change modelling. Otherwise, the synonyms span all associated synsets.
When the caller specified multiple words, the function returns the
intersection of the synsets for these words."
([word]
(wordnet word
(let [syns (get Concept-Synsets word)
use? #(or (nil? syns)
(contains? syns (:id %)))]
(->> (Dictionary word)
(map wnet/synset)
(filter use?)))))
([word & more]
(apply set/intersection (map #(into #{} (synsets %))
(conj more word)))))
;;; --------------------------------------------------------------------------
(defn synonyms
"Returns synonyms (lemmas) of the word. Note that for words representing
Say-Sila concepts, the function will only return synonyms associated with
climate change modelling."
[word]
(when-let [syns (synsets word)]
(->> syns
(mapcat wnet/words)
(map :lemma)
(remove (cfg/?? :wordnet :omit #{}))
(into #{}))))
(def synonyms# (memoize synonyms))
;;; --------------------------------------------------------------------------
(defn synonym-values
"Finds the synonyms for all values in a hashmap."
[wmap]
(wordnet wmap
(update-values wmap #(into #{} (mapcat synonyms# %)))))
| true | ;;;; -------------------------------------------------------------------------
;;;;
;;;; _/_/_/ _/_/_/ _/ _/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/ _/ _/ _/_/_/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/
;;;;
;;;; Wrappers WordNet functionality
;;;;
;;;; @copyright 2020 PI:NAME:<NAME>END_PI et l'Université du Québec à Montréal
;;;; -------------------------------------------------------------------------
(ns say.wordnet
(:require [say.genie :refer :all]
[say.config :as cfg]
[say.log :as log]
[wordnet.core :as wnet]
[clojure.set :as set]
[clojure.pprint :refer [pp]]))
(defonce Concept-Synsets
;; These are synsets applicable to climate change concepts as described in the Six Americas
{"cause"
#{"SID-07341157-N" ;gloss "events that provide the generative force that is the origin of something..."
"SID-00007347-N" ;gloss "any entity that produces an effect or is responsible for events or results"
"SID-01649143-V" ;gloss "give rise to; cause to happen or occur, not always intentionally..."
"SID-00772482-V"} ;gloss "cause to do; cause to act in a specified manner"
"human"
#{"SID-02474924-N" ;gloss "any living or extinct member of the family Hominidae characterized by
; superior intelligence, articulate speech, and erect carriage"
"SID-02754015-A" ;gloss "characteristic of humanity; 'human nature'"
"SID-02754145-A" ;gloss "relating to a person; 'the experiment was conducted on 6 monkeys and 2 human subjects'"
"SID-01261689-A"} ;gloss "having human form or attributes as opposed to those of animals or divine beings..."
"nature"
#{"SID-09389659-N"} ;gloss "the natural physical world including plants and animals and landscapes etc."
;; --------------------------------------------------------------------------
"conservagtion"
#{"SID-07434199-N" ;gloss "an occurrence of improvement by virtue of preventing loss or injury or other change"
"SID-00820935-N"} ;gloss "the preservation and careful management of the environment and of natural resources"
"save"
#{"SID-02556565-V" ;gloss "save from ruin, destruction, or harm"
"SID-02557529-V" ;gloss "bring into safety; \"We pulled through most of the victims of the bomb attack\""
"SID-02470006-V"} ;gloss "refrain from harming"
;; --------------------------------------------------------------------------
"carbon"
#{"SID-14657384-N"} ;gloss "an abundant nonmetallic tetravalent element occurring in three allotropic forms..."
;; --------------------------------------------------------------------------
"cut"
#{"SID-00430013-V" ;gloss "cut down on; make a reduction in; 'reduce your daily fat intake'"
"SID-00244786-V"} ;gloss "reduce in scope while retaining essential elements; 'The manuscript must be shortened'"
;; --------------------------------------------------------------------------
"protect"
#{"SID-01130619-V"} ;gloss "shield from danger, injury, destruction, or damage"
"environment"
#{"SID-13957629-N"} ;gloss "the totality of surrounding conditions"
;; --------------------------------------------------------------------------
"economic"
#{"SID-02727475-A" ;gloss "of or relating to an economy, the system of production and management of material wealth"
"SID-02587892-A"} ;gloss "concerned with worldly necessities of life (especially money)"
"growth"
#{"SID-13518338-N"} ;gloss "a process of becoming larger or longer or more numerous or more important"
;; --------------------------------------------------------------------------
"year"
#{"SID-15228587-N" ;gloss "a period of time containing 365 (or 366) days"
"SID-15226340-N"} ;gloss "the period of time that it takes for a planet to make a complete revolution around the sun"
})
;;; --------------------------------------------------------------------------
(set! *warn-on-reflection* true)
;;; Boost survey vocabulary with WordNet, if available
(defonce Dictionary (when-let [dir (cfg/?? :sila :wordnet-dir)]
(wnet/make-dictionary dir)))
;;; --------------------------------------------------------------------------
(defmacro wordnet
"If the application has access to WordNet, this macro executes the body
expression. If not, it logs a warning and returns its argument unchanged."
[arg & body]
`(if Dictionary
(do ~@body)
(do (log/warn "WordNet is not configured.")
~arg)))
;;; --------------------------------------------------------------------------
(defn synsets
"Returns synsets for the specified word. If the word represents a Say-Sila
concept, the caller will only get the synsets wich are applicable climate
change modelling. Otherwise, the synonyms span all associated synsets.
When the caller specified multiple words, the function returns the
intersection of the synsets for these words."
([word]
(wordnet word
(let [syns (get Concept-Synsets word)
use? #(or (nil? syns)
(contains? syns (:id %)))]
(->> (Dictionary word)
(map wnet/synset)
(filter use?)))))
([word & more]
(apply set/intersection (map #(into #{} (synsets %))
(conj more word)))))
;;; --------------------------------------------------------------------------
(defn synonyms
"Returns synonyms (lemmas) of the word. Note that for words representing
Say-Sila concepts, the function will only return synonyms associated with
climate change modelling."
[word]
(when-let [syns (synsets word)]
(->> syns
(mapcat wnet/words)
(map :lemma)
(remove (cfg/?? :wordnet :omit #{}))
(into #{}))))
(def synonyms# (memoize synonyms))
;;; --------------------------------------------------------------------------
(defn synonym-values
"Finds the synonyms for all values in a hashmap."
[wmap]
(wordnet wmap
(update-values wmap #(into #{} (mapcat synonyms# %)))))
|
[
{
"context": " :password password})))))))\n\n(defn change-password [request]\n (let [",
"end": 4033,
"score": 0.8816888332366943,
"start": 4025,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "[user-fields (last user)]\n (let [password (auth/generate-random-password 8)\n unique ",
"end": 6414,
"score": 0.5131294131278992,
"start": 6410,
"tag": "PASSWORD",
"value": "auth"
},
{
"context": "-fields (last user)]\n (let [password (auth/generate-random-password 8)\n unique (empty? (db/get-u",
"end": 6430,
"score": 0.78789883852005,
"start": 6415,
"tag": "PASSWORD",
"value": "generate-random"
},
{
"context": " (let [password (auth/generate-random-password 8)\n unique (empty? (db/get-user {:id-f",
"end": 6441,
"score": 0.837741494178772,
"start": 6440,
"tag": "PASSWORD",
"value": "8"
},
{
"context": "ser-fields)\n :password password})))))\n (-> (redirect \"/register\")\n ",
"end": 7295,
"score": 0.9984708428382874,
"start": 7287,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " \"first_name\" \"last_name\" \"is_active\" \"password\" \"admin\"]})\n password-match (hashers/check (:p",
"end": 7891,
"score": 0.9940471649169922,
"start": 7886,
"tag": "PASSWORD",
"value": "admin"
}
] | data/train/clojure/f9a8b54a7ef17ad4269ba71f423757cc35c157d5auth.clj | harshp8l/deep-learning-lang-detection | 84 | (ns sltapp.routes.auth
(:require [sltapp.layout :refer [render base-context-authenticated-access base-context-any-access error-page]]
[compojure.core :refer [defroutes GET POST]]
[sltapp.utils :refer [get-next-url perform-action-and-redirect]]
[ring.util.response :refer [redirect]]
[sltapp.db.core :as db]
[sltapp.constants :refer [permissions]]
[sltapp.validators :as validators]
[sltapp.utils :as utils]
[sltapp.service.auth :as auth]
[sltapp.templates.auth :as auth-templates]
[buddy.hashers :as hashers]
[clojure.java.io :as io]))
(defn login-page [request next]
(if (-> request :identity :id)
(redirect "/")
(render (auth-templates/login (merge
(base-context-any-access request)
{:next next
:errors (-> request :flash :form_errors)})))))
(defn register-page [request]
(render (auth-templates/register (merge
(base-context-authenticated-access request)
{:errors (-> request :flash :form_errors)
:permissions (map #(-> [(utils/db-field-to-verbose-name %) %]) permissions)}))))
(defn profile-page [request]
(render (auth-templates/profile (base-context-authenticated-access request))))
(defn manage-users-page [request]
(render (auth-templates/manage-users (merge
(base-context-authenticated-access request)
{:user_list (db/get-user-list {:email (-> request :identity :email)})}))))
(defn modify-user [request id field value]
(let [return-fn (partial perform-action-and-redirect "/manage-users")
is_user (not (:admin (db/get-user {:id-field "id" :id-value id :cols ["admin"]})))]
(cond
(and (= field "role") is_user) (return-fn #(db/update-user {:id-field "id" :id-value id :col "admin" :value (= value "admin")}) {:class "success" :message "User role changed succesfully!"})
(and (= field "is_active") is_user) (return-fn #(db/update-user {:id-field "id" :id-value id :col "is_active" :value false}) {:class "success" :message "User deleted successfully!"})
:else
(return-fn nil {:class "danger" :message "Invalid action"}))))
(defn change-permissions-page [request id]
(let [is_admin (:admin (db/get-user {:id-field "id" :id-value id :cols ["admin"]}))
user_perms (for [perm (db/get-user-permissions {:user_id id})] (:codename perm))]
(if (or is_admin (nil? is_admin))
(error-page {:status 404 :title "Not found"})
(render (auth-templates/change-permissions (merge
(base-context-authenticated-access request)
{:user_id id
:current_perms (map #(-> [(utils/db-field-to-verbose-name %) %]) user_perms)
:new_perms (map #(-> [(utils/db-field-to-verbose-name %) %]) (filter #(empty? (some #{%} user_perms)) permissions))}))))))
(defn reset-password [request id]
(let [user (db/get-user {:cols ["email" "admin"] :id-field "id" :id-value id})]
(if (or (:admin user) (nil? user))
(error-page {:status 404 :title "Not found"})
(let [password (auth/generate-random-password 8)]
(db/update-user {:id-field "id" :id-value id :col "password" :value (auth/encrypt-password password)})
(render (auth-templates/reset-password (merge
(base-context-authenticated-access request)
{:alerts [{:class "success" :message "Password reset successfully"}]
:email (:email user)
:password password})))))))
(defn change-password [request]
(let [form (validators/validate-change-password-form (:params request))]
(let [valid_form (and
(utils/valid? form)
(validators/validate-change-password (:params request) (:password (db/get-user {:cols ["password"] :id-field "id" :id-value (-> request :identity :id)}))))]
(if valid_form (db/update-user {:id-field "id" :id-value (str (-> request :identity :id)) :col "password" :value (auth/encrypt-password (-> request :params :new_password))}))
(render (auth-templates/profile (merge
(base-context-authenticated-access request)
{:alerts [{:class (if valid_form "success" "danger") :message (if valid_form "Password updated successfully" "Invalid")}]
:errors (utils/get-errors form)}))))))
(defn add-permissions-to-user [user_id perms]
(doall (for [perm (if (= java.lang.String (type perms)) [perms] perms)]
(db/insert-user-perms {:user_id user_id
:codename perm}))))
(defn remove-permissions-from-user [user_id perms]
(doall (for [perm (if (= java.lang.String (type perms)) [perms] perms)]
(db/delete-user-perms {:user_id user_id
:codename perm}))))
(defn change-permissions [request id action]
(cond
(= action "add") (perform-action-and-redirect (str "/change-permissions/" id) #(add-permissions-to-user id (-> request :params :perms)) {:class "success" :message "Permissions added successfully!"})
(= action "remove") (perform-action-and-redirect (str "/change-permissions/" id) #(remove-permissions-from-user id (-> request :params :perms)) {:class "success" :message "Permissions removed successfully!"})
:else
(error-page {:status 404 :title "Not found"})))
(defn create-user [details perms]
(db/create-user details)
(if-not (:admin details)
(add-permissions-to-user (:id (db/get-user {:id-field "email" :id-value (:email details) :cols ["id"]})) perms)))
(defn register-user [request]
(let [user (validators/validate-user-register (:params request))
valid_user_perms (validators/valid-user-perms? (:params request))]
(if (and (utils/valid? user) valid_user_perms)
(let [user-fields (last user)]
(let [password (auth/generate-random-password 8)
unique (empty? (db/get-user {:id-field "email" :id-value (:email user-fields) :cols ["id"]}))]
(if unique
(create-user (merge user-fields {:password (auth/encrypt-password password)
:admin (= "Admin" (:role user-fields))
:is_active true})
(:permissions user-fields)))
(render ((if unique auth-templates/register-success auth-templates/register)
(merge (base-context-authenticated-access request)
{:alerts [{:class (if unique "success" "danger") :message (if unique "User registerd successfully" "A user with this email already exists")}]
:email (:email user-fields)
:password password})))))
(-> (redirect "/register")
(assoc-in [:flash :form_errors] (merge
{:permissions (if-not valid_user_perms ["Please select alteast one permission"] [])}
(utils/get-errors user)))))))
(defn login-user [request next]
(let [cleaned-user (validators/validate-user-login (:params request))]
(if (utils/valid? cleaned-user)
(let [user (db/get-user {:id-field "email" :id-value (:email (last cleaned-user)) :cols ["id" "email" "first_name" "last_name" "is_active" "password" "admin"]})
password-match (hashers/check (:password (last cleaned-user)) (:password user))]
(if (and user password-match (:is_active user))
(-> (redirect (if (clojure.string/blank? next) "/" next))
(assoc-in [:session :identity] (merge (select-keys user [:id :email :admin :first_name :last_name])
{:permissions (for [perm (db/get-user-permissions {:user_id (:id user)})] (:codename perm))})))
(-> (redirect (str "/login?next=" next))
(assoc-in [:flash :alerts] [{:class "danger" :message (if password-match "User has been deactivated" "Invalid email/password" )}]))))
(-> (redirect (str "/login?next=" next))
(assoc-in [:flash :form_errors] (utils/get-errors cleaned-user))))))
(defn logout [request]
(-> (redirect "/login")
(assoc :session {})
(assoc-in [:flash :alerts] [{:class "success" :message "Logged out successfully!"}])))
(defroutes auth-routes
(POST "/login" [next :as r] (login-user r next))
(GET "/register" [] register-page)
(POST "/register" [] register-user)
(GET "/logout" [] logout)
(GET "/profile" [] profile-page)
(GET "/manage-users" [] manage-users-page)
(GET "/reset-password/:id{[0-9]+}" [id :as r] (reset-password r id))
(GET "/modify-user/:id{[0-9]+}/:field{[a-z_]+}/:value{[0-9a-zA-Z]+}" [id field value :as r] (modify-user r id field value))
(POST "/change-password" [] change-password)
(GET "/change-permissions/:id{[0-9]+}" [id :as r] (change-permissions-page r id))
(POST "/change-permissions/:id{[0-9]+}/:action{(add|remove)}" [id action :as r] (change-permissions r id action))
(GET "/login" [next :as r] (login-page r next)))
| 37919 | (ns sltapp.routes.auth
(:require [sltapp.layout :refer [render base-context-authenticated-access base-context-any-access error-page]]
[compojure.core :refer [defroutes GET POST]]
[sltapp.utils :refer [get-next-url perform-action-and-redirect]]
[ring.util.response :refer [redirect]]
[sltapp.db.core :as db]
[sltapp.constants :refer [permissions]]
[sltapp.validators :as validators]
[sltapp.utils :as utils]
[sltapp.service.auth :as auth]
[sltapp.templates.auth :as auth-templates]
[buddy.hashers :as hashers]
[clojure.java.io :as io]))
(defn login-page [request next]
(if (-> request :identity :id)
(redirect "/")
(render (auth-templates/login (merge
(base-context-any-access request)
{:next next
:errors (-> request :flash :form_errors)})))))
(defn register-page [request]
(render (auth-templates/register (merge
(base-context-authenticated-access request)
{:errors (-> request :flash :form_errors)
:permissions (map #(-> [(utils/db-field-to-verbose-name %) %]) permissions)}))))
(defn profile-page [request]
(render (auth-templates/profile (base-context-authenticated-access request))))
(defn manage-users-page [request]
(render (auth-templates/manage-users (merge
(base-context-authenticated-access request)
{:user_list (db/get-user-list {:email (-> request :identity :email)})}))))
(defn modify-user [request id field value]
(let [return-fn (partial perform-action-and-redirect "/manage-users")
is_user (not (:admin (db/get-user {:id-field "id" :id-value id :cols ["admin"]})))]
(cond
(and (= field "role") is_user) (return-fn #(db/update-user {:id-field "id" :id-value id :col "admin" :value (= value "admin")}) {:class "success" :message "User role changed succesfully!"})
(and (= field "is_active") is_user) (return-fn #(db/update-user {:id-field "id" :id-value id :col "is_active" :value false}) {:class "success" :message "User deleted successfully!"})
:else
(return-fn nil {:class "danger" :message "Invalid action"}))))
(defn change-permissions-page [request id]
(let [is_admin (:admin (db/get-user {:id-field "id" :id-value id :cols ["admin"]}))
user_perms (for [perm (db/get-user-permissions {:user_id id})] (:codename perm))]
(if (or is_admin (nil? is_admin))
(error-page {:status 404 :title "Not found"})
(render (auth-templates/change-permissions (merge
(base-context-authenticated-access request)
{:user_id id
:current_perms (map #(-> [(utils/db-field-to-verbose-name %) %]) user_perms)
:new_perms (map #(-> [(utils/db-field-to-verbose-name %) %]) (filter #(empty? (some #{%} user_perms)) permissions))}))))))
(defn reset-password [request id]
(let [user (db/get-user {:cols ["email" "admin"] :id-field "id" :id-value id})]
(if (or (:admin user) (nil? user))
(error-page {:status 404 :title "Not found"})
(let [password (auth/generate-random-password 8)]
(db/update-user {:id-field "id" :id-value id :col "password" :value (auth/encrypt-password password)})
(render (auth-templates/reset-password (merge
(base-context-authenticated-access request)
{:alerts [{:class "success" :message "Password reset successfully"}]
:email (:email user)
:password <PASSWORD>})))))))
(defn change-password [request]
(let [form (validators/validate-change-password-form (:params request))]
(let [valid_form (and
(utils/valid? form)
(validators/validate-change-password (:params request) (:password (db/get-user {:cols ["password"] :id-field "id" :id-value (-> request :identity :id)}))))]
(if valid_form (db/update-user {:id-field "id" :id-value (str (-> request :identity :id)) :col "password" :value (auth/encrypt-password (-> request :params :new_password))}))
(render (auth-templates/profile (merge
(base-context-authenticated-access request)
{:alerts [{:class (if valid_form "success" "danger") :message (if valid_form "Password updated successfully" "Invalid")}]
:errors (utils/get-errors form)}))))))
(defn add-permissions-to-user [user_id perms]
(doall (for [perm (if (= java.lang.String (type perms)) [perms] perms)]
(db/insert-user-perms {:user_id user_id
:codename perm}))))
(defn remove-permissions-from-user [user_id perms]
(doall (for [perm (if (= java.lang.String (type perms)) [perms] perms)]
(db/delete-user-perms {:user_id user_id
:codename perm}))))
(defn change-permissions [request id action]
(cond
(= action "add") (perform-action-and-redirect (str "/change-permissions/" id) #(add-permissions-to-user id (-> request :params :perms)) {:class "success" :message "Permissions added successfully!"})
(= action "remove") (perform-action-and-redirect (str "/change-permissions/" id) #(remove-permissions-from-user id (-> request :params :perms)) {:class "success" :message "Permissions removed successfully!"})
:else
(error-page {:status 404 :title "Not found"})))
(defn create-user [details perms]
(db/create-user details)
(if-not (:admin details)
(add-permissions-to-user (:id (db/get-user {:id-field "email" :id-value (:email details) :cols ["id"]})) perms)))
(defn register-user [request]
(let [user (validators/validate-user-register (:params request))
valid_user_perms (validators/valid-user-perms? (:params request))]
(if (and (utils/valid? user) valid_user_perms)
(let [user-fields (last user)]
(let [password (<PASSWORD>/<PASSWORD>-password <PASSWORD>)
unique (empty? (db/get-user {:id-field "email" :id-value (:email user-fields) :cols ["id"]}))]
(if unique
(create-user (merge user-fields {:password (auth/encrypt-password password)
:admin (= "Admin" (:role user-fields))
:is_active true})
(:permissions user-fields)))
(render ((if unique auth-templates/register-success auth-templates/register)
(merge (base-context-authenticated-access request)
{:alerts [{:class (if unique "success" "danger") :message (if unique "User registerd successfully" "A user with this email already exists")}]
:email (:email user-fields)
:password <PASSWORD>})))))
(-> (redirect "/register")
(assoc-in [:flash :form_errors] (merge
{:permissions (if-not valid_user_perms ["Please select alteast one permission"] [])}
(utils/get-errors user)))))))
(defn login-user [request next]
(let [cleaned-user (validators/validate-user-login (:params request))]
(if (utils/valid? cleaned-user)
(let [user (db/get-user {:id-field "email" :id-value (:email (last cleaned-user)) :cols ["id" "email" "first_name" "last_name" "is_active" "password" "<PASSWORD>"]})
password-match (hashers/check (:password (last cleaned-user)) (:password user))]
(if (and user password-match (:is_active user))
(-> (redirect (if (clojure.string/blank? next) "/" next))
(assoc-in [:session :identity] (merge (select-keys user [:id :email :admin :first_name :last_name])
{:permissions (for [perm (db/get-user-permissions {:user_id (:id user)})] (:codename perm))})))
(-> (redirect (str "/login?next=" next))
(assoc-in [:flash :alerts] [{:class "danger" :message (if password-match "User has been deactivated" "Invalid email/password" )}]))))
(-> (redirect (str "/login?next=" next))
(assoc-in [:flash :form_errors] (utils/get-errors cleaned-user))))))
(defn logout [request]
(-> (redirect "/login")
(assoc :session {})
(assoc-in [:flash :alerts] [{:class "success" :message "Logged out successfully!"}])))
(defroutes auth-routes
(POST "/login" [next :as r] (login-user r next))
(GET "/register" [] register-page)
(POST "/register" [] register-user)
(GET "/logout" [] logout)
(GET "/profile" [] profile-page)
(GET "/manage-users" [] manage-users-page)
(GET "/reset-password/:id{[0-9]+}" [id :as r] (reset-password r id))
(GET "/modify-user/:id{[0-9]+}/:field{[a-z_]+}/:value{[0-9a-zA-Z]+}" [id field value :as r] (modify-user r id field value))
(POST "/change-password" [] change-password)
(GET "/change-permissions/:id{[0-9]+}" [id :as r] (change-permissions-page r id))
(POST "/change-permissions/:id{[0-9]+}/:action{(add|remove)}" [id action :as r] (change-permissions r id action))
(GET "/login" [next :as r] (login-page r next)))
| true | (ns sltapp.routes.auth
(:require [sltapp.layout :refer [render base-context-authenticated-access base-context-any-access error-page]]
[compojure.core :refer [defroutes GET POST]]
[sltapp.utils :refer [get-next-url perform-action-and-redirect]]
[ring.util.response :refer [redirect]]
[sltapp.db.core :as db]
[sltapp.constants :refer [permissions]]
[sltapp.validators :as validators]
[sltapp.utils :as utils]
[sltapp.service.auth :as auth]
[sltapp.templates.auth :as auth-templates]
[buddy.hashers :as hashers]
[clojure.java.io :as io]))
(defn login-page [request next]
(if (-> request :identity :id)
(redirect "/")
(render (auth-templates/login (merge
(base-context-any-access request)
{:next next
:errors (-> request :flash :form_errors)})))))
(defn register-page [request]
(render (auth-templates/register (merge
(base-context-authenticated-access request)
{:errors (-> request :flash :form_errors)
:permissions (map #(-> [(utils/db-field-to-verbose-name %) %]) permissions)}))))
(defn profile-page [request]
(render (auth-templates/profile (base-context-authenticated-access request))))
(defn manage-users-page [request]
(render (auth-templates/manage-users (merge
(base-context-authenticated-access request)
{:user_list (db/get-user-list {:email (-> request :identity :email)})}))))
(defn modify-user [request id field value]
(let [return-fn (partial perform-action-and-redirect "/manage-users")
is_user (not (:admin (db/get-user {:id-field "id" :id-value id :cols ["admin"]})))]
(cond
(and (= field "role") is_user) (return-fn #(db/update-user {:id-field "id" :id-value id :col "admin" :value (= value "admin")}) {:class "success" :message "User role changed succesfully!"})
(and (= field "is_active") is_user) (return-fn #(db/update-user {:id-field "id" :id-value id :col "is_active" :value false}) {:class "success" :message "User deleted successfully!"})
:else
(return-fn nil {:class "danger" :message "Invalid action"}))))
(defn change-permissions-page [request id]
(let [is_admin (:admin (db/get-user {:id-field "id" :id-value id :cols ["admin"]}))
user_perms (for [perm (db/get-user-permissions {:user_id id})] (:codename perm))]
(if (or is_admin (nil? is_admin))
(error-page {:status 404 :title "Not found"})
(render (auth-templates/change-permissions (merge
(base-context-authenticated-access request)
{:user_id id
:current_perms (map #(-> [(utils/db-field-to-verbose-name %) %]) user_perms)
:new_perms (map #(-> [(utils/db-field-to-verbose-name %) %]) (filter #(empty? (some #{%} user_perms)) permissions))}))))))
(defn reset-password [request id]
(let [user (db/get-user {:cols ["email" "admin"] :id-field "id" :id-value id})]
(if (or (:admin user) (nil? user))
(error-page {:status 404 :title "Not found"})
(let [password (auth/generate-random-password 8)]
(db/update-user {:id-field "id" :id-value id :col "password" :value (auth/encrypt-password password)})
(render (auth-templates/reset-password (merge
(base-context-authenticated-access request)
{:alerts [{:class "success" :message "Password reset successfully"}]
:email (:email user)
:password PI:PASSWORD:<PASSWORD>END_PI})))))))
(defn change-password [request]
(let [form (validators/validate-change-password-form (:params request))]
(let [valid_form (and
(utils/valid? form)
(validators/validate-change-password (:params request) (:password (db/get-user {:cols ["password"] :id-field "id" :id-value (-> request :identity :id)}))))]
(if valid_form (db/update-user {:id-field "id" :id-value (str (-> request :identity :id)) :col "password" :value (auth/encrypt-password (-> request :params :new_password))}))
(render (auth-templates/profile (merge
(base-context-authenticated-access request)
{:alerts [{:class (if valid_form "success" "danger") :message (if valid_form "Password updated successfully" "Invalid")}]
:errors (utils/get-errors form)}))))))
(defn add-permissions-to-user [user_id perms]
(doall (for [perm (if (= java.lang.String (type perms)) [perms] perms)]
(db/insert-user-perms {:user_id user_id
:codename perm}))))
(defn remove-permissions-from-user [user_id perms]
(doall (for [perm (if (= java.lang.String (type perms)) [perms] perms)]
(db/delete-user-perms {:user_id user_id
:codename perm}))))
(defn change-permissions [request id action]
(cond
(= action "add") (perform-action-and-redirect (str "/change-permissions/" id) #(add-permissions-to-user id (-> request :params :perms)) {:class "success" :message "Permissions added successfully!"})
(= action "remove") (perform-action-and-redirect (str "/change-permissions/" id) #(remove-permissions-from-user id (-> request :params :perms)) {:class "success" :message "Permissions removed successfully!"})
:else
(error-page {:status 404 :title "Not found"})))
(defn create-user [details perms]
(db/create-user details)
(if-not (:admin details)
(add-permissions-to-user (:id (db/get-user {:id-field "email" :id-value (:email details) :cols ["id"]})) perms)))
(defn register-user [request]
(let [user (validators/validate-user-register (:params request))
valid_user_perms (validators/valid-user-perms? (:params request))]
(if (and (utils/valid? user) valid_user_perms)
(let [user-fields (last user)]
(let [password (PI:PASSWORD:<PASSWORD>END_PI/PI:PASSWORD:<PASSWORD>END_PI-password PI:PASSWORD:<PASSWORD>END_PI)
unique (empty? (db/get-user {:id-field "email" :id-value (:email user-fields) :cols ["id"]}))]
(if unique
(create-user (merge user-fields {:password (auth/encrypt-password password)
:admin (= "Admin" (:role user-fields))
:is_active true})
(:permissions user-fields)))
(render ((if unique auth-templates/register-success auth-templates/register)
(merge (base-context-authenticated-access request)
{:alerts [{:class (if unique "success" "danger") :message (if unique "User registerd successfully" "A user with this email already exists")}]
:email (:email user-fields)
:password PI:PASSWORD:<PASSWORD>END_PI})))))
(-> (redirect "/register")
(assoc-in [:flash :form_errors] (merge
{:permissions (if-not valid_user_perms ["Please select alteast one permission"] [])}
(utils/get-errors user)))))))
(defn login-user [request next]
(let [cleaned-user (validators/validate-user-login (:params request))]
(if (utils/valid? cleaned-user)
(let [user (db/get-user {:id-field "email" :id-value (:email (last cleaned-user)) :cols ["id" "email" "first_name" "last_name" "is_active" "password" "PI:PASSWORD:<PASSWORD>END_PI"]})
password-match (hashers/check (:password (last cleaned-user)) (:password user))]
(if (and user password-match (:is_active user))
(-> (redirect (if (clojure.string/blank? next) "/" next))
(assoc-in [:session :identity] (merge (select-keys user [:id :email :admin :first_name :last_name])
{:permissions (for [perm (db/get-user-permissions {:user_id (:id user)})] (:codename perm))})))
(-> (redirect (str "/login?next=" next))
(assoc-in [:flash :alerts] [{:class "danger" :message (if password-match "User has been deactivated" "Invalid email/password" )}]))))
(-> (redirect (str "/login?next=" next))
(assoc-in [:flash :form_errors] (utils/get-errors cleaned-user))))))
(defn logout [request]
(-> (redirect "/login")
(assoc :session {})
(assoc-in [:flash :alerts] [{:class "success" :message "Logged out successfully!"}])))
(defroutes auth-routes
(POST "/login" [next :as r] (login-user r next))
(GET "/register" [] register-page)
(POST "/register" [] register-user)
(GET "/logout" [] logout)
(GET "/profile" [] profile-page)
(GET "/manage-users" [] manage-users-page)
(GET "/reset-password/:id{[0-9]+}" [id :as r] (reset-password r id))
(GET "/modify-user/:id{[0-9]+}/:field{[a-z_]+}/:value{[0-9a-zA-Z]+}" [id field value :as r] (modify-user r id field value))
(POST "/change-password" [] change-password)
(GET "/change-permissions/:id{[0-9]+}" [id :as r] (change-permissions-page r id))
(POST "/change-permissions/:id{[0-9]+}/:action{(add|remove)}" [id action :as r] (change-permissions r id action))
(GET "/login" [next :as r] (login-page r next)))
|
[
{
"context": "o worlds are better than one\"\n (= [\"Real Jerry\" \"Bizarro Jerry\"]\n (do\n (dosync\n (ref-set ",
"end": 1014,
"score": 0.8541180491447449,
"start": 1001,
"tag": "NAME",
"value": "Bizarro Jerry"
},
{
"context": "})\n (alter the-world assoc :jerry \"Real Jerry\")\n (alter bizarro-world assoc :jerry \"Bi",
"end": 1129,
"score": 0.5611279606819153,
"start": 1125,
"tag": "NAME",
"value": "erry"
},
{
"context": "ry\")\n (alter bizarro-world assoc :jerry \"Bizarro Jerry\")\n (vec (map #(:jerry %) (list @the-world",
"end": 1190,
"score": 0.9240649938583374,
"start": 1177,
"tag": "NAME",
"value": "Bizarro Jerry"
}
] | clojure-koans/16_refs.clj | CKamadev/clojure-exercises | 0 | (ns koans.16-refs
(:require [koan-engine.core :refer :all]))
(def the-world (ref "hello"))
(def bizarro-world (ref {}))
(meditations
"In the beginning, there was a word"
(= "hello" (deref the-world))
"You can get the word more succinctly, but it's the same"
(= "hello" @the-world)
"You can be the change you wish to see in the world."
(= "better" (do
(dosync (ref-set the-world "better"))
@the-world))
"Alter where you need not replace"
(= "better!!!" (let [exclamator (fn [x] (str x "!"))]
(dosync
(alter the-world exclamator)
(alter the-world exclamator)
(alter the-world exclamator))
@the-world))
"Don't forget to do your work in a transaction!"
(= 0 (do
(dosync (ref-set the-world 0))
@the-world))
"Functions passed to alter may depend on the data in the ref"
(= 20 (do
(dosync (alter the-world + 20))))
"Two worlds are better than one"
(= ["Real Jerry" "Bizarro Jerry"]
(do
(dosync
(ref-set the-world {})
(alter the-world assoc :jerry "Real Jerry")
(alter bizarro-world assoc :jerry "Bizarro Jerry")
(vec (map #(:jerry %) (list @the-world @bizarro-world)))))))
| 91883 | (ns koans.16-refs
(:require [koan-engine.core :refer :all]))
(def the-world (ref "hello"))
(def bizarro-world (ref {}))
(meditations
"In the beginning, there was a word"
(= "hello" (deref the-world))
"You can get the word more succinctly, but it's the same"
(= "hello" @the-world)
"You can be the change you wish to see in the world."
(= "better" (do
(dosync (ref-set the-world "better"))
@the-world))
"Alter where you need not replace"
(= "better!!!" (let [exclamator (fn [x] (str x "!"))]
(dosync
(alter the-world exclamator)
(alter the-world exclamator)
(alter the-world exclamator))
@the-world))
"Don't forget to do your work in a transaction!"
(= 0 (do
(dosync (ref-set the-world 0))
@the-world))
"Functions passed to alter may depend on the data in the ref"
(= 20 (do
(dosync (alter the-world + 20))))
"Two worlds are better than one"
(= ["Real Jerry" "<NAME>"]
(do
(dosync
(ref-set the-world {})
(alter the-world assoc :jerry "Real J<NAME>")
(alter bizarro-world assoc :jerry "<NAME>")
(vec (map #(:jerry %) (list @the-world @bizarro-world)))))))
| true | (ns koans.16-refs
(:require [koan-engine.core :refer :all]))
(def the-world (ref "hello"))
(def bizarro-world (ref {}))
(meditations
"In the beginning, there was a word"
(= "hello" (deref the-world))
"You can get the word more succinctly, but it's the same"
(= "hello" @the-world)
"You can be the change you wish to see in the world."
(= "better" (do
(dosync (ref-set the-world "better"))
@the-world))
"Alter where you need not replace"
(= "better!!!" (let [exclamator (fn [x] (str x "!"))]
(dosync
(alter the-world exclamator)
(alter the-world exclamator)
(alter the-world exclamator))
@the-world))
"Don't forget to do your work in a transaction!"
(= 0 (do
(dosync (ref-set the-world 0))
@the-world))
"Functions passed to alter may depend on the data in the ref"
(= 20 (do
(dosync (alter the-world + 20))))
"Two worlds are better than one"
(= ["Real Jerry" "PI:NAME:<NAME>END_PI"]
(do
(dosync
(ref-set the-world {})
(alter the-world assoc :jerry "Real JPI:NAME:<NAME>END_PI")
(alter bizarro-world assoc :jerry "PI:NAME:<NAME>END_PI")
(vec (map #(:jerry %) (list @the-world @bizarro-world)))))))
|
[
{
"context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio",
"end": 29,
"score": 0.9998223185539246,
"start": 18,
"tag": "NAME",
"value": "Rich Hickey"
}
] | ext/clojure-clojurescript-bef56a7/src/clj/cljs/core.clj | yokolet/clementine | 35 | ; Copyright (c) Rich Hickey. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns cljs.core
(:refer-clojure :exclude [-> ->> .. amap and areduce alength aclone assert binding bound-fn case comment cond condp
declare definline definterface defmethod defmulti defn defn- defonce
defprotocol defrecord defstruct deftype delay destructure doseq dosync dotimes doto
extend-protocol extend-type fn for future gen-class gen-interface
if-let if-not import io! lazy-cat lazy-seq let letfn locking loop
memfn ns or proxy proxy-super pvalues refer-clojure reify sync time
when when-first when-let when-not while with-bindings with-in-str
with-loading-context with-local-vars with-open with-out-str with-precision with-redefs
satisfies? identical? true? false? nil? str get
aget aset
+ - * / < <= > >= == zero? pos? neg? inc dec max min mod
bit-and bit-and-not bit-clear bit-flip bit-not bit-or bit-set
bit-test bit-shift-left bit-shift-right bit-xor])
(:require clojure.walk))
(alias 'core 'clojure.core)
(defmacro import-macros [ns [& vars]]
(core/let [ns (find-ns ns)
vars (map #(ns-resolve ns %) vars)
syms (map (core/fn [^clojure.lang.Var v] (core/-> v .sym (with-meta {:macro true}))) vars)
defs (map (core/fn [sym var]
`(def ~sym (deref ~var))) syms vars)]
`(do ~@defs
:imported)))
(import-macros clojure.core
[-> ->> .. and assert comment cond
declare defn defn-
doto
extend-protocol fn for
if-let if-not letfn
memfn or
when when-first when-let when-not while])
(defmacro ^{:private true} assert-args [fnname & pairs]
`(do (when-not ~(first pairs)
(throw (IllegalArgumentException.
~(core/str fnname " requires " (second pairs)))))
~(core/let [more (nnext pairs)]
(when more
(list* `assert-args fnname more)))))
(defn destructure [bindings]
(core/let [bents (partition 2 bindings)
pb (fn pb [bvec b v]
(core/let [pvec
(fn [bvec b val]
(core/let [gvec (gensym "vec__")]
(core/loop [ret (-> bvec (conj gvec) (conj val))
n 0
bs b
seen-rest? false]
(if (seq bs)
(core/let [firstb (first bs)]
(cond
(= firstb '&) (recur (pb ret (second bs) (list `nthnext gvec n))
n
(nnext bs)
true)
(= firstb :as) (pb ret (second bs) gvec)
:else (if seen-rest?
(throw (new Exception "Unsupported binding form, only :as can follow & parameter"))
(recur (pb ret firstb (list `nth gvec n nil))
(core/inc n)
(next bs)
seen-rest?))))
ret))))
pmap
(fn [bvec b v]
(core/let [gmap (gensym "map__")
defaults (:or b)]
(core/loop [ret (-> bvec (conj gmap) (conj v)
(conj gmap) (conj `(if (seq? ~gmap) (apply hash-map ~gmap) ~gmap))
((fn [ret]
(if (:as b)
(conj ret (:as b) gmap)
ret))))
bes (reduce
(fn [bes entry]
(reduce #(assoc %1 %2 ((val entry) %2))
(dissoc bes (key entry))
((key entry) bes)))
(dissoc b :as :or)
{:keys #(keyword (core/str %)), :strs core/str, :syms #(list `quote %)})]
(if (seq bes)
(core/let [bb (key (first bes))
bk (val (first bes))
has-default (contains? defaults bb)]
(recur (pb ret bb (if has-default
(list `get gmap bk (defaults bb))
(list `get gmap bk)))
(next bes)))
ret))))]
(cond
(symbol? b) (-> bvec (conj b) (conj v))
(vector? b) (pvec bvec b v)
(map? b) (pmap bvec b v)
:else (throw (new Exception (core/str "Unsupported binding form: " b))))))
process-entry (fn [bvec b] (pb bvec (first b) (second b)))]
(if (every? symbol? (map first bents))
bindings
(reduce process-entry [] bents))))
(defmacro let
"binding => binding-form init-expr
Evaluates the exprs in a lexical context in which the symbols in
the binding-forms are bound to their respective init-exprs or parts
therein."
[bindings & body]
(assert-args
(vector? bindings) "a vector for its binding"
(even? (count bindings)) "an even number of forms in binding vector")
`(let* ~(destructure bindings) ~@body))
(defmacro loop
"Evaluates the exprs in a lexical context in which the symbols in
the binding-forms are bound to their respective init-exprs or parts
therein. Acts as a recur target."
[bindings & body]
(assert-args
(vector? bindings) "a vector for its binding"
(even? (count bindings)) "an even number of forms in binding vector")
(let [db (destructure bindings)]
(if (= db bindings)
`(loop* ~bindings ~@body)
(let [vs (take-nth 2 (drop 1 bindings))
bs (take-nth 2 bindings)
gs (map (fn [b] (if (symbol? b) b (gensym))) bs)
bfs (reduce (fn [ret [b v g]]
(if (symbol? b)
(conj ret g v)
(conj ret g v b g)))
[] (map vector bs vs gs))]
`(let ~bfs
(loop* ~(vec (interleave gs gs))
(let ~(vec (interleave bs gs))
~@body)))))))
(def fast-path-protocols
"protocol fqn -> [partition number, bit]"
(zipmap (map #(symbol "cljs.core" (core/str %))
'[IFn ICounted IEmptyableCollection ICollection IIndexed ASeq ISeq INext
ILookup IAssociative IMap IMapEntry ISet IStack IVector IDeref
IDerefWithTimeout IMeta IWithMeta IReduce IKVReduce IEquiv IHash
ISeqable ISequential IList IRecord IReversible ISorted IPrintable IWriter
IPrintWithWriter IPending IWatchable IEditableCollection ITransientCollection
ITransientAssociative ITransientMap ITransientVector ITransientSet
IMultiFn IChunkedSeq IChunkedNext IComparable])
(iterate (fn [[p b]]
(if (core/== 2147483648 b)
[(core/inc p) 1]
[p (core/bit-shift-left b 1)]))
[0 1])))
(def fast-path-protocol-partitions-count
"total number of partitions"
(let [c (count fast-path-protocols)
m (core/mod c 32)]
(if (core/zero? m)
(core/quot c 32)
(core/inc (core/quot c 32)))))
(defmacro str [& xs]
(let [strs (->> (repeat (count xs) "cljs.core.str(~{})")
(interpose ",")
(apply core/str))]
(concat (list 'js* (core/str "[" strs "].join('')")) xs)))
(defn bool-expr [e]
(vary-meta e assoc :tag 'boolean))
(defmacro nil? [x]
`(coercive-= ~x nil))
;; internal - do not use.
(defmacro coercive-not [x]
(bool-expr (list 'js* "(!~{})" x)))
;; internal - do not use.
(defmacro coercive-not= [x y]
(bool-expr (list 'js* "(~{} != ~{})" x y)))
;; internal - do not use.
(defmacro coercive-= [x y]
(bool-expr (list 'js* "(~{} == ~{})" x y)))
(defmacro true? [x]
(bool-expr (list 'js* "~{} === true" x)))
(defmacro false? [x]
(bool-expr (list 'js* "~{} === false" x)))
(defmacro undefined? [x]
(bool-expr (list 'js* "(void 0 === ~{})" x)))
(defmacro identical? [a b]
(bool-expr (list 'js* "(~{} === ~{})" a b)))
(defmacro aget
([a i]
(list 'js* "(~{}[~{}])" a i))
([a i & idxs]
(let [astr (apply core/str (repeat (count idxs) "[~{}]"))]
`(~'js* ~(core/str "(~{}[~{}]" astr ")") ~a ~i ~@idxs))))
(defmacro aset [a i v]
(list 'js* "(~{}[~{}] = ~{})" a i v))
(defmacro +
([] 0)
([x] x)
([x y] (list 'js* "(~{} + ~{})" x y))
([x y & more] `(+ (+ ~x ~y) ~@more)))
(defmacro -
([x] (list 'js* "(- ~{})" x))
([x y] (list 'js* "(~{} - ~{})" x y))
([x y & more] `(- (- ~x ~y) ~@more)))
(defmacro *
([] 1)
([x] x)
([x y] (list 'js* "(~{} * ~{})" x y))
([x y & more] `(* (* ~x ~y) ~@more)))
(defmacro /
([x] `(/ 1 ~x))
([x y] (list 'js* "(~{} / ~{})" x y))
([x y & more] `(/ (/ ~x ~y) ~@more)))
(defmacro <
([x] true)
([x y] (bool-expr (list 'js* "(~{} < ~{})" x y)))
([x y & more] `(and (< ~x ~y) (< ~y ~@more))))
(defmacro <=
([x] true)
([x y] (bool-expr (list 'js* "(~{} <= ~{})" x y)))
([x y & more] `(and (<= ~x ~y) (<= ~y ~@more))))
(defmacro >
([x] true)
([x y] (bool-expr (list 'js* "(~{} > ~{})" x y)))
([x y & more] `(and (> ~x ~y) (> ~y ~@more))))
(defmacro >=
([x] true)
([x y] (bool-expr (list 'js* "(~{} >= ~{})" x y)))
([x y & more] `(and (>= ~x ~y) (>= ~y ~@more))))
(defmacro ==
([x] true)
([x y] (bool-expr (list 'js* "(~{} === ~{})" x y)))
([x y & more] `(and (== ~x ~y) (== ~y ~@more))))
(defmacro dec [x]
`(- ~x 1))
(defmacro inc [x]
`(+ ~x 1))
(defmacro zero? [x]
`(== ~x 0))
(defmacro pos? [x]
`(> ~x 0))
(defmacro neg? [x]
`(< ~x 0))
(defmacro max
([x] x)
([x y] (list 'js* "((~{} > ~{}) ? ~{} : ~{})" x y x y))
([x y & more] `(max (max ~x ~y) ~@more)))
(defmacro min
([x] x)
([x y] (list 'js* "((~{} < ~{}) ? ~{} : ~{})" x y x y))
([x y & more] `(min (min ~x ~y) ~@more)))
(defmacro mod [num div]
(list 'js* "(~{} % ~{})" num div))
(defmacro bit-not [x]
(list 'js* "(~ ~{})" x))
(defmacro bit-and
([x y] (list 'js* "(~{} & ~{})" x y))
([x y & more] `(bit-and (bit-and ~x ~y) ~@more)))
;; internal do not use
(defmacro unsafe-bit-and
([x y] (bool-expr (list 'js* "(~{} & ~{})" x y)))
([x y & more] `(unsafe-bit-and (unsafe-bit-and ~x ~y) ~@more)))
(defmacro bit-or
([x y] (list 'js* "(~{} | ~{})" x y))
([x y & more] `(bit-or (bit-or ~x ~y) ~@more)))
(defmacro bit-xor
([x y] (list 'js* "(~{} ^ ~{})" x y))
([x y & more] `(bit-xor (bit-xor ~x ~y) ~@more)))
(defmacro bit-and-not
([x y] (list 'js* "(~{} & ~~{})" x y))
([x y & more] `(bit-and-not (bit-and-not ~x ~y) ~@more)))
(defmacro bit-clear [x n]
(list 'js* "(~{} & ~(1 << ~{}))" x n))
(defmacro bit-flip [x n]
(list 'js* "(~{} ^ (1 << ~{}))" x n))
(defmacro bit-test [x n]
(list 'js* "((~{} & (1 << ~{})) != 0)" x n))
(defmacro bit-shift-left [x n]
(list 'js* "(~{} << ~{})" x n))
(defmacro bit-shift-right [x n]
(list 'js* "(~{} >> ~{})" x n))
(defmacro bit-shift-right-zero-fill [x n]
(list 'js* "(~{} >>> ~{})" x n))
(defmacro bit-set [x n]
(list 'js* "(~{} | (1 << ~{}))" x n))
;; internal
(defmacro mask [hash shift]
(list 'js* "((~{} >>> ~{}) & 0x01f)" hash shift))
;; internal
(defmacro bitpos [hash shift]
(list 'js* "(1 << ~{})" `(mask ~hash ~shift)))
;; internal
(defmacro caching-hash [coll hash-fn hash-key]
`(let [h# ~hash-key]
(if-not (nil? h#)
h#
(let [h# (~hash-fn ~coll)]
(set! ~hash-key h#)
h#))))
(defmacro get
([coll k]
`(-lookup ~coll ~k nil))
([coll k not-found]
`(-lookup ~coll ~k ~not-found)))
;;; internal -- reducers-related macros
(defn- do-curried
[name doc meta args body]
(let [cargs (vec (butlast args))]
`(defn ~name ~doc ~meta
(~cargs (fn [x#] (~name ~@cargs x#)))
(~args ~@body))))
(defmacro ^:private defcurried
"Builds another arity of the fn that returns a fn awaiting the last
param"
[name doc meta args & body]
(do-curried name doc meta args body))
(defn- do-rfn [f1 k fkv]
`(fn
([] (~f1))
~(clojure.walk/postwalk
#(if (sequential? %)
((if (vector? %) vec identity)
(core/remove #{k} %))
%)
fkv)
~fkv))
(defmacro ^:private rfn
"Builds 3-arity reducing fn given names of wrapped fn and key, and k/v impl."
[[f1 k] fkv]
(do-rfn f1 k fkv))
;;; end of reducers macros
(defn protocol-prefix [psym]
(core/str (-> (core/str psym) (.replace \. \$) (.replace \/ \$)) "$"))
(def #^:private base-type
{nil "null"
'object "object"
'string "string"
'number "number"
'array "array"
'function "function"
'boolean "boolean"
'default "_"})
(defmacro reify [& impls]
(let [t (gensym "t")
meta-sym (gensym "meta")
this-sym (gensym "_")
locals (keys (:locals &env))
ns (-> &env :ns :name)
munge cljs.compiler/munge
ns-t (list 'js* (core/str (munge ns) "." (munge t)))]
`(do
(when (undefined? ~ns-t)
(deftype ~t [~@locals ~meta-sym]
IWithMeta
(~'-with-meta [~this-sym ~meta-sym]
(new ~t ~@locals ~meta-sym))
IMeta
(~'-meta [~this-sym] ~meta-sym)
~@impls))
(new ~t ~@locals nil))))
(defmacro this-as
"Defines a scope where JavaScript's implicit \"this\" is bound to the name provided."
[name & body]
`(let [~name (~'js* "this")]
~@body))
(defn to-property [sym]
(symbol (core/str "-" sym)))
(defmacro extend-type [tsym & impls]
(let [resolve #(let [ret (:name (cljs.analyzer/resolve-var (dissoc &env :locals) %))]
(assert ret (core/str "Can't resolve: " %))
ret)
impl-map (loop [ret {} s impls]
(if (seq s)
(recur (assoc ret (first s) (take-while seq? (next s)))
(drop-while seq? (next s)))
ret))
warn-if-not-protocol #(when-not (= 'Object %)
(if cljs.analyzer/*cljs-warn-on-undeclared*
(if-let [var (cljs.analyzer/resolve-existing-var (dissoc &env :locals) %)]
(do
(when-not (:protocol-symbol var)
(cljs.analyzer/warning &env
(core/str "WARNING: Symbol " % " is not a protocol")))
(when (and cljs.analyzer/*cljs-warn-protocol-deprecated*
(-> var :deprecated)
(not (-> % meta :deprecation-nowarn)))
(cljs.analyzer/warning &env
(core/str "WARNING: Protocol " % " is deprecated"))))
(cljs.analyzer/warning &env
(core/str "WARNING: Can't resolve protocol symbol " %)))))
skip-flag (set (-> tsym meta :skip-protocol-flag))]
(if (base-type tsym)
(let [t (base-type tsym)
assign-impls (fn [[p sigs]]
(warn-if-not-protocol p)
(let [psym (resolve p)
pfn-prefix (subs (core/str psym) 0 (clojure.core/inc (.indexOf (core/str psym) "/")))]
(cons `(aset ~psym ~t true)
(map (fn [[f & meths :as form]]
`(aset ~(symbol (core/str pfn-prefix f)) ~t ~(with-meta `(fn ~@meths) (meta form))))
sigs))))]
`(do ~@(mapcat assign-impls impl-map)))
(let [t (resolve tsym)
prototype-prefix (fn [sym]
`(.. ~tsym -prototype ~(to-property sym)))
assign-impls (fn [[p sigs]]
(warn-if-not-protocol p)
(let [psym (resolve p)
pprefix (protocol-prefix psym)]
(if (= p 'Object)
(let [adapt-params (fn [[sig & body]]
(let [[tname & args] sig]
(list (vec args) (list* 'this-as (vary-meta tname assoc :tag t) body))))]
(map (fn [[f & meths :as form]]
`(set! ~(prototype-prefix f)
~(with-meta `(fn ~@(map adapt-params meths)) (meta form))))
sigs))
(concat (when-not (skip-flag psym)
[`(set! ~(prototype-prefix pprefix) true)])
(mapcat (fn [[f & meths :as form]]
(if (= psym 'cljs.core/IFn)
(let [adapt-params (fn [[[targ & args :as sig] & body]]
(let [this-sym (with-meta (gensym "this-sym") {:tag t})]
`(~(vec (cons this-sym args))
(this-as ~this-sym
(let [~targ ~this-sym]
~@body)))))
meths (map adapt-params meths)
this-sym (with-meta (gensym "this-sym") {:tag t})
argsym (gensym "args")]
[`(set! ~(prototype-prefix 'call) ~(with-meta `(fn ~@meths) (meta form)))
`(set! ~(prototype-prefix 'apply)
~(with-meta
`(fn ~[this-sym argsym]
(.apply (.-call ~this-sym) ~this-sym
(.concat (array ~this-sym) (aclone ~argsym))))
(meta form)))])
(let [pf (core/str pprefix f)
adapt-params (fn [[[targ & args :as sig] & body]]
(cons (vec (cons (vary-meta targ assoc :tag t) args))
body))]
(if (vector? (first meths))
[`(set! ~(prototype-prefix (core/str pf "$arity$" (count (first meths)))) ~(with-meta `(fn ~@(adapt-params meths)) (meta form)))]
(map (fn [[sig & body :as meth]]
`(set! ~(prototype-prefix (core/str pf "$arity$" (count sig)))
~(with-meta `(fn ~(adapt-params meth)) (meta form))))
meths)))))
sigs)))))]
`(do ~@(mapcat assign-impls impl-map))))))
(defn- prepare-protocol-masks [env t impls]
(let [resolve #(let [ret (:name (cljs.analyzer/resolve-var (dissoc env :locals) %))]
(assert ret (core/str "Can't resolve: " %))
ret)
impl-map (loop [ret {} s impls]
(if (seq s)
(recur (assoc ret (first s) (take-while seq? (next s)))
(drop-while seq? (next s)))
ret))]
(if-let [fpp-pbs (seq (keep fast-path-protocols
(map resolve
(keys impl-map))))]
(let [fpps (into #{} (filter (partial contains? fast-path-protocols)
(map resolve
(keys impl-map))))
fpp-partitions (group-by first fpp-pbs)
fpp-partitions (into {} (map (juxt key (comp (partial map peek) val))
fpp-partitions))
fpp-partitions (into {} (map (juxt key (comp (partial reduce core/bit-or) val))
fpp-partitions))]
[fpps
(reduce (fn [ps p]
(update-in ps [p] (fnil identity 0)))
fpp-partitions
(range fast-path-protocol-partitions-count))]))))
(defn dt->et
([t specs fields] (dt->et t specs fields false))
([t specs fields inline]
(loop [ret [] s specs]
(if (seq s)
(recur (-> ret
(conj (first s))
(into
(reduce (fn [v [f sigs]]
(conj v (vary-meta (cons f (map #(cons (second %) (nnext %)) sigs))
assoc :cljs.analyzer/type t
:cljs.analyzer/fields fields
:protocol-impl true
:protocol-inline inline)))
[]
(group-by first (take-while seq? (next s))))))
(drop-while seq? (next s)))
ret))))
(defn collect-protocols [impls env]
(->> impls
(filter symbol?)
(map #(:name (cljs.analyzer/resolve-var (dissoc env :locals) %)))
(into #{})))
(defmacro deftype [t fields & impls]
(let [r (:name (cljs.analyzer/resolve-var (dissoc &env :locals) t))
[fpps pmasks] (prepare-protocol-masks &env t impls)
protocols (collect-protocols impls &env)
t (vary-meta t assoc
:protocols protocols
:skip-protocol-flag fpps) ]
(if (seq impls)
`(do
(deftype* ~t ~fields ~pmasks)
(set! (.-cljs$lang$type ~t) true)
(set! (.-cljs$lang$ctorPrSeq ~t) (fn [this#] (list ~(core/str r))))
(set! (.-cljs$lang$ctorPrWriter ~t) (fn [this# writer#] (-write writer# ~(core/str r))))
(extend-type ~t ~@(dt->et t impls fields true))
~t)
`(do
(deftype* ~t ~fields ~pmasks)
(set! (.-cljs$lang$type ~t) true)
(set! (.-cljs$lang$ctorPrSeq ~t) (fn [this#] (list ~(core/str r))))
(set! (.-cljs$lang$ctorPrWriter ~t) (fn [this# writer#] (-write writer# ~(core/str r))))
~t))))
(defn- emit-defrecord
"Do not use this directly - use defrecord"
[env tagname rname fields impls]
(let [hinted-fields fields
fields (vec (map #(with-meta % nil) fields))
base-fields fields
fields (conj fields '__meta '__extmap (with-meta '__hash {:mutable true}))]
(let [gs (gensym)
ksym (gensym "k")
impls (concat
impls
['IRecord
'IHash
`(~'-hash [this#] (caching-hash this# ~'hash-imap ~'__hash))
'IEquiv
`(~'-equiv [this# other#]
(if (and other#
(identical? (.-constructor this#)
(.-constructor other#))
(equiv-map this# other#))
true
false))
'IMeta
`(~'-meta [this#] ~'__meta)
'IWithMeta
`(~'-with-meta [this# ~gs] (new ~tagname ~@(replace {'__meta gs} fields)))
'ILookup
`(~'-lookup [this# k#] (-lookup this# k# nil))
`(~'-lookup [this# ~ksym else#]
(cond
~@(mapcat (fn [f] [`(identical? ~ksym ~(keyword f)) f]) base-fields)
:else (get ~'__extmap ~ksym else#)))
'ICounted
`(~'-count [this#] (+ ~(count base-fields) (count ~'__extmap)))
'ICollection
`(~'-conj [this# entry#]
(if (vector? entry#)
(-assoc this# (-nth entry# 0) (-nth entry# 1))
(reduce -conj
this#
entry#)))
'IAssociative
`(~'-assoc [this# k# ~gs]
(condp identical? k#
~@(mapcat (fn [fld]
[(keyword fld) (list* `new tagname (replace {fld gs '__hash nil} fields))])
base-fields)
(new ~tagname ~@(remove #{'__extmap '__hash} fields) (assoc ~'__extmap k# ~gs) nil)))
'IMap
`(~'-dissoc [this# k#] (if (contains? #{~@(map keyword base-fields)} k#)
(dissoc (with-meta (into {} this#) ~'__meta) k#)
(new ~tagname ~@(remove #{'__extmap '__hash} fields)
(not-empty (dissoc ~'__extmap k#))
nil)))
'ISeqable
`(~'-seq [this#] (seq (concat [~@(map #(list `vector (keyword %) %) base-fields)]
~'__extmap)))
'IPrintWithWriter
`(~'-pr-writer [this# writer# opts#]
(let [pr-pair# (fn [keyval#] (pr-sequential-writer writer# pr-writer "" " " "" opts# keyval#))]
(pr-sequential-writer
writer# pr-pair# (core/str "#" ~(name rname) "{") ", " "}" opts#
(concat [~@(map #(list `vector (keyword %) %) base-fields)]
~'__extmap))))
])
[fpps pmasks] (prepare-protocol-masks env tagname impls)
protocols (collect-protocols impls env)
tagname (vary-meta tagname assoc
:protocols protocols
:skip-protocol-flag fpps)]
`(do
(~'defrecord* ~tagname ~hinted-fields ~pmasks)
(extend-type ~tagname ~@(dt->et tagname impls fields true))))))
(defn- build-positional-factory
[rsym rname fields]
(let [fn-name (symbol (core/str '-> rsym))]
`(defn ~fn-name
[~@fields]
(new ~rname ~@fields))))
(defn- build-map-factory
[rsym rname fields]
(let [fn-name (symbol (core/str 'map-> rsym))
ms (gensym)
ks (map keyword fields)
getters (map (fn [k] `(~k ~ms)) ks)]
`(defn ~fn-name
[~ms]
(new ~rname ~@getters nil (dissoc ~ms ~@ks)))))
(defmacro defrecord [rsym fields & impls]
(let [r (:name (cljs.analyzer/resolve-var (dissoc &env :locals) rsym))]
`(let []
~(emit-defrecord &env rsym r fields impls)
(set! (.-cljs$lang$type ~r) true)
(set! (.-cljs$lang$ctorPrSeq ~r) (fn [this#] (list ~(core/str r))))
(set! (.-cljs$lang$ctorPrWriter ~r) (fn [this# writer#] (-write writer# ~(core/str r))))
~(build-positional-factory rsym r fields)
~(build-map-factory rsym r fields)
~r)))
(defmacro defprotocol [psym & doc+methods]
(let [p (:name (cljs.analyzer/resolve-var (dissoc &env :locals) psym))
psym (vary-meta psym assoc :protocol-symbol true)
ns-name (-> &env :ns :name)
fqn (fn [n] (symbol (core/str ns-name "." n)))
prefix (protocol-prefix p)
methods (if (core/string? (first doc+methods)) (next doc+methods) doc+methods)
expand-sig (fn [fname slot sig]
`(~sig
(if (and ~(first sig) (. ~(first sig) ~(symbol (core/str "-" slot)))) ;; Property access needed here.
(. ~(first sig) ~slot ~@sig)
(let [x# (if (nil? ~(first sig)) nil ~(first sig))]
((or
(aget ~(fqn fname) (goog.typeOf x#))
(aget ~(fqn fname) "_")
(throw (missing-protocol
~(core/str psym "." fname) ~(first sig))))
~@sig)))))
method (fn [[fname & sigs]]
(let [sigs (take-while vector? sigs)
slot (symbol (core/str prefix (name fname)))
fname (vary-meta fname assoc :protocol p)]
`(defn ~fname ~@(map (fn [sig]
(expand-sig fname
(symbol (core/str slot "$arity$" (count sig)))
sig))
sigs))))]
`(do
(set! ~'*unchecked-if* true)
(def ~psym (~'js* "{}"))
~@(map method methods)
(set! ~'*unchecked-if* false))))
(defmacro satisfies?
"Returns true if x satisfies the protocol"
[psym x]
(let [p (:name (cljs.analyzer/resolve-var (dissoc &env :locals) psym))
prefix (protocol-prefix p)
xsym (bool-expr (gensym))
[part bit] (fast-path-protocols p)
msym (symbol (core/str "-cljs$lang$protocol_mask$partition" part "$"))]
`(let [~xsym ~x]
(if ~xsym
(if (or ~(if bit `(unsafe-bit-and (. ~xsym ~msym) ~bit))
~(bool-expr `(. ~xsym ~(symbol (core/str "-" prefix)))))
true
(if (coercive-not (. ~xsym ~msym))
(cljs.core/type_satisfies_ ~psym ~xsym)
false))
(cljs.core/type_satisfies_ ~psym ~xsym)))))
(defmacro lazy-seq [& body]
`(new cljs.core/LazySeq nil false (fn [] ~@body) nil))
(defmacro delay [& body]
"Takes a body of expressions and yields a Delay object that will
invoke the body only the first time it is forced (with force or deref/@), and
will cache the result and return it on all subsequent force
calls."
`(new cljs.core/Delay (atom {:done false, :value nil}) (fn [] ~@body)))
(defmacro binding
"binding => var-symbol init-expr
Creates new bindings for the (already-existing) vars, with the
supplied initial values, executes the exprs in an implicit do, then
re-establishes the bindings that existed before. The new bindings
are made in parallel (unlike let); all init-exprs are evaluated
before the vars are bound to their new values."
[bindings & body]
(let [names (take-nth 2 bindings)
vals (take-nth 2 (drop 1 bindings))
tempnames (map (comp gensym name) names)
binds (map vector names vals)
resets (reverse (map vector names tempnames))]
(cljs.analyzer/confirm-bindings &env names)
`(let [~@(interleave tempnames names)]
(try
~@(map
(fn [[k v]] (list 'set! k v))
binds)
~@body
(finally
~@(map
(fn [[k v]] (list 'set! k v))
resets))))))
(defmacro condp
"Takes a binary predicate, an expression, and a set of clauses.
Each clause can take the form of either:
test-expr result-expr
test-expr :>> result-fn
Note :>> is an ordinary keyword.
For each clause, (pred test-expr expr) is evaluated. If it returns
logical true, the clause is a match. If a binary clause matches, the
result-expr is returned, if a ternary clause matches, its result-fn,
which must be a unary function, is called with the result of the
predicate as its argument, the result of that call being the return
value of condp. A single default expression can follow the clauses,
and its value will be returned if no clause matches. If no default
expression is provided and no clause matches, an
IllegalArgumentException is thrown."
{:added "1.0"}
[pred expr & clauses]
(let [gpred (gensym "pred__")
gexpr (gensym "expr__")
emit (fn emit [pred expr args]
(let [[[a b c :as clause] more]
(split-at (if (= :>> (second args)) 3 2) args)
n (count clause)]
(cond
(= 0 n) `(throw (js/Error. (core/str "No matching clause: " ~expr)))
(= 1 n) a
(= 2 n) `(if (~pred ~a ~expr)
~b
~(emit pred expr more))
:else `(if-let [p# (~pred ~a ~expr)]
(~c p#)
~(emit pred expr more)))))
gres (gensym "res__")]
`(let [~gpred ~pred
~gexpr ~expr]
~(emit gpred gexpr clauses))))
(defmacro case [e & clauses]
(let [default (if (odd? (count clauses))
(last clauses)
`(throw (js/Error. (core/str "No matching clause: " ~e))))
assoc-test (fn assoc-test [m test expr]
(if (contains? m test)
(throw (clojure.core/IllegalArgumentException.
(core/str "Duplicate case test constant '"
test "'"
(when (:line &env)
(core/str " on line " (:line &env) " "
cljs.analyzer/*cljs-file*)))))
(assoc m test expr)))
pairs (reduce (fn [m [test expr]]
(cond
(seq? test) (reduce (fn [m test]
(let [test (if (symbol? test)
(list 'quote test)
test)]
(assoc-test m test expr)))
m test)
(symbol? test) (assoc-test m (list 'quote test) expr)
:else (assoc-test m test expr)))
{} (partition 2 clauses))
esym (gensym)]
`(let [~esym ~e]
(cond
~@(mapcat (fn [[m c]] `((cljs.core/= ~m ~esym) ~c)) pairs)
:else ~default))))
(defmacro try
"(try expr* catch-clause* finally-clause?)
Special Form
catch-clause => (catch protoname name expr*)
finally-clause => (finally expr*)
Catches and handles JavaScript exceptions."
[& forms]
(let [catch? #(and (list? %) (= (first %) 'catch))
[body catches] (split-with (complement catch?) forms)
[catches fin] (split-with catch? catches)
e (gensym "e")]
(assert (every? #(clojure.core/> (count %) 2) catches) "catch block must specify a prototype and a name")
(if (seq catches)
`(~'try*
~@body
(catch ~e
(cond
~@(mapcat
(fn [[_ type name & cb]]
`[(instance? ~type ~e) (let [~name ~e] ~@cb)])
catches)
:else (throw ~e)))
~@fin)
`(~'try*
~@body
~@fin))))
(defmacro assert
"Evaluates expr and throws an exception if it does not evaluate to
logical true."
([x]
(when *assert*
`(when-not ~x
(throw (js/Error.
(cljs.core/str "Assert failed: " (cljs.core/pr-str '~x)))))))
([x message]
(when *assert*
`(when-not ~x
(throw (js/Error.
(cljs.core/str "Assert failed: " ~message "\n" (cljs.core/pr-str '~x))))))))
(defmacro for
"List comprehension. Takes a vector of one or more
binding-form/collection-expr pairs, each followed by zero or more
modifiers, and yields a lazy sequence of evaluations of expr.
Collections are iterated in a nested fashion, rightmost fastest,
and nested coll-exprs can refer to bindings created in prior
binding-forms. Supported modifiers are: :let [binding-form expr ...],
:while test, :when test.
(take 100 (for [x (range 100000000) y (range 1000000) :while (< y x)] [x y]))"
[seq-exprs body-expr]
(assert-args for
(vector? seq-exprs) "a vector for its binding"
(even? (count seq-exprs)) "an even number of forms in binding vector")
(let [to-groups (fn [seq-exprs]
(reduce (fn [groups [k v]]
(if (keyword? k)
(conj (pop groups) (conj (peek groups) [k v]))
(conj groups [k v])))
[] (partition 2 seq-exprs)))
err (fn [& msg] (throw (apply core/str msg)))
emit-bind (fn emit-bind [[[bind expr & mod-pairs]
& [[_ next-expr] :as next-groups]]]
(let [giter (gensym "iter__")
gxs (gensym "s__")
do-mod (fn do-mod [[[k v :as pair] & etc]]
(cond
(= k :let) `(let ~v ~(do-mod etc))
(= k :while) `(when ~v ~(do-mod etc))
(= k :when) `(if ~v
~(do-mod etc)
(recur (rest ~gxs)))
(keyword? k) (err "Invalid 'for' keyword " k)
next-groups
`(let [iterys# ~(emit-bind next-groups)
fs# (seq (iterys# ~next-expr))]
(if fs#
(concat fs# (~giter (rest ~gxs)))
(recur (rest ~gxs))))
:else `(cons ~body-expr
(~giter (rest ~gxs)))))]
`(fn ~giter [~gxs]
(lazy-seq
(loop [~gxs ~gxs]
(when-first [~bind ~gxs]
~(do-mod mod-pairs)))))))]
`(let [iter# ~(emit-bind (to-groups seq-exprs))]
(iter# ~(second seq-exprs)))))
(defmacro doseq
"Repeatedly executes body (presumably for side-effects) with
bindings and filtering as provided by \"for\". Does not retain
the head of the sequence. Returns nil."
[seq-exprs & body]
(assert-args doseq
(vector? seq-exprs) "a vector for its binding"
(even? (count seq-exprs)) "an even number of forms in binding vector")
(let [step (fn step [recform exprs]
(if-not exprs
[true `(do ~@body)]
(let [k (first exprs)
v (second exprs)
seqsym (when-not (keyword? k) (gensym))
recform (if (keyword? k) recform `(recur (next ~seqsym)))
steppair (step recform (nnext exprs))
needrec (steppair 0)
subform (steppair 1)]
(cond
(= k :let) [needrec `(let ~v ~subform)]
(= k :while) [false `(when ~v
~subform
~@(when needrec [recform]))]
(= k :when) [false `(if ~v
(do
~subform
~@(when needrec [recform]))
~recform)]
:else [true `(loop [~seqsym (seq ~v)]
(when ~seqsym
(let [~k (first ~seqsym)]
~subform
~@(when needrec [recform]))))]))))]
(nth (step nil (seq seq-exprs)) 1)))
(defmacro array [& rest]
(let [xs-str (->> (repeat "~{}")
(take (count rest))
(interpose ",")
(apply core/str))]
(concat
(list 'js* (core/str "[" xs-str "]"))
rest)))
(defmacro js-obj [& rest]
(let [kvs-str (->> (repeat "~{}:~{}")
(take (quot (count rest) 2))
(interpose ",")
(apply core/str))]
(concat
(list 'js* (core/str "{" kvs-str "}"))
rest)))
(defmacro alength [a]
(list 'js* "~{}.length" a))
(defmacro aclone [a]
(list 'js* "~{}.slice()" a))
(defmacro amap
"Maps an expression across an array a, using an index named idx, and
return value named ret, initialized to a clone of a, then setting
each element of ret to the evaluation of expr, returning the new
array ret."
[a idx ret expr]
`(let [a# ~a
~ret (aclone a#)]
(loop [~idx 0]
(if (< ~idx (alength a#))
(do
(aset ~ret ~idx ~expr)
(recur (inc ~idx)))
~ret))))
(defmacro areduce
"Reduces an expression across an array a, using an index named idx,
and return value named ret, initialized to init, setting ret to the
evaluation of expr at each step, returning ret."
[a idx ret init expr]
`(let [a# ~a]
(loop [~idx 0 ~ret ~init]
(if (< ~idx (alength a#))
(recur (inc ~idx) ~expr)
~ret))))
(defmacro dotimes
"bindings => name n
Repeatedly executes body (presumably for side-effects) with name
bound to integers from 0 through n-1."
[bindings & body]
(let [i (first bindings)
n (second bindings)]
`(let [n# ~n]
(loop [~i 0]
(when (< ~i n#)
~@body
(recur (inc ~i)))))))
(defn ^:private check-valid-options
"Throws an exception if the given option map contains keys not listed
as valid, else returns nil."
[options & valid-keys]
(when (seq (apply disj (apply hash-set (keys options)) valid-keys))
(throw
(apply core/str "Only these options are valid: "
(first valid-keys)
(map #(core/str ", " %) (rest valid-keys))))))
(defmacro defmulti
"Creates a new multimethod with the associated dispatch function.
The docstring and attribute-map are optional.
Options are key-value pairs and may be one of:
:default the default dispatch value, defaults to :default
:hierarchy the isa? hierarchy to use for dispatching
defaults to the global hierarchy"
[mm-name & options]
(let [docstring (if (core/string? (first options))
(first options)
nil)
options (if (core/string? (first options))
(next options)
options)
m (if (map? (first options))
(first options)
{})
options (if (map? (first options))
(next options)
options)
dispatch-fn (first options)
options (next options)
m (if docstring
(assoc m :doc docstring)
m)
m (if (meta mm-name)
(conj (meta mm-name) m)
m)]
(when (= (count options) 1)
(throw "The syntax for defmulti has changed. Example: (defmulti name dispatch-fn :default dispatch-value)"))
(let [options (apply hash-map options)
default (core/get options :default :default)]
(check-valid-options options :default :hierarchy)
`(def ~(with-meta mm-name m)
(let [method-table# (atom {})
prefer-table# (atom {})
method-cache# (atom {})
cached-hierarchy# (atom {})
hierarchy# (get ~options :hierarchy cljs.core/global-hierarchy)]
(cljs.core/MultiFn. ~(name mm-name) ~dispatch-fn ~default hierarchy#
method-table# prefer-table# method-cache# cached-hierarchy#))))))
(defmacro defmethod
"Creates and installs a new method of multimethod associated with dispatch-value. "
[multifn dispatch-val & fn-tail]
`(-add-method ~(with-meta multifn {:tag 'cljs.core/MultiFn}) ~dispatch-val (fn ~@fn-tail)))
(defmacro time
"Evaluates expr and prints the time it took. Returns the value of expr."
[expr]
`(let [start# (.getTime (js/Date.))
ret# ~expr]
(prn (core/str "Elapsed time: " (- (.getTime (js/Date.)) start#) " msecs"))
ret#))
(defmacro simple-benchmark
"Runs expr iterations times in the context of a let expression with
the given bindings, then prints out the bindings and the expr
followed by number of iterations and total time. The optional
argument print-fn, defaulting to println, sets function used to
print the result. expr's string representation will be produced
using pr-str in any case."
[bindings expr iterations & {:keys [print-fn] :or {print-fn 'println}}]
(let [bs-str (pr-str bindings)
expr-str (pr-str expr)]
`(let ~bindings
(let [start# (.getTime (js/Date.))
ret# (dotimes [_# ~iterations] ~expr)
end# (.getTime (js/Date.))
elapsed# (- end# start#)]
(~print-fn (str ~bs-str ", " ~expr-str ", "
~iterations " runs, " elapsed# " msecs"))))))
(def cs (into [] (map (comp symbol core/str char) (range 97 118))))
(defn gen-apply-to-helper
([] (gen-apply-to-helper 1))
([n]
(let [prop (symbol (core/str "-cljs$lang$arity$" n))
f (symbol (core/str "cljs$lang$arity$" n))]
(if (core/<= n 20)
`(let [~(cs (core/dec n)) (-first ~'args)
~'args (-rest ~'args)]
(if (core/== ~'argc ~n)
(if (. ~'f ~prop)
(. ~'f (~f ~@(take n cs)))
(~'f ~@(take n cs)))
~(gen-apply-to-helper (core/inc n))))
`(throw (js/Error. "Only up to 20 arguments supported on functions"))))))
(defmacro gen-apply-to []
`(do
(set! ~'*unchecked-if* true)
(defn ~'apply-to [~'f ~'argc ~'args]
(let [~'args (seq ~'args)]
(if (zero? ~'argc)
(~'f)
~(gen-apply-to-helper))))
(set! ~'*unchecked-if* false)))
| 66203 | ; Copyright (c) <NAME>. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns cljs.core
(:refer-clojure :exclude [-> ->> .. amap and areduce alength aclone assert binding bound-fn case comment cond condp
declare definline definterface defmethod defmulti defn defn- defonce
defprotocol defrecord defstruct deftype delay destructure doseq dosync dotimes doto
extend-protocol extend-type fn for future gen-class gen-interface
if-let if-not import io! lazy-cat lazy-seq let letfn locking loop
memfn ns or proxy proxy-super pvalues refer-clojure reify sync time
when when-first when-let when-not while with-bindings with-in-str
with-loading-context with-local-vars with-open with-out-str with-precision with-redefs
satisfies? identical? true? false? nil? str get
aget aset
+ - * / < <= > >= == zero? pos? neg? inc dec max min mod
bit-and bit-and-not bit-clear bit-flip bit-not bit-or bit-set
bit-test bit-shift-left bit-shift-right bit-xor])
(:require clojure.walk))
(alias 'core 'clojure.core)
(defmacro import-macros [ns [& vars]]
(core/let [ns (find-ns ns)
vars (map #(ns-resolve ns %) vars)
syms (map (core/fn [^clojure.lang.Var v] (core/-> v .sym (with-meta {:macro true}))) vars)
defs (map (core/fn [sym var]
`(def ~sym (deref ~var))) syms vars)]
`(do ~@defs
:imported)))
(import-macros clojure.core
[-> ->> .. and assert comment cond
declare defn defn-
doto
extend-protocol fn for
if-let if-not letfn
memfn or
when when-first when-let when-not while])
(defmacro ^{:private true} assert-args [fnname & pairs]
`(do (when-not ~(first pairs)
(throw (IllegalArgumentException.
~(core/str fnname " requires " (second pairs)))))
~(core/let [more (nnext pairs)]
(when more
(list* `assert-args fnname more)))))
(defn destructure [bindings]
(core/let [bents (partition 2 bindings)
pb (fn pb [bvec b v]
(core/let [pvec
(fn [bvec b val]
(core/let [gvec (gensym "vec__")]
(core/loop [ret (-> bvec (conj gvec) (conj val))
n 0
bs b
seen-rest? false]
(if (seq bs)
(core/let [firstb (first bs)]
(cond
(= firstb '&) (recur (pb ret (second bs) (list `nthnext gvec n))
n
(nnext bs)
true)
(= firstb :as) (pb ret (second bs) gvec)
:else (if seen-rest?
(throw (new Exception "Unsupported binding form, only :as can follow & parameter"))
(recur (pb ret firstb (list `nth gvec n nil))
(core/inc n)
(next bs)
seen-rest?))))
ret))))
pmap
(fn [bvec b v]
(core/let [gmap (gensym "map__")
defaults (:or b)]
(core/loop [ret (-> bvec (conj gmap) (conj v)
(conj gmap) (conj `(if (seq? ~gmap) (apply hash-map ~gmap) ~gmap))
((fn [ret]
(if (:as b)
(conj ret (:as b) gmap)
ret))))
bes (reduce
(fn [bes entry]
(reduce #(assoc %1 %2 ((val entry) %2))
(dissoc bes (key entry))
((key entry) bes)))
(dissoc b :as :or)
{:keys #(keyword (core/str %)), :strs core/str, :syms #(list `quote %)})]
(if (seq bes)
(core/let [bb (key (first bes))
bk (val (first bes))
has-default (contains? defaults bb)]
(recur (pb ret bb (if has-default
(list `get gmap bk (defaults bb))
(list `get gmap bk)))
(next bes)))
ret))))]
(cond
(symbol? b) (-> bvec (conj b) (conj v))
(vector? b) (pvec bvec b v)
(map? b) (pmap bvec b v)
:else (throw (new Exception (core/str "Unsupported binding form: " b))))))
process-entry (fn [bvec b] (pb bvec (first b) (second b)))]
(if (every? symbol? (map first bents))
bindings
(reduce process-entry [] bents))))
(defmacro let
"binding => binding-form init-expr
Evaluates the exprs in a lexical context in which the symbols in
the binding-forms are bound to their respective init-exprs or parts
therein."
[bindings & body]
(assert-args
(vector? bindings) "a vector for its binding"
(even? (count bindings)) "an even number of forms in binding vector")
`(let* ~(destructure bindings) ~@body))
(defmacro loop
"Evaluates the exprs in a lexical context in which the symbols in
the binding-forms are bound to their respective init-exprs or parts
therein. Acts as a recur target."
[bindings & body]
(assert-args
(vector? bindings) "a vector for its binding"
(even? (count bindings)) "an even number of forms in binding vector")
(let [db (destructure bindings)]
(if (= db bindings)
`(loop* ~bindings ~@body)
(let [vs (take-nth 2 (drop 1 bindings))
bs (take-nth 2 bindings)
gs (map (fn [b] (if (symbol? b) b (gensym))) bs)
bfs (reduce (fn [ret [b v g]]
(if (symbol? b)
(conj ret g v)
(conj ret g v b g)))
[] (map vector bs vs gs))]
`(let ~bfs
(loop* ~(vec (interleave gs gs))
(let ~(vec (interleave bs gs))
~@body)))))))
(def fast-path-protocols
"protocol fqn -> [partition number, bit]"
(zipmap (map #(symbol "cljs.core" (core/str %))
'[IFn ICounted IEmptyableCollection ICollection IIndexed ASeq ISeq INext
ILookup IAssociative IMap IMapEntry ISet IStack IVector IDeref
IDerefWithTimeout IMeta IWithMeta IReduce IKVReduce IEquiv IHash
ISeqable ISequential IList IRecord IReversible ISorted IPrintable IWriter
IPrintWithWriter IPending IWatchable IEditableCollection ITransientCollection
ITransientAssociative ITransientMap ITransientVector ITransientSet
IMultiFn IChunkedSeq IChunkedNext IComparable])
(iterate (fn [[p b]]
(if (core/== 2147483648 b)
[(core/inc p) 1]
[p (core/bit-shift-left b 1)]))
[0 1])))
(def fast-path-protocol-partitions-count
"total number of partitions"
(let [c (count fast-path-protocols)
m (core/mod c 32)]
(if (core/zero? m)
(core/quot c 32)
(core/inc (core/quot c 32)))))
(defmacro str [& xs]
(let [strs (->> (repeat (count xs) "cljs.core.str(~{})")
(interpose ",")
(apply core/str))]
(concat (list 'js* (core/str "[" strs "].join('')")) xs)))
(defn bool-expr [e]
(vary-meta e assoc :tag 'boolean))
(defmacro nil? [x]
`(coercive-= ~x nil))
;; internal - do not use.
(defmacro coercive-not [x]
(bool-expr (list 'js* "(!~{})" x)))
;; internal - do not use.
(defmacro coercive-not= [x y]
(bool-expr (list 'js* "(~{} != ~{})" x y)))
;; internal - do not use.
(defmacro coercive-= [x y]
(bool-expr (list 'js* "(~{} == ~{})" x y)))
(defmacro true? [x]
(bool-expr (list 'js* "~{} === true" x)))
(defmacro false? [x]
(bool-expr (list 'js* "~{} === false" x)))
(defmacro undefined? [x]
(bool-expr (list 'js* "(void 0 === ~{})" x)))
(defmacro identical? [a b]
(bool-expr (list 'js* "(~{} === ~{})" a b)))
(defmacro aget
([a i]
(list 'js* "(~{}[~{}])" a i))
([a i & idxs]
(let [astr (apply core/str (repeat (count idxs) "[~{}]"))]
`(~'js* ~(core/str "(~{}[~{}]" astr ")") ~a ~i ~@idxs))))
(defmacro aset [a i v]
(list 'js* "(~{}[~{}] = ~{})" a i v))
(defmacro +
([] 0)
([x] x)
([x y] (list 'js* "(~{} + ~{})" x y))
([x y & more] `(+ (+ ~x ~y) ~@more)))
(defmacro -
([x] (list 'js* "(- ~{})" x))
([x y] (list 'js* "(~{} - ~{})" x y))
([x y & more] `(- (- ~x ~y) ~@more)))
(defmacro *
([] 1)
([x] x)
([x y] (list 'js* "(~{} * ~{})" x y))
([x y & more] `(* (* ~x ~y) ~@more)))
(defmacro /
([x] `(/ 1 ~x))
([x y] (list 'js* "(~{} / ~{})" x y))
([x y & more] `(/ (/ ~x ~y) ~@more)))
(defmacro <
([x] true)
([x y] (bool-expr (list 'js* "(~{} < ~{})" x y)))
([x y & more] `(and (< ~x ~y) (< ~y ~@more))))
(defmacro <=
([x] true)
([x y] (bool-expr (list 'js* "(~{} <= ~{})" x y)))
([x y & more] `(and (<= ~x ~y) (<= ~y ~@more))))
(defmacro >
([x] true)
([x y] (bool-expr (list 'js* "(~{} > ~{})" x y)))
([x y & more] `(and (> ~x ~y) (> ~y ~@more))))
(defmacro >=
([x] true)
([x y] (bool-expr (list 'js* "(~{} >= ~{})" x y)))
([x y & more] `(and (>= ~x ~y) (>= ~y ~@more))))
(defmacro ==
([x] true)
([x y] (bool-expr (list 'js* "(~{} === ~{})" x y)))
([x y & more] `(and (== ~x ~y) (== ~y ~@more))))
(defmacro dec [x]
`(- ~x 1))
(defmacro inc [x]
`(+ ~x 1))
(defmacro zero? [x]
`(== ~x 0))
(defmacro pos? [x]
`(> ~x 0))
(defmacro neg? [x]
`(< ~x 0))
(defmacro max
([x] x)
([x y] (list 'js* "((~{} > ~{}) ? ~{} : ~{})" x y x y))
([x y & more] `(max (max ~x ~y) ~@more)))
(defmacro min
([x] x)
([x y] (list 'js* "((~{} < ~{}) ? ~{} : ~{})" x y x y))
([x y & more] `(min (min ~x ~y) ~@more)))
(defmacro mod [num div]
(list 'js* "(~{} % ~{})" num div))
(defmacro bit-not [x]
(list 'js* "(~ ~{})" x))
(defmacro bit-and
([x y] (list 'js* "(~{} & ~{})" x y))
([x y & more] `(bit-and (bit-and ~x ~y) ~@more)))
;; internal do not use
(defmacro unsafe-bit-and
([x y] (bool-expr (list 'js* "(~{} & ~{})" x y)))
([x y & more] `(unsafe-bit-and (unsafe-bit-and ~x ~y) ~@more)))
(defmacro bit-or
([x y] (list 'js* "(~{} | ~{})" x y))
([x y & more] `(bit-or (bit-or ~x ~y) ~@more)))
(defmacro bit-xor
([x y] (list 'js* "(~{} ^ ~{})" x y))
([x y & more] `(bit-xor (bit-xor ~x ~y) ~@more)))
(defmacro bit-and-not
([x y] (list 'js* "(~{} & ~~{})" x y))
([x y & more] `(bit-and-not (bit-and-not ~x ~y) ~@more)))
(defmacro bit-clear [x n]
(list 'js* "(~{} & ~(1 << ~{}))" x n))
(defmacro bit-flip [x n]
(list 'js* "(~{} ^ (1 << ~{}))" x n))
(defmacro bit-test [x n]
(list 'js* "((~{} & (1 << ~{})) != 0)" x n))
(defmacro bit-shift-left [x n]
(list 'js* "(~{} << ~{})" x n))
(defmacro bit-shift-right [x n]
(list 'js* "(~{} >> ~{})" x n))
(defmacro bit-shift-right-zero-fill [x n]
(list 'js* "(~{} >>> ~{})" x n))
(defmacro bit-set [x n]
(list 'js* "(~{} | (1 << ~{}))" x n))
;; internal
(defmacro mask [hash shift]
(list 'js* "((~{} >>> ~{}) & 0x01f)" hash shift))
;; internal
(defmacro bitpos [hash shift]
(list 'js* "(1 << ~{})" `(mask ~hash ~shift)))
;; internal
(defmacro caching-hash [coll hash-fn hash-key]
`(let [h# ~hash-key]
(if-not (nil? h#)
h#
(let [h# (~hash-fn ~coll)]
(set! ~hash-key h#)
h#))))
(defmacro get
([coll k]
`(-lookup ~coll ~k nil))
([coll k not-found]
`(-lookup ~coll ~k ~not-found)))
;;; internal -- reducers-related macros
(defn- do-curried
[name doc meta args body]
(let [cargs (vec (butlast args))]
`(defn ~name ~doc ~meta
(~cargs (fn [x#] (~name ~@cargs x#)))
(~args ~@body))))
(defmacro ^:private defcurried
"Builds another arity of the fn that returns a fn awaiting the last
param"
[name doc meta args & body]
(do-curried name doc meta args body))
(defn- do-rfn [f1 k fkv]
`(fn
([] (~f1))
~(clojure.walk/postwalk
#(if (sequential? %)
((if (vector? %) vec identity)
(core/remove #{k} %))
%)
fkv)
~fkv))
(defmacro ^:private rfn
"Builds 3-arity reducing fn given names of wrapped fn and key, and k/v impl."
[[f1 k] fkv]
(do-rfn f1 k fkv))
;;; end of reducers macros
(defn protocol-prefix [psym]
(core/str (-> (core/str psym) (.replace \. \$) (.replace \/ \$)) "$"))
(def #^:private base-type
{nil "null"
'object "object"
'string "string"
'number "number"
'array "array"
'function "function"
'boolean "boolean"
'default "_"})
(defmacro reify [& impls]
(let [t (gensym "t")
meta-sym (gensym "meta")
this-sym (gensym "_")
locals (keys (:locals &env))
ns (-> &env :ns :name)
munge cljs.compiler/munge
ns-t (list 'js* (core/str (munge ns) "." (munge t)))]
`(do
(when (undefined? ~ns-t)
(deftype ~t [~@locals ~meta-sym]
IWithMeta
(~'-with-meta [~this-sym ~meta-sym]
(new ~t ~@locals ~meta-sym))
IMeta
(~'-meta [~this-sym] ~meta-sym)
~@impls))
(new ~t ~@locals nil))))
(defmacro this-as
"Defines a scope where JavaScript's implicit \"this\" is bound to the name provided."
[name & body]
`(let [~name (~'js* "this")]
~@body))
(defn to-property [sym]
(symbol (core/str "-" sym)))
(defmacro extend-type [tsym & impls]
(let [resolve #(let [ret (:name (cljs.analyzer/resolve-var (dissoc &env :locals) %))]
(assert ret (core/str "Can't resolve: " %))
ret)
impl-map (loop [ret {} s impls]
(if (seq s)
(recur (assoc ret (first s) (take-while seq? (next s)))
(drop-while seq? (next s)))
ret))
warn-if-not-protocol #(when-not (= 'Object %)
(if cljs.analyzer/*cljs-warn-on-undeclared*
(if-let [var (cljs.analyzer/resolve-existing-var (dissoc &env :locals) %)]
(do
(when-not (:protocol-symbol var)
(cljs.analyzer/warning &env
(core/str "WARNING: Symbol " % " is not a protocol")))
(when (and cljs.analyzer/*cljs-warn-protocol-deprecated*
(-> var :deprecated)
(not (-> % meta :deprecation-nowarn)))
(cljs.analyzer/warning &env
(core/str "WARNING: Protocol " % " is deprecated"))))
(cljs.analyzer/warning &env
(core/str "WARNING: Can't resolve protocol symbol " %)))))
skip-flag (set (-> tsym meta :skip-protocol-flag))]
(if (base-type tsym)
(let [t (base-type tsym)
assign-impls (fn [[p sigs]]
(warn-if-not-protocol p)
(let [psym (resolve p)
pfn-prefix (subs (core/str psym) 0 (clojure.core/inc (.indexOf (core/str psym) "/")))]
(cons `(aset ~psym ~t true)
(map (fn [[f & meths :as form]]
`(aset ~(symbol (core/str pfn-prefix f)) ~t ~(with-meta `(fn ~@meths) (meta form))))
sigs))))]
`(do ~@(mapcat assign-impls impl-map)))
(let [t (resolve tsym)
prototype-prefix (fn [sym]
`(.. ~tsym -prototype ~(to-property sym)))
assign-impls (fn [[p sigs]]
(warn-if-not-protocol p)
(let [psym (resolve p)
pprefix (protocol-prefix psym)]
(if (= p 'Object)
(let [adapt-params (fn [[sig & body]]
(let [[tname & args] sig]
(list (vec args) (list* 'this-as (vary-meta tname assoc :tag t) body))))]
(map (fn [[f & meths :as form]]
`(set! ~(prototype-prefix f)
~(with-meta `(fn ~@(map adapt-params meths)) (meta form))))
sigs))
(concat (when-not (skip-flag psym)
[`(set! ~(prototype-prefix pprefix) true)])
(mapcat (fn [[f & meths :as form]]
(if (= psym 'cljs.core/IFn)
(let [adapt-params (fn [[[targ & args :as sig] & body]]
(let [this-sym (with-meta (gensym "this-sym") {:tag t})]
`(~(vec (cons this-sym args))
(this-as ~this-sym
(let [~targ ~this-sym]
~@body)))))
meths (map adapt-params meths)
this-sym (with-meta (gensym "this-sym") {:tag t})
argsym (gensym "args")]
[`(set! ~(prototype-prefix 'call) ~(with-meta `(fn ~@meths) (meta form)))
`(set! ~(prototype-prefix 'apply)
~(with-meta
`(fn ~[this-sym argsym]
(.apply (.-call ~this-sym) ~this-sym
(.concat (array ~this-sym) (aclone ~argsym))))
(meta form)))])
(let [pf (core/str pprefix f)
adapt-params (fn [[[targ & args :as sig] & body]]
(cons (vec (cons (vary-meta targ assoc :tag t) args))
body))]
(if (vector? (first meths))
[`(set! ~(prototype-prefix (core/str pf "$arity$" (count (first meths)))) ~(with-meta `(fn ~@(adapt-params meths)) (meta form)))]
(map (fn [[sig & body :as meth]]
`(set! ~(prototype-prefix (core/str pf "$arity$" (count sig)))
~(with-meta `(fn ~(adapt-params meth)) (meta form))))
meths)))))
sigs)))))]
`(do ~@(mapcat assign-impls impl-map))))))
(defn- prepare-protocol-masks [env t impls]
(let [resolve #(let [ret (:name (cljs.analyzer/resolve-var (dissoc env :locals) %))]
(assert ret (core/str "Can't resolve: " %))
ret)
impl-map (loop [ret {} s impls]
(if (seq s)
(recur (assoc ret (first s) (take-while seq? (next s)))
(drop-while seq? (next s)))
ret))]
(if-let [fpp-pbs (seq (keep fast-path-protocols
(map resolve
(keys impl-map))))]
(let [fpps (into #{} (filter (partial contains? fast-path-protocols)
(map resolve
(keys impl-map))))
fpp-partitions (group-by first fpp-pbs)
fpp-partitions (into {} (map (juxt key (comp (partial map peek) val))
fpp-partitions))
fpp-partitions (into {} (map (juxt key (comp (partial reduce core/bit-or) val))
fpp-partitions))]
[fpps
(reduce (fn [ps p]
(update-in ps [p] (fnil identity 0)))
fpp-partitions
(range fast-path-protocol-partitions-count))]))))
(defn dt->et
([t specs fields] (dt->et t specs fields false))
([t specs fields inline]
(loop [ret [] s specs]
(if (seq s)
(recur (-> ret
(conj (first s))
(into
(reduce (fn [v [f sigs]]
(conj v (vary-meta (cons f (map #(cons (second %) (nnext %)) sigs))
assoc :cljs.analyzer/type t
:cljs.analyzer/fields fields
:protocol-impl true
:protocol-inline inline)))
[]
(group-by first (take-while seq? (next s))))))
(drop-while seq? (next s)))
ret))))
(defn collect-protocols [impls env]
(->> impls
(filter symbol?)
(map #(:name (cljs.analyzer/resolve-var (dissoc env :locals) %)))
(into #{})))
(defmacro deftype [t fields & impls]
(let [r (:name (cljs.analyzer/resolve-var (dissoc &env :locals) t))
[fpps pmasks] (prepare-protocol-masks &env t impls)
protocols (collect-protocols impls &env)
t (vary-meta t assoc
:protocols protocols
:skip-protocol-flag fpps) ]
(if (seq impls)
`(do
(deftype* ~t ~fields ~pmasks)
(set! (.-cljs$lang$type ~t) true)
(set! (.-cljs$lang$ctorPrSeq ~t) (fn [this#] (list ~(core/str r))))
(set! (.-cljs$lang$ctorPrWriter ~t) (fn [this# writer#] (-write writer# ~(core/str r))))
(extend-type ~t ~@(dt->et t impls fields true))
~t)
`(do
(deftype* ~t ~fields ~pmasks)
(set! (.-cljs$lang$type ~t) true)
(set! (.-cljs$lang$ctorPrSeq ~t) (fn [this#] (list ~(core/str r))))
(set! (.-cljs$lang$ctorPrWriter ~t) (fn [this# writer#] (-write writer# ~(core/str r))))
~t))))
(defn- emit-defrecord
"Do not use this directly - use defrecord"
[env tagname rname fields impls]
(let [hinted-fields fields
fields (vec (map #(with-meta % nil) fields))
base-fields fields
fields (conj fields '__meta '__extmap (with-meta '__hash {:mutable true}))]
(let [gs (gensym)
ksym (gensym "k")
impls (concat
impls
['IRecord
'IHash
`(~'-hash [this#] (caching-hash this# ~'hash-imap ~'__hash))
'IEquiv
`(~'-equiv [this# other#]
(if (and other#
(identical? (.-constructor this#)
(.-constructor other#))
(equiv-map this# other#))
true
false))
'IMeta
`(~'-meta [this#] ~'__meta)
'IWithMeta
`(~'-with-meta [this# ~gs] (new ~tagname ~@(replace {'__meta gs} fields)))
'ILookup
`(~'-lookup [this# k#] (-lookup this# k# nil))
`(~'-lookup [this# ~ksym else#]
(cond
~@(mapcat (fn [f] [`(identical? ~ksym ~(keyword f)) f]) base-fields)
:else (get ~'__extmap ~ksym else#)))
'ICounted
`(~'-count [this#] (+ ~(count base-fields) (count ~'__extmap)))
'ICollection
`(~'-conj [this# entry#]
(if (vector? entry#)
(-assoc this# (-nth entry# 0) (-nth entry# 1))
(reduce -conj
this#
entry#)))
'IAssociative
`(~'-assoc [this# k# ~gs]
(condp identical? k#
~@(mapcat (fn [fld]
[(keyword fld) (list* `new tagname (replace {fld gs '__hash nil} fields))])
base-fields)
(new ~tagname ~@(remove #{'__extmap '__hash} fields) (assoc ~'__extmap k# ~gs) nil)))
'IMap
`(~'-dissoc [this# k#] (if (contains? #{~@(map keyword base-fields)} k#)
(dissoc (with-meta (into {} this#) ~'__meta) k#)
(new ~tagname ~@(remove #{'__extmap '__hash} fields)
(not-empty (dissoc ~'__extmap k#))
nil)))
'ISeqable
`(~'-seq [this#] (seq (concat [~@(map #(list `vector (keyword %) %) base-fields)]
~'__extmap)))
'IPrintWithWriter
`(~'-pr-writer [this# writer# opts#]
(let [pr-pair# (fn [keyval#] (pr-sequential-writer writer# pr-writer "" " " "" opts# keyval#))]
(pr-sequential-writer
writer# pr-pair# (core/str "#" ~(name rname) "{") ", " "}" opts#
(concat [~@(map #(list `vector (keyword %) %) base-fields)]
~'__extmap))))
])
[fpps pmasks] (prepare-protocol-masks env tagname impls)
protocols (collect-protocols impls env)
tagname (vary-meta tagname assoc
:protocols protocols
:skip-protocol-flag fpps)]
`(do
(~'defrecord* ~tagname ~hinted-fields ~pmasks)
(extend-type ~tagname ~@(dt->et tagname impls fields true))))))
(defn- build-positional-factory
[rsym rname fields]
(let [fn-name (symbol (core/str '-> rsym))]
`(defn ~fn-name
[~@fields]
(new ~rname ~@fields))))
(defn- build-map-factory
[rsym rname fields]
(let [fn-name (symbol (core/str 'map-> rsym))
ms (gensym)
ks (map keyword fields)
getters (map (fn [k] `(~k ~ms)) ks)]
`(defn ~fn-name
[~ms]
(new ~rname ~@getters nil (dissoc ~ms ~@ks)))))
(defmacro defrecord [rsym fields & impls]
(let [r (:name (cljs.analyzer/resolve-var (dissoc &env :locals) rsym))]
`(let []
~(emit-defrecord &env rsym r fields impls)
(set! (.-cljs$lang$type ~r) true)
(set! (.-cljs$lang$ctorPrSeq ~r) (fn [this#] (list ~(core/str r))))
(set! (.-cljs$lang$ctorPrWriter ~r) (fn [this# writer#] (-write writer# ~(core/str r))))
~(build-positional-factory rsym r fields)
~(build-map-factory rsym r fields)
~r)))
(defmacro defprotocol [psym & doc+methods]
(let [p (:name (cljs.analyzer/resolve-var (dissoc &env :locals) psym))
psym (vary-meta psym assoc :protocol-symbol true)
ns-name (-> &env :ns :name)
fqn (fn [n] (symbol (core/str ns-name "." n)))
prefix (protocol-prefix p)
methods (if (core/string? (first doc+methods)) (next doc+methods) doc+methods)
expand-sig (fn [fname slot sig]
`(~sig
(if (and ~(first sig) (. ~(first sig) ~(symbol (core/str "-" slot)))) ;; Property access needed here.
(. ~(first sig) ~slot ~@sig)
(let [x# (if (nil? ~(first sig)) nil ~(first sig))]
((or
(aget ~(fqn fname) (goog.typeOf x#))
(aget ~(fqn fname) "_")
(throw (missing-protocol
~(core/str psym "." fname) ~(first sig))))
~@sig)))))
method (fn [[fname & sigs]]
(let [sigs (take-while vector? sigs)
slot (symbol (core/str prefix (name fname)))
fname (vary-meta fname assoc :protocol p)]
`(defn ~fname ~@(map (fn [sig]
(expand-sig fname
(symbol (core/str slot "$arity$" (count sig)))
sig))
sigs))))]
`(do
(set! ~'*unchecked-if* true)
(def ~psym (~'js* "{}"))
~@(map method methods)
(set! ~'*unchecked-if* false))))
(defmacro satisfies?
"Returns true if x satisfies the protocol"
[psym x]
(let [p (:name (cljs.analyzer/resolve-var (dissoc &env :locals) psym))
prefix (protocol-prefix p)
xsym (bool-expr (gensym))
[part bit] (fast-path-protocols p)
msym (symbol (core/str "-cljs$lang$protocol_mask$partition" part "$"))]
`(let [~xsym ~x]
(if ~xsym
(if (or ~(if bit `(unsafe-bit-and (. ~xsym ~msym) ~bit))
~(bool-expr `(. ~xsym ~(symbol (core/str "-" prefix)))))
true
(if (coercive-not (. ~xsym ~msym))
(cljs.core/type_satisfies_ ~psym ~xsym)
false))
(cljs.core/type_satisfies_ ~psym ~xsym)))))
(defmacro lazy-seq [& body]
`(new cljs.core/LazySeq nil false (fn [] ~@body) nil))
(defmacro delay [& body]
"Takes a body of expressions and yields a Delay object that will
invoke the body only the first time it is forced (with force or deref/@), and
will cache the result and return it on all subsequent force
calls."
`(new cljs.core/Delay (atom {:done false, :value nil}) (fn [] ~@body)))
(defmacro binding
"binding => var-symbol init-expr
Creates new bindings for the (already-existing) vars, with the
supplied initial values, executes the exprs in an implicit do, then
re-establishes the bindings that existed before. The new bindings
are made in parallel (unlike let); all init-exprs are evaluated
before the vars are bound to their new values."
[bindings & body]
(let [names (take-nth 2 bindings)
vals (take-nth 2 (drop 1 bindings))
tempnames (map (comp gensym name) names)
binds (map vector names vals)
resets (reverse (map vector names tempnames))]
(cljs.analyzer/confirm-bindings &env names)
`(let [~@(interleave tempnames names)]
(try
~@(map
(fn [[k v]] (list 'set! k v))
binds)
~@body
(finally
~@(map
(fn [[k v]] (list 'set! k v))
resets))))))
(defmacro condp
"Takes a binary predicate, an expression, and a set of clauses.
Each clause can take the form of either:
test-expr result-expr
test-expr :>> result-fn
Note :>> is an ordinary keyword.
For each clause, (pred test-expr expr) is evaluated. If it returns
logical true, the clause is a match. If a binary clause matches, the
result-expr is returned, if a ternary clause matches, its result-fn,
which must be a unary function, is called with the result of the
predicate as its argument, the result of that call being the return
value of condp. A single default expression can follow the clauses,
and its value will be returned if no clause matches. If no default
expression is provided and no clause matches, an
IllegalArgumentException is thrown."
{:added "1.0"}
[pred expr & clauses]
(let [gpred (gensym "pred__")
gexpr (gensym "expr__")
emit (fn emit [pred expr args]
(let [[[a b c :as clause] more]
(split-at (if (= :>> (second args)) 3 2) args)
n (count clause)]
(cond
(= 0 n) `(throw (js/Error. (core/str "No matching clause: " ~expr)))
(= 1 n) a
(= 2 n) `(if (~pred ~a ~expr)
~b
~(emit pred expr more))
:else `(if-let [p# (~pred ~a ~expr)]
(~c p#)
~(emit pred expr more)))))
gres (gensym "res__")]
`(let [~gpred ~pred
~gexpr ~expr]
~(emit gpred gexpr clauses))))
(defmacro case [e & clauses]
(let [default (if (odd? (count clauses))
(last clauses)
`(throw (js/Error. (core/str "No matching clause: " ~e))))
assoc-test (fn assoc-test [m test expr]
(if (contains? m test)
(throw (clojure.core/IllegalArgumentException.
(core/str "Duplicate case test constant '"
test "'"
(when (:line &env)
(core/str " on line " (:line &env) " "
cljs.analyzer/*cljs-file*)))))
(assoc m test expr)))
pairs (reduce (fn [m [test expr]]
(cond
(seq? test) (reduce (fn [m test]
(let [test (if (symbol? test)
(list 'quote test)
test)]
(assoc-test m test expr)))
m test)
(symbol? test) (assoc-test m (list 'quote test) expr)
:else (assoc-test m test expr)))
{} (partition 2 clauses))
esym (gensym)]
`(let [~esym ~e]
(cond
~@(mapcat (fn [[m c]] `((cljs.core/= ~m ~esym) ~c)) pairs)
:else ~default))))
(defmacro try
"(try expr* catch-clause* finally-clause?)
Special Form
catch-clause => (catch protoname name expr*)
finally-clause => (finally expr*)
Catches and handles JavaScript exceptions."
[& forms]
(let [catch? #(and (list? %) (= (first %) 'catch))
[body catches] (split-with (complement catch?) forms)
[catches fin] (split-with catch? catches)
e (gensym "e")]
(assert (every? #(clojure.core/> (count %) 2) catches) "catch block must specify a prototype and a name")
(if (seq catches)
`(~'try*
~@body
(catch ~e
(cond
~@(mapcat
(fn [[_ type name & cb]]
`[(instance? ~type ~e) (let [~name ~e] ~@cb)])
catches)
:else (throw ~e)))
~@fin)
`(~'try*
~@body
~@fin))))
(defmacro assert
"Evaluates expr and throws an exception if it does not evaluate to
logical true."
([x]
(when *assert*
`(when-not ~x
(throw (js/Error.
(cljs.core/str "Assert failed: " (cljs.core/pr-str '~x)))))))
([x message]
(when *assert*
`(when-not ~x
(throw (js/Error.
(cljs.core/str "Assert failed: " ~message "\n" (cljs.core/pr-str '~x))))))))
(defmacro for
"List comprehension. Takes a vector of one or more
binding-form/collection-expr pairs, each followed by zero or more
modifiers, and yields a lazy sequence of evaluations of expr.
Collections are iterated in a nested fashion, rightmost fastest,
and nested coll-exprs can refer to bindings created in prior
binding-forms. Supported modifiers are: :let [binding-form expr ...],
:while test, :when test.
(take 100 (for [x (range 100000000) y (range 1000000) :while (< y x)] [x y]))"
[seq-exprs body-expr]
(assert-args for
(vector? seq-exprs) "a vector for its binding"
(even? (count seq-exprs)) "an even number of forms in binding vector")
(let [to-groups (fn [seq-exprs]
(reduce (fn [groups [k v]]
(if (keyword? k)
(conj (pop groups) (conj (peek groups) [k v]))
(conj groups [k v])))
[] (partition 2 seq-exprs)))
err (fn [& msg] (throw (apply core/str msg)))
emit-bind (fn emit-bind [[[bind expr & mod-pairs]
& [[_ next-expr] :as next-groups]]]
(let [giter (gensym "iter__")
gxs (gensym "s__")
do-mod (fn do-mod [[[k v :as pair] & etc]]
(cond
(= k :let) `(let ~v ~(do-mod etc))
(= k :while) `(when ~v ~(do-mod etc))
(= k :when) `(if ~v
~(do-mod etc)
(recur (rest ~gxs)))
(keyword? k) (err "Invalid 'for' keyword " k)
next-groups
`(let [iterys# ~(emit-bind next-groups)
fs# (seq (iterys# ~next-expr))]
(if fs#
(concat fs# (~giter (rest ~gxs)))
(recur (rest ~gxs))))
:else `(cons ~body-expr
(~giter (rest ~gxs)))))]
`(fn ~giter [~gxs]
(lazy-seq
(loop [~gxs ~gxs]
(when-first [~bind ~gxs]
~(do-mod mod-pairs)))))))]
`(let [iter# ~(emit-bind (to-groups seq-exprs))]
(iter# ~(second seq-exprs)))))
(defmacro doseq
"Repeatedly executes body (presumably for side-effects) with
bindings and filtering as provided by \"for\". Does not retain
the head of the sequence. Returns nil."
[seq-exprs & body]
(assert-args doseq
(vector? seq-exprs) "a vector for its binding"
(even? (count seq-exprs)) "an even number of forms in binding vector")
(let [step (fn step [recform exprs]
(if-not exprs
[true `(do ~@body)]
(let [k (first exprs)
v (second exprs)
seqsym (when-not (keyword? k) (gensym))
recform (if (keyword? k) recform `(recur (next ~seqsym)))
steppair (step recform (nnext exprs))
needrec (steppair 0)
subform (steppair 1)]
(cond
(= k :let) [needrec `(let ~v ~subform)]
(= k :while) [false `(when ~v
~subform
~@(when needrec [recform]))]
(= k :when) [false `(if ~v
(do
~subform
~@(when needrec [recform]))
~recform)]
:else [true `(loop [~seqsym (seq ~v)]
(when ~seqsym
(let [~k (first ~seqsym)]
~subform
~@(when needrec [recform]))))]))))]
(nth (step nil (seq seq-exprs)) 1)))
(defmacro array [& rest]
(let [xs-str (->> (repeat "~{}")
(take (count rest))
(interpose ",")
(apply core/str))]
(concat
(list 'js* (core/str "[" xs-str "]"))
rest)))
(defmacro js-obj [& rest]
(let [kvs-str (->> (repeat "~{}:~{}")
(take (quot (count rest) 2))
(interpose ",")
(apply core/str))]
(concat
(list 'js* (core/str "{" kvs-str "}"))
rest)))
(defmacro alength [a]
(list 'js* "~{}.length" a))
(defmacro aclone [a]
(list 'js* "~{}.slice()" a))
(defmacro amap
"Maps an expression across an array a, using an index named idx, and
return value named ret, initialized to a clone of a, then setting
each element of ret to the evaluation of expr, returning the new
array ret."
[a idx ret expr]
`(let [a# ~a
~ret (aclone a#)]
(loop [~idx 0]
(if (< ~idx (alength a#))
(do
(aset ~ret ~idx ~expr)
(recur (inc ~idx)))
~ret))))
(defmacro areduce
"Reduces an expression across an array a, using an index named idx,
and return value named ret, initialized to init, setting ret to the
evaluation of expr at each step, returning ret."
[a idx ret init expr]
`(let [a# ~a]
(loop [~idx 0 ~ret ~init]
(if (< ~idx (alength a#))
(recur (inc ~idx) ~expr)
~ret))))
(defmacro dotimes
"bindings => name n
Repeatedly executes body (presumably for side-effects) with name
bound to integers from 0 through n-1."
[bindings & body]
(let [i (first bindings)
n (second bindings)]
`(let [n# ~n]
(loop [~i 0]
(when (< ~i n#)
~@body
(recur (inc ~i)))))))
(defn ^:private check-valid-options
"Throws an exception if the given option map contains keys not listed
as valid, else returns nil."
[options & valid-keys]
(when (seq (apply disj (apply hash-set (keys options)) valid-keys))
(throw
(apply core/str "Only these options are valid: "
(first valid-keys)
(map #(core/str ", " %) (rest valid-keys))))))
(defmacro defmulti
"Creates a new multimethod with the associated dispatch function.
The docstring and attribute-map are optional.
Options are key-value pairs and may be one of:
:default the default dispatch value, defaults to :default
:hierarchy the isa? hierarchy to use for dispatching
defaults to the global hierarchy"
[mm-name & options]
(let [docstring (if (core/string? (first options))
(first options)
nil)
options (if (core/string? (first options))
(next options)
options)
m (if (map? (first options))
(first options)
{})
options (if (map? (first options))
(next options)
options)
dispatch-fn (first options)
options (next options)
m (if docstring
(assoc m :doc docstring)
m)
m (if (meta mm-name)
(conj (meta mm-name) m)
m)]
(when (= (count options) 1)
(throw "The syntax for defmulti has changed. Example: (defmulti name dispatch-fn :default dispatch-value)"))
(let [options (apply hash-map options)
default (core/get options :default :default)]
(check-valid-options options :default :hierarchy)
`(def ~(with-meta mm-name m)
(let [method-table# (atom {})
prefer-table# (atom {})
method-cache# (atom {})
cached-hierarchy# (atom {})
hierarchy# (get ~options :hierarchy cljs.core/global-hierarchy)]
(cljs.core/MultiFn. ~(name mm-name) ~dispatch-fn ~default hierarchy#
method-table# prefer-table# method-cache# cached-hierarchy#))))))
(defmacro defmethod
"Creates and installs a new method of multimethod associated with dispatch-value. "
[multifn dispatch-val & fn-tail]
`(-add-method ~(with-meta multifn {:tag 'cljs.core/MultiFn}) ~dispatch-val (fn ~@fn-tail)))
(defmacro time
"Evaluates expr and prints the time it took. Returns the value of expr."
[expr]
`(let [start# (.getTime (js/Date.))
ret# ~expr]
(prn (core/str "Elapsed time: " (- (.getTime (js/Date.)) start#) " msecs"))
ret#))
(defmacro simple-benchmark
"Runs expr iterations times in the context of a let expression with
the given bindings, then prints out the bindings and the expr
followed by number of iterations and total time. The optional
argument print-fn, defaulting to println, sets function used to
print the result. expr's string representation will be produced
using pr-str in any case."
[bindings expr iterations & {:keys [print-fn] :or {print-fn 'println}}]
(let [bs-str (pr-str bindings)
expr-str (pr-str expr)]
`(let ~bindings
(let [start# (.getTime (js/Date.))
ret# (dotimes [_# ~iterations] ~expr)
end# (.getTime (js/Date.))
elapsed# (- end# start#)]
(~print-fn (str ~bs-str ", " ~expr-str ", "
~iterations " runs, " elapsed# " msecs"))))))
(def cs (into [] (map (comp symbol core/str char) (range 97 118))))
(defn gen-apply-to-helper
([] (gen-apply-to-helper 1))
([n]
(let [prop (symbol (core/str "-cljs$lang$arity$" n))
f (symbol (core/str "cljs$lang$arity$" n))]
(if (core/<= n 20)
`(let [~(cs (core/dec n)) (-first ~'args)
~'args (-rest ~'args)]
(if (core/== ~'argc ~n)
(if (. ~'f ~prop)
(. ~'f (~f ~@(take n cs)))
(~'f ~@(take n cs)))
~(gen-apply-to-helper (core/inc n))))
`(throw (js/Error. "Only up to 20 arguments supported on functions"))))))
(defmacro gen-apply-to []
`(do
(set! ~'*unchecked-if* true)
(defn ~'apply-to [~'f ~'argc ~'args]
(let [~'args (seq ~'args)]
(if (zero? ~'argc)
(~'f)
~(gen-apply-to-helper))))
(set! ~'*unchecked-if* false)))
| true | ; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns cljs.core
(:refer-clojure :exclude [-> ->> .. amap and areduce alength aclone assert binding bound-fn case comment cond condp
declare definline definterface defmethod defmulti defn defn- defonce
defprotocol defrecord defstruct deftype delay destructure doseq dosync dotimes doto
extend-protocol extend-type fn for future gen-class gen-interface
if-let if-not import io! lazy-cat lazy-seq let letfn locking loop
memfn ns or proxy proxy-super pvalues refer-clojure reify sync time
when when-first when-let when-not while with-bindings with-in-str
with-loading-context with-local-vars with-open with-out-str with-precision with-redefs
satisfies? identical? true? false? nil? str get
aget aset
+ - * / < <= > >= == zero? pos? neg? inc dec max min mod
bit-and bit-and-not bit-clear bit-flip bit-not bit-or bit-set
bit-test bit-shift-left bit-shift-right bit-xor])
(:require clojure.walk))
(alias 'core 'clojure.core)
(defmacro import-macros [ns [& vars]]
(core/let [ns (find-ns ns)
vars (map #(ns-resolve ns %) vars)
syms (map (core/fn [^clojure.lang.Var v] (core/-> v .sym (with-meta {:macro true}))) vars)
defs (map (core/fn [sym var]
`(def ~sym (deref ~var))) syms vars)]
`(do ~@defs
:imported)))
(import-macros clojure.core
[-> ->> .. and assert comment cond
declare defn defn-
doto
extend-protocol fn for
if-let if-not letfn
memfn or
when when-first when-let when-not while])
(defmacro ^{:private true} assert-args [fnname & pairs]
`(do (when-not ~(first pairs)
(throw (IllegalArgumentException.
~(core/str fnname " requires " (second pairs)))))
~(core/let [more (nnext pairs)]
(when more
(list* `assert-args fnname more)))))
(defn destructure [bindings]
(core/let [bents (partition 2 bindings)
pb (fn pb [bvec b v]
(core/let [pvec
(fn [bvec b val]
(core/let [gvec (gensym "vec__")]
(core/loop [ret (-> bvec (conj gvec) (conj val))
n 0
bs b
seen-rest? false]
(if (seq bs)
(core/let [firstb (first bs)]
(cond
(= firstb '&) (recur (pb ret (second bs) (list `nthnext gvec n))
n
(nnext bs)
true)
(= firstb :as) (pb ret (second bs) gvec)
:else (if seen-rest?
(throw (new Exception "Unsupported binding form, only :as can follow & parameter"))
(recur (pb ret firstb (list `nth gvec n nil))
(core/inc n)
(next bs)
seen-rest?))))
ret))))
pmap
(fn [bvec b v]
(core/let [gmap (gensym "map__")
defaults (:or b)]
(core/loop [ret (-> bvec (conj gmap) (conj v)
(conj gmap) (conj `(if (seq? ~gmap) (apply hash-map ~gmap) ~gmap))
((fn [ret]
(if (:as b)
(conj ret (:as b) gmap)
ret))))
bes (reduce
(fn [bes entry]
(reduce #(assoc %1 %2 ((val entry) %2))
(dissoc bes (key entry))
((key entry) bes)))
(dissoc b :as :or)
{:keys #(keyword (core/str %)), :strs core/str, :syms #(list `quote %)})]
(if (seq bes)
(core/let [bb (key (first bes))
bk (val (first bes))
has-default (contains? defaults bb)]
(recur (pb ret bb (if has-default
(list `get gmap bk (defaults bb))
(list `get gmap bk)))
(next bes)))
ret))))]
(cond
(symbol? b) (-> bvec (conj b) (conj v))
(vector? b) (pvec bvec b v)
(map? b) (pmap bvec b v)
:else (throw (new Exception (core/str "Unsupported binding form: " b))))))
process-entry (fn [bvec b] (pb bvec (first b) (second b)))]
(if (every? symbol? (map first bents))
bindings
(reduce process-entry [] bents))))
(defmacro let
"binding => binding-form init-expr
Evaluates the exprs in a lexical context in which the symbols in
the binding-forms are bound to their respective init-exprs or parts
therein."
[bindings & body]
(assert-args
(vector? bindings) "a vector for its binding"
(even? (count bindings)) "an even number of forms in binding vector")
`(let* ~(destructure bindings) ~@body))
(defmacro loop
"Evaluates the exprs in a lexical context in which the symbols in
the binding-forms are bound to their respective init-exprs or parts
therein. Acts as a recur target."
[bindings & body]
(assert-args
(vector? bindings) "a vector for its binding"
(even? (count bindings)) "an even number of forms in binding vector")
(let [db (destructure bindings)]
(if (= db bindings)
`(loop* ~bindings ~@body)
(let [vs (take-nth 2 (drop 1 bindings))
bs (take-nth 2 bindings)
gs (map (fn [b] (if (symbol? b) b (gensym))) bs)
bfs (reduce (fn [ret [b v g]]
(if (symbol? b)
(conj ret g v)
(conj ret g v b g)))
[] (map vector bs vs gs))]
`(let ~bfs
(loop* ~(vec (interleave gs gs))
(let ~(vec (interleave bs gs))
~@body)))))))
(def fast-path-protocols
"protocol fqn -> [partition number, bit]"
(zipmap (map #(symbol "cljs.core" (core/str %))
'[IFn ICounted IEmptyableCollection ICollection IIndexed ASeq ISeq INext
ILookup IAssociative IMap IMapEntry ISet IStack IVector IDeref
IDerefWithTimeout IMeta IWithMeta IReduce IKVReduce IEquiv IHash
ISeqable ISequential IList IRecord IReversible ISorted IPrintable IWriter
IPrintWithWriter IPending IWatchable IEditableCollection ITransientCollection
ITransientAssociative ITransientMap ITransientVector ITransientSet
IMultiFn IChunkedSeq IChunkedNext IComparable])
(iterate (fn [[p b]]
(if (core/== 2147483648 b)
[(core/inc p) 1]
[p (core/bit-shift-left b 1)]))
[0 1])))
(def fast-path-protocol-partitions-count
"total number of partitions"
(let [c (count fast-path-protocols)
m (core/mod c 32)]
(if (core/zero? m)
(core/quot c 32)
(core/inc (core/quot c 32)))))
(defmacro str [& xs]
(let [strs (->> (repeat (count xs) "cljs.core.str(~{})")
(interpose ",")
(apply core/str))]
(concat (list 'js* (core/str "[" strs "].join('')")) xs)))
(defn bool-expr [e]
(vary-meta e assoc :tag 'boolean))
(defmacro nil? [x]
`(coercive-= ~x nil))
;; internal - do not use.
(defmacro coercive-not [x]
(bool-expr (list 'js* "(!~{})" x)))
;; internal - do not use.
(defmacro coercive-not= [x y]
(bool-expr (list 'js* "(~{} != ~{})" x y)))
;; internal - do not use.
(defmacro coercive-= [x y]
(bool-expr (list 'js* "(~{} == ~{})" x y)))
(defmacro true? [x]
(bool-expr (list 'js* "~{} === true" x)))
(defmacro false? [x]
(bool-expr (list 'js* "~{} === false" x)))
(defmacro undefined? [x]
(bool-expr (list 'js* "(void 0 === ~{})" x)))
(defmacro identical? [a b]
(bool-expr (list 'js* "(~{} === ~{})" a b)))
(defmacro aget
([a i]
(list 'js* "(~{}[~{}])" a i))
([a i & idxs]
(let [astr (apply core/str (repeat (count idxs) "[~{}]"))]
`(~'js* ~(core/str "(~{}[~{}]" astr ")") ~a ~i ~@idxs))))
(defmacro aset [a i v]
(list 'js* "(~{}[~{}] = ~{})" a i v))
(defmacro +
([] 0)
([x] x)
([x y] (list 'js* "(~{} + ~{})" x y))
([x y & more] `(+ (+ ~x ~y) ~@more)))
(defmacro -
([x] (list 'js* "(- ~{})" x))
([x y] (list 'js* "(~{} - ~{})" x y))
([x y & more] `(- (- ~x ~y) ~@more)))
(defmacro *
([] 1)
([x] x)
([x y] (list 'js* "(~{} * ~{})" x y))
([x y & more] `(* (* ~x ~y) ~@more)))
(defmacro /
([x] `(/ 1 ~x))
([x y] (list 'js* "(~{} / ~{})" x y))
([x y & more] `(/ (/ ~x ~y) ~@more)))
(defmacro <
([x] true)
([x y] (bool-expr (list 'js* "(~{} < ~{})" x y)))
([x y & more] `(and (< ~x ~y) (< ~y ~@more))))
(defmacro <=
([x] true)
([x y] (bool-expr (list 'js* "(~{} <= ~{})" x y)))
([x y & more] `(and (<= ~x ~y) (<= ~y ~@more))))
(defmacro >
([x] true)
([x y] (bool-expr (list 'js* "(~{} > ~{})" x y)))
([x y & more] `(and (> ~x ~y) (> ~y ~@more))))
(defmacro >=
([x] true)
([x y] (bool-expr (list 'js* "(~{} >= ~{})" x y)))
([x y & more] `(and (>= ~x ~y) (>= ~y ~@more))))
(defmacro ==
([x] true)
([x y] (bool-expr (list 'js* "(~{} === ~{})" x y)))
([x y & more] `(and (== ~x ~y) (== ~y ~@more))))
(defmacro dec [x]
`(- ~x 1))
(defmacro inc [x]
`(+ ~x 1))
(defmacro zero? [x]
`(== ~x 0))
(defmacro pos? [x]
`(> ~x 0))
(defmacro neg? [x]
`(< ~x 0))
(defmacro max
([x] x)
([x y] (list 'js* "((~{} > ~{}) ? ~{} : ~{})" x y x y))
([x y & more] `(max (max ~x ~y) ~@more)))
(defmacro min
([x] x)
([x y] (list 'js* "((~{} < ~{}) ? ~{} : ~{})" x y x y))
([x y & more] `(min (min ~x ~y) ~@more)))
(defmacro mod [num div]
(list 'js* "(~{} % ~{})" num div))
(defmacro bit-not [x]
(list 'js* "(~ ~{})" x))
(defmacro bit-and
([x y] (list 'js* "(~{} & ~{})" x y))
([x y & more] `(bit-and (bit-and ~x ~y) ~@more)))
;; internal do not use
(defmacro unsafe-bit-and
([x y] (bool-expr (list 'js* "(~{} & ~{})" x y)))
([x y & more] `(unsafe-bit-and (unsafe-bit-and ~x ~y) ~@more)))
(defmacro bit-or
([x y] (list 'js* "(~{} | ~{})" x y))
([x y & more] `(bit-or (bit-or ~x ~y) ~@more)))
(defmacro bit-xor
([x y] (list 'js* "(~{} ^ ~{})" x y))
([x y & more] `(bit-xor (bit-xor ~x ~y) ~@more)))
(defmacro bit-and-not
([x y] (list 'js* "(~{} & ~~{})" x y))
([x y & more] `(bit-and-not (bit-and-not ~x ~y) ~@more)))
(defmacro bit-clear [x n]
(list 'js* "(~{} & ~(1 << ~{}))" x n))
(defmacro bit-flip [x n]
(list 'js* "(~{} ^ (1 << ~{}))" x n))
(defmacro bit-test [x n]
(list 'js* "((~{} & (1 << ~{})) != 0)" x n))
(defmacro bit-shift-left [x n]
(list 'js* "(~{} << ~{})" x n))
(defmacro bit-shift-right [x n]
(list 'js* "(~{} >> ~{})" x n))
(defmacro bit-shift-right-zero-fill [x n]
(list 'js* "(~{} >>> ~{})" x n))
(defmacro bit-set [x n]
(list 'js* "(~{} | (1 << ~{}))" x n))
;; internal
(defmacro mask [hash shift]
(list 'js* "((~{} >>> ~{}) & 0x01f)" hash shift))
;; internal
(defmacro bitpos [hash shift]
(list 'js* "(1 << ~{})" `(mask ~hash ~shift)))
;; internal
(defmacro caching-hash [coll hash-fn hash-key]
`(let [h# ~hash-key]
(if-not (nil? h#)
h#
(let [h# (~hash-fn ~coll)]
(set! ~hash-key h#)
h#))))
(defmacro get
([coll k]
`(-lookup ~coll ~k nil))
([coll k not-found]
`(-lookup ~coll ~k ~not-found)))
;;; internal -- reducers-related macros
(defn- do-curried
[name doc meta args body]
(let [cargs (vec (butlast args))]
`(defn ~name ~doc ~meta
(~cargs (fn [x#] (~name ~@cargs x#)))
(~args ~@body))))
(defmacro ^:private defcurried
"Builds another arity of the fn that returns a fn awaiting the last
param"
[name doc meta args & body]
(do-curried name doc meta args body))
(defn- do-rfn [f1 k fkv]
`(fn
([] (~f1))
~(clojure.walk/postwalk
#(if (sequential? %)
((if (vector? %) vec identity)
(core/remove #{k} %))
%)
fkv)
~fkv))
(defmacro ^:private rfn
"Builds 3-arity reducing fn given names of wrapped fn and key, and k/v impl."
[[f1 k] fkv]
(do-rfn f1 k fkv))
;;; end of reducers macros
(defn protocol-prefix [psym]
(core/str (-> (core/str psym) (.replace \. \$) (.replace \/ \$)) "$"))
(def #^:private base-type
{nil "null"
'object "object"
'string "string"
'number "number"
'array "array"
'function "function"
'boolean "boolean"
'default "_"})
(defmacro reify [& impls]
(let [t (gensym "t")
meta-sym (gensym "meta")
this-sym (gensym "_")
locals (keys (:locals &env))
ns (-> &env :ns :name)
munge cljs.compiler/munge
ns-t (list 'js* (core/str (munge ns) "." (munge t)))]
`(do
(when (undefined? ~ns-t)
(deftype ~t [~@locals ~meta-sym]
IWithMeta
(~'-with-meta [~this-sym ~meta-sym]
(new ~t ~@locals ~meta-sym))
IMeta
(~'-meta [~this-sym] ~meta-sym)
~@impls))
(new ~t ~@locals nil))))
(defmacro this-as
"Defines a scope where JavaScript's implicit \"this\" is bound to the name provided."
[name & body]
`(let [~name (~'js* "this")]
~@body))
(defn to-property [sym]
(symbol (core/str "-" sym)))
(defmacro extend-type [tsym & impls]
(let [resolve #(let [ret (:name (cljs.analyzer/resolve-var (dissoc &env :locals) %))]
(assert ret (core/str "Can't resolve: " %))
ret)
impl-map (loop [ret {} s impls]
(if (seq s)
(recur (assoc ret (first s) (take-while seq? (next s)))
(drop-while seq? (next s)))
ret))
warn-if-not-protocol #(when-not (= 'Object %)
(if cljs.analyzer/*cljs-warn-on-undeclared*
(if-let [var (cljs.analyzer/resolve-existing-var (dissoc &env :locals) %)]
(do
(when-not (:protocol-symbol var)
(cljs.analyzer/warning &env
(core/str "WARNING: Symbol " % " is not a protocol")))
(when (and cljs.analyzer/*cljs-warn-protocol-deprecated*
(-> var :deprecated)
(not (-> % meta :deprecation-nowarn)))
(cljs.analyzer/warning &env
(core/str "WARNING: Protocol " % " is deprecated"))))
(cljs.analyzer/warning &env
(core/str "WARNING: Can't resolve protocol symbol " %)))))
skip-flag (set (-> tsym meta :skip-protocol-flag))]
(if (base-type tsym)
(let [t (base-type tsym)
assign-impls (fn [[p sigs]]
(warn-if-not-protocol p)
(let [psym (resolve p)
pfn-prefix (subs (core/str psym) 0 (clojure.core/inc (.indexOf (core/str psym) "/")))]
(cons `(aset ~psym ~t true)
(map (fn [[f & meths :as form]]
`(aset ~(symbol (core/str pfn-prefix f)) ~t ~(with-meta `(fn ~@meths) (meta form))))
sigs))))]
`(do ~@(mapcat assign-impls impl-map)))
(let [t (resolve tsym)
prototype-prefix (fn [sym]
`(.. ~tsym -prototype ~(to-property sym)))
assign-impls (fn [[p sigs]]
(warn-if-not-protocol p)
(let [psym (resolve p)
pprefix (protocol-prefix psym)]
(if (= p 'Object)
(let [adapt-params (fn [[sig & body]]
(let [[tname & args] sig]
(list (vec args) (list* 'this-as (vary-meta tname assoc :tag t) body))))]
(map (fn [[f & meths :as form]]
`(set! ~(prototype-prefix f)
~(with-meta `(fn ~@(map adapt-params meths)) (meta form))))
sigs))
(concat (when-not (skip-flag psym)
[`(set! ~(prototype-prefix pprefix) true)])
(mapcat (fn [[f & meths :as form]]
(if (= psym 'cljs.core/IFn)
(let [adapt-params (fn [[[targ & args :as sig] & body]]
(let [this-sym (with-meta (gensym "this-sym") {:tag t})]
`(~(vec (cons this-sym args))
(this-as ~this-sym
(let [~targ ~this-sym]
~@body)))))
meths (map adapt-params meths)
this-sym (with-meta (gensym "this-sym") {:tag t})
argsym (gensym "args")]
[`(set! ~(prototype-prefix 'call) ~(with-meta `(fn ~@meths) (meta form)))
`(set! ~(prototype-prefix 'apply)
~(with-meta
`(fn ~[this-sym argsym]
(.apply (.-call ~this-sym) ~this-sym
(.concat (array ~this-sym) (aclone ~argsym))))
(meta form)))])
(let [pf (core/str pprefix f)
adapt-params (fn [[[targ & args :as sig] & body]]
(cons (vec (cons (vary-meta targ assoc :tag t) args))
body))]
(if (vector? (first meths))
[`(set! ~(prototype-prefix (core/str pf "$arity$" (count (first meths)))) ~(with-meta `(fn ~@(adapt-params meths)) (meta form)))]
(map (fn [[sig & body :as meth]]
`(set! ~(prototype-prefix (core/str pf "$arity$" (count sig)))
~(with-meta `(fn ~(adapt-params meth)) (meta form))))
meths)))))
sigs)))))]
`(do ~@(mapcat assign-impls impl-map))))))
(defn- prepare-protocol-masks [env t impls]
(let [resolve #(let [ret (:name (cljs.analyzer/resolve-var (dissoc env :locals) %))]
(assert ret (core/str "Can't resolve: " %))
ret)
impl-map (loop [ret {} s impls]
(if (seq s)
(recur (assoc ret (first s) (take-while seq? (next s)))
(drop-while seq? (next s)))
ret))]
(if-let [fpp-pbs (seq (keep fast-path-protocols
(map resolve
(keys impl-map))))]
(let [fpps (into #{} (filter (partial contains? fast-path-protocols)
(map resolve
(keys impl-map))))
fpp-partitions (group-by first fpp-pbs)
fpp-partitions (into {} (map (juxt key (comp (partial map peek) val))
fpp-partitions))
fpp-partitions (into {} (map (juxt key (comp (partial reduce core/bit-or) val))
fpp-partitions))]
[fpps
(reduce (fn [ps p]
(update-in ps [p] (fnil identity 0)))
fpp-partitions
(range fast-path-protocol-partitions-count))]))))
(defn dt->et
([t specs fields] (dt->et t specs fields false))
([t specs fields inline]
(loop [ret [] s specs]
(if (seq s)
(recur (-> ret
(conj (first s))
(into
(reduce (fn [v [f sigs]]
(conj v (vary-meta (cons f (map #(cons (second %) (nnext %)) sigs))
assoc :cljs.analyzer/type t
:cljs.analyzer/fields fields
:protocol-impl true
:protocol-inline inline)))
[]
(group-by first (take-while seq? (next s))))))
(drop-while seq? (next s)))
ret))))
(defn collect-protocols [impls env]
(->> impls
(filter symbol?)
(map #(:name (cljs.analyzer/resolve-var (dissoc env :locals) %)))
(into #{})))
(defmacro deftype [t fields & impls]
(let [r (:name (cljs.analyzer/resolve-var (dissoc &env :locals) t))
[fpps pmasks] (prepare-protocol-masks &env t impls)
protocols (collect-protocols impls &env)
t (vary-meta t assoc
:protocols protocols
:skip-protocol-flag fpps) ]
(if (seq impls)
`(do
(deftype* ~t ~fields ~pmasks)
(set! (.-cljs$lang$type ~t) true)
(set! (.-cljs$lang$ctorPrSeq ~t) (fn [this#] (list ~(core/str r))))
(set! (.-cljs$lang$ctorPrWriter ~t) (fn [this# writer#] (-write writer# ~(core/str r))))
(extend-type ~t ~@(dt->et t impls fields true))
~t)
`(do
(deftype* ~t ~fields ~pmasks)
(set! (.-cljs$lang$type ~t) true)
(set! (.-cljs$lang$ctorPrSeq ~t) (fn [this#] (list ~(core/str r))))
(set! (.-cljs$lang$ctorPrWriter ~t) (fn [this# writer#] (-write writer# ~(core/str r))))
~t))))
(defn- emit-defrecord
"Do not use this directly - use defrecord"
[env tagname rname fields impls]
(let [hinted-fields fields
fields (vec (map #(with-meta % nil) fields))
base-fields fields
fields (conj fields '__meta '__extmap (with-meta '__hash {:mutable true}))]
(let [gs (gensym)
ksym (gensym "k")
impls (concat
impls
['IRecord
'IHash
`(~'-hash [this#] (caching-hash this# ~'hash-imap ~'__hash))
'IEquiv
`(~'-equiv [this# other#]
(if (and other#
(identical? (.-constructor this#)
(.-constructor other#))
(equiv-map this# other#))
true
false))
'IMeta
`(~'-meta [this#] ~'__meta)
'IWithMeta
`(~'-with-meta [this# ~gs] (new ~tagname ~@(replace {'__meta gs} fields)))
'ILookup
`(~'-lookup [this# k#] (-lookup this# k# nil))
`(~'-lookup [this# ~ksym else#]
(cond
~@(mapcat (fn [f] [`(identical? ~ksym ~(keyword f)) f]) base-fields)
:else (get ~'__extmap ~ksym else#)))
'ICounted
`(~'-count [this#] (+ ~(count base-fields) (count ~'__extmap)))
'ICollection
`(~'-conj [this# entry#]
(if (vector? entry#)
(-assoc this# (-nth entry# 0) (-nth entry# 1))
(reduce -conj
this#
entry#)))
'IAssociative
`(~'-assoc [this# k# ~gs]
(condp identical? k#
~@(mapcat (fn [fld]
[(keyword fld) (list* `new tagname (replace {fld gs '__hash nil} fields))])
base-fields)
(new ~tagname ~@(remove #{'__extmap '__hash} fields) (assoc ~'__extmap k# ~gs) nil)))
'IMap
`(~'-dissoc [this# k#] (if (contains? #{~@(map keyword base-fields)} k#)
(dissoc (with-meta (into {} this#) ~'__meta) k#)
(new ~tagname ~@(remove #{'__extmap '__hash} fields)
(not-empty (dissoc ~'__extmap k#))
nil)))
'ISeqable
`(~'-seq [this#] (seq (concat [~@(map #(list `vector (keyword %) %) base-fields)]
~'__extmap)))
'IPrintWithWriter
`(~'-pr-writer [this# writer# opts#]
(let [pr-pair# (fn [keyval#] (pr-sequential-writer writer# pr-writer "" " " "" opts# keyval#))]
(pr-sequential-writer
writer# pr-pair# (core/str "#" ~(name rname) "{") ", " "}" opts#
(concat [~@(map #(list `vector (keyword %) %) base-fields)]
~'__extmap))))
])
[fpps pmasks] (prepare-protocol-masks env tagname impls)
protocols (collect-protocols impls env)
tagname (vary-meta tagname assoc
:protocols protocols
:skip-protocol-flag fpps)]
`(do
(~'defrecord* ~tagname ~hinted-fields ~pmasks)
(extend-type ~tagname ~@(dt->et tagname impls fields true))))))
(defn- build-positional-factory
[rsym rname fields]
(let [fn-name (symbol (core/str '-> rsym))]
`(defn ~fn-name
[~@fields]
(new ~rname ~@fields))))
(defn- build-map-factory
[rsym rname fields]
(let [fn-name (symbol (core/str 'map-> rsym))
ms (gensym)
ks (map keyword fields)
getters (map (fn [k] `(~k ~ms)) ks)]
`(defn ~fn-name
[~ms]
(new ~rname ~@getters nil (dissoc ~ms ~@ks)))))
(defmacro defrecord [rsym fields & impls]
(let [r (:name (cljs.analyzer/resolve-var (dissoc &env :locals) rsym))]
`(let []
~(emit-defrecord &env rsym r fields impls)
(set! (.-cljs$lang$type ~r) true)
(set! (.-cljs$lang$ctorPrSeq ~r) (fn [this#] (list ~(core/str r))))
(set! (.-cljs$lang$ctorPrWriter ~r) (fn [this# writer#] (-write writer# ~(core/str r))))
~(build-positional-factory rsym r fields)
~(build-map-factory rsym r fields)
~r)))
(defmacro defprotocol [psym & doc+methods]
(let [p (:name (cljs.analyzer/resolve-var (dissoc &env :locals) psym))
psym (vary-meta psym assoc :protocol-symbol true)
ns-name (-> &env :ns :name)
fqn (fn [n] (symbol (core/str ns-name "." n)))
prefix (protocol-prefix p)
methods (if (core/string? (first doc+methods)) (next doc+methods) doc+methods)
expand-sig (fn [fname slot sig]
`(~sig
(if (and ~(first sig) (. ~(first sig) ~(symbol (core/str "-" slot)))) ;; Property access needed here.
(. ~(first sig) ~slot ~@sig)
(let [x# (if (nil? ~(first sig)) nil ~(first sig))]
((or
(aget ~(fqn fname) (goog.typeOf x#))
(aget ~(fqn fname) "_")
(throw (missing-protocol
~(core/str psym "." fname) ~(first sig))))
~@sig)))))
method (fn [[fname & sigs]]
(let [sigs (take-while vector? sigs)
slot (symbol (core/str prefix (name fname)))
fname (vary-meta fname assoc :protocol p)]
`(defn ~fname ~@(map (fn [sig]
(expand-sig fname
(symbol (core/str slot "$arity$" (count sig)))
sig))
sigs))))]
`(do
(set! ~'*unchecked-if* true)
(def ~psym (~'js* "{}"))
~@(map method methods)
(set! ~'*unchecked-if* false))))
(defmacro satisfies?
"Returns true if x satisfies the protocol"
[psym x]
(let [p (:name (cljs.analyzer/resolve-var (dissoc &env :locals) psym))
prefix (protocol-prefix p)
xsym (bool-expr (gensym))
[part bit] (fast-path-protocols p)
msym (symbol (core/str "-cljs$lang$protocol_mask$partition" part "$"))]
`(let [~xsym ~x]
(if ~xsym
(if (or ~(if bit `(unsafe-bit-and (. ~xsym ~msym) ~bit))
~(bool-expr `(. ~xsym ~(symbol (core/str "-" prefix)))))
true
(if (coercive-not (. ~xsym ~msym))
(cljs.core/type_satisfies_ ~psym ~xsym)
false))
(cljs.core/type_satisfies_ ~psym ~xsym)))))
(defmacro lazy-seq [& body]
`(new cljs.core/LazySeq nil false (fn [] ~@body) nil))
(defmacro delay [& body]
"Takes a body of expressions and yields a Delay object that will
invoke the body only the first time it is forced (with force or deref/@), and
will cache the result and return it on all subsequent force
calls."
`(new cljs.core/Delay (atom {:done false, :value nil}) (fn [] ~@body)))
(defmacro binding
"binding => var-symbol init-expr
Creates new bindings for the (already-existing) vars, with the
supplied initial values, executes the exprs in an implicit do, then
re-establishes the bindings that existed before. The new bindings
are made in parallel (unlike let); all init-exprs are evaluated
before the vars are bound to their new values."
[bindings & body]
(let [names (take-nth 2 bindings)
vals (take-nth 2 (drop 1 bindings))
tempnames (map (comp gensym name) names)
binds (map vector names vals)
resets (reverse (map vector names tempnames))]
(cljs.analyzer/confirm-bindings &env names)
`(let [~@(interleave tempnames names)]
(try
~@(map
(fn [[k v]] (list 'set! k v))
binds)
~@body
(finally
~@(map
(fn [[k v]] (list 'set! k v))
resets))))))
(defmacro condp
"Takes a binary predicate, an expression, and a set of clauses.
Each clause can take the form of either:
test-expr result-expr
test-expr :>> result-fn
Note :>> is an ordinary keyword.
For each clause, (pred test-expr expr) is evaluated. If it returns
logical true, the clause is a match. If a binary clause matches, the
result-expr is returned, if a ternary clause matches, its result-fn,
which must be a unary function, is called with the result of the
predicate as its argument, the result of that call being the return
value of condp. A single default expression can follow the clauses,
and its value will be returned if no clause matches. If no default
expression is provided and no clause matches, an
IllegalArgumentException is thrown."
{:added "1.0"}
[pred expr & clauses]
(let [gpred (gensym "pred__")
gexpr (gensym "expr__")
emit (fn emit [pred expr args]
(let [[[a b c :as clause] more]
(split-at (if (= :>> (second args)) 3 2) args)
n (count clause)]
(cond
(= 0 n) `(throw (js/Error. (core/str "No matching clause: " ~expr)))
(= 1 n) a
(= 2 n) `(if (~pred ~a ~expr)
~b
~(emit pred expr more))
:else `(if-let [p# (~pred ~a ~expr)]
(~c p#)
~(emit pred expr more)))))
gres (gensym "res__")]
`(let [~gpred ~pred
~gexpr ~expr]
~(emit gpred gexpr clauses))))
(defmacro case [e & clauses]
(let [default (if (odd? (count clauses))
(last clauses)
`(throw (js/Error. (core/str "No matching clause: " ~e))))
assoc-test (fn assoc-test [m test expr]
(if (contains? m test)
(throw (clojure.core/IllegalArgumentException.
(core/str "Duplicate case test constant '"
test "'"
(when (:line &env)
(core/str " on line " (:line &env) " "
cljs.analyzer/*cljs-file*)))))
(assoc m test expr)))
pairs (reduce (fn [m [test expr]]
(cond
(seq? test) (reduce (fn [m test]
(let [test (if (symbol? test)
(list 'quote test)
test)]
(assoc-test m test expr)))
m test)
(symbol? test) (assoc-test m (list 'quote test) expr)
:else (assoc-test m test expr)))
{} (partition 2 clauses))
esym (gensym)]
`(let [~esym ~e]
(cond
~@(mapcat (fn [[m c]] `((cljs.core/= ~m ~esym) ~c)) pairs)
:else ~default))))
(defmacro try
"(try expr* catch-clause* finally-clause?)
Special Form
catch-clause => (catch protoname name expr*)
finally-clause => (finally expr*)
Catches and handles JavaScript exceptions."
[& forms]
(let [catch? #(and (list? %) (= (first %) 'catch))
[body catches] (split-with (complement catch?) forms)
[catches fin] (split-with catch? catches)
e (gensym "e")]
(assert (every? #(clojure.core/> (count %) 2) catches) "catch block must specify a prototype and a name")
(if (seq catches)
`(~'try*
~@body
(catch ~e
(cond
~@(mapcat
(fn [[_ type name & cb]]
`[(instance? ~type ~e) (let [~name ~e] ~@cb)])
catches)
:else (throw ~e)))
~@fin)
`(~'try*
~@body
~@fin))))
(defmacro assert
"Evaluates expr and throws an exception if it does not evaluate to
logical true."
([x]
(when *assert*
`(when-not ~x
(throw (js/Error.
(cljs.core/str "Assert failed: " (cljs.core/pr-str '~x)))))))
([x message]
(when *assert*
`(when-not ~x
(throw (js/Error.
(cljs.core/str "Assert failed: " ~message "\n" (cljs.core/pr-str '~x))))))))
(defmacro for
"List comprehension. Takes a vector of one or more
binding-form/collection-expr pairs, each followed by zero or more
modifiers, and yields a lazy sequence of evaluations of expr.
Collections are iterated in a nested fashion, rightmost fastest,
and nested coll-exprs can refer to bindings created in prior
binding-forms. Supported modifiers are: :let [binding-form expr ...],
:while test, :when test.
(take 100 (for [x (range 100000000) y (range 1000000) :while (< y x)] [x y]))"
[seq-exprs body-expr]
(assert-args for
(vector? seq-exprs) "a vector for its binding"
(even? (count seq-exprs)) "an even number of forms in binding vector")
(let [to-groups (fn [seq-exprs]
(reduce (fn [groups [k v]]
(if (keyword? k)
(conj (pop groups) (conj (peek groups) [k v]))
(conj groups [k v])))
[] (partition 2 seq-exprs)))
err (fn [& msg] (throw (apply core/str msg)))
emit-bind (fn emit-bind [[[bind expr & mod-pairs]
& [[_ next-expr] :as next-groups]]]
(let [giter (gensym "iter__")
gxs (gensym "s__")
do-mod (fn do-mod [[[k v :as pair] & etc]]
(cond
(= k :let) `(let ~v ~(do-mod etc))
(= k :while) `(when ~v ~(do-mod etc))
(= k :when) `(if ~v
~(do-mod etc)
(recur (rest ~gxs)))
(keyword? k) (err "Invalid 'for' keyword " k)
next-groups
`(let [iterys# ~(emit-bind next-groups)
fs# (seq (iterys# ~next-expr))]
(if fs#
(concat fs# (~giter (rest ~gxs)))
(recur (rest ~gxs))))
:else `(cons ~body-expr
(~giter (rest ~gxs)))))]
`(fn ~giter [~gxs]
(lazy-seq
(loop [~gxs ~gxs]
(when-first [~bind ~gxs]
~(do-mod mod-pairs)))))))]
`(let [iter# ~(emit-bind (to-groups seq-exprs))]
(iter# ~(second seq-exprs)))))
(defmacro doseq
"Repeatedly executes body (presumably for side-effects) with
bindings and filtering as provided by \"for\". Does not retain
the head of the sequence. Returns nil."
[seq-exprs & body]
(assert-args doseq
(vector? seq-exprs) "a vector for its binding"
(even? (count seq-exprs)) "an even number of forms in binding vector")
(let [step (fn step [recform exprs]
(if-not exprs
[true `(do ~@body)]
(let [k (first exprs)
v (second exprs)
seqsym (when-not (keyword? k) (gensym))
recform (if (keyword? k) recform `(recur (next ~seqsym)))
steppair (step recform (nnext exprs))
needrec (steppair 0)
subform (steppair 1)]
(cond
(= k :let) [needrec `(let ~v ~subform)]
(= k :while) [false `(when ~v
~subform
~@(when needrec [recform]))]
(= k :when) [false `(if ~v
(do
~subform
~@(when needrec [recform]))
~recform)]
:else [true `(loop [~seqsym (seq ~v)]
(when ~seqsym
(let [~k (first ~seqsym)]
~subform
~@(when needrec [recform]))))]))))]
(nth (step nil (seq seq-exprs)) 1)))
(defmacro array [& rest]
(let [xs-str (->> (repeat "~{}")
(take (count rest))
(interpose ",")
(apply core/str))]
(concat
(list 'js* (core/str "[" xs-str "]"))
rest)))
(defmacro js-obj [& rest]
(let [kvs-str (->> (repeat "~{}:~{}")
(take (quot (count rest) 2))
(interpose ",")
(apply core/str))]
(concat
(list 'js* (core/str "{" kvs-str "}"))
rest)))
(defmacro alength [a]
(list 'js* "~{}.length" a))
(defmacro aclone [a]
(list 'js* "~{}.slice()" a))
(defmacro amap
"Maps an expression across an array a, using an index named idx, and
return value named ret, initialized to a clone of a, then setting
each element of ret to the evaluation of expr, returning the new
array ret."
[a idx ret expr]
`(let [a# ~a
~ret (aclone a#)]
(loop [~idx 0]
(if (< ~idx (alength a#))
(do
(aset ~ret ~idx ~expr)
(recur (inc ~idx)))
~ret))))
(defmacro areduce
"Reduces an expression across an array a, using an index named idx,
and return value named ret, initialized to init, setting ret to the
evaluation of expr at each step, returning ret."
[a idx ret init expr]
`(let [a# ~a]
(loop [~idx 0 ~ret ~init]
(if (< ~idx (alength a#))
(recur (inc ~idx) ~expr)
~ret))))
(defmacro dotimes
"bindings => name n
Repeatedly executes body (presumably for side-effects) with name
bound to integers from 0 through n-1."
[bindings & body]
(let [i (first bindings)
n (second bindings)]
`(let [n# ~n]
(loop [~i 0]
(when (< ~i n#)
~@body
(recur (inc ~i)))))))
(defn ^:private check-valid-options
"Throws an exception if the given option map contains keys not listed
as valid, else returns nil."
[options & valid-keys]
(when (seq (apply disj (apply hash-set (keys options)) valid-keys))
(throw
(apply core/str "Only these options are valid: "
(first valid-keys)
(map #(core/str ", " %) (rest valid-keys))))))
(defmacro defmulti
"Creates a new multimethod with the associated dispatch function.
The docstring and attribute-map are optional.
Options are key-value pairs and may be one of:
:default the default dispatch value, defaults to :default
:hierarchy the isa? hierarchy to use for dispatching
defaults to the global hierarchy"
[mm-name & options]
(let [docstring (if (core/string? (first options))
(first options)
nil)
options (if (core/string? (first options))
(next options)
options)
m (if (map? (first options))
(first options)
{})
options (if (map? (first options))
(next options)
options)
dispatch-fn (first options)
options (next options)
m (if docstring
(assoc m :doc docstring)
m)
m (if (meta mm-name)
(conj (meta mm-name) m)
m)]
(when (= (count options) 1)
(throw "The syntax for defmulti has changed. Example: (defmulti name dispatch-fn :default dispatch-value)"))
(let [options (apply hash-map options)
default (core/get options :default :default)]
(check-valid-options options :default :hierarchy)
`(def ~(with-meta mm-name m)
(let [method-table# (atom {})
prefer-table# (atom {})
method-cache# (atom {})
cached-hierarchy# (atom {})
hierarchy# (get ~options :hierarchy cljs.core/global-hierarchy)]
(cljs.core/MultiFn. ~(name mm-name) ~dispatch-fn ~default hierarchy#
method-table# prefer-table# method-cache# cached-hierarchy#))))))
(defmacro defmethod
"Creates and installs a new method of multimethod associated with dispatch-value. "
[multifn dispatch-val & fn-tail]
`(-add-method ~(with-meta multifn {:tag 'cljs.core/MultiFn}) ~dispatch-val (fn ~@fn-tail)))
(defmacro time
"Evaluates expr and prints the time it took. Returns the value of expr."
[expr]
`(let [start# (.getTime (js/Date.))
ret# ~expr]
(prn (core/str "Elapsed time: " (- (.getTime (js/Date.)) start#) " msecs"))
ret#))
(defmacro simple-benchmark
"Runs expr iterations times in the context of a let expression with
the given bindings, then prints out the bindings and the expr
followed by number of iterations and total time. The optional
argument print-fn, defaulting to println, sets function used to
print the result. expr's string representation will be produced
using pr-str in any case."
[bindings expr iterations & {:keys [print-fn] :or {print-fn 'println}}]
(let [bs-str (pr-str bindings)
expr-str (pr-str expr)]
`(let ~bindings
(let [start# (.getTime (js/Date.))
ret# (dotimes [_# ~iterations] ~expr)
end# (.getTime (js/Date.))
elapsed# (- end# start#)]
(~print-fn (str ~bs-str ", " ~expr-str ", "
~iterations " runs, " elapsed# " msecs"))))))
(def cs (into [] (map (comp symbol core/str char) (range 97 118))))
(defn gen-apply-to-helper
([] (gen-apply-to-helper 1))
([n]
(let [prop (symbol (core/str "-cljs$lang$arity$" n))
f (symbol (core/str "cljs$lang$arity$" n))]
(if (core/<= n 20)
`(let [~(cs (core/dec n)) (-first ~'args)
~'args (-rest ~'args)]
(if (core/== ~'argc ~n)
(if (. ~'f ~prop)
(. ~'f (~f ~@(take n cs)))
(~'f ~@(take n cs)))
~(gen-apply-to-helper (core/inc n))))
`(throw (js/Error. "Only up to 20 arguments supported on functions"))))))
(defmacro gen-apply-to []
`(do
(set! ~'*unchecked-if* true)
(defn ~'apply-to [~'f ~'argc ~'args]
(let [~'args (seq ~'args)]
(if (zero? ~'argc)
(~'f)
~(gen-apply-to-helper))))
(set! ~'*unchecked-if* false)))
|
[
{
"context": "(ns cljnode.server\r\n #^{:authors [\"Maxim Molchanov <elzor.job@gmail.com>\",\r\n \"Duncan",
"end": 53,
"score": 0.9998437762260437,
"start": 38,
"tag": "NAME",
"value": "Maxim Molchanov"
},
{
"context": "ljnode.server\r\n #^{:authors [\"Maxim Molchanov <elzor.job@gmail.com>\",\r\n \"Duncan McGreggor <oubiwann@",
"end": 74,
"score": 0.9999317526817322,
"start": 55,
"tag": "EMAIL",
"value": "elzor.job@gmail.com"
},
{
"context": "chanov <elzor.job@gmail.com>\",\r\n \"Duncan McGreggor <oubiwann@gmail.com>\"],\r\n :doc \"Main server",
"end": 113,
"score": 0.9998787045478821,
"start": 97,
"tag": "NAME",
"value": "Duncan McGreggor"
},
{
"context": "gmail.com>\",\r\n \"Duncan McGreggor <oubiwann@gmail.com>\"],\r\n :doc \"Main server class\"}\r\n (:requ",
"end": 133,
"score": 0.9999281167984009,
"start": 115,
"tag": "EMAIL",
"value": "oubiwann@gmail.com"
}
] | src/clj/cljnode/server.clj | J3T4R0/duplet-public | 0 | (ns cljnode.server
#^{:authors ["Maxim Molchanov <elzor.job@gmail.com>",
"Duncan McGreggor <oubiwann@gmail.com>"],
:doc "Main server class"}
(:require [clojure.tools.logging :as log]
[cljnode.proto :as proto])
(:import [com.ericsson.otp.erlang
OtpErlangTuple
OtpNode])
(:gen-class))
(defn process
[msg mbox]
(def cmd (.elementAt ^OtpErlangTuple msg 0))
(cond
(= (.atomValue cmd) "ping") (proto/handle-ping msg mbox)
:else (log/error (format "Undefined msg: %s" (str msg)))))
(defn handle-erl-messages
[mbox]
(try (def msg (.receive mbox 50))
(if (instance? OtpErlangTuple msg) (process msg mbox) ())
#(handle-erl-messages mbox)
(catch Exception e (log/error (format (str e))))))
(defn server
[NodeName Mbox Cookie Port]
(log/info (format "Started with params:\n\tnodename: %s\n\tmbox: %s\n\tcookie: %s\n\tepmd_port: %s"
NodeName Mbox Cookie Port))
(def mbox (.createMbox (new OtpNode NodeName Cookie Port) Mbox))
(proto/check-erl-node mbox 10000)
(trampoline handle-erl-messages mbox)
(log/info "Terminating Clojure node server ..."))
| 3962 | (ns cljnode.server
#^{:authors ["<NAME> <<EMAIL>>",
"<NAME> <<EMAIL>>"],
:doc "Main server class"}
(:require [clojure.tools.logging :as log]
[cljnode.proto :as proto])
(:import [com.ericsson.otp.erlang
OtpErlangTuple
OtpNode])
(:gen-class))
(defn process
[msg mbox]
(def cmd (.elementAt ^OtpErlangTuple msg 0))
(cond
(= (.atomValue cmd) "ping") (proto/handle-ping msg mbox)
:else (log/error (format "Undefined msg: %s" (str msg)))))
(defn handle-erl-messages
[mbox]
(try (def msg (.receive mbox 50))
(if (instance? OtpErlangTuple msg) (process msg mbox) ())
#(handle-erl-messages mbox)
(catch Exception e (log/error (format (str e))))))
(defn server
[NodeName Mbox Cookie Port]
(log/info (format "Started with params:\n\tnodename: %s\n\tmbox: %s\n\tcookie: %s\n\tepmd_port: %s"
NodeName Mbox Cookie Port))
(def mbox (.createMbox (new OtpNode NodeName Cookie Port) Mbox))
(proto/check-erl-node mbox 10000)
(trampoline handle-erl-messages mbox)
(log/info "Terminating Clojure node server ..."))
| true | (ns cljnode.server
#^{:authors ["PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>",
"PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"],
:doc "Main server class"}
(:require [clojure.tools.logging :as log]
[cljnode.proto :as proto])
(:import [com.ericsson.otp.erlang
OtpErlangTuple
OtpNode])
(:gen-class))
(defn process
[msg mbox]
(def cmd (.elementAt ^OtpErlangTuple msg 0))
(cond
(= (.atomValue cmd) "ping") (proto/handle-ping msg mbox)
:else (log/error (format "Undefined msg: %s" (str msg)))))
(defn handle-erl-messages
[mbox]
(try (def msg (.receive mbox 50))
(if (instance? OtpErlangTuple msg) (process msg mbox) ())
#(handle-erl-messages mbox)
(catch Exception e (log/error (format (str e))))))
(defn server
[NodeName Mbox Cookie Port]
(log/info (format "Started with params:\n\tnodename: %s\n\tmbox: %s\n\tcookie: %s\n\tepmd_port: %s"
NodeName Mbox Cookie Port))
(def mbox (.createMbox (new OtpNode NodeName Cookie Port) Mbox))
(proto/check-erl-node mbox 10000)
(trampoline handle-erl-messages mbox)
(log/info "Terminating Clojure node server ..."))
|
[
{
"context": "int search-endpoint\n :token user-token\n :params params})\n ",
"end": 4473,
"score": 0.7269780039787292,
"start": 4463,
"tag": "PASSWORD",
"value": "user-token"
}
] | src/cmr/ous/impl/v2_1.clj | chris-durbin/cmr-ous-plugin | 0 | (ns cmr.ous.impl.v2-1
"Version 2.1 was introduced in order to provide better support to EDSC users
who would see their spatial query parameters removed if the variables in their
results did not contain metadata for lat/lon dimensions (support for this was
added in UMM-Var 1.2).
By putting this change into a versioned portion of the API, EDSC (and anyone
else) now has the ability to set the API version to 'v2' and thus still
have the results previously expected when making calls against metadata that
has not been updated to use UMM-Var 1.2."
(:require
[cmr.exchange.common.results.core :as results]
[cmr.exchange.common.results.errors :as errors]
[cmr.exchange.common.results.warnings :as warnings]
[cmr.exchange.common.util :as util]
[cmr.metadata.proxy.concepts.collection :as collection]
[cmr.metadata.proxy.concepts.granule :as granule]
[cmr.metadata.proxy.concepts.service :as service]
[cmr.metadata.proxy.results.errors :as metadata-errors]
[cmr.ous.common :as common]
[cmr.ous.components.config :as config]
[cmr.ous.util.geog :as geog]
[taoensso.timbre :as log]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Stages Overrides for URL Generation ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn stage2
[component coll-promise grans-promise {:keys [endpoint token params]}]
(log/debug "Starting stage 2 ...")
(let [granules (granule/extract-metadata grans-promise)
coll (collection/extract-metadata coll-promise)
data-files (map granule/extract-datafile-link granules)
service-ids (collection/extract-service-ids coll)
vars (common/apply-bounding-conditions endpoint token coll params)
errs (apply errors/collect (concat [granules coll vars] data-files))]
(when errs
(log/error "Stage 2 errors:" errs))
(log/trace "data-files:" (vec data-files))
(log/trace "service ids:" service-ids)
(log/debug "Finishing stage 2 ...")
[params data-files service-ids vars errs]))
(defn stage3
[component service-ids vars bounding-box {:keys [endpoint token params]}]
(log/debug "Starting stage 3 ...")
(let [[vars params bounding-box gridded-warns]
(common/apply-gridded-conditions vars params bounding-box)
services-promise (service/async-get-metadata endpoint token service-ids)
bounding-infos (if-not (seq gridded-warns)
(map #(geog/extract-bounding-info % bounding-box)
vars)
[])
errs (apply errors/collect bounding-infos)
warns (warnings/collect gridded-warns)]
(when errs
(log/error "Stage 3 errors:" errs))
(log/trace "variables bounding-info:" (vec bounding-infos))
(log/debug "Finishing stage 3 ...")
[services-promise vars params bounding-infos errs warns]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; API ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn get-opendap-urls
[component user-token raw-params]
(log/trace "Got params:" raw-params)
(let [start (util/now)
search-endpoint (config/get-search-url component)
;; Stage 1
[params bounding-box grans-promise coll-promise s1-errs]
(common/stage1 component
{:endpoint search-endpoint
:token user-token
:params raw-params})
;; Stage 2
[params data-files service-ids vars s2-errs]
(stage2 component
coll-promise
grans-promise
{:endpoint search-endpoint
:token user-token
:params params})
;; Stage 3
[services vars params bounding-info s3-errs s3-warns]
(stage3 component
service-ids
vars
bounding-box
{:endpoint search-endpoint
:token user-token
:params params})
;; Stage 4
[query s4-errs]
(common/stage4 component
services
bounding-box
bounding-info
{:endpoint search-endpoint
:token user-token
:params params})
;; Warnings for all stages
warns (warnings/collect s3-warns)
;; Error handling for all stages
errs (errors/collect
start params bounding-box grans-promise coll-promise s1-errs
data-files service-ids vars s2-errs
services bounding-info s3-errs
query s4-errs
{:errors (errors/check
[not data-files metadata-errors/empty-gnl-data-files])})]
(common/process-results {:params params
:data-files data-files
:query query} start errs warns)))
| 42585 | (ns cmr.ous.impl.v2-1
"Version 2.1 was introduced in order to provide better support to EDSC users
who would see their spatial query parameters removed if the variables in their
results did not contain metadata for lat/lon dimensions (support for this was
added in UMM-Var 1.2).
By putting this change into a versioned portion of the API, EDSC (and anyone
else) now has the ability to set the API version to 'v2' and thus still
have the results previously expected when making calls against metadata that
has not been updated to use UMM-Var 1.2."
(:require
[cmr.exchange.common.results.core :as results]
[cmr.exchange.common.results.errors :as errors]
[cmr.exchange.common.results.warnings :as warnings]
[cmr.exchange.common.util :as util]
[cmr.metadata.proxy.concepts.collection :as collection]
[cmr.metadata.proxy.concepts.granule :as granule]
[cmr.metadata.proxy.concepts.service :as service]
[cmr.metadata.proxy.results.errors :as metadata-errors]
[cmr.ous.common :as common]
[cmr.ous.components.config :as config]
[cmr.ous.util.geog :as geog]
[taoensso.timbre :as log]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Stages Overrides for URL Generation ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn stage2
[component coll-promise grans-promise {:keys [endpoint token params]}]
(log/debug "Starting stage 2 ...")
(let [granules (granule/extract-metadata grans-promise)
coll (collection/extract-metadata coll-promise)
data-files (map granule/extract-datafile-link granules)
service-ids (collection/extract-service-ids coll)
vars (common/apply-bounding-conditions endpoint token coll params)
errs (apply errors/collect (concat [granules coll vars] data-files))]
(when errs
(log/error "Stage 2 errors:" errs))
(log/trace "data-files:" (vec data-files))
(log/trace "service ids:" service-ids)
(log/debug "Finishing stage 2 ...")
[params data-files service-ids vars errs]))
(defn stage3
[component service-ids vars bounding-box {:keys [endpoint token params]}]
(log/debug "Starting stage 3 ...")
(let [[vars params bounding-box gridded-warns]
(common/apply-gridded-conditions vars params bounding-box)
services-promise (service/async-get-metadata endpoint token service-ids)
bounding-infos (if-not (seq gridded-warns)
(map #(geog/extract-bounding-info % bounding-box)
vars)
[])
errs (apply errors/collect bounding-infos)
warns (warnings/collect gridded-warns)]
(when errs
(log/error "Stage 3 errors:" errs))
(log/trace "variables bounding-info:" (vec bounding-infos))
(log/debug "Finishing stage 3 ...")
[services-promise vars params bounding-infos errs warns]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; API ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn get-opendap-urls
[component user-token raw-params]
(log/trace "Got params:" raw-params)
(let [start (util/now)
search-endpoint (config/get-search-url component)
;; Stage 1
[params bounding-box grans-promise coll-promise s1-errs]
(common/stage1 component
{:endpoint search-endpoint
:token user-token
:params raw-params})
;; Stage 2
[params data-files service-ids vars s2-errs]
(stage2 component
coll-promise
grans-promise
{:endpoint search-endpoint
:token user-token
:params params})
;; Stage 3
[services vars params bounding-info s3-errs s3-warns]
(stage3 component
service-ids
vars
bounding-box
{:endpoint search-endpoint
:token user-token
:params params})
;; Stage 4
[query s4-errs]
(common/stage4 component
services
bounding-box
bounding-info
{:endpoint search-endpoint
:token <PASSWORD>
:params params})
;; Warnings for all stages
warns (warnings/collect s3-warns)
;; Error handling for all stages
errs (errors/collect
start params bounding-box grans-promise coll-promise s1-errs
data-files service-ids vars s2-errs
services bounding-info s3-errs
query s4-errs
{:errors (errors/check
[not data-files metadata-errors/empty-gnl-data-files])})]
(common/process-results {:params params
:data-files data-files
:query query} start errs warns)))
| true | (ns cmr.ous.impl.v2-1
"Version 2.1 was introduced in order to provide better support to EDSC users
who would see their spatial query parameters removed if the variables in their
results did not contain metadata for lat/lon dimensions (support for this was
added in UMM-Var 1.2).
By putting this change into a versioned portion of the API, EDSC (and anyone
else) now has the ability to set the API version to 'v2' and thus still
have the results previously expected when making calls against metadata that
has not been updated to use UMM-Var 1.2."
(:require
[cmr.exchange.common.results.core :as results]
[cmr.exchange.common.results.errors :as errors]
[cmr.exchange.common.results.warnings :as warnings]
[cmr.exchange.common.util :as util]
[cmr.metadata.proxy.concepts.collection :as collection]
[cmr.metadata.proxy.concepts.granule :as granule]
[cmr.metadata.proxy.concepts.service :as service]
[cmr.metadata.proxy.results.errors :as metadata-errors]
[cmr.ous.common :as common]
[cmr.ous.components.config :as config]
[cmr.ous.util.geog :as geog]
[taoensso.timbre :as log]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Stages Overrides for URL Generation ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn stage2
[component coll-promise grans-promise {:keys [endpoint token params]}]
(log/debug "Starting stage 2 ...")
(let [granules (granule/extract-metadata grans-promise)
coll (collection/extract-metadata coll-promise)
data-files (map granule/extract-datafile-link granules)
service-ids (collection/extract-service-ids coll)
vars (common/apply-bounding-conditions endpoint token coll params)
errs (apply errors/collect (concat [granules coll vars] data-files))]
(when errs
(log/error "Stage 2 errors:" errs))
(log/trace "data-files:" (vec data-files))
(log/trace "service ids:" service-ids)
(log/debug "Finishing stage 2 ...")
[params data-files service-ids vars errs]))
(defn stage3
[component service-ids vars bounding-box {:keys [endpoint token params]}]
(log/debug "Starting stage 3 ...")
(let [[vars params bounding-box gridded-warns]
(common/apply-gridded-conditions vars params bounding-box)
services-promise (service/async-get-metadata endpoint token service-ids)
bounding-infos (if-not (seq gridded-warns)
(map #(geog/extract-bounding-info % bounding-box)
vars)
[])
errs (apply errors/collect bounding-infos)
warns (warnings/collect gridded-warns)]
(when errs
(log/error "Stage 3 errors:" errs))
(log/trace "variables bounding-info:" (vec bounding-infos))
(log/debug "Finishing stage 3 ...")
[services-promise vars params bounding-infos errs warns]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; API ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn get-opendap-urls
[component user-token raw-params]
(log/trace "Got params:" raw-params)
(let [start (util/now)
search-endpoint (config/get-search-url component)
;; Stage 1
[params bounding-box grans-promise coll-promise s1-errs]
(common/stage1 component
{:endpoint search-endpoint
:token user-token
:params raw-params})
;; Stage 2
[params data-files service-ids vars s2-errs]
(stage2 component
coll-promise
grans-promise
{:endpoint search-endpoint
:token user-token
:params params})
;; Stage 3
[services vars params bounding-info s3-errs s3-warns]
(stage3 component
service-ids
vars
bounding-box
{:endpoint search-endpoint
:token user-token
:params params})
;; Stage 4
[query s4-errs]
(common/stage4 component
services
bounding-box
bounding-info
{:endpoint search-endpoint
:token PI:PASSWORD:<PASSWORD>END_PI
:params params})
;; Warnings for all stages
warns (warnings/collect s3-warns)
;; Error handling for all stages
errs (errors/collect
start params bounding-box grans-promise coll-promise s1-errs
data-files service-ids vars s2-errs
services bounding-info s3-errs
query s4-errs
{:errors (errors/check
[not data-files metadata-errors/empty-gnl-data-files])})]
(common/process-results {:params params
:data-files data-files
:query query} start errs warns)))
|
[
{
"context": " testing with Clojure\"\n :url \"https://github.com/milankinen/cuic\"\n :scm {:name \"git\"\n :url \"https://",
"end": 115,
"score": 0.9995889663696289,
"start": 105,
"tag": "USERNAME",
"value": "milankinen"
},
{
"context": "cm {:name \"git\"\n :url \"https://github.com/milankinen/cuic\"}\n :license {:name \"MIT\"\n :url ",
"end": 186,
"score": 0.999025285243988,
"start": 176,
"tag": "USERNAME",
"value": "milankinen"
},
{
"context": "ensource.org/licenses/MIT\"}\n :signing {:gpg-key \"9DD8C3E9\"}\n :clean-targets\n ^{:protect false}\n [:target",
"end": 305,
"score": 0.992667555809021,
"start": 297,
"tag": "KEY",
"value": "9DD8C3E9"
}
] | project.clj | milankinen/repluit | 26 | (defproject cuic "1.0.0-RC2"
:description "Concise UI testing with Clojure"
:url "https://github.com/milankinen/cuic"
:scm {:name "git"
:url "https://github.com/milankinen/cuic"}
:license {:name "MIT"
:url "https://opensource.org/licenses/MIT"}
:signing {:gpg-key "9DD8C3E9"}
:clean-targets
^{:protect false}
[:target-path
"src/js/node_modules"
"src/js/build"]
:auto-clean false
:pedantic? :abort
:dependencies
[[org.clojure/tools.logging "1.2.3" :exclusions [org.clojure/clojure]]
[org.clojure/data.json "2.4.0" :exclusions [org.clojure/clojure]]
[stylefruits/gniazdo "1.2.0" :exclusions [org.clojure/clojure]]
[org.jsoup/jsoup "1.14.3"]]
:source-paths ["src/clj"]
:java-source-paths ["src/java"]
:resource-paths ["resources" "src/js/build"]
:profiles {:dev {:dependencies
[[org.clojure/clojure "1.10.2"]
[http-kit "2.5.3"]
[compojure "1.6.2"]
[ch.qos.logback/logback-classic "1.2.10"]
[eftest "0.5.9"]
[clj-kondo "2021.12.19"]]
:repl-options
{:init-ns repl}
:plugins
[[lein-ancient "0.7.0"]
[lein-shell "0.5.0"]]}
:repl {:jvm-opts ["-Dcuic.headless=false"
"-Dcuic.exceptions.full_stacktrace=true"]}}
:deploy-repositories [["releases" :clojars]
["snapshots" :clojars]]
:aliases {"test" ["trampoline" "run" "-m" "test-runner/run-tests-cli"]
"build-js" ["shell" "./src/js/build.sh"]
"t" ["test"]
"lint" ["trampoline" "run" "-m" "clj-kondo.main" "--lint" "src" "test"]}
:release-tasks [["deploy"]])
| 43317 | (defproject cuic "1.0.0-RC2"
:description "Concise UI testing with Clojure"
:url "https://github.com/milankinen/cuic"
:scm {:name "git"
:url "https://github.com/milankinen/cuic"}
:license {:name "MIT"
:url "https://opensource.org/licenses/MIT"}
:signing {:gpg-key "<KEY>"}
:clean-targets
^{:protect false}
[:target-path
"src/js/node_modules"
"src/js/build"]
:auto-clean false
:pedantic? :abort
:dependencies
[[org.clojure/tools.logging "1.2.3" :exclusions [org.clojure/clojure]]
[org.clojure/data.json "2.4.0" :exclusions [org.clojure/clojure]]
[stylefruits/gniazdo "1.2.0" :exclusions [org.clojure/clojure]]
[org.jsoup/jsoup "1.14.3"]]
:source-paths ["src/clj"]
:java-source-paths ["src/java"]
:resource-paths ["resources" "src/js/build"]
:profiles {:dev {:dependencies
[[org.clojure/clojure "1.10.2"]
[http-kit "2.5.3"]
[compojure "1.6.2"]
[ch.qos.logback/logback-classic "1.2.10"]
[eftest "0.5.9"]
[clj-kondo "2021.12.19"]]
:repl-options
{:init-ns repl}
:plugins
[[lein-ancient "0.7.0"]
[lein-shell "0.5.0"]]}
:repl {:jvm-opts ["-Dcuic.headless=false"
"-Dcuic.exceptions.full_stacktrace=true"]}}
:deploy-repositories [["releases" :clojars]
["snapshots" :clojars]]
:aliases {"test" ["trampoline" "run" "-m" "test-runner/run-tests-cli"]
"build-js" ["shell" "./src/js/build.sh"]
"t" ["test"]
"lint" ["trampoline" "run" "-m" "clj-kondo.main" "--lint" "src" "test"]}
:release-tasks [["deploy"]])
| true | (defproject cuic "1.0.0-RC2"
:description "Concise UI testing with Clojure"
:url "https://github.com/milankinen/cuic"
:scm {:name "git"
:url "https://github.com/milankinen/cuic"}
:license {:name "MIT"
:url "https://opensource.org/licenses/MIT"}
:signing {:gpg-key "PI:KEY:<KEY>END_PI"}
:clean-targets
^{:protect false}
[:target-path
"src/js/node_modules"
"src/js/build"]
:auto-clean false
:pedantic? :abort
:dependencies
[[org.clojure/tools.logging "1.2.3" :exclusions [org.clojure/clojure]]
[org.clojure/data.json "2.4.0" :exclusions [org.clojure/clojure]]
[stylefruits/gniazdo "1.2.0" :exclusions [org.clojure/clojure]]
[org.jsoup/jsoup "1.14.3"]]
:source-paths ["src/clj"]
:java-source-paths ["src/java"]
:resource-paths ["resources" "src/js/build"]
:profiles {:dev {:dependencies
[[org.clojure/clojure "1.10.2"]
[http-kit "2.5.3"]
[compojure "1.6.2"]
[ch.qos.logback/logback-classic "1.2.10"]
[eftest "0.5.9"]
[clj-kondo "2021.12.19"]]
:repl-options
{:init-ns repl}
:plugins
[[lein-ancient "0.7.0"]
[lein-shell "0.5.0"]]}
:repl {:jvm-opts ["-Dcuic.headless=false"
"-Dcuic.exceptions.full_stacktrace=true"]}}
:deploy-repositories [["releases" :clojars]
["snapshots" :clojars]]
:aliases {"test" ["trampoline" "run" "-m" "test-runner/run-tests-cli"]
"build-js" ["shell" "./src/js/build.sh"]
"t" ["test"]
"lint" ["trampoline" "run" "-m" "clj-kondo.main" "--lint" "src" "test"]}
:release-tasks [["deploy"]])
|
[
{
"context": " nat-int?)\n(s/def ::queue-size nat-int?)\n\n;; TODO(stevan): test needs to contain executor topology, so we ",
"end": 3417,
"score": 0.646177351474762,
"start": 3411,
"tag": "USERNAME",
"value": "stevan"
},
{
"context": "annot-execute-in-this-state))))\n ;; TODO(stevan): handle case when executor-id doesn't exist... P",
"end": 7597,
"score": 0.9986079335212708,
"start": 7591,
"tag": "USERNAME",
"value": "stevan"
},
{
"context": "lient-requests to-keep)\n to-drop]))\n\n\n;; TODO(stevan): move to other module, since isn't pure?\n;; ",
"end": 11958,
"score": 0.8375000357627869,
"start": 11956,
"tag": "USERNAME",
"value": "st"
},
{
"context": "ent-requests to-keep)\n to-drop]))\n\n\n;; TODO(stevan): move to other module, since isn't pure?\n;; TODO",
"end": 11962,
"score": 0.6759738922119141,
"start": 11958,
"tag": "NAME",
"value": "evan"
},
{
"context": ": move to other module, since isn't pure?\n;; TODO(stevan): can we avoid using nilable here? Return `Error ",
"end": 12019,
"score": 0.7629241943359375,
"start": 12013,
"tag": "NAME",
"value": "stevan"
},
{
"context": "data' {:events []}])\n (let ;; TODO(stevan): Retry on failure, this possibly needs changes t",
"end": 14102,
"score": 0.7419314980506897,
"start": 14096,
"tag": "NAME",
"value": "stevan"
},
{
"context": "ents expand-events))]\n ;; TODO(stevan): go into error state if response body is of form",
"end": 14642,
"score": 0.7644846439361572,
"start": 14638,
"tag": "NAME",
"value": "evan"
},
{
"context": "lient-responses)))]\n ;; TODO(stevan): use seed to shuffle client-responses?\n ",
"end": 15598,
"score": 0.784423828125,
"start": 15594,
"tag": "NAME",
"value": "evan"
}
] | src/scheduler/src/scheduler/pure.clj | symbiont-io/detsys-testkit | 5 | (ns scheduler.pure
(:refer-clojure :exclude [run!])
(:require [clojure.spec.alpha :as s]
[clojure.data.generators :as gen]
[clojure.java.io :as io]
[clj-http.client :as client]
[clj-http.fake :as fake]
[scheduler.spec :refer [>defn => component-id?]]
[scheduler.agenda :as agenda]
[scheduler.db :as db]
[scheduler.json :as json]
[scheduler.random :as random]
[scheduler.time :as time]
[taoensso.timbre :as log]
[clojure.string :as str]))
(set! *warn-on-reflection* true)
(s/def ::total-executors pos-int?)
(s/def ::connected-executors nat-int?)
(s/def ::topology (s/map-of string? string?))
(s/def ::seed integer?)
(s/def ::agenda agenda/agenda?)
(s/def ::clock time/instant?)
(s/def ::next-tick time/instant?)
(s/def ::tick-frequency double?)
(s/def ::min-time-ns double?)
(s/def ::max-time-ns double?)
(s/def ::client-requests (s/coll-of agenda/entry?))
(s/def ::client-timeout-ms double?)
(s/def ::client-delay-ms double?)
(s/def ::logical-clock nat-int?)
(s/def ::state #{:started
:test-prepared
:inits-prepared
:executors-prepared
:ready
:requesting
:responding
:finished
:error-cannot-load-test-in-this-state
:error-cannot-register-in-this-state
:error-cannot-create-run-in-this-state
:error-cannot-enqueue-in-this-state
:error-cannot-execute-in-this-state})
(s/def ::data (s/keys :req-un [::total-executors
::connected-executors
::topology
::seed
::agenda
::faults
::clock
::next-tick
::tick-frequency
::min-time-ns
::max-time-ns
::client-requests
::client-timeout-ms
::client-delay-ms
::logical-clock
::state]))
(s/def ::executor-id string?)
(s/def ::components (s/coll-of component-id? :kind vector?))
(s/def ::remaining-executors nat-int?)
(>defn init-data
[]
[=> ::data]
{:total-executors 1
:connected-executors 0
:topology {}
:agenda (agenda/empty-agenda)
:seed 1
:faults []
:clock (time/init-clock)
:next-tick (time/init-clock)
:tick-frequency 50.0
:min-time-ns 0.0
:max-time-ns 0.0
:client-requests []
:client-timeout-ms (* 30.0 1000)
:client-delay-ms (* 1.0 1000)
:logical-clock 0
:state :started})
(defn ap
[data f]
[data (f data)])
(s/def ::test-id nat-int?)
(s/def ::queue-size nat-int?)
;; TODO(stevan): test needs to contain executor topology, so we know how many
;; executors to wait for.
(>defn load-test!
[data {:keys [test-id]}]
[::data (s/keys :req-un [::test-id])
=> (s/tuple ::data (s/keys :req-un [::queue-size]))]
(-> data
(update :agenda #(agenda/enqueue-many % (db/load-test! test-id)))
(update :state (fn [state]
(case state
:started :test-prepared
:error-cannot-load-test-in-this-state)))
(ap (fn [data']
{:queue-size (count (:agenda data'))}))))
(defn update+
"Like `update`, but the function also has access to the original map."
[m k f]
(update m k #(f m %)))
(comment
(-> (init-data)
(load-test! {:test-id 1})
first
(register-executor! {:executor-id "http://localhost:3000" :components ["component0"]})
first
(create-run! {:test-id 1})))
(def not-empty? (complement empty?))
(defn component-crashed?
[data entry]
(->> data
:faults
(filter #(and (= (:kind %) "crash")
(= (:from %) (:to entry))
(<= (:at %) (:at entry))))
not-empty?))
(defn should-drop?
[data entry]
(let [faults (:faults data)
entry' (-> entry
(select-keys [:to :from])
(assoc :kind "omission"
:at (:logical-clock data)))]
(or (some? ((set faults) entry'))
(component-crashed? data entry')
)))
(comment
(should-drop? {:faults [{:from "a", :to "b", :kind "omission", :at 0}]
:logical-clock 0}
{:from "a", :to "b"})
;; => true
(should-drop? {:faults [{:from "a", :to "b", :kind "omission", :at 1}]
:logical-clock 0}
{:from "a", :to "b"})
;; => false
(should-drop? {:faults [{:from "b", :kind "crash", :at 1}]
:logical-clock 0}
{:from "a", :to "b"})
;; => false
(should-drop? {:faults [{:from "b", :kind "crash", :at 0}]
:logical-clock 1}
{:from "a", :to "b"})
;; => true
(should-drop? {:faults [{:from "b", :kind "crash", :at 1}]
:logical-clock 1}
{:from "a", :to "b"})
;; => true
(should-drop? {:faults [{:from "b", :kind "crash", :at 2}
{:from "b", :kind "crash", :at 1}]
:logical-clock 1}
{:from "a", :to "b"})
;; => true
)
(defn from-client?
[body]
(-> body :from (re-matches #"^client:\d+$")))
(s/def ::url string?)
(s/def ::timestamp time/instant?)
(s/def ::body agenda/entry?)
(s/def ::drop? #{:keep :drop :delay})
(>defn fetch-new-entry!
[data]
[::data => (s/tuple ::data (s/nilable
(s/keys :req-un [::url
::timestamp
::body
::drop?])))]
(if-not (contains? #{:ready :requesting} (:state data))
[(assoc data :state :error-cannot-execute-in-this-state) nil]
(let [[agenda' entry] (agenda/dequeue (:agenda data))
entry-from-client-with-current-request (some #(= (-> % :from)
(-> entry :from))
(:client-requests data))
data' (-> data
(assoc :agenda agenda'
:clock (:at entry))
(assoc :agenda (if entry-from-client-with-current-request
(agenda/enqueue agenda' (update entry :at #(time/plus-millis % (:client-delay-ms data))))
agenda'))
(update :logical-clock (if entry-from-client-with-current-request identity inc))
(update :state (fn [state]
(case state
:ready :responding
:requesting :responding
:error-cannot-execute-in-this-state))))
;; TODO(stevan): handle case when executor-id doesn't exist... Perhaps
;; this should be checked when commands are enqueued?
meta {:test-id (:test-id data')
:run-id (:run-id data')
:logical-time (:logical-clock data')}
executor-id (get (:topology data') (:to entry))]
(assert executor-id (str "Target `" (:to entry) "' isn't in topology."))
[data' {:url executor-id
:timestamp (:at entry)
:body (assoc entry :meta meta)
:drop? (cond
(should-drop? data' entry) :drop
entry-from-client-with-current-request :delay
:else :keep)}])))
(comment
(-> (init-data)
(update
:agenda
#(agenda/enqueue
%
{:kind "invoke", :event :a, :args {}, :at (time/instant 0), :from "f", :to "t"}))
:agenda
agenda/dequeue))
(comment
(-> (init-data)
(load-test! {:test-id 1})
first
(register-executor! {:executor-id "http://localhost:3000/api/v1/event"
:components ["node1" "node2"]})
first
(create-run! {:test-id 1})
first
(fetch-new-entry!)))
(s/def ::kind string?)
(s/def ::event string?)
(s/def ::args map?)
(s/def ::to string?)
(s/def ::from string?)
(def entry? (s/and (s/keys :req-un [::kind
::event
::args
::to
::from])
#(not (#{"timer"} (:kind %)))))
(def entries? (s/coll-of entry? :kind vector?))
(s/def :ext/to
(s/or :singleton string?
:set (s/coll-of string? :kind vector?)))
(def ext-entry?
(s/and (s/keys :req-un [::kind
::event
::args
:ext/to
::from])
#(not (#{"timer"} (:kind %)))))
(def timer?
(s/and (s/keys :req-un [::kind
::args
::from
::duration-ns])
#(= (:kind %) "timer")))
(def event?
(s/or :entry entry?
:timer timer?))
(def ext-event?
(s/or :entry ext-entry?
:timer timer?))
(def events? (s/coll-of event? :kind vector?))
(>defn expand-events
[events]
[(s/coll-of ext-event?) => (s/coll-of event? :kind vector?)]
(let [up (fn [event]
(case (:kind event)
"timer" [event]
(if (string? (:to event))
[event]
(mapv #(assoc event :to %) (:to event)))))]
(vec (mapcat up events))))
(s/def ::events events?)
(defn error-state?
[state]
(some? (re-matches #"^error-.*$" (name state))))
(defn partition-haskell
"Effectively though non-lazily splits the `coll`ection using `pred`,
essentially like `[(filter coll pred) (remove coll pred)]`"
[pred coll]
(let [match (transient [])
no-match (transient [])]
(doseq [v coll]
(if (pred v)
(conj! match v)
(conj! no-match v)))
[(persistent! match) (persistent! no-match)]))
(comment
(partition-haskell odd? (range 10))
(partition-haskell odd? []))
(>defn parse-client-id
[s]
[string? => nat-int?]
(->> s (re-matches #"^client:(\d+)$") second Integer/parseInt))
(comment
(parse-client-id "client:0"))
(>defn add-client-request
[data body]
[::data agenda/entry? => ::data]
(update data :client-requests (fn [m] (conj m body))))
(>defn remove-client-requests
[data clients]
[::data (s/coll-of string?) => ::data]
(let [clients-set (set clients)]
(update data :client-requests (fn [m]
(remove (fn [body]
(contains? clients-set (:from body))) m)))))
(>defn expired-clients
[data current-time]
[::data time/instant? => (s/tuple ::data (s/coll-of agenda/entry?))]
(let [expired? (fn [body] (time/before? (time/plus-millis (:at body)
(:client-timeout-ms data))
current-time))
[to-drop to-keep] (partition-haskell expired? (-> data :client-requests))]
[(assoc data :client-requests to-keep)
to-drop]))
;; TODO(stevan): move to other module, since isn't pure?
;; TODO(stevan): can we avoid using nilable here? Return `Error + Data *
;; Response` instead of always `Data * Response`? Or `Data * Error + Data * Response`?
(>defn execute!
[data]
[::data => (s/tuple ::data (s/nilable (s/keys :req-un [::events])))]
(let [[data' {:keys [url timestamp body drop?]}] (fetch-new-entry! data)]
(cond
(error-state? (:state data')) [data nil]
(= drop? :delay) (do
(log/debug :delaying-message body)
[data' {:events []}])
:else (let [is-from-client? (re-matches #"^client:\d+$" (:from body))
dropped? (= drop? :drop)
_ (log/debug :sent-logical-time body)
sent-logical-time (or (-> body :sent-logical-time)
(and is-from-client?
(:logical-clock data)))]
(let [obj (cond-> {:message (:event body)
:args (:args body)
:from (:from body)
:to (:to body)
:kind (:kind body)
:sent-logical-time sent-logical-time
:recv-logical-time (:logical-clock data')
:recv-simulated-time (:clock data')
:dropped dropped?}
is-from-client? (merge {:jepsen-type :invoke
:jepsen-process (-> body
:from
parse-client-id)}))]
(db/append-network-trace! (:test-id data)
(:run-id data)
obj))
(if dropped?
(do
(log/debug :dropped? dropped? :clock (:clock data'))
[data' {:events []}])
(let ;; TODO(stevan): Retry on failure, this possibly needs changes to executor
;; so that we don't end up executing the same command twice.
[events (-> (client/post (str url (if (= (:kind body) "timer") "timer" "event"))
{:body (json/write body) :content-type "application/json; charset=utf-8"})
:body
json/read
(update :events expand-events))]
;; TODO(stevan): go into error state if response body is of form {"error": ...}
;; (if (:error events) true false)
(log/debug :events events)
(assert (:run-id data) "execute!: no run-id set...")
(let [[client-responses internal]
(partition-haskell #(and (#{"ok"} (:kind %))
(some? (re-matches #"^client:\d+$" (:to %))))
(:events events))
internal (mapv #(assoc % :sent-logical-time (:logical-clock data')) internal)
data'' (cond-> data'
is-from-client? (add-client-request body)
(not (empty? client-responses)) (update :logical-clock inc)
true (remove-client-requests (map :to client-responses)))]
;; TODO(stevan): use seed to shuffle client-responses?
(doseq [client-response client-responses]
(db/append-network-trace! (:test-id data)
(:run-id data)
{:message (:event client-response)
:args (:response (:args client-response))
:from (:from client-response)
:to (:to client-response)
:kind "ok" ;; ??
:sent-logical-time (:logical-clock data')
:recv-logical-time (:logical-clock data'')
:recv-simulated-time (:clock data'')
:dropped false
:jepsen-type :ok
:jepsen-process (-> client-response :to parse-client-id)}))
[data'' {:events internal}])))))))
(comment
(fake/with-fake-routes
{"http://localhost:3001/api/v1/event"
(fn [_request] {:status 200
:headers {}
:body (json/write {:events
[{:kind "invoke"
:event "inc",
:args {}
:to "client:0"
:from "node1"}]})})}
(-> (init-data)
(load-test! {:test-id 1})
first
(register-executor! {:executor-id "http://localhost:3001/api/v1/event"
:components ["node1" "node2"]})
first
(create-run! {:test-id 1})
first
(execute!))))
(s/def ::timestamped-entries (s/coll-of agenda/entry?))
(>defn timestamp-entries
[data entries timestamp]
[::data events? time/instant?
=> (s/tuple ::data (s/keys :req-un [::timestamped-entries]))]
(with-bindings {#'gen/*rnd* (java.util.Random. (:seed data))}
(let [new-seed (.nextLong gen/*rnd*)
timestamps (->> (gen/vec #(random/exponential 20) (count entries))
(mapv #(time/plus-millis timestamp %)))
update-entry (fn [entry timestamp]
(case (:kind entry)
"timer" (-> entry
;; Maybe these should have another probability distribution for how slow they are
(assoc :at (time/plus-nanos timestamp (double (max (:duration-ns entry) 0)))
:to (:from entry)
:event :timer)
(dissoc :duration))
(assoc entry :at timestamp)))]
[(assoc data :seed new-seed)
{:timestamped-entries (mapv update-entry entries timestamps)}])))
(comment
(-> (init-data)
(timestamp-entries
[{:kind "invoke"
:event "do-inc"
:args {}
:to "inc"
:from "client"}
{:kind "invoke"
:event "do-inc"
:args {}
:to "inc"
:from "client"}]
(time/init-clock))
second) )
(>defn enqueue-entry
[data timestamped-entry]
[::data agenda/entry? => (s/tuple ::data (s/keys :req-un [::queue-size]))]
(-> data
(update :agenda #(agenda/enqueue % timestamped-entry))
(update :state (fn [state]
(case state
:executors-prepared :executors-prepared ;; Loading initial messages.
:responding :responding
:error-cannot-enqueue-in-this-state)))
(ap (fn [data'] {:queue-size (count (:agenda data'))}))))
(comment
(s/explain-str agenda/entry? {:kind "invoke", :event :a, :args {}, :at (time/instant 0)
:from "f", :to "t"})
(-> (init-data)
(load-test! {:test-id 1})
first
(register-executor! {:executor-id "http://localhost:3001" :components ["node1" "node2"]})
first
(create-run! {:test-id 1})
first
(fetch-new-entry!)
first
(enqueue-entry {:kind "invoke", :event :a, :args {}, :at (time/instant 0)
:from "f", :to "t"})))
(defn min-time?
[data]
(time/before? (time/plus-nanos (time/init-clock)
(:min-time-ns data))
(:clock data)))
(comment
(min-time? {:clock (time/init-clock), :min-time-ns 0.0})
;; => false
(min-time? {:clock (time/init-clock), :min-time-ns 1.0})
;; => false
(min-time? {:clock (time/plus-nanos (time/init-clock) 1.0), :min-time-ns 1.0})
;; => false
(min-time? {:clock (time/plus-nanos (time/init-clock) 2.0), :min-time-ns 1.0})
;; => true
)
(defn max-time?
[data]
(and (not= (:max-time-ns data) 0.0)
(time/before? (time/plus-nanos (time/init-clock)
(:max-time-ns data))
(:clock data))))
(comment
(max-time? {:clock (time/init-clock), :max-time-ns 0.0})
;; => false
(max-time? {:clock (time/init-clock), :max-time-ns 1.0})
;; => false
(max-time? {:clock (time/plus-nanos (time/init-clock) 1.0), :max-time-ns 1.0})
;; => false
(max-time? {:clock (time/plus-nanos (time/init-clock) 2.0), :max-time-ns 1.0})
;; => true
)
(>defn expire-clients!
[data expired-clients]
[::data (s/coll-of agenda/entry?) => nil?]
(doseq [client expired-clients]
(db/append-network-trace! (:test-id data)
(:run-id data)
{:message (:event client)
:args (:args client)
:from (:to client)
:to (:from client)
:kind (:kind client)
:sent-logical-time (:logical-clock data)
:recv-logical-time (:logical-clock data)
:recv-simulated-time (:clock data)
:dropped false
:jepsen-type :info
:jepsen-process (-> client :from parse-client-id)})))
(>defn enqueue-timestamped-entries
[data {:keys [timestamped-entries]}]
[::data (s/keys :req-un [::timestamped-entries])
=> (s/tuple ::data (s/keys :req-un [::queue-size]))]
(if (or (and (empty? timestamped-entries) (-> data :agenda empty?) (min-time? data))
(max-time? data))
(do
(expire-clients! data (-> data :client-requests))
[(update data :state
(fn [state]
(case state
:responding :finished
:executors-prepared :inits-prepared
:error-cannot-enqueue-in-this-state)))
{:queue-size (-> data :agenda count)}])
(let [data' (-> (reduce (fn [ih timestamped-entry]
(first (enqueue-entry ih timestamped-entry)))
data
timestamped-entries)
(update :state
(fn [state] (case state
:responding :requesting
:executors-prepared :inits-prepared
:error-cannot-enqueue-in-this-state))))]
[data' {:queue-size (count (:agenda data'))}])))
(comment
(enqueue-timestamped-entries
(-> (init-data)
(load-test! {:test-id 1})
first
(register-executor! {:executor-id "http://localhost:3001" :components ["inc" "store"]})
first)
(-> (init-data)
(timestamp-entries
[{:kind "invoke"
:event "do-inc"
:args {}
:to "inc"
:from "client"}
{:kind "invoke"
:event "do-inc"
:args {}
:to "inc"
:from "client"}]
(time/instant (time/init-clock))
0)
second)))
(>defn get-initial-events!
"Get all the initial events for each component that run on an executor."
[data {:keys [executor-id]}]
[::data (s/keys :req-un [::executor-id])
=> (s/tuple ::data (s/keys :req-un [::queue-size]))]
(let [events (mapv #(assoc % :sent-logical-time (:logical-clock data))
(-> (client/get (str executor-id "/inits"))
:body
json/read
:events
expand-events))
_ (log/debug :get-initial-events executor-id events (:state data))
[data' timestamped-entries] (timestamp-entries data events (:clock data))
[data'' queue-size] (enqueue-timestamped-entries data' timestamped-entries)]
(log/debug :get-initial-events executor-id (count events))
[data'' queue-size]))
(>defn register-executor!
[data {:keys [executor-id components]}]
[::data (s/keys :req-un [::executor-id ::components])
=> (s/tuple ::data (s/keys :req-un [::remaining-executors]))]
(-> data
(update :connected-executors inc)
(update :topology #(merge % (apply hash-map
(interleave components
(replicate (count components)
executor-id)))))
(update+ :state
(fn [data' state]
(let [state' (case (compare (:connected-executors data')
(:total-executors data'))
-1 :waiting-for-executors
0 :executors-prepared
1 :error-too-many-executors)]
(case state
:test-prepared state'
:waiting-for-executors state'
:error-cannot-register-in-this-state))))
(get-initial-events! {:executor-id executor-id})
first
(ap (fn [data']
{:remaining-executors (max 0 (- (:total-executors data')
(:connected-executors data')))}))))
(comment
(let [executor-id "http://localhost:3001"
components ["components0"]]
(apply hash-map
(interleave components
(replicate (count components)
executor-id)))))
(>defn tick!
[data]
[::data => (s/tuple ::data (s/nilable (s/keys :req-un [::events])))]
(assert (or (not (empty? (:agenda data)))
(not (min-time? data))))
(let [all-events (transient [])]
(doseq [[reactor url] (:topology data)]
(let [url (str url "tick")
events (-> (client/put url
{:body (json/write {:at (:next-tick data)
:reactor reactor})
:content-type "application/json; charset=utf-8"})
:body
json/read
(update :events expand-events))]
(doseq [event (:events events)]
(conj! all-events event))))
(let [events (->> all-events
persistent!
(mapv #(assoc % :sent-logical-time (-> data :logical-clock inc))))]
[(-> data
(update :next-tick (fn [c] (time/plus-millis c (:tick-frequency data))))
(update :logical-clock (if (empty? events) identity inc))
(assoc :state :responding) ;; probably??
(assoc :clock (:next-tick data)))
{:events events}])))
(>defn execute-or-tick!
[data]
[::data => (s/tuple ::data (s/nilable (s/keys :req-un [::events])))]
(if-let [entry (-> data :agenda peek)]
(if (time/before? (:next-tick data) (:at entry))
(tick! data)
(let [[data' expired-clients] (expired-clients data (:at entry))]
(expire-clients! data' expired-clients)
(execute! data')))
(if (time/before? (:next-tick data) (time/plus-nanos (time/init-clock)
(:min-time-ns data)))
(tick! data)
[(assoc data
:clock (:next-tick data)
:state :responding) ;; I think?
{:events []}])))
(>defn step!
[data]
[::data => (s/tuple ::data (s/keys :req-un [::events ::queue-size]))]
(let [[data' events] (execute-or-tick! data)
[data'' timestamped-entries] (timestamp-entries data'
(:events events)
(-> data' :clock))
[data''' queue-size] (enqueue-timestamped-entries data'' timestamped-entries)]
[data''' (merge events queue-size)]))
(comment
(fake/with-fake-routes
{"http://localhost:3001/api/v1/event"
(fn [_request] {:status 200
:headers {}
:body (json/write {:events [{:kind "invoke"
:event :a
:args {}
:to "node1"
:from "from"}]})})}
(-> (init-data)
(load-test! {:test-id 1})
first
(register-executor! {:executor-id "http://localhost:3001/api/v1/event"
:components ["node1"]})
first
(create-run! {:test-id 1})
first
step!
first
step!)))
(defn run!
[data]
(client/with-connection-pool {:timeout 30 :threads 4 :insecure? true}
(loop [data data steps 0]
(if (= :finished (:state data))
[data {:steps steps}]
(recur (-> data step! first) (inc steps))))))
(comment
(fake/with-fake-routes
{"http://localhost:3001/api/v1/event"
(fn [_request] {:status 200
:headers {}
:body (json/write {:events []})})}
(-> (init-data)
(load-test! {:test-id 1})
first
(register-executor! {:executor-id "http://localhost:3001/api/v1/event"
:components ["node1"]})
first
(create-run! {:test-id 1})
first
run!)))
(>defn status
[data]
[::data => (s/tuple ::data ::data)]
[data data])
(comment
(status (init-data)))
(defn reset
[_data]
[(init-data) :reset])
(s/def ::at nat-int?)
(def fault? (s/keys :req-un [:scheduler.agenda/kind
:scheduler.agenda/to
:scheduler.agenda/from
::at]))
(s/def ::faults (s/coll-of fault?))
(s/def ::create-run-event
(s/keys :req-un
[::test-id
::seed
::faults
;; The following fields can in the event also be integer rather than just double
;; in the data field they will always be double though.
;; ::tick-frequency
;; ::min-time-ns
;; ::max-time-ns
]))
(>defn create-run!
[data event]
[::data ::create-run-event => (s/tuple ::data (s/keys :req-un [::run-id]))]
(case (:state data)
:inits-prepared
(let [test-id (:test-id event)
run-id (db/next-run-id! test-id)
seed (:seed event)
tick-frequency (double (:tick-frequency event))
min-time (double (:min-time-ns event))
max-time (double (:max-time-ns event))
faults (:faults event)
data (-> data
(assoc :state :ready
:test-id test-id
:run-id (:run-id run-id)
:seed seed
:tick-frequency tick-frequency
:min-time-ns min-time
:max-time-ns max-time
:faults faults))]
(db/append-create-run-event! (:test-id data) (:run-id data) event)
[data run-id])
[(assoc data :state :error-cannot-create-run-in-this-state) nil]))
;; When building with Bazel we generate a resource file containing the git
;; commit hash, otherwise we expect the git commit hash to be passed in via an
;; environment variable.
(def gitrev ^String
(if-let [file (io/resource "version.txt")]
(str/trimr (slurp file))
(or (System/getenv "DETSYS_SCHEDULER_VERSION")
"unknown")))
(s/def ::gitrev string?)
(>defn version
[data]
[::data => (s/tuple ::data (s/keys :req-un [::gitrev]))]
[data {:gitrev gitrev}])
| 103005 | (ns scheduler.pure
(:refer-clojure :exclude [run!])
(:require [clojure.spec.alpha :as s]
[clojure.data.generators :as gen]
[clojure.java.io :as io]
[clj-http.client :as client]
[clj-http.fake :as fake]
[scheduler.spec :refer [>defn => component-id?]]
[scheduler.agenda :as agenda]
[scheduler.db :as db]
[scheduler.json :as json]
[scheduler.random :as random]
[scheduler.time :as time]
[taoensso.timbre :as log]
[clojure.string :as str]))
(set! *warn-on-reflection* true)
(s/def ::total-executors pos-int?)
(s/def ::connected-executors nat-int?)
(s/def ::topology (s/map-of string? string?))
(s/def ::seed integer?)
(s/def ::agenda agenda/agenda?)
(s/def ::clock time/instant?)
(s/def ::next-tick time/instant?)
(s/def ::tick-frequency double?)
(s/def ::min-time-ns double?)
(s/def ::max-time-ns double?)
(s/def ::client-requests (s/coll-of agenda/entry?))
(s/def ::client-timeout-ms double?)
(s/def ::client-delay-ms double?)
(s/def ::logical-clock nat-int?)
(s/def ::state #{:started
:test-prepared
:inits-prepared
:executors-prepared
:ready
:requesting
:responding
:finished
:error-cannot-load-test-in-this-state
:error-cannot-register-in-this-state
:error-cannot-create-run-in-this-state
:error-cannot-enqueue-in-this-state
:error-cannot-execute-in-this-state})
(s/def ::data (s/keys :req-un [::total-executors
::connected-executors
::topology
::seed
::agenda
::faults
::clock
::next-tick
::tick-frequency
::min-time-ns
::max-time-ns
::client-requests
::client-timeout-ms
::client-delay-ms
::logical-clock
::state]))
(s/def ::executor-id string?)
(s/def ::components (s/coll-of component-id? :kind vector?))
(s/def ::remaining-executors nat-int?)
(>defn init-data
[]
[=> ::data]
{:total-executors 1
:connected-executors 0
:topology {}
:agenda (agenda/empty-agenda)
:seed 1
:faults []
:clock (time/init-clock)
:next-tick (time/init-clock)
:tick-frequency 50.0
:min-time-ns 0.0
:max-time-ns 0.0
:client-requests []
:client-timeout-ms (* 30.0 1000)
:client-delay-ms (* 1.0 1000)
:logical-clock 0
:state :started})
(defn ap
[data f]
[data (f data)])
(s/def ::test-id nat-int?)
(s/def ::queue-size nat-int?)
;; TODO(stevan): test needs to contain executor topology, so we know how many
;; executors to wait for.
(>defn load-test!
[data {:keys [test-id]}]
[::data (s/keys :req-un [::test-id])
=> (s/tuple ::data (s/keys :req-un [::queue-size]))]
(-> data
(update :agenda #(agenda/enqueue-many % (db/load-test! test-id)))
(update :state (fn [state]
(case state
:started :test-prepared
:error-cannot-load-test-in-this-state)))
(ap (fn [data']
{:queue-size (count (:agenda data'))}))))
(defn update+
"Like `update`, but the function also has access to the original map."
[m k f]
(update m k #(f m %)))
(comment
(-> (init-data)
(load-test! {:test-id 1})
first
(register-executor! {:executor-id "http://localhost:3000" :components ["component0"]})
first
(create-run! {:test-id 1})))
(def not-empty? (complement empty?))
(defn component-crashed?
[data entry]
(->> data
:faults
(filter #(and (= (:kind %) "crash")
(= (:from %) (:to entry))
(<= (:at %) (:at entry))))
not-empty?))
(defn should-drop?
[data entry]
(let [faults (:faults data)
entry' (-> entry
(select-keys [:to :from])
(assoc :kind "omission"
:at (:logical-clock data)))]
(or (some? ((set faults) entry'))
(component-crashed? data entry')
)))
(comment
(should-drop? {:faults [{:from "a", :to "b", :kind "omission", :at 0}]
:logical-clock 0}
{:from "a", :to "b"})
;; => true
(should-drop? {:faults [{:from "a", :to "b", :kind "omission", :at 1}]
:logical-clock 0}
{:from "a", :to "b"})
;; => false
(should-drop? {:faults [{:from "b", :kind "crash", :at 1}]
:logical-clock 0}
{:from "a", :to "b"})
;; => false
(should-drop? {:faults [{:from "b", :kind "crash", :at 0}]
:logical-clock 1}
{:from "a", :to "b"})
;; => true
(should-drop? {:faults [{:from "b", :kind "crash", :at 1}]
:logical-clock 1}
{:from "a", :to "b"})
;; => true
(should-drop? {:faults [{:from "b", :kind "crash", :at 2}
{:from "b", :kind "crash", :at 1}]
:logical-clock 1}
{:from "a", :to "b"})
;; => true
)
(defn from-client?
[body]
(-> body :from (re-matches #"^client:\d+$")))
(s/def ::url string?)
(s/def ::timestamp time/instant?)
(s/def ::body agenda/entry?)
(s/def ::drop? #{:keep :drop :delay})
(>defn fetch-new-entry!
[data]
[::data => (s/tuple ::data (s/nilable
(s/keys :req-un [::url
::timestamp
::body
::drop?])))]
(if-not (contains? #{:ready :requesting} (:state data))
[(assoc data :state :error-cannot-execute-in-this-state) nil]
(let [[agenda' entry] (agenda/dequeue (:agenda data))
entry-from-client-with-current-request (some #(= (-> % :from)
(-> entry :from))
(:client-requests data))
data' (-> data
(assoc :agenda agenda'
:clock (:at entry))
(assoc :agenda (if entry-from-client-with-current-request
(agenda/enqueue agenda' (update entry :at #(time/plus-millis % (:client-delay-ms data))))
agenda'))
(update :logical-clock (if entry-from-client-with-current-request identity inc))
(update :state (fn [state]
(case state
:ready :responding
:requesting :responding
:error-cannot-execute-in-this-state))))
;; TODO(stevan): handle case when executor-id doesn't exist... Perhaps
;; this should be checked when commands are enqueued?
meta {:test-id (:test-id data')
:run-id (:run-id data')
:logical-time (:logical-clock data')}
executor-id (get (:topology data') (:to entry))]
(assert executor-id (str "Target `" (:to entry) "' isn't in topology."))
[data' {:url executor-id
:timestamp (:at entry)
:body (assoc entry :meta meta)
:drop? (cond
(should-drop? data' entry) :drop
entry-from-client-with-current-request :delay
:else :keep)}])))
(comment
(-> (init-data)
(update
:agenda
#(agenda/enqueue
%
{:kind "invoke", :event :a, :args {}, :at (time/instant 0), :from "f", :to "t"}))
:agenda
agenda/dequeue))
(comment
(-> (init-data)
(load-test! {:test-id 1})
first
(register-executor! {:executor-id "http://localhost:3000/api/v1/event"
:components ["node1" "node2"]})
first
(create-run! {:test-id 1})
first
(fetch-new-entry!)))
(s/def ::kind string?)
(s/def ::event string?)
(s/def ::args map?)
(s/def ::to string?)
(s/def ::from string?)
(def entry? (s/and (s/keys :req-un [::kind
::event
::args
::to
::from])
#(not (#{"timer"} (:kind %)))))
(def entries? (s/coll-of entry? :kind vector?))
(s/def :ext/to
(s/or :singleton string?
:set (s/coll-of string? :kind vector?)))
(def ext-entry?
(s/and (s/keys :req-un [::kind
::event
::args
:ext/to
::from])
#(not (#{"timer"} (:kind %)))))
(def timer?
(s/and (s/keys :req-un [::kind
::args
::from
::duration-ns])
#(= (:kind %) "timer")))
(def event?
(s/or :entry entry?
:timer timer?))
(def ext-event?
(s/or :entry ext-entry?
:timer timer?))
(def events? (s/coll-of event? :kind vector?))
(>defn expand-events
[events]
[(s/coll-of ext-event?) => (s/coll-of event? :kind vector?)]
(let [up (fn [event]
(case (:kind event)
"timer" [event]
(if (string? (:to event))
[event]
(mapv #(assoc event :to %) (:to event)))))]
(vec (mapcat up events))))
(s/def ::events events?)
(defn error-state?
[state]
(some? (re-matches #"^error-.*$" (name state))))
(defn partition-haskell
"Effectively though non-lazily splits the `coll`ection using `pred`,
essentially like `[(filter coll pred) (remove coll pred)]`"
[pred coll]
(let [match (transient [])
no-match (transient [])]
(doseq [v coll]
(if (pred v)
(conj! match v)
(conj! no-match v)))
[(persistent! match) (persistent! no-match)]))
(comment
(partition-haskell odd? (range 10))
(partition-haskell odd? []))
(>defn parse-client-id
[s]
[string? => nat-int?]
(->> s (re-matches #"^client:(\d+)$") second Integer/parseInt))
(comment
(parse-client-id "client:0"))
(>defn add-client-request
[data body]
[::data agenda/entry? => ::data]
(update data :client-requests (fn [m] (conj m body))))
(>defn remove-client-requests
[data clients]
[::data (s/coll-of string?) => ::data]
(let [clients-set (set clients)]
(update data :client-requests (fn [m]
(remove (fn [body]
(contains? clients-set (:from body))) m)))))
(>defn expired-clients
[data current-time]
[::data time/instant? => (s/tuple ::data (s/coll-of agenda/entry?))]
(let [expired? (fn [body] (time/before? (time/plus-millis (:at body)
(:client-timeout-ms data))
current-time))
[to-drop to-keep] (partition-haskell expired? (-> data :client-requests))]
[(assoc data :client-requests to-keep)
to-drop]))
;; TODO(st<NAME>): move to other module, since isn't pure?
;; TODO(<NAME>): can we avoid using nilable here? Return `Error + Data *
;; Response` instead of always `Data * Response`? Or `Data * Error + Data * Response`?
(>defn execute!
[data]
[::data => (s/tuple ::data (s/nilable (s/keys :req-un [::events])))]
(let [[data' {:keys [url timestamp body drop?]}] (fetch-new-entry! data)]
(cond
(error-state? (:state data')) [data nil]
(= drop? :delay) (do
(log/debug :delaying-message body)
[data' {:events []}])
:else (let [is-from-client? (re-matches #"^client:\d+$" (:from body))
dropped? (= drop? :drop)
_ (log/debug :sent-logical-time body)
sent-logical-time (or (-> body :sent-logical-time)
(and is-from-client?
(:logical-clock data)))]
(let [obj (cond-> {:message (:event body)
:args (:args body)
:from (:from body)
:to (:to body)
:kind (:kind body)
:sent-logical-time sent-logical-time
:recv-logical-time (:logical-clock data')
:recv-simulated-time (:clock data')
:dropped dropped?}
is-from-client? (merge {:jepsen-type :invoke
:jepsen-process (-> body
:from
parse-client-id)}))]
(db/append-network-trace! (:test-id data)
(:run-id data)
obj))
(if dropped?
(do
(log/debug :dropped? dropped? :clock (:clock data'))
[data' {:events []}])
(let ;; TODO(<NAME>): Retry on failure, this possibly needs changes to executor
;; so that we don't end up executing the same command twice.
[events (-> (client/post (str url (if (= (:kind body) "timer") "timer" "event"))
{:body (json/write body) :content-type "application/json; charset=utf-8"})
:body
json/read
(update :events expand-events))]
;; TODO(st<NAME>): go into error state if response body is of form {"error": ...}
;; (if (:error events) true false)
(log/debug :events events)
(assert (:run-id data) "execute!: no run-id set...")
(let [[client-responses internal]
(partition-haskell #(and (#{"ok"} (:kind %))
(some? (re-matches #"^client:\d+$" (:to %))))
(:events events))
internal (mapv #(assoc % :sent-logical-time (:logical-clock data')) internal)
data'' (cond-> data'
is-from-client? (add-client-request body)
(not (empty? client-responses)) (update :logical-clock inc)
true (remove-client-requests (map :to client-responses)))]
;; TODO(st<NAME>): use seed to shuffle client-responses?
(doseq [client-response client-responses]
(db/append-network-trace! (:test-id data)
(:run-id data)
{:message (:event client-response)
:args (:response (:args client-response))
:from (:from client-response)
:to (:to client-response)
:kind "ok" ;; ??
:sent-logical-time (:logical-clock data')
:recv-logical-time (:logical-clock data'')
:recv-simulated-time (:clock data'')
:dropped false
:jepsen-type :ok
:jepsen-process (-> client-response :to parse-client-id)}))
[data'' {:events internal}])))))))
(comment
(fake/with-fake-routes
{"http://localhost:3001/api/v1/event"
(fn [_request] {:status 200
:headers {}
:body (json/write {:events
[{:kind "invoke"
:event "inc",
:args {}
:to "client:0"
:from "node1"}]})})}
(-> (init-data)
(load-test! {:test-id 1})
first
(register-executor! {:executor-id "http://localhost:3001/api/v1/event"
:components ["node1" "node2"]})
first
(create-run! {:test-id 1})
first
(execute!))))
(s/def ::timestamped-entries (s/coll-of agenda/entry?))
(>defn timestamp-entries
[data entries timestamp]
[::data events? time/instant?
=> (s/tuple ::data (s/keys :req-un [::timestamped-entries]))]
(with-bindings {#'gen/*rnd* (java.util.Random. (:seed data))}
(let [new-seed (.nextLong gen/*rnd*)
timestamps (->> (gen/vec #(random/exponential 20) (count entries))
(mapv #(time/plus-millis timestamp %)))
update-entry (fn [entry timestamp]
(case (:kind entry)
"timer" (-> entry
;; Maybe these should have another probability distribution for how slow they are
(assoc :at (time/plus-nanos timestamp (double (max (:duration-ns entry) 0)))
:to (:from entry)
:event :timer)
(dissoc :duration))
(assoc entry :at timestamp)))]
[(assoc data :seed new-seed)
{:timestamped-entries (mapv update-entry entries timestamps)}])))
(comment
(-> (init-data)
(timestamp-entries
[{:kind "invoke"
:event "do-inc"
:args {}
:to "inc"
:from "client"}
{:kind "invoke"
:event "do-inc"
:args {}
:to "inc"
:from "client"}]
(time/init-clock))
second) )
(>defn enqueue-entry
[data timestamped-entry]
[::data agenda/entry? => (s/tuple ::data (s/keys :req-un [::queue-size]))]
(-> data
(update :agenda #(agenda/enqueue % timestamped-entry))
(update :state (fn [state]
(case state
:executors-prepared :executors-prepared ;; Loading initial messages.
:responding :responding
:error-cannot-enqueue-in-this-state)))
(ap (fn [data'] {:queue-size (count (:agenda data'))}))))
(comment
(s/explain-str agenda/entry? {:kind "invoke", :event :a, :args {}, :at (time/instant 0)
:from "f", :to "t"})
(-> (init-data)
(load-test! {:test-id 1})
first
(register-executor! {:executor-id "http://localhost:3001" :components ["node1" "node2"]})
first
(create-run! {:test-id 1})
first
(fetch-new-entry!)
first
(enqueue-entry {:kind "invoke", :event :a, :args {}, :at (time/instant 0)
:from "f", :to "t"})))
(defn min-time?
[data]
(time/before? (time/plus-nanos (time/init-clock)
(:min-time-ns data))
(:clock data)))
(comment
(min-time? {:clock (time/init-clock), :min-time-ns 0.0})
;; => false
(min-time? {:clock (time/init-clock), :min-time-ns 1.0})
;; => false
(min-time? {:clock (time/plus-nanos (time/init-clock) 1.0), :min-time-ns 1.0})
;; => false
(min-time? {:clock (time/plus-nanos (time/init-clock) 2.0), :min-time-ns 1.0})
;; => true
)
(defn max-time?
[data]
(and (not= (:max-time-ns data) 0.0)
(time/before? (time/plus-nanos (time/init-clock)
(:max-time-ns data))
(:clock data))))
(comment
(max-time? {:clock (time/init-clock), :max-time-ns 0.0})
;; => false
(max-time? {:clock (time/init-clock), :max-time-ns 1.0})
;; => false
(max-time? {:clock (time/plus-nanos (time/init-clock) 1.0), :max-time-ns 1.0})
;; => false
(max-time? {:clock (time/plus-nanos (time/init-clock) 2.0), :max-time-ns 1.0})
;; => true
)
(>defn expire-clients!
[data expired-clients]
[::data (s/coll-of agenda/entry?) => nil?]
(doseq [client expired-clients]
(db/append-network-trace! (:test-id data)
(:run-id data)
{:message (:event client)
:args (:args client)
:from (:to client)
:to (:from client)
:kind (:kind client)
:sent-logical-time (:logical-clock data)
:recv-logical-time (:logical-clock data)
:recv-simulated-time (:clock data)
:dropped false
:jepsen-type :info
:jepsen-process (-> client :from parse-client-id)})))
(>defn enqueue-timestamped-entries
[data {:keys [timestamped-entries]}]
[::data (s/keys :req-un [::timestamped-entries])
=> (s/tuple ::data (s/keys :req-un [::queue-size]))]
(if (or (and (empty? timestamped-entries) (-> data :agenda empty?) (min-time? data))
(max-time? data))
(do
(expire-clients! data (-> data :client-requests))
[(update data :state
(fn [state]
(case state
:responding :finished
:executors-prepared :inits-prepared
:error-cannot-enqueue-in-this-state)))
{:queue-size (-> data :agenda count)}])
(let [data' (-> (reduce (fn [ih timestamped-entry]
(first (enqueue-entry ih timestamped-entry)))
data
timestamped-entries)
(update :state
(fn [state] (case state
:responding :requesting
:executors-prepared :inits-prepared
:error-cannot-enqueue-in-this-state))))]
[data' {:queue-size (count (:agenda data'))}])))
(comment
(enqueue-timestamped-entries
(-> (init-data)
(load-test! {:test-id 1})
first
(register-executor! {:executor-id "http://localhost:3001" :components ["inc" "store"]})
first)
(-> (init-data)
(timestamp-entries
[{:kind "invoke"
:event "do-inc"
:args {}
:to "inc"
:from "client"}
{:kind "invoke"
:event "do-inc"
:args {}
:to "inc"
:from "client"}]
(time/instant (time/init-clock))
0)
second)))
(>defn get-initial-events!
"Get all the initial events for each component that run on an executor."
[data {:keys [executor-id]}]
[::data (s/keys :req-un [::executor-id])
=> (s/tuple ::data (s/keys :req-un [::queue-size]))]
(let [events (mapv #(assoc % :sent-logical-time (:logical-clock data))
(-> (client/get (str executor-id "/inits"))
:body
json/read
:events
expand-events))
_ (log/debug :get-initial-events executor-id events (:state data))
[data' timestamped-entries] (timestamp-entries data events (:clock data))
[data'' queue-size] (enqueue-timestamped-entries data' timestamped-entries)]
(log/debug :get-initial-events executor-id (count events))
[data'' queue-size]))
(>defn register-executor!
[data {:keys [executor-id components]}]
[::data (s/keys :req-un [::executor-id ::components])
=> (s/tuple ::data (s/keys :req-un [::remaining-executors]))]
(-> data
(update :connected-executors inc)
(update :topology #(merge % (apply hash-map
(interleave components
(replicate (count components)
executor-id)))))
(update+ :state
(fn [data' state]
(let [state' (case (compare (:connected-executors data')
(:total-executors data'))
-1 :waiting-for-executors
0 :executors-prepared
1 :error-too-many-executors)]
(case state
:test-prepared state'
:waiting-for-executors state'
:error-cannot-register-in-this-state))))
(get-initial-events! {:executor-id executor-id})
first
(ap (fn [data']
{:remaining-executors (max 0 (- (:total-executors data')
(:connected-executors data')))}))))
(comment
(let [executor-id "http://localhost:3001"
components ["components0"]]
(apply hash-map
(interleave components
(replicate (count components)
executor-id)))))
(>defn tick!
[data]
[::data => (s/tuple ::data (s/nilable (s/keys :req-un [::events])))]
(assert (or (not (empty? (:agenda data)))
(not (min-time? data))))
(let [all-events (transient [])]
(doseq [[reactor url] (:topology data)]
(let [url (str url "tick")
events (-> (client/put url
{:body (json/write {:at (:next-tick data)
:reactor reactor})
:content-type "application/json; charset=utf-8"})
:body
json/read
(update :events expand-events))]
(doseq [event (:events events)]
(conj! all-events event))))
(let [events (->> all-events
persistent!
(mapv #(assoc % :sent-logical-time (-> data :logical-clock inc))))]
[(-> data
(update :next-tick (fn [c] (time/plus-millis c (:tick-frequency data))))
(update :logical-clock (if (empty? events) identity inc))
(assoc :state :responding) ;; probably??
(assoc :clock (:next-tick data)))
{:events events}])))
(>defn execute-or-tick!
[data]
[::data => (s/tuple ::data (s/nilable (s/keys :req-un [::events])))]
(if-let [entry (-> data :agenda peek)]
(if (time/before? (:next-tick data) (:at entry))
(tick! data)
(let [[data' expired-clients] (expired-clients data (:at entry))]
(expire-clients! data' expired-clients)
(execute! data')))
(if (time/before? (:next-tick data) (time/plus-nanos (time/init-clock)
(:min-time-ns data)))
(tick! data)
[(assoc data
:clock (:next-tick data)
:state :responding) ;; I think?
{:events []}])))
(>defn step!
[data]
[::data => (s/tuple ::data (s/keys :req-un [::events ::queue-size]))]
(let [[data' events] (execute-or-tick! data)
[data'' timestamped-entries] (timestamp-entries data'
(:events events)
(-> data' :clock))
[data''' queue-size] (enqueue-timestamped-entries data'' timestamped-entries)]
[data''' (merge events queue-size)]))
(comment
(fake/with-fake-routes
{"http://localhost:3001/api/v1/event"
(fn [_request] {:status 200
:headers {}
:body (json/write {:events [{:kind "invoke"
:event :a
:args {}
:to "node1"
:from "from"}]})})}
(-> (init-data)
(load-test! {:test-id 1})
first
(register-executor! {:executor-id "http://localhost:3001/api/v1/event"
:components ["node1"]})
first
(create-run! {:test-id 1})
first
step!
first
step!)))
(defn run!
[data]
(client/with-connection-pool {:timeout 30 :threads 4 :insecure? true}
(loop [data data steps 0]
(if (= :finished (:state data))
[data {:steps steps}]
(recur (-> data step! first) (inc steps))))))
(comment
(fake/with-fake-routes
{"http://localhost:3001/api/v1/event"
(fn [_request] {:status 200
:headers {}
:body (json/write {:events []})})}
(-> (init-data)
(load-test! {:test-id 1})
first
(register-executor! {:executor-id "http://localhost:3001/api/v1/event"
:components ["node1"]})
first
(create-run! {:test-id 1})
first
run!)))
(>defn status
[data]
[::data => (s/tuple ::data ::data)]
[data data])
(comment
(status (init-data)))
(defn reset
[_data]
[(init-data) :reset])
(s/def ::at nat-int?)
(def fault? (s/keys :req-un [:scheduler.agenda/kind
:scheduler.agenda/to
:scheduler.agenda/from
::at]))
(s/def ::faults (s/coll-of fault?))
(s/def ::create-run-event
(s/keys :req-un
[::test-id
::seed
::faults
;; The following fields can in the event also be integer rather than just double
;; in the data field they will always be double though.
;; ::tick-frequency
;; ::min-time-ns
;; ::max-time-ns
]))
(>defn create-run!
[data event]
[::data ::create-run-event => (s/tuple ::data (s/keys :req-un [::run-id]))]
(case (:state data)
:inits-prepared
(let [test-id (:test-id event)
run-id (db/next-run-id! test-id)
seed (:seed event)
tick-frequency (double (:tick-frequency event))
min-time (double (:min-time-ns event))
max-time (double (:max-time-ns event))
faults (:faults event)
data (-> data
(assoc :state :ready
:test-id test-id
:run-id (:run-id run-id)
:seed seed
:tick-frequency tick-frequency
:min-time-ns min-time
:max-time-ns max-time
:faults faults))]
(db/append-create-run-event! (:test-id data) (:run-id data) event)
[data run-id])
[(assoc data :state :error-cannot-create-run-in-this-state) nil]))
;; When building with Bazel we generate a resource file containing the git
;; commit hash, otherwise we expect the git commit hash to be passed in via an
;; environment variable.
(def gitrev ^String
(if-let [file (io/resource "version.txt")]
(str/trimr (slurp file))
(or (System/getenv "DETSYS_SCHEDULER_VERSION")
"unknown")))
(s/def ::gitrev string?)
(>defn version
[data]
[::data => (s/tuple ::data (s/keys :req-un [::gitrev]))]
[data {:gitrev gitrev}])
| true | (ns scheduler.pure
(:refer-clojure :exclude [run!])
(:require [clojure.spec.alpha :as s]
[clojure.data.generators :as gen]
[clojure.java.io :as io]
[clj-http.client :as client]
[clj-http.fake :as fake]
[scheduler.spec :refer [>defn => component-id?]]
[scheduler.agenda :as agenda]
[scheduler.db :as db]
[scheduler.json :as json]
[scheduler.random :as random]
[scheduler.time :as time]
[taoensso.timbre :as log]
[clojure.string :as str]))
(set! *warn-on-reflection* true)
(s/def ::total-executors pos-int?)
(s/def ::connected-executors nat-int?)
(s/def ::topology (s/map-of string? string?))
(s/def ::seed integer?)
(s/def ::agenda agenda/agenda?)
(s/def ::clock time/instant?)
(s/def ::next-tick time/instant?)
(s/def ::tick-frequency double?)
(s/def ::min-time-ns double?)
(s/def ::max-time-ns double?)
(s/def ::client-requests (s/coll-of agenda/entry?))
(s/def ::client-timeout-ms double?)
(s/def ::client-delay-ms double?)
(s/def ::logical-clock nat-int?)
(s/def ::state #{:started
:test-prepared
:inits-prepared
:executors-prepared
:ready
:requesting
:responding
:finished
:error-cannot-load-test-in-this-state
:error-cannot-register-in-this-state
:error-cannot-create-run-in-this-state
:error-cannot-enqueue-in-this-state
:error-cannot-execute-in-this-state})
(s/def ::data (s/keys :req-un [::total-executors
::connected-executors
::topology
::seed
::agenda
::faults
::clock
::next-tick
::tick-frequency
::min-time-ns
::max-time-ns
::client-requests
::client-timeout-ms
::client-delay-ms
::logical-clock
::state]))
(s/def ::executor-id string?)
(s/def ::components (s/coll-of component-id? :kind vector?))
(s/def ::remaining-executors nat-int?)
(>defn init-data
[]
[=> ::data]
{:total-executors 1
:connected-executors 0
:topology {}
:agenda (agenda/empty-agenda)
:seed 1
:faults []
:clock (time/init-clock)
:next-tick (time/init-clock)
:tick-frequency 50.0
:min-time-ns 0.0
:max-time-ns 0.0
:client-requests []
:client-timeout-ms (* 30.0 1000)
:client-delay-ms (* 1.0 1000)
:logical-clock 0
:state :started})
(defn ap
[data f]
[data (f data)])
(s/def ::test-id nat-int?)
(s/def ::queue-size nat-int?)
;; TODO(stevan): test needs to contain executor topology, so we know how many
;; executors to wait for.
(>defn load-test!
[data {:keys [test-id]}]
[::data (s/keys :req-un [::test-id])
=> (s/tuple ::data (s/keys :req-un [::queue-size]))]
(-> data
(update :agenda #(agenda/enqueue-many % (db/load-test! test-id)))
(update :state (fn [state]
(case state
:started :test-prepared
:error-cannot-load-test-in-this-state)))
(ap (fn [data']
{:queue-size (count (:agenda data'))}))))
(defn update+
"Like `update`, but the function also has access to the original map."
[m k f]
(update m k #(f m %)))
(comment
(-> (init-data)
(load-test! {:test-id 1})
first
(register-executor! {:executor-id "http://localhost:3000" :components ["component0"]})
first
(create-run! {:test-id 1})))
(def not-empty? (complement empty?))
(defn component-crashed?
[data entry]
(->> data
:faults
(filter #(and (= (:kind %) "crash")
(= (:from %) (:to entry))
(<= (:at %) (:at entry))))
not-empty?))
(defn should-drop?
[data entry]
(let [faults (:faults data)
entry' (-> entry
(select-keys [:to :from])
(assoc :kind "omission"
:at (:logical-clock data)))]
(or (some? ((set faults) entry'))
(component-crashed? data entry')
)))
(comment
(should-drop? {:faults [{:from "a", :to "b", :kind "omission", :at 0}]
:logical-clock 0}
{:from "a", :to "b"})
;; => true
(should-drop? {:faults [{:from "a", :to "b", :kind "omission", :at 1}]
:logical-clock 0}
{:from "a", :to "b"})
;; => false
(should-drop? {:faults [{:from "b", :kind "crash", :at 1}]
:logical-clock 0}
{:from "a", :to "b"})
;; => false
(should-drop? {:faults [{:from "b", :kind "crash", :at 0}]
:logical-clock 1}
{:from "a", :to "b"})
;; => true
(should-drop? {:faults [{:from "b", :kind "crash", :at 1}]
:logical-clock 1}
{:from "a", :to "b"})
;; => true
(should-drop? {:faults [{:from "b", :kind "crash", :at 2}
{:from "b", :kind "crash", :at 1}]
:logical-clock 1}
{:from "a", :to "b"})
;; => true
)
(defn from-client?
[body]
(-> body :from (re-matches #"^client:\d+$")))
(s/def ::url string?)
(s/def ::timestamp time/instant?)
(s/def ::body agenda/entry?)
(s/def ::drop? #{:keep :drop :delay})
(>defn fetch-new-entry!
[data]
[::data => (s/tuple ::data (s/nilable
(s/keys :req-un [::url
::timestamp
::body
::drop?])))]
(if-not (contains? #{:ready :requesting} (:state data))
[(assoc data :state :error-cannot-execute-in-this-state) nil]
(let [[agenda' entry] (agenda/dequeue (:agenda data))
entry-from-client-with-current-request (some #(= (-> % :from)
(-> entry :from))
(:client-requests data))
data' (-> data
(assoc :agenda agenda'
:clock (:at entry))
(assoc :agenda (if entry-from-client-with-current-request
(agenda/enqueue agenda' (update entry :at #(time/plus-millis % (:client-delay-ms data))))
agenda'))
(update :logical-clock (if entry-from-client-with-current-request identity inc))
(update :state (fn [state]
(case state
:ready :responding
:requesting :responding
:error-cannot-execute-in-this-state))))
;; TODO(stevan): handle case when executor-id doesn't exist... Perhaps
;; this should be checked when commands are enqueued?
meta {:test-id (:test-id data')
:run-id (:run-id data')
:logical-time (:logical-clock data')}
executor-id (get (:topology data') (:to entry))]
(assert executor-id (str "Target `" (:to entry) "' isn't in topology."))
[data' {:url executor-id
:timestamp (:at entry)
:body (assoc entry :meta meta)
:drop? (cond
(should-drop? data' entry) :drop
entry-from-client-with-current-request :delay
:else :keep)}])))
(comment
(-> (init-data)
(update
:agenda
#(agenda/enqueue
%
{:kind "invoke", :event :a, :args {}, :at (time/instant 0), :from "f", :to "t"}))
:agenda
agenda/dequeue))
(comment
(-> (init-data)
(load-test! {:test-id 1})
first
(register-executor! {:executor-id "http://localhost:3000/api/v1/event"
:components ["node1" "node2"]})
first
(create-run! {:test-id 1})
first
(fetch-new-entry!)))
(s/def ::kind string?)
(s/def ::event string?)
(s/def ::args map?)
(s/def ::to string?)
(s/def ::from string?)
(def entry? (s/and (s/keys :req-un [::kind
::event
::args
::to
::from])
#(not (#{"timer"} (:kind %)))))
(def entries? (s/coll-of entry? :kind vector?))
(s/def :ext/to
(s/or :singleton string?
:set (s/coll-of string? :kind vector?)))
(def ext-entry?
(s/and (s/keys :req-un [::kind
::event
::args
:ext/to
::from])
#(not (#{"timer"} (:kind %)))))
(def timer?
(s/and (s/keys :req-un [::kind
::args
::from
::duration-ns])
#(= (:kind %) "timer")))
(def event?
(s/or :entry entry?
:timer timer?))
(def ext-event?
(s/or :entry ext-entry?
:timer timer?))
(def events? (s/coll-of event? :kind vector?))
(>defn expand-events
[events]
[(s/coll-of ext-event?) => (s/coll-of event? :kind vector?)]
(let [up (fn [event]
(case (:kind event)
"timer" [event]
(if (string? (:to event))
[event]
(mapv #(assoc event :to %) (:to event)))))]
(vec (mapcat up events))))
(s/def ::events events?)
(defn error-state?
[state]
(some? (re-matches #"^error-.*$" (name state))))
(defn partition-haskell
"Effectively though non-lazily splits the `coll`ection using `pred`,
essentially like `[(filter coll pred) (remove coll pred)]`"
[pred coll]
(let [match (transient [])
no-match (transient [])]
(doseq [v coll]
(if (pred v)
(conj! match v)
(conj! no-match v)))
[(persistent! match) (persistent! no-match)]))
(comment
(partition-haskell odd? (range 10))
(partition-haskell odd? []))
(>defn parse-client-id
[s]
[string? => nat-int?]
(->> s (re-matches #"^client:(\d+)$") second Integer/parseInt))
(comment
(parse-client-id "client:0"))
(>defn add-client-request
[data body]
[::data agenda/entry? => ::data]
(update data :client-requests (fn [m] (conj m body))))
(>defn remove-client-requests
[data clients]
[::data (s/coll-of string?) => ::data]
(let [clients-set (set clients)]
(update data :client-requests (fn [m]
(remove (fn [body]
(contains? clients-set (:from body))) m)))))
(>defn expired-clients
[data current-time]
[::data time/instant? => (s/tuple ::data (s/coll-of agenda/entry?))]
(let [expired? (fn [body] (time/before? (time/plus-millis (:at body)
(:client-timeout-ms data))
current-time))
[to-drop to-keep] (partition-haskell expired? (-> data :client-requests))]
[(assoc data :client-requests to-keep)
to-drop]))
;; TODO(stPI:NAME:<NAME>END_PI): move to other module, since isn't pure?
;; TODO(PI:NAME:<NAME>END_PI): can we avoid using nilable here? Return `Error + Data *
;; Response` instead of always `Data * Response`? Or `Data * Error + Data * Response`?
(>defn execute!
[data]
[::data => (s/tuple ::data (s/nilable (s/keys :req-un [::events])))]
(let [[data' {:keys [url timestamp body drop?]}] (fetch-new-entry! data)]
(cond
(error-state? (:state data')) [data nil]
(= drop? :delay) (do
(log/debug :delaying-message body)
[data' {:events []}])
:else (let [is-from-client? (re-matches #"^client:\d+$" (:from body))
dropped? (= drop? :drop)
_ (log/debug :sent-logical-time body)
sent-logical-time (or (-> body :sent-logical-time)
(and is-from-client?
(:logical-clock data)))]
(let [obj (cond-> {:message (:event body)
:args (:args body)
:from (:from body)
:to (:to body)
:kind (:kind body)
:sent-logical-time sent-logical-time
:recv-logical-time (:logical-clock data')
:recv-simulated-time (:clock data')
:dropped dropped?}
is-from-client? (merge {:jepsen-type :invoke
:jepsen-process (-> body
:from
parse-client-id)}))]
(db/append-network-trace! (:test-id data)
(:run-id data)
obj))
(if dropped?
(do
(log/debug :dropped? dropped? :clock (:clock data'))
[data' {:events []}])
(let ;; TODO(PI:NAME:<NAME>END_PI): Retry on failure, this possibly needs changes to executor
;; so that we don't end up executing the same command twice.
[events (-> (client/post (str url (if (= (:kind body) "timer") "timer" "event"))
{:body (json/write body) :content-type "application/json; charset=utf-8"})
:body
json/read
(update :events expand-events))]
;; TODO(stPI:NAME:<NAME>END_PI): go into error state if response body is of form {"error": ...}
;; (if (:error events) true false)
(log/debug :events events)
(assert (:run-id data) "execute!: no run-id set...")
(let [[client-responses internal]
(partition-haskell #(and (#{"ok"} (:kind %))
(some? (re-matches #"^client:\d+$" (:to %))))
(:events events))
internal (mapv #(assoc % :sent-logical-time (:logical-clock data')) internal)
data'' (cond-> data'
is-from-client? (add-client-request body)
(not (empty? client-responses)) (update :logical-clock inc)
true (remove-client-requests (map :to client-responses)))]
;; TODO(stPI:NAME:<NAME>END_PI): use seed to shuffle client-responses?
(doseq [client-response client-responses]
(db/append-network-trace! (:test-id data)
(:run-id data)
{:message (:event client-response)
:args (:response (:args client-response))
:from (:from client-response)
:to (:to client-response)
:kind "ok" ;; ??
:sent-logical-time (:logical-clock data')
:recv-logical-time (:logical-clock data'')
:recv-simulated-time (:clock data'')
:dropped false
:jepsen-type :ok
:jepsen-process (-> client-response :to parse-client-id)}))
[data'' {:events internal}])))))))
(comment
(fake/with-fake-routes
{"http://localhost:3001/api/v1/event"
(fn [_request] {:status 200
:headers {}
:body (json/write {:events
[{:kind "invoke"
:event "inc",
:args {}
:to "client:0"
:from "node1"}]})})}
(-> (init-data)
(load-test! {:test-id 1})
first
(register-executor! {:executor-id "http://localhost:3001/api/v1/event"
:components ["node1" "node2"]})
first
(create-run! {:test-id 1})
first
(execute!))))
(s/def ::timestamped-entries (s/coll-of agenda/entry?))
(>defn timestamp-entries
[data entries timestamp]
[::data events? time/instant?
=> (s/tuple ::data (s/keys :req-un [::timestamped-entries]))]
(with-bindings {#'gen/*rnd* (java.util.Random. (:seed data))}
(let [new-seed (.nextLong gen/*rnd*)
timestamps (->> (gen/vec #(random/exponential 20) (count entries))
(mapv #(time/plus-millis timestamp %)))
update-entry (fn [entry timestamp]
(case (:kind entry)
"timer" (-> entry
;; Maybe these should have another probability distribution for how slow they are
(assoc :at (time/plus-nanos timestamp (double (max (:duration-ns entry) 0)))
:to (:from entry)
:event :timer)
(dissoc :duration))
(assoc entry :at timestamp)))]
[(assoc data :seed new-seed)
{:timestamped-entries (mapv update-entry entries timestamps)}])))
(comment
(-> (init-data)
(timestamp-entries
[{:kind "invoke"
:event "do-inc"
:args {}
:to "inc"
:from "client"}
{:kind "invoke"
:event "do-inc"
:args {}
:to "inc"
:from "client"}]
(time/init-clock))
second) )
(>defn enqueue-entry
[data timestamped-entry]
[::data agenda/entry? => (s/tuple ::data (s/keys :req-un [::queue-size]))]
(-> data
(update :agenda #(agenda/enqueue % timestamped-entry))
(update :state (fn [state]
(case state
:executors-prepared :executors-prepared ;; Loading initial messages.
:responding :responding
:error-cannot-enqueue-in-this-state)))
(ap (fn [data'] {:queue-size (count (:agenda data'))}))))
(comment
(s/explain-str agenda/entry? {:kind "invoke", :event :a, :args {}, :at (time/instant 0)
:from "f", :to "t"})
(-> (init-data)
(load-test! {:test-id 1})
first
(register-executor! {:executor-id "http://localhost:3001" :components ["node1" "node2"]})
first
(create-run! {:test-id 1})
first
(fetch-new-entry!)
first
(enqueue-entry {:kind "invoke", :event :a, :args {}, :at (time/instant 0)
:from "f", :to "t"})))
(defn min-time?
[data]
(time/before? (time/plus-nanos (time/init-clock)
(:min-time-ns data))
(:clock data)))
(comment
(min-time? {:clock (time/init-clock), :min-time-ns 0.0})
;; => false
(min-time? {:clock (time/init-clock), :min-time-ns 1.0})
;; => false
(min-time? {:clock (time/plus-nanos (time/init-clock) 1.0), :min-time-ns 1.0})
;; => false
(min-time? {:clock (time/plus-nanos (time/init-clock) 2.0), :min-time-ns 1.0})
;; => true
)
(defn max-time?
[data]
(and (not= (:max-time-ns data) 0.0)
(time/before? (time/plus-nanos (time/init-clock)
(:max-time-ns data))
(:clock data))))
(comment
(max-time? {:clock (time/init-clock), :max-time-ns 0.0})
;; => false
(max-time? {:clock (time/init-clock), :max-time-ns 1.0})
;; => false
(max-time? {:clock (time/plus-nanos (time/init-clock) 1.0), :max-time-ns 1.0})
;; => false
(max-time? {:clock (time/plus-nanos (time/init-clock) 2.0), :max-time-ns 1.0})
;; => true
)
(>defn expire-clients!
[data expired-clients]
[::data (s/coll-of agenda/entry?) => nil?]
(doseq [client expired-clients]
(db/append-network-trace! (:test-id data)
(:run-id data)
{:message (:event client)
:args (:args client)
:from (:to client)
:to (:from client)
:kind (:kind client)
:sent-logical-time (:logical-clock data)
:recv-logical-time (:logical-clock data)
:recv-simulated-time (:clock data)
:dropped false
:jepsen-type :info
:jepsen-process (-> client :from parse-client-id)})))
(>defn enqueue-timestamped-entries
[data {:keys [timestamped-entries]}]
[::data (s/keys :req-un [::timestamped-entries])
=> (s/tuple ::data (s/keys :req-un [::queue-size]))]
(if (or (and (empty? timestamped-entries) (-> data :agenda empty?) (min-time? data))
(max-time? data))
(do
(expire-clients! data (-> data :client-requests))
[(update data :state
(fn [state]
(case state
:responding :finished
:executors-prepared :inits-prepared
:error-cannot-enqueue-in-this-state)))
{:queue-size (-> data :agenda count)}])
(let [data' (-> (reduce (fn [ih timestamped-entry]
(first (enqueue-entry ih timestamped-entry)))
data
timestamped-entries)
(update :state
(fn [state] (case state
:responding :requesting
:executors-prepared :inits-prepared
:error-cannot-enqueue-in-this-state))))]
[data' {:queue-size (count (:agenda data'))}])))
(comment
(enqueue-timestamped-entries
(-> (init-data)
(load-test! {:test-id 1})
first
(register-executor! {:executor-id "http://localhost:3001" :components ["inc" "store"]})
first)
(-> (init-data)
(timestamp-entries
[{:kind "invoke"
:event "do-inc"
:args {}
:to "inc"
:from "client"}
{:kind "invoke"
:event "do-inc"
:args {}
:to "inc"
:from "client"}]
(time/instant (time/init-clock))
0)
second)))
(>defn get-initial-events!
"Get all the initial events for each component that run on an executor."
[data {:keys [executor-id]}]
[::data (s/keys :req-un [::executor-id])
=> (s/tuple ::data (s/keys :req-un [::queue-size]))]
(let [events (mapv #(assoc % :sent-logical-time (:logical-clock data))
(-> (client/get (str executor-id "/inits"))
:body
json/read
:events
expand-events))
_ (log/debug :get-initial-events executor-id events (:state data))
[data' timestamped-entries] (timestamp-entries data events (:clock data))
[data'' queue-size] (enqueue-timestamped-entries data' timestamped-entries)]
(log/debug :get-initial-events executor-id (count events))
[data'' queue-size]))
(>defn register-executor!
[data {:keys [executor-id components]}]
[::data (s/keys :req-un [::executor-id ::components])
=> (s/tuple ::data (s/keys :req-un [::remaining-executors]))]
(-> data
(update :connected-executors inc)
(update :topology #(merge % (apply hash-map
(interleave components
(replicate (count components)
executor-id)))))
(update+ :state
(fn [data' state]
(let [state' (case (compare (:connected-executors data')
(:total-executors data'))
-1 :waiting-for-executors
0 :executors-prepared
1 :error-too-many-executors)]
(case state
:test-prepared state'
:waiting-for-executors state'
:error-cannot-register-in-this-state))))
(get-initial-events! {:executor-id executor-id})
first
(ap (fn [data']
{:remaining-executors (max 0 (- (:total-executors data')
(:connected-executors data')))}))))
(comment
(let [executor-id "http://localhost:3001"
components ["components0"]]
(apply hash-map
(interleave components
(replicate (count components)
executor-id)))))
(>defn tick!
[data]
[::data => (s/tuple ::data (s/nilable (s/keys :req-un [::events])))]
(assert (or (not (empty? (:agenda data)))
(not (min-time? data))))
(let [all-events (transient [])]
(doseq [[reactor url] (:topology data)]
(let [url (str url "tick")
events (-> (client/put url
{:body (json/write {:at (:next-tick data)
:reactor reactor})
:content-type "application/json; charset=utf-8"})
:body
json/read
(update :events expand-events))]
(doseq [event (:events events)]
(conj! all-events event))))
(let [events (->> all-events
persistent!
(mapv #(assoc % :sent-logical-time (-> data :logical-clock inc))))]
[(-> data
(update :next-tick (fn [c] (time/plus-millis c (:tick-frequency data))))
(update :logical-clock (if (empty? events) identity inc))
(assoc :state :responding) ;; probably??
(assoc :clock (:next-tick data)))
{:events events}])))
(>defn execute-or-tick!
[data]
[::data => (s/tuple ::data (s/nilable (s/keys :req-un [::events])))]
(if-let [entry (-> data :agenda peek)]
(if (time/before? (:next-tick data) (:at entry))
(tick! data)
(let [[data' expired-clients] (expired-clients data (:at entry))]
(expire-clients! data' expired-clients)
(execute! data')))
(if (time/before? (:next-tick data) (time/plus-nanos (time/init-clock)
(:min-time-ns data)))
(tick! data)
[(assoc data
:clock (:next-tick data)
:state :responding) ;; I think?
{:events []}])))
(>defn step!
[data]
[::data => (s/tuple ::data (s/keys :req-un [::events ::queue-size]))]
(let [[data' events] (execute-or-tick! data)
[data'' timestamped-entries] (timestamp-entries data'
(:events events)
(-> data' :clock))
[data''' queue-size] (enqueue-timestamped-entries data'' timestamped-entries)]
[data''' (merge events queue-size)]))
(comment
(fake/with-fake-routes
{"http://localhost:3001/api/v1/event"
(fn [_request] {:status 200
:headers {}
:body (json/write {:events [{:kind "invoke"
:event :a
:args {}
:to "node1"
:from "from"}]})})}
(-> (init-data)
(load-test! {:test-id 1})
first
(register-executor! {:executor-id "http://localhost:3001/api/v1/event"
:components ["node1"]})
first
(create-run! {:test-id 1})
first
step!
first
step!)))
(defn run!
[data]
(client/with-connection-pool {:timeout 30 :threads 4 :insecure? true}
(loop [data data steps 0]
(if (= :finished (:state data))
[data {:steps steps}]
(recur (-> data step! first) (inc steps))))))
(comment
(fake/with-fake-routes
{"http://localhost:3001/api/v1/event"
(fn [_request] {:status 200
:headers {}
:body (json/write {:events []})})}
(-> (init-data)
(load-test! {:test-id 1})
first
(register-executor! {:executor-id "http://localhost:3001/api/v1/event"
:components ["node1"]})
first
(create-run! {:test-id 1})
first
run!)))
(>defn status
[data]
[::data => (s/tuple ::data ::data)]
[data data])
(comment
(status (init-data)))
(defn reset
[_data]
[(init-data) :reset])
(s/def ::at nat-int?)
(def fault? (s/keys :req-un [:scheduler.agenda/kind
:scheduler.agenda/to
:scheduler.agenda/from
::at]))
(s/def ::faults (s/coll-of fault?))
(s/def ::create-run-event
(s/keys :req-un
[::test-id
::seed
::faults
;; The following fields can in the event also be integer rather than just double
;; in the data field they will always be double though.
;; ::tick-frequency
;; ::min-time-ns
;; ::max-time-ns
]))
(>defn create-run!
[data event]
[::data ::create-run-event => (s/tuple ::data (s/keys :req-un [::run-id]))]
(case (:state data)
:inits-prepared
(let [test-id (:test-id event)
run-id (db/next-run-id! test-id)
seed (:seed event)
tick-frequency (double (:tick-frequency event))
min-time (double (:min-time-ns event))
max-time (double (:max-time-ns event))
faults (:faults event)
data (-> data
(assoc :state :ready
:test-id test-id
:run-id (:run-id run-id)
:seed seed
:tick-frequency tick-frequency
:min-time-ns min-time
:max-time-ns max-time
:faults faults))]
(db/append-create-run-event! (:test-id data) (:run-id data) event)
[data run-id])
[(assoc data :state :error-cannot-create-run-in-this-state) nil]))
;; When building with Bazel we generate a resource file containing the git
;; commit hash, otherwise we expect the git commit hash to be passed in via an
;; environment variable.
(def gitrev ^String
(if-let [file (io/resource "version.txt")]
(str/trimr (slurp file))
(or (System/getenv "DETSYS_SCHEDULER_VERSION")
"unknown")))
(s/def ::gitrev string?)
(>defn version
[data]
[::data => (s/tuple ::data (s/keys :req-un [::gitrev]))]
[data {:gitrev gitrev}])
|
[
{
"context": ")\n\n; most codes are taken from https://github.com/clojure-cookbook/clojure-cookbook\n\n; capitalization of a string id",
"end": 142,
"score": 0.9968780875205994,
"start": 126,
"tag": "USERNAME",
"value": "clojure-cookbook"
},
{
"context": "\", \"Last Name\", \"Employee ID\"])\n(def employees [[\"Ryan\", \"Neufeld\", 2]\n [\"Luke\", \"Vanderh",
"end": 1803,
"score": 0.999849796295166,
"start": 1799,
"tag": "NAME",
"value": "Ryan"
},
{
"context": " Name\", \"Employee ID\"])\n(def employees [[\"Ryan\", \"Neufeld\", 2]\n [\"Luke\", \"Vanderhart\", 1]])\n",
"end": 1814,
"score": 0.9985551834106445,
"start": 1807,
"tag": "NAME",
"value": "Neufeld"
},
{
"context": "ployees [[\"Ryan\", \"Neufeld\", 2]\n [\"Luke\", \"Vanderhart\", 1]])\n\n(->> (concat [header] emplo",
"end": 1842,
"score": 0.9998040199279785,
"start": 1838,
"tag": "NAME",
"value": "Luke"
},
{
"context": "[[\"Ryan\", \"Neufeld\", 2]\n [\"Luke\", \"Vanderhart\", 1]])\n\n(->> (concat [header] employees)\n (ma",
"end": 1856,
"score": 0.9997775554656982,
"start": 1846,
"tag": "NAME",
"value": "Vanderhart"
},
{
"context": " | Last Name | Employee ID\n;; Ryan | Neufeld | 2\n;; Luk",
"end": 2016,
"score": 0.9998326301574707,
"start": 2012,
"tag": "NAME",
"value": "Ryan"
},
{
"context": " | Employee ID\n;; Ryan | Neufeld | 2\n;; Luke | Vander",
"end": 2042,
"score": 0.9996536374092102,
"start": 2035,
"tag": "NAME",
"value": "Neufeld"
},
{
"context": "Ryan | Neufeld | 2\n;; Luke | Vanderhart | 1\n\n; Reg",
"end": 2067,
"score": 0.9997514486312866,
"start": 2063,
"tag": "NAME",
"value": "Luke"
},
{
"context": "Neufeld | 2\n;; Luke | Vanderhart | 1\n\n; Regex Match id=g11378\n\n(re-find ",
"end": 2096,
"score": 0.9997380971908569,
"start": 2086,
"tag": "NAME",
"value": "Vanderhart"
}
] | clj/ex/study_clojure/ex06/src/book_clojure_cookbook_van_der_hart.clj | mertnuhoglu/study | 1 | (ns book_clojure_cookbook_van_der_hart
(:require [clojure.string :as str]))
; most codes are taken from https://github.com/clojure-cookbook/clojure-cookbook
; capitalization of a string id=g11372
(str/capitalize "a b. c d.")
;; => "A b. c d."
(str/upper-case "ab c")
;; => "AB C"
(str/lower-case "A B")
;; => "a b"
; Clean Whitespace in a String id=g11373
(str/trim " \ta b\n")
;; => "a b"
(str/replace "a\t\nb c\fd" #"\s+" " ")
;; => "a b c d"
; Combine/Join a String id=g11374
(str "a" " " "b")
;; => "a b"
(def lines ["#! /bin/bash\n", "du -a ./ | sort -n -r\n"])
(apply str lines)
;; -> "#! /bin/bash\ndu -a ./ | sort -n -r\n"
(def f ["a" "b"]) (str/join ", " f)
(str/join [1 2 3 4]) ;; -> "1234"
;; => "1234"
;; Constructing a CSV from a header string and vector of rows
(def header "a,b\n")
(def rows ["10,20","11,21"])
(apply str header (interpose "\n" rows))
;; => "a,b\n10,20\n11,21"
; String to Character id=g11375
(seq "ali")
;; => (\a \l \i)
(frequencies (str/lower-case "aa b"))
;; => {\a 2, \space 1, \b 1}
(defn all_upper? [s]
(every? #(or (not (Character/isLetter %))
(Character/isUpperCase %))
s))
(all_upper? "A B")
;; => true
(all_upper? "A b")
;; => false
; Character to/from Integer id=g11376
(int \a)
;; -> 97
(map int "a b")
;; => (97 32 98)
(char 97)
;; -> \a
; Formatting Strings id=g11377
;; str
(def me {:k "v"})
(str "key: " (:k me))
;; => "key: v"
(apply str (interpose " " [1 2.000 (/ 3 1) (/ 4 9)]))
;; -> "1 2.0 3 4/9"
;; format
(defn filename [name i]
(format "%03d-%s" i name))
(filename "file.txt" 12)
;; => "012-file.txt"
;; Create a table using justification
(defn tableify [row]
(apply format "%-20s | %-20s | %-20s" row))
(def header ["First Name", "Last Name", "Employee ID"])
(def employees [["Ryan", "Neufeld", 2]
["Luke", "Vanderhart", 1]])
(->> (concat [header] employees)
(map tableify)
(mapv println))
;; *out*
;; First Name | Last Name | Employee ID
;; Ryan | Neufeld | 2
;; Luke | Vanderhart | 1
; Regex Match id=g11378
(re-find #"\d+" "ab 12")
;; => "12"
(re-matches #"\w+" "ab c")
;; => nil
; Regex Match: successive matches
(re-seq #"\w+" "ab c")
;; => ("ab" "c")
(defn mentions [tweet]
(re-seq #"(@|#)(\w+)" tweet))
(mentions "ab @c de. #fg")
;; => (["@c" "@" "c"] ["#fg" "#" "fg"])
; Regex Replace id=g11379
(str/replace "a b" "a" "c")
;; => "c b"
; Regex Split
(str/split "A,B" #",")
;; => ["A" "B"]
; Pluralizing Strings id=g11380
(require '[inflections.core :as inf])
(inf/pluralize 1 "monkey")
;; -> "1 monkey"
(inf/pluralize 12 "monkey")
;; -> "12 monkeys"
; Converting Between Strings, Symbols, and Keywords id=g11381
(symbol "a?")
;; => a?
(str 'a?)
;; => "a?"
(name :a)
;; => "a"
(str :a)
;; => ":a"
(keyword "a")
;; => :a
(keyword 'a)
;; => :a
(symbol (name :a))
;; => a
(name :user/a?)
;; => "a?"
(namespace :user/a?)
;; => "user"
; Precision Numbers id=g11382
2.1e2
;; -> 2.1E2
1e-10
;; -> 1.0E-10
(* 9999 9999 9999 9999 9999)
;; ArithmeticException integer overflow clojure.lang.Numbers.throwIntOverflow
(*' 9999 9999 9999 9999 9999)
;; => 99950009999000049999N
; Rational Numbers id=g11383
(/ 1 3)
;; -> 1/3
(type (/ 1 3))
;; -> clojure.lang.Ratio
(* 3 (/ 1 3))
;; -> 1N
;; `rationalize`: converts decimals to rationals
(rationalize 0.3)
;; -> 3/10
(+ (/ 1 3) (rationalize 0.3))
;; -> 19/30
; Parsing Numbers id=g11384
(Integer/parseInt "-42")
;; -> -42
(Double/parseDouble "3.14")
;; -> 3.14
; Rounding and Truncating id=g11385
(int 2.0001)
;; -> 2
(int 2.999999999)
;; -> 2
(Math/round 2.0001)
;; -> 2
(Math/round 2.999)
;; -> 3
; Fuzzy Comparison id=g11386
(defn fuzzy= [tolerance x y]
(let [diff (Math/abs (- x y))]
(< diff tolerance)))
(fuzzy= 0.01 10 10.001)
;; => true
; Trigonometry id=g11388
(Math/sin 0.1)
;; => 0.09983341664682815
; Different Bases id=g11387
(int 2r101)
;; => 5
(int 16r2A)
;; => 42
; Output:
(Integer/toString 5 2)
;; => "101"
; Partially applying: Change order of args
(defn to-base [radix n]
(Integer/toString n radix))
(def base-two (partial to-base 2))
(base-two 5)
;; => "101"
; Simple Statistics
(defn mean [coll]
(let [sum (apply + coll)
count (count coll)]
(if (pos? count)
(/ sum count)
0)))
(mean [1 2 3])
;; => 2
(mean [])
;; => 0
(defn median [coll]
(let [sorted (sort coll)
cnt (count sorted)
halfway (quot cnt 2)]
(if (odd? cnt)
(nth sorted halfway) ; <1>
(let [bottom (dec halfway)
bottom-val (nth sorted bottom)
top-val (nth sorted halfway)]
(mean [bottom-val top-val]))))) ; <2>
(median [5 2 4])
;; => 4
; Random Numbers id=g11389
(rand)
;; -> 0.0249306187447903
(inc (rand-int 6))
;; => 1
(rand-nth '(:a :b :c))
;; -> :c
; For nonsequential collections:
(rand-nth (seq #{:heads :tails}))
;; -> :heads
(shuffle [1 2 3 4 5 6])
;; -> [3 1 4 5 2 6]
; Currency
; $ lein try clojurewerkz/money
(require '[clojurewerkz.money.amounts :as ma])
(require '[clojurewerkz.money.currencies :as mc])
(def two (ma/amount-of mc/USD 2))
two
;; -> #<Money USD 2.00>
(ma/plus two two)
;; -> #<Money USD 4.00>
; imprecise numbers id=g11391
; IEEE 754 standard carry a certain imprecision by design
(- 0.23 0.24)
;; -> -0.009999999999999981
; uuid global identifiers id=g11390
(java.util.UUID/randomUUID)
;; -> #uuid "5358e6e3-7f81-40f0-84e5-750e29e6ee05"
; squuid: sortable and unique uuid
(def u1 (squuid))
u1
;; -> #uuid "527bf210-dfae-4c73-8b7a-302d3b511f41"
; Date and Time id=g11392
(defn now []
(java.util.Date.))
(now)
;; => #inst "2020-06-16T18:44:08.981-00:00"
; unix timestamp
(System/currentTimeMillis)
;; => 1592333064027
; Dates as Literals id=g11393
(def my-birthday #inst "1987-02-18T18:00:00.000-00:00")
(println my-birthday)
;; #inst "1987-02-18T18:00:00.000-00:00"
; Parsing Dates id=g11394
; $ lein try clj-time
(require '[clj-time.format :as tf])
(tf/parse (tf/formatter "MM/dd/yy") "02/18/87")
;; -> #<DateTime 1987-02-18T00:00:00.000Z>
(def wonky-format (tf/formatter "HH:mm:ss:SS' on 'yyyy-MM-dd"))
;; -> #'user/wonky-format
(tf/parse wonky-format "16:13:49:06 on 2013-04-06")
;; -> #<DateTime 2013-04-06T16:13:49.060Z>
; Formatting Dates id=g11395
(require '[clj-time.format :as tf])
(require '[clj-time.core :as t])
(tf/unparse (tf/formatters :date) (t/now))
;; -> "2013-04-06"
(def my-format (tf/formatter "MMM d, yyyy 'at' hh:mm"))
(tf/unparse my-format (t/now))
;; -> "Apr 6, 2013 at 04:54"
; Convert joda from/to java date instances id=g11396
(require '[clj-time.coerce :as tc])
(tc/from-date (java.util.Date.))
;; -> #<DateTime 2013-04-06T17:03:16.872Z>
(tc/to-date (t/now))
;; -> #inst "2013-04-06T17:03:57.239-00:00"
(tc/to-long (t/now))
;; -> 1365267761585
; Comparing Dates id=g11397
(defn now [] (java.util.Date.))
(def one-second-ago (now))
(compare (now) one-second-ago)
;; -> 1
(def occurrences
[#inst "2013-04-06T17:40:57.688-00:00"
#inst "2002-12-25T00:40:57.688-00:00"])
(sort occurrences)
;; => (#inst "2002-12-25T00:40:57.688-00:00" #inst "2013-04-06T17:40:57.688-00:00")
; Time Interval Between id=g11398
(require '[clj-time.core :as t])
(def since-april-first
(t/interval (t/date-time 2013 04 01) (t/now)))
since-april-first
;; -> #<Interval 2013-04-01T00:00:00.000Z/2013-04-06T20:06:30.507Z>
(t/in-days since-april-first)
;; -> 5
;; Years since the Moon landing
(t/in-years (t/interval (t/date-time 1969 07 20) (t/now)))
;; -> 43
;; Days from Feb. 28 to March 1 in 2012 (a leap year)
(t/in-days (t/interval (t/date-time 2012 02 28)
(t/date-time 2012 03 01)))
;; -> 2
;; And in a non-leap year
(t/in-days (t/interval (t/date-time 2013 02 28)
(t/date-time 2013 03 01)))
;; -> 1
; Generate Date and Time Ranges
;; ## Chapter 02
; Create List
'(1 :2 "3")
;; => (1 :2 "3")
(list 1 :2 "3")
;; => (1 :2 "3")
| 959 | (ns book_clojure_cookbook_van_der_hart
(:require [clojure.string :as str]))
; most codes are taken from https://github.com/clojure-cookbook/clojure-cookbook
; capitalization of a string id=g11372
(str/capitalize "a b. c d.")
;; => "A b. c d."
(str/upper-case "ab c")
;; => "AB C"
(str/lower-case "A B")
;; => "a b"
; Clean Whitespace in a String id=g11373
(str/trim " \ta b\n")
;; => "a b"
(str/replace "a\t\nb c\fd" #"\s+" " ")
;; => "a b c d"
; Combine/Join a String id=g11374
(str "a" " " "b")
;; => "a b"
(def lines ["#! /bin/bash\n", "du -a ./ | sort -n -r\n"])
(apply str lines)
;; -> "#! /bin/bash\ndu -a ./ | sort -n -r\n"
(def f ["a" "b"]) (str/join ", " f)
(str/join [1 2 3 4]) ;; -> "1234"
;; => "1234"
;; Constructing a CSV from a header string and vector of rows
(def header "a,b\n")
(def rows ["10,20","11,21"])
(apply str header (interpose "\n" rows))
;; => "a,b\n10,20\n11,21"
; String to Character id=g11375
(seq "ali")
;; => (\a \l \i)
(frequencies (str/lower-case "aa b"))
;; => {\a 2, \space 1, \b 1}
(defn all_upper? [s]
(every? #(or (not (Character/isLetter %))
(Character/isUpperCase %))
s))
(all_upper? "A B")
;; => true
(all_upper? "A b")
;; => false
; Character to/from Integer id=g11376
(int \a)
;; -> 97
(map int "a b")
;; => (97 32 98)
(char 97)
;; -> \a
; Formatting Strings id=g11377
;; str
(def me {:k "v"})
(str "key: " (:k me))
;; => "key: v"
(apply str (interpose " " [1 2.000 (/ 3 1) (/ 4 9)]))
;; -> "1 2.0 3 4/9"
;; format
(defn filename [name i]
(format "%03d-%s" i name))
(filename "file.txt" 12)
;; => "012-file.txt"
;; Create a table using justification
(defn tableify [row]
(apply format "%-20s | %-20s | %-20s" row))
(def header ["First Name", "Last Name", "Employee ID"])
(def employees [["<NAME>", "<NAME>", 2]
["<NAME>", "<NAME>", 1]])
(->> (concat [header] employees)
(map tableify)
(mapv println))
;; *out*
;; First Name | Last Name | Employee ID
;; <NAME> | <NAME> | 2
;; <NAME> | <NAME> | 1
; Regex Match id=g11378
(re-find #"\d+" "ab 12")
;; => "12"
(re-matches #"\w+" "ab c")
;; => nil
; Regex Match: successive matches
(re-seq #"\w+" "ab c")
;; => ("ab" "c")
(defn mentions [tweet]
(re-seq #"(@|#)(\w+)" tweet))
(mentions "ab @c de. #fg")
;; => (["@c" "@" "c"] ["#fg" "#" "fg"])
; Regex Replace id=g11379
(str/replace "a b" "a" "c")
;; => "c b"
; Regex Split
(str/split "A,B" #",")
;; => ["A" "B"]
; Pluralizing Strings id=g11380
(require '[inflections.core :as inf])
(inf/pluralize 1 "monkey")
;; -> "1 monkey"
(inf/pluralize 12 "monkey")
;; -> "12 monkeys"
; Converting Between Strings, Symbols, and Keywords id=g11381
(symbol "a?")
;; => a?
(str 'a?)
;; => "a?"
(name :a)
;; => "a"
(str :a)
;; => ":a"
(keyword "a")
;; => :a
(keyword 'a)
;; => :a
(symbol (name :a))
;; => a
(name :user/a?)
;; => "a?"
(namespace :user/a?)
;; => "user"
; Precision Numbers id=g11382
2.1e2
;; -> 2.1E2
1e-10
;; -> 1.0E-10
(* 9999 9999 9999 9999 9999)
;; ArithmeticException integer overflow clojure.lang.Numbers.throwIntOverflow
(*' 9999 9999 9999 9999 9999)
;; => 99950009999000049999N
; Rational Numbers id=g11383
(/ 1 3)
;; -> 1/3
(type (/ 1 3))
;; -> clojure.lang.Ratio
(* 3 (/ 1 3))
;; -> 1N
;; `rationalize`: converts decimals to rationals
(rationalize 0.3)
;; -> 3/10
(+ (/ 1 3) (rationalize 0.3))
;; -> 19/30
; Parsing Numbers id=g11384
(Integer/parseInt "-42")
;; -> -42
(Double/parseDouble "3.14")
;; -> 3.14
; Rounding and Truncating id=g11385
(int 2.0001)
;; -> 2
(int 2.999999999)
;; -> 2
(Math/round 2.0001)
;; -> 2
(Math/round 2.999)
;; -> 3
; Fuzzy Comparison id=g11386
(defn fuzzy= [tolerance x y]
(let [diff (Math/abs (- x y))]
(< diff tolerance)))
(fuzzy= 0.01 10 10.001)
;; => true
; Trigonometry id=g11388
(Math/sin 0.1)
;; => 0.09983341664682815
; Different Bases id=g11387
(int 2r101)
;; => 5
(int 16r2A)
;; => 42
; Output:
(Integer/toString 5 2)
;; => "101"
; Partially applying: Change order of args
(defn to-base [radix n]
(Integer/toString n radix))
(def base-two (partial to-base 2))
(base-two 5)
;; => "101"
; Simple Statistics
(defn mean [coll]
(let [sum (apply + coll)
count (count coll)]
(if (pos? count)
(/ sum count)
0)))
(mean [1 2 3])
;; => 2
(mean [])
;; => 0
(defn median [coll]
(let [sorted (sort coll)
cnt (count sorted)
halfway (quot cnt 2)]
(if (odd? cnt)
(nth sorted halfway) ; <1>
(let [bottom (dec halfway)
bottom-val (nth sorted bottom)
top-val (nth sorted halfway)]
(mean [bottom-val top-val]))))) ; <2>
(median [5 2 4])
;; => 4
; Random Numbers id=g11389
(rand)
;; -> 0.0249306187447903
(inc (rand-int 6))
;; => 1
(rand-nth '(:a :b :c))
;; -> :c
; For nonsequential collections:
(rand-nth (seq #{:heads :tails}))
;; -> :heads
(shuffle [1 2 3 4 5 6])
;; -> [3 1 4 5 2 6]
; Currency
; $ lein try clojurewerkz/money
(require '[clojurewerkz.money.amounts :as ma])
(require '[clojurewerkz.money.currencies :as mc])
(def two (ma/amount-of mc/USD 2))
two
;; -> #<Money USD 2.00>
(ma/plus two two)
;; -> #<Money USD 4.00>
; imprecise numbers id=g11391
; IEEE 754 standard carry a certain imprecision by design
(- 0.23 0.24)
;; -> -0.009999999999999981
; uuid global identifiers id=g11390
(java.util.UUID/randomUUID)
;; -> #uuid "5358e6e3-7f81-40f0-84e5-750e29e6ee05"
; squuid: sortable and unique uuid
(def u1 (squuid))
u1
;; -> #uuid "527bf210-dfae-4c73-8b7a-302d3b511f41"
; Date and Time id=g11392
(defn now []
(java.util.Date.))
(now)
;; => #inst "2020-06-16T18:44:08.981-00:00"
; unix timestamp
(System/currentTimeMillis)
;; => 1592333064027
; Dates as Literals id=g11393
(def my-birthday #inst "1987-02-18T18:00:00.000-00:00")
(println my-birthday)
;; #inst "1987-02-18T18:00:00.000-00:00"
; Parsing Dates id=g11394
; $ lein try clj-time
(require '[clj-time.format :as tf])
(tf/parse (tf/formatter "MM/dd/yy") "02/18/87")
;; -> #<DateTime 1987-02-18T00:00:00.000Z>
(def wonky-format (tf/formatter "HH:mm:ss:SS' on 'yyyy-MM-dd"))
;; -> #'user/wonky-format
(tf/parse wonky-format "16:13:49:06 on 2013-04-06")
;; -> #<DateTime 2013-04-06T16:13:49.060Z>
; Formatting Dates id=g11395
(require '[clj-time.format :as tf])
(require '[clj-time.core :as t])
(tf/unparse (tf/formatters :date) (t/now))
;; -> "2013-04-06"
(def my-format (tf/formatter "MMM d, yyyy 'at' hh:mm"))
(tf/unparse my-format (t/now))
;; -> "Apr 6, 2013 at 04:54"
; Convert joda from/to java date instances id=g11396
(require '[clj-time.coerce :as tc])
(tc/from-date (java.util.Date.))
;; -> #<DateTime 2013-04-06T17:03:16.872Z>
(tc/to-date (t/now))
;; -> #inst "2013-04-06T17:03:57.239-00:00"
(tc/to-long (t/now))
;; -> 1365267761585
; Comparing Dates id=g11397
(defn now [] (java.util.Date.))
(def one-second-ago (now))
(compare (now) one-second-ago)
;; -> 1
(def occurrences
[#inst "2013-04-06T17:40:57.688-00:00"
#inst "2002-12-25T00:40:57.688-00:00"])
(sort occurrences)
;; => (#inst "2002-12-25T00:40:57.688-00:00" #inst "2013-04-06T17:40:57.688-00:00")
; Time Interval Between id=g11398
(require '[clj-time.core :as t])
(def since-april-first
(t/interval (t/date-time 2013 04 01) (t/now)))
since-april-first
;; -> #<Interval 2013-04-01T00:00:00.000Z/2013-04-06T20:06:30.507Z>
(t/in-days since-april-first)
;; -> 5
;; Years since the Moon landing
(t/in-years (t/interval (t/date-time 1969 07 20) (t/now)))
;; -> 43
;; Days from Feb. 28 to March 1 in 2012 (a leap year)
(t/in-days (t/interval (t/date-time 2012 02 28)
(t/date-time 2012 03 01)))
;; -> 2
;; And in a non-leap year
(t/in-days (t/interval (t/date-time 2013 02 28)
(t/date-time 2013 03 01)))
;; -> 1
; Generate Date and Time Ranges
;; ## Chapter 02
; Create List
'(1 :2 "3")
;; => (1 :2 "3")
(list 1 :2 "3")
;; => (1 :2 "3")
| true | (ns book_clojure_cookbook_van_der_hart
(:require [clojure.string :as str]))
; most codes are taken from https://github.com/clojure-cookbook/clojure-cookbook
; capitalization of a string id=g11372
(str/capitalize "a b. c d.")
;; => "A b. c d."
(str/upper-case "ab c")
;; => "AB C"
(str/lower-case "A B")
;; => "a b"
; Clean Whitespace in a String id=g11373
(str/trim " \ta b\n")
;; => "a b"
(str/replace "a\t\nb c\fd" #"\s+" " ")
;; => "a b c d"
; Combine/Join a String id=g11374
(str "a" " " "b")
;; => "a b"
(def lines ["#! /bin/bash\n", "du -a ./ | sort -n -r\n"])
(apply str lines)
;; -> "#! /bin/bash\ndu -a ./ | sort -n -r\n"
(def f ["a" "b"]) (str/join ", " f)
(str/join [1 2 3 4]) ;; -> "1234"
;; => "1234"
;; Constructing a CSV from a header string and vector of rows
(def header "a,b\n")
(def rows ["10,20","11,21"])
(apply str header (interpose "\n" rows))
;; => "a,b\n10,20\n11,21"
; String to Character id=g11375
(seq "ali")
;; => (\a \l \i)
(frequencies (str/lower-case "aa b"))
;; => {\a 2, \space 1, \b 1}
(defn all_upper? [s]
(every? #(or (not (Character/isLetter %))
(Character/isUpperCase %))
s))
(all_upper? "A B")
;; => true
(all_upper? "A b")
;; => false
; Character to/from Integer id=g11376
(int \a)
;; -> 97
(map int "a b")
;; => (97 32 98)
(char 97)
;; -> \a
; Formatting Strings id=g11377
;; str
(def me {:k "v"})
(str "key: " (:k me))
;; => "key: v"
(apply str (interpose " " [1 2.000 (/ 3 1) (/ 4 9)]))
;; -> "1 2.0 3 4/9"
;; format
(defn filename [name i]
(format "%03d-%s" i name))
(filename "file.txt" 12)
;; => "012-file.txt"
;; Create a table using justification
(defn tableify [row]
(apply format "%-20s | %-20s | %-20s" row))
(def header ["First Name", "Last Name", "Employee ID"])
(def employees [["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", 2]
["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", 1]])
(->> (concat [header] employees)
(map tableify)
(mapv println))
;; *out*
;; First Name | Last Name | Employee ID
;; PI:NAME:<NAME>END_PI | PI:NAME:<NAME>END_PI | 2
;; PI:NAME:<NAME>END_PI | PI:NAME:<NAME>END_PI | 1
; Regex Match id=g11378
(re-find #"\d+" "ab 12")
;; => "12"
(re-matches #"\w+" "ab c")
;; => nil
; Regex Match: successive matches
(re-seq #"\w+" "ab c")
;; => ("ab" "c")
(defn mentions [tweet]
(re-seq #"(@|#)(\w+)" tweet))
(mentions "ab @c de. #fg")
;; => (["@c" "@" "c"] ["#fg" "#" "fg"])
; Regex Replace id=g11379
(str/replace "a b" "a" "c")
;; => "c b"
; Regex Split
(str/split "A,B" #",")
;; => ["A" "B"]
; Pluralizing Strings id=g11380
(require '[inflections.core :as inf])
(inf/pluralize 1 "monkey")
;; -> "1 monkey"
(inf/pluralize 12 "monkey")
;; -> "12 monkeys"
; Converting Between Strings, Symbols, and Keywords id=g11381
(symbol "a?")
;; => a?
(str 'a?)
;; => "a?"
(name :a)
;; => "a"
(str :a)
;; => ":a"
(keyword "a")
;; => :a
(keyword 'a)
;; => :a
(symbol (name :a))
;; => a
(name :user/a?)
;; => "a?"
(namespace :user/a?)
;; => "user"
; Precision Numbers id=g11382
2.1e2
;; -> 2.1E2
1e-10
;; -> 1.0E-10
(* 9999 9999 9999 9999 9999)
;; ArithmeticException integer overflow clojure.lang.Numbers.throwIntOverflow
(*' 9999 9999 9999 9999 9999)
;; => 99950009999000049999N
; Rational Numbers id=g11383
(/ 1 3)
;; -> 1/3
(type (/ 1 3))
;; -> clojure.lang.Ratio
(* 3 (/ 1 3))
;; -> 1N
;; `rationalize`: converts decimals to rationals
(rationalize 0.3)
;; -> 3/10
(+ (/ 1 3) (rationalize 0.3))
;; -> 19/30
; Parsing Numbers id=g11384
(Integer/parseInt "-42")
;; -> -42
(Double/parseDouble "3.14")
;; -> 3.14
; Rounding and Truncating id=g11385
(int 2.0001)
;; -> 2
(int 2.999999999)
;; -> 2
(Math/round 2.0001)
;; -> 2
(Math/round 2.999)
;; -> 3
; Fuzzy Comparison id=g11386
(defn fuzzy= [tolerance x y]
(let [diff (Math/abs (- x y))]
(< diff tolerance)))
(fuzzy= 0.01 10 10.001)
;; => true
; Trigonometry id=g11388
(Math/sin 0.1)
;; => 0.09983341664682815
; Different Bases id=g11387
(int 2r101)
;; => 5
(int 16r2A)
;; => 42
; Output:
(Integer/toString 5 2)
;; => "101"
; Partially applying: Change order of args
(defn to-base [radix n]
(Integer/toString n radix))
(def base-two (partial to-base 2))
(base-two 5)
;; => "101"
; Simple Statistics
(defn mean [coll]
(let [sum (apply + coll)
count (count coll)]
(if (pos? count)
(/ sum count)
0)))
(mean [1 2 3])
;; => 2
(mean [])
;; => 0
(defn median [coll]
(let [sorted (sort coll)
cnt (count sorted)
halfway (quot cnt 2)]
(if (odd? cnt)
(nth sorted halfway) ; <1>
(let [bottom (dec halfway)
bottom-val (nth sorted bottom)
top-val (nth sorted halfway)]
(mean [bottom-val top-val]))))) ; <2>
(median [5 2 4])
;; => 4
; Random Numbers id=g11389
(rand)
;; -> 0.0249306187447903
(inc (rand-int 6))
;; => 1
(rand-nth '(:a :b :c))
;; -> :c
; For nonsequential collections:
(rand-nth (seq #{:heads :tails}))
;; -> :heads
(shuffle [1 2 3 4 5 6])
;; -> [3 1 4 5 2 6]
; Currency
; $ lein try clojurewerkz/money
(require '[clojurewerkz.money.amounts :as ma])
(require '[clojurewerkz.money.currencies :as mc])
(def two (ma/amount-of mc/USD 2))
two
;; -> #<Money USD 2.00>
(ma/plus two two)
;; -> #<Money USD 4.00>
; imprecise numbers id=g11391
; IEEE 754 standard carry a certain imprecision by design
(- 0.23 0.24)
;; -> -0.009999999999999981
; uuid global identifiers id=g11390
(java.util.UUID/randomUUID)
;; -> #uuid "5358e6e3-7f81-40f0-84e5-750e29e6ee05"
; squuid: sortable and unique uuid
(def u1 (squuid))
u1
;; -> #uuid "527bf210-dfae-4c73-8b7a-302d3b511f41"
; Date and Time id=g11392
(defn now []
(java.util.Date.))
(now)
;; => #inst "2020-06-16T18:44:08.981-00:00"
; unix timestamp
(System/currentTimeMillis)
;; => 1592333064027
; Dates as Literals id=g11393
(def my-birthday #inst "1987-02-18T18:00:00.000-00:00")
(println my-birthday)
;; #inst "1987-02-18T18:00:00.000-00:00"
; Parsing Dates id=g11394
; $ lein try clj-time
(require '[clj-time.format :as tf])
(tf/parse (tf/formatter "MM/dd/yy") "02/18/87")
;; -> #<DateTime 1987-02-18T00:00:00.000Z>
(def wonky-format (tf/formatter "HH:mm:ss:SS' on 'yyyy-MM-dd"))
;; -> #'user/wonky-format
(tf/parse wonky-format "16:13:49:06 on 2013-04-06")
;; -> #<DateTime 2013-04-06T16:13:49.060Z>
; Formatting Dates id=g11395
(require '[clj-time.format :as tf])
(require '[clj-time.core :as t])
(tf/unparse (tf/formatters :date) (t/now))
;; -> "2013-04-06"
(def my-format (tf/formatter "MMM d, yyyy 'at' hh:mm"))
(tf/unparse my-format (t/now))
;; -> "Apr 6, 2013 at 04:54"
; Convert joda from/to java date instances id=g11396
(require '[clj-time.coerce :as tc])
(tc/from-date (java.util.Date.))
;; -> #<DateTime 2013-04-06T17:03:16.872Z>
(tc/to-date (t/now))
;; -> #inst "2013-04-06T17:03:57.239-00:00"
(tc/to-long (t/now))
;; -> 1365267761585
; Comparing Dates id=g11397
(defn now [] (java.util.Date.))
(def one-second-ago (now))
(compare (now) one-second-ago)
;; -> 1
(def occurrences
[#inst "2013-04-06T17:40:57.688-00:00"
#inst "2002-12-25T00:40:57.688-00:00"])
(sort occurrences)
;; => (#inst "2002-12-25T00:40:57.688-00:00" #inst "2013-04-06T17:40:57.688-00:00")
; Time Interval Between id=g11398
(require '[clj-time.core :as t])
(def since-april-first
(t/interval (t/date-time 2013 04 01) (t/now)))
since-april-first
;; -> #<Interval 2013-04-01T00:00:00.000Z/2013-04-06T20:06:30.507Z>
(t/in-days since-april-first)
;; -> 5
;; Years since the Moon landing
(t/in-years (t/interval (t/date-time 1969 07 20) (t/now)))
;; -> 43
;; Days from Feb. 28 to March 1 in 2012 (a leap year)
(t/in-days (t/interval (t/date-time 2012 02 28)
(t/date-time 2012 03 01)))
;; -> 2
;; And in a non-leap year
(t/in-days (t/interval (t/date-time 2013 02 28)
(t/date-time 2013 03 01)))
;; -> 1
; Generate Date and Time Ranges
;; ## Chapter 02
; Create List
'(1 :2 "3")
;; => (1 :2 "3")
(list 1 :2 "3")
;; => (1 :2 "3")
|
[
{
"context": "\n ; [:g [:title \"Mierda\"]\n ; [:circle {",
"end": 11139,
"score": 0.7029390335083008,
"start": 11133,
"tag": "NAME",
"value": "Mierda"
}
] | src/cljs/orbis_grcmanager/pages/riskprofile.cljs | Orbisnetworkadmin/orbis-grcmanager | 0 | (ns orbis-grcmanager.pages.riskprofile
(:require [reagent.core :as r]
[re-frame.core :refer [subscribe]]
[orbis-grcmanager.pages.issues :refer [markdown-preview]]
[orbis-grcmanager.subscriptions :as subs]
[orbis-grcmanager.key-events :refer [on-enter]]
[orbis-grcmanager.bootstrap :as bs]
[orbis-grcmanager.routes :refer [href navigate!]]
[reagent-data-table.core :as rdt]
[orbis-grcmanager.validation :as v]
[re-frame-datatable.core :as dt]
[re-frame-datatable.views :as views]
[orbis-grcmanager.pages.common :refer [validation-modal confirm-modal]]
[re-com.core
:refer [box v-box h-split v-split title flex-child-style input-text input-textarea]]))
; Funciones / Componentes General:
(defn nuevo-rr []
[:a.btn.btn-sm.btn-success.pull-right
(href "/create-rr") "Nuevo"])
(defn editar-registro []
[:a.btn.btn-sm.btn-success.pull-right
(href "/edit-rr") "Editar"])
(defn eliminar-rr-group []
[:a.btn.btn-sm.btn-danger.pull-right
(href "/delete-group") "Eliminar"])
; Fin Funciones / Componentes General------------------------------------------------------------------------------------------------------------------
; ---------------------------------------------------------------------------------------------------------------------
; Risk Profile Sumary
; Funciones:
(defn buscar-risk-register []
(r/with-let [search (r/atom nil)
buscar #(when-let [value (not-empty @search)]
(navigate! (str "/riskprofile" value)))]
[bs/FormGroup
[bs/InputGroup
[bs/FormControl
{:type "text"
:class "input-sm"
:placeholder "Introduzca el valor de busqueda"
:on-change #(reset! search (-> % .-target .-value))
:on-key-down #(on-enter % buscar)}]
[bs/InputGroup.Button
[:button.btn.btn-sm.btn-default
{:on-click buscar}
"Buscar"]]]]))
; Grid
; Define la función de renderización de la tabla re-frame. Se incluyen:
;;:NombreDeLaTabla
;[:mi-subscripción-re-frame]
;[{::dt/column-key [:columna-1-llave-reframe]
; ::dt/sorting {::dt/enabled? false}
; ::dt/column-label "Riesgo"}
(defn tabla-reframe []
[dt/datatable
:RegistrodeRiesgos
[:risk-registers]
[{::dt/column-key [:id-risk-register]
::dt/sorting {::dt/enabled? false}
::dt/column-label "ID"}
{::dt/column-key [:id-risk]
::dt/sorting {::dt/enabled? false}
::dt/column-label "Riesgo"}
{::dt/column-key [:id-risk-subtype]
::dt/column-label "Tipo"}
{::dt/column-key [:description-risk-register]
::dt/column-label "Descripción"
::dt/sorting {::dt/enabled? false}
::dt/render-fn formato-columna-href}
{::dt/column-key [:likelihood-risk-register]
::dt/column-label "Probabilidad"
::dt/sorting {::dt/enabled? true}}
{::dt/column-key [:impact-risk-register]
::dt/column-label "Impacto"
::dt/sorting {::dt/enabled? true}}
{::dt/column-key [:inherent-risk-register]
::dt/column-label "Inherente"
::dt/sorting {::dt/enabled? true}
::dt/render-fn semaforo-formatter-inherent
}
{::dt/column-key [:current-risk-register]
::dt/column-label "Corriente"
::dt/sorting {::dt/enabled? true}
::dt/render-fn semaforo-formatter-current
}
{::dt/column-key [:residual-risk-register]
::dt/column-label "Residual"
::dt/sorting {::dt/enabled? true}
::dt/render-fn semaforo-formatter-residual
}
{::dt/column-key [:status-risk-register]
::dt/column-label "Status"
::dt/sorting {::dt/enabled? true}}
]
{::dt/pagination {::dt/enabled? true
::dt/per-page 10}
::dt/table-classes ["table-striped" "table-bordered" "table-hover" "table"],
::dt/selection {::dt/enabled? true}}]
)
; Se hace la referencia al ns views de la librería, para funciones de visualización paginación y selección de página.
;Risk Register:
(defn control-paginacion []
[views/default-pagination-controls :RegistrodeRiesgos [:risk-registers]]
)
(defn selector-por-pagina []
[views/per-page-selector :RegistrodeRiesgos [:risk-registers]]
)
(defn formato-columna-href [description risk-register]
[:a {:href (str "/riskregister/" (get-in risk-register [:id-risk-register]))}
description]
)
(defn selected-rows-preview []
[:pre
[:code
@(subscribe [::dt/selected-items
:RegistrodeRiesgos
[:risk-registers]])]])
(defn semaforo-formatter-residual [_ risk-registers]
[:div.row>div.col-sm-12
[bs/Label
(semaforo :residual-risk-register risk-registers) (texto-etiqueta :residual-risk-register risk-registers)]
])
(defn semaforo-formatter-inherent [_ risk-registers]
[:div.row>div.col-sm-12
[bs/Label
(semaforo :inherent-risk-register risk-registers) (texto-etiqueta :inherent-risk-register risk-registers)]
])
(defn semaforo-formatter-current [_ risk-registers]
[:div.row>div.col-sm-12
[bs/Label
(semaforo :current-risk-register risk-registers) (texto-etiqueta :current-risk-register risk-registers)]
])
(defn texto-etiqueta [clave risk-registers]
(if (not (= (get-in risk-registers [clave]) nil))
(str (get-in risk-registers [clave]))
"vacio"
))
(defn semaforo [clave risk-registers]
(if (not (= (get-in risk-registers [clave]) nil))
(cond
(and (> (get-in risk-registers [clave]) 3.99) (< (get-in risk-registers [clave]) 7.00))
{:bs-style "success"}
(and (> (get-in risk-registers [clave]) 6.99) (< (get-in risk-registers [clave]) 10.00))
{:bs-style "info"}
(and (> (get-in risk-registers [clave]) 9.99) (< (get-in risk-registers [clave]) 13.00))
{:bs-style "warning"}
(> (get-in risk-registers [clave]) 12.99)
{:bs-style "danger"}
:else {:bs-style "primary"}
)
{:bs-style "default"}))
(defn pintar-circulo [risk-registers]
[:div
(if (or (= (:impact-risk-register rg) nil) (= (:likelihood-risk-register rg) nil))
(for [rg risk-registers]
[:h1 [:svg.heat-map
;[:g
[:g [:title "Prueba"][componente (:impact-risk-register rg) (:likelihood-risk-register rg) "white"]]
;[componente-texto (:impact-risk-register rg) (:likelihood-risk-register rg) (str (:id-risk-register rg))]
;]
]]
)
[componente 10000 10000 "yellow"])
])
(defn pintar-id [risk-registers]
[:div
(if (or (= (:impact-risk-register rg) nil) (= (:likelihood-risk-register rg) nil))
(for [rg risk-registers]
[:h1 [:svg.heat-map
[componente-texto (:impact-risk-register rg) (:likelihood-risk-register rg) (str (:id-risk-register rg))]
]
]
)
[componente 10000 10000 "yellow"])
])
(defn componente [x y color] [:circle {:fill color :stroke "black" :r 20 :cx (* x 100) :cy (- 500 (* y 100))}])
(defn componente-texto [x y texto] [:text {:fill "black" :x (* x 100) :y (- 500 (* y 100)) :text-anchor "middle" :stroke "black" :stroke-width "1px" :dy ".3em"} texto])
;[:svg.heat-map [:circle {:fill "blue" :stroke "black" :r 20 :cx 100 :cy 100}][:text {:fill "black" :x 100 :y 100 :text-anchor "middle" :stroke "black" :stroke-width "1px" :dy ".3em"} "10"]]
; Páginas:
(defn heat-map []
[:table.table.table-bordered.heat-mapT
[:thead
[:tr
[:th.cellYellow]
[:th.cellOrange]
[:th.cellRed]
[:th.cellRed]
[:th.cellRed]
]
]
[:thead
[:tr
[:th.cellLGreen]
[:th.cellYellow]
[:th.cellOrange]
[:th.cellRed]
[:th.cellRed]
]
]
[:thead
[:tr
[:th.cellGreen]
[:th.cellLGreen]
[:th.cellYellow]
[:th.cellOrange]
[:th.cellRed]
]
]
[:thead
[:tr
[:th.cellGreen]
[:th.cellLGreen]
[:th.cellLGreen]
[:th.cellYellow]
[:th.cellOrange]
]
]
[:thead
[:tr
[:th.cellGreen]
[:th.cellGreen]
[:th.cellGreen]
[:th.cellLGreen]
[:th.cellYellow]
]
]]
)
;(defn svg []
; ;[:svg.heat-map
; [pintar-circulo atomo-risk-profile-local]
; ;[:circle {:fill "Green" :stroke "black" :r 5 :cx 10 :cy 400}]
; ;(pintar-circulo [])
; ;[pintar-circulo atomo-risk-profile-local]
; ;]
; )
(defn svg-texto []
[:svg.heat-mapSVG
[:text {:fill "black" :x -250 :y 30 :transform "rotate(-90 20,20)"} "Probabilidad 0 - 5"]
[:text {:fill "black" :x 250 :y 525} "Impacto 0 - 5"]
]
)
(defn subscription-rows-preview []
[:pre
[:code
(db [:risk-registers])]])
(defn risk-profile-sumary-page []
(r/with-let [atomo-risk-profile-local @(subscribe [:risk-registers])]
[:div.container
[:div.row
[:div.col-sm-6
;[svg-texto] [heat-map][pintar-circulo atomo-risk-profile-local] [pintar-id atomo-risk-profile-local] [svg-texto-horizontal]
[heat-map][pintar-circulo atomo-risk-profile-local] [pintar-id atomo-risk-profile-local] [svg-texto]
]
[:div.col-sm-6
[heat-map][pintar-circulo @(subscribe [::dt/selected-items
:RegistrodeRiesgos
[:risk-registers]]) ] [pintar-id @(subscribe [::dt/selected-items
:RegistrodeRiesgos
[:risk-registers]])] [svg-texto] ]]
[:div.espacio
[:div.row
[:div.col-sm-12
[:h2 "Risk Profile"]
; Para pruebas
;[pintar-circulo atomo-risk-profile-local]
;[:h2 (str (pintar-circulo @(subscribe [::dt/selected-items
; :RegistrodeRiesgos
; [:risk-registers]]) ))]
[buscar-risk-register]]
[:div.col-sm-12 [:div.panel.panel-default [tabla-reframe] [control-paginacion] [selector-por-pagina]
;pruebas:
;[:svg.heat-map [:g [:title "Prueba"]
; [:circle {:fill "green" :stroke "black" :r 20 :cx 120 :cy 120}][:text {:fill "black" :x 120 :y 120 :text-anchor "middle" :stroke "black" :stroke-width "1px" :dy ".3em"} "10"]
; ]
; [:g [:title "Mierda"]
; [:circle {:fill "blue" :stroke "black" :r 20 :cx 100 :cy 100}][:text {:fill "black" :x 100 :y 100 :text-anchor "middle" :stroke "black" :stroke-width "1px" :dy ".3em"} "10"]
; ]
; ]
; Fin pruebas
]
]]]]))
; Fin Risk Register Summary---------------------------------------------------------------------------------------------------------------------
| 63487 | (ns orbis-grcmanager.pages.riskprofile
(:require [reagent.core :as r]
[re-frame.core :refer [subscribe]]
[orbis-grcmanager.pages.issues :refer [markdown-preview]]
[orbis-grcmanager.subscriptions :as subs]
[orbis-grcmanager.key-events :refer [on-enter]]
[orbis-grcmanager.bootstrap :as bs]
[orbis-grcmanager.routes :refer [href navigate!]]
[reagent-data-table.core :as rdt]
[orbis-grcmanager.validation :as v]
[re-frame-datatable.core :as dt]
[re-frame-datatable.views :as views]
[orbis-grcmanager.pages.common :refer [validation-modal confirm-modal]]
[re-com.core
:refer [box v-box h-split v-split title flex-child-style input-text input-textarea]]))
; Funciones / Componentes General:
(defn nuevo-rr []
[:a.btn.btn-sm.btn-success.pull-right
(href "/create-rr") "Nuevo"])
(defn editar-registro []
[:a.btn.btn-sm.btn-success.pull-right
(href "/edit-rr") "Editar"])
(defn eliminar-rr-group []
[:a.btn.btn-sm.btn-danger.pull-right
(href "/delete-group") "Eliminar"])
; Fin Funciones / Componentes General------------------------------------------------------------------------------------------------------------------
; ---------------------------------------------------------------------------------------------------------------------
; Risk Profile Sumary
; Funciones:
(defn buscar-risk-register []
(r/with-let [search (r/atom nil)
buscar #(when-let [value (not-empty @search)]
(navigate! (str "/riskprofile" value)))]
[bs/FormGroup
[bs/InputGroup
[bs/FormControl
{:type "text"
:class "input-sm"
:placeholder "Introduzca el valor de busqueda"
:on-change #(reset! search (-> % .-target .-value))
:on-key-down #(on-enter % buscar)}]
[bs/InputGroup.Button
[:button.btn.btn-sm.btn-default
{:on-click buscar}
"Buscar"]]]]))
; Grid
; Define la función de renderización de la tabla re-frame. Se incluyen:
;;:NombreDeLaTabla
;[:mi-subscripción-re-frame]
;[{::dt/column-key [:columna-1-llave-reframe]
; ::dt/sorting {::dt/enabled? false}
; ::dt/column-label "Riesgo"}
(defn tabla-reframe []
[dt/datatable
:RegistrodeRiesgos
[:risk-registers]
[{::dt/column-key [:id-risk-register]
::dt/sorting {::dt/enabled? false}
::dt/column-label "ID"}
{::dt/column-key [:id-risk]
::dt/sorting {::dt/enabled? false}
::dt/column-label "Riesgo"}
{::dt/column-key [:id-risk-subtype]
::dt/column-label "Tipo"}
{::dt/column-key [:description-risk-register]
::dt/column-label "Descripción"
::dt/sorting {::dt/enabled? false}
::dt/render-fn formato-columna-href}
{::dt/column-key [:likelihood-risk-register]
::dt/column-label "Probabilidad"
::dt/sorting {::dt/enabled? true}}
{::dt/column-key [:impact-risk-register]
::dt/column-label "Impacto"
::dt/sorting {::dt/enabled? true}}
{::dt/column-key [:inherent-risk-register]
::dt/column-label "Inherente"
::dt/sorting {::dt/enabled? true}
::dt/render-fn semaforo-formatter-inherent
}
{::dt/column-key [:current-risk-register]
::dt/column-label "Corriente"
::dt/sorting {::dt/enabled? true}
::dt/render-fn semaforo-formatter-current
}
{::dt/column-key [:residual-risk-register]
::dt/column-label "Residual"
::dt/sorting {::dt/enabled? true}
::dt/render-fn semaforo-formatter-residual
}
{::dt/column-key [:status-risk-register]
::dt/column-label "Status"
::dt/sorting {::dt/enabled? true}}
]
{::dt/pagination {::dt/enabled? true
::dt/per-page 10}
::dt/table-classes ["table-striped" "table-bordered" "table-hover" "table"],
::dt/selection {::dt/enabled? true}}]
)
; Se hace la referencia al ns views de la librería, para funciones de visualización paginación y selección de página.
;Risk Register:
(defn control-paginacion []
[views/default-pagination-controls :RegistrodeRiesgos [:risk-registers]]
)
(defn selector-por-pagina []
[views/per-page-selector :RegistrodeRiesgos [:risk-registers]]
)
(defn formato-columna-href [description risk-register]
[:a {:href (str "/riskregister/" (get-in risk-register [:id-risk-register]))}
description]
)
(defn selected-rows-preview []
[:pre
[:code
@(subscribe [::dt/selected-items
:RegistrodeRiesgos
[:risk-registers]])]])
(defn semaforo-formatter-residual [_ risk-registers]
[:div.row>div.col-sm-12
[bs/Label
(semaforo :residual-risk-register risk-registers) (texto-etiqueta :residual-risk-register risk-registers)]
])
(defn semaforo-formatter-inherent [_ risk-registers]
[:div.row>div.col-sm-12
[bs/Label
(semaforo :inherent-risk-register risk-registers) (texto-etiqueta :inherent-risk-register risk-registers)]
])
(defn semaforo-formatter-current [_ risk-registers]
[:div.row>div.col-sm-12
[bs/Label
(semaforo :current-risk-register risk-registers) (texto-etiqueta :current-risk-register risk-registers)]
])
(defn texto-etiqueta [clave risk-registers]
(if (not (= (get-in risk-registers [clave]) nil))
(str (get-in risk-registers [clave]))
"vacio"
))
(defn semaforo [clave risk-registers]
(if (not (= (get-in risk-registers [clave]) nil))
(cond
(and (> (get-in risk-registers [clave]) 3.99) (< (get-in risk-registers [clave]) 7.00))
{:bs-style "success"}
(and (> (get-in risk-registers [clave]) 6.99) (< (get-in risk-registers [clave]) 10.00))
{:bs-style "info"}
(and (> (get-in risk-registers [clave]) 9.99) (< (get-in risk-registers [clave]) 13.00))
{:bs-style "warning"}
(> (get-in risk-registers [clave]) 12.99)
{:bs-style "danger"}
:else {:bs-style "primary"}
)
{:bs-style "default"}))
(defn pintar-circulo [risk-registers]
[:div
(if (or (= (:impact-risk-register rg) nil) (= (:likelihood-risk-register rg) nil))
(for [rg risk-registers]
[:h1 [:svg.heat-map
;[:g
[:g [:title "Prueba"][componente (:impact-risk-register rg) (:likelihood-risk-register rg) "white"]]
;[componente-texto (:impact-risk-register rg) (:likelihood-risk-register rg) (str (:id-risk-register rg))]
;]
]]
)
[componente 10000 10000 "yellow"])
])
(defn pintar-id [risk-registers]
[:div
(if (or (= (:impact-risk-register rg) nil) (= (:likelihood-risk-register rg) nil))
(for [rg risk-registers]
[:h1 [:svg.heat-map
[componente-texto (:impact-risk-register rg) (:likelihood-risk-register rg) (str (:id-risk-register rg))]
]
]
)
[componente 10000 10000 "yellow"])
])
(defn componente [x y color] [:circle {:fill color :stroke "black" :r 20 :cx (* x 100) :cy (- 500 (* y 100))}])
(defn componente-texto [x y texto] [:text {:fill "black" :x (* x 100) :y (- 500 (* y 100)) :text-anchor "middle" :stroke "black" :stroke-width "1px" :dy ".3em"} texto])
;[:svg.heat-map [:circle {:fill "blue" :stroke "black" :r 20 :cx 100 :cy 100}][:text {:fill "black" :x 100 :y 100 :text-anchor "middle" :stroke "black" :stroke-width "1px" :dy ".3em"} "10"]]
; Páginas:
(defn heat-map []
[:table.table.table-bordered.heat-mapT
[:thead
[:tr
[:th.cellYellow]
[:th.cellOrange]
[:th.cellRed]
[:th.cellRed]
[:th.cellRed]
]
]
[:thead
[:tr
[:th.cellLGreen]
[:th.cellYellow]
[:th.cellOrange]
[:th.cellRed]
[:th.cellRed]
]
]
[:thead
[:tr
[:th.cellGreen]
[:th.cellLGreen]
[:th.cellYellow]
[:th.cellOrange]
[:th.cellRed]
]
]
[:thead
[:tr
[:th.cellGreen]
[:th.cellLGreen]
[:th.cellLGreen]
[:th.cellYellow]
[:th.cellOrange]
]
]
[:thead
[:tr
[:th.cellGreen]
[:th.cellGreen]
[:th.cellGreen]
[:th.cellLGreen]
[:th.cellYellow]
]
]]
)
;(defn svg []
; ;[:svg.heat-map
; [pintar-circulo atomo-risk-profile-local]
; ;[:circle {:fill "Green" :stroke "black" :r 5 :cx 10 :cy 400}]
; ;(pintar-circulo [])
; ;[pintar-circulo atomo-risk-profile-local]
; ;]
; )
(defn svg-texto []
[:svg.heat-mapSVG
[:text {:fill "black" :x -250 :y 30 :transform "rotate(-90 20,20)"} "Probabilidad 0 - 5"]
[:text {:fill "black" :x 250 :y 525} "Impacto 0 - 5"]
]
)
(defn subscription-rows-preview []
[:pre
[:code
(db [:risk-registers])]])
(defn risk-profile-sumary-page []
(r/with-let [atomo-risk-profile-local @(subscribe [:risk-registers])]
[:div.container
[:div.row
[:div.col-sm-6
;[svg-texto] [heat-map][pintar-circulo atomo-risk-profile-local] [pintar-id atomo-risk-profile-local] [svg-texto-horizontal]
[heat-map][pintar-circulo atomo-risk-profile-local] [pintar-id atomo-risk-profile-local] [svg-texto]
]
[:div.col-sm-6
[heat-map][pintar-circulo @(subscribe [::dt/selected-items
:RegistrodeRiesgos
[:risk-registers]]) ] [pintar-id @(subscribe [::dt/selected-items
:RegistrodeRiesgos
[:risk-registers]])] [svg-texto] ]]
[:div.espacio
[:div.row
[:div.col-sm-12
[:h2 "Risk Profile"]
; Para pruebas
;[pintar-circulo atomo-risk-profile-local]
;[:h2 (str (pintar-circulo @(subscribe [::dt/selected-items
; :RegistrodeRiesgos
; [:risk-registers]]) ))]
[buscar-risk-register]]
[:div.col-sm-12 [:div.panel.panel-default [tabla-reframe] [control-paginacion] [selector-por-pagina]
;pruebas:
;[:svg.heat-map [:g [:title "Prueba"]
; [:circle {:fill "green" :stroke "black" :r 20 :cx 120 :cy 120}][:text {:fill "black" :x 120 :y 120 :text-anchor "middle" :stroke "black" :stroke-width "1px" :dy ".3em"} "10"]
; ]
; [:g [:title "<NAME>"]
; [:circle {:fill "blue" :stroke "black" :r 20 :cx 100 :cy 100}][:text {:fill "black" :x 100 :y 100 :text-anchor "middle" :stroke "black" :stroke-width "1px" :dy ".3em"} "10"]
; ]
; ]
; Fin pruebas
]
]]]]))
; Fin Risk Register Summary---------------------------------------------------------------------------------------------------------------------
| true | (ns orbis-grcmanager.pages.riskprofile
(:require [reagent.core :as r]
[re-frame.core :refer [subscribe]]
[orbis-grcmanager.pages.issues :refer [markdown-preview]]
[orbis-grcmanager.subscriptions :as subs]
[orbis-grcmanager.key-events :refer [on-enter]]
[orbis-grcmanager.bootstrap :as bs]
[orbis-grcmanager.routes :refer [href navigate!]]
[reagent-data-table.core :as rdt]
[orbis-grcmanager.validation :as v]
[re-frame-datatable.core :as dt]
[re-frame-datatable.views :as views]
[orbis-grcmanager.pages.common :refer [validation-modal confirm-modal]]
[re-com.core
:refer [box v-box h-split v-split title flex-child-style input-text input-textarea]]))
; Funciones / Componentes General:
(defn nuevo-rr []
[:a.btn.btn-sm.btn-success.pull-right
(href "/create-rr") "Nuevo"])
(defn editar-registro []
[:a.btn.btn-sm.btn-success.pull-right
(href "/edit-rr") "Editar"])
(defn eliminar-rr-group []
[:a.btn.btn-sm.btn-danger.pull-right
(href "/delete-group") "Eliminar"])
; Fin Funciones / Componentes General------------------------------------------------------------------------------------------------------------------
; ---------------------------------------------------------------------------------------------------------------------
; Risk Profile Sumary
; Funciones:
(defn buscar-risk-register []
(r/with-let [search (r/atom nil)
buscar #(when-let [value (not-empty @search)]
(navigate! (str "/riskprofile" value)))]
[bs/FormGroup
[bs/InputGroup
[bs/FormControl
{:type "text"
:class "input-sm"
:placeholder "Introduzca el valor de busqueda"
:on-change #(reset! search (-> % .-target .-value))
:on-key-down #(on-enter % buscar)}]
[bs/InputGroup.Button
[:button.btn.btn-sm.btn-default
{:on-click buscar}
"Buscar"]]]]))
; Grid
; Define la función de renderización de la tabla re-frame. Se incluyen:
;;:NombreDeLaTabla
;[:mi-subscripción-re-frame]
;[{::dt/column-key [:columna-1-llave-reframe]
; ::dt/sorting {::dt/enabled? false}
; ::dt/column-label "Riesgo"}
(defn tabla-reframe []
[dt/datatable
:RegistrodeRiesgos
[:risk-registers]
[{::dt/column-key [:id-risk-register]
::dt/sorting {::dt/enabled? false}
::dt/column-label "ID"}
{::dt/column-key [:id-risk]
::dt/sorting {::dt/enabled? false}
::dt/column-label "Riesgo"}
{::dt/column-key [:id-risk-subtype]
::dt/column-label "Tipo"}
{::dt/column-key [:description-risk-register]
::dt/column-label "Descripción"
::dt/sorting {::dt/enabled? false}
::dt/render-fn formato-columna-href}
{::dt/column-key [:likelihood-risk-register]
::dt/column-label "Probabilidad"
::dt/sorting {::dt/enabled? true}}
{::dt/column-key [:impact-risk-register]
::dt/column-label "Impacto"
::dt/sorting {::dt/enabled? true}}
{::dt/column-key [:inherent-risk-register]
::dt/column-label "Inherente"
::dt/sorting {::dt/enabled? true}
::dt/render-fn semaforo-formatter-inherent
}
{::dt/column-key [:current-risk-register]
::dt/column-label "Corriente"
::dt/sorting {::dt/enabled? true}
::dt/render-fn semaforo-formatter-current
}
{::dt/column-key [:residual-risk-register]
::dt/column-label "Residual"
::dt/sorting {::dt/enabled? true}
::dt/render-fn semaforo-formatter-residual
}
{::dt/column-key [:status-risk-register]
::dt/column-label "Status"
::dt/sorting {::dt/enabled? true}}
]
{::dt/pagination {::dt/enabled? true
::dt/per-page 10}
::dt/table-classes ["table-striped" "table-bordered" "table-hover" "table"],
::dt/selection {::dt/enabled? true}}]
)
; Se hace la referencia al ns views de la librería, para funciones de visualización paginación y selección de página.
;Risk Register:
(defn control-paginacion []
[views/default-pagination-controls :RegistrodeRiesgos [:risk-registers]]
)
(defn selector-por-pagina []
[views/per-page-selector :RegistrodeRiesgos [:risk-registers]]
)
(defn formato-columna-href [description risk-register]
[:a {:href (str "/riskregister/" (get-in risk-register [:id-risk-register]))}
description]
)
(defn selected-rows-preview []
[:pre
[:code
@(subscribe [::dt/selected-items
:RegistrodeRiesgos
[:risk-registers]])]])
(defn semaforo-formatter-residual [_ risk-registers]
[:div.row>div.col-sm-12
[bs/Label
(semaforo :residual-risk-register risk-registers) (texto-etiqueta :residual-risk-register risk-registers)]
])
(defn semaforo-formatter-inherent [_ risk-registers]
[:div.row>div.col-sm-12
[bs/Label
(semaforo :inherent-risk-register risk-registers) (texto-etiqueta :inherent-risk-register risk-registers)]
])
(defn semaforo-formatter-current [_ risk-registers]
[:div.row>div.col-sm-12
[bs/Label
(semaforo :current-risk-register risk-registers) (texto-etiqueta :current-risk-register risk-registers)]
])
(defn texto-etiqueta [clave risk-registers]
(if (not (= (get-in risk-registers [clave]) nil))
(str (get-in risk-registers [clave]))
"vacio"
))
(defn semaforo [clave risk-registers]
(if (not (= (get-in risk-registers [clave]) nil))
(cond
(and (> (get-in risk-registers [clave]) 3.99) (< (get-in risk-registers [clave]) 7.00))
{:bs-style "success"}
(and (> (get-in risk-registers [clave]) 6.99) (< (get-in risk-registers [clave]) 10.00))
{:bs-style "info"}
(and (> (get-in risk-registers [clave]) 9.99) (< (get-in risk-registers [clave]) 13.00))
{:bs-style "warning"}
(> (get-in risk-registers [clave]) 12.99)
{:bs-style "danger"}
:else {:bs-style "primary"}
)
{:bs-style "default"}))
(defn pintar-circulo [risk-registers]
[:div
(if (or (= (:impact-risk-register rg) nil) (= (:likelihood-risk-register rg) nil))
(for [rg risk-registers]
[:h1 [:svg.heat-map
;[:g
[:g [:title "Prueba"][componente (:impact-risk-register rg) (:likelihood-risk-register rg) "white"]]
;[componente-texto (:impact-risk-register rg) (:likelihood-risk-register rg) (str (:id-risk-register rg))]
;]
]]
)
[componente 10000 10000 "yellow"])
])
(defn pintar-id [risk-registers]
[:div
(if (or (= (:impact-risk-register rg) nil) (= (:likelihood-risk-register rg) nil))
(for [rg risk-registers]
[:h1 [:svg.heat-map
[componente-texto (:impact-risk-register rg) (:likelihood-risk-register rg) (str (:id-risk-register rg))]
]
]
)
[componente 10000 10000 "yellow"])
])
(defn componente [x y color] [:circle {:fill color :stroke "black" :r 20 :cx (* x 100) :cy (- 500 (* y 100))}])
(defn componente-texto [x y texto] [:text {:fill "black" :x (* x 100) :y (- 500 (* y 100)) :text-anchor "middle" :stroke "black" :stroke-width "1px" :dy ".3em"} texto])
;[:svg.heat-map [:circle {:fill "blue" :stroke "black" :r 20 :cx 100 :cy 100}][:text {:fill "black" :x 100 :y 100 :text-anchor "middle" :stroke "black" :stroke-width "1px" :dy ".3em"} "10"]]
; Páginas:
(defn heat-map []
[:table.table.table-bordered.heat-mapT
[:thead
[:tr
[:th.cellYellow]
[:th.cellOrange]
[:th.cellRed]
[:th.cellRed]
[:th.cellRed]
]
]
[:thead
[:tr
[:th.cellLGreen]
[:th.cellYellow]
[:th.cellOrange]
[:th.cellRed]
[:th.cellRed]
]
]
[:thead
[:tr
[:th.cellGreen]
[:th.cellLGreen]
[:th.cellYellow]
[:th.cellOrange]
[:th.cellRed]
]
]
[:thead
[:tr
[:th.cellGreen]
[:th.cellLGreen]
[:th.cellLGreen]
[:th.cellYellow]
[:th.cellOrange]
]
]
[:thead
[:tr
[:th.cellGreen]
[:th.cellGreen]
[:th.cellGreen]
[:th.cellLGreen]
[:th.cellYellow]
]
]]
)
;(defn svg []
; ;[:svg.heat-map
; [pintar-circulo atomo-risk-profile-local]
; ;[:circle {:fill "Green" :stroke "black" :r 5 :cx 10 :cy 400}]
; ;(pintar-circulo [])
; ;[pintar-circulo atomo-risk-profile-local]
; ;]
; )
(defn svg-texto []
[:svg.heat-mapSVG
[:text {:fill "black" :x -250 :y 30 :transform "rotate(-90 20,20)"} "Probabilidad 0 - 5"]
[:text {:fill "black" :x 250 :y 525} "Impacto 0 - 5"]
]
)
(defn subscription-rows-preview []
[:pre
[:code
(db [:risk-registers])]])
(defn risk-profile-sumary-page []
(r/with-let [atomo-risk-profile-local @(subscribe [:risk-registers])]
[:div.container
[:div.row
[:div.col-sm-6
;[svg-texto] [heat-map][pintar-circulo atomo-risk-profile-local] [pintar-id atomo-risk-profile-local] [svg-texto-horizontal]
[heat-map][pintar-circulo atomo-risk-profile-local] [pintar-id atomo-risk-profile-local] [svg-texto]
]
[:div.col-sm-6
[heat-map][pintar-circulo @(subscribe [::dt/selected-items
:RegistrodeRiesgos
[:risk-registers]]) ] [pintar-id @(subscribe [::dt/selected-items
:RegistrodeRiesgos
[:risk-registers]])] [svg-texto] ]]
[:div.espacio
[:div.row
[:div.col-sm-12
[:h2 "Risk Profile"]
; Para pruebas
;[pintar-circulo atomo-risk-profile-local]
;[:h2 (str (pintar-circulo @(subscribe [::dt/selected-items
; :RegistrodeRiesgos
; [:risk-registers]]) ))]
[buscar-risk-register]]
[:div.col-sm-12 [:div.panel.panel-default [tabla-reframe] [control-paginacion] [selector-por-pagina]
;pruebas:
;[:svg.heat-map [:g [:title "Prueba"]
; [:circle {:fill "green" :stroke "black" :r 20 :cx 120 :cy 120}][:text {:fill "black" :x 120 :y 120 :text-anchor "middle" :stroke "black" :stroke-width "1px" :dy ".3em"} "10"]
; ]
; [:g [:title "PI:NAME:<NAME>END_PI"]
; [:circle {:fill "blue" :stroke "black" :r 20 :cx 100 :cy 100}][:text {:fill "black" :x 100 :y 100 :text-anchor "middle" :stroke "black" :stroke-width "1px" :dy ".3em"} "10"]
; ]
; ]
; Fin pruebas
]
]]]]))
; Fin Risk Register Summary---------------------------------------------------------------------------------------------------------------------
|
[
{
"context": "h-application-client-id\"\n :client-secret \"github-oauth-application-client-secret\"})\n\n\n;;\n;; multime",
"end": 629,
"score": 0.5432994961738586,
"start": 629,
"tag": "KEY",
"value": ""
},
{
"context": "ication-client-id\"\n :client-secret \"github-oauth-application-client-secret\"})\n\n\n;;\n;; multimethods ",
"end": 635,
"score": 0.5278010964393616,
"start": 635,
"tag": "KEY",
"value": ""
},
{
"context": "nt-id\"\n :client-secret \"github-oauth-application-client-secret\"})\n\n\n;;\n;; multimethods for validati",
"end": 647,
"score": 0.5124680399894714,
"start": 647,
"tag": "KEY",
"value": ""
},
{
"context": " :client-secret \"github-oauth-application-client-secret\"})\n\n\n;;\n;; multimethods for validation\n;;\n\n",
"end": 654,
"score": 0.5959228277206421,
"start": 654,
"tag": "KEY",
"value": ""
}
] | code/src/sixsq/nuvla/server/resources/configuration_template_session_github.clj | nuvla/server | 6 | (ns sixsq.nuvla.server.resources.configuration-template-session-github
(:require
[sixsq.nuvla.server.resources.common.utils :as u]
[sixsq.nuvla.server.resources.configuration-template :as p]
[sixsq.nuvla.server.resources.spec.configuration-template-session-github :as cts-github]))
(def ^:const service "session-github")
;;
;; resource
;;
(def ^:const resource
{:service service
:name "GitHub Authentication Configuration"
:description "GitHub Authentication Configuration"
:instance "authn-name"
:client-id "github-oauth-application-client-id"
:client-secret "github-oauth-application-client-secret"})
;;
;; multimethods for validation
;;
(def validate-fn (u/create-spec-validation-fn ::cts-github/schema))
(defmethod p/validate-subtype service
[resource]
(validate-fn resource))
;;
;; initialization: register this Configuration template
;;
(defn initialize
[]
(p/register resource))
| 90910 | (ns sixsq.nuvla.server.resources.configuration-template-session-github
(:require
[sixsq.nuvla.server.resources.common.utils :as u]
[sixsq.nuvla.server.resources.configuration-template :as p]
[sixsq.nuvla.server.resources.spec.configuration-template-session-github :as cts-github]))
(def ^:const service "session-github")
;;
;; resource
;;
(def ^:const resource
{:service service
:name "GitHub Authentication Configuration"
:description "GitHub Authentication Configuration"
:instance "authn-name"
:client-id "github-oauth-application-client-id"
:client-secret "github<KEY>-oauth<KEY>-application<KEY>-client<KEY>-secret"})
;;
;; multimethods for validation
;;
(def validate-fn (u/create-spec-validation-fn ::cts-github/schema))
(defmethod p/validate-subtype service
[resource]
(validate-fn resource))
;;
;; initialization: register this Configuration template
;;
(defn initialize
[]
(p/register resource))
| true | (ns sixsq.nuvla.server.resources.configuration-template-session-github
(:require
[sixsq.nuvla.server.resources.common.utils :as u]
[sixsq.nuvla.server.resources.configuration-template :as p]
[sixsq.nuvla.server.resources.spec.configuration-template-session-github :as cts-github]))
(def ^:const service "session-github")
;;
;; resource
;;
(def ^:const resource
{:service service
:name "GitHub Authentication Configuration"
:description "GitHub Authentication Configuration"
:instance "authn-name"
:client-id "github-oauth-application-client-id"
:client-secret "githubPI:KEY:<KEY>END_PI-oauthPI:KEY:<KEY>END_PI-applicationPI:KEY:<KEY>END_PI-clientPI:KEY:<KEY>END_PI-secret"})
;;
;; multimethods for validation
;;
(def validate-fn (u/create-spec-validation-fn ::cts-github/schema))
(defmethod p/validate-subtype service
[resource]
(validate-fn resource))
;;
;; initialization: register this Configuration template
;;
(defn initialize
[]
(p/register resource))
|
[
{
"context": "e program was last run.\n;;\n(def conduit-user-key \"conduit-user\") ;; localstore key\n\n(defn set-user-ls\n \"Puts u",
"end": 738,
"score": 0.8384312391281128,
"start": 726,
"tag": "KEY",
"value": "conduit-user"
}
] | src/conduit/db.cljs | zelark/conduit | 0 | (ns conduit.db
(:require [cljs.reader]
[re-frame.core :refer [reg-cofx]]))
;; -- Default app-db Value ---------------------------------------------------
;;
;; When the application first starts, this will be the value put in app-db
;; Look in:
;; 1. `core.cljs` for "(dispatch-sync [:initialise-db])"
;; 2. `events.cljs` for the registration of :initialise-db handler
;;
(def default-db {:active-page :home}) ;; what gets put into app-db by default.
;; -- Local Storage ----------------------------------------------------------
;;
;; Part of the conduit challenge is to store a user in localStorage, and
;; on app startup, reload the user from when the program was last run.
;;
(def conduit-user-key "conduit-user") ;; localstore key
(defn set-user-ls
"Puts user into localStorage"
[user]
(.setItem js/localStorage conduit-user-key (str user))) ;; sorted-map written as an EDN map
;; Removes user information from localStorge when a user logs out.
;;
(defn remove-user-ls
"Removes user from localStorage"
[]
(.removeItem js/localStorage conduit-user-key))
;; -- cofx Registrations -----------------------------------------------------
;;
;; Use `reg-cofx` to register a "coeffect handler" which will inject the user
;; stored in localStorge.
;;
;; To see it used, look in `events.cljs` at the event handler for `:initialise-db`.
;; That event handler has the interceptor `(inject-cofx :local-store-user)`
;; The function registered below will be used to fulfill that request.
;;
;; We must supply a `sorted-map` but in localStorage it is stored as a `map`.
;;
(reg-cofx
:local-store-user
(fn [cofx _]
(assoc cofx :local-store-user ;; put the local-store user into the coeffect under :local-store-user
(into (sorted-map) ;; read in user from localstore, and process into a sorted map
(some->> (.getItem js/localStorage conduit-user-key)
(cljs.reader/read-string)))))) ;; EDN map -> map
| 113198 | (ns conduit.db
(:require [cljs.reader]
[re-frame.core :refer [reg-cofx]]))
;; -- Default app-db Value ---------------------------------------------------
;;
;; When the application first starts, this will be the value put in app-db
;; Look in:
;; 1. `core.cljs` for "(dispatch-sync [:initialise-db])"
;; 2. `events.cljs` for the registration of :initialise-db handler
;;
(def default-db {:active-page :home}) ;; what gets put into app-db by default.
;; -- Local Storage ----------------------------------------------------------
;;
;; Part of the conduit challenge is to store a user in localStorage, and
;; on app startup, reload the user from when the program was last run.
;;
(def conduit-user-key "<KEY>") ;; localstore key
(defn set-user-ls
"Puts user into localStorage"
[user]
(.setItem js/localStorage conduit-user-key (str user))) ;; sorted-map written as an EDN map
;; Removes user information from localStorge when a user logs out.
;;
(defn remove-user-ls
"Removes user from localStorage"
[]
(.removeItem js/localStorage conduit-user-key))
;; -- cofx Registrations -----------------------------------------------------
;;
;; Use `reg-cofx` to register a "coeffect handler" which will inject the user
;; stored in localStorge.
;;
;; To see it used, look in `events.cljs` at the event handler for `:initialise-db`.
;; That event handler has the interceptor `(inject-cofx :local-store-user)`
;; The function registered below will be used to fulfill that request.
;;
;; We must supply a `sorted-map` but in localStorage it is stored as a `map`.
;;
(reg-cofx
:local-store-user
(fn [cofx _]
(assoc cofx :local-store-user ;; put the local-store user into the coeffect under :local-store-user
(into (sorted-map) ;; read in user from localstore, and process into a sorted map
(some->> (.getItem js/localStorage conduit-user-key)
(cljs.reader/read-string)))))) ;; EDN map -> map
| true | (ns conduit.db
(:require [cljs.reader]
[re-frame.core :refer [reg-cofx]]))
;; -- Default app-db Value ---------------------------------------------------
;;
;; When the application first starts, this will be the value put in app-db
;; Look in:
;; 1. `core.cljs` for "(dispatch-sync [:initialise-db])"
;; 2. `events.cljs` for the registration of :initialise-db handler
;;
(def default-db {:active-page :home}) ;; what gets put into app-db by default.
;; -- Local Storage ----------------------------------------------------------
;;
;; Part of the conduit challenge is to store a user in localStorage, and
;; on app startup, reload the user from when the program was last run.
;;
(def conduit-user-key "PI:KEY:<KEY>END_PI") ;; localstore key
(defn set-user-ls
"Puts user into localStorage"
[user]
(.setItem js/localStorage conduit-user-key (str user))) ;; sorted-map written as an EDN map
;; Removes user information from localStorge when a user logs out.
;;
(defn remove-user-ls
"Removes user from localStorage"
[]
(.removeItem js/localStorage conduit-user-key))
;; -- cofx Registrations -----------------------------------------------------
;;
;; Use `reg-cofx` to register a "coeffect handler" which will inject the user
;; stored in localStorge.
;;
;; To see it used, look in `events.cljs` at the event handler for `:initialise-db`.
;; That event handler has the interceptor `(inject-cofx :local-store-user)`
;; The function registered below will be used to fulfill that request.
;;
;; We must supply a `sorted-map` but in localStorage it is stored as a `map`.
;;
(reg-cofx
:local-store-user
(fn [cofx _]
(assoc cofx :local-store-user ;; put the local-store user into the coeffect under :local-store-user
(into (sorted-map) ;; read in user from localstore, and process into a sorted map
(some->> (.getItem js/localStorage conduit-user-key)
(cljs.reader/read-string)))))) ;; EDN map -> map
|
[
{
"context": " \"Basic landcycling\"})\n\n(def token-name\n #{\"Beast\"\n \"Demon\"\n \"Elephant\"\n \"Element",
"end": 1702,
"score": 0.7949883937835693,
"start": 1699,
"tag": "NAME",
"value": "ast"
},
{
"context": "ycling\"})\n\n(def token-name\n #{\"Beast\"\n \"Demon\"\n \"Elephant\"\n \"Elemental\"\n \"Ele",
"end": 1717,
"score": 0.9013525247573853,
"start": 1712,
"tag": "NAME",
"value": "Demon"
},
{
"context": " token-name\n #{\"Beast\"\n \"Demon\"\n \"Elephant\"\n \"Elemental\"\n \"Elemental Shaman\"\n ",
"end": 1735,
"score": 0.8519055843353271,
"start": 1727,
"tag": "NAME",
"value": "Elephant"
},
{
"context": " \"Elemental\"\n \"Elemental Shaman\"\n \"Elf Warrior\"\n \"Goblin\"\n \"Hornet\"\n \"Minion\"\n",
"end": 1801,
"score": 0.763074517250061,
"start": 1791,
"tag": "NAME",
"value": "lf Warrior"
},
{
"context": " \"Elemental Shaman\"\n \"Elf Warrior\"\n \"Goblin\"\n \"Hornet\"\n \"Minion\"\n \"Saprolin",
"end": 1817,
"score": 0.9233846664428711,
"start": 1811,
"tag": "NAME",
"value": "Goblin"
},
{
"context": "man\"\n \"Elf Warrior\"\n \"Goblin\"\n \"Hornet\"\n \"Minion\"\n \"Saproling\"\n \"Spiri",
"end": 1833,
"score": 0.7463551163673401,
"start": 1827,
"tag": "NAME",
"value": "Hornet"
}
] | src/loa/util/magic.clj | karmag/loa | 4 | (ns loa.util.magic)
;;--------------------------------------------------
;; data
(def super-type #{"Basic" "Legendary" "Ongoing" "Snow" "World"})
(def card-type #{"Artifact" "Creature" "Conspiracy" "Enchantment" "Instant"
"Land" "Plane" "Planeswalker" "Scheme" "Sorcery" "Tribal"
"Vanguard" "Phenomenon"})
(def keyword-ability
#{ ;; general
"Absorb" "Affinity" "Amplify"
"Annihilator" "Aura Swap" "Banding"
"Battle Cry" "Bloodthirst" "Bushido"
"Buyback" "Cascade" "Champion"
"Changeling" "Conspire" "Convoke"
"Cumulative Upkeep" "Cycling" "Deathtouch"
"Defender" "Delve" "Devour"
"Double Strike" "Dredge" "Echo"
"Enchant" "Entwine" "Epic"
"Equip" "Evoke" "Exalted"
"Fading" "Fear" "First Strike"
"Flanking" "Flash" "Flashback"
"Flying" "Forecast" "Fortify"
"Frenzy" "Graft" "Gravestorm"
"Haste" "Haunt" "Hexproof"
"Hideaway" "Horsemanship" "Infect"
"Intimidate" "Kicker" "Level Up"
"Lifelink" "Living Weapon"
"Madness" "Modular" "Morph"
"Ninjutsu" "Offering" "Persist"
"Phasing" "Poisonous" "Protection"
"Provoke" "Prowl" "Rampage"
"Reach" "Rebound" "Recover"
"Reinforce" "Replicate" "Retrace"
"Ripple" "Shadow" "Shroud"
"Soulshift" "Splice" "Split Second"
"Storm" "Sunburst" "Suspend"
"Totem Armor" "Trample" "Transfigure"
"Transmute" "Unearth" "Vanishing"
"Vigilance" "Wither"
;; landwalk
"Plainswalk" "Islandwalk" "Swampwalk"
"Mountainwalk" "Forestwalk"
;; Cycling alternatives
"Plainscycling" "Islandcycling" "Swampcycling"
"Mountaincycling" "Forestcycling"
"Basic landcycling"})
(def token-name
#{"Beast"
"Demon"
"Elephant"
"Elemental"
"Elemental Shaman"
"Elf Warrior"
"Goblin"
"Hornet"
"Minion"
"Saproling"
"Spirit"
"Thrull"
"Goblin token card"
"Pegasus token card"
"Sheep token card"
"Soldier token card"
"Squirrel token card"
"Zombie token card"})
;;--------------------------------------------------
;; functions
(defn find-type
"Returns the type of a single type from the typeline of a card."
[type]
(cond (super-type type) "super"
(card-type type) "card"
:else "sub"))
| 69230 | (ns loa.util.magic)
;;--------------------------------------------------
;; data
(def super-type #{"Basic" "Legendary" "Ongoing" "Snow" "World"})
(def card-type #{"Artifact" "Creature" "Conspiracy" "Enchantment" "Instant"
"Land" "Plane" "Planeswalker" "Scheme" "Sorcery" "Tribal"
"Vanguard" "Phenomenon"})
(def keyword-ability
#{ ;; general
"Absorb" "Affinity" "Amplify"
"Annihilator" "Aura Swap" "Banding"
"Battle Cry" "Bloodthirst" "Bushido"
"Buyback" "Cascade" "Champion"
"Changeling" "Conspire" "Convoke"
"Cumulative Upkeep" "Cycling" "Deathtouch"
"Defender" "Delve" "Devour"
"Double Strike" "Dredge" "Echo"
"Enchant" "Entwine" "Epic"
"Equip" "Evoke" "Exalted"
"Fading" "Fear" "First Strike"
"Flanking" "Flash" "Flashback"
"Flying" "Forecast" "Fortify"
"Frenzy" "Graft" "Gravestorm"
"Haste" "Haunt" "Hexproof"
"Hideaway" "Horsemanship" "Infect"
"Intimidate" "Kicker" "Level Up"
"Lifelink" "Living Weapon"
"Madness" "Modular" "Morph"
"Ninjutsu" "Offering" "Persist"
"Phasing" "Poisonous" "Protection"
"Provoke" "Prowl" "Rampage"
"Reach" "Rebound" "Recover"
"Reinforce" "Replicate" "Retrace"
"Ripple" "Shadow" "Shroud"
"Soulshift" "Splice" "Split Second"
"Storm" "Sunburst" "Suspend"
"Totem Armor" "Trample" "Transfigure"
"Transmute" "Unearth" "Vanishing"
"Vigilance" "Wither"
;; landwalk
"Plainswalk" "Islandwalk" "Swampwalk"
"Mountainwalk" "Forestwalk"
;; Cycling alternatives
"Plainscycling" "Islandcycling" "Swampcycling"
"Mountaincycling" "Forestcycling"
"Basic landcycling"})
(def token-name
#{"Be<NAME>"
"<NAME>"
"<NAME>"
"Elemental"
"Elemental Shaman"
"E<NAME>"
"<NAME>"
"<NAME>"
"Minion"
"Saproling"
"Spirit"
"Thrull"
"Goblin token card"
"Pegasus token card"
"Sheep token card"
"Soldier token card"
"Squirrel token card"
"Zombie token card"})
;;--------------------------------------------------
;; functions
(defn find-type
"Returns the type of a single type from the typeline of a card."
[type]
(cond (super-type type) "super"
(card-type type) "card"
:else "sub"))
| true | (ns loa.util.magic)
;;--------------------------------------------------
;; data
(def super-type #{"Basic" "Legendary" "Ongoing" "Snow" "World"})
(def card-type #{"Artifact" "Creature" "Conspiracy" "Enchantment" "Instant"
"Land" "Plane" "Planeswalker" "Scheme" "Sorcery" "Tribal"
"Vanguard" "Phenomenon"})
(def keyword-ability
#{ ;; general
"Absorb" "Affinity" "Amplify"
"Annihilator" "Aura Swap" "Banding"
"Battle Cry" "Bloodthirst" "Bushido"
"Buyback" "Cascade" "Champion"
"Changeling" "Conspire" "Convoke"
"Cumulative Upkeep" "Cycling" "Deathtouch"
"Defender" "Delve" "Devour"
"Double Strike" "Dredge" "Echo"
"Enchant" "Entwine" "Epic"
"Equip" "Evoke" "Exalted"
"Fading" "Fear" "First Strike"
"Flanking" "Flash" "Flashback"
"Flying" "Forecast" "Fortify"
"Frenzy" "Graft" "Gravestorm"
"Haste" "Haunt" "Hexproof"
"Hideaway" "Horsemanship" "Infect"
"Intimidate" "Kicker" "Level Up"
"Lifelink" "Living Weapon"
"Madness" "Modular" "Morph"
"Ninjutsu" "Offering" "Persist"
"Phasing" "Poisonous" "Protection"
"Provoke" "Prowl" "Rampage"
"Reach" "Rebound" "Recover"
"Reinforce" "Replicate" "Retrace"
"Ripple" "Shadow" "Shroud"
"Soulshift" "Splice" "Split Second"
"Storm" "Sunburst" "Suspend"
"Totem Armor" "Trample" "Transfigure"
"Transmute" "Unearth" "Vanishing"
"Vigilance" "Wither"
;; landwalk
"Plainswalk" "Islandwalk" "Swampwalk"
"Mountainwalk" "Forestwalk"
;; Cycling alternatives
"Plainscycling" "Islandcycling" "Swampcycling"
"Mountaincycling" "Forestcycling"
"Basic landcycling"})
(def token-name
#{"BePI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"Elemental"
"Elemental Shaman"
"EPI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"Minion"
"Saproling"
"Spirit"
"Thrull"
"Goblin token card"
"Pegasus token card"
"Sheep token card"
"Soldier token card"
"Squirrel token card"
"Zombie token card"})
;;--------------------------------------------------
;; functions
(defn find-type
"Returns the type of a single type from the typeline of a card."
[type]
(cond (super-type type) "super"
(card-type type) "card"
:else "sub"))
|
[
{
"context": "; Copyright (c) 2013-2015 Tim Molderez.\n;\n; All rights reserved. This program and the ac",
"end": 38,
"score": 0.9998607039451599,
"start": 26,
"tag": "NAME",
"value": "Tim Molderez"
},
{
"context": "Clojure objects and data structures.\"\n {:author \"Tim Molderez\"}\n (:gen-class\n :name inspectorjay.InspectorJ",
"end": 438,
"score": 0.9998731017112732,
"start": 426,
"tag": "NAME",
"value": "Tim Molderez"
}
] | src/inspector_jay/core.clj | kawas44/inspector-jay | 69 | ; Copyright (c) 2013-2015 Tim Molderez.
;
; All rights reserved. This program and the accompanying materials
; are made available under the terms of the 3-Clause BSD License
; which accompanies this distribution, and is available at
; http://www.opensource.org/licenses/BSD-3-Clause
(ns inspector-jay.core
"Inspector Jay is a graphical inspector that lets you examine Java/Clojure objects and data structures."
{:author "Tim Molderez"}
(:gen-class
:name inspectorjay.InspectorJay
:prefix java-
:methods [#^{:static true} [inspect [Object] Object]])
(:require [inspector-jay.gui
[gui :as gui]
[utils :as utils]]))
(defn inspect
"Displays an inspector window for a given object.
The return value of inspect is the object itself, so you can plug in this function anywhere you like.
See gui/default-options for more information on all available keyword arguments."
^Object [^Object object & {:as args}]
(if (not= object nil)
(apply gui/inspector-window object (utils/map-to-keyword-args args)))
object)
(defn last-selected-value
"Retrieve the value of the tree node that was last selected.
See gui/last-selected-value for more information."
[]
(gui/last-selected-value))
(defn java-inspect
"Java wrapper for the inspect function.
When using Java, you can call this function as follows:
inspectorjay.InspectorJay.inspect(anObject);"
[object]
(inspect object))
(defn java-inspectorPanel
"Java wrapper for the inspector-panel function.
Rather than opening an inspector window, this method only returns the inspector's JPanel.
You can use it to embed Inspector Jay in your own applications."
[object]
(gui/inspector-panel object)) | 121421 | ; Copyright (c) 2013-2015 <NAME>.
;
; All rights reserved. This program and the accompanying materials
; are made available under the terms of the 3-Clause BSD License
; which accompanies this distribution, and is available at
; http://www.opensource.org/licenses/BSD-3-Clause
(ns inspector-jay.core
"Inspector Jay is a graphical inspector that lets you examine Java/Clojure objects and data structures."
{:author "<NAME>"}
(:gen-class
:name inspectorjay.InspectorJay
:prefix java-
:methods [#^{:static true} [inspect [Object] Object]])
(:require [inspector-jay.gui
[gui :as gui]
[utils :as utils]]))
(defn inspect
"Displays an inspector window for a given object.
The return value of inspect is the object itself, so you can plug in this function anywhere you like.
See gui/default-options for more information on all available keyword arguments."
^Object [^Object object & {:as args}]
(if (not= object nil)
(apply gui/inspector-window object (utils/map-to-keyword-args args)))
object)
(defn last-selected-value
"Retrieve the value of the tree node that was last selected.
See gui/last-selected-value for more information."
[]
(gui/last-selected-value))
(defn java-inspect
"Java wrapper for the inspect function.
When using Java, you can call this function as follows:
inspectorjay.InspectorJay.inspect(anObject);"
[object]
(inspect object))
(defn java-inspectorPanel
"Java wrapper for the inspector-panel function.
Rather than opening an inspector window, this method only returns the inspector's JPanel.
You can use it to embed Inspector Jay in your own applications."
[object]
(gui/inspector-panel object)) | true | ; Copyright (c) 2013-2015 PI:NAME:<NAME>END_PI.
;
; All rights reserved. This program and the accompanying materials
; are made available under the terms of the 3-Clause BSD License
; which accompanies this distribution, and is available at
; http://www.opensource.org/licenses/BSD-3-Clause
(ns inspector-jay.core
"Inspector Jay is a graphical inspector that lets you examine Java/Clojure objects and data structures."
{:author "PI:NAME:<NAME>END_PI"}
(:gen-class
:name inspectorjay.InspectorJay
:prefix java-
:methods [#^{:static true} [inspect [Object] Object]])
(:require [inspector-jay.gui
[gui :as gui]
[utils :as utils]]))
(defn inspect
"Displays an inspector window for a given object.
The return value of inspect is the object itself, so you can plug in this function anywhere you like.
See gui/default-options for more information on all available keyword arguments."
^Object [^Object object & {:as args}]
(if (not= object nil)
(apply gui/inspector-window object (utils/map-to-keyword-args args)))
object)
(defn last-selected-value
"Retrieve the value of the tree node that was last selected.
See gui/last-selected-value for more information."
[]
(gui/last-selected-value))
(defn java-inspect
"Java wrapper for the inspect function.
When using Java, you can call this function as follows:
inspectorjay.InspectorJay.inspect(anObject);"
[object]
(inspect object))
(defn java-inspectorPanel
"Java wrapper for the inspector-panel function.
Rather than opening an inspector window, this method only returns the inspector's JPanel.
You can use it to embed Inspector Jay in your own applications."
[object]
(gui/inspector-panel object)) |
[
{
"context": ";; author: Mark W. Naylor\n;; file: day01.clj\n;; date: 2021-Apr-09\n(ns adv",
"end": 25,
"score": 0.9998675584793091,
"start": 11,
"tag": "NAME",
"value": "Mark W. Naylor"
},
{
"context": "----\n;; BSD 3-Clause License\n\n;; Copyright © 2021, Mark W. Naylor\n;; All rights reserved.\n\n;; Redistribution and us",
"end": 2057,
"score": 0.9998787045478821,
"start": 2043,
"tag": "NAME",
"value": "Mark W. Naylor"
}
] | src/advent_2020/day01.clj | mark-naylor-1701/advent_2020 | 0 | ;; author: Mark W. Naylor
;; file: day01.clj
;; date: 2021-Apr-09
(ns advent-2020.day01)
(def input [1688 1463 1461 1842 1441 1838 1583 1891 1876 1551 1506
2005 1989 1417 1784 1975 1428 1485 1597 1871 105 788
1971 1892 1854 1466 1584 1565 1400 1640 1780 1774 360
1421 1368 1771 1666 1707 1627 1449 1677 1504 1721 1994
1959 1862 1768 1986 1904 1382 1969 1852 1917 1966 1742
1371 1405 1995 1906 1694 1735 1422 1719 1978 1641 1761
1567 1974 1495 1973 1958 1599 1770 1600 1465 1865 1479
1687 1390 1802 2008 645 1435 1589 1949 1909 1526 1667
1831 1864 1713 1718 1232 1868 1884 1825 1999 1590 1759
1391 1757 323 1612 1637 1727 1783 1643 1442 1452 675
1812 1604 1518 1894 1933 1801 1914 912 1576 1961 1970
1446 1985 1988 1563 1826 1409 1503 1539 1832 1698 1990
1689 1532 765 1546 1384 1519 1615 1556 1754 1983 1394
1763 1823 1788 1407 1946 1751 1837 1680 1929 1814 1948
1919 1953 55 1731 1516 1895 1795 1890 1881 1799 1536
1396 1942 1798 1767 1745 1883 2004 1550 1916 1650 1749
1991 1789 1740 1490 1873 1003 1699 1669 1781 2000 1728
1877 1733 1588 1168 1828 1848 1963 1928 1920 1493 1968
1564 1572])
(def sum (partial reduce +))
(defn is2020? [coll]
(= 2020 (sum coll)))
(defn pairs
"From given input sequence, create a set of pairs."
[items]
(for [i items j items] [i j]))
(defn triples
"From given input sequence, create a set of triples."
[items]
(for [i items j items k items] [i j k]))
(defn solve
[group-fn items]
(->> (group-fn items)
(map sort)
(into #{})
(filter is2020?)
first
(reduce *)))
(def solve-pairs (partial solve pairs))
(def solve-triples (partial solve triples))
;; Pairs solution: 970816
;; Triples solution: 96047280
;; ------------------------------------------------------------------------------
;; BSD 3-Clause License
;; Copyright © 2021, Mark W. Naylor
;; All rights reserved.
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;; 1. Redistributions of source code must retain the above copyright notice, this
;; list of conditions and the following disclaimer.
;; 2. Redistributions in binary form must reproduce the above copyright notice,
;; this list of conditions and the following disclaimer in the documentation
;; and/or other materials provided with the distribution.
;; 3. Neither the name of the copyright holder nor the names of its
;; contributors may be used to endorse or promote products derived from
;; this software without specific prior written permission.
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| 18714 | ;; author: <NAME>
;; file: day01.clj
;; date: 2021-Apr-09
(ns advent-2020.day01)
(def input [1688 1463 1461 1842 1441 1838 1583 1891 1876 1551 1506
2005 1989 1417 1784 1975 1428 1485 1597 1871 105 788
1971 1892 1854 1466 1584 1565 1400 1640 1780 1774 360
1421 1368 1771 1666 1707 1627 1449 1677 1504 1721 1994
1959 1862 1768 1986 1904 1382 1969 1852 1917 1966 1742
1371 1405 1995 1906 1694 1735 1422 1719 1978 1641 1761
1567 1974 1495 1973 1958 1599 1770 1600 1465 1865 1479
1687 1390 1802 2008 645 1435 1589 1949 1909 1526 1667
1831 1864 1713 1718 1232 1868 1884 1825 1999 1590 1759
1391 1757 323 1612 1637 1727 1783 1643 1442 1452 675
1812 1604 1518 1894 1933 1801 1914 912 1576 1961 1970
1446 1985 1988 1563 1826 1409 1503 1539 1832 1698 1990
1689 1532 765 1546 1384 1519 1615 1556 1754 1983 1394
1763 1823 1788 1407 1946 1751 1837 1680 1929 1814 1948
1919 1953 55 1731 1516 1895 1795 1890 1881 1799 1536
1396 1942 1798 1767 1745 1883 2004 1550 1916 1650 1749
1991 1789 1740 1490 1873 1003 1699 1669 1781 2000 1728
1877 1733 1588 1168 1828 1848 1963 1928 1920 1493 1968
1564 1572])
(def sum (partial reduce +))
(defn is2020? [coll]
(= 2020 (sum coll)))
(defn pairs
"From given input sequence, create a set of pairs."
[items]
(for [i items j items] [i j]))
(defn triples
"From given input sequence, create a set of triples."
[items]
(for [i items j items k items] [i j k]))
(defn solve
[group-fn items]
(->> (group-fn items)
(map sort)
(into #{})
(filter is2020?)
first
(reduce *)))
(def solve-pairs (partial solve pairs))
(def solve-triples (partial solve triples))
;; Pairs solution: 970816
;; Triples solution: 96047280
;; ------------------------------------------------------------------------------
;; BSD 3-Clause License
;; Copyright © 2021, <NAME>
;; All rights reserved.
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;; 1. Redistributions of source code must retain the above copyright notice, this
;; list of conditions and the following disclaimer.
;; 2. Redistributions in binary form must reproduce the above copyright notice,
;; this list of conditions and the following disclaimer in the documentation
;; and/or other materials provided with the distribution.
;; 3. Neither the name of the copyright holder nor the names of its
;; contributors may be used to endorse or promote products derived from
;; this software without specific prior written permission.
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
| true | ;; author: PI:NAME:<NAME>END_PI
;; file: day01.clj
;; date: 2021-Apr-09
(ns advent-2020.day01)
(def input [1688 1463 1461 1842 1441 1838 1583 1891 1876 1551 1506
2005 1989 1417 1784 1975 1428 1485 1597 1871 105 788
1971 1892 1854 1466 1584 1565 1400 1640 1780 1774 360
1421 1368 1771 1666 1707 1627 1449 1677 1504 1721 1994
1959 1862 1768 1986 1904 1382 1969 1852 1917 1966 1742
1371 1405 1995 1906 1694 1735 1422 1719 1978 1641 1761
1567 1974 1495 1973 1958 1599 1770 1600 1465 1865 1479
1687 1390 1802 2008 645 1435 1589 1949 1909 1526 1667
1831 1864 1713 1718 1232 1868 1884 1825 1999 1590 1759
1391 1757 323 1612 1637 1727 1783 1643 1442 1452 675
1812 1604 1518 1894 1933 1801 1914 912 1576 1961 1970
1446 1985 1988 1563 1826 1409 1503 1539 1832 1698 1990
1689 1532 765 1546 1384 1519 1615 1556 1754 1983 1394
1763 1823 1788 1407 1946 1751 1837 1680 1929 1814 1948
1919 1953 55 1731 1516 1895 1795 1890 1881 1799 1536
1396 1942 1798 1767 1745 1883 2004 1550 1916 1650 1749
1991 1789 1740 1490 1873 1003 1699 1669 1781 2000 1728
1877 1733 1588 1168 1828 1848 1963 1928 1920 1493 1968
1564 1572])
(def sum (partial reduce +))
(defn is2020? [coll]
(= 2020 (sum coll)))
(defn pairs
"From given input sequence, create a set of pairs."
[items]
(for [i items j items] [i j]))
(defn triples
"From given input sequence, create a set of triples."
[items]
(for [i items j items k items] [i j k]))
(defn solve
[group-fn items]
(->> (group-fn items)
(map sort)
(into #{})
(filter is2020?)
first
(reduce *)))
(def solve-pairs (partial solve pairs))
(def solve-triples (partial solve triples))
;; Pairs solution: 970816
;; Triples solution: 96047280
;; ------------------------------------------------------------------------------
;; BSD 3-Clause License
;; Copyright © 2021, PI:NAME:<NAME>END_PI
;; All rights reserved.
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;; 1. Redistributions of source code must retain the above copyright notice, this
;; list of conditions and the following disclaimer.
;; 2. Redistributions in binary form must reproduce the above copyright notice,
;; this list of conditions and the following disclaimer in the documentation
;; and/or other materials provided with the distribution.
;; 3. Neither the name of the copyright holder nor the names of its
;; contributors may be used to endorse or promote products derived from
;; this software without specific prior written permission.
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
[
{
"context": "n/preprocessing routings\n;;;;\n;;;; @copyright 2019 Dennis Drown et l'Université du Québec à Montréal\n;;;; -------",
"end": 394,
"score": 0.9998794794082642,
"start": 382,
"tag": "NAME",
"value": "Dennis Drown"
}
] | apps/say_sila/priv/fnode/say/src/say/data.clj | dendrown/say_sila | 0 | ;;;; -------------------------------------------------------------------------
;;;;
;;;; _/_/_/ _/_/_/ _/ _/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/ _/ _/ _/_/_/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/
;;;;
;;;; Data collection/preprocessing routings
;;;;
;;;; @copyright 2019 Dennis Drown et l'Université du Québec à Montréal
;;;; -------------------------------------------------------------------------
(ns say.data
(:require [say.genie :refer :all]
[say.log :as log]
[clojure.data.csv :as csv]
[clojure.java.io :as io]
[clojure.string :as str]
[net.cgrand.enlive-html :as web])
(:import [java.net URL]))
;;; --------------------------------------------------------------------------
(set! *warn-on-reflection* true)
;;; Female/male names in English from the web
;;; TODO: Compare with the methodology from \cite{thelwall2018}, which uses
;;; names from the 1990 U.S. census @ 90% male and 90% female
(def ^:const NAMES {:female {:url "http://www.20000-names.com/female_english_names" :cnt 20}
:male {:url "http://www.20000-names.com/male_english_names" :cnt 17}
:edn "resources/gender/names.edn"})
;;; Gender word-usage model: \cite{sap2014}
(def ^:const EMNLP14 {:csv "resources/gender/emnlp14gender.csv"
:edn "resources/gender/emnlp14.edn"})
;;; --------------------------------------------------------------------------
(defn get-dom
"Pull the document object model from a web resource."
[url]
(-> url URL. web/html-resource))
;;; --------------------------------------------------------------------------
(defn get-content
"Pulls the :content value from a web structure."
([x]
(first (:content x))))
;;; --------------------------------------------------------------------------
(defn get-content!
"Pulls the innermost :content value from a nested web structure."
([xx]
(loop [x xx]
(when-let [c (get-content x)]
(if (string? c)
(str/trim c)
(recur c))))))
;;; --------------------------------------------------------------------------
(defn get-names
"Pull English male and female names from the http://www.20000-names.com
Note that the <ol> lists on the page seem a bit funky, and so we're
pulling the names by the colour of the font!"
([]
;; Pull ALL the names
(into {}
(for [[gender {:keys [url cnt]}] NAMES]
[gender
(reduce #(into %1 (get-names (str url
(if (< %2 2) "" (strfmt "_~2,'0d" %2))
".htm")))
#{} (range 1 (inc cnt)))])))
([url]
(let [COLOR "#9393FF"
items (-> url get-dom
(web/select [:body [:font (web/attr? :color)]]))
names (filter #(= (get-in % [:attrs :color]) COLOR) items)]
;; Don't look like a bot!
(Thread/sleep (rand-int 20000))
;; We're got some clean-up to do...
(println "Fetching names from:" url)
(set (filter seq (map get-content! names))))))
;;; --------------------------------------------------------------------------
(defn save-names
"Saves a hash-map of :female and :male names for later use."
([names]
(save-names names (:edn NAMES)))
([names fpath]
(let [finalize (fn [nset]
(into (sorted-set) (map #(str/lower-case %) nset)))
finalists (reduce (fn [acc [gnd nset]]
(assoc acc gnd (finalize nset)))
{}
names)]
(println "Saving names to" fpath
(map (fn [[g nn]] {g (count nn)}) finalists)) ; Report counts
(spit fpath (pr-str finalists)))))
;;; --------------------------------------------------------------------------
(defn make-emnlp
"Creates a hashmap out of the EMNLP14 CSV lexicon. Returns a vector pair
containing:
[0] the interercept
[1] the hashmap"
[& opts]
(with-open [rdr (io/reader (:csv EMNLP14))]
(let [[head bias & lines] (csv/read-csv rdr)
intercept (Double/parseDouble (bias 1))
[lcnt model] (reduce (fn [[cnt acc] [word weight]]
[(inc cnt) (assoc acc word (Double/parseDouble weight))])
[0 {}]
lines)]
;; Make the hashmap model, report the intercept
(log/info "Mapping EMNLP 2014 lexicon:" head)
(log/fmt-info "Model: words[~a] [~8$]" lcnt intercept)
[intercept model]
;; Save the hashmap if they're requested it
(when (some #{:save} opts)
(let [fpath (:edn EMNLP14)]
(log/info "Saving model to" fpath)
(spit fpath (pr-str model)))))))
| 2105 | ;;;; -------------------------------------------------------------------------
;;;;
;;;; _/_/_/ _/_/_/ _/ _/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/ _/ _/ _/_/_/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/
;;;;
;;;; Data collection/preprocessing routings
;;;;
;;;; @copyright 2019 <NAME> et l'Université du Québec à Montréal
;;;; -------------------------------------------------------------------------
(ns say.data
(:require [say.genie :refer :all]
[say.log :as log]
[clojure.data.csv :as csv]
[clojure.java.io :as io]
[clojure.string :as str]
[net.cgrand.enlive-html :as web])
(:import [java.net URL]))
;;; --------------------------------------------------------------------------
(set! *warn-on-reflection* true)
;;; Female/male names in English from the web
;;; TODO: Compare with the methodology from \cite{thelwall2018}, which uses
;;; names from the 1990 U.S. census @ 90% male and 90% female
(def ^:const NAMES {:female {:url "http://www.20000-names.com/female_english_names" :cnt 20}
:male {:url "http://www.20000-names.com/male_english_names" :cnt 17}
:edn "resources/gender/names.edn"})
;;; Gender word-usage model: \cite{sap2014}
(def ^:const EMNLP14 {:csv "resources/gender/emnlp14gender.csv"
:edn "resources/gender/emnlp14.edn"})
;;; --------------------------------------------------------------------------
(defn get-dom
"Pull the document object model from a web resource."
[url]
(-> url URL. web/html-resource))
;;; --------------------------------------------------------------------------
(defn get-content
"Pulls the :content value from a web structure."
([x]
(first (:content x))))
;;; --------------------------------------------------------------------------
(defn get-content!
"Pulls the innermost :content value from a nested web structure."
([xx]
(loop [x xx]
(when-let [c (get-content x)]
(if (string? c)
(str/trim c)
(recur c))))))
;;; --------------------------------------------------------------------------
(defn get-names
"Pull English male and female names from the http://www.20000-names.com
Note that the <ol> lists on the page seem a bit funky, and so we're
pulling the names by the colour of the font!"
([]
;; Pull ALL the names
(into {}
(for [[gender {:keys [url cnt]}] NAMES]
[gender
(reduce #(into %1 (get-names (str url
(if (< %2 2) "" (strfmt "_~2,'0d" %2))
".htm")))
#{} (range 1 (inc cnt)))])))
([url]
(let [COLOR "#9393FF"
items (-> url get-dom
(web/select [:body [:font (web/attr? :color)]]))
names (filter #(= (get-in % [:attrs :color]) COLOR) items)]
;; Don't look like a bot!
(Thread/sleep (rand-int 20000))
;; We're got some clean-up to do...
(println "Fetching names from:" url)
(set (filter seq (map get-content! names))))))
;;; --------------------------------------------------------------------------
(defn save-names
"Saves a hash-map of :female and :male names for later use."
([names]
(save-names names (:edn NAMES)))
([names fpath]
(let [finalize (fn [nset]
(into (sorted-set) (map #(str/lower-case %) nset)))
finalists (reduce (fn [acc [gnd nset]]
(assoc acc gnd (finalize nset)))
{}
names)]
(println "Saving names to" fpath
(map (fn [[g nn]] {g (count nn)}) finalists)) ; Report counts
(spit fpath (pr-str finalists)))))
;;; --------------------------------------------------------------------------
(defn make-emnlp
"Creates a hashmap out of the EMNLP14 CSV lexicon. Returns a vector pair
containing:
[0] the interercept
[1] the hashmap"
[& opts]
(with-open [rdr (io/reader (:csv EMNLP14))]
(let [[head bias & lines] (csv/read-csv rdr)
intercept (Double/parseDouble (bias 1))
[lcnt model] (reduce (fn [[cnt acc] [word weight]]
[(inc cnt) (assoc acc word (Double/parseDouble weight))])
[0 {}]
lines)]
;; Make the hashmap model, report the intercept
(log/info "Mapping EMNLP 2014 lexicon:" head)
(log/fmt-info "Model: words[~a] [~8$]" lcnt intercept)
[intercept model]
;; Save the hashmap if they're requested it
(when (some #{:save} opts)
(let [fpath (:edn EMNLP14)]
(log/info "Saving model to" fpath)
(spit fpath (pr-str model)))))))
| true | ;;;; -------------------------------------------------------------------------
;;;;
;;;; _/_/_/ _/_/_/ _/ _/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/ _/ _/ _/_/_/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/
;;;;
;;;; Data collection/preprocessing routings
;;;;
;;;; @copyright 2019 PI:NAME:<NAME>END_PI et l'Université du Québec à Montréal
;;;; -------------------------------------------------------------------------
(ns say.data
(:require [say.genie :refer :all]
[say.log :as log]
[clojure.data.csv :as csv]
[clojure.java.io :as io]
[clojure.string :as str]
[net.cgrand.enlive-html :as web])
(:import [java.net URL]))
;;; --------------------------------------------------------------------------
(set! *warn-on-reflection* true)
;;; Female/male names in English from the web
;;; TODO: Compare with the methodology from \cite{thelwall2018}, which uses
;;; names from the 1990 U.S. census @ 90% male and 90% female
(def ^:const NAMES {:female {:url "http://www.20000-names.com/female_english_names" :cnt 20}
:male {:url "http://www.20000-names.com/male_english_names" :cnt 17}
:edn "resources/gender/names.edn"})
;;; Gender word-usage model: \cite{sap2014}
(def ^:const EMNLP14 {:csv "resources/gender/emnlp14gender.csv"
:edn "resources/gender/emnlp14.edn"})
;;; --------------------------------------------------------------------------
(defn get-dom
"Pull the document object model from a web resource."
[url]
(-> url URL. web/html-resource))
;;; --------------------------------------------------------------------------
(defn get-content
"Pulls the :content value from a web structure."
([x]
(first (:content x))))
;;; --------------------------------------------------------------------------
(defn get-content!
"Pulls the innermost :content value from a nested web structure."
([xx]
(loop [x xx]
(when-let [c (get-content x)]
(if (string? c)
(str/trim c)
(recur c))))))
;;; --------------------------------------------------------------------------
(defn get-names
"Pull English male and female names from the http://www.20000-names.com
Note that the <ol> lists on the page seem a bit funky, and so we're
pulling the names by the colour of the font!"
([]
;; Pull ALL the names
(into {}
(for [[gender {:keys [url cnt]}] NAMES]
[gender
(reduce #(into %1 (get-names (str url
(if (< %2 2) "" (strfmt "_~2,'0d" %2))
".htm")))
#{} (range 1 (inc cnt)))])))
([url]
(let [COLOR "#9393FF"
items (-> url get-dom
(web/select [:body [:font (web/attr? :color)]]))
names (filter #(= (get-in % [:attrs :color]) COLOR) items)]
;; Don't look like a bot!
(Thread/sleep (rand-int 20000))
;; We're got some clean-up to do...
(println "Fetching names from:" url)
(set (filter seq (map get-content! names))))))
;;; --------------------------------------------------------------------------
(defn save-names
"Saves a hash-map of :female and :male names for later use."
([names]
(save-names names (:edn NAMES)))
([names fpath]
(let [finalize (fn [nset]
(into (sorted-set) (map #(str/lower-case %) nset)))
finalists (reduce (fn [acc [gnd nset]]
(assoc acc gnd (finalize nset)))
{}
names)]
(println "Saving names to" fpath
(map (fn [[g nn]] {g (count nn)}) finalists)) ; Report counts
(spit fpath (pr-str finalists)))))
;;; --------------------------------------------------------------------------
(defn make-emnlp
"Creates a hashmap out of the EMNLP14 CSV lexicon. Returns a vector pair
containing:
[0] the interercept
[1] the hashmap"
[& opts]
(with-open [rdr (io/reader (:csv EMNLP14))]
(let [[head bias & lines] (csv/read-csv rdr)
intercept (Double/parseDouble (bias 1))
[lcnt model] (reduce (fn [[cnt acc] [word weight]]
[(inc cnt) (assoc acc word (Double/parseDouble weight))])
[0 {}]
lines)]
;; Make the hashmap model, report the intercept
(log/info "Mapping EMNLP 2014 lexicon:" head)
(log/fmt-info "Model: words[~a] [~8$]" lcnt intercept)
[intercept model]
;; Save the hashmap if they're requested it
(when (some #{:save} opts)
(let [fpath (:edn EMNLP14)]
(log/info "Saving model to" fpath)
(spit fpath (pr-str model)))))))
|
[
{
"context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li",
"end": 111,
"score": 0.9998078346252441,
"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.9998205900192261,
"start": 113,
"tag": "NAME",
"value": "Christian Murray"
}
] | editor/src/clj/editor/scene_text.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.scene-text
(:require [editor.gl :as gl]
[editor.scene-cache :as scene-cache])
(:import [com.jogamp.opengl.util.awt TextRenderer]
[java.awt Font]
[com.jogamp.opengl GL2]))
(set! *warn-on-reflection* true)
(defn- request-text-renderer! ^TextRenderer [^GL2 gl]
(scene-cache/request-object! ::text-renderer ::overlay-text gl [Font/SANS_SERIF Font/PLAIN 9]))
(defn overlay
([^GL2 gl ^String text x y]
(overlay gl text x y 1 1 1 1))
([^GL2 gl ^String text x y r g b a]
(overlay gl text x y r g b a 0.0))
([^GL2 gl ^String text x y r g b a rot-z]
(let [^TextRenderer text-renderer (request-text-renderer! gl)]
(gl/overlay gl text-renderer text x y r g b a rot-z))))
(defn bounds [^GL2 gl ^String text]
(let [^TextRenderer text-renderer (request-text-renderer! gl)]
(let [bounds (.getBounds text-renderer text)]
[(.getWidth bounds) (.getHeight bounds)])))
(defn- make-text-renderer [^GL2 gl data]
(let [[font-family font-style font-size] data]
(gl/text-renderer font-family font-style font-size)))
(defn- destroy-text-renderers [^GL2 gl text-renderers _]
(doseq [^TextRenderer text-renderer text-renderers]
(.dispose text-renderer)))
(defn- update-text-renderer [^GL2 gl text-renderer data]
(destroy-text-renderers gl [text-renderer] nil)
(make-text-renderer gl data))
(scene-cache/register-object-cache! ::text-renderer make-text-renderer update-text-renderer destroy-text-renderers)
| 102717 | ;; 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.scene-text
(:require [editor.gl :as gl]
[editor.scene-cache :as scene-cache])
(:import [com.jogamp.opengl.util.awt TextRenderer]
[java.awt Font]
[com.jogamp.opengl GL2]))
(set! *warn-on-reflection* true)
(defn- request-text-renderer! ^TextRenderer [^GL2 gl]
(scene-cache/request-object! ::text-renderer ::overlay-text gl [Font/SANS_SERIF Font/PLAIN 9]))
(defn overlay
([^GL2 gl ^String text x y]
(overlay gl text x y 1 1 1 1))
([^GL2 gl ^String text x y r g b a]
(overlay gl text x y r g b a 0.0))
([^GL2 gl ^String text x y r g b a rot-z]
(let [^TextRenderer text-renderer (request-text-renderer! gl)]
(gl/overlay gl text-renderer text x y r g b a rot-z))))
(defn bounds [^GL2 gl ^String text]
(let [^TextRenderer text-renderer (request-text-renderer! gl)]
(let [bounds (.getBounds text-renderer text)]
[(.getWidth bounds) (.getHeight bounds)])))
(defn- make-text-renderer [^GL2 gl data]
(let [[font-family font-style font-size] data]
(gl/text-renderer font-family font-style font-size)))
(defn- destroy-text-renderers [^GL2 gl text-renderers _]
(doseq [^TextRenderer text-renderer text-renderers]
(.dispose text-renderer)))
(defn- update-text-renderer [^GL2 gl text-renderer data]
(destroy-text-renderers gl [text-renderer] nil)
(make-text-renderer gl data))
(scene-cache/register-object-cache! ::text-renderer make-text-renderer update-text-renderer destroy-text-renderers)
| 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.scene-text
(:require [editor.gl :as gl]
[editor.scene-cache :as scene-cache])
(:import [com.jogamp.opengl.util.awt TextRenderer]
[java.awt Font]
[com.jogamp.opengl GL2]))
(set! *warn-on-reflection* true)
(defn- request-text-renderer! ^TextRenderer [^GL2 gl]
(scene-cache/request-object! ::text-renderer ::overlay-text gl [Font/SANS_SERIF Font/PLAIN 9]))
(defn overlay
([^GL2 gl ^String text x y]
(overlay gl text x y 1 1 1 1))
([^GL2 gl ^String text x y r g b a]
(overlay gl text x y r g b a 0.0))
([^GL2 gl ^String text x y r g b a rot-z]
(let [^TextRenderer text-renderer (request-text-renderer! gl)]
(gl/overlay gl text-renderer text x y r g b a rot-z))))
(defn bounds [^GL2 gl ^String text]
(let [^TextRenderer text-renderer (request-text-renderer! gl)]
(let [bounds (.getBounds text-renderer text)]
[(.getWidth bounds) (.getHeight bounds)])))
(defn- make-text-renderer [^GL2 gl data]
(let [[font-family font-style font-size] data]
(gl/text-renderer font-family font-style font-size)))
(defn- destroy-text-renderers [^GL2 gl text-renderers _]
(doseq [^TextRenderer text-renderer text-renderers]
(.dispose text-renderer)))
(defn- update-text-renderer [^GL2 gl text-renderer data]
(destroy-text-renderers gl [text-renderer] nil)
(make-text-renderer gl data))
(scene-cache/register-object-cache! ::text-renderer make-text-renderer update-text-renderer destroy-text-renderers)
|
[
{
"context": "ns under the License.\n;;\n;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.\n\n(ns czlab.basal.meta\n\n \"C",
"end": 597,
"score": 0.9998524785041809,
"start": 584,
"tag": "NAME",
"value": "Kenneth Leung"
}
] | src/main/clojure/czlab/basal/meta.clj | llnek/xlib | 0 | ;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.
(ns czlab.basal.meta
"Class & reflection helpers."
(:require [czlab.basal.util :as u]
[czlab.basal.core :as c])
(:import [clojure.lang
RestFn]
[java.lang.reflect
Member
Field
Method
Modifier]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* true)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn count-arity
"Figure out arity of function, returning the set of
arity counts and whether var-args are used.
e.g. [#{0 1 2 3} true]."
{:arglists '([func])}
[func]
{:pre [(fn? func)]}
(let [s (c/preduce<set>
#(let [^java.lang.reflect.Method m %2
n (.getName m)]
(cond (.equals "getRequiredArity" n)
(-> (conj! %1
(.getRequiredArity ^RestFn func))
(conj! 709394))
(.equals "invoke" n)
(conj! %1 (.getParameterCount m))
:else %1))
(.getDeclaredMethods (class func)))
v? (c/in? s 709394)]
[(disj s 709394) v?]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-child?
"If clazz is subclass of this base class?"
{:arglists '([parent child])}
[parent child]
(cond (and (class? child)
(class? parent)) (isa? child parent)
(or (nil? child)
(nil? parent)) false
(not (class? parent)) (is-child? (class parent) child)
(not (class? child)) (is-child? parent (class child))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gcn
[z] (some-> ^Class z .getName))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- is-XXX?
[c classes]
(-> (gcn (if-not
(class? c) (class c) c)) (c/eq-any? classes)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-boolean?
"Is class Boolean?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["boolean" "Boolean" "java.lang.Boolean"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-void?
"Is class Void?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["void" "Void" "java.lang.Void"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-char?
"Is class Char?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["char" "Char" "java.lang.Character"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-int?
"Is class Int?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["int" "Int" "java.lang.Integer"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-long?
"Is class Long?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["long" "Long" "java.lang.Long"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-float?
"Is class Float?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["float" "Float" "java.lang.Float"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-double?
"Is class Double?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["double" "Double" "java.lang.Double"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-byte?
"Is class Byte?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["byte" "Byte" "java.lang.Byte"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-short?
"Is class Short?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["short" "Short" "java.lang.Short"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-string?
"Is class String?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["String" "java.lang.String"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-object?
"Is class Object?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["Object" "java.lang.Object"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-chars?
"Is class char[]?"
{:arglists '([obj])}
[obj]
(= u/CSCZ (if-not (class? obj) (class obj) obj)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-bytes?
"Is class byte[]?"
{:arglists '([obj])}
[obj]
(= u/BSCZ (if-not (class? obj) (class obj) obj)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn forname
"Load class by name."
{:tag Class
:arglists '([z][z cl])}
([z]
(forname z nil))
([^String z cl]
(if (nil? cl)
(java.lang.Class/forName z)
(java.lang.Class/forName z true cl))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn load-class
"Load class by name."
{:tag Class
:arglists '([clazzName]
[clazzName cl])}
([clazzName]
(load-class clazzName nil))
([clazzName cl]
(if (c/hgl? clazzName)
(.loadClass (u/get-cldr cl) clazzName))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn obj<>
"Instantiate the class by
invoking the constructor with args."
{:tag Object
:arglists '([cz & args])}
[cz & args]
{:pre [(or (string? cz)
(class? cz))(c/n#-even? args)]}
(let [cz (if (string? cz) (load-class cz) cz)
args (partition 2 args)
len (count args)
cargs (c/marray Object len)
ca (c/marray Class len)]
(doseq [n (range len)
:let [[z v] (nth args n)]]
(u/aset* cargs n v)
(aset #^"[Ljava.lang.Class;" ca n z))
(.newInstance (.getDeclaredConstructor ^Class cz ca) cargs)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn list-parents
"List all parent classes."
{:arglists '([javaClass])}
[javaClass]
{:pre [(class? javaClass)]}
(let [rc (loop [sum (c/tvec*)
par javaClass]
(if (nil? par)
(c/persist! sum)
(recur (conj! sum par)
(.getSuperclass ^Class par))))]
;; since we always add the original class,
;; we need to ignore it on return
(c/vec-> (drop 1 rc))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- iter-XXX
[level]
(fn [sum ^Member m]
(let [x (.getModifiers m)]
(if (and (pos? level)
(or (Modifier/isStatic x)
(Modifier/isPrivate x)))
sum
(assoc! sum (.getName m) m)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- list-mtds
[^Class cz level]
(let [par (.getSuperclass cz)]
(reduce (iter-XXX level)
(if (nil? par)
(c/tmap*)
(list-mtds par
(+ 1 level)))
(.getDeclaredMethods cz))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- list-flds
[^Class cz level]
(let [par (.getSuperclass cz)]
(reduce (iter-XXX level)
(if (nil? par)
(c/tmap*)
(list-flds par
(+ 1 level)))
(.getDeclaredFields cz))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn list-methods
"List methods belonging to this class,
including inherited ones."
{:arglists '([javaClass])}
[javaClass]
(vals (if javaClass
(c/persist! (list-mtds javaClass 0)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn list-fields
"List fields belonging to this class,
including inherited ones."
{:arglists '([javaClass])}
[javaClass]
(vals (if javaClass
(c/persist! (list-flds javaClass 0)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
| 46868 | ;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; Copyright © 2013-2022, <NAME>. All rights reserved.
(ns czlab.basal.meta
"Class & reflection helpers."
(:require [czlab.basal.util :as u]
[czlab.basal.core :as c])
(:import [clojure.lang
RestFn]
[java.lang.reflect
Member
Field
Method
Modifier]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* true)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn count-arity
"Figure out arity of function, returning the set of
arity counts and whether var-args are used.
e.g. [#{0 1 2 3} true]."
{:arglists '([func])}
[func]
{:pre [(fn? func)]}
(let [s (c/preduce<set>
#(let [^java.lang.reflect.Method m %2
n (.getName m)]
(cond (.equals "getRequiredArity" n)
(-> (conj! %1
(.getRequiredArity ^RestFn func))
(conj! 709394))
(.equals "invoke" n)
(conj! %1 (.getParameterCount m))
:else %1))
(.getDeclaredMethods (class func)))
v? (c/in? s 709394)]
[(disj s 709394) v?]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-child?
"If clazz is subclass of this base class?"
{:arglists '([parent child])}
[parent child]
(cond (and (class? child)
(class? parent)) (isa? child parent)
(or (nil? child)
(nil? parent)) false
(not (class? parent)) (is-child? (class parent) child)
(not (class? child)) (is-child? parent (class child))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gcn
[z] (some-> ^Class z .getName))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- is-XXX?
[c classes]
(-> (gcn (if-not
(class? c) (class c) c)) (c/eq-any? classes)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-boolean?
"Is class Boolean?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["boolean" "Boolean" "java.lang.Boolean"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-void?
"Is class Void?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["void" "Void" "java.lang.Void"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-char?
"Is class Char?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["char" "Char" "java.lang.Character"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-int?
"Is class Int?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["int" "Int" "java.lang.Integer"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-long?
"Is class Long?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["long" "Long" "java.lang.Long"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-float?
"Is class Float?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["float" "Float" "java.lang.Float"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-double?
"Is class Double?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["double" "Double" "java.lang.Double"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-byte?
"Is class Byte?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["byte" "Byte" "java.lang.Byte"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-short?
"Is class Short?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["short" "Short" "java.lang.Short"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-string?
"Is class String?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["String" "java.lang.String"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-object?
"Is class Object?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["Object" "java.lang.Object"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-chars?
"Is class char[]?"
{:arglists '([obj])}
[obj]
(= u/CSCZ (if-not (class? obj) (class obj) obj)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-bytes?
"Is class byte[]?"
{:arglists '([obj])}
[obj]
(= u/BSCZ (if-not (class? obj) (class obj) obj)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn forname
"Load class by name."
{:tag Class
:arglists '([z][z cl])}
([z]
(forname z nil))
([^String z cl]
(if (nil? cl)
(java.lang.Class/forName z)
(java.lang.Class/forName z true cl))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn load-class
"Load class by name."
{:tag Class
:arglists '([clazzName]
[clazzName cl])}
([clazzName]
(load-class clazzName nil))
([clazzName cl]
(if (c/hgl? clazzName)
(.loadClass (u/get-cldr cl) clazzName))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn obj<>
"Instantiate the class by
invoking the constructor with args."
{:tag Object
:arglists '([cz & args])}
[cz & args]
{:pre [(or (string? cz)
(class? cz))(c/n#-even? args)]}
(let [cz (if (string? cz) (load-class cz) cz)
args (partition 2 args)
len (count args)
cargs (c/marray Object len)
ca (c/marray Class len)]
(doseq [n (range len)
:let [[z v] (nth args n)]]
(u/aset* cargs n v)
(aset #^"[Ljava.lang.Class;" ca n z))
(.newInstance (.getDeclaredConstructor ^Class cz ca) cargs)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn list-parents
"List all parent classes."
{:arglists '([javaClass])}
[javaClass]
{:pre [(class? javaClass)]}
(let [rc (loop [sum (c/tvec*)
par javaClass]
(if (nil? par)
(c/persist! sum)
(recur (conj! sum par)
(.getSuperclass ^Class par))))]
;; since we always add the original class,
;; we need to ignore it on return
(c/vec-> (drop 1 rc))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- iter-XXX
[level]
(fn [sum ^Member m]
(let [x (.getModifiers m)]
(if (and (pos? level)
(or (Modifier/isStatic x)
(Modifier/isPrivate x)))
sum
(assoc! sum (.getName m) m)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- list-mtds
[^Class cz level]
(let [par (.getSuperclass cz)]
(reduce (iter-XXX level)
(if (nil? par)
(c/tmap*)
(list-mtds par
(+ 1 level)))
(.getDeclaredMethods cz))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- list-flds
[^Class cz level]
(let [par (.getSuperclass cz)]
(reduce (iter-XXX level)
(if (nil? par)
(c/tmap*)
(list-flds par
(+ 1 level)))
(.getDeclaredFields cz))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn list-methods
"List methods belonging to this class,
including inherited ones."
{:arglists '([javaClass])}
[javaClass]
(vals (if javaClass
(c/persist! (list-mtds javaClass 0)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn list-fields
"List fields belonging to this class,
including inherited ones."
{:arglists '([javaClass])}
[javaClass]
(vals (if javaClass
(c/persist! (list-flds javaClass 0)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
| true | ;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; Copyright © 2013-2022, PI:NAME:<NAME>END_PI. All rights reserved.
(ns czlab.basal.meta
"Class & reflection helpers."
(:require [czlab.basal.util :as u]
[czlab.basal.core :as c])
(:import [clojure.lang
RestFn]
[java.lang.reflect
Member
Field
Method
Modifier]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* true)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn count-arity
"Figure out arity of function, returning the set of
arity counts and whether var-args are used.
e.g. [#{0 1 2 3} true]."
{:arglists '([func])}
[func]
{:pre [(fn? func)]}
(let [s (c/preduce<set>
#(let [^java.lang.reflect.Method m %2
n (.getName m)]
(cond (.equals "getRequiredArity" n)
(-> (conj! %1
(.getRequiredArity ^RestFn func))
(conj! 709394))
(.equals "invoke" n)
(conj! %1 (.getParameterCount m))
:else %1))
(.getDeclaredMethods (class func)))
v? (c/in? s 709394)]
[(disj s 709394) v?]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-child?
"If clazz is subclass of this base class?"
{:arglists '([parent child])}
[parent child]
(cond (and (class? child)
(class? parent)) (isa? child parent)
(or (nil? child)
(nil? parent)) false
(not (class? parent)) (is-child? (class parent) child)
(not (class? child)) (is-child? parent (class child))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gcn
[z] (some-> ^Class z .getName))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- is-XXX?
[c classes]
(-> (gcn (if-not
(class? c) (class c) c)) (c/eq-any? classes)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-boolean?
"Is class Boolean?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["boolean" "Boolean" "java.lang.Boolean"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-void?
"Is class Void?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["void" "Void" "java.lang.Void"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-char?
"Is class Char?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["char" "Char" "java.lang.Character"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-int?
"Is class Int?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["int" "Int" "java.lang.Integer"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-long?
"Is class Long?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["long" "Long" "java.lang.Long"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-float?
"Is class Float?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["float" "Float" "java.lang.Float"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-double?
"Is class Double?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["double" "Double" "java.lang.Double"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-byte?
"Is class Byte?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["byte" "Byte" "java.lang.Byte"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-short?
"Is class Short?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["short" "Short" "java.lang.Short"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-string?
"Is class String?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["String" "java.lang.String"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-object?
"Is class Object?"
{:arglists '([obj])}
[obj]
(is-XXX? obj ["Object" "java.lang.Object"]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-chars?
"Is class char[]?"
{:arglists '([obj])}
[obj]
(= u/CSCZ (if-not (class? obj) (class obj) obj)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-bytes?
"Is class byte[]?"
{:arglists '([obj])}
[obj]
(= u/BSCZ (if-not (class? obj) (class obj) obj)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn forname
"Load class by name."
{:tag Class
:arglists '([z][z cl])}
([z]
(forname z nil))
([^String z cl]
(if (nil? cl)
(java.lang.Class/forName z)
(java.lang.Class/forName z true cl))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn load-class
"Load class by name."
{:tag Class
:arglists '([clazzName]
[clazzName cl])}
([clazzName]
(load-class clazzName nil))
([clazzName cl]
(if (c/hgl? clazzName)
(.loadClass (u/get-cldr cl) clazzName))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn obj<>
"Instantiate the class by
invoking the constructor with args."
{:tag Object
:arglists '([cz & args])}
[cz & args]
{:pre [(or (string? cz)
(class? cz))(c/n#-even? args)]}
(let [cz (if (string? cz) (load-class cz) cz)
args (partition 2 args)
len (count args)
cargs (c/marray Object len)
ca (c/marray Class len)]
(doseq [n (range len)
:let [[z v] (nth args n)]]
(u/aset* cargs n v)
(aset #^"[Ljava.lang.Class;" ca n z))
(.newInstance (.getDeclaredConstructor ^Class cz ca) cargs)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn list-parents
"List all parent classes."
{:arglists '([javaClass])}
[javaClass]
{:pre [(class? javaClass)]}
(let [rc (loop [sum (c/tvec*)
par javaClass]
(if (nil? par)
(c/persist! sum)
(recur (conj! sum par)
(.getSuperclass ^Class par))))]
;; since we always add the original class,
;; we need to ignore it on return
(c/vec-> (drop 1 rc))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- iter-XXX
[level]
(fn [sum ^Member m]
(let [x (.getModifiers m)]
(if (and (pos? level)
(or (Modifier/isStatic x)
(Modifier/isPrivate x)))
sum
(assoc! sum (.getName m) m)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- list-mtds
[^Class cz level]
(let [par (.getSuperclass cz)]
(reduce (iter-XXX level)
(if (nil? par)
(c/tmap*)
(list-mtds par
(+ 1 level)))
(.getDeclaredMethods cz))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- list-flds
[^Class cz level]
(let [par (.getSuperclass cz)]
(reduce (iter-XXX level)
(if (nil? par)
(c/tmap*)
(list-flds par
(+ 1 level)))
(.getDeclaredFields cz))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn list-methods
"List methods belonging to this class,
including inherited ones."
{:arglists '([javaClass])}
[javaClass]
(vals (if javaClass
(c/persist! (list-mtds javaClass 0)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn list-fields
"List fields belonging to this class,
including inherited ones."
{:arglists '([javaClass])}
[javaClass]
(vals (if javaClass
(c/persist! (list-flds javaClass 0)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
|
[
{
"context": "Name arbitrary-class-name)\n arbitrary-key \"0123456789abcdef\"\n conf (merge (read-default-config)\n ",
"end": 1996,
"score": 0.9997346997261047,
"start": 1980,
"tag": "KEY",
"value": "0123456789abcdef"
}
] | storm-core/test/clj/backtype/storm/serialization/SerializationFactory_test.clj | desmorto/storm | 1,655 | ;; Licensed to the Apache Software Foundation (ASF) under one
;; or more contributor license agreements. See the NOTICE file
;; distributed with this work for additional information
;; regarding copyright ownership. The ASF licenses this file
;; to you under the Apache License, Version 2.0 (the
;; "License"); you may not use this file except in compliance
;; with the License. You may obtain a copy of the License at
;;
;; http:;; www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns backtype.storm.serialization.SerializationFactory-test
(:import [backtype.storm Config])
(:import [backtype.storm.security.serialization BlowfishTupleSerializer])
(:import [backtype.storm.serialization SerializationFactory])
(:import [backtype.storm.utils ListDelegate])
(:use [backtype.storm config])
(:use [clojure test])
)
(deftest test-registers-default-when-not-in-conf
(let [conf (read-default-config)
klass-name (get conf Config/TOPOLOGY_TUPLE_SERIALIZER)
configured-class (Class/forName klass-name)
kryo (SerializationFactory/getKryo conf)]
(is (= configured-class (.getClass (.getSerializer kryo ListDelegate))))
)
)
(deftest test-throws-runtimeexception-when-no-such-class
(let [conf (merge (read-default-config)
{Config/TOPOLOGY_TUPLE_SERIALIZER "null.this.class.does.not.exist"})]
(is (thrown? RuntimeException
(SerializationFactory/getKryo conf)))
)
)
(deftest test-registeres-when-valid-class-name
(let [arbitrary-class-name
(String. "backtype.storm.security.serialization.BlowfishTupleSerializer")
serializer-class (Class/forName arbitrary-class-name)
arbitrary-key "0123456789abcdef"
conf (merge (read-default-config)
{Config/TOPOLOGY_TUPLE_SERIALIZER arbitrary-class-name
BlowfishTupleSerializer/SECRET_KEY arbitrary-key})
kryo (SerializationFactory/getKryo conf)]
(is (= serializer-class (.getClass (.getSerializer kryo ListDelegate))))
)
)
| 32056 | ;; Licensed to the Apache Software Foundation (ASF) under one
;; or more contributor license agreements. See the NOTICE file
;; distributed with this work for additional information
;; regarding copyright ownership. The ASF licenses this file
;; to you under the Apache License, Version 2.0 (the
;; "License"); you may not use this file except in compliance
;; with the License. You may obtain a copy of the License at
;;
;; http:;; www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns backtype.storm.serialization.SerializationFactory-test
(:import [backtype.storm Config])
(:import [backtype.storm.security.serialization BlowfishTupleSerializer])
(:import [backtype.storm.serialization SerializationFactory])
(:import [backtype.storm.utils ListDelegate])
(:use [backtype.storm config])
(:use [clojure test])
)
(deftest test-registers-default-when-not-in-conf
(let [conf (read-default-config)
klass-name (get conf Config/TOPOLOGY_TUPLE_SERIALIZER)
configured-class (Class/forName klass-name)
kryo (SerializationFactory/getKryo conf)]
(is (= configured-class (.getClass (.getSerializer kryo ListDelegate))))
)
)
(deftest test-throws-runtimeexception-when-no-such-class
(let [conf (merge (read-default-config)
{Config/TOPOLOGY_TUPLE_SERIALIZER "null.this.class.does.not.exist"})]
(is (thrown? RuntimeException
(SerializationFactory/getKryo conf)))
)
)
(deftest test-registeres-when-valid-class-name
(let [arbitrary-class-name
(String. "backtype.storm.security.serialization.BlowfishTupleSerializer")
serializer-class (Class/forName arbitrary-class-name)
arbitrary-key "<KEY>"
conf (merge (read-default-config)
{Config/TOPOLOGY_TUPLE_SERIALIZER arbitrary-class-name
BlowfishTupleSerializer/SECRET_KEY arbitrary-key})
kryo (SerializationFactory/getKryo conf)]
(is (= serializer-class (.getClass (.getSerializer kryo ListDelegate))))
)
)
| true | ;; Licensed to the Apache Software Foundation (ASF) under one
;; or more contributor license agreements. See the NOTICE file
;; distributed with this work for additional information
;; regarding copyright ownership. The ASF licenses this file
;; to you under the Apache License, Version 2.0 (the
;; "License"); you may not use this file except in compliance
;; with the License. You may obtain a copy of the License at
;;
;; http:;; www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns backtype.storm.serialization.SerializationFactory-test
(:import [backtype.storm Config])
(:import [backtype.storm.security.serialization BlowfishTupleSerializer])
(:import [backtype.storm.serialization SerializationFactory])
(:import [backtype.storm.utils ListDelegate])
(:use [backtype.storm config])
(:use [clojure test])
)
(deftest test-registers-default-when-not-in-conf
(let [conf (read-default-config)
klass-name (get conf Config/TOPOLOGY_TUPLE_SERIALIZER)
configured-class (Class/forName klass-name)
kryo (SerializationFactory/getKryo conf)]
(is (= configured-class (.getClass (.getSerializer kryo ListDelegate))))
)
)
(deftest test-throws-runtimeexception-when-no-such-class
(let [conf (merge (read-default-config)
{Config/TOPOLOGY_TUPLE_SERIALIZER "null.this.class.does.not.exist"})]
(is (thrown? RuntimeException
(SerializationFactory/getKryo conf)))
)
)
(deftest test-registeres-when-valid-class-name
(let [arbitrary-class-name
(String. "backtype.storm.security.serialization.BlowfishTupleSerializer")
serializer-class (Class/forName arbitrary-class-name)
arbitrary-key "PI:KEY:<KEY>END_PI"
conf (merge (read-default-config)
{Config/TOPOLOGY_TUPLE_SERIALIZER arbitrary-class-name
BlowfishTupleSerializer/SECRET_KEY arbitrary-key})
kryo (SerializationFactory/getKryo conf)]
(is (= serializer-class (.getClass (.getSerializer kryo ListDelegate))))
)
)
|
[
{
"context": ";\n; Copyright © 2013 Sebastian Hoß <mail@shoss.de>\n; This work is free. You can redi",
"end": 34,
"score": 0.9998674392700195,
"start": 21,
"tag": "NAME",
"value": "Sebastian Hoß"
},
{
"context": ";\n; Copyright © 2013 Sebastian Hoß <mail@shoss.de>\n; This work is free. You can redistribute it and",
"end": 49,
"score": 0.9999291896820068,
"start": 36,
"tag": "EMAIL",
"value": "mail@shoss.de"
}
] | src/main/clojure/finj/common.clj | sebhoss/finj | 30 | ;
; Copyright © 2013 Sebastian Hoß <mail@shoss.de>
; This work is free. You can redistribute it and/or modify it under the
; terms of the Do What The Fuck You Want To Public License, Version 2,
; as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
;
(ns finj.common
(:require [com.github.sebhoss.def :refer :all]))
(defnk rate [:rate-per-cent]
(/ rate-per-cent 100))
(defnk accumulation-factor [:rate]
(inc rate))
| 12534 | ;
; Copyright © 2013 <NAME> <<EMAIL>>
; This work is free. You can redistribute it and/or modify it under the
; terms of the Do What The Fuck You Want To Public License, Version 2,
; as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
;
(ns finj.common
(:require [com.github.sebhoss.def :refer :all]))
(defnk rate [:rate-per-cent]
(/ rate-per-cent 100))
(defnk accumulation-factor [:rate]
(inc rate))
| true | ;
; Copyright © 2013 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
; This work is free. You can redistribute it and/or modify it under the
; terms of the Do What The Fuck You Want To Public License, Version 2,
; as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
;
(ns finj.common
(:require [com.github.sebhoss.def :refer :all]))
(defnk rate [:rate-per-cent]
(/ rate-per-cent 100))
(defnk accumulation-factor [:rate]
(inc rate))
|
[
{
"context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio",
"end": 29,
"score": 0.9997937679290771,
"start": 18,
"tag": "NAME",
"value": "Rich Hickey"
}
] | Source/clojure/spec/gen.clj | max-lv/Arcadia | 0 | ; Copyright (c) Rich Hickey. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns clojure.spec.gen
(:refer-clojure :exclude [boolean bytes cat hash-map list map not-empty set vector
char double int keyword symbol string uuid delay]))
(alias 'c 'clojure.core)
(defn- dynaload
[s]
(let [ns (namespace s)]
(assert ns)
(require (c/symbol ns))
(let [v (resolve s)]
(if v
@v
(throw (Exception. (str "Var " s " is not on the classpath")))))))
(def ^:private quick-check-ref
(c/delay (dynaload 'clojure.test.check/quick-check)))
(defn quick-check
[& args]
(apply @quick-check-ref args))
(def ^:private for-all*-ref
(c/delay (dynaload 'clojure.test.check.properties/for-all*)))
(defn for-all*
"Dynamically loaded clojure.test.check.properties/for-all*."
[& args]
(apply @for-all*-ref args))
(let [g? (c/delay (dynaload 'clojure.test.check.generators/generator?))
g (c/delay (dynaload 'clojure.test.check.generators/generate))
mkg (c/delay (dynaload 'clojure.test.check.generators/->Generator))]
(defn- generator?
[x]
(@g? x))
(defn- generator
[gfn]
(@mkg gfn))
(defn generate
"Generate a single value using generator."
[generator]
(@g generator)))
(defn ^:skip-wiki delay-impl
[gfnd]
;;N.B. depends on test.check impl details
(generator (fn [rnd size]
((:gen @gfnd) rnd size))))
(defmacro delay
"given body that returns a generator, returns a
generator that delegates to that, but delays
creation until used."
[& body]
`(delay-impl (c/delay ~@body)))
(defn gen-for-name
"Dynamically loads test.check generator named s."
[s]
(let [g (dynaload s)]
(if (generator? g)
g
(throw (Exception. (str "Var " s " is not a generator"))))))
(defmacro ^:skip-wiki lazy-combinator
"Implementation macro, do not call directly."
[s]
(let [fqn (c/symbol "clojure.test.check.generators" (name s))
doc (str "Lazy loaded version of " fqn)]
`(let [g# (c/delay (dynaload '~fqn))]
(defn ~s
~doc
[& ~'args]
(apply @g# ~'args)))))
(defmacro ^:skip-wiki lazy-combinators
"Implementation macro, do not call directly."
[& syms]
`(do
~@(c/map
(fn [s] (c/list 'lazy-combinator s))
syms)))
(lazy-combinators hash-map list map not-empty set vector vector-distinct fmap elements
bind choose fmap one-of such-that tuple sample return
large-integer* double*)
(defmacro ^:skip-wiki lazy-prim
"Implementation macro, do not call directly."
[s]
(let [fqn (c/symbol "clojure.test.check.generators" (name s))
doc (str "Fn returning " fqn)]
`(let [g# (c/delay (dynaload '~fqn))]
(defn ~s
~doc
[& ~'args]
@g#))))
(defmacro ^:skip-wiki lazy-prims
"Implementation macro, do not call directly."
[& syms]
`(do
~@(c/map
(fn [s] (c/list 'lazy-prim s))
syms)))
(lazy-prims any any-printable boolean bytes char char-alpha char-alphanumeric char-ascii double
int keyword keyword-ns large-integer ratio simple-type simple-type-printable
string string-ascii string-alphanumeric symbol symbol-ns uuid)
(defn cat
"Returns a generator of a sequence catenated from results of
gens, each of which should generate something sequential."
[& gens]
(fmap #(apply concat %)
(apply tuple gens)))
(defn- qualified? [ident] (not (nil? (namespace ident))))
(def ^:private
gen-builtins
(c/delay
(let [simple (simple-type-printable)]
{any? (one-of [(return nil) (any-printable)])
some? (such-that some? (any-printable))
number? (one-of [(large-integer) (double)])
integer? (large-integer)
int? (large-integer)
pos-int? (large-integer* {:min 1})
neg-int? (large-integer* {:max -1})
nat-int? (large-integer* {:min 0})
float? (double)
double? (double)
boolean? (boolean)
string? (string-alphanumeric)
ident? (one-of [(keyword-ns) (symbol-ns)])
simple-ident? (one-of [(keyword) (symbol)])
qualified-ident? (such-that qualified? (one-of [(keyword-ns) (symbol-ns)]))
keyword? (keyword-ns)
simple-keyword? (keyword)
qualified-keyword? (such-that qualified? (keyword-ns))
symbol? (symbol-ns)
simple-symbol? (symbol)
qualified-symbol? (such-that qualified? (symbol-ns))
;; uuid? (uuid)
;; uri? (fmap #(java.net.URI/create (str "http://" % ".com")) (uuid))
;; bigdec? (fmap #(BigDecimal/valueOf %)
;; (double* {:infinite? false :NaN? false}))
;; inst? (fmap #(java.util.Date. %)
;; (large-integer))
seqable? (one-of [(return nil)
(list simple)
(vector simple)
(map simple simple)
(set simple)
(string-alphanumeric)])
indexed? (vector simple)
map? (map simple simple)
vector? (vector simple)
list? (list simple)
seq? (list simple)
char? (char)
set? (set simple)
nil? (return nil)
false? (return false)
true? (return true)
zero? (return 0)
rational? (one-of [(large-integer) (ratio)])
coll? (one-of [(map simple simple)
(list simple)
(vector simple)
(set simple)])
empty? (elements [nil '() [] {} #{}])
associative? (one-of [(map simple simple) (vector simple)])
sequential? (one-of [(list simple) (vector simple)])
ratio? (such-that ratio? (ratio))
;; bytes? (bytes)
})))
(defn gen-for-pred
"Given a predicate, returns a built-in generator if one exists."
[pred]
(if (set? pred)
(elements pred)
(get @gen-builtins pred)))
(comment
(require :reload 'clojure.spec.gen)
(in-ns 'clojure.spec.gen)
;; combinators, see call to lazy-combinators above for complete list
(generate (one-of [(gen-for-pred integer?) (gen-for-pred string?)]))
(generate (such-that #(< 10000 %) (gen-for-pred integer?)))
(let [reqs {:a (gen-for-pred number?)
:b (gen-for-pred ratio?)}
opts {:c (gen-for-pred string?)}]
(generate (bind (choose 0 (count opts))
#(let [args (concat (seq reqs) (shuffle (seq opts)))]
(->> args
(take (+ % (count reqs)))
(mapcat identity)
(apply hash-map))))))
(generate (cat (list (gen-for-pred string?))
(list (gen-for-pred ratio?))))
;; load your own generator
(gen-for-name 'clojure.test.check.generators/int)
;; failure modes
(gen-for-name 'unqualified)
(gen-for-name 'clojure.core/+)
(gen-for-name 'clojure.core/name-does-not-exist)
(gen-for-name 'ns.does.not.exist/f)
)
| 56789 | ; 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.spec.gen
(:refer-clojure :exclude [boolean bytes cat hash-map list map not-empty set vector
char double int keyword symbol string uuid delay]))
(alias 'c 'clojure.core)
(defn- dynaload
[s]
(let [ns (namespace s)]
(assert ns)
(require (c/symbol ns))
(let [v (resolve s)]
(if v
@v
(throw (Exception. (str "Var " s " is not on the classpath")))))))
(def ^:private quick-check-ref
(c/delay (dynaload 'clojure.test.check/quick-check)))
(defn quick-check
[& args]
(apply @quick-check-ref args))
(def ^:private for-all*-ref
(c/delay (dynaload 'clojure.test.check.properties/for-all*)))
(defn for-all*
"Dynamically loaded clojure.test.check.properties/for-all*."
[& args]
(apply @for-all*-ref args))
(let [g? (c/delay (dynaload 'clojure.test.check.generators/generator?))
g (c/delay (dynaload 'clojure.test.check.generators/generate))
mkg (c/delay (dynaload 'clojure.test.check.generators/->Generator))]
(defn- generator?
[x]
(@g? x))
(defn- generator
[gfn]
(@mkg gfn))
(defn generate
"Generate a single value using generator."
[generator]
(@g generator)))
(defn ^:skip-wiki delay-impl
[gfnd]
;;N.B. depends on test.check impl details
(generator (fn [rnd size]
((:gen @gfnd) rnd size))))
(defmacro delay
"given body that returns a generator, returns a
generator that delegates to that, but delays
creation until used."
[& body]
`(delay-impl (c/delay ~@body)))
(defn gen-for-name
"Dynamically loads test.check generator named s."
[s]
(let [g (dynaload s)]
(if (generator? g)
g
(throw (Exception. (str "Var " s " is not a generator"))))))
(defmacro ^:skip-wiki lazy-combinator
"Implementation macro, do not call directly."
[s]
(let [fqn (c/symbol "clojure.test.check.generators" (name s))
doc (str "Lazy loaded version of " fqn)]
`(let [g# (c/delay (dynaload '~fqn))]
(defn ~s
~doc
[& ~'args]
(apply @g# ~'args)))))
(defmacro ^:skip-wiki lazy-combinators
"Implementation macro, do not call directly."
[& syms]
`(do
~@(c/map
(fn [s] (c/list 'lazy-combinator s))
syms)))
(lazy-combinators hash-map list map not-empty set vector vector-distinct fmap elements
bind choose fmap one-of such-that tuple sample return
large-integer* double*)
(defmacro ^:skip-wiki lazy-prim
"Implementation macro, do not call directly."
[s]
(let [fqn (c/symbol "clojure.test.check.generators" (name s))
doc (str "Fn returning " fqn)]
`(let [g# (c/delay (dynaload '~fqn))]
(defn ~s
~doc
[& ~'args]
@g#))))
(defmacro ^:skip-wiki lazy-prims
"Implementation macro, do not call directly."
[& syms]
`(do
~@(c/map
(fn [s] (c/list 'lazy-prim s))
syms)))
(lazy-prims any any-printable boolean bytes char char-alpha char-alphanumeric char-ascii double
int keyword keyword-ns large-integer ratio simple-type simple-type-printable
string string-ascii string-alphanumeric symbol symbol-ns uuid)
(defn cat
"Returns a generator of a sequence catenated from results of
gens, each of which should generate something sequential."
[& gens]
(fmap #(apply concat %)
(apply tuple gens)))
(defn- qualified? [ident] (not (nil? (namespace ident))))
(def ^:private
gen-builtins
(c/delay
(let [simple (simple-type-printable)]
{any? (one-of [(return nil) (any-printable)])
some? (such-that some? (any-printable))
number? (one-of [(large-integer) (double)])
integer? (large-integer)
int? (large-integer)
pos-int? (large-integer* {:min 1})
neg-int? (large-integer* {:max -1})
nat-int? (large-integer* {:min 0})
float? (double)
double? (double)
boolean? (boolean)
string? (string-alphanumeric)
ident? (one-of [(keyword-ns) (symbol-ns)])
simple-ident? (one-of [(keyword) (symbol)])
qualified-ident? (such-that qualified? (one-of [(keyword-ns) (symbol-ns)]))
keyword? (keyword-ns)
simple-keyword? (keyword)
qualified-keyword? (such-that qualified? (keyword-ns))
symbol? (symbol-ns)
simple-symbol? (symbol)
qualified-symbol? (such-that qualified? (symbol-ns))
;; uuid? (uuid)
;; uri? (fmap #(java.net.URI/create (str "http://" % ".com")) (uuid))
;; bigdec? (fmap #(BigDecimal/valueOf %)
;; (double* {:infinite? false :NaN? false}))
;; inst? (fmap #(java.util.Date. %)
;; (large-integer))
seqable? (one-of [(return nil)
(list simple)
(vector simple)
(map simple simple)
(set simple)
(string-alphanumeric)])
indexed? (vector simple)
map? (map simple simple)
vector? (vector simple)
list? (list simple)
seq? (list simple)
char? (char)
set? (set simple)
nil? (return nil)
false? (return false)
true? (return true)
zero? (return 0)
rational? (one-of [(large-integer) (ratio)])
coll? (one-of [(map simple simple)
(list simple)
(vector simple)
(set simple)])
empty? (elements [nil '() [] {} #{}])
associative? (one-of [(map simple simple) (vector simple)])
sequential? (one-of [(list simple) (vector simple)])
ratio? (such-that ratio? (ratio))
;; bytes? (bytes)
})))
(defn gen-for-pred
"Given a predicate, returns a built-in generator if one exists."
[pred]
(if (set? pred)
(elements pred)
(get @gen-builtins pred)))
(comment
(require :reload 'clojure.spec.gen)
(in-ns 'clojure.spec.gen)
;; combinators, see call to lazy-combinators above for complete list
(generate (one-of [(gen-for-pred integer?) (gen-for-pred string?)]))
(generate (such-that #(< 10000 %) (gen-for-pred integer?)))
(let [reqs {:a (gen-for-pred number?)
:b (gen-for-pred ratio?)}
opts {:c (gen-for-pred string?)}]
(generate (bind (choose 0 (count opts))
#(let [args (concat (seq reqs) (shuffle (seq opts)))]
(->> args
(take (+ % (count reqs)))
(mapcat identity)
(apply hash-map))))))
(generate (cat (list (gen-for-pred string?))
(list (gen-for-pred ratio?))))
;; load your own generator
(gen-for-name 'clojure.test.check.generators/int)
;; failure modes
(gen-for-name 'unqualified)
(gen-for-name 'clojure.core/+)
(gen-for-name 'clojure.core/name-does-not-exist)
(gen-for-name 'ns.does.not.exist/f)
)
| 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.spec.gen
(:refer-clojure :exclude [boolean bytes cat hash-map list map not-empty set vector
char double int keyword symbol string uuid delay]))
(alias 'c 'clojure.core)
(defn- dynaload
[s]
(let [ns (namespace s)]
(assert ns)
(require (c/symbol ns))
(let [v (resolve s)]
(if v
@v
(throw (Exception. (str "Var " s " is not on the classpath")))))))
(def ^:private quick-check-ref
(c/delay (dynaload 'clojure.test.check/quick-check)))
(defn quick-check
[& args]
(apply @quick-check-ref args))
(def ^:private for-all*-ref
(c/delay (dynaload 'clojure.test.check.properties/for-all*)))
(defn for-all*
"Dynamically loaded clojure.test.check.properties/for-all*."
[& args]
(apply @for-all*-ref args))
(let [g? (c/delay (dynaload 'clojure.test.check.generators/generator?))
g (c/delay (dynaload 'clojure.test.check.generators/generate))
mkg (c/delay (dynaload 'clojure.test.check.generators/->Generator))]
(defn- generator?
[x]
(@g? x))
(defn- generator
[gfn]
(@mkg gfn))
(defn generate
"Generate a single value using generator."
[generator]
(@g generator)))
(defn ^:skip-wiki delay-impl
[gfnd]
;;N.B. depends on test.check impl details
(generator (fn [rnd size]
((:gen @gfnd) rnd size))))
(defmacro delay
"given body that returns a generator, returns a
generator that delegates to that, but delays
creation until used."
[& body]
`(delay-impl (c/delay ~@body)))
(defn gen-for-name
"Dynamically loads test.check generator named s."
[s]
(let [g (dynaload s)]
(if (generator? g)
g
(throw (Exception. (str "Var " s " is not a generator"))))))
(defmacro ^:skip-wiki lazy-combinator
"Implementation macro, do not call directly."
[s]
(let [fqn (c/symbol "clojure.test.check.generators" (name s))
doc (str "Lazy loaded version of " fqn)]
`(let [g# (c/delay (dynaload '~fqn))]
(defn ~s
~doc
[& ~'args]
(apply @g# ~'args)))))
(defmacro ^:skip-wiki lazy-combinators
"Implementation macro, do not call directly."
[& syms]
`(do
~@(c/map
(fn [s] (c/list 'lazy-combinator s))
syms)))
(lazy-combinators hash-map list map not-empty set vector vector-distinct fmap elements
bind choose fmap one-of such-that tuple sample return
large-integer* double*)
(defmacro ^:skip-wiki lazy-prim
"Implementation macro, do not call directly."
[s]
(let [fqn (c/symbol "clojure.test.check.generators" (name s))
doc (str "Fn returning " fqn)]
`(let [g# (c/delay (dynaload '~fqn))]
(defn ~s
~doc
[& ~'args]
@g#))))
(defmacro ^:skip-wiki lazy-prims
"Implementation macro, do not call directly."
[& syms]
`(do
~@(c/map
(fn [s] (c/list 'lazy-prim s))
syms)))
(lazy-prims any any-printable boolean bytes char char-alpha char-alphanumeric char-ascii double
int keyword keyword-ns large-integer ratio simple-type simple-type-printable
string string-ascii string-alphanumeric symbol symbol-ns uuid)
(defn cat
"Returns a generator of a sequence catenated from results of
gens, each of which should generate something sequential."
[& gens]
(fmap #(apply concat %)
(apply tuple gens)))
(defn- qualified? [ident] (not (nil? (namespace ident))))
(def ^:private
gen-builtins
(c/delay
(let [simple (simple-type-printable)]
{any? (one-of [(return nil) (any-printable)])
some? (such-that some? (any-printable))
number? (one-of [(large-integer) (double)])
integer? (large-integer)
int? (large-integer)
pos-int? (large-integer* {:min 1})
neg-int? (large-integer* {:max -1})
nat-int? (large-integer* {:min 0})
float? (double)
double? (double)
boolean? (boolean)
string? (string-alphanumeric)
ident? (one-of [(keyword-ns) (symbol-ns)])
simple-ident? (one-of [(keyword) (symbol)])
qualified-ident? (such-that qualified? (one-of [(keyword-ns) (symbol-ns)]))
keyword? (keyword-ns)
simple-keyword? (keyword)
qualified-keyword? (such-that qualified? (keyword-ns))
symbol? (symbol-ns)
simple-symbol? (symbol)
qualified-symbol? (such-that qualified? (symbol-ns))
;; uuid? (uuid)
;; uri? (fmap #(java.net.URI/create (str "http://" % ".com")) (uuid))
;; bigdec? (fmap #(BigDecimal/valueOf %)
;; (double* {:infinite? false :NaN? false}))
;; inst? (fmap #(java.util.Date. %)
;; (large-integer))
seqable? (one-of [(return nil)
(list simple)
(vector simple)
(map simple simple)
(set simple)
(string-alphanumeric)])
indexed? (vector simple)
map? (map simple simple)
vector? (vector simple)
list? (list simple)
seq? (list simple)
char? (char)
set? (set simple)
nil? (return nil)
false? (return false)
true? (return true)
zero? (return 0)
rational? (one-of [(large-integer) (ratio)])
coll? (one-of [(map simple simple)
(list simple)
(vector simple)
(set simple)])
empty? (elements [nil '() [] {} #{}])
associative? (one-of [(map simple simple) (vector simple)])
sequential? (one-of [(list simple) (vector simple)])
ratio? (such-that ratio? (ratio))
;; bytes? (bytes)
})))
(defn gen-for-pred
"Given a predicate, returns a built-in generator if one exists."
[pred]
(if (set? pred)
(elements pred)
(get @gen-builtins pred)))
(comment
(require :reload 'clojure.spec.gen)
(in-ns 'clojure.spec.gen)
;; combinators, see call to lazy-combinators above for complete list
(generate (one-of [(gen-for-pred integer?) (gen-for-pred string?)]))
(generate (such-that #(< 10000 %) (gen-for-pred integer?)))
(let [reqs {:a (gen-for-pred number?)
:b (gen-for-pred ratio?)}
opts {:c (gen-for-pred string?)}]
(generate (bind (choose 0 (count opts))
#(let [args (concat (seq reqs) (shuffle (seq opts)))]
(->> args
(take (+ % (count reqs)))
(mapcat identity)
(apply hash-map))))))
(generate (cat (list (gen-for-pred string?))
(list (gen-for-pred ratio?))))
;; load your own generator
(gen-for-name 'clojure.test.check.generators/int)
;; failure modes
(gen-for-name 'unqualified)
(gen-for-name 'clojure.core/+)
(gen-for-name 'clojure.core/name-does-not-exist)
(gen-for-name 'ns.does.not.exist/f)
)
|
[
{
"context": " scraping utility functions.\n;;\n;; Copyright 2012, F.M. de Waard & Vixu.com <fmw@vixu.com>.\n;;\n;; Licensed under t",
"end": 88,
"score": 0.999864935874939,
"start": 75,
"tag": "NAME",
"value": "F.M. de Waard"
},
{
"context": ".\n;;\n;; Copyright 2012, F.M. de Waard & Vixu.com <fmw@vixu.com>.\n;;\n;; Licensed under the Apache License, Versio",
"end": 113,
"score": 0.9999327659606934,
"start": 101,
"tag": "EMAIL",
"value": "fmw@vixu.com"
}
] | src/alida/scrape.clj | fmw/alida | 6 | ;; src/alida/scrape.clj: scraping utility functions.
;;
;; Copyright 2012, F.M. de Waard & Vixu.com <fmw@vixu.com>.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns alida.scrape
(:require [clojure.string :as string]
[net.cgrand.enlive-html :as enlive]
[alida.util :as util]
[alida.db :as db])
(:import [java.io StringReader]
[org.jsoup Jsoup]))
(defn content-type-is-html? [request]
"Checks if the Content-Type header for the specified request map
says the document is text/html."
(not (nil? (re-matches #"^text/html.*"
(get (:headers request) "content-type")))))
(defn get-links-enlive
"Returns the set of unique href attribute values from
the elements that match the provided enlive selector
(e.g. [:a]) in the given string using the current-uri
value to turn the links into absolute URIs."
[current-uri s selector]
(into #{}
(map #(util/get-absolute-uri current-uri (:href (:attrs %)))
(enlive/select (enlive/html-resource (StringReader. s))
selector))))
(defn get-links
"Returns the set of unique href attribute values from the elements
that match the provided enlive selector (e.g. [:a]) in the given
string using the provided current-uri to turn the links into absolute
URIs. Optionally also accepts a map with filters as a third argument,
which supports :filter (ran over the absolute URI, including
the hostname and scheme) and :path-filter (only ran over the
path segment of the URI). "
[current-uri
s
selector
& [filters]]
(let [links (get-links-enlive current-uri s selector)]
(if (empty? filters)
links
(loop [filtered-links links
filter-pairs (vec filters)]
(if-let [[filter-name filter-pattern] (first filter-pairs)]
(recur (if (= (class filter-pattern) java.util.regex.Pattern)
(filter
(cond
(= filter-name :filter)
#(re-matches filter-pattern %)
(= filter-name :path-filter)
#(re-matches filter-pattern
(:path (util/get-uri-segments %))))
filtered-links)
filtered-links)
(rest filter-pairs))
filtered-links)))))
(defn get-links-jsoup
"Returns a set of absolute URIs for all links in a given html string
using the provided current-uri as a base. This fn provides less
control than the get-links-enlive fn, but offers much better
performance."
[current-uri html]
(into #{}
(map (fn [element]
(util/get-absolute-uri current-uri (.attr element "href")))
(.select (Jsoup/parse html) "a[href]"))))
(defn #^String html-to-plaintext
"Returns the plaintext value of the provided HTML string.
This function only returns the actual text of the page. This
doesn't include attribute values like image titles. See the
vix/lucene/distill-plaintext fn for an example of a function that
also includes img attributes."
[html]
(.text (Jsoup/parse html)))
(defmulti get-trimmed-content
"Returns a string or sequence of strings (if multiple values are
found) given either a string containing html or the output of
Enlive's html-resource fn as the first argument and a selector
vector as the second argument."
(fn [page selector]
(cond
(string? page) :string
(seq? page) :enlive-resource)))
(defmethod get-trimmed-content :enlive-resource [resource selector]
(let [selection (enlive/select resource selector)]
(cond
(= (count selection) 1)
(string/trim (apply str (:content (first selection))))
(> (count selection) 1)
(map (fn [node]
(string/trim (apply str (:content node))))
selection))))
(defmethod get-trimmed-content :string [html selector]
(get-trimmed-content (enlive/html-resource (StringReader. html)) selector))
(defn extract-and-store-data
"Processes crawl results with the provided crawl-tag and
crawl-timestamp that are stored in the database by running
scraping-fn over them. The scraping-fn should always return a map
or nil. This fn requests and stores documents in quantities of
batch-size (optional)."
[database crawl-tag crawl-timestamp scraping-fn & [batch-size]]
(let [limit (or batch-size 1000)]
(loop [raw (db/get-pages-for-crawl-tag-and-timestamp database
crawl-tag
crawl-timestamp
limit)]
(db/add-batched-documents database
(map (fn [raw-page]
(assoc (scraping-fn raw-page)
:type "scrape-result"
:uri (:uri raw-page)
:crawled-at (:crawled-at raw-page)
:crawl-tag crawl-tag
:crawl-timestamp crawl-timestamp))
(:documents raw)))
(when-let [{:keys [uri timestamp id]} (:next raw)]
(recur (db/get-pages-for-crawl-tag-and-timestamp database
crawl-tag
crawl-timestamp
limit
uri
timestamp
id)))))) | 122262 | ;; src/alida/scrape.clj: scraping utility functions.
;;
;; Copyright 2012, <NAME> & Vixu.com <<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 alida.scrape
(:require [clojure.string :as string]
[net.cgrand.enlive-html :as enlive]
[alida.util :as util]
[alida.db :as db])
(:import [java.io StringReader]
[org.jsoup Jsoup]))
(defn content-type-is-html? [request]
"Checks if the Content-Type header for the specified request map
says the document is text/html."
(not (nil? (re-matches #"^text/html.*"
(get (:headers request) "content-type")))))
(defn get-links-enlive
"Returns the set of unique href attribute values from
the elements that match the provided enlive selector
(e.g. [:a]) in the given string using the current-uri
value to turn the links into absolute URIs."
[current-uri s selector]
(into #{}
(map #(util/get-absolute-uri current-uri (:href (:attrs %)))
(enlive/select (enlive/html-resource (StringReader. s))
selector))))
(defn get-links
"Returns the set of unique href attribute values from the elements
that match the provided enlive selector (e.g. [:a]) in the given
string using the provided current-uri to turn the links into absolute
URIs. Optionally also accepts a map with filters as a third argument,
which supports :filter (ran over the absolute URI, including
the hostname and scheme) and :path-filter (only ran over the
path segment of the URI). "
[current-uri
s
selector
& [filters]]
(let [links (get-links-enlive current-uri s selector)]
(if (empty? filters)
links
(loop [filtered-links links
filter-pairs (vec filters)]
(if-let [[filter-name filter-pattern] (first filter-pairs)]
(recur (if (= (class filter-pattern) java.util.regex.Pattern)
(filter
(cond
(= filter-name :filter)
#(re-matches filter-pattern %)
(= filter-name :path-filter)
#(re-matches filter-pattern
(:path (util/get-uri-segments %))))
filtered-links)
filtered-links)
(rest filter-pairs))
filtered-links)))))
(defn get-links-jsoup
"Returns a set of absolute URIs for all links in a given html string
using the provided current-uri as a base. This fn provides less
control than the get-links-enlive fn, but offers much better
performance."
[current-uri html]
(into #{}
(map (fn [element]
(util/get-absolute-uri current-uri (.attr element "href")))
(.select (Jsoup/parse html) "a[href]"))))
(defn #^String html-to-plaintext
"Returns the plaintext value of the provided HTML string.
This function only returns the actual text of the page. This
doesn't include attribute values like image titles. See the
vix/lucene/distill-plaintext fn for an example of a function that
also includes img attributes."
[html]
(.text (Jsoup/parse html)))
(defmulti get-trimmed-content
"Returns a string or sequence of strings (if multiple values are
found) given either a string containing html or the output of
Enlive's html-resource fn as the first argument and a selector
vector as the second argument."
(fn [page selector]
(cond
(string? page) :string
(seq? page) :enlive-resource)))
(defmethod get-trimmed-content :enlive-resource [resource selector]
(let [selection (enlive/select resource selector)]
(cond
(= (count selection) 1)
(string/trim (apply str (:content (first selection))))
(> (count selection) 1)
(map (fn [node]
(string/trim (apply str (:content node))))
selection))))
(defmethod get-trimmed-content :string [html selector]
(get-trimmed-content (enlive/html-resource (StringReader. html)) selector))
(defn extract-and-store-data
"Processes crawl results with the provided crawl-tag and
crawl-timestamp that are stored in the database by running
scraping-fn over them. The scraping-fn should always return a map
or nil. This fn requests and stores documents in quantities of
batch-size (optional)."
[database crawl-tag crawl-timestamp scraping-fn & [batch-size]]
(let [limit (or batch-size 1000)]
(loop [raw (db/get-pages-for-crawl-tag-and-timestamp database
crawl-tag
crawl-timestamp
limit)]
(db/add-batched-documents database
(map (fn [raw-page]
(assoc (scraping-fn raw-page)
:type "scrape-result"
:uri (:uri raw-page)
:crawled-at (:crawled-at raw-page)
:crawl-tag crawl-tag
:crawl-timestamp crawl-timestamp))
(:documents raw)))
(when-let [{:keys [uri timestamp id]} (:next raw)]
(recur (db/get-pages-for-crawl-tag-and-timestamp database
crawl-tag
crawl-timestamp
limit
uri
timestamp
id)))))) | true | ;; src/alida/scrape.clj: scraping utility functions.
;;
;; Copyright 2012, PI:NAME:<NAME>END_PI & Vixu.com <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 alida.scrape
(:require [clojure.string :as string]
[net.cgrand.enlive-html :as enlive]
[alida.util :as util]
[alida.db :as db])
(:import [java.io StringReader]
[org.jsoup Jsoup]))
(defn content-type-is-html? [request]
"Checks if the Content-Type header for the specified request map
says the document is text/html."
(not (nil? (re-matches #"^text/html.*"
(get (:headers request) "content-type")))))
(defn get-links-enlive
"Returns the set of unique href attribute values from
the elements that match the provided enlive selector
(e.g. [:a]) in the given string using the current-uri
value to turn the links into absolute URIs."
[current-uri s selector]
(into #{}
(map #(util/get-absolute-uri current-uri (:href (:attrs %)))
(enlive/select (enlive/html-resource (StringReader. s))
selector))))
(defn get-links
"Returns the set of unique href attribute values from the elements
that match the provided enlive selector (e.g. [:a]) in the given
string using the provided current-uri to turn the links into absolute
URIs. Optionally also accepts a map with filters as a third argument,
which supports :filter (ran over the absolute URI, including
the hostname and scheme) and :path-filter (only ran over the
path segment of the URI). "
[current-uri
s
selector
& [filters]]
(let [links (get-links-enlive current-uri s selector)]
(if (empty? filters)
links
(loop [filtered-links links
filter-pairs (vec filters)]
(if-let [[filter-name filter-pattern] (first filter-pairs)]
(recur (if (= (class filter-pattern) java.util.regex.Pattern)
(filter
(cond
(= filter-name :filter)
#(re-matches filter-pattern %)
(= filter-name :path-filter)
#(re-matches filter-pattern
(:path (util/get-uri-segments %))))
filtered-links)
filtered-links)
(rest filter-pairs))
filtered-links)))))
(defn get-links-jsoup
"Returns a set of absolute URIs for all links in a given html string
using the provided current-uri as a base. This fn provides less
control than the get-links-enlive fn, but offers much better
performance."
[current-uri html]
(into #{}
(map (fn [element]
(util/get-absolute-uri current-uri (.attr element "href")))
(.select (Jsoup/parse html) "a[href]"))))
(defn #^String html-to-plaintext
"Returns the plaintext value of the provided HTML string.
This function only returns the actual text of the page. This
doesn't include attribute values like image titles. See the
vix/lucene/distill-plaintext fn for an example of a function that
also includes img attributes."
[html]
(.text (Jsoup/parse html)))
(defmulti get-trimmed-content
"Returns a string or sequence of strings (if multiple values are
found) given either a string containing html or the output of
Enlive's html-resource fn as the first argument and a selector
vector as the second argument."
(fn [page selector]
(cond
(string? page) :string
(seq? page) :enlive-resource)))
(defmethod get-trimmed-content :enlive-resource [resource selector]
(let [selection (enlive/select resource selector)]
(cond
(= (count selection) 1)
(string/trim (apply str (:content (first selection))))
(> (count selection) 1)
(map (fn [node]
(string/trim (apply str (:content node))))
selection))))
(defmethod get-trimmed-content :string [html selector]
(get-trimmed-content (enlive/html-resource (StringReader. html)) selector))
(defn extract-and-store-data
"Processes crawl results with the provided crawl-tag and
crawl-timestamp that are stored in the database by running
scraping-fn over them. The scraping-fn should always return a map
or nil. This fn requests and stores documents in quantities of
batch-size (optional)."
[database crawl-tag crawl-timestamp scraping-fn & [batch-size]]
(let [limit (or batch-size 1000)]
(loop [raw (db/get-pages-for-crawl-tag-and-timestamp database
crawl-tag
crawl-timestamp
limit)]
(db/add-batched-documents database
(map (fn [raw-page]
(assoc (scraping-fn raw-page)
:type "scrape-result"
:uri (:uri raw-page)
:crawled-at (:crawled-at raw-page)
:crawl-tag crawl-tag
:crawl-timestamp crawl-timestamp))
(:documents raw)))
(when-let [{:keys [uri timestamp id]} (:next raw)]
(recur (db/get-pages-for-crawl-tag-and-timestamp database
crawl-tag
crawl-timestamp
limit
uri
timestamp
id)))))) |
[
{
"context": " })\n\n(def redis-ec2-spec {\n :env :dev \n :owner \"admin\"\n\n :machine {\n :hostname \"red1\" :user \"ubuntu\"",
"end": 1860,
"score": 0.9340895414352417,
"start": 1855,
"tag": "USERNAME",
"value": "admin"
},
{
"context": " \"admin\"\n\n :machine {\n :hostname \"red1\" :user \"ubuntu\" \n :domain \"local\" :os :ubuntu-12.10\n }\n\n :aw",
"end": 1909,
"score": 0.999299168586731,
"start": 1903,
"tag": "USERNAME",
"value": "ubuntu"
},
{
"context": "aws {\n :instance-type \"t1.micro\" \n :key-name \"Uranus\" \n :endpoint \"ec2.eu-west-1.amazonaws.com\"\n :",
"end": 2013,
"score": 0.9985111355781555,
"start": 2007,
"tag": "KEY",
"value": "Uranus"
}
] | test/subs/test/aws.clj | narkisr/substantiation | 1 | (ns subs.test.aws
(:import clojure.lang.ExceptionInfo)
(:use midje.sweet)
(:require
[clojure.core.strint :refer (<<)]
[subs.core :as subs :refer (validate! combine every-v every-kv validation when-not-nil)])
)
(def machine-entity
{:machine {
:hostname #{:required :String} :domain #{:required :String}
:user #{:required :String} :os #{:required :Keyword}
}})
(def ebs-type #{"io1" "standard" "gp2"})
(validation :ebs-type
(when-not-nil (<< "EBS type must be either ~{ebs-type}")))
(validation :volume {
:device #{:required :String} :size #{:required :Integer}
:clear #{:required :Boolean} :volume-type #{:required :ebs-type}
})
(validation :iops
(fn [{:keys [volume-type iops]}]
(when (and (= volume-type "io1") (nil? iops)) "iops required if io1 type is used")))
(validation :volume* (every-v #{:volume}))
(validation :group* (every-v #{:String}))
(validate! {:volumes {:device "do"}} {:volumes #{:volume}} )
(validate! {:volumes {:device "do"}} {:volumes {:device #{:Integer}}} )
#_(validate! {:groups [{:device "do"}]} {:groups #{:group*}} )
(def aws-entity
{:aws {
:instance-type #{:required :String} :key-name #{:required :String}
:endpoint #{:required :String} :volumes #{:volume*}
:security-groups #{:Vector :group*} :availability-zone #{:String}
:ebs-optimized #{:Boolean}
}})
(defn validate-entity
"aws based systems entity validation "
[aws]
(validate! aws (combine machine-entity aws-entity) :error ::invalid-system))
(def aws-provider
{:instance-type #{:required :String} :key-name #{:required :String}
:placement {:availability-zone #{:String}} :security-groups #{:Vector :group*}
:min-count #{:required :Integer} :max-count #{:required :Integer}
:ebs-optimized #{:Boolean}
})
(def redis-ec2-spec {
:env :dev
:owner "admin"
:machine {
:hostname "red1" :user "ubuntu"
:domain "local" :os :ubuntu-12.10
}
:aws {
:instance-type "t1.micro"
:key-name "Uranus"
:endpoint "ec2.eu-west-1.amazonaws.com"
:ebs-optimized false
}
:type "redis"
})
#_(validate!
(merge-with merge redis-ec2-spec {:aws {:volumes [{:device "do"}]}})
(combine machine-entity aws-entity) :error ::invalid-system)
| 112886 | (ns subs.test.aws
(:import clojure.lang.ExceptionInfo)
(:use midje.sweet)
(:require
[clojure.core.strint :refer (<<)]
[subs.core :as subs :refer (validate! combine every-v every-kv validation when-not-nil)])
)
(def machine-entity
{:machine {
:hostname #{:required :String} :domain #{:required :String}
:user #{:required :String} :os #{:required :Keyword}
}})
(def ebs-type #{"io1" "standard" "gp2"})
(validation :ebs-type
(when-not-nil (<< "EBS type must be either ~{ebs-type}")))
(validation :volume {
:device #{:required :String} :size #{:required :Integer}
:clear #{:required :Boolean} :volume-type #{:required :ebs-type}
})
(validation :iops
(fn [{:keys [volume-type iops]}]
(when (and (= volume-type "io1") (nil? iops)) "iops required if io1 type is used")))
(validation :volume* (every-v #{:volume}))
(validation :group* (every-v #{:String}))
(validate! {:volumes {:device "do"}} {:volumes #{:volume}} )
(validate! {:volumes {:device "do"}} {:volumes {:device #{:Integer}}} )
#_(validate! {:groups [{:device "do"}]} {:groups #{:group*}} )
(def aws-entity
{:aws {
:instance-type #{:required :String} :key-name #{:required :String}
:endpoint #{:required :String} :volumes #{:volume*}
:security-groups #{:Vector :group*} :availability-zone #{:String}
:ebs-optimized #{:Boolean}
}})
(defn validate-entity
"aws based systems entity validation "
[aws]
(validate! aws (combine machine-entity aws-entity) :error ::invalid-system))
(def aws-provider
{:instance-type #{:required :String} :key-name #{:required :String}
:placement {:availability-zone #{:String}} :security-groups #{:Vector :group*}
:min-count #{:required :Integer} :max-count #{:required :Integer}
:ebs-optimized #{:Boolean}
})
(def redis-ec2-spec {
:env :dev
:owner "admin"
:machine {
:hostname "red1" :user "ubuntu"
:domain "local" :os :ubuntu-12.10
}
:aws {
:instance-type "t1.micro"
:key-name "<KEY>"
:endpoint "ec2.eu-west-1.amazonaws.com"
:ebs-optimized false
}
:type "redis"
})
#_(validate!
(merge-with merge redis-ec2-spec {:aws {:volumes [{:device "do"}]}})
(combine machine-entity aws-entity) :error ::invalid-system)
| true | (ns subs.test.aws
(:import clojure.lang.ExceptionInfo)
(:use midje.sweet)
(:require
[clojure.core.strint :refer (<<)]
[subs.core :as subs :refer (validate! combine every-v every-kv validation when-not-nil)])
)
(def machine-entity
{:machine {
:hostname #{:required :String} :domain #{:required :String}
:user #{:required :String} :os #{:required :Keyword}
}})
(def ebs-type #{"io1" "standard" "gp2"})
(validation :ebs-type
(when-not-nil (<< "EBS type must be either ~{ebs-type}")))
(validation :volume {
:device #{:required :String} :size #{:required :Integer}
:clear #{:required :Boolean} :volume-type #{:required :ebs-type}
})
(validation :iops
(fn [{:keys [volume-type iops]}]
(when (and (= volume-type "io1") (nil? iops)) "iops required if io1 type is used")))
(validation :volume* (every-v #{:volume}))
(validation :group* (every-v #{:String}))
(validate! {:volumes {:device "do"}} {:volumes #{:volume}} )
(validate! {:volumes {:device "do"}} {:volumes {:device #{:Integer}}} )
#_(validate! {:groups [{:device "do"}]} {:groups #{:group*}} )
(def aws-entity
{:aws {
:instance-type #{:required :String} :key-name #{:required :String}
:endpoint #{:required :String} :volumes #{:volume*}
:security-groups #{:Vector :group*} :availability-zone #{:String}
:ebs-optimized #{:Boolean}
}})
(defn validate-entity
"aws based systems entity validation "
[aws]
(validate! aws (combine machine-entity aws-entity) :error ::invalid-system))
(def aws-provider
{:instance-type #{:required :String} :key-name #{:required :String}
:placement {:availability-zone #{:String}} :security-groups #{:Vector :group*}
:min-count #{:required :Integer} :max-count #{:required :Integer}
:ebs-optimized #{:Boolean}
})
(def redis-ec2-spec {
:env :dev
:owner "admin"
:machine {
:hostname "red1" :user "ubuntu"
:domain "local" :os :ubuntu-12.10
}
:aws {
:instance-type "t1.micro"
:key-name "PI:KEY:<KEY>END_PI"
:endpoint "ec2.eu-west-1.amazonaws.com"
:ebs-optimized false
}
:type "redis"
})
#_(validate!
(merge-with merge redis-ec2-spec {:aws {:volumes [{:device "do"}]}})
(combine machine-entity aws-entity) :error ::invalid-system)
|
[
{
"context": "ns under the License.\n;;\n;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.\n\n(ns czlab.hoard.drivers\n\n ",
"end": 597,
"score": 0.9998527765274048,
"start": 584,
"tag": "NAME",
"value": "Kenneth Leung"
},
{
"context": "er-url \"jdbc:h2:tcp://host/path/db\")\n;h2-database 1.4.199 works but 1.4.200 fails with MVCC\n;(def h2-fil",
"end": 7945,
"score": 0.5991909503936768,
"start": 7942,
"tag": "IP_ADDRESS",
"value": "1.4"
},
{
"context": "l \"jdbc:h2:tcp://host/path/db\")\n;h2-database 1.4.199 works but 1.4.200 fails with MVCC\n;(def h2-file-",
"end": 7948,
"score": 0.5614405274391174,
"start": 7947,
"tag": "IP_ADDRESS",
"value": "9"
}
] | src/main/clojure/czlab/hoard/drivers.clj | llnek/dbio | 1 | ;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.
(ns czlab.hoard.drivers
"Utility functions for DDL generation."
(:require [clojure.java.io :as io]
[clojure.string :as cs]
[czlab.basal.core :as c]
[czlab.hoard.core :as h])
(:import [clojure.lang Var]
[java.io File]
[java.sql DriverManager Connection Statement]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* true)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gsqlid
"Format SQL identifier."
{:tag String}
([idstr] (gsqlid idstr nil))
([idstr quote?]
(let [{:keys [case-fn qstr]} h/*ddl-cfg*
id (case-fn idstr)]
(if (false? quote?) id (str qstr id qstr)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gtable
"Get the table name (quoted)."
{:tag String}
([model] (gtable model nil))
([model quote?]
{:pre [(map? model)]} (gsqlid (:table model) quote?)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gcolumn
"Get the column name (quoted)."
{:tag String}
([field] (gcolumn field nil))
([field quote?]
{:pre [(map? field)]} (gsqlid (:column field) quote?)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gen-col-def
^String [vt db typedef field]
(let [dft (c/_1 (:dft field))]
(str (c/vt-run?? vt :getPad [db])
(c/vt-run?? vt :genCol [db field])
" " typedef " "
(c/vt-run?? vt :nullClause [db (:null? field)])
(if (c/hgl? dft) (str " default " dft) ""))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gen-ex-indexes
"External indexes."
^String [vt db schema fields model]
(c/sreduce<>
(fn [b [k v]]
(if (empty? v)
b
(c/sbf+ b
"create index "
(c/vt-run?? vt :genIndex [db model (name k)])
" on "
(c/vt-run?? vt :genTable [db model])
" ("
(->> (map #(c/vt-run?? vt :genCol [db (fields %)]) v)
(cs/join "," ))
") "
(c/vt-run?? vt :genExec [db]) "\n\n")))
(:indexes model)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gen-uniques
^String [vt db schema fields model]
(c/sreduce<>
(fn [b [_ v]]
(if (empty? v)
b
(c/sbf-join b
",\n"
(str (c/vt-run?? vt :getPad [db])
"unique("
(cs/join ","
(map #(c/vt-run?? vt
:genCol [db (fields %)]) v))
")"))))
(:uniques model)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gen-pkey
^String [vt db model pks]
(str (c/vt-run?? vt :getPad [db])
"primary key("
(cs/join "," (map #(c/vt-run?? vt :genCol [db %]) pks)) ")"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gen-body
^String [vt db schema model]
(let [{:keys [fields pkey]} model
bf (c/sbf<>)
pkeys
(c/preduce<vec>
(fn [p [k fld]]
(c/sbf-join bf ",\n"
(case (:domain fld)
:Timestamp (c/vt-run?? vt :genTimestamp [db fld])
:Date (c/vt-run?? vt :genDate [db fld])
:Calendar (c/vt-run?? vt :genCaldr [db fld])
:Boolean (c/vt-run?? vt :genBool [db fld])
:Int (if (:auto? fld)
(c/vt-run?? vt :genAutoInteger [db model fld])
(c/vt-run?? vt :genInteger [db fld]))
:Long (if (:auto? fld)
(c/vt-run?? vt :genAutoLong [db model fld])
(c/vt-run?? vt :genLong [db fld]))
:Double (c/vt-run?? vt :genDouble [db fld])
:Float (c/vt-run?? vt :genFloat [db fld])
(:Password :String)
(c/vt-run?? vt :genString [db fld])
:Bytes (c/vt-run?? vt :genBytes [db fld])
(h/dberr! "Unsupported field: %s." fld)))
(if (not= pkey (:id fld))
p
(conj! p fld))) fields)]
(when (pos? (.length bf))
(when-not (empty? pkeys)
(c/sbf+ bf ",\n" (gen-pkey vt db
model pkeys)))
(let [s (gen-uniques vt db
schema fields model)]
(when (c/hgl? s)
(c/sbf+ bf ",\n" s))))
[(str bf)
(gen-ex-indexes vt db schema fields model)]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gen-one-table
^String [vt db schema model]
(let [d (gen-body vt db schema model)
b (c/vt-run?? vt :genBegin [db model])
e (c/vt-run?? vt :genEnd [db])]
(str b
(c/_1 d) e (c/_E d)
(c/vt-run?? vt :genGrant [db model]))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/def- ddl-base
(c/vtbl*
:genExec #(str ";\n" (c/vt-run?? %1 :genSep [%2]))
:getNotNull "not null"
:getNull "null"
:nullClause #(if %3
(c/vt-run?? %1 :getNull [%2])
(c/vt-run?? %1 :getNotNull [%2]))
:genSep (c/fn_2
(if (:use-sep? h/*ddl-cfg*) h/ddl-sep ""))
:genDrop
#(str "drop table "
(gtable %3) (c/vt-run?? %1 :genExec [%2]) "\n\n")
:genBegin
#(str "create table " (gtable %3) " (\n")
:genEnd
#(str "\n) " (c/vt-run?? %1 :genExec [%2]) "\n\n")
:genEndSQL ""
:genGrant ""
:genIndex #(gsqlid (str (:table %3) "_" %4))
:genTable #(gtable %3)
:genCol #(gcolumn %3)
:getPad " "
;; data types
:genBytes
#(gen-col-def %1 %2 (c/vt-run?? %1 :getBlobKwd [%2]) %3)
:genString
#(gen-col-def %1 %2
(str (c/vt-run?? %1 :getStringKwd [%2])
"(" (:size %3) ")") %3)
:genInteger
#(gen-col-def %1 %2 (c/vt-run?? %1 :getIntKwd [%2]) %3)
:genAutoInteger ""
:genDouble
#(gen-col-def %1 %2 (c/vt-run?? %1 :getDoubleKwd [%2]) %3)
:genFloat
#(gen-col-def %1 %2 (c/vt-run?? %1 :getFloatKwd [%2]) %3)
:genLong
#(gen-col-def %1 %2 (c/vt-run?? %1 :getLongKwd [%2]) %3)
:genAutoLong ""
:getTSDefault "CURRENT_TIMESTAMP"
:genTimestamp
#(gen-col-def %1 %2 (c/vt-run?? %1 :getTSKwd [%2]) %3)
:genDate
#(gen-col-def %1 %2 (c/vt-run?? %1 :getDateKwd [%2]) %3)
:genCaldr
#(c/vt-run?? %1 :genTimestamp [%2 %3])
:genBool
#(gen-col-def %1 %2 (c/vt-run?? %1 :getBoolKwd [%2]) %3)
;; keywords
:getDoubleKwd "double precision"
:getStringKwd "varchar"
:getFloatKwd "float"
:getIntKwd "integer"
:getTSKwd "timestamp"
:getDateKwd "date"
:getBoolKwd "integer"
:getLongKwd "bigint"
:getBlobKwd "blob"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;H2 database
(def h2-mem-url "jdbc:h2:mem:{{dbid}};DB_CLOSE_DELAY=-1")
(def h2-server-url "jdbc:h2:tcp://host/path/db")
;h2-database 1.4.199 works but 1.4.200 fails with MVCC
;(def h2-file-url "jdbc:h2:{{path}};MVCC=TRUE")
(def h2-file-url "jdbc:h2:{{path}}")
(def h2-driver "org.h2.Driver")
(def h2-mvcc ";MVCC=TRUE")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; H2
(c/def- ddl-h2
(c/vtbl** ddl-base
:id :h2
:getDateKwd "timestamp"
:getDoubleKwd "double"
:getBlobKwd "blob"
:getFloatKwd "float"
:genAutoInteger
(fn [vt db model field]
(str (c/vt-run?? vt :getPad [db])
(c/vt-run?? vt :genCol [db field])
" "
(c/vt-run?? vt :getIntKwd [db])
(if (:pkey field)
" identity(1) " " auto_increment(1) ")))
:genAutoLong
(fn [vt db model field]
(str (c/vt-run?? vt :getPad [db])
(c/vt-run?? vt :genCol [db field])
" "
(c/vt-run?? vt :getLongKwd [db])
(if (:pkey field)
" identity(1) " " auto_increment(1) ")))
:genBegin
#(str "create cached table " (gtable %3) " (\n" )
:genDrop
#(str "drop table "
(gtable %3)
" if exists cascade"
(c/vt-run?? %1 :genExec [%2]) "\n\n")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn h2db
"Create a H2 database"
{:arglists '([dbDir dbid user pwd])}
[dbDir ^String dbid ^String user ^String pwd]
(c/test-some "file-dir" dbDir)
(c/test-hgl "db-id" dbid)
(c/test-hgl "user" user)
(let [url (doto (io/file dbDir dbid) (.mkdirs))
u (.getCanonicalPath url)
dbUrl (cs/replace h2-file-url "{{path}}" u)]
(c/debug "Creating H2: %s." dbUrl)
(c/wo* [c1 (DriverManager/getConnection dbUrl user pwd)]
(.setAutoCommit c1 true)
(c/wo* [s (.createStatement c1)]
;;(.execute s (str "create user " user " password \"" pwd "\" admin"))
(.execute s "set default_table_type cached"))
(c/wo* [s (.createStatement c1)]
(.execute s "shutdown")))
dbUrl))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn close-h2db
"Close an existing H2 database"
{:arglists '([dbDir dbid user pwd])}
[dbDir ^String dbid ^String user ^String pwd]
(c/test-some "file-dir" dbDir)
(c/test-hgl "db-id" dbid)
(c/test-hgl "user" user)
(let [url (io/file dbDir dbid)
u (.getCanonicalPath url)
dbUrl (cs/replace h2-file-url "{{path}}" u)]
(c/debug "Closing H2: %s." dbUrl)
(c/wo* [c1 (DriverManager/getConnection dbUrl user pwd)]
(.setAutoCommit c1 true)
(c/wo* [s (.createStatement c1)] (.execute s "shutdown")))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;MySQL
(def mysql-driver "com.mysql.jdbc.Driver")
(c/def- ddl-mysql
(c/vtbl** ddl-base
:id :mysql
:getBlobKwd "longblob"
:getTSKwd "timestamp"
:getDoubleKwd "double"
:getFloatKwd "double"
:genEnd #(str "\n) type=InnoDB"
(c/vt-run?? %1 :genExec [%2]) "\n\n")
:genAutoInteger #(str (c/vt-run?? %1 :getPad [%2])
(c/vt-run?? %1 :genCol [%2 %3])
" "
(c/vt-run?? %1 :getIntKwd [%2])
" not null auto_increment")
:genAutoLong #(str (c/vt-run?? %1 :getPad [%2])
(c/vt-run?? %1 :genCol [%2 %3])
" "
(c/vt-run?? %1 :getLongKwd [%2])
" not null auto_increment")
:genDrop #(str "drop table if exists "
(gtable %3)
(c/vt-run?? %1 :genExec [%2]) "\n\n")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;PostgreSQL
(def postgresql-url "jdbc:postgresql://{{host}}:{{port}}/{{db}}")
(def postgresql-driver "org.postgresql.Driver")
(c/def- ddl-postgres
(c/vtbl** ddl-base
:id :postgres
:getTSKwd "timestamp with time zone"
:getBlobKwd "bytea"
:getDoubleKwd "double precision"
:getFloatKwd "real"
:genCaldr #(c/vt-run?? %1 :genTimestamp [%2 %3])
:genAutoInteger #(str (c/vt-run?? %1 :getPad [%2])
(c/vt-run?? %1 :genCol [%2 %3])
" serial"
" not null auto_increment")
:genAutoLong #(str (c/vt-run?? %1 :getPad [%2])
(c/vt-run?? %1 :genCol [%2 %3])
" bigserial"
" not null auto_increment")
:genDrop #(str "drop table if exists "
(gtable %3)
" cascade "
(c/vt-run?? %1 :genExec [%2]) "\n\n")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; SQLServer
(c/def- ddl-sqlserver
(c/vtbl** ddl-base
:id :sqlserver
:getDoubleKwd "float(53)"
:getFloatKwd "float(53)"
:getBlobKwd "image"
:getTSKwd "datetime"
:genAutoInteger #(str (c/vt-run?? %1 :getPad [%2])
(c/vt-run?? %1 :genCol [%2 %3])
" "
(c/vt-run?? %1 :getIntKwd [%2])
(if (:pkey %3)
" identity (1,1) "
" autoincrement "))
:genAutoLong #(str (c/vt-run?? %1 :getPad [%2])
(c/vt-run?? %1 :genCol [%2 %3])
" "
(c/vt-run?? %1 :getLongKwd [%2])
(if (:pkey %3)
" identity (1,1) "
" autoincrement "))
:genDrop #(str "if exists (select * from "
"dbo.sysobjects where id=object_id('"
(gtable %3 false)
"')) drop table "
(gtable %3)
(c/vt-run?? %1 :genExec [%2]) "\n\n")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;Oracle
(defn- create-seq
[vt db m fd]
(let [s (gsqlid (str "S_"
(:table m) "_" (:column fd)))
t (gsqlid (str "T_"
(:table m) "_" (:column fd)))]
(str "create sequence "
s
" start with 1 increment by 1"
(c/vt-run?? vt :genExec [db])
"\n\n"
"create or replace trigger "
t
"\n"
"before insert on "
(gtable m)
"\n"
"referencing new as new\n"
"for each row\n"
"begin\n"
"select "
s
".nextval into :new."
(gcolumn fd) " from dual;\n"
"end" (c/vt-run?? vt :genExec [db]) "\n\n")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- maybe-track-fields
[model field]
(if-not (or (.equals "12c+" (h/*ddl-cfg* :db-version))
(.equals "12c" (h/*ddl-cfg* :db-version)))
(c/let->true [m (deref h/*ddl-bvs*)
t (:id model)
r (or (m t) {})]
(swap! h/*ddl-bvs*
assoc
t
(assoc r (:id field) field)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- auto-xxx
[vt db model fld]
(str (c/vt-run?? vt :getPad [db])
(c/vt-run?? vt :genCol [db fld])
" "
"number generated by default on null as identity."))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/def- ddl-oracle
(c/vtbl** ddl-base
:id :oracle
:getTSDefault "default systimestamp"
:getStringKwd "varchar2"
:getLongKwd "number(38)"
:getDoubleKwd "binary_double"
:getFloatKwd "binary_float"
:genAutoInteger #(if (maybe-track-fields %3 %4)
(c/vt-run?? %1 :genInteger [%2 %4])
(c/vt-run?? %1 :autoXXX [%2 %3 %4]))
:genAutoLong #(if (maybe-track-fields %3 %4)
(c/vt-run?? %1 :genLong [%2 %4])
(auto-xxx %2 %3 %4))
:genEndSQL
#(if (or (.equals "12c+" (h/*ddl-cfg* :db-version))
(.equals "12c" (h/*ddl-cfg* :db-version)))
""
(c/sreduce<>
(fn [bd [model fields]]
(reduce
(fn [bd [_ fld]]
(c/sbf+ bd
(create-seq %2 model fld)))
bd fields))
(deref h/*ddl-bvs*)))
:genDrop #(str "drop table "
(gtable %3)
" cascade constraints purge"
(c/vt-run?? %1 :genExec [%2]) "\n\n")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- find-vtbl
[dbID]
(let [nsp "czlab.hoard.drivers/ddl-"
v (-> (str nsp
(name dbID))
symbol resolve)]
(.deref ^Var v)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn get-ddl
"Generate database DDL for this schema."
{:tag String
:arglists '([schema db]
[schema db dbver])}
([schema db]
(get-ddl schema db nil))
([schema db dbver]
(binding [h/*ddl-cfg* {:db-version (c/strim dbver)
:use-sep? true
:qstr ""
:case-fn clojure.string/upper-case}
h/*ddl-bvs* (atom {})]
(let [ms (:models @schema)
vt (if (keyword? db)
(find-vtbl db)
(do (assert (map? db)) db))
dbID (:id vt)
drops (c/sbf<>)
body (c/sbf<>)]
(doseq [[id model] ms
:let [tbl (:table model)]
:when (and (not (:abstract? model))
(c/hgl? tbl))]
(c/debug "model id: %s, table: %s." (name id) tbl)
(c/sbf+ drops (c/vt-run?? vt :genDrop [dbID model]))
(c/sbf+ body (gen-one-table vt dbID schema model)))
(str drops body (c/vt-run?? vt :genEndSQL [dbID]))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
| 47360 | ;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; Copyright © 2013-2022, <NAME>. All rights reserved.
(ns czlab.hoard.drivers
"Utility functions for DDL generation."
(:require [clojure.java.io :as io]
[clojure.string :as cs]
[czlab.basal.core :as c]
[czlab.hoard.core :as h])
(:import [clojure.lang Var]
[java.io File]
[java.sql DriverManager Connection Statement]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* true)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gsqlid
"Format SQL identifier."
{:tag String}
([idstr] (gsqlid idstr nil))
([idstr quote?]
(let [{:keys [case-fn qstr]} h/*ddl-cfg*
id (case-fn idstr)]
(if (false? quote?) id (str qstr id qstr)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gtable
"Get the table name (quoted)."
{:tag String}
([model] (gtable model nil))
([model quote?]
{:pre [(map? model)]} (gsqlid (:table model) quote?)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gcolumn
"Get the column name (quoted)."
{:tag String}
([field] (gcolumn field nil))
([field quote?]
{:pre [(map? field)]} (gsqlid (:column field) quote?)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gen-col-def
^String [vt db typedef field]
(let [dft (c/_1 (:dft field))]
(str (c/vt-run?? vt :getPad [db])
(c/vt-run?? vt :genCol [db field])
" " typedef " "
(c/vt-run?? vt :nullClause [db (:null? field)])
(if (c/hgl? dft) (str " default " dft) ""))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gen-ex-indexes
"External indexes."
^String [vt db schema fields model]
(c/sreduce<>
(fn [b [k v]]
(if (empty? v)
b
(c/sbf+ b
"create index "
(c/vt-run?? vt :genIndex [db model (name k)])
" on "
(c/vt-run?? vt :genTable [db model])
" ("
(->> (map #(c/vt-run?? vt :genCol [db (fields %)]) v)
(cs/join "," ))
") "
(c/vt-run?? vt :genExec [db]) "\n\n")))
(:indexes model)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gen-uniques
^String [vt db schema fields model]
(c/sreduce<>
(fn [b [_ v]]
(if (empty? v)
b
(c/sbf-join b
",\n"
(str (c/vt-run?? vt :getPad [db])
"unique("
(cs/join ","
(map #(c/vt-run?? vt
:genCol [db (fields %)]) v))
")"))))
(:uniques model)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gen-pkey
^String [vt db model pks]
(str (c/vt-run?? vt :getPad [db])
"primary key("
(cs/join "," (map #(c/vt-run?? vt :genCol [db %]) pks)) ")"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gen-body
^String [vt db schema model]
(let [{:keys [fields pkey]} model
bf (c/sbf<>)
pkeys
(c/preduce<vec>
(fn [p [k fld]]
(c/sbf-join bf ",\n"
(case (:domain fld)
:Timestamp (c/vt-run?? vt :genTimestamp [db fld])
:Date (c/vt-run?? vt :genDate [db fld])
:Calendar (c/vt-run?? vt :genCaldr [db fld])
:Boolean (c/vt-run?? vt :genBool [db fld])
:Int (if (:auto? fld)
(c/vt-run?? vt :genAutoInteger [db model fld])
(c/vt-run?? vt :genInteger [db fld]))
:Long (if (:auto? fld)
(c/vt-run?? vt :genAutoLong [db model fld])
(c/vt-run?? vt :genLong [db fld]))
:Double (c/vt-run?? vt :genDouble [db fld])
:Float (c/vt-run?? vt :genFloat [db fld])
(:Password :String)
(c/vt-run?? vt :genString [db fld])
:Bytes (c/vt-run?? vt :genBytes [db fld])
(h/dberr! "Unsupported field: %s." fld)))
(if (not= pkey (:id fld))
p
(conj! p fld))) fields)]
(when (pos? (.length bf))
(when-not (empty? pkeys)
(c/sbf+ bf ",\n" (gen-pkey vt db
model pkeys)))
(let [s (gen-uniques vt db
schema fields model)]
(when (c/hgl? s)
(c/sbf+ bf ",\n" s))))
[(str bf)
(gen-ex-indexes vt db schema fields model)]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gen-one-table
^String [vt db schema model]
(let [d (gen-body vt db schema model)
b (c/vt-run?? vt :genBegin [db model])
e (c/vt-run?? vt :genEnd [db])]
(str b
(c/_1 d) e (c/_E d)
(c/vt-run?? vt :genGrant [db model]))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/def- ddl-base
(c/vtbl*
:genExec #(str ";\n" (c/vt-run?? %1 :genSep [%2]))
:getNotNull "not null"
:getNull "null"
:nullClause #(if %3
(c/vt-run?? %1 :getNull [%2])
(c/vt-run?? %1 :getNotNull [%2]))
:genSep (c/fn_2
(if (:use-sep? h/*ddl-cfg*) h/ddl-sep ""))
:genDrop
#(str "drop table "
(gtable %3) (c/vt-run?? %1 :genExec [%2]) "\n\n")
:genBegin
#(str "create table " (gtable %3) " (\n")
:genEnd
#(str "\n) " (c/vt-run?? %1 :genExec [%2]) "\n\n")
:genEndSQL ""
:genGrant ""
:genIndex #(gsqlid (str (:table %3) "_" %4))
:genTable #(gtable %3)
:genCol #(gcolumn %3)
:getPad " "
;; data types
:genBytes
#(gen-col-def %1 %2 (c/vt-run?? %1 :getBlobKwd [%2]) %3)
:genString
#(gen-col-def %1 %2
(str (c/vt-run?? %1 :getStringKwd [%2])
"(" (:size %3) ")") %3)
:genInteger
#(gen-col-def %1 %2 (c/vt-run?? %1 :getIntKwd [%2]) %3)
:genAutoInteger ""
:genDouble
#(gen-col-def %1 %2 (c/vt-run?? %1 :getDoubleKwd [%2]) %3)
:genFloat
#(gen-col-def %1 %2 (c/vt-run?? %1 :getFloatKwd [%2]) %3)
:genLong
#(gen-col-def %1 %2 (c/vt-run?? %1 :getLongKwd [%2]) %3)
:genAutoLong ""
:getTSDefault "CURRENT_TIMESTAMP"
:genTimestamp
#(gen-col-def %1 %2 (c/vt-run?? %1 :getTSKwd [%2]) %3)
:genDate
#(gen-col-def %1 %2 (c/vt-run?? %1 :getDateKwd [%2]) %3)
:genCaldr
#(c/vt-run?? %1 :genTimestamp [%2 %3])
:genBool
#(gen-col-def %1 %2 (c/vt-run?? %1 :getBoolKwd [%2]) %3)
;; keywords
:getDoubleKwd "double precision"
:getStringKwd "varchar"
:getFloatKwd "float"
:getIntKwd "integer"
:getTSKwd "timestamp"
:getDateKwd "date"
:getBoolKwd "integer"
:getLongKwd "bigint"
:getBlobKwd "blob"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;H2 database
(def h2-mem-url "jdbc:h2:mem:{{dbid}};DB_CLOSE_DELAY=-1")
(def h2-server-url "jdbc:h2:tcp://host/path/db")
;h2-database 1.4.199 works but 1.4.200 fails with MVCC
;(def h2-file-url "jdbc:h2:{{path}};MVCC=TRUE")
(def h2-file-url "jdbc:h2:{{path}}")
(def h2-driver "org.h2.Driver")
(def h2-mvcc ";MVCC=TRUE")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; H2
(c/def- ddl-h2
(c/vtbl** ddl-base
:id :h2
:getDateKwd "timestamp"
:getDoubleKwd "double"
:getBlobKwd "blob"
:getFloatKwd "float"
:genAutoInteger
(fn [vt db model field]
(str (c/vt-run?? vt :getPad [db])
(c/vt-run?? vt :genCol [db field])
" "
(c/vt-run?? vt :getIntKwd [db])
(if (:pkey field)
" identity(1) " " auto_increment(1) ")))
:genAutoLong
(fn [vt db model field]
(str (c/vt-run?? vt :getPad [db])
(c/vt-run?? vt :genCol [db field])
" "
(c/vt-run?? vt :getLongKwd [db])
(if (:pkey field)
" identity(1) " " auto_increment(1) ")))
:genBegin
#(str "create cached table " (gtable %3) " (\n" )
:genDrop
#(str "drop table "
(gtable %3)
" if exists cascade"
(c/vt-run?? %1 :genExec [%2]) "\n\n")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn h2db
"Create a H2 database"
{:arglists '([dbDir dbid user pwd])}
[dbDir ^String dbid ^String user ^String pwd]
(c/test-some "file-dir" dbDir)
(c/test-hgl "db-id" dbid)
(c/test-hgl "user" user)
(let [url (doto (io/file dbDir dbid) (.mkdirs))
u (.getCanonicalPath url)
dbUrl (cs/replace h2-file-url "{{path}}" u)]
(c/debug "Creating H2: %s." dbUrl)
(c/wo* [c1 (DriverManager/getConnection dbUrl user pwd)]
(.setAutoCommit c1 true)
(c/wo* [s (.createStatement c1)]
;;(.execute s (str "create user " user " password \"" pwd "\" admin"))
(.execute s "set default_table_type cached"))
(c/wo* [s (.createStatement c1)]
(.execute s "shutdown")))
dbUrl))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn close-h2db
"Close an existing H2 database"
{:arglists '([dbDir dbid user pwd])}
[dbDir ^String dbid ^String user ^String pwd]
(c/test-some "file-dir" dbDir)
(c/test-hgl "db-id" dbid)
(c/test-hgl "user" user)
(let [url (io/file dbDir dbid)
u (.getCanonicalPath url)
dbUrl (cs/replace h2-file-url "{{path}}" u)]
(c/debug "Closing H2: %s." dbUrl)
(c/wo* [c1 (DriverManager/getConnection dbUrl user pwd)]
(.setAutoCommit c1 true)
(c/wo* [s (.createStatement c1)] (.execute s "shutdown")))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;MySQL
(def mysql-driver "com.mysql.jdbc.Driver")
(c/def- ddl-mysql
(c/vtbl** ddl-base
:id :mysql
:getBlobKwd "longblob"
:getTSKwd "timestamp"
:getDoubleKwd "double"
:getFloatKwd "double"
:genEnd #(str "\n) type=InnoDB"
(c/vt-run?? %1 :genExec [%2]) "\n\n")
:genAutoInteger #(str (c/vt-run?? %1 :getPad [%2])
(c/vt-run?? %1 :genCol [%2 %3])
" "
(c/vt-run?? %1 :getIntKwd [%2])
" not null auto_increment")
:genAutoLong #(str (c/vt-run?? %1 :getPad [%2])
(c/vt-run?? %1 :genCol [%2 %3])
" "
(c/vt-run?? %1 :getLongKwd [%2])
" not null auto_increment")
:genDrop #(str "drop table if exists "
(gtable %3)
(c/vt-run?? %1 :genExec [%2]) "\n\n")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;PostgreSQL
(def postgresql-url "jdbc:postgresql://{{host}}:{{port}}/{{db}}")
(def postgresql-driver "org.postgresql.Driver")
(c/def- ddl-postgres
(c/vtbl** ddl-base
:id :postgres
:getTSKwd "timestamp with time zone"
:getBlobKwd "bytea"
:getDoubleKwd "double precision"
:getFloatKwd "real"
:genCaldr #(c/vt-run?? %1 :genTimestamp [%2 %3])
:genAutoInteger #(str (c/vt-run?? %1 :getPad [%2])
(c/vt-run?? %1 :genCol [%2 %3])
" serial"
" not null auto_increment")
:genAutoLong #(str (c/vt-run?? %1 :getPad [%2])
(c/vt-run?? %1 :genCol [%2 %3])
" bigserial"
" not null auto_increment")
:genDrop #(str "drop table if exists "
(gtable %3)
" cascade "
(c/vt-run?? %1 :genExec [%2]) "\n\n")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; SQLServer
(c/def- ddl-sqlserver
(c/vtbl** ddl-base
:id :sqlserver
:getDoubleKwd "float(53)"
:getFloatKwd "float(53)"
:getBlobKwd "image"
:getTSKwd "datetime"
:genAutoInteger #(str (c/vt-run?? %1 :getPad [%2])
(c/vt-run?? %1 :genCol [%2 %3])
" "
(c/vt-run?? %1 :getIntKwd [%2])
(if (:pkey %3)
" identity (1,1) "
" autoincrement "))
:genAutoLong #(str (c/vt-run?? %1 :getPad [%2])
(c/vt-run?? %1 :genCol [%2 %3])
" "
(c/vt-run?? %1 :getLongKwd [%2])
(if (:pkey %3)
" identity (1,1) "
" autoincrement "))
:genDrop #(str "if exists (select * from "
"dbo.sysobjects where id=object_id('"
(gtable %3 false)
"')) drop table "
(gtable %3)
(c/vt-run?? %1 :genExec [%2]) "\n\n")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;Oracle
(defn- create-seq
[vt db m fd]
(let [s (gsqlid (str "S_"
(:table m) "_" (:column fd)))
t (gsqlid (str "T_"
(:table m) "_" (:column fd)))]
(str "create sequence "
s
" start with 1 increment by 1"
(c/vt-run?? vt :genExec [db])
"\n\n"
"create or replace trigger "
t
"\n"
"before insert on "
(gtable m)
"\n"
"referencing new as new\n"
"for each row\n"
"begin\n"
"select "
s
".nextval into :new."
(gcolumn fd) " from dual;\n"
"end" (c/vt-run?? vt :genExec [db]) "\n\n")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- maybe-track-fields
[model field]
(if-not (or (.equals "12c+" (h/*ddl-cfg* :db-version))
(.equals "12c" (h/*ddl-cfg* :db-version)))
(c/let->true [m (deref h/*ddl-bvs*)
t (:id model)
r (or (m t) {})]
(swap! h/*ddl-bvs*
assoc
t
(assoc r (:id field) field)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- auto-xxx
[vt db model fld]
(str (c/vt-run?? vt :getPad [db])
(c/vt-run?? vt :genCol [db fld])
" "
"number generated by default on null as identity."))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/def- ddl-oracle
(c/vtbl** ddl-base
:id :oracle
:getTSDefault "default systimestamp"
:getStringKwd "varchar2"
:getLongKwd "number(38)"
:getDoubleKwd "binary_double"
:getFloatKwd "binary_float"
:genAutoInteger #(if (maybe-track-fields %3 %4)
(c/vt-run?? %1 :genInteger [%2 %4])
(c/vt-run?? %1 :autoXXX [%2 %3 %4]))
:genAutoLong #(if (maybe-track-fields %3 %4)
(c/vt-run?? %1 :genLong [%2 %4])
(auto-xxx %2 %3 %4))
:genEndSQL
#(if (or (.equals "12c+" (h/*ddl-cfg* :db-version))
(.equals "12c" (h/*ddl-cfg* :db-version)))
""
(c/sreduce<>
(fn [bd [model fields]]
(reduce
(fn [bd [_ fld]]
(c/sbf+ bd
(create-seq %2 model fld)))
bd fields))
(deref h/*ddl-bvs*)))
:genDrop #(str "drop table "
(gtable %3)
" cascade constraints purge"
(c/vt-run?? %1 :genExec [%2]) "\n\n")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- find-vtbl
[dbID]
(let [nsp "czlab.hoard.drivers/ddl-"
v (-> (str nsp
(name dbID))
symbol resolve)]
(.deref ^Var v)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn get-ddl
"Generate database DDL for this schema."
{:tag String
:arglists '([schema db]
[schema db dbver])}
([schema db]
(get-ddl schema db nil))
([schema db dbver]
(binding [h/*ddl-cfg* {:db-version (c/strim dbver)
:use-sep? true
:qstr ""
:case-fn clojure.string/upper-case}
h/*ddl-bvs* (atom {})]
(let [ms (:models @schema)
vt (if (keyword? db)
(find-vtbl db)
(do (assert (map? db)) db))
dbID (:id vt)
drops (c/sbf<>)
body (c/sbf<>)]
(doseq [[id model] ms
:let [tbl (:table model)]
:when (and (not (:abstract? model))
(c/hgl? tbl))]
(c/debug "model id: %s, table: %s." (name id) tbl)
(c/sbf+ drops (c/vt-run?? vt :genDrop [dbID model]))
(c/sbf+ body (gen-one-table vt dbID schema model)))
(str drops body (c/vt-run?? vt :genEndSQL [dbID]))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
| true | ;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; Copyright © 2013-2022, PI:NAME:<NAME>END_PI. All rights reserved.
(ns czlab.hoard.drivers
"Utility functions for DDL generation."
(:require [clojure.java.io :as io]
[clojure.string :as cs]
[czlab.basal.core :as c]
[czlab.hoard.core :as h])
(:import [clojure.lang Var]
[java.io File]
[java.sql DriverManager Connection Statement]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* true)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gsqlid
"Format SQL identifier."
{:tag String}
([idstr] (gsqlid idstr nil))
([idstr quote?]
(let [{:keys [case-fn qstr]} h/*ddl-cfg*
id (case-fn idstr)]
(if (false? quote?) id (str qstr id qstr)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gtable
"Get the table name (quoted)."
{:tag String}
([model] (gtable model nil))
([model quote?]
{:pre [(map? model)]} (gsqlid (:table model) quote?)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gcolumn
"Get the column name (quoted)."
{:tag String}
([field] (gcolumn field nil))
([field quote?]
{:pre [(map? field)]} (gsqlid (:column field) quote?)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gen-col-def
^String [vt db typedef field]
(let [dft (c/_1 (:dft field))]
(str (c/vt-run?? vt :getPad [db])
(c/vt-run?? vt :genCol [db field])
" " typedef " "
(c/vt-run?? vt :nullClause [db (:null? field)])
(if (c/hgl? dft) (str " default " dft) ""))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gen-ex-indexes
"External indexes."
^String [vt db schema fields model]
(c/sreduce<>
(fn [b [k v]]
(if (empty? v)
b
(c/sbf+ b
"create index "
(c/vt-run?? vt :genIndex [db model (name k)])
" on "
(c/vt-run?? vt :genTable [db model])
" ("
(->> (map #(c/vt-run?? vt :genCol [db (fields %)]) v)
(cs/join "," ))
") "
(c/vt-run?? vt :genExec [db]) "\n\n")))
(:indexes model)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gen-uniques
^String [vt db schema fields model]
(c/sreduce<>
(fn [b [_ v]]
(if (empty? v)
b
(c/sbf-join b
",\n"
(str (c/vt-run?? vt :getPad [db])
"unique("
(cs/join ","
(map #(c/vt-run?? vt
:genCol [db (fields %)]) v))
")"))))
(:uniques model)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gen-pkey
^String [vt db model pks]
(str (c/vt-run?? vt :getPad [db])
"primary key("
(cs/join "," (map #(c/vt-run?? vt :genCol [db %]) pks)) ")"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gen-body
^String [vt db schema model]
(let [{:keys [fields pkey]} model
bf (c/sbf<>)
pkeys
(c/preduce<vec>
(fn [p [k fld]]
(c/sbf-join bf ",\n"
(case (:domain fld)
:Timestamp (c/vt-run?? vt :genTimestamp [db fld])
:Date (c/vt-run?? vt :genDate [db fld])
:Calendar (c/vt-run?? vt :genCaldr [db fld])
:Boolean (c/vt-run?? vt :genBool [db fld])
:Int (if (:auto? fld)
(c/vt-run?? vt :genAutoInteger [db model fld])
(c/vt-run?? vt :genInteger [db fld]))
:Long (if (:auto? fld)
(c/vt-run?? vt :genAutoLong [db model fld])
(c/vt-run?? vt :genLong [db fld]))
:Double (c/vt-run?? vt :genDouble [db fld])
:Float (c/vt-run?? vt :genFloat [db fld])
(:Password :String)
(c/vt-run?? vt :genString [db fld])
:Bytes (c/vt-run?? vt :genBytes [db fld])
(h/dberr! "Unsupported field: %s." fld)))
(if (not= pkey (:id fld))
p
(conj! p fld))) fields)]
(when (pos? (.length bf))
(when-not (empty? pkeys)
(c/sbf+ bf ",\n" (gen-pkey vt db
model pkeys)))
(let [s (gen-uniques vt db
schema fields model)]
(when (c/hgl? s)
(c/sbf+ bf ",\n" s))))
[(str bf)
(gen-ex-indexes vt db schema fields model)]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gen-one-table
^String [vt db schema model]
(let [d (gen-body vt db schema model)
b (c/vt-run?? vt :genBegin [db model])
e (c/vt-run?? vt :genEnd [db])]
(str b
(c/_1 d) e (c/_E d)
(c/vt-run?? vt :genGrant [db model]))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/def- ddl-base
(c/vtbl*
:genExec #(str ";\n" (c/vt-run?? %1 :genSep [%2]))
:getNotNull "not null"
:getNull "null"
:nullClause #(if %3
(c/vt-run?? %1 :getNull [%2])
(c/vt-run?? %1 :getNotNull [%2]))
:genSep (c/fn_2
(if (:use-sep? h/*ddl-cfg*) h/ddl-sep ""))
:genDrop
#(str "drop table "
(gtable %3) (c/vt-run?? %1 :genExec [%2]) "\n\n")
:genBegin
#(str "create table " (gtable %3) " (\n")
:genEnd
#(str "\n) " (c/vt-run?? %1 :genExec [%2]) "\n\n")
:genEndSQL ""
:genGrant ""
:genIndex #(gsqlid (str (:table %3) "_" %4))
:genTable #(gtable %3)
:genCol #(gcolumn %3)
:getPad " "
;; data types
:genBytes
#(gen-col-def %1 %2 (c/vt-run?? %1 :getBlobKwd [%2]) %3)
:genString
#(gen-col-def %1 %2
(str (c/vt-run?? %1 :getStringKwd [%2])
"(" (:size %3) ")") %3)
:genInteger
#(gen-col-def %1 %2 (c/vt-run?? %1 :getIntKwd [%2]) %3)
:genAutoInteger ""
:genDouble
#(gen-col-def %1 %2 (c/vt-run?? %1 :getDoubleKwd [%2]) %3)
:genFloat
#(gen-col-def %1 %2 (c/vt-run?? %1 :getFloatKwd [%2]) %3)
:genLong
#(gen-col-def %1 %2 (c/vt-run?? %1 :getLongKwd [%2]) %3)
:genAutoLong ""
:getTSDefault "CURRENT_TIMESTAMP"
:genTimestamp
#(gen-col-def %1 %2 (c/vt-run?? %1 :getTSKwd [%2]) %3)
:genDate
#(gen-col-def %1 %2 (c/vt-run?? %1 :getDateKwd [%2]) %3)
:genCaldr
#(c/vt-run?? %1 :genTimestamp [%2 %3])
:genBool
#(gen-col-def %1 %2 (c/vt-run?? %1 :getBoolKwd [%2]) %3)
;; keywords
:getDoubleKwd "double precision"
:getStringKwd "varchar"
:getFloatKwd "float"
:getIntKwd "integer"
:getTSKwd "timestamp"
:getDateKwd "date"
:getBoolKwd "integer"
:getLongKwd "bigint"
:getBlobKwd "blob"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;H2 database
(def h2-mem-url "jdbc:h2:mem:{{dbid}};DB_CLOSE_DELAY=-1")
(def h2-server-url "jdbc:h2:tcp://host/path/db")
;h2-database 1.4.199 works but 1.4.200 fails with MVCC
;(def h2-file-url "jdbc:h2:{{path}};MVCC=TRUE")
(def h2-file-url "jdbc:h2:{{path}}")
(def h2-driver "org.h2.Driver")
(def h2-mvcc ";MVCC=TRUE")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; H2
(c/def- ddl-h2
(c/vtbl** ddl-base
:id :h2
:getDateKwd "timestamp"
:getDoubleKwd "double"
:getBlobKwd "blob"
:getFloatKwd "float"
:genAutoInteger
(fn [vt db model field]
(str (c/vt-run?? vt :getPad [db])
(c/vt-run?? vt :genCol [db field])
" "
(c/vt-run?? vt :getIntKwd [db])
(if (:pkey field)
" identity(1) " " auto_increment(1) ")))
:genAutoLong
(fn [vt db model field]
(str (c/vt-run?? vt :getPad [db])
(c/vt-run?? vt :genCol [db field])
" "
(c/vt-run?? vt :getLongKwd [db])
(if (:pkey field)
" identity(1) " " auto_increment(1) ")))
:genBegin
#(str "create cached table " (gtable %3) " (\n" )
:genDrop
#(str "drop table "
(gtable %3)
" if exists cascade"
(c/vt-run?? %1 :genExec [%2]) "\n\n")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn h2db
"Create a H2 database"
{:arglists '([dbDir dbid user pwd])}
[dbDir ^String dbid ^String user ^String pwd]
(c/test-some "file-dir" dbDir)
(c/test-hgl "db-id" dbid)
(c/test-hgl "user" user)
(let [url (doto (io/file dbDir dbid) (.mkdirs))
u (.getCanonicalPath url)
dbUrl (cs/replace h2-file-url "{{path}}" u)]
(c/debug "Creating H2: %s." dbUrl)
(c/wo* [c1 (DriverManager/getConnection dbUrl user pwd)]
(.setAutoCommit c1 true)
(c/wo* [s (.createStatement c1)]
;;(.execute s (str "create user " user " password \"" pwd "\" admin"))
(.execute s "set default_table_type cached"))
(c/wo* [s (.createStatement c1)]
(.execute s "shutdown")))
dbUrl))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn close-h2db
"Close an existing H2 database"
{:arglists '([dbDir dbid user pwd])}
[dbDir ^String dbid ^String user ^String pwd]
(c/test-some "file-dir" dbDir)
(c/test-hgl "db-id" dbid)
(c/test-hgl "user" user)
(let [url (io/file dbDir dbid)
u (.getCanonicalPath url)
dbUrl (cs/replace h2-file-url "{{path}}" u)]
(c/debug "Closing H2: %s." dbUrl)
(c/wo* [c1 (DriverManager/getConnection dbUrl user pwd)]
(.setAutoCommit c1 true)
(c/wo* [s (.createStatement c1)] (.execute s "shutdown")))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;MySQL
(def mysql-driver "com.mysql.jdbc.Driver")
(c/def- ddl-mysql
(c/vtbl** ddl-base
:id :mysql
:getBlobKwd "longblob"
:getTSKwd "timestamp"
:getDoubleKwd "double"
:getFloatKwd "double"
:genEnd #(str "\n) type=InnoDB"
(c/vt-run?? %1 :genExec [%2]) "\n\n")
:genAutoInteger #(str (c/vt-run?? %1 :getPad [%2])
(c/vt-run?? %1 :genCol [%2 %3])
" "
(c/vt-run?? %1 :getIntKwd [%2])
" not null auto_increment")
:genAutoLong #(str (c/vt-run?? %1 :getPad [%2])
(c/vt-run?? %1 :genCol [%2 %3])
" "
(c/vt-run?? %1 :getLongKwd [%2])
" not null auto_increment")
:genDrop #(str "drop table if exists "
(gtable %3)
(c/vt-run?? %1 :genExec [%2]) "\n\n")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;PostgreSQL
(def postgresql-url "jdbc:postgresql://{{host}}:{{port}}/{{db}}")
(def postgresql-driver "org.postgresql.Driver")
(c/def- ddl-postgres
(c/vtbl** ddl-base
:id :postgres
:getTSKwd "timestamp with time zone"
:getBlobKwd "bytea"
:getDoubleKwd "double precision"
:getFloatKwd "real"
:genCaldr #(c/vt-run?? %1 :genTimestamp [%2 %3])
:genAutoInteger #(str (c/vt-run?? %1 :getPad [%2])
(c/vt-run?? %1 :genCol [%2 %3])
" serial"
" not null auto_increment")
:genAutoLong #(str (c/vt-run?? %1 :getPad [%2])
(c/vt-run?? %1 :genCol [%2 %3])
" bigserial"
" not null auto_increment")
:genDrop #(str "drop table if exists "
(gtable %3)
" cascade "
(c/vt-run?? %1 :genExec [%2]) "\n\n")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; SQLServer
(c/def- ddl-sqlserver
(c/vtbl** ddl-base
:id :sqlserver
:getDoubleKwd "float(53)"
:getFloatKwd "float(53)"
:getBlobKwd "image"
:getTSKwd "datetime"
:genAutoInteger #(str (c/vt-run?? %1 :getPad [%2])
(c/vt-run?? %1 :genCol [%2 %3])
" "
(c/vt-run?? %1 :getIntKwd [%2])
(if (:pkey %3)
" identity (1,1) "
" autoincrement "))
:genAutoLong #(str (c/vt-run?? %1 :getPad [%2])
(c/vt-run?? %1 :genCol [%2 %3])
" "
(c/vt-run?? %1 :getLongKwd [%2])
(if (:pkey %3)
" identity (1,1) "
" autoincrement "))
:genDrop #(str "if exists (select * from "
"dbo.sysobjects where id=object_id('"
(gtable %3 false)
"')) drop table "
(gtable %3)
(c/vt-run?? %1 :genExec [%2]) "\n\n")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;Oracle
(defn- create-seq
[vt db m fd]
(let [s (gsqlid (str "S_"
(:table m) "_" (:column fd)))
t (gsqlid (str "T_"
(:table m) "_" (:column fd)))]
(str "create sequence "
s
" start with 1 increment by 1"
(c/vt-run?? vt :genExec [db])
"\n\n"
"create or replace trigger "
t
"\n"
"before insert on "
(gtable m)
"\n"
"referencing new as new\n"
"for each row\n"
"begin\n"
"select "
s
".nextval into :new."
(gcolumn fd) " from dual;\n"
"end" (c/vt-run?? vt :genExec [db]) "\n\n")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- maybe-track-fields
[model field]
(if-not (or (.equals "12c+" (h/*ddl-cfg* :db-version))
(.equals "12c" (h/*ddl-cfg* :db-version)))
(c/let->true [m (deref h/*ddl-bvs*)
t (:id model)
r (or (m t) {})]
(swap! h/*ddl-bvs*
assoc
t
(assoc r (:id field) field)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- auto-xxx
[vt db model fld]
(str (c/vt-run?? vt :getPad [db])
(c/vt-run?? vt :genCol [db fld])
" "
"number generated by default on null as identity."))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/def- ddl-oracle
(c/vtbl** ddl-base
:id :oracle
:getTSDefault "default systimestamp"
:getStringKwd "varchar2"
:getLongKwd "number(38)"
:getDoubleKwd "binary_double"
:getFloatKwd "binary_float"
:genAutoInteger #(if (maybe-track-fields %3 %4)
(c/vt-run?? %1 :genInteger [%2 %4])
(c/vt-run?? %1 :autoXXX [%2 %3 %4]))
:genAutoLong #(if (maybe-track-fields %3 %4)
(c/vt-run?? %1 :genLong [%2 %4])
(auto-xxx %2 %3 %4))
:genEndSQL
#(if (or (.equals "12c+" (h/*ddl-cfg* :db-version))
(.equals "12c" (h/*ddl-cfg* :db-version)))
""
(c/sreduce<>
(fn [bd [model fields]]
(reduce
(fn [bd [_ fld]]
(c/sbf+ bd
(create-seq %2 model fld)))
bd fields))
(deref h/*ddl-bvs*)))
:genDrop #(str "drop table "
(gtable %3)
" cascade constraints purge"
(c/vt-run?? %1 :genExec [%2]) "\n\n")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- find-vtbl
[dbID]
(let [nsp "czlab.hoard.drivers/ddl-"
v (-> (str nsp
(name dbID))
symbol resolve)]
(.deref ^Var v)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn get-ddl
"Generate database DDL for this schema."
{:tag String
:arglists '([schema db]
[schema db dbver])}
([schema db]
(get-ddl schema db nil))
([schema db dbver]
(binding [h/*ddl-cfg* {:db-version (c/strim dbver)
:use-sep? true
:qstr ""
:case-fn clojure.string/upper-case}
h/*ddl-bvs* (atom {})]
(let [ms (:models @schema)
vt (if (keyword? db)
(find-vtbl db)
(do (assert (map? db)) db))
dbID (:id vt)
drops (c/sbf<>)
body (c/sbf<>)]
(doseq [[id model] ms
:let [tbl (:table model)]
:when (and (not (:abstract? model))
(c/hgl? tbl))]
(c/debug "model id: %s, table: %s." (name id) tbl)
(c/sbf+ drops (c/vt-run?? vt :genDrop [dbID model]))
(c/sbf+ body (gen-one-table vt dbID schema model)))
(str drops body (c/vt-run?? vt :genEndSQL [dbID]))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
|
[
{
"context": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n; Copyright 2015 Xebia B.V.\n;\n; Licensed under the Apache License, Version 2",
"end": 107,
"score": 0.9974423050880432,
"start": 98,
"tag": "NAME",
"value": "Xebia B.V"
}
] | src/main/clojure/com/xebia/visualreview/service/image/persistence.clj | andstepanuk/VisualReview | 290 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Copyright 2015 Xebia B.V.
;
; Licensed under the Apache License, Version 2.0 (the "License")
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns com.xebia.visualreview.service.image.persistence
(:require [com.xebia.visualreview.service.persistence.util :as putil]
[slingshot.slingshot :as ex]))
(defn insert-image!
"Adds a new image to the database. Returns the new image's ID."
[conn directory]
(putil/insert-single! conn :image { :directory directory }))
(defn get-image-path
"Gets the path of an image with the given image ID.
The path will contain the directory structure and file name of the image
relative to the screenshot directory. Example: '2015/1/15/22/1.png'."
[conn image-id]
(let [image (putil/query-single conn
["SELECT id, directory FROM image WHERE id = ?" image-id])
directory (:directory image)
id (:id image)]
(if (nil? image)
nil
(str directory "/" id ".png"))
))
(defn get-unused-image-ids [conn]
"Returns a vector of image id's that are not referenced in any diff or screenshot"
(putil/query conn ["SELECT id FROM image WHERE id NOT IN (SELECT image_id FROM screenshot) AND id NOT IN (SELECT image_id FROM diff) AND id NOT IN (SELECT mask_image_id FROM diff)"]
:row-fn :id
:result-set-fn vec))
(defn delete-image!
"Removes the image with the given image-id from the database"
[conn image-id]
(putil/delete! conn :image ["id = ? " image-id])) | 46645 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Copyright 2015 <NAME>.
;
; Licensed under the Apache License, Version 2.0 (the "License")
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns com.xebia.visualreview.service.image.persistence
(:require [com.xebia.visualreview.service.persistence.util :as putil]
[slingshot.slingshot :as ex]))
(defn insert-image!
"Adds a new image to the database. Returns the new image's ID."
[conn directory]
(putil/insert-single! conn :image { :directory directory }))
(defn get-image-path
"Gets the path of an image with the given image ID.
The path will contain the directory structure and file name of the image
relative to the screenshot directory. Example: '2015/1/15/22/1.png'."
[conn image-id]
(let [image (putil/query-single conn
["SELECT id, directory FROM image WHERE id = ?" image-id])
directory (:directory image)
id (:id image)]
(if (nil? image)
nil
(str directory "/" id ".png"))
))
(defn get-unused-image-ids [conn]
"Returns a vector of image id's that are not referenced in any diff or screenshot"
(putil/query conn ["SELECT id FROM image WHERE id NOT IN (SELECT image_id FROM screenshot) AND id NOT IN (SELECT image_id FROM diff) AND id NOT IN (SELECT mask_image_id FROM diff)"]
:row-fn :id
:result-set-fn vec))
(defn delete-image!
"Removes the image with the given image-id from the database"
[conn image-id]
(putil/delete! conn :image ["id = ? " image-id])) | true | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Copyright 2015 PI:NAME:<NAME>END_PI.
;
; Licensed under the Apache License, Version 2.0 (the "License")
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns com.xebia.visualreview.service.image.persistence
(:require [com.xebia.visualreview.service.persistence.util :as putil]
[slingshot.slingshot :as ex]))
(defn insert-image!
"Adds a new image to the database. Returns the new image's ID."
[conn directory]
(putil/insert-single! conn :image { :directory directory }))
(defn get-image-path
"Gets the path of an image with the given image ID.
The path will contain the directory structure and file name of the image
relative to the screenshot directory. Example: '2015/1/15/22/1.png'."
[conn image-id]
(let [image (putil/query-single conn
["SELECT id, directory FROM image WHERE id = ?" image-id])
directory (:directory image)
id (:id image)]
(if (nil? image)
nil
(str directory "/" id ".png"))
))
(defn get-unused-image-ids [conn]
"Returns a vector of image id's that are not referenced in any diff or screenshot"
(putil/query conn ["SELECT id FROM image WHERE id NOT IN (SELECT image_id FROM screenshot) AND id NOT IN (SELECT image_id FROM diff) AND id NOT IN (SELECT mask_image_id FROM diff)"]
:row-fn :id
:result-set-fn vec))
(defn delete-image!
"Removes the image with the given image-id from the database"
[conn image-id]
(putil/delete! conn :image ["id = ? " image-id])) |
[
{
"context": " (change-password username [\"currentPasswordId\" \"newPasswordId\" \"reNewPasswordId\"]))} \"update\"]]",
"end": 689,
"score": 0.9320079684257507,
"start": 672,
"tag": "PASSWORD",
"value": "currentPasswordId"
},
{
"context": " (change-password username [\"currentPasswordId\" \"newPasswordId\" \"reNewPasswordId\"]))} \"update\"]]\n [:td]]]])\n",
"end": 705,
"score": 0.988699734210968,
"start": 692,
"tag": "PASSWORD",
"value": "newPasswordId"
},
{
"context": "rd username [\"currentPasswordId\" \"newPasswordId\" \"reNewPasswordId\"]))} \"update\"]]\n [:td]]]])\n",
"end": 723,
"score": 0.9951132535934448,
"start": 708,
"tag": "PASSWORD",
"value": "reNewPasswordId"
}
] | src/cljs/view/changepassword.cljs | wuleicanada/ClojureNews | 254 | (ns view.changepassword)
(defn component
[username change-password]
[:table
[:tbody
[:tr
[:td "current password:"]
[:td
[:input {:id "currentPasswordId" :name "current-password" :type "password"}]]]
[:tr
[:td
[:br]]]
[:tr
[:td "new password:"]
[:td
[:input {:id "newPasswordId" :name "new-password" :type "password"}]]]
[:tr
[:td "re-new password:"]
[:td
[:input {:id "reNewPasswordId" :name "re-new-password" :type "password"}]]]
[:tr
[:td
[:button {:id "buttonUpdateId" :on-click (fn [_]
(change-password username ["currentPasswordId" "newPasswordId" "reNewPasswordId"]))} "update"]]
[:td]]]])
| 68082 | (ns view.changepassword)
(defn component
[username change-password]
[:table
[:tbody
[:tr
[:td "current password:"]
[:td
[:input {:id "currentPasswordId" :name "current-password" :type "password"}]]]
[:tr
[:td
[:br]]]
[:tr
[:td "new password:"]
[:td
[:input {:id "newPasswordId" :name "new-password" :type "password"}]]]
[:tr
[:td "re-new password:"]
[:td
[:input {:id "reNewPasswordId" :name "re-new-password" :type "password"}]]]
[:tr
[:td
[:button {:id "buttonUpdateId" :on-click (fn [_]
(change-password username ["<PASSWORD>" "<PASSWORD>" "<PASSWORD>"]))} "update"]]
[:td]]]])
| true | (ns view.changepassword)
(defn component
[username change-password]
[:table
[:tbody
[:tr
[:td "current password:"]
[:td
[:input {:id "currentPasswordId" :name "current-password" :type "password"}]]]
[:tr
[:td
[:br]]]
[:tr
[:td "new password:"]
[:td
[:input {:id "newPasswordId" :name "new-password" :type "password"}]]]
[:tr
[:td "re-new password:"]
[:td
[:input {:id "reNewPasswordId" :name "re-new-password" :type "password"}]]]
[:tr
[:td
[:button {:id "buttonUpdateId" :on-click (fn [_]
(change-password username ["PI:PASSWORD:<PASSWORD>END_PI" "PI:PASSWORD:<PASSWORD>END_PI" "PI:PASSWORD:<PASSWORD>END_PI"]))} "update"]]
[:td]]]])
|
[
{
"context": " {:id 1000\n :name \"Luke\"\n :home_planet \"Tatooine\"\n :appea",
"end": 2475,
"score": 0.9996297359466553,
"start": 2471,
"tag": "NAME",
"value": "Luke"
},
{
"context": " {:id 2000\n :name \"Lando Calrissian\"\n :home_planet \"Socorro\"\n :appear",
"end": 2627,
"score": 0.9998305439949036,
"start": 2611,
"tag": "NAME",
"value": "Lando Calrissian"
},
{
"context": "0\")\n {:id 1000\n :name \"Luke\"\n :home_planet \"Tatooine\"\n :appears_i",
"end": 2872,
"score": 0.9996997714042664,
"start": 2868,
"tag": "NAME",
"value": "Luke"
},
{
"context": "\"]}\n {:id 2000\n :name \"Lando Calrissian\"\n :home_planet \"Socorro\"\n :appears_in",
"end": 3016,
"score": 0.9997997283935547,
"start": 3000,
"tag": "NAME",
"value": "Lando Calrissian"
},
{
"context": "\n {:id 1\n :name \"Droid Sample\"\n :primary_function [\"Work\"]}))\n\n(defn resolv",
"end": 3221,
"score": 0.9965211749076843,
"start": 3209,
"tag": "NAME",
"value": "Droid Sample"
}
] | test/com/wsscode/pathom3/graphql/test/server.clj | wilkerlucio/pathom3-graphql | 9 | (ns com.wsscode.pathom3.graphql.test.server
(:require
[clojure.data.json :as json]
[com.walmartlabs.lacinia :refer [execute]]
[com.walmartlabs.lacinia.schema :as schema]
[com.walmartlabs.lacinia.util :as util]
[com.wsscode.pathom3.graphql :as p.gql]
[com.wsscode.pathom3.interface.smart-map :as psm]
[edn-query-language.eql-graphql :as eql-gql]
[org.httpkit.client :as http]))
(def schema
'{:enums
{:episode
{:description "The episodes of the original Star Wars trilogy."
:values [:NEWHOPE :EMPIRE :JEDI]}}
:interfaces
{:character
{:fields {:id {:type String}
:name {:type String}
:appears_in {:type (list :episode)}
:friends {:type (list :character)}}}}
:objects
{:droid
{:implements [:character]
:fields {:id {:type String}
:name {:type String}
:appears_in {:type (list :episode)}
:friends {:type (list :character)
:resolve :friends}
:primary_function {:type (list String)}}}
:human
{:implements [:character]
:fields {:id {:type String}
:name {:type String}
:appears_in {:type (list :episode)}
:friends {:type (list :character)
:resolve :friends}
:home_planet {:type String}}}}
:queries
{:hero {:type (non-null :character)
:args {:episode {:type :episode}}
:resolve :hero}
:human {:type (non-null :human)
:args {:id {:type String
:default-value "1001"}}
:resolve :human}
:droid {:type :droid
:args {:id {:type String
:default-value "2001"}}
:resolve :droid}
:allHumans {:type (non-null (list :human))
:resolve :all-humans}}
:mutations
{:create_human
{:type :human
:args {:name {:type (non-null String)}}
:resolve :mutation/create-human}}})
(defn resolve-hero [_ arguments _]
(let [{:keys [id]} arguments]
(schema/tag-with-type
(if (= id 1000)
{:id 1000
:name "Luke"
:home_planet "Tatooine"
:appears_in ["NEWHOPE" "EMPIRE" "JEDI"]}
{:id 2000
:name "Lando Calrissian"
:home_planet "Socorro"
:appears_in ["EMPIRE" "JEDI"]})
:human)))
(defn resolve-human [_context arguments _value]
(let [{:keys [id]} arguments]
(if (= id "1000")
{:id 1000
:name "Luke"
:home_planet "Tatooine"
:appears_in ["NEWHOPE" "EMPIRE" "JEDI"]}
{:id 2000
:name "Lando Calrissian"
:home_planet "Socorro"
:appears_in ["EMPIRE" "JEDI"]})))
(defn resolve-droid [_context arguments _value]
(let [_ arguments]
{:id 1
:name "Droid Sample"
:primary_function ["Work"]}))
(defn resolve-friends [_context _args _value])
(defn create-human [_context args _value]
{:id 3000
:name (:name args)
:home_planet "New one"
:appears_in ["JEDI"]})
(defn all-humans [_ _ _]
[])
(def star-wars-schema
(-> schema
(util/attach-resolvers {:hero resolve-hero
:human resolve-human
:droid resolve-droid
:friends resolve-friends
:all-humans all-humans
:mutation/create-human create-human})
schema/compile))
(defn request [query]
(json/read-str (json/write-str (execute star-wars-schema query nil nil))))
(defn load-schema [request]
(p.gql/load-schema {::p.gql/namespace "acme.stars"} request))
(comment
(request (eql-gql/query->graphql p.gql/schema-query) )
(-> @(http/request
{:url "https://swapi-graphql.netlify.app/.netlify/functions/index"
:method :post
:headers {"Content-Type" "application/json"
"Accept" "*/*"}
:body (json/write-str {:query "{\n allPeople {\n people {\n id\n name\n }\n }\n}"})})
:body
json/read-str)
(-> (load-schema request)
::p.gql/gql-query-type
::p.gql/gql-type-indexable?)
(-> (load-schema request)
::p.gql/gql-query-type
::p.gql/gql-type-qualified-name)
(-> (load-schema request)
::p.gql/gql-types-index)
(->> (load-schema request)
::p.gql/gql-all-types
(mapv ::p.gql/gql-type-qualified-name))
(->> (load-schema request)
::p.gql/gql-all-types)
(->> (load-schema request)
::p.gql/gql-indexable-types
)
(->> (psm/sm-replace-context schema
{::p.gql/gql-type-name "human"})
::p.gql/gql-type-interfaces
(mapv ::p.gql/gql-type-qualified-name))
(-> schema
(assoc ::p.gql/gql-type-name "human")
::p.gql/gql-indexable-type-resolver)
(tap> (psm/sm-entity schema))
(->> schema
::p.gql/gql-indexable-types
(mapv ::p.gql/gql-indexable-type-resolver))
(->> schema
::p.gql/gql-pathom-indexes)
(json/read-str (request (eql-gql/query->graphql p.gql/schema-query)))
(request "{\n human {\n id\n name\n friends {\n name\n }\n }\n}")
(request "query {\n human {\n id\n name\n __typename\n }\n __typename\n}\n"
))
| 59402 | (ns com.wsscode.pathom3.graphql.test.server
(:require
[clojure.data.json :as json]
[com.walmartlabs.lacinia :refer [execute]]
[com.walmartlabs.lacinia.schema :as schema]
[com.walmartlabs.lacinia.util :as util]
[com.wsscode.pathom3.graphql :as p.gql]
[com.wsscode.pathom3.interface.smart-map :as psm]
[edn-query-language.eql-graphql :as eql-gql]
[org.httpkit.client :as http]))
(def schema
'{:enums
{:episode
{:description "The episodes of the original Star Wars trilogy."
:values [:NEWHOPE :EMPIRE :JEDI]}}
:interfaces
{:character
{:fields {:id {:type String}
:name {:type String}
:appears_in {:type (list :episode)}
:friends {:type (list :character)}}}}
:objects
{:droid
{:implements [:character]
:fields {:id {:type String}
:name {:type String}
:appears_in {:type (list :episode)}
:friends {:type (list :character)
:resolve :friends}
:primary_function {:type (list String)}}}
:human
{:implements [:character]
:fields {:id {:type String}
:name {:type String}
:appears_in {:type (list :episode)}
:friends {:type (list :character)
:resolve :friends}
:home_planet {:type String}}}}
:queries
{:hero {:type (non-null :character)
:args {:episode {:type :episode}}
:resolve :hero}
:human {:type (non-null :human)
:args {:id {:type String
:default-value "1001"}}
:resolve :human}
:droid {:type :droid
:args {:id {:type String
:default-value "2001"}}
:resolve :droid}
:allHumans {:type (non-null (list :human))
:resolve :all-humans}}
:mutations
{:create_human
{:type :human
:args {:name {:type (non-null String)}}
:resolve :mutation/create-human}}})
(defn resolve-hero [_ arguments _]
(let [{:keys [id]} arguments]
(schema/tag-with-type
(if (= id 1000)
{:id 1000
:name "<NAME>"
:home_planet "Tatooine"
:appears_in ["NEWHOPE" "EMPIRE" "JEDI"]}
{:id 2000
:name "<NAME>"
:home_planet "Socorro"
:appears_in ["EMPIRE" "JEDI"]})
:human)))
(defn resolve-human [_context arguments _value]
(let [{:keys [id]} arguments]
(if (= id "1000")
{:id 1000
:name "<NAME>"
:home_planet "Tatooine"
:appears_in ["NEWHOPE" "EMPIRE" "JEDI"]}
{:id 2000
:name "<NAME>"
:home_planet "Socorro"
:appears_in ["EMPIRE" "JEDI"]})))
(defn resolve-droid [_context arguments _value]
(let [_ arguments]
{:id 1
:name "<NAME>"
:primary_function ["Work"]}))
(defn resolve-friends [_context _args _value])
(defn create-human [_context args _value]
{:id 3000
:name (:name args)
:home_planet "New one"
:appears_in ["JEDI"]})
(defn all-humans [_ _ _]
[])
(def star-wars-schema
(-> schema
(util/attach-resolvers {:hero resolve-hero
:human resolve-human
:droid resolve-droid
:friends resolve-friends
:all-humans all-humans
:mutation/create-human create-human})
schema/compile))
(defn request [query]
(json/read-str (json/write-str (execute star-wars-schema query nil nil))))
(defn load-schema [request]
(p.gql/load-schema {::p.gql/namespace "acme.stars"} request))
(comment
(request (eql-gql/query->graphql p.gql/schema-query) )
(-> @(http/request
{:url "https://swapi-graphql.netlify.app/.netlify/functions/index"
:method :post
:headers {"Content-Type" "application/json"
"Accept" "*/*"}
:body (json/write-str {:query "{\n allPeople {\n people {\n id\n name\n }\n }\n}"})})
:body
json/read-str)
(-> (load-schema request)
::p.gql/gql-query-type
::p.gql/gql-type-indexable?)
(-> (load-schema request)
::p.gql/gql-query-type
::p.gql/gql-type-qualified-name)
(-> (load-schema request)
::p.gql/gql-types-index)
(->> (load-schema request)
::p.gql/gql-all-types
(mapv ::p.gql/gql-type-qualified-name))
(->> (load-schema request)
::p.gql/gql-all-types)
(->> (load-schema request)
::p.gql/gql-indexable-types
)
(->> (psm/sm-replace-context schema
{::p.gql/gql-type-name "human"})
::p.gql/gql-type-interfaces
(mapv ::p.gql/gql-type-qualified-name))
(-> schema
(assoc ::p.gql/gql-type-name "human")
::p.gql/gql-indexable-type-resolver)
(tap> (psm/sm-entity schema))
(->> schema
::p.gql/gql-indexable-types
(mapv ::p.gql/gql-indexable-type-resolver))
(->> schema
::p.gql/gql-pathom-indexes)
(json/read-str (request (eql-gql/query->graphql p.gql/schema-query)))
(request "{\n human {\n id\n name\n friends {\n name\n }\n }\n}")
(request "query {\n human {\n id\n name\n __typename\n }\n __typename\n}\n"
))
| true | (ns com.wsscode.pathom3.graphql.test.server
(:require
[clojure.data.json :as json]
[com.walmartlabs.lacinia :refer [execute]]
[com.walmartlabs.lacinia.schema :as schema]
[com.walmartlabs.lacinia.util :as util]
[com.wsscode.pathom3.graphql :as p.gql]
[com.wsscode.pathom3.interface.smart-map :as psm]
[edn-query-language.eql-graphql :as eql-gql]
[org.httpkit.client :as http]))
(def schema
'{:enums
{:episode
{:description "The episodes of the original Star Wars trilogy."
:values [:NEWHOPE :EMPIRE :JEDI]}}
:interfaces
{:character
{:fields {:id {:type String}
:name {:type String}
:appears_in {:type (list :episode)}
:friends {:type (list :character)}}}}
:objects
{:droid
{:implements [:character]
:fields {:id {:type String}
:name {:type String}
:appears_in {:type (list :episode)}
:friends {:type (list :character)
:resolve :friends}
:primary_function {:type (list String)}}}
:human
{:implements [:character]
:fields {:id {:type String}
:name {:type String}
:appears_in {:type (list :episode)}
:friends {:type (list :character)
:resolve :friends}
:home_planet {:type String}}}}
:queries
{:hero {:type (non-null :character)
:args {:episode {:type :episode}}
:resolve :hero}
:human {:type (non-null :human)
:args {:id {:type String
:default-value "1001"}}
:resolve :human}
:droid {:type :droid
:args {:id {:type String
:default-value "2001"}}
:resolve :droid}
:allHumans {:type (non-null (list :human))
:resolve :all-humans}}
:mutations
{:create_human
{:type :human
:args {:name {:type (non-null String)}}
:resolve :mutation/create-human}}})
(defn resolve-hero [_ arguments _]
(let [{:keys [id]} arguments]
(schema/tag-with-type
(if (= id 1000)
{: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"]})
:human)))
(defn resolve-human [_context arguments _value]
(let [{:keys [id]} arguments]
(if (= id "1000")
{: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"]})))
(defn resolve-droid [_context arguments _value]
(let [_ arguments]
{:id 1
:name "PI:NAME:<NAME>END_PI"
:primary_function ["Work"]}))
(defn resolve-friends [_context _args _value])
(defn create-human [_context args _value]
{:id 3000
:name (:name args)
:home_planet "New one"
:appears_in ["JEDI"]})
(defn all-humans [_ _ _]
[])
(def star-wars-schema
(-> schema
(util/attach-resolvers {:hero resolve-hero
:human resolve-human
:droid resolve-droid
:friends resolve-friends
:all-humans all-humans
:mutation/create-human create-human})
schema/compile))
(defn request [query]
(json/read-str (json/write-str (execute star-wars-schema query nil nil))))
(defn load-schema [request]
(p.gql/load-schema {::p.gql/namespace "acme.stars"} request))
(comment
(request (eql-gql/query->graphql p.gql/schema-query) )
(-> @(http/request
{:url "https://swapi-graphql.netlify.app/.netlify/functions/index"
:method :post
:headers {"Content-Type" "application/json"
"Accept" "*/*"}
:body (json/write-str {:query "{\n allPeople {\n people {\n id\n name\n }\n }\n}"})})
:body
json/read-str)
(-> (load-schema request)
::p.gql/gql-query-type
::p.gql/gql-type-indexable?)
(-> (load-schema request)
::p.gql/gql-query-type
::p.gql/gql-type-qualified-name)
(-> (load-schema request)
::p.gql/gql-types-index)
(->> (load-schema request)
::p.gql/gql-all-types
(mapv ::p.gql/gql-type-qualified-name))
(->> (load-schema request)
::p.gql/gql-all-types)
(->> (load-schema request)
::p.gql/gql-indexable-types
)
(->> (psm/sm-replace-context schema
{::p.gql/gql-type-name "human"})
::p.gql/gql-type-interfaces
(mapv ::p.gql/gql-type-qualified-name))
(-> schema
(assoc ::p.gql/gql-type-name "human")
::p.gql/gql-indexable-type-resolver)
(tap> (psm/sm-entity schema))
(->> schema
::p.gql/gql-indexable-types
(mapv ::p.gql/gql-indexable-type-resolver))
(->> schema
::p.gql/gql-pathom-indexes)
(json/read-str (request (eql-gql/query->graphql p.gql/schema-query)))
(request "{\n human {\n id\n name\n friends {\n name\n }\n }\n}")
(request "query {\n human {\n id\n name\n __typename\n }\n __typename\n}\n"
))
|
[
{
"context": " :username \"root\"\n :password \"shadow\"\n :strict-host-key-checking false\n ",
"end": 6756,
"score": 0.9996084570884705,
"start": 6750,
"tag": "PASSWORD",
"value": "shadow"
},
{
"context": " :username \"root\"\n :password \"shadow\"\n :strict-host-key-checking false\n ",
"end": 19054,
"score": 0.9995492100715637,
"start": 19048,
"tag": "PASSWORD",
"value": "shadow"
}
] | linearizable/jepsen/src/comdb2/core.clj | isabella232/comdb2 | 1 | (ns comdb2.core
"Tests for Comdb2"
(:require
[clojure.tools.logging :refer :all]
[clojure.core.reducers :as r]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.pprint :refer [pprint]]
[jepsen.checker.timeline :as timeline]
[jepsen [client :as client]
[core :as jepsen]
[db :as db]
[tests :as tests]
[control :as c :refer [|]]
[checker :as checker]
[nemesis :as nemesis]
[independent :as independent]
[util :refer [timeout meh]]
[generator :as gen]]
[knossos.op :as op]
[knossos.model :as model]
[clojure.java.jdbc :as j]))
(java.sql.DriverManager/registerDriver (com.bloomberg.comdb2.jdbc.Driver.))
(defn db
[name]
(reify db/DB
(setup! [name test node])
(teardown! [name test node])))
(def conn-spec
{:classname "com.bloomberg.comdb2.jdbc.Driver"
:subprotocol "comdb2"
:subname (.concat (System/getenv "COMDB2_DBNAME") ":dev")})
(defn retriable-transaction-error [e]
(or (re-find #"not serializable" e)
(re-find #"unable to update record rc = 4" e)
(re-find #"selectv constraints" e)
(re-find #"Maximum number of retries done." e)))
(defmacro capture-txn-abort
"Converts aborted transactions to an ::abort keyword"
[& body]
`(try ~@body
(catch java.sql.SQLException e#
(println "error is " (.getMessage e#))
(if (retriable-transaction-error (.getMessage e#))
::abort
(throw e#)))))
(defmacro with-txn-retries
"Retries body on rollbacks."
[& body]
`(loop []
(let [res# (capture-txn-abort ~@body)]
(if (= ::abort res#)
(do
(info "RETRY")
(recur))
res#))))
(defmacro with-txn
"Executes body in a transaction, with a timeout, automatically retrying
conflicts and handling common errors."
[op c node & body]
`(with-txn-retries
~@body))
(defrecord BankClient [node n starting-balance]
client/Client
(setup! [this test node]
; (println "n " (:n this) "test " test "node " node)
(j/with-db-connection [c conn-spec]
; Create initial accts
(dotimes [i n]
(try
(j/insert! c :accounts {:id i, :balance starting-balance})
(catch java.sql.SQLException e
(if (.contains (.getMessage e) "add key constraint duplicate key")
nil
(throw e))))))
(assoc this :node node))
(invoke! [this test op]
(with-txn op conn-spec nil
(j/with-db-transaction [connection conn-spec :isolation :serializable]
(j/query connection ["set hasql on"])
(j/query connection ["set max_retries 100000"])
(try
(case (:f op)
:read (->> (j/query connection ["select * from accounts"])
(mapv :balance)
(assoc op :type :ok, :value))
:transfer
(let [{:keys [from to amount]} (:value op)
b1 (-> connection
(j/query ["select * from accounts where id = ?" from]
:row-fn :balance)
first
(- amount))
b2 (-> connection
(j/query ["select * from accounts where id = ?" to]
:row-fn :balance)
first
(+ amount))]
(cond (neg? b1)
(assoc op :type :fail, :value [:negative from b1])
(neg? b2)
(assoc op :type :fail, :value [:negative to b2])
true
(do (j/execute! connection ["update accounts set balance = balance - ? where id = ?" amount from])
(j/execute! connection ["update accounts set balance = balance + ? where id = ?" amount to])
(assoc op :type :ok)))))))))
(teardown! [_ test]))
(defn bank-client
"Simulates bank account transfers between n accounts, each starting with
starting-balance."
[n starting-balance]
(BankClient. nil n starting-balance))
(defn bank-read
"Reads the current state of all accounts without any synchronization."
[_ _]
{:type :invoke, :f :read})
(defn bank-transfer
"Transfers a random amount between two randomly selected accounts."
[test process]
(let [n (-> test :client :n)]
{:type :invoke
:f :transfer
:value {:from (rand-int n)
:to (rand-int n)
:amount (rand-int 5)}}))
(def bank-diff-transfer
"Like transfer, but only transfers between *different* accounts."
(gen/filter (fn [op] (not= (-> op :value :from)
(-> op :value :to)))
bank-transfer))
(defn bank-checker
"Balances must all be non-negative and sum to the model's total."
[]
(reify checker/Checker
(check [this test model history opts]
(let [bad-reads (->> history
(r/filter op/ok?)
(r/filter #(= :read (:f %)))
(r/map (fn [op]
(let [balances (:value op)]
(cond (not= (:n model) (count balances))
{:type :wrong-n
:expected (:n model)
:found (count balances)
:op op}
(not= (:total model)
(reduce + balances))
{:type :wrong-total
:expected (:total model)
:found (reduce + balances)
:op op}))))
(r/filter identity)
(into []))]
{:valid? (empty? bad-reads)
:bad-reads bad-reads}))))
(defn with-nemesis
"Wraps a client generator in a nemesis that induces failures and eventually
stops."
[client]
(gen/phases
(gen/phases
(->> client
(gen/nemesis
(gen/seq (cycle [(gen/sleep 0)
{:type :info, :f :start}
(gen/sleep 10)
{:type :info, :f :stop}])))
(gen/time-limit 30))
(gen/nemesis (gen/once {:type :info, :f :stop}))
(gen/sleep 5))))
(defn basic-test
[opts]
(merge tests/noop-test
{:name "comdb2-bank"
:db (db (System/getenv "COMDB2_DBNAME"))
; :db (db "marktdb")
:nemesis (nemesis/partition-random-halves)
:nodes ["m1" "m2" "m3" "m4" "m5"]
:ssh {
:username "root"
:password "shadow"
:strict-host-key-checking false
}}
(dissoc opts :name :version)))
;(defn connect-to [conn-spec node]
; (merge conn-spec {:subname (str "marktdb:" node)}))
(defn connect-to [conn-spec node]
conn-spec)
(def nkey (agent 0))
(defn next-key []
(let [n @nkey]
(send nkey inc)
n))
(defn set-client
[node]
(reify client/Client
(setup! [this test node]
(set-client node))
(invoke! [this test op]
(println op)
(j/with-db-transaction [connection conn-spec :isolation :serializable]
(j/query connection ["set hasql on"])
(j/query connection ["set transaction serializable"])
(when (System/getenv "COMDB2_DEBUG") (j/query connection ["set debug on"]))
; (j/query connection ["set debug on"])
(j/query connection ["set max_retries 100000"])
(with-txn op conn-spec node
(try
(case (:f op)
:add (do (j/execute! connection [(str "insert into jepsen(id, value) values(" (next-key) ", " (:value op) ")")])
(assoc op :type :ok))
:read (->> (j/query connection ["select * from jepsen"])
(mapv :value)
(into (sorted-set))
(assoc op :type :ok, :value)))))))
(teardown! [_ test])))
(defn sets-test
[]
(basic-test
{:name "set"
:client (set-client nil)
:generator (gen/phases
(->> (range)
(map (partial array-map
:type :invoke
:f :add
:value))
gen/seq
(gen/delay 1/10)
with-nemesis)
(->> {:type :invoke, :f :read, :value nil}
gen/once
gen/clients))
:checker (checker/compose
{:perf (checker/perf)
:set checker/set})}))
(defn bank-test-nemesis
[n initial-balance]
(basic-test
{:name "bank"
:concurrency 10
:model {:n n :total (* n initial-balance)}
:client (bank-client n initial-balance)
:generator (gen/phases
(->> (gen/mix [bank-read bank-diff-transfer])
(gen/clients)
(gen/stagger 1/10)
(gen/time-limit 100)
with-nemesis)
(gen/log "waiting for quiescence")
(gen/sleep 10)
(gen/clients (gen/once bank-read)))
:nemesis (nemesis/partition-random-halves)
:checker (checker/compose
{:perf (checker/perf)
:linearizable (independent/checker checker/linearizable)
:bank (bank-checker)})}))
(defn bank-test
[n initial-balance]
(basic-test
{:name "bank"
:concurrency 10
:model {:n n :total (* n initial-balance)}
:client (bank-client n initial-balance)
:generator (gen/phases
(->> (gen/mix [bank-read bank-diff-transfer])
(gen/clients)
(gen/stagger 1/10)
(gen/time-limit 100))
(gen/log "waiting for quiescence")
(gen/sleep 10)
(gen/clients (gen/once bank-read)))
:nemesis nemesis/noop
:checker (checker/compose
{:perf (checker/perf)
:linearizable (independent/checker checker/linearizable)
:bank (bank-checker)})}))
; This is the dirty reads test for Galera
(defrecord DirtyReadsClient [node n]
client/Client
(setup! [this test node]
(warn "setup")
(j/with-db-connection [c (connect-to conn-spec node)]
; Create table
(dotimes [i n]
(try
(with-txn-retries
(Thread/sleep (rand-int 10))
(j/insert! c :dirty {:id i, :x -1})))))
(assoc this :node node))
(invoke! [this test op]
(try
(j/with-db-transaction [c (connect-to conn-spec node) :isolation :serializable]
(try
(case (:f op)
; skip initial records - not all threads are done initial writing, and the initial writes
; aren't a single transaction so we won't see consistent reads
:read (->> (j/query c ["select * from dirty where x != -1"])
(mapv :x)
(assoc op :type :ok, :value))
:write (let [x (:value op)
order (shuffle (range n))]
(doseq [i order]
(j/query c ["select * from dirty where id = ?" i]))
(doseq [i order]
(j/update! c :dirty {:x x} ["id = ?" i]))
(assoc op :type :ok)))))
(catch java.sql.SQLException e
(assoc op :type :fail :reason (.getMessage e)))))
(teardown! [_ test]))
(defn comdb2-cas-register-client
"Comdb2 register client"
[node]
(reify client/Client
(setup! [this test node]
(j/with-db-connection [c conn-spec]
(do
(j/delete! c :register ["1 = 1"])
(comdb2-cas-register-client node))))
(invoke! [this test op]
(j/with-db-connection [c conn-spec]
(do
(j/query c ["set hasql on"])
(j/query c ["set transaction serializable"])
(when (System/getenv "COMDB2_DEBUG") (j/query c ["set debug on"]))
(j/query c ["set max_retries 100000"])
(case (:f op)
:read
(let [id (first (:value op))
val' (second (:value op))
[val uid] (second (j/query c ["select val,uid from register where id = 1"] :as-arrays? true)) ]
(info "Worker " (:process op) " READS val " val " uid " uid " PRE-COMMIT")
(assoc op :type :ok, :value (independent/tuple 1 val))
)
:write
(try
(let [updated (first (j/with-db-transaction [c c]
(let [id (first (:value op))
val' (second (:value op))
[val uid] (second (j/query c ["select val,uid from register where id = 1"] :as-arrays? true))
uid' (+ (* 1000 (rand-int 100000)) (:process op))]
(do
(if (nil? val)
(do
(info "Worker " (:process op) " INSERTS val " val' " uid " uid' " PRE-COMMIT")
(j/execute! c [(str "insert into register (id, val, uid) values (" id "," val' "," uid' ")")])
)
(do
(info "Worker " (:process op) " WRITES val from " val "-" uid " to " val' "-" uid' " PRE-COMMIT")
(j/execute! c [(str "update register set val=" val' ",uid=" uid' " where 1")])
)
)
)
)
)
) ; first
]
(if (zero? updated)
(do
(info "Worker " (:process op) " WRITE FAILED")
(assoc op :type :fail)
)
(do
(info "Worker " (:process op) " WRITE SUCCESS - RETURNING " (second (:value op)))
(assoc op :type :ok, :value (independent/tuple 1 (second (:value op))))
)
)
)
(catch java.sql.SQLException e
(let [error (.getErrorCode e)]
(cond
(= error 2) (do
(info "Worker " (:process op) " FAILED: "(.getMessage e))
(assoc op :type :fail)
)
:else (throw e))
)
)
) ; try / :write case
:cas
(try
(let [updated (first (j/with-db-transaction [c c]
(let [id (first (:value op))
val' (second (:value op))
[val uid] (second (j/query c ["select val,uid from register where id = 1"] :as-arrays? true))
uid' (+ (* 1000 (rand-int 100000)) (:process op))]
(do
(let [[expected-val new-val] val' ]
(do
(info "Worker " (:process op) " CAS FROM " expected-val "-" uid " to " new-val "-" uid')
(j/execute! c [(str "update register set val=" new-val ",uid=" uid' " where id=" id " and val=" expected-val " -- old-uid is " uid)]))))
)
)
)
]
(do
(info "Worker " (:process op) " TXN RCODE IS " updated)
(if (zero? updated)
(do
(info "Worker " (:process op) " CAS FAILED")
(assoc op :type :fail)
)
(do
(info "Worker " (:process op) " CAS SUCCESS")
(assoc op :type :ok, :value (independent/tuple 1 (second (:value op))))
)
)
)
)
(catch java.sql.SQLException e
(let [error (.getErrorCode e)]
(cond
(= error 2) (do
(info "Worker " (:process op) " FAILED: "(.getMessage e))
(assoc op :type :fail)
)
:else (throw e))
)
)
)
)
)
)
)
(teardown! [_ test])))
; Test on only one register for now
(defn r [_ _] {:type :invoke, :f :read, :value [1 nil]})
(defn w [_ _] {:type :invoke, :f :write, :value [1 (rand-int 5)]})
(defn cas [_ _] {:type :invoke, :f :cas, :value [1 [(rand-int 5) (rand-int 5)]]})
(defn client
[n]
(DirtyReadsClient. nil n))
(defn dirty-reads-checker
"We're looking for a failed transaction whose value became visible to some
read."
[]
(reify checker/Checker
(check [this test model history opts]
(let [
failed-writes
; Add a dummy failed write so we have something to compare to in the
; unlikely case that there's no other write failures
(merge {:type :fail, :f :write, :value -12, :process 0, :time 0}
(->> history
(r/filter op/fail?)
(r/filter #(= :write (:f %)))
(r/map :value)
(into (hash-set))))
reads (->> history
(r/filter op/ok?)
(r/filter #(= :read (:f %)))
(r/map :value))
inconsistent-reads (->> reads
(r/filter (partial apply not=))
(into []))
filthy-reads (->> reads
(r/filter (partial some failed-writes))
(into []))]
{:valid? (empty? filthy-reads)
:inconsistent-reads inconsistent-reads
:dirty-reads filthy-reads}))))
(def dirty-reads-reads {:type :invoke, :f :read, :value nil})
(def dirty-reads-writes (->> (range)
(map (partial array-map
:type :invoke,
:f :write,
:value))
gen/seq))
(defn dirty-reads-basic-test
[opts]
(merge tests/noop-test
{:name "dirty-reads"
:nodes ["m1" "m2" "m3" "m4" "m5"]
:ssh {
:username "root"
:password "shadow"
:strict-host-key-checking false
}
:db (db (:version opts))
:nemesis (nemesis/partition-random-halves)}
(dissoc opts :name :version)))
(defn minutes [seconds] (* 60 seconds))
(defn dirty-reads-tester
[version n]
(dirty-reads-basic-test
{:name "dirty reads"
:concurrency 1
:version version
:client (client n)
:generator (->> (gen/mix [dirty-reads-reads dirty-reads-writes])
gen/clients
(gen/time-limit 10))
:nemesis nemesis/noop
:checker (checker/compose
{:perf (checker/perf)
:dirty-reads (dirty-reads-checker)
:linearizable (independent/checker checker/linearizable)})}))
(defn register-tester
[opts]
(basic-test
(merge
{:name "register"
:client (comdb2-cas-register-client nil)
:concurrency 10
:generator (gen/phases
(->> (gen/mix [w cas cas r])
(gen/clients)
(gen/stagger 1/10)
(gen/time-limit 10))
(gen/log "waiting for quiescence")
(gen/sleep 10))
:model (model/cas-register-comdb2 [1 1])
:time-limit 100
:recovery-time 30
:checker (checker/compose
{:perf (checker/perf)
:linearizable checker/linearizable}) }
opts)))
(defn register-tester-nemesis
[opts]
(basic-test
(merge
{:name "register"
:client (comdb2-cas-register-client nil)
:concurrency 10
:generator (gen/phases
(->> (gen/mix [w cas cas r])
(gen/clients)
(gen/stagger 1/10)
(gen/time-limit 300)
with-nemesis)
(gen/log "waiting for quiescence")
(gen/sleep 10))
:model (model/cas-register-comdb2 [1 1])
:time-limit 300
:recovery-time 30
:checker (checker/compose
{:perf (checker/perf)
:linearizable checker/linearizable}) }
opts)))
| 111804 | (ns comdb2.core
"Tests for Comdb2"
(:require
[clojure.tools.logging :refer :all]
[clojure.core.reducers :as r]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.pprint :refer [pprint]]
[jepsen.checker.timeline :as timeline]
[jepsen [client :as client]
[core :as jepsen]
[db :as db]
[tests :as tests]
[control :as c :refer [|]]
[checker :as checker]
[nemesis :as nemesis]
[independent :as independent]
[util :refer [timeout meh]]
[generator :as gen]]
[knossos.op :as op]
[knossos.model :as model]
[clojure.java.jdbc :as j]))
(java.sql.DriverManager/registerDriver (com.bloomberg.comdb2.jdbc.Driver.))
(defn db
[name]
(reify db/DB
(setup! [name test node])
(teardown! [name test node])))
(def conn-spec
{:classname "com.bloomberg.comdb2.jdbc.Driver"
:subprotocol "comdb2"
:subname (.concat (System/getenv "COMDB2_DBNAME") ":dev")})
(defn retriable-transaction-error [e]
(or (re-find #"not serializable" e)
(re-find #"unable to update record rc = 4" e)
(re-find #"selectv constraints" e)
(re-find #"Maximum number of retries done." e)))
(defmacro capture-txn-abort
"Converts aborted transactions to an ::abort keyword"
[& body]
`(try ~@body
(catch java.sql.SQLException e#
(println "error is " (.getMessage e#))
(if (retriable-transaction-error (.getMessage e#))
::abort
(throw e#)))))
(defmacro with-txn-retries
"Retries body on rollbacks."
[& body]
`(loop []
(let [res# (capture-txn-abort ~@body)]
(if (= ::abort res#)
(do
(info "RETRY")
(recur))
res#))))
(defmacro with-txn
"Executes body in a transaction, with a timeout, automatically retrying
conflicts and handling common errors."
[op c node & body]
`(with-txn-retries
~@body))
(defrecord BankClient [node n starting-balance]
client/Client
(setup! [this test node]
; (println "n " (:n this) "test " test "node " node)
(j/with-db-connection [c conn-spec]
; Create initial accts
(dotimes [i n]
(try
(j/insert! c :accounts {:id i, :balance starting-balance})
(catch java.sql.SQLException e
(if (.contains (.getMessage e) "add key constraint duplicate key")
nil
(throw e))))))
(assoc this :node node))
(invoke! [this test op]
(with-txn op conn-spec nil
(j/with-db-transaction [connection conn-spec :isolation :serializable]
(j/query connection ["set hasql on"])
(j/query connection ["set max_retries 100000"])
(try
(case (:f op)
:read (->> (j/query connection ["select * from accounts"])
(mapv :balance)
(assoc op :type :ok, :value))
:transfer
(let [{:keys [from to amount]} (:value op)
b1 (-> connection
(j/query ["select * from accounts where id = ?" from]
:row-fn :balance)
first
(- amount))
b2 (-> connection
(j/query ["select * from accounts where id = ?" to]
:row-fn :balance)
first
(+ amount))]
(cond (neg? b1)
(assoc op :type :fail, :value [:negative from b1])
(neg? b2)
(assoc op :type :fail, :value [:negative to b2])
true
(do (j/execute! connection ["update accounts set balance = balance - ? where id = ?" amount from])
(j/execute! connection ["update accounts set balance = balance + ? where id = ?" amount to])
(assoc op :type :ok)))))))))
(teardown! [_ test]))
(defn bank-client
"Simulates bank account transfers between n accounts, each starting with
starting-balance."
[n starting-balance]
(BankClient. nil n starting-balance))
(defn bank-read
"Reads the current state of all accounts without any synchronization."
[_ _]
{:type :invoke, :f :read})
(defn bank-transfer
"Transfers a random amount between two randomly selected accounts."
[test process]
(let [n (-> test :client :n)]
{:type :invoke
:f :transfer
:value {:from (rand-int n)
:to (rand-int n)
:amount (rand-int 5)}}))
(def bank-diff-transfer
"Like transfer, but only transfers between *different* accounts."
(gen/filter (fn [op] (not= (-> op :value :from)
(-> op :value :to)))
bank-transfer))
(defn bank-checker
"Balances must all be non-negative and sum to the model's total."
[]
(reify checker/Checker
(check [this test model history opts]
(let [bad-reads (->> history
(r/filter op/ok?)
(r/filter #(= :read (:f %)))
(r/map (fn [op]
(let [balances (:value op)]
(cond (not= (:n model) (count balances))
{:type :wrong-n
:expected (:n model)
:found (count balances)
:op op}
(not= (:total model)
(reduce + balances))
{:type :wrong-total
:expected (:total model)
:found (reduce + balances)
:op op}))))
(r/filter identity)
(into []))]
{:valid? (empty? bad-reads)
:bad-reads bad-reads}))))
(defn with-nemesis
"Wraps a client generator in a nemesis that induces failures and eventually
stops."
[client]
(gen/phases
(gen/phases
(->> client
(gen/nemesis
(gen/seq (cycle [(gen/sleep 0)
{:type :info, :f :start}
(gen/sleep 10)
{:type :info, :f :stop}])))
(gen/time-limit 30))
(gen/nemesis (gen/once {:type :info, :f :stop}))
(gen/sleep 5))))
(defn basic-test
[opts]
(merge tests/noop-test
{:name "comdb2-bank"
:db (db (System/getenv "COMDB2_DBNAME"))
; :db (db "marktdb")
:nemesis (nemesis/partition-random-halves)
:nodes ["m1" "m2" "m3" "m4" "m5"]
:ssh {
:username "root"
:password "<PASSWORD>"
:strict-host-key-checking false
}}
(dissoc opts :name :version)))
;(defn connect-to [conn-spec node]
; (merge conn-spec {:subname (str "marktdb:" node)}))
(defn connect-to [conn-spec node]
conn-spec)
(def nkey (agent 0))
(defn next-key []
(let [n @nkey]
(send nkey inc)
n))
(defn set-client
[node]
(reify client/Client
(setup! [this test node]
(set-client node))
(invoke! [this test op]
(println op)
(j/with-db-transaction [connection conn-spec :isolation :serializable]
(j/query connection ["set hasql on"])
(j/query connection ["set transaction serializable"])
(when (System/getenv "COMDB2_DEBUG") (j/query connection ["set debug on"]))
; (j/query connection ["set debug on"])
(j/query connection ["set max_retries 100000"])
(with-txn op conn-spec node
(try
(case (:f op)
:add (do (j/execute! connection [(str "insert into jepsen(id, value) values(" (next-key) ", " (:value op) ")")])
(assoc op :type :ok))
:read (->> (j/query connection ["select * from jepsen"])
(mapv :value)
(into (sorted-set))
(assoc op :type :ok, :value)))))))
(teardown! [_ test])))
(defn sets-test
[]
(basic-test
{:name "set"
:client (set-client nil)
:generator (gen/phases
(->> (range)
(map (partial array-map
:type :invoke
:f :add
:value))
gen/seq
(gen/delay 1/10)
with-nemesis)
(->> {:type :invoke, :f :read, :value nil}
gen/once
gen/clients))
:checker (checker/compose
{:perf (checker/perf)
:set checker/set})}))
(defn bank-test-nemesis
[n initial-balance]
(basic-test
{:name "bank"
:concurrency 10
:model {:n n :total (* n initial-balance)}
:client (bank-client n initial-balance)
:generator (gen/phases
(->> (gen/mix [bank-read bank-diff-transfer])
(gen/clients)
(gen/stagger 1/10)
(gen/time-limit 100)
with-nemesis)
(gen/log "waiting for quiescence")
(gen/sleep 10)
(gen/clients (gen/once bank-read)))
:nemesis (nemesis/partition-random-halves)
:checker (checker/compose
{:perf (checker/perf)
:linearizable (independent/checker checker/linearizable)
:bank (bank-checker)})}))
(defn bank-test
[n initial-balance]
(basic-test
{:name "bank"
:concurrency 10
:model {:n n :total (* n initial-balance)}
:client (bank-client n initial-balance)
:generator (gen/phases
(->> (gen/mix [bank-read bank-diff-transfer])
(gen/clients)
(gen/stagger 1/10)
(gen/time-limit 100))
(gen/log "waiting for quiescence")
(gen/sleep 10)
(gen/clients (gen/once bank-read)))
:nemesis nemesis/noop
:checker (checker/compose
{:perf (checker/perf)
:linearizable (independent/checker checker/linearizable)
:bank (bank-checker)})}))
; This is the dirty reads test for Galera
(defrecord DirtyReadsClient [node n]
client/Client
(setup! [this test node]
(warn "setup")
(j/with-db-connection [c (connect-to conn-spec node)]
; Create table
(dotimes [i n]
(try
(with-txn-retries
(Thread/sleep (rand-int 10))
(j/insert! c :dirty {:id i, :x -1})))))
(assoc this :node node))
(invoke! [this test op]
(try
(j/with-db-transaction [c (connect-to conn-spec node) :isolation :serializable]
(try
(case (:f op)
; skip initial records - not all threads are done initial writing, and the initial writes
; aren't a single transaction so we won't see consistent reads
:read (->> (j/query c ["select * from dirty where x != -1"])
(mapv :x)
(assoc op :type :ok, :value))
:write (let [x (:value op)
order (shuffle (range n))]
(doseq [i order]
(j/query c ["select * from dirty where id = ?" i]))
(doseq [i order]
(j/update! c :dirty {:x x} ["id = ?" i]))
(assoc op :type :ok)))))
(catch java.sql.SQLException e
(assoc op :type :fail :reason (.getMessage e)))))
(teardown! [_ test]))
(defn comdb2-cas-register-client
"Comdb2 register client"
[node]
(reify client/Client
(setup! [this test node]
(j/with-db-connection [c conn-spec]
(do
(j/delete! c :register ["1 = 1"])
(comdb2-cas-register-client node))))
(invoke! [this test op]
(j/with-db-connection [c conn-spec]
(do
(j/query c ["set hasql on"])
(j/query c ["set transaction serializable"])
(when (System/getenv "COMDB2_DEBUG") (j/query c ["set debug on"]))
(j/query c ["set max_retries 100000"])
(case (:f op)
:read
(let [id (first (:value op))
val' (second (:value op))
[val uid] (second (j/query c ["select val,uid from register where id = 1"] :as-arrays? true)) ]
(info "Worker " (:process op) " READS val " val " uid " uid " PRE-COMMIT")
(assoc op :type :ok, :value (independent/tuple 1 val))
)
:write
(try
(let [updated (first (j/with-db-transaction [c c]
(let [id (first (:value op))
val' (second (:value op))
[val uid] (second (j/query c ["select val,uid from register where id = 1"] :as-arrays? true))
uid' (+ (* 1000 (rand-int 100000)) (:process op))]
(do
(if (nil? val)
(do
(info "Worker " (:process op) " INSERTS val " val' " uid " uid' " PRE-COMMIT")
(j/execute! c [(str "insert into register (id, val, uid) values (" id "," val' "," uid' ")")])
)
(do
(info "Worker " (:process op) " WRITES val from " val "-" uid " to " val' "-" uid' " PRE-COMMIT")
(j/execute! c [(str "update register set val=" val' ",uid=" uid' " where 1")])
)
)
)
)
)
) ; first
]
(if (zero? updated)
(do
(info "Worker " (:process op) " WRITE FAILED")
(assoc op :type :fail)
)
(do
(info "Worker " (:process op) " WRITE SUCCESS - RETURNING " (second (:value op)))
(assoc op :type :ok, :value (independent/tuple 1 (second (:value op))))
)
)
)
(catch java.sql.SQLException e
(let [error (.getErrorCode e)]
(cond
(= error 2) (do
(info "Worker " (:process op) " FAILED: "(.getMessage e))
(assoc op :type :fail)
)
:else (throw e))
)
)
) ; try / :write case
:cas
(try
(let [updated (first (j/with-db-transaction [c c]
(let [id (first (:value op))
val' (second (:value op))
[val uid] (second (j/query c ["select val,uid from register where id = 1"] :as-arrays? true))
uid' (+ (* 1000 (rand-int 100000)) (:process op))]
(do
(let [[expected-val new-val] val' ]
(do
(info "Worker " (:process op) " CAS FROM " expected-val "-" uid " to " new-val "-" uid')
(j/execute! c [(str "update register set val=" new-val ",uid=" uid' " where id=" id " and val=" expected-val " -- old-uid is " uid)]))))
)
)
)
]
(do
(info "Worker " (:process op) " TXN RCODE IS " updated)
(if (zero? updated)
(do
(info "Worker " (:process op) " CAS FAILED")
(assoc op :type :fail)
)
(do
(info "Worker " (:process op) " CAS SUCCESS")
(assoc op :type :ok, :value (independent/tuple 1 (second (:value op))))
)
)
)
)
(catch java.sql.SQLException e
(let [error (.getErrorCode e)]
(cond
(= error 2) (do
(info "Worker " (:process op) " FAILED: "(.getMessage e))
(assoc op :type :fail)
)
:else (throw e))
)
)
)
)
)
)
)
(teardown! [_ test])))
; Test on only one register for now
(defn r [_ _] {:type :invoke, :f :read, :value [1 nil]})
(defn w [_ _] {:type :invoke, :f :write, :value [1 (rand-int 5)]})
(defn cas [_ _] {:type :invoke, :f :cas, :value [1 [(rand-int 5) (rand-int 5)]]})
(defn client
[n]
(DirtyReadsClient. nil n))
(defn dirty-reads-checker
"We're looking for a failed transaction whose value became visible to some
read."
[]
(reify checker/Checker
(check [this test model history opts]
(let [
failed-writes
; Add a dummy failed write so we have something to compare to in the
; unlikely case that there's no other write failures
(merge {:type :fail, :f :write, :value -12, :process 0, :time 0}
(->> history
(r/filter op/fail?)
(r/filter #(= :write (:f %)))
(r/map :value)
(into (hash-set))))
reads (->> history
(r/filter op/ok?)
(r/filter #(= :read (:f %)))
(r/map :value))
inconsistent-reads (->> reads
(r/filter (partial apply not=))
(into []))
filthy-reads (->> reads
(r/filter (partial some failed-writes))
(into []))]
{:valid? (empty? filthy-reads)
:inconsistent-reads inconsistent-reads
:dirty-reads filthy-reads}))))
(def dirty-reads-reads {:type :invoke, :f :read, :value nil})
(def dirty-reads-writes (->> (range)
(map (partial array-map
:type :invoke,
:f :write,
:value))
gen/seq))
(defn dirty-reads-basic-test
[opts]
(merge tests/noop-test
{:name "dirty-reads"
:nodes ["m1" "m2" "m3" "m4" "m5"]
:ssh {
:username "root"
:password "<PASSWORD>"
:strict-host-key-checking false
}
:db (db (:version opts))
:nemesis (nemesis/partition-random-halves)}
(dissoc opts :name :version)))
(defn minutes [seconds] (* 60 seconds))
(defn dirty-reads-tester
[version n]
(dirty-reads-basic-test
{:name "dirty reads"
:concurrency 1
:version version
:client (client n)
:generator (->> (gen/mix [dirty-reads-reads dirty-reads-writes])
gen/clients
(gen/time-limit 10))
:nemesis nemesis/noop
:checker (checker/compose
{:perf (checker/perf)
:dirty-reads (dirty-reads-checker)
:linearizable (independent/checker checker/linearizable)})}))
(defn register-tester
[opts]
(basic-test
(merge
{:name "register"
:client (comdb2-cas-register-client nil)
:concurrency 10
:generator (gen/phases
(->> (gen/mix [w cas cas r])
(gen/clients)
(gen/stagger 1/10)
(gen/time-limit 10))
(gen/log "waiting for quiescence")
(gen/sleep 10))
:model (model/cas-register-comdb2 [1 1])
:time-limit 100
:recovery-time 30
:checker (checker/compose
{:perf (checker/perf)
:linearizable checker/linearizable}) }
opts)))
(defn register-tester-nemesis
[opts]
(basic-test
(merge
{:name "register"
:client (comdb2-cas-register-client nil)
:concurrency 10
:generator (gen/phases
(->> (gen/mix [w cas cas r])
(gen/clients)
(gen/stagger 1/10)
(gen/time-limit 300)
with-nemesis)
(gen/log "waiting for quiescence")
(gen/sleep 10))
:model (model/cas-register-comdb2 [1 1])
:time-limit 300
:recovery-time 30
:checker (checker/compose
{:perf (checker/perf)
:linearizable checker/linearizable}) }
opts)))
| true | (ns comdb2.core
"Tests for Comdb2"
(:require
[clojure.tools.logging :refer :all]
[clojure.core.reducers :as r]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.pprint :refer [pprint]]
[jepsen.checker.timeline :as timeline]
[jepsen [client :as client]
[core :as jepsen]
[db :as db]
[tests :as tests]
[control :as c :refer [|]]
[checker :as checker]
[nemesis :as nemesis]
[independent :as independent]
[util :refer [timeout meh]]
[generator :as gen]]
[knossos.op :as op]
[knossos.model :as model]
[clojure.java.jdbc :as j]))
(java.sql.DriverManager/registerDriver (com.bloomberg.comdb2.jdbc.Driver.))
(defn db
[name]
(reify db/DB
(setup! [name test node])
(teardown! [name test node])))
(def conn-spec
{:classname "com.bloomberg.comdb2.jdbc.Driver"
:subprotocol "comdb2"
:subname (.concat (System/getenv "COMDB2_DBNAME") ":dev")})
(defn retriable-transaction-error [e]
(or (re-find #"not serializable" e)
(re-find #"unable to update record rc = 4" e)
(re-find #"selectv constraints" e)
(re-find #"Maximum number of retries done." e)))
(defmacro capture-txn-abort
"Converts aborted transactions to an ::abort keyword"
[& body]
`(try ~@body
(catch java.sql.SQLException e#
(println "error is " (.getMessage e#))
(if (retriable-transaction-error (.getMessage e#))
::abort
(throw e#)))))
(defmacro with-txn-retries
"Retries body on rollbacks."
[& body]
`(loop []
(let [res# (capture-txn-abort ~@body)]
(if (= ::abort res#)
(do
(info "RETRY")
(recur))
res#))))
(defmacro with-txn
"Executes body in a transaction, with a timeout, automatically retrying
conflicts and handling common errors."
[op c node & body]
`(with-txn-retries
~@body))
(defrecord BankClient [node n starting-balance]
client/Client
(setup! [this test node]
; (println "n " (:n this) "test " test "node " node)
(j/with-db-connection [c conn-spec]
; Create initial accts
(dotimes [i n]
(try
(j/insert! c :accounts {:id i, :balance starting-balance})
(catch java.sql.SQLException e
(if (.contains (.getMessage e) "add key constraint duplicate key")
nil
(throw e))))))
(assoc this :node node))
(invoke! [this test op]
(with-txn op conn-spec nil
(j/with-db-transaction [connection conn-spec :isolation :serializable]
(j/query connection ["set hasql on"])
(j/query connection ["set max_retries 100000"])
(try
(case (:f op)
:read (->> (j/query connection ["select * from accounts"])
(mapv :balance)
(assoc op :type :ok, :value))
:transfer
(let [{:keys [from to amount]} (:value op)
b1 (-> connection
(j/query ["select * from accounts where id = ?" from]
:row-fn :balance)
first
(- amount))
b2 (-> connection
(j/query ["select * from accounts where id = ?" to]
:row-fn :balance)
first
(+ amount))]
(cond (neg? b1)
(assoc op :type :fail, :value [:negative from b1])
(neg? b2)
(assoc op :type :fail, :value [:negative to b2])
true
(do (j/execute! connection ["update accounts set balance = balance - ? where id = ?" amount from])
(j/execute! connection ["update accounts set balance = balance + ? where id = ?" amount to])
(assoc op :type :ok)))))))))
(teardown! [_ test]))
(defn bank-client
"Simulates bank account transfers between n accounts, each starting with
starting-balance."
[n starting-balance]
(BankClient. nil n starting-balance))
(defn bank-read
"Reads the current state of all accounts without any synchronization."
[_ _]
{:type :invoke, :f :read})
(defn bank-transfer
"Transfers a random amount between two randomly selected accounts."
[test process]
(let [n (-> test :client :n)]
{:type :invoke
:f :transfer
:value {:from (rand-int n)
:to (rand-int n)
:amount (rand-int 5)}}))
(def bank-diff-transfer
"Like transfer, but only transfers between *different* accounts."
(gen/filter (fn [op] (not= (-> op :value :from)
(-> op :value :to)))
bank-transfer))
(defn bank-checker
"Balances must all be non-negative and sum to the model's total."
[]
(reify checker/Checker
(check [this test model history opts]
(let [bad-reads (->> history
(r/filter op/ok?)
(r/filter #(= :read (:f %)))
(r/map (fn [op]
(let [balances (:value op)]
(cond (not= (:n model) (count balances))
{:type :wrong-n
:expected (:n model)
:found (count balances)
:op op}
(not= (:total model)
(reduce + balances))
{:type :wrong-total
:expected (:total model)
:found (reduce + balances)
:op op}))))
(r/filter identity)
(into []))]
{:valid? (empty? bad-reads)
:bad-reads bad-reads}))))
(defn with-nemesis
"Wraps a client generator in a nemesis that induces failures and eventually
stops."
[client]
(gen/phases
(gen/phases
(->> client
(gen/nemesis
(gen/seq (cycle [(gen/sleep 0)
{:type :info, :f :start}
(gen/sleep 10)
{:type :info, :f :stop}])))
(gen/time-limit 30))
(gen/nemesis (gen/once {:type :info, :f :stop}))
(gen/sleep 5))))
(defn basic-test
[opts]
(merge tests/noop-test
{:name "comdb2-bank"
:db (db (System/getenv "COMDB2_DBNAME"))
; :db (db "marktdb")
:nemesis (nemesis/partition-random-halves)
:nodes ["m1" "m2" "m3" "m4" "m5"]
:ssh {
:username "root"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:strict-host-key-checking false
}}
(dissoc opts :name :version)))
;(defn connect-to [conn-spec node]
; (merge conn-spec {:subname (str "marktdb:" node)}))
(defn connect-to [conn-spec node]
conn-spec)
(def nkey (agent 0))
(defn next-key []
(let [n @nkey]
(send nkey inc)
n))
(defn set-client
[node]
(reify client/Client
(setup! [this test node]
(set-client node))
(invoke! [this test op]
(println op)
(j/with-db-transaction [connection conn-spec :isolation :serializable]
(j/query connection ["set hasql on"])
(j/query connection ["set transaction serializable"])
(when (System/getenv "COMDB2_DEBUG") (j/query connection ["set debug on"]))
; (j/query connection ["set debug on"])
(j/query connection ["set max_retries 100000"])
(with-txn op conn-spec node
(try
(case (:f op)
:add (do (j/execute! connection [(str "insert into jepsen(id, value) values(" (next-key) ", " (:value op) ")")])
(assoc op :type :ok))
:read (->> (j/query connection ["select * from jepsen"])
(mapv :value)
(into (sorted-set))
(assoc op :type :ok, :value)))))))
(teardown! [_ test])))
(defn sets-test
[]
(basic-test
{:name "set"
:client (set-client nil)
:generator (gen/phases
(->> (range)
(map (partial array-map
:type :invoke
:f :add
:value))
gen/seq
(gen/delay 1/10)
with-nemesis)
(->> {:type :invoke, :f :read, :value nil}
gen/once
gen/clients))
:checker (checker/compose
{:perf (checker/perf)
:set checker/set})}))
(defn bank-test-nemesis
[n initial-balance]
(basic-test
{:name "bank"
:concurrency 10
:model {:n n :total (* n initial-balance)}
:client (bank-client n initial-balance)
:generator (gen/phases
(->> (gen/mix [bank-read bank-diff-transfer])
(gen/clients)
(gen/stagger 1/10)
(gen/time-limit 100)
with-nemesis)
(gen/log "waiting for quiescence")
(gen/sleep 10)
(gen/clients (gen/once bank-read)))
:nemesis (nemesis/partition-random-halves)
:checker (checker/compose
{:perf (checker/perf)
:linearizable (independent/checker checker/linearizable)
:bank (bank-checker)})}))
(defn bank-test
[n initial-balance]
(basic-test
{:name "bank"
:concurrency 10
:model {:n n :total (* n initial-balance)}
:client (bank-client n initial-balance)
:generator (gen/phases
(->> (gen/mix [bank-read bank-diff-transfer])
(gen/clients)
(gen/stagger 1/10)
(gen/time-limit 100))
(gen/log "waiting for quiescence")
(gen/sleep 10)
(gen/clients (gen/once bank-read)))
:nemesis nemesis/noop
:checker (checker/compose
{:perf (checker/perf)
:linearizable (independent/checker checker/linearizable)
:bank (bank-checker)})}))
; This is the dirty reads test for Galera
(defrecord DirtyReadsClient [node n]
client/Client
(setup! [this test node]
(warn "setup")
(j/with-db-connection [c (connect-to conn-spec node)]
; Create table
(dotimes [i n]
(try
(with-txn-retries
(Thread/sleep (rand-int 10))
(j/insert! c :dirty {:id i, :x -1})))))
(assoc this :node node))
(invoke! [this test op]
(try
(j/with-db-transaction [c (connect-to conn-spec node) :isolation :serializable]
(try
(case (:f op)
; skip initial records - not all threads are done initial writing, and the initial writes
; aren't a single transaction so we won't see consistent reads
:read (->> (j/query c ["select * from dirty where x != -1"])
(mapv :x)
(assoc op :type :ok, :value))
:write (let [x (:value op)
order (shuffle (range n))]
(doseq [i order]
(j/query c ["select * from dirty where id = ?" i]))
(doseq [i order]
(j/update! c :dirty {:x x} ["id = ?" i]))
(assoc op :type :ok)))))
(catch java.sql.SQLException e
(assoc op :type :fail :reason (.getMessage e)))))
(teardown! [_ test]))
(defn comdb2-cas-register-client
"Comdb2 register client"
[node]
(reify client/Client
(setup! [this test node]
(j/with-db-connection [c conn-spec]
(do
(j/delete! c :register ["1 = 1"])
(comdb2-cas-register-client node))))
(invoke! [this test op]
(j/with-db-connection [c conn-spec]
(do
(j/query c ["set hasql on"])
(j/query c ["set transaction serializable"])
(when (System/getenv "COMDB2_DEBUG") (j/query c ["set debug on"]))
(j/query c ["set max_retries 100000"])
(case (:f op)
:read
(let [id (first (:value op))
val' (second (:value op))
[val uid] (second (j/query c ["select val,uid from register where id = 1"] :as-arrays? true)) ]
(info "Worker " (:process op) " READS val " val " uid " uid " PRE-COMMIT")
(assoc op :type :ok, :value (independent/tuple 1 val))
)
:write
(try
(let [updated (first (j/with-db-transaction [c c]
(let [id (first (:value op))
val' (second (:value op))
[val uid] (second (j/query c ["select val,uid from register where id = 1"] :as-arrays? true))
uid' (+ (* 1000 (rand-int 100000)) (:process op))]
(do
(if (nil? val)
(do
(info "Worker " (:process op) " INSERTS val " val' " uid " uid' " PRE-COMMIT")
(j/execute! c [(str "insert into register (id, val, uid) values (" id "," val' "," uid' ")")])
)
(do
(info "Worker " (:process op) " WRITES val from " val "-" uid " to " val' "-" uid' " PRE-COMMIT")
(j/execute! c [(str "update register set val=" val' ",uid=" uid' " where 1")])
)
)
)
)
)
) ; first
]
(if (zero? updated)
(do
(info "Worker " (:process op) " WRITE FAILED")
(assoc op :type :fail)
)
(do
(info "Worker " (:process op) " WRITE SUCCESS - RETURNING " (second (:value op)))
(assoc op :type :ok, :value (independent/tuple 1 (second (:value op))))
)
)
)
(catch java.sql.SQLException e
(let [error (.getErrorCode e)]
(cond
(= error 2) (do
(info "Worker " (:process op) " FAILED: "(.getMessage e))
(assoc op :type :fail)
)
:else (throw e))
)
)
) ; try / :write case
:cas
(try
(let [updated (first (j/with-db-transaction [c c]
(let [id (first (:value op))
val' (second (:value op))
[val uid] (second (j/query c ["select val,uid from register where id = 1"] :as-arrays? true))
uid' (+ (* 1000 (rand-int 100000)) (:process op))]
(do
(let [[expected-val new-val] val' ]
(do
(info "Worker " (:process op) " CAS FROM " expected-val "-" uid " to " new-val "-" uid')
(j/execute! c [(str "update register set val=" new-val ",uid=" uid' " where id=" id " and val=" expected-val " -- old-uid is " uid)]))))
)
)
)
]
(do
(info "Worker " (:process op) " TXN RCODE IS " updated)
(if (zero? updated)
(do
(info "Worker " (:process op) " CAS FAILED")
(assoc op :type :fail)
)
(do
(info "Worker " (:process op) " CAS SUCCESS")
(assoc op :type :ok, :value (independent/tuple 1 (second (:value op))))
)
)
)
)
(catch java.sql.SQLException e
(let [error (.getErrorCode e)]
(cond
(= error 2) (do
(info "Worker " (:process op) " FAILED: "(.getMessage e))
(assoc op :type :fail)
)
:else (throw e))
)
)
)
)
)
)
)
(teardown! [_ test])))
; Test on only one register for now
(defn r [_ _] {:type :invoke, :f :read, :value [1 nil]})
(defn w [_ _] {:type :invoke, :f :write, :value [1 (rand-int 5)]})
(defn cas [_ _] {:type :invoke, :f :cas, :value [1 [(rand-int 5) (rand-int 5)]]})
(defn client
[n]
(DirtyReadsClient. nil n))
(defn dirty-reads-checker
"We're looking for a failed transaction whose value became visible to some
read."
[]
(reify checker/Checker
(check [this test model history opts]
(let [
failed-writes
; Add a dummy failed write so we have something to compare to in the
; unlikely case that there's no other write failures
(merge {:type :fail, :f :write, :value -12, :process 0, :time 0}
(->> history
(r/filter op/fail?)
(r/filter #(= :write (:f %)))
(r/map :value)
(into (hash-set))))
reads (->> history
(r/filter op/ok?)
(r/filter #(= :read (:f %)))
(r/map :value))
inconsistent-reads (->> reads
(r/filter (partial apply not=))
(into []))
filthy-reads (->> reads
(r/filter (partial some failed-writes))
(into []))]
{:valid? (empty? filthy-reads)
:inconsistent-reads inconsistent-reads
:dirty-reads filthy-reads}))))
(def dirty-reads-reads {:type :invoke, :f :read, :value nil})
(def dirty-reads-writes (->> (range)
(map (partial array-map
:type :invoke,
:f :write,
:value))
gen/seq))
(defn dirty-reads-basic-test
[opts]
(merge tests/noop-test
{:name "dirty-reads"
:nodes ["m1" "m2" "m3" "m4" "m5"]
:ssh {
:username "root"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:strict-host-key-checking false
}
:db (db (:version opts))
:nemesis (nemesis/partition-random-halves)}
(dissoc opts :name :version)))
(defn minutes [seconds] (* 60 seconds))
(defn dirty-reads-tester
[version n]
(dirty-reads-basic-test
{:name "dirty reads"
:concurrency 1
:version version
:client (client n)
:generator (->> (gen/mix [dirty-reads-reads dirty-reads-writes])
gen/clients
(gen/time-limit 10))
:nemesis nemesis/noop
:checker (checker/compose
{:perf (checker/perf)
:dirty-reads (dirty-reads-checker)
:linearizable (independent/checker checker/linearizable)})}))
(defn register-tester
[opts]
(basic-test
(merge
{:name "register"
:client (comdb2-cas-register-client nil)
:concurrency 10
:generator (gen/phases
(->> (gen/mix [w cas cas r])
(gen/clients)
(gen/stagger 1/10)
(gen/time-limit 10))
(gen/log "waiting for quiescence")
(gen/sleep 10))
:model (model/cas-register-comdb2 [1 1])
:time-limit 100
:recovery-time 30
:checker (checker/compose
{:perf (checker/perf)
:linearizable checker/linearizable}) }
opts)))
(defn register-tester-nemesis
[opts]
(basic-test
(merge
{:name "register"
:client (comdb2-cas-register-client nil)
:concurrency 10
:generator (gen/phases
(->> (gen/mix [w cas cas r])
(gen/clients)
(gen/stagger 1/10)
(gen/time-limit 300)
with-nemesis)
(gen/log "waiting for quiescence")
(gen/sleep 10))
:model (model/cas-register-comdb2 [1 1])
:time-limit 300
:recovery-time 30
:checker (checker/compose
{:perf (checker/perf)
:linearizable checker/linearizable}) }
opts)))
|
[
{
"context": "\n(def opts\n {:values {:email \"foobar\" :password \"p@sswOad\"}\n :errors {:email \"please input your email add",
"end": 304,
"score": 0.9994069933891296,
"start": 296,
"tag": "PASSWORD",
"value": "p@sswOad"
}
] | examples/benchmark/src/example/core.clj | ayato-p/kuuga | 23 | (ns example.core
(:gen-class)
(:require [criterium.core :as criterium]
[hiccup2.core :as hiccup]))
;; load order is important thing just in this test
(require 'example.naive)
(require 'example.macro)
(require 'example.function)
(def opts
{:values {:email "foobar" :password "p@sswOad"}
:errors {:email "please input your email address"}})
(defn execute-naive-version []
(example.naive/naive-form opts))
(defn execute-macro-version []
(example.macro/macro-form opts))
(defn execute-function-version []
(example.function/function-form opts))
(defn same-result? []
;; should be true
(println (= (str (hiccup/html (execute-naive-version)))
(str (hiccup/html (execute-macro-version)))
(str (hiccup/html (execute-function-version))))))
(defn -main [& args]
(same-result?)
(println "naive version")
(criterium/bench (execute-naive-version))
(println "macro version")
(criterium/bench (execute-macro-version))
(println "function version")
(criterium/bench (execute-function-version)))
| 30795 | (ns example.core
(:gen-class)
(:require [criterium.core :as criterium]
[hiccup2.core :as hiccup]))
;; load order is important thing just in this test
(require 'example.naive)
(require 'example.macro)
(require 'example.function)
(def opts
{:values {:email "foobar" :password "<PASSWORD>"}
:errors {:email "please input your email address"}})
(defn execute-naive-version []
(example.naive/naive-form opts))
(defn execute-macro-version []
(example.macro/macro-form opts))
(defn execute-function-version []
(example.function/function-form opts))
(defn same-result? []
;; should be true
(println (= (str (hiccup/html (execute-naive-version)))
(str (hiccup/html (execute-macro-version)))
(str (hiccup/html (execute-function-version))))))
(defn -main [& args]
(same-result?)
(println "naive version")
(criterium/bench (execute-naive-version))
(println "macro version")
(criterium/bench (execute-macro-version))
(println "function version")
(criterium/bench (execute-function-version)))
| true | (ns example.core
(:gen-class)
(:require [criterium.core :as criterium]
[hiccup2.core :as hiccup]))
;; load order is important thing just in this test
(require 'example.naive)
(require 'example.macro)
(require 'example.function)
(def opts
{:values {:email "foobar" :password "PI:PASSWORD:<PASSWORD>END_PI"}
:errors {:email "please input your email address"}})
(defn execute-naive-version []
(example.naive/naive-form opts))
(defn execute-macro-version []
(example.macro/macro-form opts))
(defn execute-function-version []
(example.function/function-form opts))
(defn same-result? []
;; should be true
(println (= (str (hiccup/html (execute-naive-version)))
(str (hiccup/html (execute-macro-version)))
(str (hiccup/html (execute-function-version))))))
(defn -main [& args]
(same-result?)
(println "naive version")
(criterium/bench (execute-naive-version))
(println "macro version")
(criterium/bench (execute-macro-version))
(println "function version")
(criterium/bench (execute-function-version)))
|
[
{
"context": "rg/html/rfc4648#section-10\n - https://github.com/eth-r/multibase/tree/master/tests\"\n (:require\n [alp",
"end": 132,
"score": 0.9993942379951477,
"start": 127,
"tag": "USERNAME",
"value": "eth-r"
},
{
"context": "IQ\"\n :base64pad \"MRGVjZW50cmFsaXplIGV2ZXJ5dGhpbmchIQ==\"\n :base64url \"uRGV",
"end": 5884,
"score": 0.5073392987251282,
"start": 5883,
"tag": "KEY",
"value": "V"
},
{
"context": " :base64pad \"MRGVjZW50cmFsaXplIGV2ZXJ5dGhpbmchIQ==\"\n :base64url \"uRGVjZW50",
"end": 5889,
"score": 0.5230979323387146,
"start": 5888,
"tag": "KEY",
"value": "5"
},
{
"context": "GV2ZXJ5dGhpbmchIQ==\"\n :base64url \"uRGVjZW50cmFsaXplIGV2ZXJ5dGhpbmchIQ\"\n :base64",
"end": 5939,
"score": 0.6578136682510376,
"start": 5932,
"tag": "KEY",
"value": "GVjZW50"
},
{
"context": "hpbmchIQ==\"\n :base64url \"uRGVjZW50cmFsaXplIGV2ZXJ5dGhpbmchIQ\"\n :base64url",
"end": 5942,
"score": 0.5996958613395691,
"start": 5941,
"tag": "KEY",
"value": "F"
},
{
"context": "mchIQ==\"\n :base64url \"uRGVjZW50cmFsaXplIGV2ZXJ5dGhpbmchIQ\"\n :base64urlpad \"",
"end": 5947,
"score": 0.576996386051178,
"start": 5944,
"tag": "KEY",
"value": "Xpl"
},
{
"context": "==\"\n :base64url \"uRGVjZW50cmFsaXplIGV2ZXJ5dGhpbmchIQ\"\n :base64urlpad \"URGVjZW50cmFsaXplI",
"end": 5965,
"score": 0.6622928380966187,
"start": 5949,
"tag": "KEY",
"value": "V2ZXJ5dGhpbmchIQ"
}
] | test/multiformats/base_test.cljc | aria42/clj-multiformats | 0 | (ns multiformats.base-test
"Test cases drawn from:
- https://tools.ietf.org/html/rfc4648#section-10
- https://github.com/eth-r/multibase/tree/master/tests"
(:require
[alphabase.bytes :as b :refer [bytes=]]
[clojure.string :as str]
#?(:clj [clojure.test :refer [deftest testing is]]
:cljs [cljs.test :refer-macros [deftest testing is]])
#?(:cljs [goog.crypt :as crypt])
[multiformats.base :as mbase]))
(deftest base-setup
#?(:clj
(testing "install-base"
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"registered with invalid key"
(#'mbase/install-base {} {:key 123})))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"has no assigned prefix code"
(#'mbase/install-base {} {:key :foo})))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"is already registered"
(#'mbase/install-base {:base1 {}} {:key :base1})))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"does not specify a formatter function"
(#'mbase/install-base {} {:key :base1})))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"does not specify a parser function"
(#'mbase/install-base {} {:key :base1, :formatter identity}))))))
(deftest arg-validation
(testing "formatting"
(is (thrown-with-msg? #?(:clj clojure.lang.ExceptionInfo
:cljs js/Error)
#"must be a keyword"
(mbase/format* 123 (b/byte-array 1))))
(is (thrown-with-msg? #?(:clj clojure.lang.ExceptionInfo
:cljs js/Error)
#"not format empty data"
(mbase/format :base32 (b/byte-array 0))))
(is (thrown-with-msg? #?(:clj clojure.lang.ExceptionInfo
:cljs js/Error)
#"foo does not have a supported multibase formatter"
(mbase/format :foo (b/byte-array 1)))))
(testing "parsing"
(is (thrown-with-msg? #?(:clj clojure.lang.ExceptionInfo
:cljs js/Error)
#"must be a keyword"
(mbase/parse* 123 "abc")))
(is (thrown-with-msg? #?(:clj clojure.lang.ExceptionInfo
:cljs js/Error)
#"foo does not have a supported multibase parser"
(mbase/parse* :foo "abc")))
(is (thrown-with-msg? #?(:clj clojure.lang.ExceptionInfo
:cljs js/Error)
#"is too short to be multibase-formatted data"
(mbase/parse "")))
(is (thrown-with-msg? #?(:clj clojure.lang.ExceptionInfo
:cljs js/Error)
#"is too short to be multibase-formatted data"
(mbase/parse "1")))
(is (thrown-with-msg? #?(:clj clojure.lang.ExceptionInfo
:cljs js/Error)
#"prefix \"x\" does not map to a supported multibase encoding"
(mbase/parse "xabc")))))
(defn- string-bytes
"Get a UTF-8 byte array from a string."
[string]
(#?(:clj .getBytes, :cljs crypt/stringToUtf8ByteArray) string))
(deftest rfc-vectors
(doseq [[base input encoded]
[[:base64pad "f" "MZg=="]
[:base64pad "fo" "MZm8="]
[:base64 "foo" "mZm9v"]
[:base64pad "foob" "MZm9vYg=="]
[:base64pad "fooba" "MZm9vYmE="]
[:base64 "foobar" "mZm9vYmFy"]
[:base32pad "f" "cmy======"]
[:BASE32PAD "fo" "CMZXQ===="]
[:base32pad "foo" "cmzxw6==="]
[:BASE32PAD "foob" "CMZXW6YQ="]
[:base32 "fooba" "bmzxw6ytb"]
[:BASE32 "foobar" "BMZXW6YTBOI"]
[:base32hexpad "f" "tco======"]
[:BASE32HEXPAD "fo" "TCPNG===="]
[:BASE32HEXPAD "foo" "TCPNMU==="]
[:base32hex "foob" "vcpnmuog"]
[:BASE32HEX "fooba" "VCPNMUOJ1"]
[:BASE32HEXPAD "foobar" "TCPNMUOJ1E8======"]
[:BASE16 "f" "F66"]
[:BASE16 "fo" "F666F"]
[:BASE16 "foo" "F666F6F"]
[:BASE16 "foob" "F666F6F62"]
[:BASE16 "fooba" "F666F6F6261"]
[:BASE16 "foobar" "F666F6F626172"]]]
(testing (name base)
(let [data (string-bytes input)]
(is (= encoded (mbase/format base data)))
(is (bytes= data (mbase/parse encoded)))))))
(deftest example-1
(let [data (string-bytes "Decentralize everything!!")
cases {:base2 "001000100011001010110001101100101011011100111010001110010011000010110110001101001011110100110010100100000011001010111011001100101011100100111100101110100011010000110100101101110011001110010000100100001"
:base8 "71043126154533472162302661513646244031273145344745643206455631620441"
;:base10 "9429328951066508984658627669258025763026247056774804621697313"
:base16 "f446563656e7472616c697a652065766572797468696e672121"
:BASE16 "F446563656E7472616C697A652065766572797468696E672121"
:base32 "birswgzloorzgc3djpjssazlwmvzhs5dinfxgoijb"
:BASE32 "BIRSWGZLOORZGC3DJPJSSAZLWMVZHS5DINFXGOIJB"
:base32pad "cirswgzloorzgc3djpjssazlwmvzhs5dinfxgoijb"
:BASE32PAD "CIRSWGZLOORZGC3DJPJSSAZLWMVZHS5DINFXGOIJB"
:base32hex "v8him6pbeehp62r39f9ii0pbmclp7it38d5n6e891"
:BASE32HEX "V8HIM6PBEEHP62R39F9II0PBMCLP7IT38D5N6E891"
:base32hexpad "t8him6pbeehp62r39f9ii0pbmclp7it38d5n6e891"
:BASE32HEXPAD "T8HIM6PBEEHP62R39F9II0PBMCLP7IT38D5N6E891"
;:base32z "het1sg3mqqt3gn5djxj11y3msci3817depfzgqejb"
;:base58flickr "Ztwe7gVTeK8wswS1gf8hrgAua9fcw9reboD"
:base58btc "zUXE7GvtEk8XTXs1GF8HSGbVA9FCX9SEBPe"
:base64 "mRGVjZW50cmFsaXplIGV2ZXJ5dGhpbmchIQ"
:base64pad "MRGVjZW50cmFsaXplIGV2ZXJ5dGhpbmchIQ=="
:base64url "uRGVjZW50cmFsaXplIGV2ZXJ5dGhpbmchIQ"
:base64urlpad "URGVjZW50cmFsaXplIGV2ZXJ5dGhpbmchIQ=="}]
(doseq [[base encoded] cases]
(testing (name base)
(is (= encoded (mbase/format base data)))
(is (bytes= data (mbase/parse encoded)))))))
(deftest example-2
(let [data (string-bytes "yes mani !")
cases {:base2 "001111001011001010111001100100000011011010110000101101110011010010010000000100001"
:base8 "7171312714403326055632220041"
;:base10 "9573277761329450583662625"
:base16 "f796573206d616e692021"
:BASE16 "F796573206D616E692021"
:base32 "bpfsxgidnmfxgsibb"
:BASE32 "BPFSXGIDNMFXGSIBB"
:base32pad "cpfsxgidnmfxgsibb"
:BASE32PAD "CPFSXGIDNMFXGSIBB"
:base32hex "vf5in683dc5n6i811"
:BASE32HEX "VF5IN683DC5N6I811"
:base32hexpad "tf5in683dc5n6i811"
:BASE32HEXPAD "TF5IN683DC5N6I811"
;:base32z "hxf1zgedpcfzg1ebb"
;:base58flickr "Z7Pznk19XTTzBtx"
:base58btc "z7paNL19xttacUY"
:base64 "meWVzIG1hbmkgIQ"
:base64pad "MeWVzIG1hbmkgIQ=="
:base64url "ueWVzIG1hbmkgIQ"
:base64urlpad "UeWVzIG1hbmkgIQ=="}]
(doseq [[base encoded] cases]
(testing (name base)
(is (= encoded (mbase/format base data)))
(is (bytes= data (mbase/parse encoded)))))))
(deftest example-3
(let [data (string-bytes "hello world")
cases {:base2 "00110100001100101011011000110110001101111001000000111011101101111011100100110110001100100"
:base8 "764145330661571007355734466144" ; originally had leading zero?
;:base10 "9126207244316550804821666916"
:base16 "f68656c6c6f20776f726c64"
:BASE16 "F68656C6C6F20776F726C64"
:base32 "bnbswy3dpeb3w64tmmq"
:BASE32 "BNBSWY3DPEB3W64TMMQ"
:base32pad "cnbswy3dpeb3w64tmmq======"
:BASE32PAD "CNBSWY3DPEB3W64TMMQ======"
:base32hex "vd1imor3f41rmusjccg"
:BASE32HEX "VD1IMOR3F41RMUSJCCG"
:base32hexpad "td1imor3f41rmusjccg======"
:BASE32HEXPAD "TD1IMOR3F41RMUSJCCG======"
;:base32z "hpb1sa5dxrb5s6hucco"
;:base58flickr "ZrTu1dk6cWsRYjYu"
:base58btc "zStV1DL6CwTryKyV"
:base64 "maGVsbG8gd29ybGQ"
:base64pad "MaGVsbG8gd29ybGQ="
:base64url "uaGVsbG8gd29ybGQ"
:base64urlpad "UaGVsbG8gd29ybGQ="}]
(doseq [[base encoded] cases]
(testing (name base)
(is (= encoded (mbase/format base data)))
(is (bytes= data (mbase/parse encoded)))))))
(deftest mixed-case
(let [data (string-bytes "hello world")]
(testing "base16 vs BASE16"
(is (bytes= data (mbase/parse "f68656c6c6f20776F726C64")))
(is (bytes= data (mbase/parse "F68656c6c6f20776F726C64"))))
(testing "base32 vs BASE32"
(is (bytes= data (mbase/parse "bnbswy3dpeB3W64TMMQ")))
(is (bytes= data (mbase/parse "Bnbswy3dpeB3W64TMMQ"))))
(testing "base32hex vs BASE32HEX"
(is (bytes= data (mbase/parse "vd1imor3f41RMUSJCCG")))
(is (bytes= data (mbase/parse "Vd1imor3f41RMUSJCCG"))))
(testing "base32pad vs BASE32PAD"
(is (bytes= data (mbase/parse "cnbswy3dpeB3W64TMMQ======")))
(is (bytes= data (mbase/parse "Cnbswy3dpeB3W64TMMQ======"))))
(testing "base32hexpad vs BASE32HEXPAD"
(is (bytes= data (mbase/parse "td1imor3f41RMUSJCCG======")))
(is (bytes= data (mbase/parse "Td1imor3f41RMUSJCCG======"))))))
(deftest miscellaneous
(testing "binary padding"
(is (bytes= (b/init-bytes [0x01 0x23 0x45])
(mbase/parse "00010010001101000101"))))
(testing "inspect"
(let [info (mbase/inspect "zUXE7GvtEk8XTXs1GF8HSGbVA9FCX9SEBPe")]
(is (map? info))
(is (= "z" (:prefix info)))
(is (= :base58btc (:base info))))))
| 25740 | (ns multiformats.base-test
"Test cases drawn from:
- https://tools.ietf.org/html/rfc4648#section-10
- https://github.com/eth-r/multibase/tree/master/tests"
(:require
[alphabase.bytes :as b :refer [bytes=]]
[clojure.string :as str]
#?(:clj [clojure.test :refer [deftest testing is]]
:cljs [cljs.test :refer-macros [deftest testing is]])
#?(:cljs [goog.crypt :as crypt])
[multiformats.base :as mbase]))
(deftest base-setup
#?(:clj
(testing "install-base"
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"registered with invalid key"
(#'mbase/install-base {} {:key 123})))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"has no assigned prefix code"
(#'mbase/install-base {} {:key :foo})))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"is already registered"
(#'mbase/install-base {:base1 {}} {:key :base1})))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"does not specify a formatter function"
(#'mbase/install-base {} {:key :base1})))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"does not specify a parser function"
(#'mbase/install-base {} {:key :base1, :formatter identity}))))))
(deftest arg-validation
(testing "formatting"
(is (thrown-with-msg? #?(:clj clojure.lang.ExceptionInfo
:cljs js/Error)
#"must be a keyword"
(mbase/format* 123 (b/byte-array 1))))
(is (thrown-with-msg? #?(:clj clojure.lang.ExceptionInfo
:cljs js/Error)
#"not format empty data"
(mbase/format :base32 (b/byte-array 0))))
(is (thrown-with-msg? #?(:clj clojure.lang.ExceptionInfo
:cljs js/Error)
#"foo does not have a supported multibase formatter"
(mbase/format :foo (b/byte-array 1)))))
(testing "parsing"
(is (thrown-with-msg? #?(:clj clojure.lang.ExceptionInfo
:cljs js/Error)
#"must be a keyword"
(mbase/parse* 123 "abc")))
(is (thrown-with-msg? #?(:clj clojure.lang.ExceptionInfo
:cljs js/Error)
#"foo does not have a supported multibase parser"
(mbase/parse* :foo "abc")))
(is (thrown-with-msg? #?(:clj clojure.lang.ExceptionInfo
:cljs js/Error)
#"is too short to be multibase-formatted data"
(mbase/parse "")))
(is (thrown-with-msg? #?(:clj clojure.lang.ExceptionInfo
:cljs js/Error)
#"is too short to be multibase-formatted data"
(mbase/parse "1")))
(is (thrown-with-msg? #?(:clj clojure.lang.ExceptionInfo
:cljs js/Error)
#"prefix \"x\" does not map to a supported multibase encoding"
(mbase/parse "xabc")))))
(defn- string-bytes
"Get a UTF-8 byte array from a string."
[string]
(#?(:clj .getBytes, :cljs crypt/stringToUtf8ByteArray) string))
(deftest rfc-vectors
(doseq [[base input encoded]
[[:base64pad "f" "MZg=="]
[:base64pad "fo" "MZm8="]
[:base64 "foo" "mZm9v"]
[:base64pad "foob" "MZm9vYg=="]
[:base64pad "fooba" "MZm9vYmE="]
[:base64 "foobar" "mZm9vYmFy"]
[:base32pad "f" "cmy======"]
[:BASE32PAD "fo" "CMZXQ===="]
[:base32pad "foo" "cmzxw6==="]
[:BASE32PAD "foob" "CMZXW6YQ="]
[:base32 "fooba" "bmzxw6ytb"]
[:BASE32 "foobar" "BMZXW6YTBOI"]
[:base32hexpad "f" "tco======"]
[:BASE32HEXPAD "fo" "TCPNG===="]
[:BASE32HEXPAD "foo" "TCPNMU==="]
[:base32hex "foob" "vcpnmuog"]
[:BASE32HEX "fooba" "VCPNMUOJ1"]
[:BASE32HEXPAD "foobar" "TCPNMUOJ1E8======"]
[:BASE16 "f" "F66"]
[:BASE16 "fo" "F666F"]
[:BASE16 "foo" "F666F6F"]
[:BASE16 "foob" "F666F6F62"]
[:BASE16 "fooba" "F666F6F6261"]
[:BASE16 "foobar" "F666F6F626172"]]]
(testing (name base)
(let [data (string-bytes input)]
(is (= encoded (mbase/format base data)))
(is (bytes= data (mbase/parse encoded)))))))
(deftest example-1
(let [data (string-bytes "Decentralize everything!!")
cases {:base2 "001000100011001010110001101100101011011100111010001110010011000010110110001101001011110100110010100100000011001010111011001100101011100100111100101110100011010000110100101101110011001110010000100100001"
:base8 "71043126154533472162302661513646244031273145344745643206455631620441"
;:base10 "9429328951066508984658627669258025763026247056774804621697313"
:base16 "f446563656e7472616c697a652065766572797468696e672121"
:BASE16 "F446563656E7472616C697A652065766572797468696E672121"
:base32 "birswgzloorzgc3djpjssazlwmvzhs5dinfxgoijb"
:BASE32 "BIRSWGZLOORZGC3DJPJSSAZLWMVZHS5DINFXGOIJB"
:base32pad "cirswgzloorzgc3djpjssazlwmvzhs5dinfxgoijb"
:BASE32PAD "CIRSWGZLOORZGC3DJPJSSAZLWMVZHS5DINFXGOIJB"
:base32hex "v8him6pbeehp62r39f9ii0pbmclp7it38d5n6e891"
:BASE32HEX "V8HIM6PBEEHP62R39F9II0PBMCLP7IT38D5N6E891"
:base32hexpad "t8him6pbeehp62r39f9ii0pbmclp7it38d5n6e891"
:BASE32HEXPAD "T8HIM6PBEEHP62R39F9II0PBMCLP7IT38D5N6E891"
;:base32z "het1sg3mqqt3gn5djxj11y3msci3817depfzgqejb"
;:base58flickr "Ztwe7gVTeK8wswS1gf8hrgAua9fcw9reboD"
:base58btc "zUXE7GvtEk8XTXs1GF8HSGbVA9FCX9SEBPe"
:base64 "mRGVjZW50cmFsaXplIGV2ZXJ5dGhpbmchIQ"
:base64pad "MRGVjZW50cmFsaXplIG<KEY>2ZXJ<KEY>dGhpbmchIQ=="
:base64url "uR<KEY>cm<KEY>sa<KEY>IG<KEY>"
:base64urlpad "URGVjZW50cmFsaXplIGV2ZXJ5dGhpbmchIQ=="}]
(doseq [[base encoded] cases]
(testing (name base)
(is (= encoded (mbase/format base data)))
(is (bytes= data (mbase/parse encoded)))))))
(deftest example-2
(let [data (string-bytes "yes mani !")
cases {:base2 "001111001011001010111001100100000011011010110000101101110011010010010000000100001"
:base8 "7171312714403326055632220041"
;:base10 "9573277761329450583662625"
:base16 "f796573206d616e692021"
:BASE16 "F796573206D616E692021"
:base32 "bpfsxgidnmfxgsibb"
:BASE32 "BPFSXGIDNMFXGSIBB"
:base32pad "cpfsxgidnmfxgsibb"
:BASE32PAD "CPFSXGIDNMFXGSIBB"
:base32hex "vf5in683dc5n6i811"
:BASE32HEX "VF5IN683DC5N6I811"
:base32hexpad "tf5in683dc5n6i811"
:BASE32HEXPAD "TF5IN683DC5N6I811"
;:base32z "hxf1zgedpcfzg1ebb"
;:base58flickr "Z7Pznk19XTTzBtx"
:base58btc "z7paNL19xttacUY"
:base64 "meWVzIG1hbmkgIQ"
:base64pad "MeWVzIG1hbmkgIQ=="
:base64url "ueWVzIG1hbmkgIQ"
:base64urlpad "UeWVzIG1hbmkgIQ=="}]
(doseq [[base encoded] cases]
(testing (name base)
(is (= encoded (mbase/format base data)))
(is (bytes= data (mbase/parse encoded)))))))
(deftest example-3
(let [data (string-bytes "hello world")
cases {:base2 "00110100001100101011011000110110001101111001000000111011101101111011100100110110001100100"
:base8 "764145330661571007355734466144" ; originally had leading zero?
;:base10 "9126207244316550804821666916"
:base16 "f68656c6c6f20776f726c64"
:BASE16 "F68656C6C6F20776F726C64"
:base32 "bnbswy3dpeb3w64tmmq"
:BASE32 "BNBSWY3DPEB3W64TMMQ"
:base32pad "cnbswy3dpeb3w64tmmq======"
:BASE32PAD "CNBSWY3DPEB3W64TMMQ======"
:base32hex "vd1imor3f41rmusjccg"
:BASE32HEX "VD1IMOR3F41RMUSJCCG"
:base32hexpad "td1imor3f41rmusjccg======"
:BASE32HEXPAD "TD1IMOR3F41RMUSJCCG======"
;:base32z "hpb1sa5dxrb5s6hucco"
;:base58flickr "ZrTu1dk6cWsRYjYu"
:base58btc "zStV1DL6CwTryKyV"
:base64 "maGVsbG8gd29ybGQ"
:base64pad "MaGVsbG8gd29ybGQ="
:base64url "uaGVsbG8gd29ybGQ"
:base64urlpad "UaGVsbG8gd29ybGQ="}]
(doseq [[base encoded] cases]
(testing (name base)
(is (= encoded (mbase/format base data)))
(is (bytes= data (mbase/parse encoded)))))))
(deftest mixed-case
(let [data (string-bytes "hello world")]
(testing "base16 vs BASE16"
(is (bytes= data (mbase/parse "f68656c6c6f20776F726C64")))
(is (bytes= data (mbase/parse "F68656c6c6f20776F726C64"))))
(testing "base32 vs BASE32"
(is (bytes= data (mbase/parse "bnbswy3dpeB3W64TMMQ")))
(is (bytes= data (mbase/parse "Bnbswy3dpeB3W64TMMQ"))))
(testing "base32hex vs BASE32HEX"
(is (bytes= data (mbase/parse "vd1imor3f41RMUSJCCG")))
(is (bytes= data (mbase/parse "Vd1imor3f41RMUSJCCG"))))
(testing "base32pad vs BASE32PAD"
(is (bytes= data (mbase/parse "cnbswy3dpeB3W64TMMQ======")))
(is (bytes= data (mbase/parse "Cnbswy3dpeB3W64TMMQ======"))))
(testing "base32hexpad vs BASE32HEXPAD"
(is (bytes= data (mbase/parse "td1imor3f41RMUSJCCG======")))
(is (bytes= data (mbase/parse "Td1imor3f41RMUSJCCG======"))))))
(deftest miscellaneous
(testing "binary padding"
(is (bytes= (b/init-bytes [0x01 0x23 0x45])
(mbase/parse "00010010001101000101"))))
(testing "inspect"
(let [info (mbase/inspect "zUXE7GvtEk8XTXs1GF8HSGbVA9FCX9SEBPe")]
(is (map? info))
(is (= "z" (:prefix info)))
(is (= :base58btc (:base info))))))
| true | (ns multiformats.base-test
"Test cases drawn from:
- https://tools.ietf.org/html/rfc4648#section-10
- https://github.com/eth-r/multibase/tree/master/tests"
(:require
[alphabase.bytes :as b :refer [bytes=]]
[clojure.string :as str]
#?(:clj [clojure.test :refer [deftest testing is]]
:cljs [cljs.test :refer-macros [deftest testing is]])
#?(:cljs [goog.crypt :as crypt])
[multiformats.base :as mbase]))
(deftest base-setup
#?(:clj
(testing "install-base"
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"registered with invalid key"
(#'mbase/install-base {} {:key 123})))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"has no assigned prefix code"
(#'mbase/install-base {} {:key :foo})))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"is already registered"
(#'mbase/install-base {:base1 {}} {:key :base1})))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"does not specify a formatter function"
(#'mbase/install-base {} {:key :base1})))
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"does not specify a parser function"
(#'mbase/install-base {} {:key :base1, :formatter identity}))))))
(deftest arg-validation
(testing "formatting"
(is (thrown-with-msg? #?(:clj clojure.lang.ExceptionInfo
:cljs js/Error)
#"must be a keyword"
(mbase/format* 123 (b/byte-array 1))))
(is (thrown-with-msg? #?(:clj clojure.lang.ExceptionInfo
:cljs js/Error)
#"not format empty data"
(mbase/format :base32 (b/byte-array 0))))
(is (thrown-with-msg? #?(:clj clojure.lang.ExceptionInfo
:cljs js/Error)
#"foo does not have a supported multibase formatter"
(mbase/format :foo (b/byte-array 1)))))
(testing "parsing"
(is (thrown-with-msg? #?(:clj clojure.lang.ExceptionInfo
:cljs js/Error)
#"must be a keyword"
(mbase/parse* 123 "abc")))
(is (thrown-with-msg? #?(:clj clojure.lang.ExceptionInfo
:cljs js/Error)
#"foo does not have a supported multibase parser"
(mbase/parse* :foo "abc")))
(is (thrown-with-msg? #?(:clj clojure.lang.ExceptionInfo
:cljs js/Error)
#"is too short to be multibase-formatted data"
(mbase/parse "")))
(is (thrown-with-msg? #?(:clj clojure.lang.ExceptionInfo
:cljs js/Error)
#"is too short to be multibase-formatted data"
(mbase/parse "1")))
(is (thrown-with-msg? #?(:clj clojure.lang.ExceptionInfo
:cljs js/Error)
#"prefix \"x\" does not map to a supported multibase encoding"
(mbase/parse "xabc")))))
(defn- string-bytes
"Get a UTF-8 byte array from a string."
[string]
(#?(:clj .getBytes, :cljs crypt/stringToUtf8ByteArray) string))
(deftest rfc-vectors
(doseq [[base input encoded]
[[:base64pad "f" "MZg=="]
[:base64pad "fo" "MZm8="]
[:base64 "foo" "mZm9v"]
[:base64pad "foob" "MZm9vYg=="]
[:base64pad "fooba" "MZm9vYmE="]
[:base64 "foobar" "mZm9vYmFy"]
[:base32pad "f" "cmy======"]
[:BASE32PAD "fo" "CMZXQ===="]
[:base32pad "foo" "cmzxw6==="]
[:BASE32PAD "foob" "CMZXW6YQ="]
[:base32 "fooba" "bmzxw6ytb"]
[:BASE32 "foobar" "BMZXW6YTBOI"]
[:base32hexpad "f" "tco======"]
[:BASE32HEXPAD "fo" "TCPNG===="]
[:BASE32HEXPAD "foo" "TCPNMU==="]
[:base32hex "foob" "vcpnmuog"]
[:BASE32HEX "fooba" "VCPNMUOJ1"]
[:BASE32HEXPAD "foobar" "TCPNMUOJ1E8======"]
[:BASE16 "f" "F66"]
[:BASE16 "fo" "F666F"]
[:BASE16 "foo" "F666F6F"]
[:BASE16 "foob" "F666F6F62"]
[:BASE16 "fooba" "F666F6F6261"]
[:BASE16 "foobar" "F666F6F626172"]]]
(testing (name base)
(let [data (string-bytes input)]
(is (= encoded (mbase/format base data)))
(is (bytes= data (mbase/parse encoded)))))))
(deftest example-1
(let [data (string-bytes "Decentralize everything!!")
cases {:base2 "001000100011001010110001101100101011011100111010001110010011000010110110001101001011110100110010100100000011001010111011001100101011100100111100101110100011010000110100101101110011001110010000100100001"
:base8 "71043126154533472162302661513646244031273145344745643206455631620441"
;:base10 "9429328951066508984658627669258025763026247056774804621697313"
:base16 "f446563656e7472616c697a652065766572797468696e672121"
:BASE16 "F446563656E7472616C697A652065766572797468696E672121"
:base32 "birswgzloorzgc3djpjssazlwmvzhs5dinfxgoijb"
:BASE32 "BIRSWGZLOORZGC3DJPJSSAZLWMVZHS5DINFXGOIJB"
:base32pad "cirswgzloorzgc3djpjssazlwmvzhs5dinfxgoijb"
:BASE32PAD "CIRSWGZLOORZGC3DJPJSSAZLWMVZHS5DINFXGOIJB"
:base32hex "v8him6pbeehp62r39f9ii0pbmclp7it38d5n6e891"
:BASE32HEX "V8HIM6PBEEHP62R39F9II0PBMCLP7IT38D5N6E891"
:base32hexpad "t8him6pbeehp62r39f9ii0pbmclp7it38d5n6e891"
:BASE32HEXPAD "T8HIM6PBEEHP62R39F9II0PBMCLP7IT38D5N6E891"
;:base32z "het1sg3mqqt3gn5djxj11y3msci3817depfzgqejb"
;:base58flickr "Ztwe7gVTeK8wswS1gf8hrgAua9fcw9reboD"
:base58btc "zUXE7GvtEk8XTXs1GF8HSGbVA9FCX9SEBPe"
:base64 "mRGVjZW50cmFsaXplIGV2ZXJ5dGhpbmchIQ"
:base64pad "MRGVjZW50cmFsaXplIGPI:KEY:<KEY>END_PI2ZXJPI:KEY:<KEY>END_PIdGhpbmchIQ=="
:base64url "uRPI:KEY:<KEY>END_PIcmPI:KEY:<KEY>END_PIsaPI:KEY:<KEY>END_PIIGPI:KEY:<KEY>END_PI"
:base64urlpad "URGVjZW50cmFsaXplIGV2ZXJ5dGhpbmchIQ=="}]
(doseq [[base encoded] cases]
(testing (name base)
(is (= encoded (mbase/format base data)))
(is (bytes= data (mbase/parse encoded)))))))
(deftest example-2
(let [data (string-bytes "yes mani !")
cases {:base2 "001111001011001010111001100100000011011010110000101101110011010010010000000100001"
:base8 "7171312714403326055632220041"
;:base10 "9573277761329450583662625"
:base16 "f796573206d616e692021"
:BASE16 "F796573206D616E692021"
:base32 "bpfsxgidnmfxgsibb"
:BASE32 "BPFSXGIDNMFXGSIBB"
:base32pad "cpfsxgidnmfxgsibb"
:BASE32PAD "CPFSXGIDNMFXGSIBB"
:base32hex "vf5in683dc5n6i811"
:BASE32HEX "VF5IN683DC5N6I811"
:base32hexpad "tf5in683dc5n6i811"
:BASE32HEXPAD "TF5IN683DC5N6I811"
;:base32z "hxf1zgedpcfzg1ebb"
;:base58flickr "Z7Pznk19XTTzBtx"
:base58btc "z7paNL19xttacUY"
:base64 "meWVzIG1hbmkgIQ"
:base64pad "MeWVzIG1hbmkgIQ=="
:base64url "ueWVzIG1hbmkgIQ"
:base64urlpad "UeWVzIG1hbmkgIQ=="}]
(doseq [[base encoded] cases]
(testing (name base)
(is (= encoded (mbase/format base data)))
(is (bytes= data (mbase/parse encoded)))))))
(deftest example-3
(let [data (string-bytes "hello world")
cases {:base2 "00110100001100101011011000110110001101111001000000111011101101111011100100110110001100100"
:base8 "764145330661571007355734466144" ; originally had leading zero?
;:base10 "9126207244316550804821666916"
:base16 "f68656c6c6f20776f726c64"
:BASE16 "F68656C6C6F20776F726C64"
:base32 "bnbswy3dpeb3w64tmmq"
:BASE32 "BNBSWY3DPEB3W64TMMQ"
:base32pad "cnbswy3dpeb3w64tmmq======"
:BASE32PAD "CNBSWY3DPEB3W64TMMQ======"
:base32hex "vd1imor3f41rmusjccg"
:BASE32HEX "VD1IMOR3F41RMUSJCCG"
:base32hexpad "td1imor3f41rmusjccg======"
:BASE32HEXPAD "TD1IMOR3F41RMUSJCCG======"
;:base32z "hpb1sa5dxrb5s6hucco"
;:base58flickr "ZrTu1dk6cWsRYjYu"
:base58btc "zStV1DL6CwTryKyV"
:base64 "maGVsbG8gd29ybGQ"
:base64pad "MaGVsbG8gd29ybGQ="
:base64url "uaGVsbG8gd29ybGQ"
:base64urlpad "UaGVsbG8gd29ybGQ="}]
(doseq [[base encoded] cases]
(testing (name base)
(is (= encoded (mbase/format base data)))
(is (bytes= data (mbase/parse encoded)))))))
(deftest mixed-case
(let [data (string-bytes "hello world")]
(testing "base16 vs BASE16"
(is (bytes= data (mbase/parse "f68656c6c6f20776F726C64")))
(is (bytes= data (mbase/parse "F68656c6c6f20776F726C64"))))
(testing "base32 vs BASE32"
(is (bytes= data (mbase/parse "bnbswy3dpeB3W64TMMQ")))
(is (bytes= data (mbase/parse "Bnbswy3dpeB3W64TMMQ"))))
(testing "base32hex vs BASE32HEX"
(is (bytes= data (mbase/parse "vd1imor3f41RMUSJCCG")))
(is (bytes= data (mbase/parse "Vd1imor3f41RMUSJCCG"))))
(testing "base32pad vs BASE32PAD"
(is (bytes= data (mbase/parse "cnbswy3dpeB3W64TMMQ======")))
(is (bytes= data (mbase/parse "Cnbswy3dpeB3W64TMMQ======"))))
(testing "base32hexpad vs BASE32HEXPAD"
(is (bytes= data (mbase/parse "td1imor3f41RMUSJCCG======")))
(is (bytes= data (mbase/parse "Td1imor3f41RMUSJCCG======"))))))
(deftest miscellaneous
(testing "binary padding"
(is (bytes= (b/init-bytes [0x01 0x23 0x45])
(mbase/parse "00010010001101000101"))))
(testing "inspect"
(let [info (mbase/inspect "zUXE7GvtEk8XTXs1GF8HSGbVA9FCX9SEBPe")]
(is (map? info))
(is (= "z" (:prefix info)))
(is (= :base58btc (:base info))))))
|
[
{
"context": "eftest missing-dependency-error\n (let [system-key ::system-b\n local-key ::local-b\n a (component/",
"end": 8433,
"score": 0.8303860425949097,
"start": 8423,
"tag": "KEY",
"value": "::system-b"
},
{
"context": "or\n (let [system-key ::system-b\n local-key ::local-b\n a (component/using (component-a) {local-k",
"end": 8461,
"score": 0.7407991886138916,
"start": 8452,
"tag": "KEY",
"value": "::local-b"
}
] | test/com/stuartsierra/component_test.clj | reducecombine/component | 0 | (ns com.stuartsierra.component-test
(:require [clojure.test :refer (deftest is are)]
[clojure.set :refer (map-invert)]
[orchestra.core :refer [defn-spec]]
[orchestra.spec.test :as st]
[com.stuartsierra.component :as component]))
(def ^:dynamic *log* nil)
(defn- log [& args]
(when (thread-bound? #'*log*)
(set! *log* (conj *log* args))))
(defn- ordering
"Given an ordered collection of messages, returns a map from the
head of each message to its index position in the collection."
[log]
(into {} (map-indexed (fn [i [message & _]] [message i]) log)))
(defn before?
"In the collection of messages, does the message beginning with
symbol a come before the message begging with symbol b?"
[log sym-a sym-b]
(let [order (ordering log)]
(< (get order sym-a) (get order sym-b))))
(defn started? [component]
(true? (::started? component)))
(defn stopped? [component]
(false? (::started? component)))
(defrecord ComponentA [state]
component/Lifecycle
(start [this]
(log 'ComponentA.start this)
(assoc this ::started? true))
(stop [this]
(log 'ComponentA.stop this)
(assoc this ::started? false)))
(defn component-a []
(->ComponentA (rand-int Integer/MAX_VALUE)))
(defrecord ComponentB [state a]
component/Lifecycle
(start [this]
(log 'ComponentB.start this)
(assert (started? a))
(assoc this ::started? true))
(stop [this]
(log 'ComponentB.stop this)
(assert (started? a))
(assoc this ::started? false)))
(defn component-b []
(component/using
(map->ComponentB {:state (rand-int Integer/MAX_VALUE)})
[:a]))
(defrecord ComponentC [state a b]
component/Lifecycle
(start [this]
(log 'ComponentC.start this)
(assert (started? a))
(assert (started? b))
(assoc this ::started? true))
(stop [this]
(log 'ComponentC.stop this)
(assert (started? a))
(assert (started? b))
(assoc this ::started? false)))
(defn component-c []
(component/using
(map->ComponentC {:state (rand-int Integer/MAX_VALUE)})
[:a :b]))
(defrecord ComponentD [state my-c b]
component/Lifecycle
(start [this]
(log 'ComponentD.start this)
(assert (started? b))
(assert (started? my-c))
(assoc this ::started? true))
(stop [this]
(log 'ComponentD.stop this)
(assert (started? b))
(assert (started? my-c))
(assoc this ::started? false)))
(defn component-d []
(map->ComponentD {:state (rand-int Integer/MAX_VALUE)}))
(defrecord ComponentE [state]
component/Lifecycle
(start [this]
(log 'ComponentE.start this)
(assoc this ::started? true))
(stop [this]
(log 'ComponentE.stop this)
(assoc this ::started? false)))
(defn component-e []
(map->ComponentE {:state (rand-int Integer/MAX_VALUE)}))
(defrecord System1 [d a e c b] ; deliberately scrambled order
component/Lifecycle
(start [this]
(log 'System1.start this)
(component/start-system this))
(stop [this]
(log 'System1.stop this)
(component/stop-system this)))
(defn system-1 []
(map->System1 {:a (component-a)
:b (component-b)
:c (component-c)
:d (component/using (component-d)
{:b :b
:my-c :c})
:e (component-e)}))
(defmacro with-log [& body]
`(binding [*log* []]
~@body
*log*))
(deftest components-start-in-order
(let [log (with-log (component/start (system-1)))]
(are [k1 k2] (before? log k1 k2)
'ComponentA.start 'ComponentB.start
'ComponentA.start 'ComponentC.start
'ComponentB.start 'ComponentC.start
'ComponentC.start 'ComponentD.start
'ComponentB.start 'ComponentD.start)))
(deftest all-components-started
(let [system (component/start (system-1))]
(doseq [component (vals system)]
(is (started? component)))))
(deftest all-components-stopped
(let [system (component/stop (component/start (system-1)))]
(doseq [component (vals system)]
(is (stopped? component)))))
(deftest dependencies-satisfied
(let [system (component/start (component/start (system-1)))]
(are [keys] (started? (get-in system keys))
[:b :a]
[:c :a]
[:c :b]
[:d :my-c])))
(defrecord ErrorStartComponentC [state error a b]
component/Lifecycle
(start [this]
(throw error))
(stop [this]
this))
(defn error-start-c [error]
(component/using
(map->ErrorStartComponentC {:error error})
[:a :b]))
(defn setup-error
([]
(setup-error (ex-info "Boom!" {})))
([error]
(try (component/start
(assoc (system-1) :c (error-start-c error)))
(catch Exception e e))))
(deftest error-thrown-with-partial-system
(let [ex (setup-error)]
(is (started? (-> ex ex-data :system :b :a)))))
(deftest error-thrown-with-component-dependencies
(let [ex (setup-error)]
(is (started? (-> ex ex-data :component :a)))
(is (started? (-> ex ex-data :component :b)))))
(deftest error-thrown-with-cause
(let [error (ex-info "Boom!" {})
ex (setup-error error)]
(is (identical? error (.getCause ^Exception ex)))))
(deftest error-is-from-component
(let [error (ex-info "Boom!" {})
ex (setup-error error)]
(is (component/ex-component? ex))))
(deftest error-is-not-from-component
(is (not (component/ex-component? (ex-info "Boom!" {})))))
(deftest remove-components-from-error
(let [error (ex-info (str (rand-int Integer/MAX_VALUE)) {})
^Exception ex (setup-error error)
^Exception ex-without (component/ex-without-components ex)]
(is (contains? (ex-data ex) :component))
(is (contains? (ex-data ex) :system))
(is (not (contains? (ex-data ex-without) :component)))
(is (not (contains? (ex-data ex-without) :system)))
(is (= (.getMessage ex)
(.getMessage ex-without)))
(is (= (.getCause ex)
(.getCause ex-without)))
(is (java.util.Arrays/equals
(.getStackTrace ex)
(.getStackTrace ex-without)))))
(defrecord System2b [one]
component/Lifecycle
(start [this]
(assert (started? (get-in one [:b :a])))
this)
(stop [this]
(assert (started? (get-in one [:b :a])))
this))
(defn system-2 []
(component/system-map :alpha (system-1)
:beta (component/using (->System2b nil)
{:one :alpha})))
(deftest composed-systems
(let [system (component/start (system-2))]
(is (started? (get-in system [:beta :one :d :my-c])))))
(defn increment-all-components [system]
(component/update-system
system (keys system) update-in [:n] inc))
(defn assert-increments [system]
(are [n keys] (= n (get-in system keys))
11 [:a :n]
11 [:b :a :n]
11 [:c :a :n]
11 [:c :b :a :n]
11 [:e :d :b :a :n]
21 [:b :n]
21 [:c :b :n]
21 [:d :b :n]
31 [:c :n]
41 [:d :n]
51 [:e :n]))
(deftest update-with-custom-function-on-maps
(let [system {:a {:n 10}
:b (component/using {:n 20} [:a])
:c (component/using {:n 30} [:a :b])
:d (component/using {:n 40} [:a :b])
:e (component/using {:n 50} [:b :c :d])}]
(assert-increments (increment-all-components system))))
(deftest t-system-using
(let [dependency-map {:b [:a]
:c [:a :b]
:d {:a :a :b :b}
:e [:b :c :d]}
system {:a {:n 10}
:b {:n 20}
:c {:n 30}
:d {:n 40}
:e {:n 50}}
system (component/system-using system dependency-map)]
(assert-increments (increment-all-components system))))
(defrecord ComponentWithoutLifecycle [state])
(deftest component-without-lifecycle
(let [c (->ComponentWithoutLifecycle nil)]
(is (= c (component/start c)))
(is (= c (component/stop c)))))
(defrecord ComponentReturningNil [state]
component/Lifecycle
(start [this]
nil)
(stop [this]
nil))
(deftest component-returning-nil
(let [a (->ComponentReturningNil nil)
s (component/system-map :a a :b (component-b))
e (try (component/start s)
false
(catch Exception e e))]
(is (= ::component/nil-component (:reason (ex-data e))))))
(deftest missing-dependency-error
(let [system-key ::system-b
local-key ::local-b
a (component/using (component-a) {local-key system-key})
system (component/system-map
:a a)
e (try (component/start system)
false
(catch Exception e e))
data (ex-data e)]
(is (= ::component/missing-dependency (:reason data)))
(is (= system-key (:system-key data)))
(is (= local-key (:dependency-key data)))
(is (= a (:component data)))
(is (= system (:system data)))))
(defn protocols-extentable-via-metadata? []
(let [{:keys [major minor]} *clojure-version*]
(and (= major 1)
(>= minor 10))))
(when (protocols-extentable-via-metadata?)
(def ComponentF (with-meta {:state (rand-int Integer/MAX_VALUE)}
{`component/start (fn [this]
(log 'ComponentF.start this)
(assoc this ::started? true))
`component/stop (fn [this]
(log 'ComponentF.start this)
(assoc this ::started? false))}))
;; makes the test suite fail, on purpose, showing how defn-spec can be useful
(defn-spec speced-start int? [this any?]
(log 'ComponentG.start this)
(assoc this ::started? true))
(st/instrument)
(defn component-g
[x y]
(with-meta {:state (rand-int Integer/MAX_VALUE)
:x x
:y y}
{`component/start speced-start
`component/stop (fn [this]
(log 'ComponentG.start this)
(assoc this ::started? false))}))
(defrecord System3 [d f a e c g b] ; deliberately scrambled order
component/Lifecycle
(start [this]
(log 'System1.start this)
(component/start-system this))
(stop [this]
(log 'System1.stop this)
(component/stop-system this)))
(defn system-3 []
(map->System3 {:a (component-a)
:b (component-b)
:c (component-c)
:d (component/using (component-d)
{:b :b
:my-c :c})
:e (component/using (component-e)
{:my-f :f})
:f (component/using ComponentF
{:my-g :g})
:g (component-g {:some :x-map} [:vector :of :ys])}))
(deftest all-components-started-with-metadata
(let [system (component/start (system-3))]
(doseq [component (vals system)]
(is (started? component))))))
| 8182 | (ns com.stuartsierra.component-test
(:require [clojure.test :refer (deftest is are)]
[clojure.set :refer (map-invert)]
[orchestra.core :refer [defn-spec]]
[orchestra.spec.test :as st]
[com.stuartsierra.component :as component]))
(def ^:dynamic *log* nil)
(defn- log [& args]
(when (thread-bound? #'*log*)
(set! *log* (conj *log* args))))
(defn- ordering
"Given an ordered collection of messages, returns a map from the
head of each message to its index position in the collection."
[log]
(into {} (map-indexed (fn [i [message & _]] [message i]) log)))
(defn before?
"In the collection of messages, does the message beginning with
symbol a come before the message begging with symbol b?"
[log sym-a sym-b]
(let [order (ordering log)]
(< (get order sym-a) (get order sym-b))))
(defn started? [component]
(true? (::started? component)))
(defn stopped? [component]
(false? (::started? component)))
(defrecord ComponentA [state]
component/Lifecycle
(start [this]
(log 'ComponentA.start this)
(assoc this ::started? true))
(stop [this]
(log 'ComponentA.stop this)
(assoc this ::started? false)))
(defn component-a []
(->ComponentA (rand-int Integer/MAX_VALUE)))
(defrecord ComponentB [state a]
component/Lifecycle
(start [this]
(log 'ComponentB.start this)
(assert (started? a))
(assoc this ::started? true))
(stop [this]
(log 'ComponentB.stop this)
(assert (started? a))
(assoc this ::started? false)))
(defn component-b []
(component/using
(map->ComponentB {:state (rand-int Integer/MAX_VALUE)})
[:a]))
(defrecord ComponentC [state a b]
component/Lifecycle
(start [this]
(log 'ComponentC.start this)
(assert (started? a))
(assert (started? b))
(assoc this ::started? true))
(stop [this]
(log 'ComponentC.stop this)
(assert (started? a))
(assert (started? b))
(assoc this ::started? false)))
(defn component-c []
(component/using
(map->ComponentC {:state (rand-int Integer/MAX_VALUE)})
[:a :b]))
(defrecord ComponentD [state my-c b]
component/Lifecycle
(start [this]
(log 'ComponentD.start this)
(assert (started? b))
(assert (started? my-c))
(assoc this ::started? true))
(stop [this]
(log 'ComponentD.stop this)
(assert (started? b))
(assert (started? my-c))
(assoc this ::started? false)))
(defn component-d []
(map->ComponentD {:state (rand-int Integer/MAX_VALUE)}))
(defrecord ComponentE [state]
component/Lifecycle
(start [this]
(log 'ComponentE.start this)
(assoc this ::started? true))
(stop [this]
(log 'ComponentE.stop this)
(assoc this ::started? false)))
(defn component-e []
(map->ComponentE {:state (rand-int Integer/MAX_VALUE)}))
(defrecord System1 [d a e c b] ; deliberately scrambled order
component/Lifecycle
(start [this]
(log 'System1.start this)
(component/start-system this))
(stop [this]
(log 'System1.stop this)
(component/stop-system this)))
(defn system-1 []
(map->System1 {:a (component-a)
:b (component-b)
:c (component-c)
:d (component/using (component-d)
{:b :b
:my-c :c})
:e (component-e)}))
(defmacro with-log [& body]
`(binding [*log* []]
~@body
*log*))
(deftest components-start-in-order
(let [log (with-log (component/start (system-1)))]
(are [k1 k2] (before? log k1 k2)
'ComponentA.start 'ComponentB.start
'ComponentA.start 'ComponentC.start
'ComponentB.start 'ComponentC.start
'ComponentC.start 'ComponentD.start
'ComponentB.start 'ComponentD.start)))
(deftest all-components-started
(let [system (component/start (system-1))]
(doseq [component (vals system)]
(is (started? component)))))
(deftest all-components-stopped
(let [system (component/stop (component/start (system-1)))]
(doseq [component (vals system)]
(is (stopped? component)))))
(deftest dependencies-satisfied
(let [system (component/start (component/start (system-1)))]
(are [keys] (started? (get-in system keys))
[:b :a]
[:c :a]
[:c :b]
[:d :my-c])))
(defrecord ErrorStartComponentC [state error a b]
component/Lifecycle
(start [this]
(throw error))
(stop [this]
this))
(defn error-start-c [error]
(component/using
(map->ErrorStartComponentC {:error error})
[:a :b]))
(defn setup-error
([]
(setup-error (ex-info "Boom!" {})))
([error]
(try (component/start
(assoc (system-1) :c (error-start-c error)))
(catch Exception e e))))
(deftest error-thrown-with-partial-system
(let [ex (setup-error)]
(is (started? (-> ex ex-data :system :b :a)))))
(deftest error-thrown-with-component-dependencies
(let [ex (setup-error)]
(is (started? (-> ex ex-data :component :a)))
(is (started? (-> ex ex-data :component :b)))))
(deftest error-thrown-with-cause
(let [error (ex-info "Boom!" {})
ex (setup-error error)]
(is (identical? error (.getCause ^Exception ex)))))
(deftest error-is-from-component
(let [error (ex-info "Boom!" {})
ex (setup-error error)]
(is (component/ex-component? ex))))
(deftest error-is-not-from-component
(is (not (component/ex-component? (ex-info "Boom!" {})))))
(deftest remove-components-from-error
(let [error (ex-info (str (rand-int Integer/MAX_VALUE)) {})
^Exception ex (setup-error error)
^Exception ex-without (component/ex-without-components ex)]
(is (contains? (ex-data ex) :component))
(is (contains? (ex-data ex) :system))
(is (not (contains? (ex-data ex-without) :component)))
(is (not (contains? (ex-data ex-without) :system)))
(is (= (.getMessage ex)
(.getMessage ex-without)))
(is (= (.getCause ex)
(.getCause ex-without)))
(is (java.util.Arrays/equals
(.getStackTrace ex)
(.getStackTrace ex-without)))))
(defrecord System2b [one]
component/Lifecycle
(start [this]
(assert (started? (get-in one [:b :a])))
this)
(stop [this]
(assert (started? (get-in one [:b :a])))
this))
(defn system-2 []
(component/system-map :alpha (system-1)
:beta (component/using (->System2b nil)
{:one :alpha})))
(deftest composed-systems
(let [system (component/start (system-2))]
(is (started? (get-in system [:beta :one :d :my-c])))))
(defn increment-all-components [system]
(component/update-system
system (keys system) update-in [:n] inc))
(defn assert-increments [system]
(are [n keys] (= n (get-in system keys))
11 [:a :n]
11 [:b :a :n]
11 [:c :a :n]
11 [:c :b :a :n]
11 [:e :d :b :a :n]
21 [:b :n]
21 [:c :b :n]
21 [:d :b :n]
31 [:c :n]
41 [:d :n]
51 [:e :n]))
(deftest update-with-custom-function-on-maps
(let [system {:a {:n 10}
:b (component/using {:n 20} [:a])
:c (component/using {:n 30} [:a :b])
:d (component/using {:n 40} [:a :b])
:e (component/using {:n 50} [:b :c :d])}]
(assert-increments (increment-all-components system))))
(deftest t-system-using
(let [dependency-map {:b [:a]
:c [:a :b]
:d {:a :a :b :b}
:e [:b :c :d]}
system {:a {:n 10}
:b {:n 20}
:c {:n 30}
:d {:n 40}
:e {:n 50}}
system (component/system-using system dependency-map)]
(assert-increments (increment-all-components system))))
(defrecord ComponentWithoutLifecycle [state])
(deftest component-without-lifecycle
(let [c (->ComponentWithoutLifecycle nil)]
(is (= c (component/start c)))
(is (= c (component/stop c)))))
(defrecord ComponentReturningNil [state]
component/Lifecycle
(start [this]
nil)
(stop [this]
nil))
(deftest component-returning-nil
(let [a (->ComponentReturningNil nil)
s (component/system-map :a a :b (component-b))
e (try (component/start s)
false
(catch Exception e e))]
(is (= ::component/nil-component (:reason (ex-data e))))))
(deftest missing-dependency-error
(let [system-key <KEY>
local-key <KEY>
a (component/using (component-a) {local-key system-key})
system (component/system-map
:a a)
e (try (component/start system)
false
(catch Exception e e))
data (ex-data e)]
(is (= ::component/missing-dependency (:reason data)))
(is (= system-key (:system-key data)))
(is (= local-key (:dependency-key data)))
(is (= a (:component data)))
(is (= system (:system data)))))
(defn protocols-extentable-via-metadata? []
(let [{:keys [major minor]} *clojure-version*]
(and (= major 1)
(>= minor 10))))
(when (protocols-extentable-via-metadata?)
(def ComponentF (with-meta {:state (rand-int Integer/MAX_VALUE)}
{`component/start (fn [this]
(log 'ComponentF.start this)
(assoc this ::started? true))
`component/stop (fn [this]
(log 'ComponentF.start this)
(assoc this ::started? false))}))
;; makes the test suite fail, on purpose, showing how defn-spec can be useful
(defn-spec speced-start int? [this any?]
(log 'ComponentG.start this)
(assoc this ::started? true))
(st/instrument)
(defn component-g
[x y]
(with-meta {:state (rand-int Integer/MAX_VALUE)
:x x
:y y}
{`component/start speced-start
`component/stop (fn [this]
(log 'ComponentG.start this)
(assoc this ::started? false))}))
(defrecord System3 [d f a e c g b] ; deliberately scrambled order
component/Lifecycle
(start [this]
(log 'System1.start this)
(component/start-system this))
(stop [this]
(log 'System1.stop this)
(component/stop-system this)))
(defn system-3 []
(map->System3 {:a (component-a)
:b (component-b)
:c (component-c)
:d (component/using (component-d)
{:b :b
:my-c :c})
:e (component/using (component-e)
{:my-f :f})
:f (component/using ComponentF
{:my-g :g})
:g (component-g {:some :x-map} [:vector :of :ys])}))
(deftest all-components-started-with-metadata
(let [system (component/start (system-3))]
(doseq [component (vals system)]
(is (started? component))))))
| true | (ns com.stuartsierra.component-test
(:require [clojure.test :refer (deftest is are)]
[clojure.set :refer (map-invert)]
[orchestra.core :refer [defn-spec]]
[orchestra.spec.test :as st]
[com.stuartsierra.component :as component]))
(def ^:dynamic *log* nil)
(defn- log [& args]
(when (thread-bound? #'*log*)
(set! *log* (conj *log* args))))
(defn- ordering
"Given an ordered collection of messages, returns a map from the
head of each message to its index position in the collection."
[log]
(into {} (map-indexed (fn [i [message & _]] [message i]) log)))
(defn before?
"In the collection of messages, does the message beginning with
symbol a come before the message begging with symbol b?"
[log sym-a sym-b]
(let [order (ordering log)]
(< (get order sym-a) (get order sym-b))))
(defn started? [component]
(true? (::started? component)))
(defn stopped? [component]
(false? (::started? component)))
(defrecord ComponentA [state]
component/Lifecycle
(start [this]
(log 'ComponentA.start this)
(assoc this ::started? true))
(stop [this]
(log 'ComponentA.stop this)
(assoc this ::started? false)))
(defn component-a []
(->ComponentA (rand-int Integer/MAX_VALUE)))
(defrecord ComponentB [state a]
component/Lifecycle
(start [this]
(log 'ComponentB.start this)
(assert (started? a))
(assoc this ::started? true))
(stop [this]
(log 'ComponentB.stop this)
(assert (started? a))
(assoc this ::started? false)))
(defn component-b []
(component/using
(map->ComponentB {:state (rand-int Integer/MAX_VALUE)})
[:a]))
(defrecord ComponentC [state a b]
component/Lifecycle
(start [this]
(log 'ComponentC.start this)
(assert (started? a))
(assert (started? b))
(assoc this ::started? true))
(stop [this]
(log 'ComponentC.stop this)
(assert (started? a))
(assert (started? b))
(assoc this ::started? false)))
(defn component-c []
(component/using
(map->ComponentC {:state (rand-int Integer/MAX_VALUE)})
[:a :b]))
(defrecord ComponentD [state my-c b]
component/Lifecycle
(start [this]
(log 'ComponentD.start this)
(assert (started? b))
(assert (started? my-c))
(assoc this ::started? true))
(stop [this]
(log 'ComponentD.stop this)
(assert (started? b))
(assert (started? my-c))
(assoc this ::started? false)))
(defn component-d []
(map->ComponentD {:state (rand-int Integer/MAX_VALUE)}))
(defrecord ComponentE [state]
component/Lifecycle
(start [this]
(log 'ComponentE.start this)
(assoc this ::started? true))
(stop [this]
(log 'ComponentE.stop this)
(assoc this ::started? false)))
(defn component-e []
(map->ComponentE {:state (rand-int Integer/MAX_VALUE)}))
(defrecord System1 [d a e c b] ; deliberately scrambled order
component/Lifecycle
(start [this]
(log 'System1.start this)
(component/start-system this))
(stop [this]
(log 'System1.stop this)
(component/stop-system this)))
(defn system-1 []
(map->System1 {:a (component-a)
:b (component-b)
:c (component-c)
:d (component/using (component-d)
{:b :b
:my-c :c})
:e (component-e)}))
(defmacro with-log [& body]
`(binding [*log* []]
~@body
*log*))
(deftest components-start-in-order
(let [log (with-log (component/start (system-1)))]
(are [k1 k2] (before? log k1 k2)
'ComponentA.start 'ComponentB.start
'ComponentA.start 'ComponentC.start
'ComponentB.start 'ComponentC.start
'ComponentC.start 'ComponentD.start
'ComponentB.start 'ComponentD.start)))
(deftest all-components-started
(let [system (component/start (system-1))]
(doseq [component (vals system)]
(is (started? component)))))
(deftest all-components-stopped
(let [system (component/stop (component/start (system-1)))]
(doseq [component (vals system)]
(is (stopped? component)))))
(deftest dependencies-satisfied
(let [system (component/start (component/start (system-1)))]
(are [keys] (started? (get-in system keys))
[:b :a]
[:c :a]
[:c :b]
[:d :my-c])))
(defrecord ErrorStartComponentC [state error a b]
component/Lifecycle
(start [this]
(throw error))
(stop [this]
this))
(defn error-start-c [error]
(component/using
(map->ErrorStartComponentC {:error error})
[:a :b]))
(defn setup-error
([]
(setup-error (ex-info "Boom!" {})))
([error]
(try (component/start
(assoc (system-1) :c (error-start-c error)))
(catch Exception e e))))
(deftest error-thrown-with-partial-system
(let [ex (setup-error)]
(is (started? (-> ex ex-data :system :b :a)))))
(deftest error-thrown-with-component-dependencies
(let [ex (setup-error)]
(is (started? (-> ex ex-data :component :a)))
(is (started? (-> ex ex-data :component :b)))))
(deftest error-thrown-with-cause
(let [error (ex-info "Boom!" {})
ex (setup-error error)]
(is (identical? error (.getCause ^Exception ex)))))
(deftest error-is-from-component
(let [error (ex-info "Boom!" {})
ex (setup-error error)]
(is (component/ex-component? ex))))
(deftest error-is-not-from-component
(is (not (component/ex-component? (ex-info "Boom!" {})))))
(deftest remove-components-from-error
(let [error (ex-info (str (rand-int Integer/MAX_VALUE)) {})
^Exception ex (setup-error error)
^Exception ex-without (component/ex-without-components ex)]
(is (contains? (ex-data ex) :component))
(is (contains? (ex-data ex) :system))
(is (not (contains? (ex-data ex-without) :component)))
(is (not (contains? (ex-data ex-without) :system)))
(is (= (.getMessage ex)
(.getMessage ex-without)))
(is (= (.getCause ex)
(.getCause ex-without)))
(is (java.util.Arrays/equals
(.getStackTrace ex)
(.getStackTrace ex-without)))))
(defrecord System2b [one]
component/Lifecycle
(start [this]
(assert (started? (get-in one [:b :a])))
this)
(stop [this]
(assert (started? (get-in one [:b :a])))
this))
(defn system-2 []
(component/system-map :alpha (system-1)
:beta (component/using (->System2b nil)
{:one :alpha})))
(deftest composed-systems
(let [system (component/start (system-2))]
(is (started? (get-in system [:beta :one :d :my-c])))))
(defn increment-all-components [system]
(component/update-system
system (keys system) update-in [:n] inc))
(defn assert-increments [system]
(are [n keys] (= n (get-in system keys))
11 [:a :n]
11 [:b :a :n]
11 [:c :a :n]
11 [:c :b :a :n]
11 [:e :d :b :a :n]
21 [:b :n]
21 [:c :b :n]
21 [:d :b :n]
31 [:c :n]
41 [:d :n]
51 [:e :n]))
(deftest update-with-custom-function-on-maps
(let [system {:a {:n 10}
:b (component/using {:n 20} [:a])
:c (component/using {:n 30} [:a :b])
:d (component/using {:n 40} [:a :b])
:e (component/using {:n 50} [:b :c :d])}]
(assert-increments (increment-all-components system))))
(deftest t-system-using
(let [dependency-map {:b [:a]
:c [:a :b]
:d {:a :a :b :b}
:e [:b :c :d]}
system {:a {:n 10}
:b {:n 20}
:c {:n 30}
:d {:n 40}
:e {:n 50}}
system (component/system-using system dependency-map)]
(assert-increments (increment-all-components system))))
(defrecord ComponentWithoutLifecycle [state])
(deftest component-without-lifecycle
(let [c (->ComponentWithoutLifecycle nil)]
(is (= c (component/start c)))
(is (= c (component/stop c)))))
(defrecord ComponentReturningNil [state]
component/Lifecycle
(start [this]
nil)
(stop [this]
nil))
(deftest component-returning-nil
(let [a (->ComponentReturningNil nil)
s (component/system-map :a a :b (component-b))
e (try (component/start s)
false
(catch Exception e e))]
(is (= ::component/nil-component (:reason (ex-data e))))))
(deftest missing-dependency-error
(let [system-key PI:KEY:<KEY>END_PI
local-key PI:KEY:<KEY>END_PI
a (component/using (component-a) {local-key system-key})
system (component/system-map
:a a)
e (try (component/start system)
false
(catch Exception e e))
data (ex-data e)]
(is (= ::component/missing-dependency (:reason data)))
(is (= system-key (:system-key data)))
(is (= local-key (:dependency-key data)))
(is (= a (:component data)))
(is (= system (:system data)))))
(defn protocols-extentable-via-metadata? []
(let [{:keys [major minor]} *clojure-version*]
(and (= major 1)
(>= minor 10))))
(when (protocols-extentable-via-metadata?)
(def ComponentF (with-meta {:state (rand-int Integer/MAX_VALUE)}
{`component/start (fn [this]
(log 'ComponentF.start this)
(assoc this ::started? true))
`component/stop (fn [this]
(log 'ComponentF.start this)
(assoc this ::started? false))}))
;; makes the test suite fail, on purpose, showing how defn-spec can be useful
(defn-spec speced-start int? [this any?]
(log 'ComponentG.start this)
(assoc this ::started? true))
(st/instrument)
(defn component-g
[x y]
(with-meta {:state (rand-int Integer/MAX_VALUE)
:x x
:y y}
{`component/start speced-start
`component/stop (fn [this]
(log 'ComponentG.start this)
(assoc this ::started? false))}))
(defrecord System3 [d f a e c g b] ; deliberately scrambled order
component/Lifecycle
(start [this]
(log 'System1.start this)
(component/start-system this))
(stop [this]
(log 'System1.stop this)
(component/stop-system this)))
(defn system-3 []
(map->System3 {:a (component-a)
:b (component-b)
:c (component-c)
:d (component/using (component-d)
{:b :b
:my-c :c})
:e (component/using (component-e)
{:my-f :f})
:f (component/using ComponentF
{:my-g :g})
:g (component-g {:some :x-map} [:vector :of :ys])}))
(deftest all-components-started-with-metadata
(let [system (component/start (system-3))]
(doseq [component (vals system)]
(is (started? component))))))
|
[
{
"context": "ps://www.alexvear.com\"]\n [::atom/title \"Alex Vear\"]\n [::atom/subtitle \"Alex Vear's Essays",
"end": 9882,
"score": 0.9956781268119812,
"start": 9873,
"tag": "NAME",
"value": "Alex Vear"
},
{
"context": "m/title \"Alex Vear\"]\n [::atom/subtitle \"Alex Vear's Essays\"]\n [::atom/updated (->atom-date ",
"end": 9925,
"score": 0.9229891896247864,
"start": 9914,
"tag": "NAME",
"value": "Alex Vear's"
},
{
"context": " [::atom/author\n [::atom/name \"Alex Vear\"]]]\n entries))\n out)))\n\n\n(defn gene",
"end": 10358,
"score": 0.9993841052055359,
"start": 10349,
"tag": "NAME",
"value": "Alex Vear"
}
] | src/uk/axvr/www/core.clj | axvr/www.axvr.uk | 0 | (ns uk.axvr.www.core
(:require [clojure.edn :as edn]
[clojure.string :as str]
[clojure.java.io :as io]
[clojure.data.xml :as xml]
[markdown.core :as md]
[hiccup.core :refer [html] :rename {html hiccup->html}])
(:import java.util.Locale
[java.io File FileWriter]
[java.time Instant ZoneId format.DateTimeFormatter]))
(def read-edn
;; NOTE: can't use read-string and #= macro because it requires source to be
;; wrapped in a string.
(comp eval edn/read-string slurp))
(defn wipe-dir
"Delete the contents of a directory, but not the directory itself."
[dir]
(doseq [file (some->> dir file-seq reverse butlast)]
(.delete file)))
(defn copy-dir
"Copy the contents of a directory to another."
[from to]
(doseq [f (some->> from file-seq (filter #(. % isFile)))]
(let [out-f (-> (str f)
(str/replace-first
(str/re-quote-replacement from)
(str to))
io/file)
dirs (io/file (.getParent out-f))]
(.mkdirs dirs)
(io/copy f out-f))))
(defn file-ext
"Extract the file extension from a java.io.File object."
[f]
(when (.isFile f)
(second
(re-matches #"^.*\.([\w_-]+)$" (.getName f)))))
(defn edn-file?
"Returns true if file (f) is an EDN file."
[f]
(= (file-ext f) "edn"))
(defn inject
"Replace {{x}} tags in text with value of :x in replacements map."
[text replacements]
(str/replace
text
#"\{\{ *([\w_-]+) *\}\}"
(comp str replacements keyword second)))
(defn remove-comments
"Remove HTML comments (and HTML-entity encoded HTML comments) from a string."
[s]
(str/replace s #"<!(–.*?–|--.*?--)>" ""))
(defn md->html
"Compile Markdown to HTML."
[md]
(remove-comments
(md/md-to-html-string
md
:heading-anchors true
:reference-links? true)))
(defn relative-path
"Construct a relative file path from one file/dir to another."
[from to]
(let [path (if (.isFile from)
(.getParent from)
from)]
(io/file path to)))
(def pages-dir (-> "pages" io/resource io/file))
(def dist-dir (io/file (.getParent pages-dir) "dist"))
(defn attach-content
"Attach content to a page."
[{:keys [f-in content] :as page}]
(assoc page
:content
(if (string? content)
(let [file (relative-path f-in content)]
((if (= "md" (file-ext file))
md->html
identity)
(slurp file)))
(hiccup->html content))))
(defn output-file
"Create java.io.File object representing the output file of the page."
[f-in]
(-> (str f-in)
(str/replace-first
(str/re-quote-replacement (str pages-dir))
(str dist-dir))
(str/replace-first
#"\.edn$"
".html")
io/file))
;; TODO: refactor/clean this.
(defn attach-path [{:keys [f-in] :as page}]
(let [path (-> (str f-in)
(str/replace-first
(str/re-quote-replacement (str pages-dir File/separator))
""))
bread-path (-> path
(str/replace-first #"(?:index)?\.edn$" "")
(str/replace #"_" " ")
(str/split
(re-pattern (str/re-quote-replacement File/separator))))
url-path (as-> path it
(str/split it
(re-pattern (str/re-quote-replacement File/separator)))
(remove empty? it)
(str/join "/" it)
(str/replace-first it #"(?:index)?\.edn$" "")
(str "/" it))]
(assoc page
:path (when-not (= (first bread-path) "") bread-path)
:url-path url-path)))
(defn attach-breadcrumbs [{:keys [path misc?] :as page}]
(assoc page
:breadcrumbs
(let [separator " › "]
(when path
(hiccup->html
[:nav {:class "bread"}
[:span
[:a {:href "/"} "home"]
separator
(when misc?
(str "misc" separator))
(->> path
(map
(fn [idx itm]
(if (zero? idx)
itm
[:a {:href (apply str (repeat idx "../"))} itm]))
(range (dec (count path)) -1 -1))
(interpose separator))]])))))
(defn date-format
"Create a fully configured java.time.format.DateTimeFormatter object."
[pattern & {:keys [locale zone]}]
(.. DateTimeFormatter
(ofPattern pattern)
(withLocale (or locale Locale/UK))
(withZone (ZoneId/of (or zone "GMT")))))
(defn parse-date
"Parse a date in ISO-8601 format into a java.time.format.Parsed object."
[date]
(when date
(let [date (if (re-find #"T" date) date (str date "T12:00:00Z"))
fmt (date-format "yyyy-MM-dd'T'HH:mm[:ss[.SSS[SSS]]][z][O][X][x][Z]")]
(.parse fmt date))))
(defn ->essay-date
"Convert essay published and updated dates into a pretty date to display on the site."
[{:keys [published updated]}]
(letfn [(format-date [d]
(.format (date-format "MMMM yyyy")
(parse-date d)))
(close? [d1 d2]
(let [date #(.format (date-format "MM yyyy") (parse-date %))]
(= (date d1) (date d2))))]
(when published
[:time
{:class "date"
:title (if updated
(str published " (rev. " updated ")")
published)
:datetime published}
(if (and updated (not (close? published updated)))
(str (format-date published)
" (rev. "
(format-date updated)
")")
(format-date published))])))
(defn attach-intro
"Build and attach the intro/header section of the page."
[{:keys [title subtitle] :as page}]
(assoc page
:intro
(when title
(hiccup->html
[:div {:class "intro"}
[:h1 title]
(when subtitle
[:h2 subtitle])
(->essay-date page)]))))
(defn attach-page-title
"Build full page title."
[{:keys [page-title site title subtitle] :as page}]
(assoc page
:page-title
(cond
page-title page-title
title (str title
(when subtitle
(str ": " subtitle))
" | "
site)
:else site)))
(defn attach-keywords [page]
(update page :keywords #(str/join ", " %)))
;; TODO: conj onto :head.
(defn attach-redirect
[{:keys [redirect] :as page}]
(if redirect
(assoc page
:redirect
(hiccup->html
[:meta {:http-eqive "refresh"
:content (str "0; url=" redirect)}]))
page))
(defn attach-extra-head-tags [{:keys [head] :as page}]
(if (seq head)
(let [head (if (keyword? (first head)) [head] head)]
(assoc page :head
(str/join "\n" (map #(hiccup->html %) head))))
page))
(defn copy-required-files
"Copies files required by a page to the dist."
[page]
(let [{:keys [requires]} page]
(when (seq requires)
(doseq [f requires]
(let [rel-in (relative-path (:f-in page) f)
rel-out (relative-path (:f-out page) f)]
(if (.isDirectory rel-in)
(copy-dir rel-in rel-out)
(io/copy rel-in rel-out)))))))
(defn build-pages []
(let [config (-> "config.edn" io/resource read-edn)
template (-> "template.html" io/resource slurp)]
(->> pages-dir
file-seq
(filter edn-file?)
(map #(merge
config
{:f-in %
:f-out (output-file %)}
(read-edn %)))
(map attach-path)
(map attach-redirect)
(map attach-extra-head-tags)
(map attach-keywords)
(map attach-content)
(map attach-breadcrumbs)
(map attach-intro)
(map attach-page-title)
(map #(assoc % :content (inject (:content %) %)))
(map #(assoc % :final-page (inject template %))))))
(defn generate-pages [pages]
(wipe-dir dist-dir)
(doseq [page pages]
(.mkdirs (io/file (.getParent (:f-out page))))
(spit (:f-out page) (:final-page page))
(copy-required-files page)))
(defn ->atom-date [d]
(let [fmt (date-format "yyyy-MM-dd'T'HH:mm:ssX" :zone "UTC")]
(.format fmt d)))
(xml/alias-uri 'atom "http://www.w3.org/2005/Atom")
(defn atom-entry [page]
(let [url (str "https://www.alexvear.com" (:url-path page))]
[::atom/entry
[::atom/title (:title page)]
(when-let [subtitle (:subtitle page)]
[::atom/subtitle subtitle])
(when-let [summary (:summary page)]
[::atom/summary summary])
(when-let [id (:id page)]
[::atom/id (str "urn:uuid:" id)])
[::atom/link
{:type "text/html"
:rel "alternate"
:title (:title page)
:href url}]
[::atom/published (->atom-date (parse-date (:published page)))]
[::atom/updated (->atom-date (parse-date (or (:updated page) (:published page))))]
[::atom/author
[::atom/name (:author page)]]
[::atom/content
{:type "html"
:xml:base url}
(:content page)]]))
(defn atom-feed [output entries]
(with-open [out (FileWriter. output)]
(xml/emit
(xml/sexp-as-element
(into
[::atom/feed
{:xmlns "http://www.w3.org/2005/Atom"
:xml:base "https://www.alexvear.com"}
[::atom/id "https://www.alexvear.com"]
[::atom/title "Alex Vear"]
[::atom/subtitle "Alex Vear's Essays"]
[::atom/updated (->atom-date (Instant/now))]
[::atom/link
{:rel "alternative"
:type "text/html"
:href "https://www.alexvear.com"}]
[::atom/link
{:ref "self"
:type "application/atom+xml"
:href "/essays/atom.xml"}]
[::atom/icon "/favicon.jpg"]
[::atom/author
[::atom/name "Alex Vear"]]]
entries))
out)))
(defn generate-feed [pages]
(->> pages
(filter #(contains? % :published))
(sort-by :published String/CASE_INSENSITIVE_ORDER)
(reverse)
(map atom-entry)
(atom-feed (io/file dist-dir "essays" "atom.xml"))))
(defn build [& _]
(let [pages (build-pages)]
(generate-pages pages)
(generate-feed pages)))
| 116170 | (ns uk.axvr.www.core
(:require [clojure.edn :as edn]
[clojure.string :as str]
[clojure.java.io :as io]
[clojure.data.xml :as xml]
[markdown.core :as md]
[hiccup.core :refer [html] :rename {html hiccup->html}])
(:import java.util.Locale
[java.io File FileWriter]
[java.time Instant ZoneId format.DateTimeFormatter]))
(def read-edn
;; NOTE: can't use read-string and #= macro because it requires source to be
;; wrapped in a string.
(comp eval edn/read-string slurp))
(defn wipe-dir
"Delete the contents of a directory, but not the directory itself."
[dir]
(doseq [file (some->> dir file-seq reverse butlast)]
(.delete file)))
(defn copy-dir
"Copy the contents of a directory to another."
[from to]
(doseq [f (some->> from file-seq (filter #(. % isFile)))]
(let [out-f (-> (str f)
(str/replace-first
(str/re-quote-replacement from)
(str to))
io/file)
dirs (io/file (.getParent out-f))]
(.mkdirs dirs)
(io/copy f out-f))))
(defn file-ext
"Extract the file extension from a java.io.File object."
[f]
(when (.isFile f)
(second
(re-matches #"^.*\.([\w_-]+)$" (.getName f)))))
(defn edn-file?
"Returns true if file (f) is an EDN file."
[f]
(= (file-ext f) "edn"))
(defn inject
"Replace {{x}} tags in text with value of :x in replacements map."
[text replacements]
(str/replace
text
#"\{\{ *([\w_-]+) *\}\}"
(comp str replacements keyword second)))
(defn remove-comments
"Remove HTML comments (and HTML-entity encoded HTML comments) from a string."
[s]
(str/replace s #"<!(–.*?–|--.*?--)>" ""))
(defn md->html
"Compile Markdown to HTML."
[md]
(remove-comments
(md/md-to-html-string
md
:heading-anchors true
:reference-links? true)))
(defn relative-path
"Construct a relative file path from one file/dir to another."
[from to]
(let [path (if (.isFile from)
(.getParent from)
from)]
(io/file path to)))
(def pages-dir (-> "pages" io/resource io/file))
(def dist-dir (io/file (.getParent pages-dir) "dist"))
(defn attach-content
"Attach content to a page."
[{:keys [f-in content] :as page}]
(assoc page
:content
(if (string? content)
(let [file (relative-path f-in content)]
((if (= "md" (file-ext file))
md->html
identity)
(slurp file)))
(hiccup->html content))))
(defn output-file
"Create java.io.File object representing the output file of the page."
[f-in]
(-> (str f-in)
(str/replace-first
(str/re-quote-replacement (str pages-dir))
(str dist-dir))
(str/replace-first
#"\.edn$"
".html")
io/file))
;; TODO: refactor/clean this.
(defn attach-path [{:keys [f-in] :as page}]
(let [path (-> (str f-in)
(str/replace-first
(str/re-quote-replacement (str pages-dir File/separator))
""))
bread-path (-> path
(str/replace-first #"(?:index)?\.edn$" "")
(str/replace #"_" " ")
(str/split
(re-pattern (str/re-quote-replacement File/separator))))
url-path (as-> path it
(str/split it
(re-pattern (str/re-quote-replacement File/separator)))
(remove empty? it)
(str/join "/" it)
(str/replace-first it #"(?:index)?\.edn$" "")
(str "/" it))]
(assoc page
:path (when-not (= (first bread-path) "") bread-path)
:url-path url-path)))
(defn attach-breadcrumbs [{:keys [path misc?] :as page}]
(assoc page
:breadcrumbs
(let [separator " › "]
(when path
(hiccup->html
[:nav {:class "bread"}
[:span
[:a {:href "/"} "home"]
separator
(when misc?
(str "misc" separator))
(->> path
(map
(fn [idx itm]
(if (zero? idx)
itm
[:a {:href (apply str (repeat idx "../"))} itm]))
(range (dec (count path)) -1 -1))
(interpose separator))]])))))
(defn date-format
"Create a fully configured java.time.format.DateTimeFormatter object."
[pattern & {:keys [locale zone]}]
(.. DateTimeFormatter
(ofPattern pattern)
(withLocale (or locale Locale/UK))
(withZone (ZoneId/of (or zone "GMT")))))
(defn parse-date
"Parse a date in ISO-8601 format into a java.time.format.Parsed object."
[date]
(when date
(let [date (if (re-find #"T" date) date (str date "T12:00:00Z"))
fmt (date-format "yyyy-MM-dd'T'HH:mm[:ss[.SSS[SSS]]][z][O][X][x][Z]")]
(.parse fmt date))))
(defn ->essay-date
"Convert essay published and updated dates into a pretty date to display on the site."
[{:keys [published updated]}]
(letfn [(format-date [d]
(.format (date-format "MMMM yyyy")
(parse-date d)))
(close? [d1 d2]
(let [date #(.format (date-format "MM yyyy") (parse-date %))]
(= (date d1) (date d2))))]
(when published
[:time
{:class "date"
:title (if updated
(str published " (rev. " updated ")")
published)
:datetime published}
(if (and updated (not (close? published updated)))
(str (format-date published)
" (rev. "
(format-date updated)
")")
(format-date published))])))
(defn attach-intro
"Build and attach the intro/header section of the page."
[{:keys [title subtitle] :as page}]
(assoc page
:intro
(when title
(hiccup->html
[:div {:class "intro"}
[:h1 title]
(when subtitle
[:h2 subtitle])
(->essay-date page)]))))
(defn attach-page-title
"Build full page title."
[{:keys [page-title site title subtitle] :as page}]
(assoc page
:page-title
(cond
page-title page-title
title (str title
(when subtitle
(str ": " subtitle))
" | "
site)
:else site)))
(defn attach-keywords [page]
(update page :keywords #(str/join ", " %)))
;; TODO: conj onto :head.
(defn attach-redirect
[{:keys [redirect] :as page}]
(if redirect
(assoc page
:redirect
(hiccup->html
[:meta {:http-eqive "refresh"
:content (str "0; url=" redirect)}]))
page))
(defn attach-extra-head-tags [{:keys [head] :as page}]
(if (seq head)
(let [head (if (keyword? (first head)) [head] head)]
(assoc page :head
(str/join "\n" (map #(hiccup->html %) head))))
page))
(defn copy-required-files
"Copies files required by a page to the dist."
[page]
(let [{:keys [requires]} page]
(when (seq requires)
(doseq [f requires]
(let [rel-in (relative-path (:f-in page) f)
rel-out (relative-path (:f-out page) f)]
(if (.isDirectory rel-in)
(copy-dir rel-in rel-out)
(io/copy rel-in rel-out)))))))
(defn build-pages []
(let [config (-> "config.edn" io/resource read-edn)
template (-> "template.html" io/resource slurp)]
(->> pages-dir
file-seq
(filter edn-file?)
(map #(merge
config
{:f-in %
:f-out (output-file %)}
(read-edn %)))
(map attach-path)
(map attach-redirect)
(map attach-extra-head-tags)
(map attach-keywords)
(map attach-content)
(map attach-breadcrumbs)
(map attach-intro)
(map attach-page-title)
(map #(assoc % :content (inject (:content %) %)))
(map #(assoc % :final-page (inject template %))))))
(defn generate-pages [pages]
(wipe-dir dist-dir)
(doseq [page pages]
(.mkdirs (io/file (.getParent (:f-out page))))
(spit (:f-out page) (:final-page page))
(copy-required-files page)))
(defn ->atom-date [d]
(let [fmt (date-format "yyyy-MM-dd'T'HH:mm:ssX" :zone "UTC")]
(.format fmt d)))
(xml/alias-uri 'atom "http://www.w3.org/2005/Atom")
(defn atom-entry [page]
(let [url (str "https://www.alexvear.com" (:url-path page))]
[::atom/entry
[::atom/title (:title page)]
(when-let [subtitle (:subtitle page)]
[::atom/subtitle subtitle])
(when-let [summary (:summary page)]
[::atom/summary summary])
(when-let [id (:id page)]
[::atom/id (str "urn:uuid:" id)])
[::atom/link
{:type "text/html"
:rel "alternate"
:title (:title page)
:href url}]
[::atom/published (->atom-date (parse-date (:published page)))]
[::atom/updated (->atom-date (parse-date (or (:updated page) (:published page))))]
[::atom/author
[::atom/name (:author page)]]
[::atom/content
{:type "html"
:xml:base url}
(:content page)]]))
(defn atom-feed [output entries]
(with-open [out (FileWriter. output)]
(xml/emit
(xml/sexp-as-element
(into
[::atom/feed
{:xmlns "http://www.w3.org/2005/Atom"
:xml:base "https://www.alexvear.com"}
[::atom/id "https://www.alexvear.com"]
[::atom/title "<NAME>"]
[::atom/subtitle "<NAME> Essays"]
[::atom/updated (->atom-date (Instant/now))]
[::atom/link
{:rel "alternative"
:type "text/html"
:href "https://www.alexvear.com"}]
[::atom/link
{:ref "self"
:type "application/atom+xml"
:href "/essays/atom.xml"}]
[::atom/icon "/favicon.jpg"]
[::atom/author
[::atom/name "<NAME>"]]]
entries))
out)))
(defn generate-feed [pages]
(->> pages
(filter #(contains? % :published))
(sort-by :published String/CASE_INSENSITIVE_ORDER)
(reverse)
(map atom-entry)
(atom-feed (io/file dist-dir "essays" "atom.xml"))))
(defn build [& _]
(let [pages (build-pages)]
(generate-pages pages)
(generate-feed pages)))
| true | (ns uk.axvr.www.core
(:require [clojure.edn :as edn]
[clojure.string :as str]
[clojure.java.io :as io]
[clojure.data.xml :as xml]
[markdown.core :as md]
[hiccup.core :refer [html] :rename {html hiccup->html}])
(:import java.util.Locale
[java.io File FileWriter]
[java.time Instant ZoneId format.DateTimeFormatter]))
(def read-edn
;; NOTE: can't use read-string and #= macro because it requires source to be
;; wrapped in a string.
(comp eval edn/read-string slurp))
(defn wipe-dir
"Delete the contents of a directory, but not the directory itself."
[dir]
(doseq [file (some->> dir file-seq reverse butlast)]
(.delete file)))
(defn copy-dir
"Copy the contents of a directory to another."
[from to]
(doseq [f (some->> from file-seq (filter #(. % isFile)))]
(let [out-f (-> (str f)
(str/replace-first
(str/re-quote-replacement from)
(str to))
io/file)
dirs (io/file (.getParent out-f))]
(.mkdirs dirs)
(io/copy f out-f))))
(defn file-ext
"Extract the file extension from a java.io.File object."
[f]
(when (.isFile f)
(second
(re-matches #"^.*\.([\w_-]+)$" (.getName f)))))
(defn edn-file?
"Returns true if file (f) is an EDN file."
[f]
(= (file-ext f) "edn"))
(defn inject
"Replace {{x}} tags in text with value of :x in replacements map."
[text replacements]
(str/replace
text
#"\{\{ *([\w_-]+) *\}\}"
(comp str replacements keyword second)))
(defn remove-comments
"Remove HTML comments (and HTML-entity encoded HTML comments) from a string."
[s]
(str/replace s #"<!(–.*?–|--.*?--)>" ""))
(defn md->html
"Compile Markdown to HTML."
[md]
(remove-comments
(md/md-to-html-string
md
:heading-anchors true
:reference-links? true)))
(defn relative-path
"Construct a relative file path from one file/dir to another."
[from to]
(let [path (if (.isFile from)
(.getParent from)
from)]
(io/file path to)))
(def pages-dir (-> "pages" io/resource io/file))
(def dist-dir (io/file (.getParent pages-dir) "dist"))
(defn attach-content
"Attach content to a page."
[{:keys [f-in content] :as page}]
(assoc page
:content
(if (string? content)
(let [file (relative-path f-in content)]
((if (= "md" (file-ext file))
md->html
identity)
(slurp file)))
(hiccup->html content))))
(defn output-file
"Create java.io.File object representing the output file of the page."
[f-in]
(-> (str f-in)
(str/replace-first
(str/re-quote-replacement (str pages-dir))
(str dist-dir))
(str/replace-first
#"\.edn$"
".html")
io/file))
;; TODO: refactor/clean this.
(defn attach-path [{:keys [f-in] :as page}]
(let [path (-> (str f-in)
(str/replace-first
(str/re-quote-replacement (str pages-dir File/separator))
""))
bread-path (-> path
(str/replace-first #"(?:index)?\.edn$" "")
(str/replace #"_" " ")
(str/split
(re-pattern (str/re-quote-replacement File/separator))))
url-path (as-> path it
(str/split it
(re-pattern (str/re-quote-replacement File/separator)))
(remove empty? it)
(str/join "/" it)
(str/replace-first it #"(?:index)?\.edn$" "")
(str "/" it))]
(assoc page
:path (when-not (= (first bread-path) "") bread-path)
:url-path url-path)))
(defn attach-breadcrumbs [{:keys [path misc?] :as page}]
(assoc page
:breadcrumbs
(let [separator " › "]
(when path
(hiccup->html
[:nav {:class "bread"}
[:span
[:a {:href "/"} "home"]
separator
(when misc?
(str "misc" separator))
(->> path
(map
(fn [idx itm]
(if (zero? idx)
itm
[:a {:href (apply str (repeat idx "../"))} itm]))
(range (dec (count path)) -1 -1))
(interpose separator))]])))))
(defn date-format
"Create a fully configured java.time.format.DateTimeFormatter object."
[pattern & {:keys [locale zone]}]
(.. DateTimeFormatter
(ofPattern pattern)
(withLocale (or locale Locale/UK))
(withZone (ZoneId/of (or zone "GMT")))))
(defn parse-date
"Parse a date in ISO-8601 format into a java.time.format.Parsed object."
[date]
(when date
(let [date (if (re-find #"T" date) date (str date "T12:00:00Z"))
fmt (date-format "yyyy-MM-dd'T'HH:mm[:ss[.SSS[SSS]]][z][O][X][x][Z]")]
(.parse fmt date))))
(defn ->essay-date
"Convert essay published and updated dates into a pretty date to display on the site."
[{:keys [published updated]}]
(letfn [(format-date [d]
(.format (date-format "MMMM yyyy")
(parse-date d)))
(close? [d1 d2]
(let [date #(.format (date-format "MM yyyy") (parse-date %))]
(= (date d1) (date d2))))]
(when published
[:time
{:class "date"
:title (if updated
(str published " (rev. " updated ")")
published)
:datetime published}
(if (and updated (not (close? published updated)))
(str (format-date published)
" (rev. "
(format-date updated)
")")
(format-date published))])))
(defn attach-intro
"Build and attach the intro/header section of the page."
[{:keys [title subtitle] :as page}]
(assoc page
:intro
(when title
(hiccup->html
[:div {:class "intro"}
[:h1 title]
(when subtitle
[:h2 subtitle])
(->essay-date page)]))))
(defn attach-page-title
"Build full page title."
[{:keys [page-title site title subtitle] :as page}]
(assoc page
:page-title
(cond
page-title page-title
title (str title
(when subtitle
(str ": " subtitle))
" | "
site)
:else site)))
(defn attach-keywords [page]
(update page :keywords #(str/join ", " %)))
;; TODO: conj onto :head.
(defn attach-redirect
[{:keys [redirect] :as page}]
(if redirect
(assoc page
:redirect
(hiccup->html
[:meta {:http-eqive "refresh"
:content (str "0; url=" redirect)}]))
page))
(defn attach-extra-head-tags [{:keys [head] :as page}]
(if (seq head)
(let [head (if (keyword? (first head)) [head] head)]
(assoc page :head
(str/join "\n" (map #(hiccup->html %) head))))
page))
(defn copy-required-files
"Copies files required by a page to the dist."
[page]
(let [{:keys [requires]} page]
(when (seq requires)
(doseq [f requires]
(let [rel-in (relative-path (:f-in page) f)
rel-out (relative-path (:f-out page) f)]
(if (.isDirectory rel-in)
(copy-dir rel-in rel-out)
(io/copy rel-in rel-out)))))))
(defn build-pages []
(let [config (-> "config.edn" io/resource read-edn)
template (-> "template.html" io/resource slurp)]
(->> pages-dir
file-seq
(filter edn-file?)
(map #(merge
config
{:f-in %
:f-out (output-file %)}
(read-edn %)))
(map attach-path)
(map attach-redirect)
(map attach-extra-head-tags)
(map attach-keywords)
(map attach-content)
(map attach-breadcrumbs)
(map attach-intro)
(map attach-page-title)
(map #(assoc % :content (inject (:content %) %)))
(map #(assoc % :final-page (inject template %))))))
(defn generate-pages [pages]
(wipe-dir dist-dir)
(doseq [page pages]
(.mkdirs (io/file (.getParent (:f-out page))))
(spit (:f-out page) (:final-page page))
(copy-required-files page)))
(defn ->atom-date [d]
(let [fmt (date-format "yyyy-MM-dd'T'HH:mm:ssX" :zone "UTC")]
(.format fmt d)))
(xml/alias-uri 'atom "http://www.w3.org/2005/Atom")
(defn atom-entry [page]
(let [url (str "https://www.alexvear.com" (:url-path page))]
[::atom/entry
[::atom/title (:title page)]
(when-let [subtitle (:subtitle page)]
[::atom/subtitle subtitle])
(when-let [summary (:summary page)]
[::atom/summary summary])
(when-let [id (:id page)]
[::atom/id (str "urn:uuid:" id)])
[::atom/link
{:type "text/html"
:rel "alternate"
:title (:title page)
:href url}]
[::atom/published (->atom-date (parse-date (:published page)))]
[::atom/updated (->atom-date (parse-date (or (:updated page) (:published page))))]
[::atom/author
[::atom/name (:author page)]]
[::atom/content
{:type "html"
:xml:base url}
(:content page)]]))
(defn atom-feed [output entries]
(with-open [out (FileWriter. output)]
(xml/emit
(xml/sexp-as-element
(into
[::atom/feed
{:xmlns "http://www.w3.org/2005/Atom"
:xml:base "https://www.alexvear.com"}
[::atom/id "https://www.alexvear.com"]
[::atom/title "PI:NAME:<NAME>END_PI"]
[::atom/subtitle "PI:NAME:<NAME>END_PI Essays"]
[::atom/updated (->atom-date (Instant/now))]
[::atom/link
{:rel "alternative"
:type "text/html"
:href "https://www.alexvear.com"}]
[::atom/link
{:ref "self"
:type "application/atom+xml"
:href "/essays/atom.xml"}]
[::atom/icon "/favicon.jpg"]
[::atom/author
[::atom/name "PI:NAME:<NAME>END_PI"]]]
entries))
out)))
(defn generate-feed [pages]
(->> pages
(filter #(contains? % :published))
(sort-by :published String/CASE_INSENSITIVE_ORDER)
(reverse)
(map atom-entry)
(atom-feed (io/file dist-dir "essays" "atom.xml"))))
(defn build [& _]
(let [pages (build-pages)]
(generate-pages pages)
(generate-feed pages)))
|
[
{
"context": "ubtag\" \"aa\"\n \"description\" [\"Afar\" \"Multi Line Description\"]\n ",
"end": 3271,
"score": 0.9850666522979736,
"start": 3267,
"tag": "NAME",
"value": "Afar"
},
{
"context": "ubtag\" \"aa\"\n \"description\" [\"Afar\"]\n \"added\" (date 2005 10 16)",
"end": 3612,
"score": 0.9921040534973145,
"start": 3608,
"tag": "NAME",
"value": "Afar"
}
] | test/bcp47/test/core.clj | pculture/bcp47-json | 2 | (ns bcp47.test.core
(:use clojure.test
[bcp47.core :only (parse-bcp47)]))
; Data ------------------------------------------------------------------------
(def empty-registry
"File-Date: 2012-09-12
")
(def single-item-registry
"File-Date: 2012-09-12
%%
Type: language
Subtag: aa
Description: Afar
Added: 2005-10-16
")
(def two-item-registry
"File-Date: 2012-09-12
%%
Type: language
Subtag: aa
Description: Afar
Added: 2005-10-16
%%
Type: language
Subtag: ab
Description: Abkhazian
Added: 2005-10-16
Suppress-Script: Cyrl
")
(def long-line-registry
"File-Date: 2012-09-12
%%
Type: language
Subtag: pny
Description: Pinyin
Added: 2009-07-29
Comments: a Niger-Congo language spoken in Cameroon; not to be confused
with the Pinyin romanization systems used for Chinese and Tibetan
")
(def multi-description-registry
"File-Date: 2012-09-12
%%
Type: language
Subtag: aa
Description: Afar
Description: Multi
Line
Description
Added: 2005-10-16
")
(def all-fields-registry
"File-Date: 2012-09-12
%%
Type: language
Subtag: aa
Description: Afar
Added: 2005-10-16
Deprecated: 2009-01-01
Tag: zh-Hans
Prefix: rm
Preferred-Value: gan
Comments: Hello
Macrolanguage: zh
Suppress-Script: Cyrl
Scope: collection
")
; Convenience Functions -------------------------------------------------------
(defn date [y m d]
{"year" y
"month" m
"day" d})
(defn dated [subtags]
{"file-date" (date 2012 9 12)
"subtags" subtags})
; Test Cases ------------------------------------------------------------------
(deftest test-empty
(testing "An empty registry."
(let [reg (parse-bcp47 empty-registry)]
(is (= reg
(dated []))))))
(deftest test-single-item
(testing "A single basic item."
(let [reg (parse-bcp47 single-item-registry)]
(is (= reg
(dated [{"type" "language"
"subtag" "aa"
"description" ["Afar"]
"added" (date 2005 10 16)}]))))))
(deftest test-two-items
(testing "Two basic items."
(let [reg (parse-bcp47 two-item-registry)]
(is (= reg
(dated [{"type" "language"
"subtag" "aa"
"description" ["Afar"]
"added" (date 2005 10 16)}
{"type" "language"
"subtag" "ab"
"description" ["Abkhazian"]
"added" (date 2005 10 16)
"suppress-script" "Cyrl"}]))))))
(deftest test-long-lines
(testing "An item with fields containing long lines."
(let [reg (parse-bcp47 long-line-registry)]
(is (= reg
(dated [{"type" "language"
"subtag" "pny"
"description" ["Pinyin"]
"added" (date 2009 7 29)
"comments" "a Niger-Congo language spoken in Cameroon; not to be confused with the Pinyin romanization systems used for Chinese and Tibetan"
}]))))))
(deftest test-multi-description
(testing "An item with multiple description fields."
(let [reg (parse-bcp47 multi-description-registry)]
(is (= reg
(dated [{"type" "language"
"subtag" "aa"
"description" ["Afar" "Multi Line Description"]
"added" (date 2005 10 16) }]))))))
(deftest test-all-fields
(testing "An item with all possible fields."
(let [reg (parse-bcp47 all-fields-registry)]
(is (= reg
(dated [{"type" "language"
"subtag" "aa"
"description" ["Afar"]
"added" (date 2005 10 16)
"deprecated" (date 2009 1 1)
"tag" "zh-Hans"
"prefix" "rm"
"preferred-value" "gan"
"comments" "Hello"
"macrolanguage" "zh"
"suppress-script" "Cyrl"
"scope" "collection"}]))))))
| 37041 | (ns bcp47.test.core
(:use clojure.test
[bcp47.core :only (parse-bcp47)]))
; Data ------------------------------------------------------------------------
(def empty-registry
"File-Date: 2012-09-12
")
(def single-item-registry
"File-Date: 2012-09-12
%%
Type: language
Subtag: aa
Description: Afar
Added: 2005-10-16
")
(def two-item-registry
"File-Date: 2012-09-12
%%
Type: language
Subtag: aa
Description: Afar
Added: 2005-10-16
%%
Type: language
Subtag: ab
Description: Abkhazian
Added: 2005-10-16
Suppress-Script: Cyrl
")
(def long-line-registry
"File-Date: 2012-09-12
%%
Type: language
Subtag: pny
Description: Pinyin
Added: 2009-07-29
Comments: a Niger-Congo language spoken in Cameroon; not to be confused
with the Pinyin romanization systems used for Chinese and Tibetan
")
(def multi-description-registry
"File-Date: 2012-09-12
%%
Type: language
Subtag: aa
Description: Afar
Description: Multi
Line
Description
Added: 2005-10-16
")
(def all-fields-registry
"File-Date: 2012-09-12
%%
Type: language
Subtag: aa
Description: Afar
Added: 2005-10-16
Deprecated: 2009-01-01
Tag: zh-Hans
Prefix: rm
Preferred-Value: gan
Comments: Hello
Macrolanguage: zh
Suppress-Script: Cyrl
Scope: collection
")
; Convenience Functions -------------------------------------------------------
(defn date [y m d]
{"year" y
"month" m
"day" d})
(defn dated [subtags]
{"file-date" (date 2012 9 12)
"subtags" subtags})
; Test Cases ------------------------------------------------------------------
(deftest test-empty
(testing "An empty registry."
(let [reg (parse-bcp47 empty-registry)]
(is (= reg
(dated []))))))
(deftest test-single-item
(testing "A single basic item."
(let [reg (parse-bcp47 single-item-registry)]
(is (= reg
(dated [{"type" "language"
"subtag" "aa"
"description" ["Afar"]
"added" (date 2005 10 16)}]))))))
(deftest test-two-items
(testing "Two basic items."
(let [reg (parse-bcp47 two-item-registry)]
(is (= reg
(dated [{"type" "language"
"subtag" "aa"
"description" ["Afar"]
"added" (date 2005 10 16)}
{"type" "language"
"subtag" "ab"
"description" ["Abkhazian"]
"added" (date 2005 10 16)
"suppress-script" "Cyrl"}]))))))
(deftest test-long-lines
(testing "An item with fields containing long lines."
(let [reg (parse-bcp47 long-line-registry)]
(is (= reg
(dated [{"type" "language"
"subtag" "pny"
"description" ["Pinyin"]
"added" (date 2009 7 29)
"comments" "a Niger-Congo language spoken in Cameroon; not to be confused with the Pinyin romanization systems used for Chinese and Tibetan"
}]))))))
(deftest test-multi-description
(testing "An item with multiple description fields."
(let [reg (parse-bcp47 multi-description-registry)]
(is (= reg
(dated [{"type" "language"
"subtag" "aa"
"description" ["<NAME>" "Multi Line Description"]
"added" (date 2005 10 16) }]))))))
(deftest test-all-fields
(testing "An item with all possible fields."
(let [reg (parse-bcp47 all-fields-registry)]
(is (= reg
(dated [{"type" "language"
"subtag" "aa"
"description" ["<NAME>"]
"added" (date 2005 10 16)
"deprecated" (date 2009 1 1)
"tag" "zh-Hans"
"prefix" "rm"
"preferred-value" "gan"
"comments" "Hello"
"macrolanguage" "zh"
"suppress-script" "Cyrl"
"scope" "collection"}]))))))
| true | (ns bcp47.test.core
(:use clojure.test
[bcp47.core :only (parse-bcp47)]))
; Data ------------------------------------------------------------------------
(def empty-registry
"File-Date: 2012-09-12
")
(def single-item-registry
"File-Date: 2012-09-12
%%
Type: language
Subtag: aa
Description: Afar
Added: 2005-10-16
")
(def two-item-registry
"File-Date: 2012-09-12
%%
Type: language
Subtag: aa
Description: Afar
Added: 2005-10-16
%%
Type: language
Subtag: ab
Description: Abkhazian
Added: 2005-10-16
Suppress-Script: Cyrl
")
(def long-line-registry
"File-Date: 2012-09-12
%%
Type: language
Subtag: pny
Description: Pinyin
Added: 2009-07-29
Comments: a Niger-Congo language spoken in Cameroon; not to be confused
with the Pinyin romanization systems used for Chinese and Tibetan
")
(def multi-description-registry
"File-Date: 2012-09-12
%%
Type: language
Subtag: aa
Description: Afar
Description: Multi
Line
Description
Added: 2005-10-16
")
(def all-fields-registry
"File-Date: 2012-09-12
%%
Type: language
Subtag: aa
Description: Afar
Added: 2005-10-16
Deprecated: 2009-01-01
Tag: zh-Hans
Prefix: rm
Preferred-Value: gan
Comments: Hello
Macrolanguage: zh
Suppress-Script: Cyrl
Scope: collection
")
; Convenience Functions -------------------------------------------------------
(defn date [y m d]
{"year" y
"month" m
"day" d})
(defn dated [subtags]
{"file-date" (date 2012 9 12)
"subtags" subtags})
; Test Cases ------------------------------------------------------------------
(deftest test-empty
(testing "An empty registry."
(let [reg (parse-bcp47 empty-registry)]
(is (= reg
(dated []))))))
(deftest test-single-item
(testing "A single basic item."
(let [reg (parse-bcp47 single-item-registry)]
(is (= reg
(dated [{"type" "language"
"subtag" "aa"
"description" ["Afar"]
"added" (date 2005 10 16)}]))))))
(deftest test-two-items
(testing "Two basic items."
(let [reg (parse-bcp47 two-item-registry)]
(is (= reg
(dated [{"type" "language"
"subtag" "aa"
"description" ["Afar"]
"added" (date 2005 10 16)}
{"type" "language"
"subtag" "ab"
"description" ["Abkhazian"]
"added" (date 2005 10 16)
"suppress-script" "Cyrl"}]))))))
(deftest test-long-lines
(testing "An item with fields containing long lines."
(let [reg (parse-bcp47 long-line-registry)]
(is (= reg
(dated [{"type" "language"
"subtag" "pny"
"description" ["Pinyin"]
"added" (date 2009 7 29)
"comments" "a Niger-Congo language spoken in Cameroon; not to be confused with the Pinyin romanization systems used for Chinese and Tibetan"
}]))))))
(deftest test-multi-description
(testing "An item with multiple description fields."
(let [reg (parse-bcp47 multi-description-registry)]
(is (= reg
(dated [{"type" "language"
"subtag" "aa"
"description" ["PI:NAME:<NAME>END_PI" "Multi Line Description"]
"added" (date 2005 10 16) }]))))))
(deftest test-all-fields
(testing "An item with all possible fields."
(let [reg (parse-bcp47 all-fields-registry)]
(is (= reg
(dated [{"type" "language"
"subtag" "aa"
"description" ["PI:NAME:<NAME>END_PI"]
"added" (date 2005 10 16)
"deprecated" (date 2009 1 1)
"tag" "zh-Hans"
"prefix" "rm"
"preferred-value" "gan"
"comments" "Hello"
"macrolanguage" "zh"
"suppress-script" "Cyrl"
"scope" "collection"}]))))))
|
[
{
"context": ";; The MIT License (MIT)\n;;\n;; Copyright (c) 2015 Richard Hull\n;;\n;; Permission is hereby granted, free of charg",
"end": 62,
"score": 0.9997497200965881,
"start": 50,
"tag": "NAME",
"value": "Richard Hull"
}
] | src/wam/grammar.clj | rm-hull/wam | 23 | ;; The MIT License (MIT)
;;
;; Copyright (c) 2015 Richard Hull
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in all
;; copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(ns wam.grammar
(:refer-clojure :exclude [list])
(:require
[jasentaa.monad :as m]
[jasentaa.position :refer [strip-location]]
[jasentaa.parser.basic :refer :all]
[jasentaa.parser.combinators :refer :all]))
(defrecord Constant [value]
Object
(toString [this] (with-out-str (pr this)))
Comparable
(compareTo [this other] (compare (:value this) (:value other))))
(defrecord Variable [name]
Object
(toString [this] (with-out-str (pr this)))
Comparable
(compareTo [this other] (compare (:name this) (:name other))))
(defrecord Structure [functor args]
Object
(toString [this] (with-out-str (pr this))))
(defrecord Functor [name arg-count]
Object
(toString [this] (with-out-str (pr this))))
(defmethod print-method Structure [x ^java.io.Writer writer]
(print-method (-> x :functor :name) writer)
(when-not (empty? (:args x))
(print-method (:args x) writer)))
(defmethod print-method Variable [x ^java.io.Writer writer]
(print-method (:name x) writer))
(defmethod print-method Constant [x ^java.io.Writer writer]
(print-method (:value x) writer))
(defmethod print-method Functor [x ^java.io.Writer writer]
(print-method (:name x) writer)
(.write writer "|")
(print-method (:arg-count x) writer))
(def digit (from-re #"[0-9]"))
(def number
(m/do*
(v <- (plus digit))
(m/return (Integer/parseInt (strip-location v)))))
(def lower-alpha (from-re #"[a-z]"))
(def upper-alpha (from-re #"[A-Z]"))
(def alpha-num (strip-location (any-of lower-alpha upper-alpha digit)))
(def predicate
(m/do*
(a <- lower-alpha)
(as <- (many alpha-num))
(m/return (strip-location (cons a as)))))
(def constant
(m/do*
; (c <- (any-of predicate number))
(n <- number)
(m/return (Constant. n))))
(def variable
(or-else
(m/do*
(a <- upper-alpha)
(as <- (many alpha-num))
(m/return (Variable. (symbol (strip-location (cons a as))))))
(m/do*
(match "_")
(m/return (Variable. '_)))))
(declare list)
(def structure
(or-else
(m/do*
(p <- predicate)
(m/return (Structure.
(Functor. (symbol p) 0)
nil)))
(m/do*
(p <- predicate)
(symb "(")
(l <- list)
(symb ")")
(m/return (Structure.
(Functor. (symbol p) (count l))
l)))))
(def element
(any-of variable constant structure))
(def list
(separated-by (token element) (symb ",")))
| 66199 | ;; The MIT License (MIT)
;;
;; Copyright (c) 2015 <NAME>
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in all
;; copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(ns wam.grammar
(:refer-clojure :exclude [list])
(:require
[jasentaa.monad :as m]
[jasentaa.position :refer [strip-location]]
[jasentaa.parser.basic :refer :all]
[jasentaa.parser.combinators :refer :all]))
(defrecord Constant [value]
Object
(toString [this] (with-out-str (pr this)))
Comparable
(compareTo [this other] (compare (:value this) (:value other))))
(defrecord Variable [name]
Object
(toString [this] (with-out-str (pr this)))
Comparable
(compareTo [this other] (compare (:name this) (:name other))))
(defrecord Structure [functor args]
Object
(toString [this] (with-out-str (pr this))))
(defrecord Functor [name arg-count]
Object
(toString [this] (with-out-str (pr this))))
(defmethod print-method Structure [x ^java.io.Writer writer]
(print-method (-> x :functor :name) writer)
(when-not (empty? (:args x))
(print-method (:args x) writer)))
(defmethod print-method Variable [x ^java.io.Writer writer]
(print-method (:name x) writer))
(defmethod print-method Constant [x ^java.io.Writer writer]
(print-method (:value x) writer))
(defmethod print-method Functor [x ^java.io.Writer writer]
(print-method (:name x) writer)
(.write writer "|")
(print-method (:arg-count x) writer))
(def digit (from-re #"[0-9]"))
(def number
(m/do*
(v <- (plus digit))
(m/return (Integer/parseInt (strip-location v)))))
(def lower-alpha (from-re #"[a-z]"))
(def upper-alpha (from-re #"[A-Z]"))
(def alpha-num (strip-location (any-of lower-alpha upper-alpha digit)))
(def predicate
(m/do*
(a <- lower-alpha)
(as <- (many alpha-num))
(m/return (strip-location (cons a as)))))
(def constant
(m/do*
; (c <- (any-of predicate number))
(n <- number)
(m/return (Constant. n))))
(def variable
(or-else
(m/do*
(a <- upper-alpha)
(as <- (many alpha-num))
(m/return (Variable. (symbol (strip-location (cons a as))))))
(m/do*
(match "_")
(m/return (Variable. '_)))))
(declare list)
(def structure
(or-else
(m/do*
(p <- predicate)
(m/return (Structure.
(Functor. (symbol p) 0)
nil)))
(m/do*
(p <- predicate)
(symb "(")
(l <- list)
(symb ")")
(m/return (Structure.
(Functor. (symbol p) (count l))
l)))))
(def element
(any-of variable constant structure))
(def list
(separated-by (token element) (symb ",")))
| true | ;; The MIT License (MIT)
;;
;; Copyright (c) 2015 PI:NAME:<NAME>END_PI
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in all
;; copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(ns wam.grammar
(:refer-clojure :exclude [list])
(:require
[jasentaa.monad :as m]
[jasentaa.position :refer [strip-location]]
[jasentaa.parser.basic :refer :all]
[jasentaa.parser.combinators :refer :all]))
(defrecord Constant [value]
Object
(toString [this] (with-out-str (pr this)))
Comparable
(compareTo [this other] (compare (:value this) (:value other))))
(defrecord Variable [name]
Object
(toString [this] (with-out-str (pr this)))
Comparable
(compareTo [this other] (compare (:name this) (:name other))))
(defrecord Structure [functor args]
Object
(toString [this] (with-out-str (pr this))))
(defrecord Functor [name arg-count]
Object
(toString [this] (with-out-str (pr this))))
(defmethod print-method Structure [x ^java.io.Writer writer]
(print-method (-> x :functor :name) writer)
(when-not (empty? (:args x))
(print-method (:args x) writer)))
(defmethod print-method Variable [x ^java.io.Writer writer]
(print-method (:name x) writer))
(defmethod print-method Constant [x ^java.io.Writer writer]
(print-method (:value x) writer))
(defmethod print-method Functor [x ^java.io.Writer writer]
(print-method (:name x) writer)
(.write writer "|")
(print-method (:arg-count x) writer))
(def digit (from-re #"[0-9]"))
(def number
(m/do*
(v <- (plus digit))
(m/return (Integer/parseInt (strip-location v)))))
(def lower-alpha (from-re #"[a-z]"))
(def upper-alpha (from-re #"[A-Z]"))
(def alpha-num (strip-location (any-of lower-alpha upper-alpha digit)))
(def predicate
(m/do*
(a <- lower-alpha)
(as <- (many alpha-num))
(m/return (strip-location (cons a as)))))
(def constant
(m/do*
; (c <- (any-of predicate number))
(n <- number)
(m/return (Constant. n))))
(def variable
(or-else
(m/do*
(a <- upper-alpha)
(as <- (many alpha-num))
(m/return (Variable. (symbol (strip-location (cons a as))))))
(m/do*
(match "_")
(m/return (Variable. '_)))))
(declare list)
(def structure
(or-else
(m/do*
(p <- predicate)
(m/return (Structure.
(Functor. (symbol p) 0)
nil)))
(m/do*
(p <- predicate)
(symb "(")
(l <- list)
(symb ")")
(m/return (Structure.
(Functor. (symbol p) (count l))
l)))))
(def element
(any-of variable constant structure))
(def list
(separated-by (token element) (symb ",")))
|
[
{
"context": "ST\"}\n [:fieldset\n (html_/input \"Username\" :username)\n (html_/password \"Password\" :password)\n ",
"end": 302,
"score": 0.9845284819602966,
"start": 294,
"tag": "USERNAME",
"value": "username"
},
{
"context": "input \"Username\" :username)\n (html_/password \"Password\" :password)\n (html_/button \"Enter\")]]\n (htm",
"end": 334,
"score": 0.9768335819244385,
"start": 326,
"tag": "PASSWORD",
"value": "Password"
},
{
"context": "name\" :username)\n (html_/password \"Password\" :password)\n (html_/button \"Enter\")]]\n (html_/link \"No",
"end": 345,
"score": 0.5678665637969971,
"start": 337,
"tag": "PASSWORD",
"value": "password"
}
] | data/test/clojure/73efbbcbfd77db3036fbc4fa0737094313475f3alogin.clj | harshp8l/deep-learning-lang-detection | 84 | (ns note.dispatch.login
(:require (note (database :as db_)
(html :as html_))
(note.dispatch (common :as common_)
(path :as path_))))
(defn make-body
[]
[:div
[:form {:method "POST"}
[:fieldset
(html_/input "Username" :username)
(html_/password "Password" :password)
(html_/button "Enter")]]
(html_/link "No account yet?" (path_/get :create-user))])
(defn get-dispatch
[request]
{:body (make-body)})
(defn post-dispatch
[request]
(let [{:keys [username password]} (:params request)
user (db_/get-user username)]
(if user
(-> (common_/redirect :task-list)
(common_/update-session assoc :username username))
{:body (make-body)
:message [{:text "No such user." :type :error}]})))
| 107046 | (ns note.dispatch.login
(:require (note (database :as db_)
(html :as html_))
(note.dispatch (common :as common_)
(path :as path_))))
(defn make-body
[]
[:div
[:form {:method "POST"}
[:fieldset
(html_/input "Username" :username)
(html_/password "<PASSWORD>" :<PASSWORD>)
(html_/button "Enter")]]
(html_/link "No account yet?" (path_/get :create-user))])
(defn get-dispatch
[request]
{:body (make-body)})
(defn post-dispatch
[request]
(let [{:keys [username password]} (:params request)
user (db_/get-user username)]
(if user
(-> (common_/redirect :task-list)
(common_/update-session assoc :username username))
{:body (make-body)
:message [{:text "No such user." :type :error}]})))
| true | (ns note.dispatch.login
(:require (note (database :as db_)
(html :as html_))
(note.dispatch (common :as common_)
(path :as path_))))
(defn make-body
[]
[:div
[:form {:method "POST"}
[:fieldset
(html_/input "Username" :username)
(html_/password "PI:PASSWORD:<PASSWORD>END_PI" :PI:PASSWORD:<PASSWORD>END_PI)
(html_/button "Enter")]]
(html_/link "No account yet?" (path_/get :create-user))])
(defn get-dispatch
[request]
{:body (make-body)})
(defn post-dispatch
[request]
(let [{:keys [username password]} (:params request)
user (db_/get-user username)]
(if user
(-> (common_/redirect :task-list)
(common_/update-session assoc :username username))
{:body (make-body)
:message [{:text "No such user." :type :error}]})))
|
[
{
"context": "l, it's a constant.\n(def ^:private js-engine-key \"js-engine\")\n(def ^:private js-engine-pool\n (flow/instrumen",
"end": 874,
"score": 0.9862586855888367,
"start": 865,
"tag": "KEY",
"value": "js-engine"
}
] | recipes/reagent-server-rendering/src/clj/reagent_server_rendering/handler.clj | yatesj9/reagent-cookbook | 825 | (ns reagent-server-rendering.handler
(:require [aleph.flow :as flow]
[clojure.java.io :as io]
[hiccup.core :refer [html]]
[hiccup.page :refer [include-js include-css]]
[compojure.core :refer [GET defroutes]]
[compojure.route :refer [not-found resources]]
[ring.middleware.defaults :refer [site-defaults wrap-defaults]])
(:import [io.aleph.dirigiste Pools]
[javax.script ScriptEngineManager Invocable]))
(defn- create-js-engine []
(doto (.getEngineByName (ScriptEngineManager.) "nashorn")
; React requires either "window" or "global" to be defined.
(.eval "var global = this")
(.eval (-> "public/js/compiled/app.js"
io/resource
io/reader))))
; We have one and only one key in the pool, it's a constant.
(def ^:private js-engine-key "js-engine")
(def ^:private js-engine-pool
(flow/instrumented-pool
{:generate (fn [_] (create-js-engine))
:controller (Pools/utilizationController 0.9 10000 10000)}))
(defn- render-page [page-id]
(let [js-engine @(flow/acquire js-engine-pool js-engine-key)]
(try (.invokeMethod
^Invocable js-engine
(.eval js-engine "reagent_server_rendering.core")
"render_page" (object-array [page-id]))
(finally (flow/release js-engine-pool js-engine-key js-engine)))))
(defn page [page-id]
(html
[:html
[:head
[:meta {:charset "utf-8"}]
[:meta {:name "viewport"
:content "width=device-width, initial-scale=1"}]
(include-css "css/site.css")]
[:body
[:div#app
(render-page page-id)]
(include-js "js/compiled/app.js")
[:script {:type "text/javascript"}
(str "reagent_server_rendering.core.main('" page-id "');")]]]))
(defroutes app-routes
(GET "/" [] (page "home"))
(GET "/about" [] (page "about"))
(resources "/")
(not-found "Not Found"))
(def app (wrap-defaults app-routes site-defaults))
| 95711 | (ns reagent-server-rendering.handler
(:require [aleph.flow :as flow]
[clojure.java.io :as io]
[hiccup.core :refer [html]]
[hiccup.page :refer [include-js include-css]]
[compojure.core :refer [GET defroutes]]
[compojure.route :refer [not-found resources]]
[ring.middleware.defaults :refer [site-defaults wrap-defaults]])
(:import [io.aleph.dirigiste Pools]
[javax.script ScriptEngineManager Invocable]))
(defn- create-js-engine []
(doto (.getEngineByName (ScriptEngineManager.) "nashorn")
; React requires either "window" or "global" to be defined.
(.eval "var global = this")
(.eval (-> "public/js/compiled/app.js"
io/resource
io/reader))))
; We have one and only one key in the pool, it's a constant.
(def ^:private js-engine-key "<KEY>")
(def ^:private js-engine-pool
(flow/instrumented-pool
{:generate (fn [_] (create-js-engine))
:controller (Pools/utilizationController 0.9 10000 10000)}))
(defn- render-page [page-id]
(let [js-engine @(flow/acquire js-engine-pool js-engine-key)]
(try (.invokeMethod
^Invocable js-engine
(.eval js-engine "reagent_server_rendering.core")
"render_page" (object-array [page-id]))
(finally (flow/release js-engine-pool js-engine-key js-engine)))))
(defn page [page-id]
(html
[:html
[:head
[:meta {:charset "utf-8"}]
[:meta {:name "viewport"
:content "width=device-width, initial-scale=1"}]
(include-css "css/site.css")]
[:body
[:div#app
(render-page page-id)]
(include-js "js/compiled/app.js")
[:script {:type "text/javascript"}
(str "reagent_server_rendering.core.main('" page-id "');")]]]))
(defroutes app-routes
(GET "/" [] (page "home"))
(GET "/about" [] (page "about"))
(resources "/")
(not-found "Not Found"))
(def app (wrap-defaults app-routes site-defaults))
| true | (ns reagent-server-rendering.handler
(:require [aleph.flow :as flow]
[clojure.java.io :as io]
[hiccup.core :refer [html]]
[hiccup.page :refer [include-js include-css]]
[compojure.core :refer [GET defroutes]]
[compojure.route :refer [not-found resources]]
[ring.middleware.defaults :refer [site-defaults wrap-defaults]])
(:import [io.aleph.dirigiste Pools]
[javax.script ScriptEngineManager Invocable]))
(defn- create-js-engine []
(doto (.getEngineByName (ScriptEngineManager.) "nashorn")
; React requires either "window" or "global" to be defined.
(.eval "var global = this")
(.eval (-> "public/js/compiled/app.js"
io/resource
io/reader))))
; We have one and only one key in the pool, it's a constant.
(def ^:private js-engine-key "PI:KEY:<KEY>END_PI")
(def ^:private js-engine-pool
(flow/instrumented-pool
{:generate (fn [_] (create-js-engine))
:controller (Pools/utilizationController 0.9 10000 10000)}))
(defn- render-page [page-id]
(let [js-engine @(flow/acquire js-engine-pool js-engine-key)]
(try (.invokeMethod
^Invocable js-engine
(.eval js-engine "reagent_server_rendering.core")
"render_page" (object-array [page-id]))
(finally (flow/release js-engine-pool js-engine-key js-engine)))))
(defn page [page-id]
(html
[:html
[:head
[:meta {:charset "utf-8"}]
[:meta {:name "viewport"
:content "width=device-width, initial-scale=1"}]
(include-css "css/site.css")]
[:body
[:div#app
(render-page page-id)]
(include-js "js/compiled/app.js")
[:script {:type "text/javascript"}
(str "reagent_server_rendering.core.main('" page-id "');")]]]))
(defroutes app-routes
(GET "/" [] (page "home"))
(GET "/about" [] (page "about"))
(resources "/")
(not-found "Not Found"))
(def app (wrap-defaults app-routes site-defaults))
|
[
{
"context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio",
"end": 29,
"score": 0.9998134970664978,
"start": 18,
"tag": "NAME",
"value": "Rich Hickey"
}
] | Source/clojure/spec.clj | max-lv/Arcadia | 0 | ; Copyright (c) Rich Hickey. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns clojure.spec
(:refer-clojure :exclude [+ * and assert or cat def keys merge])
(:require [clojure.walk :as walk]
[clojure.spec.gen :as gen]
[clojure.string :as str]))
(alias 'c 'clojure.core)
(set! *warn-on-reflection* true)
(def ^:dynamic *recursion-limit*
"A soft limit on how many times a branching spec (or/alt/*/opt-keys/multi-spec)
can be recursed through during generation. After this a
non-recursive branch will be chosen."
4)
(def ^:dynamic *fspec-iterations*
"The number of times an anonymous fn specified by fspec will be (generatively) tested during conform"
21)
(def ^:dynamic *coll-check-limit*
"The number of elements validated in a collection spec'ed with 'every'"
101)
(def ^:dynamic *coll-error-limit*
"The number of errors reported by explain in a collection spec'ed with 'every'"
20)
(defprotocol Spec
(conform* [spec x])
(unform* [spec y])
(explain* [spec path via in x])
(gen* [spec overrides path rmap])
(with-gen* [spec gfn])
(describe* [spec]))
(defonce ^:private registry-ref (atom {}))
(defn- named? [x] (instance? clojure.lang.Named x))
(defn- with-name [spec name]
(with-meta spec (assoc (meta spec) ::name name)))
(defn- spec-name [spec]
(cond
(keyword? spec) spec
(instance? clojure.lang.IObj spec)
(-> (meta spec) ::name)))
(defn- reg-resolve
"returns the spec/regex at end of alias chain starting with k, nil if not found, k if k not Named"
[k]
(if (named? k)
(let [reg @registry-ref]
(loop [spec k]
(if (named? spec)
(recur (get reg spec))
(when spec
(with-name spec k)))))
k))
(defn- reg-resolve!
"returns the spec/regex at end of alias chain starting with k, throws if not found, k if k not ident"
[k]
(if (ident? k)
(c/or (reg-resolve k)
(throw (Exception. (str "Unable to resolve spec: " k))))
k))
(defn spec?
"returns x if x is a spec object, else logical false"
[x]
(c/and (extends? Spec (class x)) x))
(defn regex?
"returns x if x is a (clojure.spec) regex op, else logical false"
[x]
(c/and (::op x) x))
(declare spec-impl)
(declare regex-spec-impl)
(defn- maybe-spec
"spec-or-k must be a spec, regex or resolvable kw/sym, else returns nil."
[spec-or-k]
(let [s (c/or (spec? spec-or-k)
(regex? spec-or-k)
(c/and (named? spec-or-k) (reg-resolve spec-or-k))
nil)]
(if (regex? s)
(with-name (regex-spec-impl s nil) (spec-name s))
s)))
(defn- the-spec
"spec-or-k must be a spec, regex or kw/sym, else returns nil. Throws if unresolvable kw/sym"
[spec-or-k]
(c/or (maybe-spec spec-or-k)
(when (named? spec-or-k)
(throw (Exception. (str "Unable to resolve spec: " spec-or-k))))))
(defn- specize [s]
(c/or (the-spec s) (spec-impl ::unknown s nil nil)))
(defn conform
"Given a spec and a value, returns :clojure.spec/invalid if value does not match spec,
else the (possibly destructured) value."
[spec x]
(conform* (specize spec) x))
(defn unform
"Given a spec and a value created by or compliant with a call to
'conform' with the same spec, returns a value with all conform
destructuring undone."
[spec x]
(unform* (specize spec) x))
(defn form
"returns the spec as data"
[spec]
;;TODO - incorporate gens
(describe* (specize spec)))
(defn abbrev [form]
(cond
(seq? form)
(walk/postwalk (fn [form]
(cond
(c/and (symbol? form) (namespace form))
(-> form name symbol)
(c/and (seq? form) (= 'fn (first form)) (= '[%] (second form)))
(last form)
:else form))
form)
(c/and (symbol? form) (namespace form))
(-> form name symbol)
:else form))
(defn describe
"returns an abbreviated description of the spec as data"
[spec]
(abbrev (form spec)))
(defn with-gen
"Takes a spec and a no-arg, generator-returning fn and returns a version of that spec that uses that generator"
[spec gen-fn]
(let [spec (reg-resolve spec)]
(if (regex? spec)
(assoc spec ::gfn gen-fn)
(with-gen* (specize spec) gen-fn))))
(defn explain-data* [spec path via in x]
(let [probs (explain* (specize spec) path via in x)]
(when-not (empty? probs)
{::problems probs})))
(defn explain-data
"Given a spec and a value x which ought to conform, returns nil if x
conforms, else a map with at least the key ::problems whose value is
a collection of problem-maps, where problem-map has at least :path :pred and :val
keys describing the predicate and the value that failed at that
path."
[spec x]
(explain-data* spec [] (if-let [name (spec-name spec)] [name] []) [] x))
(defn explain-out
"prints explanation data (per 'explain-data') to *out*."
[ed]
(if ed
(do
;;(prn {:ed ed})
(doseq [{:keys [path pred val reason via in] :as prob} (::problems ed)]
(when-not (empty? in)
(print "In:" (pr-str in) ""))
(print "val: ")
(pr val)
(print " fails")
(when-not (empty? via)
(print " spec:" (pr-str (last via))))
(when-not (empty? path)
(print " at:" (pr-str path)))
(print " predicate: ")
(pr (abbrev pred))
(when reason (print ", " reason))
(doseq [[k v] prob]
(when-not (#{:path :pred :val :reason :via :in} k)
(print "\n\t" (pr-str k) " ")
(pr v)))
(newline))
(doseq [[k v] ed]
(when-not (#{::problems} k)
(print (pr-str k) " ")
(pr v)
(newline))))
(println "Success!")))
(defn explain
"Given a spec and a value that fails to conform, prints an explanation to *out*."
[spec x]
(explain-out (explain-data spec x)))
(defn explain-str
"Given a spec and a value that fails to conform, returns an explanation as a string."
[spec x]
(with-out-str (explain spec x)))
(declare valid?)
(defn- gensub
[spec overrides path rmap form]
;;(prn {:spec spec :over overrides :path path :form form})
(let [spec (specize spec)]
(if-let [g (c/or (when-let [gfn (c/or (get overrides (c/or (spec-name spec) spec))
(get overrides path))]
(gfn))
(gen* spec overrides path rmap))]
(gen/such-that #(valid? spec %) g 100)
(let [abbr (abbrev form)]
(throw (ex-info (str "Unable to construct gen at: " path " for: " abbr)
{::path path ::form form ::failure :no-gen}))))))
(defn gen
"Given a spec, returns the generator for it, or throws if none can
be constructed. Optionally an overrides map can be provided which
should map spec names or paths (vectors of keywords) to no-arg
generator-creating fns. These will be used instead of the generators at those
names/paths. Note that parent generator (in the spec or overrides
map) will supersede those of any subtrees. A generator for a regex
op must always return a sequential collection (i.e. a generator for
s/? should return either an empty sequence/vector or a
sequence/vector with one item in it)"
([spec] (gen spec nil))
([spec overrides] (gensub spec overrides [] {::recursion-limit *recursion-limit*} spec)))
(defn- ->sym
"Returns a symbol from a symbol or var"
[x]
(if (var? x)
(let [^clojure.lang.Var v x]
(symbol (str (.Name (.ns v)))
(str (.sym v))))
x))
(defn- unfn [expr]
(if (c/and (seq? expr)
(symbol? (first expr))
(= "fn*" (name (first expr))))
(let [[[s] & form] (rest expr)]
(conj (walk/postwalk-replace {s '%} form) '[%] 'fn))
expr))
(defn- res [form]
(cond
(keyword? form) form
(symbol? form) (c/or (-> form resolve ->sym) form)
(sequential? form) (walk/postwalk #(if (symbol? %) (res %) %) (unfn form))
:else form))
(defn ^:skip-wiki def-impl
"Do not call this directly, use 'def'"
[k form spec]
(c/assert (c/and (named? k) (namespace k)) "k must be namespaced keyword or resolvable symbol")
(let [spec (if (c/or (spec? spec) (regex? spec) (get @registry-ref spec))
spec
(spec-impl form spec nil nil))]
(swap! registry-ref assoc k spec)
k))
(defn- ns-qualify
"Qualify symbol s by resolving it or using the current *ns*."
[s]
(if-let [ns-sym (some-> s namespace symbol)]
(c/or (some-> (get (ns-aliases *ns*) ns-sym) str (symbol (name s)))
s)
(symbol (str (.Name *ns*)) (str s))))
(defmacro def
"Given a namespace-qualified keyword or resolvable symbol k, and a
spec, spec-name, predicate or regex-op makes an entry in the
registry mapping k to the spec"
[k spec-form]
(let [k (if (symbol? k) (ns-qualify k) k)]
`(def-impl '~k '~(res spec-form) ~spec-form)))
(defn registry
"returns the registry map, prefer 'get-spec' to lookup a spec by name"
[]
@registry-ref)
(defn get-spec
"Returns spec registered for keyword/symbol/var k, or nil."
[k]
(get (registry) (if (keyword? k) k (->sym k))))
(declare map-spec)
(defmacro spec
"Takes a single predicate form, e.g. can be the name of a predicate,
like even?, or a fn literal like #(< % 42). Note that it is not
generally necessary to wrap predicates in spec when using the rest
of the spec macros, only to attach a unique generator
Can also be passed the result of one of the regex ops -
cat, alt, *, +, ?, in which case it will return a regex-conforming
spec, useful when nesting an independent regex.
---
Optionally takes :gen generator-fn, which must be a fn of no args that
returns a test.check generator.
Returns a spec."
[form & {:keys [gen]}]
(when form
`(spec-impl '~(res form) ~form ~gen nil)))
(defmacro multi-spec
"Takes the name of a spec/predicate-returning multimethod and a
tag-restoring keyword or fn (retag). Returns a spec that when
conforming or explaining data will pass it to the multimethod to get
an appropriate spec. You can e.g. use multi-spec to dynamically and
extensibly associate specs with 'tagged' data (i.e. data where one
of the fields indicates the shape of the rest of the structure).
(defmulti mspec :tag)
The methods should ignore their argument and return a predicate/spec:
(defmethod mspec :int [_] (s/keys :req-un [::tag ::i]))
retag is used during generation to retag generated values with
matching tags. retag can either be a keyword, at which key the
dispatch-tag will be assoc'ed, or a fn of generated value and
dispatch-tag that should return an appropriately retagged value.
Note that because the tags themselves comprise an open set,
the tag key spec cannot enumerate the values, but can e.g.
test for keyword?.
Note also that the dispatch values of the multimethod will be
included in the path, i.e. in reporting and gen overrides, even
though those values are not evident in the spec.
"
[mm retag]
`(multi-spec-impl '~(res mm) (var ~mm) ~retag))
(defmacro keys
"Creates and returns a map validating spec. :req and :opt are both
vectors of namespaced-qualified keywords. The validator will ensure
the :req keys are present. The :opt keys serve as documentation and
may be used by the generator.
The :req key vector supports 'and' and 'or' for key groups:
(s/keys :req [::x ::y (or ::secret (and ::user ::pwd))] :opt [::z])
There are also -un versions of :req and :opt. These allow
you to connect unqualified keys to specs. In each case, fully
qualfied keywords are passed, which name the specs, but unqualified
keys (with the same name component) are expected and checked at
conform-time, and generated during gen:
(s/keys :req-un [:my.ns/x :my.ns/y])
The above says keys :x and :y are required, and will be validated
and generated by specs (if they exist) named :my.ns/x :my.ns/y
respectively.
In addition, the values of *all* namespace-qualified keys will be validated
(and possibly destructured) by any registered specs. Note: there is
no support for inline value specification, by design.
Optionally takes :gen generator-fn, which must be a fn of no args that
returns a test.check generator."
[& {:keys [req req-un opt opt-un gen]}]
(let [unk #(-> % name keyword)
req-keys (filterv keyword? (flatten req))
req-un-specs (filterv keyword? (flatten req-un))
_ (c/assert (every? #(c/and (keyword? %) (namespace %)) (concat req-keys req-un-specs opt opt-un))
"all keys must be namespace-qualified keywords")
req-specs (into req-keys req-un-specs)
req-keys (into req-keys (map unk req-un-specs))
opt-keys (into (vec opt) (map unk opt-un))
opt-specs (into (vec opt) opt-un)
parse-req (fn [rk f]
(map (fn [x]
(if (keyword? x)
`#(contains? % ~(f x))
(let [gx (gensym)]
`(fn* [~gx]
~(walk/postwalk
(fn [y] (if (keyword? y) `(contains? ~gx ~(f y)) y))
x)))))
rk))
pred-exprs [`map?]
pred-exprs (into pred-exprs (parse-req req identity))
pred-exprs (into pred-exprs (parse-req req-un unk))
pred-forms (walk/postwalk res pred-exprs)]
;; `(map-spec-impl ~req-keys '~req ~opt '~pred-forms ~pred-exprs ~gen)
`(map-spec-impl {:req '~req :opt '~opt :req-un '~req-un :opt-un '~opt-un
:req-keys '~req-keys :req-specs '~req-specs
:opt-keys '~opt-keys :opt-specs '~opt-specs
:pred-forms '~pred-forms
:pred-exprs ~pred-exprs
:gfn ~gen})))
(defmacro or
"Takes key+pred pairs, e.g.
(s/or :even even? :small #(< % 42))
Returns a destructuring spec that returns a map entry containing the
key of the first matching pred and the corresponding value. Thus the
'key' and 'val' functions can be used to refer generically to the
components of the tagged return."
[& key-pred-forms]
(let [pairs (partition 2 key-pred-forms)
keys (mapv first pairs)
pred-forms (mapv second pairs)
pf (mapv res pred-forms)]
(c/assert (c/and (even? (count key-pred-forms)) (every? keyword? keys)) "spec/or expects k1 p1 k2 p2..., where ks are keywords")
`(or-spec-impl ~keys '~pf ~pred-forms nil)))
(defmacro and
"Takes predicate/spec-forms, e.g.
(s/and even? #(< % 42))
Returns a spec that returns the conformed value. Successive
conformed values propagate through rest of predicates."
[& pred-forms]
`(and-spec-impl '~(mapv res pred-forms) ~(vec pred-forms) nil))
(defmacro merge
"Takes map-validating specs (e.g. 'keys' specs) and
returns a spec that returns a conformed map satisfying all of the
specs. Successive conformed values propagate through rest of
predicates. Unlike 'and', merge can generate maps satisfying the
union of the predicates."
[& pred-forms]
`(merge-spec-impl '~(mapv res pred-forms) ~(vec pred-forms) nil))
(defmacro every
"takes a pred and validates collection elements against that pred.
Note that 'every' does not do exhaustive checking, rather it samples
*coll-check-limit* elements. Nor (as a result) does it do any
conforming of elements. 'explain' will report at most *coll-error-limit*
problems. Thus 'every' should be suitable for potentially large
collections.
Takes several kwargs options that further constrain the collection:
:kind - a pred/spec that the collection type must satisfy, e.g. vector?
(default nil) Note that if :kind is specified and :into is
not, this pred must generate in order for every to generate.
:count - specifies coll has exactly this count (default nil)
:min-count, :max-count - coll has count (<= min-count count max-count) (defaults nil)
:distinct - all the elements are distinct (default nil)
And additional args that control gen
:gen-max - the maximum coll size to generate (default 20)
:into - one of [], (), {}, #{} - the default collection to generate into
(default: empty coll as generated by :kind pred if supplied, else [])
Optionally takes :gen generator-fn, which must be a fn of no args that
returns a test.check generator
See also - coll-of, every-kv
"
[pred & {:keys [into kind count max-count min-count distinct gen-max gen] :as opts}]
(let [nopts (-> opts (dissoc :gen) (assoc ::kind-form `'~(res (:kind opts))))]
`(every-impl '~pred ~pred ~nopts ~gen)))
(defmacro every-kv
"like 'every' but takes separate key and val preds and works on associative collections.
Same options as 'every', :into defaults to {}
See also - map-of"
[kpred vpred & opts]
`(every (tuple ~kpred ~vpred) ::kfn (fn [i# v#] (nth v# 0)) :into {} ~@opts))
(defmacro coll-of
"Returns a spec for a collection of items satisfying pred. Unlike
'every', coll-of will exhaustively conform every value.
Same options as 'every'. conform will produce a collection
corresponding to :into if supplied, else will match the input collection,
avoiding rebuilding when possible.
See also - every, map-of"
[pred & opts]
`(every ~pred ::conform-all true ~@opts))
(defmacro map-of
"Returns a spec for a map whose keys satisfy kpred and vals satisfy
vpred. Unlike 'every-kv', map-of will exhaustively conform every
value.
Same options as 'every', :kind defaults to map?, with the addition of:
:conform-keys - conform keys as well as values (default false)
See also - every-kv"
[kpred vpred & opts]
`(every-kv ~kpred ~vpred ::conform-all true :kind map? ~@opts))
(defmacro *
"Returns a regex op that matches zero or more values matching
pred. Produces a vector of matches iff there is at least one match"
[pred-form]
`(rep-impl '~(res pred-form) ~pred-form))
(defmacro +
"Returns a regex op that matches one or more values matching
pred. Produces a vector of matches"
[pred-form]
`(rep+impl '~(res pred-form) ~pred-form))
(defmacro ?
"Returns a regex op that matches zero or one value matching
pred. Produces a single value (not a collection) if matched."
[pred-form]
`(maybe-impl ~pred-form '~pred-form))
(defmacro alt
"Takes key+pred pairs, e.g.
(s/alt :even even? :small #(< % 42))
Returns a regex op that returns a map entry containing the key of the
first matching pred and the corresponding value. Thus the
'key' and 'val' functions can be used to refer generically to the
components of the tagged return"
[& key-pred-forms]
(let [pairs (partition 2 key-pred-forms)
keys (mapv first pairs)
pred-forms (mapv second pairs)
pf (mapv res pred-forms)]
(c/assert (c/and (even? (count key-pred-forms)) (every? keyword? keys)) "alt expects k1 p1 k2 p2..., where ks are keywords")
`(alt-impl ~keys ~pred-forms '~pf)))
(defmacro cat
"Takes key+pred pairs, e.g.
(s/cat :e even? :o odd?)
Returns a regex op that matches (all) values in sequence, returning a map
containing the keys of each pred and the corresponding value."
[& key-pred-forms]
(let [pairs (partition 2 key-pred-forms)
keys (mapv first pairs)
pred-forms (mapv second pairs)
pf (mapv res pred-forms)]
;;(prn key-pred-forms)
(c/assert (c/and (even? (count key-pred-forms)) (every? keyword? keys)) "cat expects k1 p1 k2 p2..., where ks are keywords")
`(cat-impl ~keys ~pred-forms '~pf)))
(defmacro &
"takes a regex op re, and predicates. Returns a regex-op that consumes
input as per re but subjects the resulting value to the
conjunction of the predicates, and any conforming they might perform."
[re & preds]
(let [pv (vec preds)]
`(amp-impl ~re ~pv '~(mapv res pv))))
(defmacro conformer
"takes a predicate function with the semantics of conform i.e. it should return either a
(possibly converted) value or :clojure.spec/invalid, and returns a
spec that uses it as a predicate/conformer. Optionally takes a
second fn that does unform of result of first"
([f] `(spec-impl '~f ~f nil true))
([f unf] `(spec-impl '~f ~f nil true ~unf)))
(defmacro fspec
"takes :args :ret and (optional) :fn kwargs whose values are preds
and returns a spec whose conform/explain take a fn and validates it
using generative testing. The conformed value is always the fn itself.
See 'fdef' for a single operation that creates an fspec and
registers it, as well as a full description of :args, :ret and :fn
fspecs can generate functions that validate the arguments and
fabricate a return value compliant with the :ret spec, ignoring
the :fn spec if present.
Optionally takes :gen generator-fn, which must be a fn of no args
that returns a test.check generator."
[& {:keys [args ret fn gen]}]
`(fspec-impl (spec ~args) '~(res args)
(spec ~ret) '~(res ret)
(spec ~fn) '~(res fn) ~gen))
(defmacro tuple
"takes one or more preds and returns a spec for a tuple, a vector
where each element conforms to the corresponding pred. Each element
will be referred to in paths using its ordinal."
[& preds]
(c/assert (not (empty? preds)))
`(tuple-impl '~(mapv res preds) ~(vec preds)))
(defn- macroexpand-check
[v args]
(let [fn-spec (get-spec v)]
(when-let [arg-spec (:args fn-spec)]
(when (= ::invalid (conform arg-spec args))
(let [ed (assoc (explain-data* arg-spec [:args]
(if-let [name (spec-name arg-spec)] [name] []) [] args)
::args args)]
(throw (ArgumentException.
(str
"Call to " (->sym v) " did not conform to spec:\n"
(with-out-str (explain-out ed))))))))))
(defmacro fdef
"Takes a symbol naming a function, and one or more of the following:
:args A regex spec for the function arguments as they were a list to be
passed to apply - in this way, a single spec can handle functions with
multiple arities
:ret A spec for the function's return value
:fn A spec of the relationship between args and ret - the
value passed is {:args conformed-args :ret conformed-ret} and is
expected to contain predicates that relate those values
Qualifies fn-sym with resolve, or using *ns* if no resolution found.
Registers an fspec in the global registry, where it can be retrieved
by calling get-spec with the var or fully-qualified symbol.
Once registered, function specs are included in doc, checked by
instrument, tested by the runner clojure.spec.test/run-tests, and (if
a macro) used to explain errors during macroexpansion.
Note that :fn specs require the presence of :args and :ret specs to
conform values, and so :fn specs will be ignored if :args or :ret
are missing.
Returns the qualified fn-sym.
For example, to register function specs for the symbol function:
(s/fdef clojure.core/symbol
:args (s/alt :separate (s/cat :ns string? :n string?)
:str string?
:sym symbol?)
:ret symbol?)"
[fn-sym & specs]
`(clojure.spec/def ~fn-sym (clojure.spec/fspec ~@specs)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; impl ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- recur-limit? [rmap id path k]
(c/and (> (get rmap id) (::recursion-limit rmap))
(contains? (set path) k)))
(defn- inck [m k]
(assoc m k (inc (c/or (get m k) 0))))
(defn- dt
([pred x form] (dt pred x form nil))
([pred x form cpred?]
(if pred
(if-let [spec (the-spec pred)]
(conform spec x)
(if (ifn? pred)
(if cpred?
(pred x)
(if (pred x) x ::invalid))
(throw (Exception. (str (pr-str form) " is not a fn, expected predicate fn")))))
x)))
(defn valid?
"Helper function that returns true when x is valid for spec."
([spec x]
(not= ::invalid (dt spec x ::unknown)))
([spec x form]
(not= ::invalid (dt spec x form))))
(defn- explain-1 [form pred path via in v]
;;(prn {:form form :pred pred :path path :in in :v v})
(let [pred (maybe-spec pred)]
(if (spec? pred)
(explain* pred path (if-let [name (spec-name pred)] (conj via name) via) in v)
[{:path path :pred (abbrev form) :val v :via via :in in}])))
(defn ^:skip-wiki map-spec-impl
"Do not call this directly, use 'spec' with a map argument"
[{:keys [req-un opt-un pred-exprs opt-keys req-specs req req-keys opt-specs pred-forms opt gfn]
:as argm}]
(let [keys-pred (apply every-pred pred-exprs)
k->s (zipmap (concat req-keys opt-keys) (concat req-specs opt-specs))
keys->specs #(c/or (k->s %) %)
;; id (java.util.UUID/randomUUID)
id (System.Guid.) ;; maaaaybe?
]
(reify
clojure.lang.IFn
(invoke [this x] (valid? this x))
Spec
(conform* [_ m]
(if (keys-pred m)
(let [reg (registry)]
(loop [ret m, [k & ks :as keys] (c/keys m)]
(if keys
(if (contains? reg (keys->specs k))
(let [v (get m k)
cv (conform (keys->specs k) v)]
(if (= cv ::invalid)
::invalid
(recur (if (identical? cv v) ret (assoc ret k cv))
ks)))
(recur ret ks))
ret)))
::invalid))
(unform* [_ m]
(let [reg (registry)]
(loop [ret m, [k & ks :as keys] (c/keys m)]
(if keys
(if (contains? reg (keys->specs k))
(let [cv (get m k)
v (unform (keys->specs k) cv)]
(recur (if (identical? cv v) ret (assoc ret k v))
ks))
(recur ret ks))
ret))))
(explain* [_ path via in x]
(if-not (map? x)
[{:path path :pred 'map? :val x :via via :in in}]
(let [reg (registry)]
(apply concat
(when-let [probs (->> (map (fn [pred form] (when-not (pred x) (abbrev form)))
pred-exprs pred-forms)
(keep identity)
seq)]
(map
#(identity {:path path :pred % :val x :via via :in in})
probs))
(map (fn [[k v]]
(when-not (c/or (not (contains? reg (keys->specs k)))
(valid? (keys->specs k) v k))
(explain-1 (keys->specs k) (keys->specs k) (conj path k) via (conj in k) v)))
(seq x))))))
(gen* [_ overrides path rmap]
(if gfn
(gfn)
(let [rmap (inck rmap id)
gen (fn [k s] (gensub s overrides (conj path k) rmap k))
ogen (fn [k s]
(when-not (recur-limit? rmap id path k)
[k (gen/delay (gensub s overrides (conj path k) rmap k))]))
req-gens (map gen req-keys req-specs)
opt-gens (remove nil? (map ogen opt-keys opt-specs))]
(when (every? identity (concat req-gens opt-gens))
(let [reqs (zipmap req-keys req-gens)
opts (into {} opt-gens)]
(gen/bind (gen/choose 0 (count opts))
#(let [args (concat (seq reqs) (when (seq opts) (shuffle (seq opts))))]
(->> args
(take (c/+ % (count reqs)))
(apply concat)
(apply gen/hash-map)))))))))
(with-gen* [_ gfn] (map-spec-impl (assoc argm :gfn gfn)))
(describe* [_] (cons `keys
(cond-> []
req (conj :req req)
opt (conj :opt opt)
req-un (conj :req-un req-un)
opt-un (conj :opt-un opt-un)))))))
(defn ^:skip-wiki spec-impl
"Do not call this directly, use 'spec'"
([form pred gfn cpred?] (spec-impl form pred gfn cpred? nil))
([form pred gfn cpred? unc]
(cond
(spec? pred) (cond-> pred gfn (with-gen gfn))
(regex? pred) (regex-spec-impl pred gfn)
(named? pred) (cond-> (the-spec pred) gfn (with-gen gfn))
:else
(reify
Spec
(conform* [_ x] (dt pred x form cpred?))
(unform* [_ x] (if cpred?
(if unc
(unc x)
(throw (InvalidOperationException. "no unform fn for conformer")))
x))
(explain* [_ path via in x]
(when (= ::invalid (dt pred x form cpred?))
[{:path path :pred (abbrev form) :val x :via via :in in}]))
(gen* [_ _ _ _] (if gfn
(gfn)
(gen/gen-for-pred pred)))
(with-gen* [_ gfn] (spec-impl form pred gfn cpred?))
(describe* [_] form)))))
(defn ^:skip-wiki multi-spec-impl
"Do not call this directly, use 'multi-spec'"
([form mmvar retag] (multi-spec-impl form mmvar retag nil))
([form mmvar retag gfn]
(let [id (System.Guid.)
predx #(let [^clojure.lang.MultiFn mm @mmvar]
(c/and (contains? (methods mm)
((.dispatchFn mm) %))
(mm %)))
dval #((.dispatchFn ^clojure.lang.MultiFn @mmvar) %)
tag (if (keyword? retag)
#(assoc %1 retag %2)
retag)]
(reify
Spec
(conform* [_ x] (if-let [pred (predx x)]
(dt pred x form)
::invalid))
(unform* [_ x] (if-let [pred (predx x)]
(unform pred x)
(throw (InvalidOperationException. (str "No method of: " form " for dispatch value: " (dval x))))))
(explain* [_ path via in x]
(let [dv (dval x)
path (conj path dv)]
(if-let [pred (predx x)]
(explain-1 form pred path via in x)
[{:path path :pred (abbrev form) :val x :reason "no method" :via via :in in}])))
(gen* [_ overrides path rmap]
(if gfn
(gfn)
(let [gen (fn [[k f]]
(let [p (f nil)]
(let [rmap (inck rmap id)]
(when-not (recur-limit? rmap id path k)
(gen/delay
(gen/fmap
#(tag % k)
(gensub p overrides (conj path k) rmap (list 'method form k))))))))
gs (->> (methods @mmvar)
(remove (fn [[k]] (= k ::invalid)))
(map gen)
(remove nil?))]
(when (every? identity gs)
(gen/one-of gs)))))
(with-gen* [_ gfn] (multi-spec-impl form mmvar retag gfn))
(describe* [_] `(multi-spec ~form))))))
(defn ^:skip-wiki tuple-impl
"Do not call this directly, use 'tuple'"
([forms preds] (tuple-impl forms preds nil))
([forms preds gfn]
(reify
Spec
(conform* [_ x]
(if-not (c/and (vector? x)
(= (count x) (count preds)))
::invalid
(loop [ret x, i 0]
(if (= i (count x))
ret
(let [v (x i)
cv (dt (preds i) v (forms i))]
(if (= ::invalid cv)
::invalid
(recur (if (identical? cv v) ret (assoc ret i cv))
(inc i))))))))
(unform* [_ x]
(c/assert (c/and (vector? x)
(= (count x) (count preds))))
(loop [ret x, i 0]
(if (= i (count x))
ret
(let [cv (x i)
v (unform (preds i) cv)]
(recur (if (identical? cv v) ret (assoc ret i v))
(inc i))))))
(explain* [_ path via in x]
(cond
(not (vector? x))
[{:path path :pred 'vector? :val x :via via :in in}]
(not= (count x) (count preds))
[{:path path :pred `(= (count ~'%) ~(count preds)) :val x :via via :in in}]
:else
(apply concat
(map (fn [i form pred]
(let [v (x i)]
(when-not (valid? pred v)
(explain-1 form pred (conj path i) via (conj in i) v))))
(range (count preds)) forms preds))))
(gen* [_ overrides path rmap]
(if gfn
(gfn)
(let [gen (fn [i p f]
(gensub p overrides (conj path i) rmap f))
gs (map gen (range (count preds)) preds forms)]
(when (every? identity gs)
(apply gen/tuple gs)))))
(with-gen* [_ gfn] (tuple-impl forms preds gfn))
(describe* [_] `(tuple ~@forms)))))
(defn- tagged-ret [tag ret]
(clojure.lang.MapEntry. tag ret))
(defn ^:skip-wiki or-spec-impl
"Do not call this directly, use 'or'"
[keys forms preds gfn]
(let [id (System.Guid.)
kps (zipmap keys preds)
cform (fn [x]
(loop [i 0]
(if (< i (count preds))
(let [pred (preds i)]
(let [ret (dt pred x (nth forms i))]
(if (= ::invalid ret)
(recur (inc i))
(tagged-ret (keys i) ret))))
::invalid)))]
(reify
Spec
(conform* [_ x] (cform x))
(unform* [_ [k x]] (unform (kps k) x))
(explain* [this path via in x]
(when-not (valid? this x)
(apply concat
(map (fn [k form pred]
(when-not (valid? pred x)
(explain-1 form pred (conj path k) via in x)))
keys forms preds))))
(gen* [_ overrides path rmap]
(if gfn
(gfn)
(let [gen (fn [k p f]
(let [rmap (inck rmap id)]
(when-not (recur-limit? rmap id path k)
(gen/delay
(gensub p overrides (conj path k) rmap f)))))
gs (remove nil? (map gen keys preds forms))]
(when-not (empty? gs)
(gen/one-of gs)))))
(with-gen* [_ gfn] (or-spec-impl keys forms preds gfn))
(describe* [_] `(or ~@(mapcat vector keys forms))))))
(defn- and-preds [x preds forms]
(loop [ret x
[pred & preds] preds
[form & forms] forms]
(if pred
(let [nret (dt pred ret form)]
(if (= ::invalid nret)
::invalid
;;propagate conformed values
(recur nret preds forms)))
ret)))
(defn- explain-pred-list
[forms preds path via in x]
(loop [ret x
[form & forms] forms
[pred & preds] preds]
(when pred
(let [nret (dt pred ret form)]
(if (not= ::invalid nret)
(recur nret forms preds)
(explain-1 form pred path via in ret))))))
(defn ^:skip-wiki and-spec-impl
"Do not call this directly, use 'and'"
[forms preds gfn]
(reify
Spec
(conform* [_ x] (and-preds x preds forms))
(unform* [_ x] (reduce #(unform %2 %1) x (reverse preds)))
(explain* [_ path via in x] (explain-pred-list forms preds path via in x))
(gen* [_ overrides path rmap] (if gfn (gfn) (gensub (first preds) overrides path rmap (first forms))))
(with-gen* [_ gfn] (and-spec-impl forms preds gfn))
(describe* [_] `(and ~@forms))))
(defn ^:skip-wiki merge-spec-impl
"Do not call this directly, use 'merge'"
[forms preds gfn]
(reify
Spec
(conform* [_ x] (let [ms (map #(dt %1 x %2) preds forms)]
(if (some #{::invalid} ms)
::invalid
(apply c/merge ms))))
(unform* [_ x] (apply c/merge (map #(unform % x) (reverse preds))))
(explain* [_ path via in x]
(apply concat
(map #(explain-1 %1 %2 path via in x)
forms preds)))
(gen* [_ overrides path rmap]
(if gfn
(gfn)
(gen/fmap
#(apply c/merge %)
(apply gen/tuple (map #(gensub %1 overrides path rmap %2)
preds forms)))))
(with-gen* [_ gfn] (merge-spec-impl forms preds gfn))
(describe* [_] `(merge ~@forms))))
(defn- coll-prob [x kfn kform distinct count min-count max-count
path via in]
(let [pred (c/or kfn coll?)
kform (c/or kform `coll?)]
(cond
(not (valid? pred x))
(explain-1 kform pred path via in x)
(c/and distinct (not (empty? x)) (not (apply distinct? x)))
[{:path path :pred 'distinct? :val x :via via :in in}]
(c/and count (not= count (bounded-count count x)))
[{:path path :pred `(= ~count (c/count ~'%)) :val x :via via :in in}]
(c/and (c/or min-count max-count)
(not (<= (c/or min-count 0)
(bounded-count (if max-count (inc max-count) min-count) x)
(c/or max-count System.Int32/MaxValue))))
[{:path path :pred `(<= ~(c/or min-count 0) (c/count ~'%) ~(c/or max-count 'System.Int32/MaxValue)) :val x :via via :in in}])))
(defn ^:skip-wiki every-impl
"Do not call this directly, use 'every', 'every-kv', 'coll-of' or 'map-of'"
([form pred opts] (every-impl form pred opts nil))
([form pred {gen-into :into
:keys [kind ::kind-form count max-count min-count distinct gen-max ::kfn
conform-keys ::conform-all]
:or {gen-max 20}
:as opts}
gfn]
(let [conform-into gen-into
check? #(valid? pred %)
kfn (c/or kfn (fn [i v] i))
addcv (fn [ret i v cv] (conj ret cv))
cfns (fn [x]
;;returns a tuple of [init add complete] fns
(cond
(c/and (vector? x) (c/or (not conform-into) (vector? conform-into)))
[identity
(fn [ret i v cv]
(if (identical? v cv)
ret
(assoc ret i cv)))
identity]
(c/and (map? x) (c/or (c/and kind (not conform-into)) (map? conform-into)))
[(if conform-keys empty identity)
(fn [ret i v cv]
(if (c/and (identical? v cv) (not conform-keys))
ret
(assoc ret (nth (if conform-keys cv v) 0) (nth cv 1))))
identity]
(c/or (list? conform-into) (c/and (not conform-into) (list? x)))
[(constantly ()) addcv reverse]
:else [#(empty (c/or conform-into %)) addcv identity]))]
(reify
Spec
(conform* [_ x]
(cond
(coll-prob x kind kind-form distinct count min-count max-count
nil nil nil)
::invalid
conform-all
(let [[init add complete] (cfns x)]
(loop [ret (init x), i 0, [v & vs :as vseq] (seq x)]
(if vseq
(let [cv (dt pred v nil)]
(if (= ::invalid cv)
::invalid
(recur (add ret i v cv) (inc i) vs)))
(complete ret))))
:else
(if (indexed? x)
(let [step (max 1 (long (/ (c/count x) *coll-check-limit*)))]
(loop [i 0]
(if (>= i (c/count x))
x
(if (check? (nth x i))
(recur (c/+ i step))
::invalid))))
(c/or (c/and (every? check? (take *coll-check-limit* x)) x)
::invalid))))
(unform* [_ x] x)
(explain* [_ path via in x]
(c/or (coll-prob x kind kind-form distinct count min-count max-count
path via in)
(apply concat
((if conform-all identity (partial take *coll-error-limit*))
(keep identity
(map (fn [i v]
(let [k (kfn i v)]
(when-not (check? v)
(let [prob (explain-1 form pred path via (conj in k) v)]
prob))))
(range) x))))))
(gen* [_ overrides path rmap]
(if gfn
(gfn)
(let [pgen (gensub pred overrides path rmap form)]
(gen/bind
(cond
gen-into (gen/return (empty gen-into))
kind (gen/fmap #(if (empty? %) % (empty %))
(gensub kind overrides path rmap form))
:else (gen/return []))
(fn [init]
(gen/fmap
#(if (vector? init) % (into init %))
(cond
distinct
(if count
(gen/vector-distinct pgen {:num-elements count :max-tries 100})
(gen/vector-distinct pgen {:min-elements (c/or min-count 0)
:max-elements (c/or max-count (max gen-max (c/* 2 (c/or min-count 0))))
:max-tries 100}))
count
(gen/vector pgen count)
(c/or min-count max-count)
(gen/vector pgen (c/or min-count 0) (c/or max-count (max gen-max (c/* 2 (c/or min-count 0)))))
:else
(gen/vector pgen 0 gen-max))))))))
(with-gen* [_ gfn] (every-impl form pred opts gfn))
(describe* [_] `(every ~form ~@(mapcat identity opts)))))))
;;;;;;;;;;;;;;;;;;;;;;; regex ;;;;;;;;;;;;;;;;;;;
;;See:
;; http://matt.might.net/articles/implementation-of-regular-expression-matching-in-scheme-with-derivatives/
;; http://www.ccs.neu.edu/home/turon/re-deriv.pdf
;;ctors
(defn- accept [x] {::op ::accept :ret x})
(defn- accept? [{:keys [::op]}]
(= ::accept op))
(defn- pcat* [{[p1 & pr :as ps] :ps, [k1 & kr :as ks] :ks, [f1 & fr :as forms] :forms, ret :ret, rep+ :rep+}]
(when (every? identity ps)
(if (accept? p1)
(let [rp (:ret p1)
ret (conj ret (if ks {k1 rp} rp))]
(if pr
(pcat* {:ps pr :ks kr :forms fr :ret ret})
(accept ret)))
{::op ::pcat, :ps ps, :ret ret, :ks ks, :forms forms :rep+ rep+})))
(defn- pcat [& ps] (pcat* {:ps ps :ret []}))
(defn ^:skip-wiki cat-impl
"Do not call this directly, use 'cat'"
[ks ps forms]
(pcat* {:ks ks, :ps ps, :forms forms, :ret {}}))
(defn- rep* [p1 p2 ret splice form]
(when p1
(let [r {::op ::rep, :p2 p2, :splice splice, :forms form :id (System.Guid.)}]
(if (accept? p1)
(assoc r :p1 p2 :ret (conj ret (:ret p1)))
(assoc r :p1 p1, :ret ret)))))
(defn ^:skip-wiki rep-impl
"Do not call this directly, use '*'"
[form p] (rep* p p [] false form))
(defn ^:skip-wiki rep+impl
"Do not call this directly, use '+'"
[form p]
(pcat* {:ps [p (rep* p p [] true form)] :forms `[~form (* ~form)] :ret [] :rep+ form}))
(defn ^:skip-wiki amp-impl
"Do not call this directly, use '&'"
[re preds pred-forms]
{::op ::amp :p1 re :ps preds :forms pred-forms})
(defn- filter-alt [ps ks forms f]
(if (c/or ks forms)
(let [pks (->> (map vector ps
(c/or (seq ks) (repeat nil))
(c/or (seq forms) (repeat nil)))
(filter #(-> % first f)))]
[(seq (map first pks)) (when ks (seq (map second pks))) (when forms (seq (map #(nth % 2) pks)))])
[(seq (filter f ps)) ks forms]))
(defn- alt* [ps ks forms]
(let [[[p1 & pr :as ps] [k1 :as ks] forms] (filter-alt ps ks forms identity)]
(when ps
(let [ret {::op ::alt, :ps ps, :ks ks :forms forms}]
(if (nil? pr)
(if k1
(if (accept? p1)
(accept (tagged-ret k1 (:ret p1)))
ret)
p1)
ret)))))
(defn- alts [& ps] (alt* ps nil nil))
(defn- alt2 [p1 p2] (if (c/and p1 p2) (alts p1 p2) (c/or p1 p2)))
(defn ^:skip-wiki alt-impl
"Do not call this directly, use 'alt'"
[ks ps forms] (assoc (alt* ps ks forms) :id (System.Guid.)))
(defn ^:skip-wiki maybe-impl
"Do not call this directly, use '?'"
[p form] (assoc (alt* [p (accept ::nil)] nil [form ::nil]) :maybe form))
(defn- noret? [p1 pret]
(c/or (= pret ::nil)
(c/and (#{::rep ::pcat} (::op (reg-resolve! p1))) ;;hrm, shouldn't know these
(empty? pret))
nil))
(declare preturn)
(defn- accept-nil? [p]
(let [{:keys [::op ps p1 p2 forms] :as p} (reg-resolve! p)]
(case op
::accept true
nil nil
::amp (c/and (accept-nil? p1)
(c/or (noret? p1 (preturn p1))
(let [ret (-> (preturn p1) (and-preds ps (next forms)))]
(not= ret ::invalid))))
::rep (c/or (identical? p1 p2) (accept-nil? p1))
::pcat (every? accept-nil? ps)
::alt (c/some accept-nil? ps))))
(declare add-ret)
(defn- preturn [p]
(let [{[p0 & pr :as ps] :ps, [k :as ks] :ks, :keys [::op p1 ret forms] :as p} (reg-resolve! p)]
(case op
::accept ret
nil nil
::amp (let [pret (preturn p1)]
(if (noret? p1 pret)
::nil
(and-preds pret ps forms)))
::rep (add-ret p1 ret k)
::pcat (add-ret p0 ret k)
::alt (let [[[p0] [k0]] (filter-alt ps ks forms accept-nil?)
r (if (nil? p0) ::nil (preturn p0))]
(if k0 (tagged-ret k0 r) r)))))
(defn- op-unform [p x]
;;(prn {:p p :x x})
(let [{[p0 & pr :as ps] :ps, [k :as ks] :ks, :keys [::op p1 ret forms rep+ maybe] :as p} (reg-resolve! p)
kps (zipmap ks ps)]
(case op
::accept [ret]
nil [(unform p x)]
::amp (let [px (reduce #(unform %2 %1) x (reverse ps))]
(op-unform p1 px))
::rep (mapcat #(op-unform p1 %) x)
::pcat (if rep+
(mapcat #(op-unform p0 %) x)
(mapcat (fn [k]
(when (contains? x k)
(op-unform (kps k) (get x k))))
ks))
::alt (if maybe
[(unform p0 x)]
(let [[k v] x]
(op-unform (kps k) v))))))
(defn- add-ret [p r k]
(let [{:keys [::op ps splice] :as p} (reg-resolve! p)
prop #(let [ret (preturn p)]
(if (empty? ret) r ((if splice into conj) r (if k {k ret} ret))))]
(case op
nil r
(::alt ::accept ::amp)
(let [ret (preturn p)]
;;(prn {:ret ret})
(if (= ret ::nil) r (conj r (if k {k ret} ret))))
(::rep ::pcat) (prop))))
(defn- deriv
[p x]
(let [{[p0 & pr :as ps] :ps, [k0 & kr :as ks] :ks, :keys [::op p1 p2 ret splice forms] :as p} (reg-resolve! p)]
(when p
(case op
::accept nil
nil (let [ret (dt p x p)]
(when-not (= ::invalid ret) (accept ret)))
::amp (when-let [p1 (deriv p1 x)]
(if (= ::accept (::op p1))
(let [ret (-> (preturn p1) (and-preds ps (next forms)))]
(when-not (= ret ::invalid)
(accept ret)))
(amp-impl p1 ps forms)))
::pcat (alt2 (pcat* {:ps (cons (deriv p0 x) pr), :ks ks, :forms forms, :ret ret})
(when (accept-nil? p0) (deriv (pcat* {:ps pr, :ks kr, :forms (next forms), :ret (add-ret p0 ret k0)}) x)))
::alt (alt* (map #(deriv % x) ps) ks forms)
::rep (alt2 (rep* (deriv p1 x) p2 ret splice forms)
(when (accept-nil? p1) (deriv (rep* p2 p2 (add-ret p1 ret nil) splice forms) x)))))))
(defn- op-describe [p]
(let [{:keys [::op ps ks forms splice p1 rep+ maybe] :as p} (reg-resolve! p)]
;;(prn {:op op :ks ks :forms forms :p p})
(when p
(case op
::accept nil
nil p
::amp (list* 'clojure.spec/& (op-describe p1) forms)
::pcat (if rep+
(list `+ rep+)
(cons `cat (mapcat vector (c/or (seq ks) (repeat :_)) forms)))
::alt (if maybe
(list `? maybe)
(cons `alt (mapcat vector ks forms)))
::rep (list (if splice `+ `*) forms)))))
(defn- op-explain [form p path via in input]
;;(prn {:form form :p p :path path :input input})
(let [[x :as input] input
{:keys [::op ps ks forms splice p1 p2] :as p} (reg-resolve! p)
via (if-let [name (spec-name p)] (conj via name) via)
insufficient (fn [path form]
[{:path path
:reason "Insufficient input"
:pred (abbrev form)
:val ()
:via via
:in in}])]
(when p
(case op
::accept nil
nil (if (empty? input)
(insufficient path form)
(explain-1 form p path via in x))
::amp (if (empty? input)
(if (accept-nil? p1)
(explain-pred-list forms ps path via in (preturn p1))
(insufficient path (op-describe p1)))
(if-let [p1 (deriv p1 x)]
(explain-pred-list forms ps path via in (preturn p1))
(op-explain (op-describe p1) p1 path via in input)))
::pcat (let [pkfs (map vector
ps
(c/or (seq ks) (repeat nil))
(c/or (seq forms) (repeat nil)))
[pred k form] (if (= 1 (count pkfs))
(first pkfs)
(first (remove (fn [[p]] (accept-nil? p)) pkfs)))
path (if k (conj path k) path)
form (c/or form (op-describe pred))]
(if (c/and (empty? input) (not pred))
(insufficient path form)
(op-explain form pred path via in input)))
::alt (if (empty? input)
(insufficient path (op-describe p))
(apply concat
(map (fn [k form pred]
(op-explain (c/or form (op-describe pred))
pred
(if k (conj path k) path)
via
in
input))
(c/or (seq ks) (repeat nil))
(c/or (seq forms) (repeat nil))
ps)))
::rep (op-explain (if (identical? p1 p2)
forms
(op-describe p1))
p1 path via in input)))))
(defn- re-gen [p overrides path rmap f]
;;(prn {:op op :ks ks :forms forms})
(let [{:keys [::op ps ks p1 p2 forms splice ret id ::gfn] :as p} (reg-resolve! p)
rmap (if id (inck rmap id) rmap)
ggens (fn [ps ks forms]
(let [gen (fn [p k f]
;;(prn {:k k :path path :rmap rmap :op op :id id})
(when-not (c/and rmap id k (recur-limit? rmap id path k))
(if id
(gen/delay (re-gen p overrides (if k (conj path k) path) rmap (c/or f p)))
(re-gen p overrides (if k (conj path k) path) rmap (c/or f p)))))]
(map gen ps (c/or (seq ks) (repeat nil)) (c/or (seq forms) (repeat nil)))))]
(c/or (when-let [g (get overrides path)]
(case op
(:accept nil) (gen/fmap vector g)
g))
(when gfn
(gfn))
(when p
(case op
::accept (if (= ret ::nil)
(gen/return [])
(gen/return [ret]))
nil (when-let [g (gensub p overrides path rmap f)]
(gen/fmap vector g))
::amp (re-gen p1 overrides path rmap (op-describe p1))
::pcat (let [gens (ggens ps ks forms)]
(when (every? identity gens)
(apply gen/cat gens)))
::alt (let [gens (remove nil? (ggens ps ks forms))]
(when-not (empty? gens)
(gen/one-of gens)))
::rep (if (recur-limit? rmap id [id] id)
(gen/return [])
(when-let [g (re-gen p2 overrides path rmap forms)]
(gen/fmap #(apply concat %)
(gen/vector g)))))))))
(defn- re-conform [p [x & xs :as data]]
;;(prn {:p p :x x :xs xs})
(if (empty? data)
(if (accept-nil? p)
(let [ret (preturn p)]
(if (= ret ::nil)
nil
ret))
::invalid)
(if-let [dp (deriv p x)]
(recur dp xs)
::invalid)))
(defn- re-explain [path via in re input]
(loop [p re [x & xs :as data] input i 0]
;;(prn {:p p :x x :xs xs :re re}) (prn)
(if (empty? data)
(if (accept-nil? p)
nil ;;success
(op-explain (op-describe p) p path via in nil))
(if-let [dp (deriv p x)]
(recur dp xs (inc i))
(if (accept? p)
(if (= (::op p) ::pcat)
(op-explain (op-describe p) p path via (conj in i) (seq data))
[{:path path
:reason "Extra input"
:pred (abbrev (op-describe re))
:val data
:via via
:in (conj in i)}])
(c/or (op-explain (op-describe p) p path via (conj in i) (seq data))
[{:path path
:reason "Extra input"
:pred (abbrev (op-describe p))
:val data
:via via
:in (conj in i)}]))))))
(defn ^:skip-wiki regex-spec-impl
"Do not call this directly, use 'spec' with a regex op argument"
[re gfn]
(reify
Spec
(conform* [_ x]
(if (c/or (nil? x) (coll? x))
(re-conform re (seq x))
::invalid))
(unform* [_ x] (op-unform re x))
(explain* [_ path via in x]
(if (c/or (nil? x) (coll? x))
(re-explain path via in re (seq x))
[{:path path :pred (abbrev (op-describe re)) :val x :via via :in in}]))
(gen* [_ overrides path rmap]
(if gfn
(gfn)
(re-gen re overrides path rmap (op-describe re))))
(with-gen* [_ gfn] (regex-spec-impl re gfn))
(describe* [_] (op-describe re))))
;;;;;;;;;;;;;;;;; HOFs ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- call-valid?
[f specs args]
(let [cargs (conform (:args specs) args)]
(when-not (= cargs ::invalid)
(let [ret (apply f args)
cret (conform (:ret specs) ret)]
(c/and (not= cret ::invalid)
(if (:fn specs)
(valid? (:fn specs) {:args cargs :ret cret})
true))))))
(defn- validate-fn
"returns f if valid, else smallest"
[f specs iters]
(let [g (gen (:args specs))
prop (gen/for-all* [g] #(call-valid? f specs %))]
(let [ret (gen/quick-check iters prop)]
(if-let [[smallest] (-> ret :shrunk :smallest)]
smallest
f))))
(defn ^:skip-wiki fspec-impl
"Do not call this directly, use 'fspec'"
[argspec aform retspec rform fnspec fform gfn]
(let [specs {:args argspec :ret retspec :fn fnspec}]
(reify
clojure.lang.ILookup
(valAt [this k] (get specs k))
(valAt [_ k not-found] (get specs k not-found))
Spec
(conform* [_ f] (if (ifn? f)
(if (identical? f (validate-fn f specs *fspec-iterations*)) f ::invalid)
::invalid))
(unform* [_ f] f)
(explain* [_ path via in f]
(if (ifn? f)
(let [args (validate-fn f specs 100)]
(if (identical? f args) ;;hrm, we might not be able to reproduce
nil
(let [ret (try (apply f args) (catch Exception ;;Throwable
t t))]
(if (instance? Exception ;;Throwable
ret)
;;TODO add exception data
{path {:pred '(apply fn) :val args :reason (.getMessage ^Exception ;;^Throwable
ret) :via via :in in}}
(let [cret (dt retspec ret rform)]
(if (= ::invalid cret)
(explain-1 rform retspec (conj path :ret) via in ret)
(when fnspec
(let [cargs (conform argspec args)]
(explain-1 fform fnspec (conj path :fn) via in {:args cargs :ret cret})))))))))
[{:path path :pred 'ifn? :val f :via via :in in}]))
(gen* [_ overrides _ _] (if gfn
(gfn)
(gen/return
(fn [& args]
(c/assert (valid? argspec args) (with-out-str (explain argspec args)))
(gen/generate (gen retspec overrides))))))
(with-gen* [_ gfn] (fspec-impl argspec aform retspec rform fnspec fform gfn))
(describe* [_] `(fspec :args ~aform :ret ~rform :fn ~fform)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; non-primitives ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(clojure.spec/def ::kvs->map (conformer #(zipmap (map ::k %) (map ::v %)) #(map (fn [[k v]] {::k k ::v v}) %)))
(defmacro keys*
"takes the same arguments as spec/keys and returns a regex op that matches sequences of key/values,
converts them into a map, and conforms that map with a corresponding
spec/keys call:
user=> (s/conform (s/keys :req-un [::a ::c]) {:a 1 :c 2})
{:a 1, :c 2}
user=> (s/conform (s/keys* :req-un [::a ::c]) [:a 1 :c 2])
{:a 1, :c 2}
the resulting regex op can be composed into a larger regex:
user=> (s/conform (s/cat :i1 integer? :m (s/keys* :req-un [::a ::c]) :i2 integer?) [42 :a 1 :c 2 :d 4 99])
{:i1 42, :m {:a 1, :c 2, :d 4}, :i2 99}"
[& kspecs]
`(let [mspec# (keys ~@kspecs)]
(with-gen (clojure.spec/& (* (cat ::k keyword? ::v any?)) ::kvs->map mspec#)
(fn [] (gen/fmap (fn [m#] (apply concat m#)) (gen mspec#))))))
(defmacro nilable
"returns a spec that accepts nil and values satisfiying pred"
[pred]
`(and (or ::nil nil? ::pred ~pred) (conformer second #(if (nil? %) [::nil nil] [::pred %]))))
(defn exercise
"generates a number (default 10) of values compatible with spec and maps conform over them,
returning a sequence of [val conformed-val] tuples. Optionally takes
a generator overrides map as per gen"
([spec] (exercise spec 10))
([spec n] (exercise spec n nil))
([spec n overrides]
(map #(vector % (conform spec %)) (gen/sample (gen spec overrides) n))))
(defn exercise-fn
"exercises the fn named by sym (a symbol) by applying it to
n (default 10) generated samples of its args spec. When fspec is
supplied its arg spec is used, and sym-or-f can be a fn. Returns a
sequence of tuples of [args ret]. "
([sym] (exercise-fn sym 10))
([sym n] (exercise-fn sym n (get-spec sym)))
([sym-or-f n fspec]
(let [f (if (symbol? sym-or-f) (resolve sym-or-f) sym-or-f)]
(for [args (gen/sample (gen (:args fspec)) n)]
[args (apply f args)]))))
(defn inst-in-range?
"Return true if inst at or after start and before end"
[start end inst]
(c/and (inst? inst)
(let [t (inst-ms inst)]
(c/and (<= (inst-ms start) t) (< t (inst-ms end))))))
(defmacro inst-in
"Returns a spec that validates insts in the range from start
(inclusive) to end (exclusive)."
[start end]
`(let [st# (inst-ms ~start)
et# (inst-ms ~end)
mkdate# (fn [d#] (java.util.Date. ^{:tag ~'long} d#))]
(spec (and inst? #(inst-in-range? ~start ~end %))
:gen (fn []
(gen/fmap mkdate#
(gen/large-integer* {:min st# :max et#}))))))
(defn int-in-range?
"Return true if start <= val and val < end"
[start end val]
(c/and int? (<= start val) (< val end)))
(defmacro int-in
"Returns a spec that validates ints in the range from start
(inclusive) to end (exclusive)."
[start end]
`(spec (and int? #(int-in-range? ~start ~end %))
:gen #(gen/large-integer* {:min ~start :max (dec ~end)})))
(defmacro double-in
"Specs a 64-bit floating point number. Options:
:infinite? - whether +/- infinity allowed (default true)
:NaN? - whether NaN allowed (default true)
:min - minimum value (inclusive, default none)
:max - maximum value (inclusive, default none)"
[& {:keys [infinite? NaN? min max]
:or {infinite? true NaN? true}
:as m}]
`(spec (and c/double?
~@(when-not infinite? '[#(not (Double/isInfinite %))])
~@(when-not NaN? '[#(not (Double/isNaN %))])
~@(when max `[#(<= % ~max)])
~@(when min `[#(<= ~min %)]))
:gen #(gen/double* ~m)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; assert ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defonce
^{:dynamic true
:doc "If true, compiler will enable spec asserts, which are then
subject to runtime control via check-asserts? If false, compiler
will eliminate all spec assert overhead. See 'assert'.
Initially set to boolean value of clojure.spec.compile-asserts
system property. Defaults to true."}
*compile-asserts*
(not= "false"
(System.Environment/GetEnvironmentVariable "CLOJURE_SPEC_COMPILE_ASSERTS")
;; (System/getProperty "clojure.spec.compile-asserts")
))
(def ^:private check-spec-asserts-ref
;; janky hack in absence of easier way to modify RT
(atom
;; ;; I guess? see https://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html
;; ;; Without some more work won't "default to true", though
;; (= "true"
;; (System.Environment/GetEnvironmentVariable "CLOJURE_SPEC_COMPILE_ASSERTS"))
true ;; fify
))
(defn check-asserts?
"Returns the value set by check-asserts."
[]
@check-spec-asserts-ref
;;clojure.lang.RT/checkSpecAsserts
)
(defn check-asserts
"Enable or disable spec asserts that have been compiled
with '*compile-asserts*' true. See 'assert'.
Initially set to boolean value of clojure.spec.check-asserts
system property. Defaults to false."
[flag]
(reset! check-spec-asserts-ref flag)
;;(set! (. clojure.lang.RT checkSpecAsserts) flag)
)
(defn assert*
"Do not call this directly, use 'assert'."
[spec x]
(if (valid? spec x)
x
(let [ed (c/merge (assoc (explain-data* spec [] [] [] x)
::failure :assertion-failed))]
(throw (ex-info
(str "Spec assertion failed\n" (with-out-str (explain-out ed)))
ed)))))
(defmacro assert
"spec-checking assert expression. Returns x if x is valid? according
to spec, else throws an ex-info with explain-data plus ::failure of
:assertion-failed.
Can be disabled at either compile time or runtime:
If *compile-asserts* is false at compile time, compiles to x. Defaults
to value of 'clojure.spec.compile-asserts' system property, or true if
not set.
If (check-asserts?) is false at runtime, always returns x. Defaults to
value of 'clojure.spec.check-asserts' system property, or false if not
set. You can toggle check-asserts? with (check-asserts bool)."
[spec x]
(if *compile-asserts*
`(if clojure.lang.RT/checkSpecAsserts
(assert* ~spec ~x)
~x)
x))
| 62972 | ; 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.spec
(:refer-clojure :exclude [+ * and assert or cat def keys merge])
(:require [clojure.walk :as walk]
[clojure.spec.gen :as gen]
[clojure.string :as str]))
(alias 'c 'clojure.core)
(set! *warn-on-reflection* true)
(def ^:dynamic *recursion-limit*
"A soft limit on how many times a branching spec (or/alt/*/opt-keys/multi-spec)
can be recursed through during generation. After this a
non-recursive branch will be chosen."
4)
(def ^:dynamic *fspec-iterations*
"The number of times an anonymous fn specified by fspec will be (generatively) tested during conform"
21)
(def ^:dynamic *coll-check-limit*
"The number of elements validated in a collection spec'ed with 'every'"
101)
(def ^:dynamic *coll-error-limit*
"The number of errors reported by explain in a collection spec'ed with 'every'"
20)
(defprotocol Spec
(conform* [spec x])
(unform* [spec y])
(explain* [spec path via in x])
(gen* [spec overrides path rmap])
(with-gen* [spec gfn])
(describe* [spec]))
(defonce ^:private registry-ref (atom {}))
(defn- named? [x] (instance? clojure.lang.Named x))
(defn- with-name [spec name]
(with-meta spec (assoc (meta spec) ::name name)))
(defn- spec-name [spec]
(cond
(keyword? spec) spec
(instance? clojure.lang.IObj spec)
(-> (meta spec) ::name)))
(defn- reg-resolve
"returns the spec/regex at end of alias chain starting with k, nil if not found, k if k not Named"
[k]
(if (named? k)
(let [reg @registry-ref]
(loop [spec k]
(if (named? spec)
(recur (get reg spec))
(when spec
(with-name spec k)))))
k))
(defn- reg-resolve!
"returns the spec/regex at end of alias chain starting with k, throws if not found, k if k not ident"
[k]
(if (ident? k)
(c/or (reg-resolve k)
(throw (Exception. (str "Unable to resolve spec: " k))))
k))
(defn spec?
"returns x if x is a spec object, else logical false"
[x]
(c/and (extends? Spec (class x)) x))
(defn regex?
"returns x if x is a (clojure.spec) regex op, else logical false"
[x]
(c/and (::op x) x))
(declare spec-impl)
(declare regex-spec-impl)
(defn- maybe-spec
"spec-or-k must be a spec, regex or resolvable kw/sym, else returns nil."
[spec-or-k]
(let [s (c/or (spec? spec-or-k)
(regex? spec-or-k)
(c/and (named? spec-or-k) (reg-resolve spec-or-k))
nil)]
(if (regex? s)
(with-name (regex-spec-impl s nil) (spec-name s))
s)))
(defn- the-spec
"spec-or-k must be a spec, regex or kw/sym, else returns nil. Throws if unresolvable kw/sym"
[spec-or-k]
(c/or (maybe-spec spec-or-k)
(when (named? spec-or-k)
(throw (Exception. (str "Unable to resolve spec: " spec-or-k))))))
(defn- specize [s]
(c/or (the-spec s) (spec-impl ::unknown s nil nil)))
(defn conform
"Given a spec and a value, returns :clojure.spec/invalid if value does not match spec,
else the (possibly destructured) value."
[spec x]
(conform* (specize spec) x))
(defn unform
"Given a spec and a value created by or compliant with a call to
'conform' with the same spec, returns a value with all conform
destructuring undone."
[spec x]
(unform* (specize spec) x))
(defn form
"returns the spec as data"
[spec]
;;TODO - incorporate gens
(describe* (specize spec)))
(defn abbrev [form]
(cond
(seq? form)
(walk/postwalk (fn [form]
(cond
(c/and (symbol? form) (namespace form))
(-> form name symbol)
(c/and (seq? form) (= 'fn (first form)) (= '[%] (second form)))
(last form)
:else form))
form)
(c/and (symbol? form) (namespace form))
(-> form name symbol)
:else form))
(defn describe
"returns an abbreviated description of the spec as data"
[spec]
(abbrev (form spec)))
(defn with-gen
"Takes a spec and a no-arg, generator-returning fn and returns a version of that spec that uses that generator"
[spec gen-fn]
(let [spec (reg-resolve spec)]
(if (regex? spec)
(assoc spec ::gfn gen-fn)
(with-gen* (specize spec) gen-fn))))
(defn explain-data* [spec path via in x]
(let [probs (explain* (specize spec) path via in x)]
(when-not (empty? probs)
{::problems probs})))
(defn explain-data
"Given a spec and a value x which ought to conform, returns nil if x
conforms, else a map with at least the key ::problems whose value is
a collection of problem-maps, where problem-map has at least :path :pred and :val
keys describing the predicate and the value that failed at that
path."
[spec x]
(explain-data* spec [] (if-let [name (spec-name spec)] [name] []) [] x))
(defn explain-out
"prints explanation data (per 'explain-data') to *out*."
[ed]
(if ed
(do
;;(prn {:ed ed})
(doseq [{:keys [path pred val reason via in] :as prob} (::problems ed)]
(when-not (empty? in)
(print "In:" (pr-str in) ""))
(print "val: ")
(pr val)
(print " fails")
(when-not (empty? via)
(print " spec:" (pr-str (last via))))
(when-not (empty? path)
(print " at:" (pr-str path)))
(print " predicate: ")
(pr (abbrev pred))
(when reason (print ", " reason))
(doseq [[k v] prob]
(when-not (#{:path :pred :val :reason :via :in} k)
(print "\n\t" (pr-str k) " ")
(pr v)))
(newline))
(doseq [[k v] ed]
(when-not (#{::problems} k)
(print (pr-str k) " ")
(pr v)
(newline))))
(println "Success!")))
(defn explain
"Given a spec and a value that fails to conform, prints an explanation to *out*."
[spec x]
(explain-out (explain-data spec x)))
(defn explain-str
"Given a spec and a value that fails to conform, returns an explanation as a string."
[spec x]
(with-out-str (explain spec x)))
(declare valid?)
(defn- gensub
[spec overrides path rmap form]
;;(prn {:spec spec :over overrides :path path :form form})
(let [spec (specize spec)]
(if-let [g (c/or (when-let [gfn (c/or (get overrides (c/or (spec-name spec) spec))
(get overrides path))]
(gfn))
(gen* spec overrides path rmap))]
(gen/such-that #(valid? spec %) g 100)
(let [abbr (abbrev form)]
(throw (ex-info (str "Unable to construct gen at: " path " for: " abbr)
{::path path ::form form ::failure :no-gen}))))))
(defn gen
"Given a spec, returns the generator for it, or throws if none can
be constructed. Optionally an overrides map can be provided which
should map spec names or paths (vectors of keywords) to no-arg
generator-creating fns. These will be used instead of the generators at those
names/paths. Note that parent generator (in the spec or overrides
map) will supersede those of any subtrees. A generator for a regex
op must always return a sequential collection (i.e. a generator for
s/? should return either an empty sequence/vector or a
sequence/vector with one item in it)"
([spec] (gen spec nil))
([spec overrides] (gensub spec overrides [] {::recursion-limit *recursion-limit*} spec)))
(defn- ->sym
"Returns a symbol from a symbol or var"
[x]
(if (var? x)
(let [^clojure.lang.Var v x]
(symbol (str (.Name (.ns v)))
(str (.sym v))))
x))
(defn- unfn [expr]
(if (c/and (seq? expr)
(symbol? (first expr))
(= "fn*" (name (first expr))))
(let [[[s] & form] (rest expr)]
(conj (walk/postwalk-replace {s '%} form) '[%] 'fn))
expr))
(defn- res [form]
(cond
(keyword? form) form
(symbol? form) (c/or (-> form resolve ->sym) form)
(sequential? form) (walk/postwalk #(if (symbol? %) (res %) %) (unfn form))
:else form))
(defn ^:skip-wiki def-impl
"Do not call this directly, use 'def'"
[k form spec]
(c/assert (c/and (named? k) (namespace k)) "k must be namespaced keyword or resolvable symbol")
(let [spec (if (c/or (spec? spec) (regex? spec) (get @registry-ref spec))
spec
(spec-impl form spec nil nil))]
(swap! registry-ref assoc k spec)
k))
(defn- ns-qualify
"Qualify symbol s by resolving it or using the current *ns*."
[s]
(if-let [ns-sym (some-> s namespace symbol)]
(c/or (some-> (get (ns-aliases *ns*) ns-sym) str (symbol (name s)))
s)
(symbol (str (.Name *ns*)) (str s))))
(defmacro def
"Given a namespace-qualified keyword or resolvable symbol k, and a
spec, spec-name, predicate or regex-op makes an entry in the
registry mapping k to the spec"
[k spec-form]
(let [k (if (symbol? k) (ns-qualify k) k)]
`(def-impl '~k '~(res spec-form) ~spec-form)))
(defn registry
"returns the registry map, prefer 'get-spec' to lookup a spec by name"
[]
@registry-ref)
(defn get-spec
"Returns spec registered for keyword/symbol/var k, or nil."
[k]
(get (registry) (if (keyword? k) k (->sym k))))
(declare map-spec)
(defmacro spec
"Takes a single predicate form, e.g. can be the name of a predicate,
like even?, or a fn literal like #(< % 42). Note that it is not
generally necessary to wrap predicates in spec when using the rest
of the spec macros, only to attach a unique generator
Can also be passed the result of one of the regex ops -
cat, alt, *, +, ?, in which case it will return a regex-conforming
spec, useful when nesting an independent regex.
---
Optionally takes :gen generator-fn, which must be a fn of no args that
returns a test.check generator.
Returns a spec."
[form & {:keys [gen]}]
(when form
`(spec-impl '~(res form) ~form ~gen nil)))
(defmacro multi-spec
"Takes the name of a spec/predicate-returning multimethod and a
tag-restoring keyword or fn (retag). Returns a spec that when
conforming or explaining data will pass it to the multimethod to get
an appropriate spec. You can e.g. use multi-spec to dynamically and
extensibly associate specs with 'tagged' data (i.e. data where one
of the fields indicates the shape of the rest of the structure).
(defmulti mspec :tag)
The methods should ignore their argument and return a predicate/spec:
(defmethod mspec :int [_] (s/keys :req-un [::tag ::i]))
retag is used during generation to retag generated values with
matching tags. retag can either be a keyword, at which key the
dispatch-tag will be assoc'ed, or a fn of generated value and
dispatch-tag that should return an appropriately retagged value.
Note that because the tags themselves comprise an open set,
the tag key spec cannot enumerate the values, but can e.g.
test for keyword?.
Note also that the dispatch values of the multimethod will be
included in the path, i.e. in reporting and gen overrides, even
though those values are not evident in the spec.
"
[mm retag]
`(multi-spec-impl '~(res mm) (var ~mm) ~retag))
(defmacro keys
"Creates and returns a map validating spec. :req and :opt are both
vectors of namespaced-qualified keywords. The validator will ensure
the :req keys are present. The :opt keys serve as documentation and
may be used by the generator.
The :req key vector supports 'and' and 'or' for key groups:
(s/keys :req [::x ::y (or ::secret (and ::user ::pwd))] :opt [::z])
There are also -un versions of :req and :opt. These allow
you to connect unqualified keys to specs. In each case, fully
qualfied keywords are passed, which name the specs, but unqualified
keys (with the same name component) are expected and checked at
conform-time, and generated during gen:
(s/keys :req-un [:my.ns/x :my.ns/y])
The above says keys :x and :y are required, and will be validated
and generated by specs (if they exist) named :my.ns/x :my.ns/y
respectively.
In addition, the values of *all* namespace-qualified keys will be validated
(and possibly destructured) by any registered specs. Note: there is
no support for inline value specification, by design.
Optionally takes :gen generator-fn, which must be a fn of no args that
returns a test.check generator."
[& {:keys [req req-un opt opt-un gen]}]
(let [unk #(-> % name keyword)
req-keys (filterv keyword? (flatten req))
req-un-specs (filterv keyword? (flatten req-un))
_ (c/assert (every? #(c/and (keyword? %) (namespace %)) (concat req-keys req-un-specs opt opt-un))
"all keys must be namespace-qualified keywords")
req-specs (into req-keys req-un-specs)
req-keys (into req-keys (map unk req-un-specs))
opt-keys (into (vec opt) (map unk opt-un))
opt-specs (into (vec opt) opt-un)
parse-req (fn [rk f]
(map (fn [x]
(if (keyword? x)
`#(contains? % ~(f x))
(let [gx (gensym)]
`(fn* [~gx]
~(walk/postwalk
(fn [y] (if (keyword? y) `(contains? ~gx ~(f y)) y))
x)))))
rk))
pred-exprs [`map?]
pred-exprs (into pred-exprs (parse-req req identity))
pred-exprs (into pred-exprs (parse-req req-un unk))
pred-forms (walk/postwalk res pred-exprs)]
;; `(map-spec-impl ~req-keys '~req ~opt '~pred-forms ~pred-exprs ~gen)
`(map-spec-impl {:req '~req :opt '~opt :req-un '~req-un :opt-un '~opt-un
:req-keys '~req-keys :req-specs '~req-specs
:opt-keys '~opt-keys :opt-specs '~opt-specs
:pred-forms '~pred-forms
:pred-exprs ~pred-exprs
:gfn ~gen})))
(defmacro or
"Takes key+pred pairs, e.g.
(s/or :even even? :small #(< % 42))
Returns a destructuring spec that returns a map entry containing the
key of the first matching pred and the corresponding value. Thus the
'key' and 'val' functions can be used to refer generically to the
components of the tagged return."
[& key-pred-forms]
(let [pairs (partition 2 key-pred-forms)
keys (mapv first pairs)
pred-forms (mapv second pairs)
pf (mapv res pred-forms)]
(c/assert (c/and (even? (count key-pred-forms)) (every? keyword? keys)) "spec/or expects k1 p1 k2 p2..., where ks are keywords")
`(or-spec-impl ~keys '~pf ~pred-forms nil)))
(defmacro and
"Takes predicate/spec-forms, e.g.
(s/and even? #(< % 42))
Returns a spec that returns the conformed value. Successive
conformed values propagate through rest of predicates."
[& pred-forms]
`(and-spec-impl '~(mapv res pred-forms) ~(vec pred-forms) nil))
(defmacro merge
"Takes map-validating specs (e.g. 'keys' specs) and
returns a spec that returns a conformed map satisfying all of the
specs. Successive conformed values propagate through rest of
predicates. Unlike 'and', merge can generate maps satisfying the
union of the predicates."
[& pred-forms]
`(merge-spec-impl '~(mapv res pred-forms) ~(vec pred-forms) nil))
(defmacro every
"takes a pred and validates collection elements against that pred.
Note that 'every' does not do exhaustive checking, rather it samples
*coll-check-limit* elements. Nor (as a result) does it do any
conforming of elements. 'explain' will report at most *coll-error-limit*
problems. Thus 'every' should be suitable for potentially large
collections.
Takes several kwargs options that further constrain the collection:
:kind - a pred/spec that the collection type must satisfy, e.g. vector?
(default nil) Note that if :kind is specified and :into is
not, this pred must generate in order for every to generate.
:count - specifies coll has exactly this count (default nil)
:min-count, :max-count - coll has count (<= min-count count max-count) (defaults nil)
:distinct - all the elements are distinct (default nil)
And additional args that control gen
:gen-max - the maximum coll size to generate (default 20)
:into - one of [], (), {}, #{} - the default collection to generate into
(default: empty coll as generated by :kind pred if supplied, else [])
Optionally takes :gen generator-fn, which must be a fn of no args that
returns a test.check generator
See also - coll-of, every-kv
"
[pred & {:keys [into kind count max-count min-count distinct gen-max gen] :as opts}]
(let [nopts (-> opts (dissoc :gen) (assoc ::kind-form `'~(res (:kind opts))))]
`(every-impl '~pred ~pred ~nopts ~gen)))
(defmacro every-kv
"like 'every' but takes separate key and val preds and works on associative collections.
Same options as 'every', :into defaults to {}
See also - map-of"
[kpred vpred & opts]
`(every (tuple ~kpred ~vpred) ::kfn (fn [i# v#] (nth v# 0)) :into {} ~@opts))
(defmacro coll-of
"Returns a spec for a collection of items satisfying pred. Unlike
'every', coll-of will exhaustively conform every value.
Same options as 'every'. conform will produce a collection
corresponding to :into if supplied, else will match the input collection,
avoiding rebuilding when possible.
See also - every, map-of"
[pred & opts]
`(every ~pred ::conform-all true ~@opts))
(defmacro map-of
"Returns a spec for a map whose keys satisfy kpred and vals satisfy
vpred. Unlike 'every-kv', map-of will exhaustively conform every
value.
Same options as 'every', :kind defaults to map?, with the addition of:
:conform-keys - conform keys as well as values (default false)
See also - every-kv"
[kpred vpred & opts]
`(every-kv ~kpred ~vpred ::conform-all true :kind map? ~@opts))
(defmacro *
"Returns a regex op that matches zero or more values matching
pred. Produces a vector of matches iff there is at least one match"
[pred-form]
`(rep-impl '~(res pred-form) ~pred-form))
(defmacro +
"Returns a regex op that matches one or more values matching
pred. Produces a vector of matches"
[pred-form]
`(rep+impl '~(res pred-form) ~pred-form))
(defmacro ?
"Returns a regex op that matches zero or one value matching
pred. Produces a single value (not a collection) if matched."
[pred-form]
`(maybe-impl ~pred-form '~pred-form))
(defmacro alt
"Takes key+pred pairs, e.g.
(s/alt :even even? :small #(< % 42))
Returns a regex op that returns a map entry containing the key of the
first matching pred and the corresponding value. Thus the
'key' and 'val' functions can be used to refer generically to the
components of the tagged return"
[& key-pred-forms]
(let [pairs (partition 2 key-pred-forms)
keys (mapv first pairs)
pred-forms (mapv second pairs)
pf (mapv res pred-forms)]
(c/assert (c/and (even? (count key-pred-forms)) (every? keyword? keys)) "alt expects k1 p1 k2 p2..., where ks are keywords")
`(alt-impl ~keys ~pred-forms '~pf)))
(defmacro cat
"Takes key+pred pairs, e.g.
(s/cat :e even? :o odd?)
Returns a regex op that matches (all) values in sequence, returning a map
containing the keys of each pred and the corresponding value."
[& key-pred-forms]
(let [pairs (partition 2 key-pred-forms)
keys (mapv first pairs)
pred-forms (mapv second pairs)
pf (mapv res pred-forms)]
;;(prn key-pred-forms)
(c/assert (c/and (even? (count key-pred-forms)) (every? keyword? keys)) "cat expects k1 p1 k2 p2..., where ks are keywords")
`(cat-impl ~keys ~pred-forms '~pf)))
(defmacro &
"takes a regex op re, and predicates. Returns a regex-op that consumes
input as per re but subjects the resulting value to the
conjunction of the predicates, and any conforming they might perform."
[re & preds]
(let [pv (vec preds)]
`(amp-impl ~re ~pv '~(mapv res pv))))
(defmacro conformer
"takes a predicate function with the semantics of conform i.e. it should return either a
(possibly converted) value or :clojure.spec/invalid, and returns a
spec that uses it as a predicate/conformer. Optionally takes a
second fn that does unform of result of first"
([f] `(spec-impl '~f ~f nil true))
([f unf] `(spec-impl '~f ~f nil true ~unf)))
(defmacro fspec
"takes :args :ret and (optional) :fn kwargs whose values are preds
and returns a spec whose conform/explain take a fn and validates it
using generative testing. The conformed value is always the fn itself.
See 'fdef' for a single operation that creates an fspec and
registers it, as well as a full description of :args, :ret and :fn
fspecs can generate functions that validate the arguments and
fabricate a return value compliant with the :ret spec, ignoring
the :fn spec if present.
Optionally takes :gen generator-fn, which must be a fn of no args
that returns a test.check generator."
[& {:keys [args ret fn gen]}]
`(fspec-impl (spec ~args) '~(res args)
(spec ~ret) '~(res ret)
(spec ~fn) '~(res fn) ~gen))
(defmacro tuple
"takes one or more preds and returns a spec for a tuple, a vector
where each element conforms to the corresponding pred. Each element
will be referred to in paths using its ordinal."
[& preds]
(c/assert (not (empty? preds)))
`(tuple-impl '~(mapv res preds) ~(vec preds)))
(defn- macroexpand-check
[v args]
(let [fn-spec (get-spec v)]
(when-let [arg-spec (:args fn-spec)]
(when (= ::invalid (conform arg-spec args))
(let [ed (assoc (explain-data* arg-spec [:args]
(if-let [name (spec-name arg-spec)] [name] []) [] args)
::args args)]
(throw (ArgumentException.
(str
"Call to " (->sym v) " did not conform to spec:\n"
(with-out-str (explain-out ed))))))))))
(defmacro fdef
"Takes a symbol naming a function, and one or more of the following:
:args A regex spec for the function arguments as they were a list to be
passed to apply - in this way, a single spec can handle functions with
multiple arities
:ret A spec for the function's return value
:fn A spec of the relationship between args and ret - the
value passed is {:args conformed-args :ret conformed-ret} and is
expected to contain predicates that relate those values
Qualifies fn-sym with resolve, or using *ns* if no resolution found.
Registers an fspec in the global registry, where it can be retrieved
by calling get-spec with the var or fully-qualified symbol.
Once registered, function specs are included in doc, checked by
instrument, tested by the runner clojure.spec.test/run-tests, and (if
a macro) used to explain errors during macroexpansion.
Note that :fn specs require the presence of :args and :ret specs to
conform values, and so :fn specs will be ignored if :args or :ret
are missing.
Returns the qualified fn-sym.
For example, to register function specs for the symbol function:
(s/fdef clojure.core/symbol
:args (s/alt :separate (s/cat :ns string? :n string?)
:str string?
:sym symbol?)
:ret symbol?)"
[fn-sym & specs]
`(clojure.spec/def ~fn-sym (clojure.spec/fspec ~@specs)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; impl ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- recur-limit? [rmap id path k]
(c/and (> (get rmap id) (::recursion-limit rmap))
(contains? (set path) k)))
(defn- inck [m k]
(assoc m k (inc (c/or (get m k) 0))))
(defn- dt
([pred x form] (dt pred x form nil))
([pred x form cpred?]
(if pred
(if-let [spec (the-spec pred)]
(conform spec x)
(if (ifn? pred)
(if cpred?
(pred x)
(if (pred x) x ::invalid))
(throw (Exception. (str (pr-str form) " is not a fn, expected predicate fn")))))
x)))
(defn valid?
"Helper function that returns true when x is valid for spec."
([spec x]
(not= ::invalid (dt spec x ::unknown)))
([spec x form]
(not= ::invalid (dt spec x form))))
(defn- explain-1 [form pred path via in v]
;;(prn {:form form :pred pred :path path :in in :v v})
(let [pred (maybe-spec pred)]
(if (spec? pred)
(explain* pred path (if-let [name (spec-name pred)] (conj via name) via) in v)
[{:path path :pred (abbrev form) :val v :via via :in in}])))
(defn ^:skip-wiki map-spec-impl
"Do not call this directly, use 'spec' with a map argument"
[{:keys [req-un opt-un pred-exprs opt-keys req-specs req req-keys opt-specs pred-forms opt gfn]
:as argm}]
(let [keys-pred (apply every-pred pred-exprs)
k->s (zipmap (concat req-keys opt-keys) (concat req-specs opt-specs))
keys->specs #(c/or (k->s %) %)
;; id (java.util.UUID/randomUUID)
id (System.Guid.) ;; maaaaybe?
]
(reify
clojure.lang.IFn
(invoke [this x] (valid? this x))
Spec
(conform* [_ m]
(if (keys-pred m)
(let [reg (registry)]
(loop [ret m, [k & ks :as keys] (c/keys m)]
(if keys
(if (contains? reg (keys->specs k))
(let [v (get m k)
cv (conform (keys->specs k) v)]
(if (= cv ::invalid)
::invalid
(recur (if (identical? cv v) ret (assoc ret k cv))
ks)))
(recur ret ks))
ret)))
::invalid))
(unform* [_ m]
(let [reg (registry)]
(loop [ret m, [k & ks :as keys] (c/keys m)]
(if keys
(if (contains? reg (keys->specs k))
(let [cv (get m k)
v (unform (keys->specs k) cv)]
(recur (if (identical? cv v) ret (assoc ret k v))
ks))
(recur ret ks))
ret))))
(explain* [_ path via in x]
(if-not (map? x)
[{:path path :pred 'map? :val x :via via :in in}]
(let [reg (registry)]
(apply concat
(when-let [probs (->> (map (fn [pred form] (when-not (pred x) (abbrev form)))
pred-exprs pred-forms)
(keep identity)
seq)]
(map
#(identity {:path path :pred % :val x :via via :in in})
probs))
(map (fn [[k v]]
(when-not (c/or (not (contains? reg (keys->specs k)))
(valid? (keys->specs k) v k))
(explain-1 (keys->specs k) (keys->specs k) (conj path k) via (conj in k) v)))
(seq x))))))
(gen* [_ overrides path rmap]
(if gfn
(gfn)
(let [rmap (inck rmap id)
gen (fn [k s] (gensub s overrides (conj path k) rmap k))
ogen (fn [k s]
(when-not (recur-limit? rmap id path k)
[k (gen/delay (gensub s overrides (conj path k) rmap k))]))
req-gens (map gen req-keys req-specs)
opt-gens (remove nil? (map ogen opt-keys opt-specs))]
(when (every? identity (concat req-gens opt-gens))
(let [reqs (zipmap req-keys req-gens)
opts (into {} opt-gens)]
(gen/bind (gen/choose 0 (count opts))
#(let [args (concat (seq reqs) (when (seq opts) (shuffle (seq opts))))]
(->> args
(take (c/+ % (count reqs)))
(apply concat)
(apply gen/hash-map)))))))))
(with-gen* [_ gfn] (map-spec-impl (assoc argm :gfn gfn)))
(describe* [_] (cons `keys
(cond-> []
req (conj :req req)
opt (conj :opt opt)
req-un (conj :req-un req-un)
opt-un (conj :opt-un opt-un)))))))
(defn ^:skip-wiki spec-impl
"Do not call this directly, use 'spec'"
([form pred gfn cpred?] (spec-impl form pred gfn cpred? nil))
([form pred gfn cpred? unc]
(cond
(spec? pred) (cond-> pred gfn (with-gen gfn))
(regex? pred) (regex-spec-impl pred gfn)
(named? pred) (cond-> (the-spec pred) gfn (with-gen gfn))
:else
(reify
Spec
(conform* [_ x] (dt pred x form cpred?))
(unform* [_ x] (if cpred?
(if unc
(unc x)
(throw (InvalidOperationException. "no unform fn for conformer")))
x))
(explain* [_ path via in x]
(when (= ::invalid (dt pred x form cpred?))
[{:path path :pred (abbrev form) :val x :via via :in in}]))
(gen* [_ _ _ _] (if gfn
(gfn)
(gen/gen-for-pred pred)))
(with-gen* [_ gfn] (spec-impl form pred gfn cpred?))
(describe* [_] form)))))
(defn ^:skip-wiki multi-spec-impl
"Do not call this directly, use 'multi-spec'"
([form mmvar retag] (multi-spec-impl form mmvar retag nil))
([form mmvar retag gfn]
(let [id (System.Guid.)
predx #(let [^clojure.lang.MultiFn mm @mmvar]
(c/and (contains? (methods mm)
((.dispatchFn mm) %))
(mm %)))
dval #((.dispatchFn ^clojure.lang.MultiFn @mmvar) %)
tag (if (keyword? retag)
#(assoc %1 retag %2)
retag)]
(reify
Spec
(conform* [_ x] (if-let [pred (predx x)]
(dt pred x form)
::invalid))
(unform* [_ x] (if-let [pred (predx x)]
(unform pred x)
(throw (InvalidOperationException. (str "No method of: " form " for dispatch value: " (dval x))))))
(explain* [_ path via in x]
(let [dv (dval x)
path (conj path dv)]
(if-let [pred (predx x)]
(explain-1 form pred path via in x)
[{:path path :pred (abbrev form) :val x :reason "no method" :via via :in in}])))
(gen* [_ overrides path rmap]
(if gfn
(gfn)
(let [gen (fn [[k f]]
(let [p (f nil)]
(let [rmap (inck rmap id)]
(when-not (recur-limit? rmap id path k)
(gen/delay
(gen/fmap
#(tag % k)
(gensub p overrides (conj path k) rmap (list 'method form k))))))))
gs (->> (methods @mmvar)
(remove (fn [[k]] (= k ::invalid)))
(map gen)
(remove nil?))]
(when (every? identity gs)
(gen/one-of gs)))))
(with-gen* [_ gfn] (multi-spec-impl form mmvar retag gfn))
(describe* [_] `(multi-spec ~form))))))
(defn ^:skip-wiki tuple-impl
"Do not call this directly, use 'tuple'"
([forms preds] (tuple-impl forms preds nil))
([forms preds gfn]
(reify
Spec
(conform* [_ x]
(if-not (c/and (vector? x)
(= (count x) (count preds)))
::invalid
(loop [ret x, i 0]
(if (= i (count x))
ret
(let [v (x i)
cv (dt (preds i) v (forms i))]
(if (= ::invalid cv)
::invalid
(recur (if (identical? cv v) ret (assoc ret i cv))
(inc i))))))))
(unform* [_ x]
(c/assert (c/and (vector? x)
(= (count x) (count preds))))
(loop [ret x, i 0]
(if (= i (count x))
ret
(let [cv (x i)
v (unform (preds i) cv)]
(recur (if (identical? cv v) ret (assoc ret i v))
(inc i))))))
(explain* [_ path via in x]
(cond
(not (vector? x))
[{:path path :pred 'vector? :val x :via via :in in}]
(not= (count x) (count preds))
[{:path path :pred `(= (count ~'%) ~(count preds)) :val x :via via :in in}]
:else
(apply concat
(map (fn [i form pred]
(let [v (x i)]
(when-not (valid? pred v)
(explain-1 form pred (conj path i) via (conj in i) v))))
(range (count preds)) forms preds))))
(gen* [_ overrides path rmap]
(if gfn
(gfn)
(let [gen (fn [i p f]
(gensub p overrides (conj path i) rmap f))
gs (map gen (range (count preds)) preds forms)]
(when (every? identity gs)
(apply gen/tuple gs)))))
(with-gen* [_ gfn] (tuple-impl forms preds gfn))
(describe* [_] `(tuple ~@forms)))))
(defn- tagged-ret [tag ret]
(clojure.lang.MapEntry. tag ret))
(defn ^:skip-wiki or-spec-impl
"Do not call this directly, use 'or'"
[keys forms preds gfn]
(let [id (System.Guid.)
kps (zipmap keys preds)
cform (fn [x]
(loop [i 0]
(if (< i (count preds))
(let [pred (preds i)]
(let [ret (dt pred x (nth forms i))]
(if (= ::invalid ret)
(recur (inc i))
(tagged-ret (keys i) ret))))
::invalid)))]
(reify
Spec
(conform* [_ x] (cform x))
(unform* [_ [k x]] (unform (kps k) x))
(explain* [this path via in x]
(when-not (valid? this x)
(apply concat
(map (fn [k form pred]
(when-not (valid? pred x)
(explain-1 form pred (conj path k) via in x)))
keys forms preds))))
(gen* [_ overrides path rmap]
(if gfn
(gfn)
(let [gen (fn [k p f]
(let [rmap (inck rmap id)]
(when-not (recur-limit? rmap id path k)
(gen/delay
(gensub p overrides (conj path k) rmap f)))))
gs (remove nil? (map gen keys preds forms))]
(when-not (empty? gs)
(gen/one-of gs)))))
(with-gen* [_ gfn] (or-spec-impl keys forms preds gfn))
(describe* [_] `(or ~@(mapcat vector keys forms))))))
(defn- and-preds [x preds forms]
(loop [ret x
[pred & preds] preds
[form & forms] forms]
(if pred
(let [nret (dt pred ret form)]
(if (= ::invalid nret)
::invalid
;;propagate conformed values
(recur nret preds forms)))
ret)))
(defn- explain-pred-list
[forms preds path via in x]
(loop [ret x
[form & forms] forms
[pred & preds] preds]
(when pred
(let [nret (dt pred ret form)]
(if (not= ::invalid nret)
(recur nret forms preds)
(explain-1 form pred path via in ret))))))
(defn ^:skip-wiki and-spec-impl
"Do not call this directly, use 'and'"
[forms preds gfn]
(reify
Spec
(conform* [_ x] (and-preds x preds forms))
(unform* [_ x] (reduce #(unform %2 %1) x (reverse preds)))
(explain* [_ path via in x] (explain-pred-list forms preds path via in x))
(gen* [_ overrides path rmap] (if gfn (gfn) (gensub (first preds) overrides path rmap (first forms))))
(with-gen* [_ gfn] (and-spec-impl forms preds gfn))
(describe* [_] `(and ~@forms))))
(defn ^:skip-wiki merge-spec-impl
"Do not call this directly, use 'merge'"
[forms preds gfn]
(reify
Spec
(conform* [_ x] (let [ms (map #(dt %1 x %2) preds forms)]
(if (some #{::invalid} ms)
::invalid
(apply c/merge ms))))
(unform* [_ x] (apply c/merge (map #(unform % x) (reverse preds))))
(explain* [_ path via in x]
(apply concat
(map #(explain-1 %1 %2 path via in x)
forms preds)))
(gen* [_ overrides path rmap]
(if gfn
(gfn)
(gen/fmap
#(apply c/merge %)
(apply gen/tuple (map #(gensub %1 overrides path rmap %2)
preds forms)))))
(with-gen* [_ gfn] (merge-spec-impl forms preds gfn))
(describe* [_] `(merge ~@forms))))
(defn- coll-prob [x kfn kform distinct count min-count max-count
path via in]
(let [pred (c/or kfn coll?)
kform (c/or kform `coll?)]
(cond
(not (valid? pred x))
(explain-1 kform pred path via in x)
(c/and distinct (not (empty? x)) (not (apply distinct? x)))
[{:path path :pred 'distinct? :val x :via via :in in}]
(c/and count (not= count (bounded-count count x)))
[{:path path :pred `(= ~count (c/count ~'%)) :val x :via via :in in}]
(c/and (c/or min-count max-count)
(not (<= (c/or min-count 0)
(bounded-count (if max-count (inc max-count) min-count) x)
(c/or max-count System.Int32/MaxValue))))
[{:path path :pred `(<= ~(c/or min-count 0) (c/count ~'%) ~(c/or max-count 'System.Int32/MaxValue)) :val x :via via :in in}])))
(defn ^:skip-wiki every-impl
"Do not call this directly, use 'every', 'every-kv', 'coll-of' or 'map-of'"
([form pred opts] (every-impl form pred opts nil))
([form pred {gen-into :into
:keys [kind ::kind-form count max-count min-count distinct gen-max ::kfn
conform-keys ::conform-all]
:or {gen-max 20}
:as opts}
gfn]
(let [conform-into gen-into
check? #(valid? pred %)
kfn (c/or kfn (fn [i v] i))
addcv (fn [ret i v cv] (conj ret cv))
cfns (fn [x]
;;returns a tuple of [init add complete] fns
(cond
(c/and (vector? x) (c/or (not conform-into) (vector? conform-into)))
[identity
(fn [ret i v cv]
(if (identical? v cv)
ret
(assoc ret i cv)))
identity]
(c/and (map? x) (c/or (c/and kind (not conform-into)) (map? conform-into)))
[(if conform-keys empty identity)
(fn [ret i v cv]
(if (c/and (identical? v cv) (not conform-keys))
ret
(assoc ret (nth (if conform-keys cv v) 0) (nth cv 1))))
identity]
(c/or (list? conform-into) (c/and (not conform-into) (list? x)))
[(constantly ()) addcv reverse]
:else [#(empty (c/or conform-into %)) addcv identity]))]
(reify
Spec
(conform* [_ x]
(cond
(coll-prob x kind kind-form distinct count min-count max-count
nil nil nil)
::invalid
conform-all
(let [[init add complete] (cfns x)]
(loop [ret (init x), i 0, [v & vs :as vseq] (seq x)]
(if vseq
(let [cv (dt pred v nil)]
(if (= ::invalid cv)
::invalid
(recur (add ret i v cv) (inc i) vs)))
(complete ret))))
:else
(if (indexed? x)
(let [step (max 1 (long (/ (c/count x) *coll-check-limit*)))]
(loop [i 0]
(if (>= i (c/count x))
x
(if (check? (nth x i))
(recur (c/+ i step))
::invalid))))
(c/or (c/and (every? check? (take *coll-check-limit* x)) x)
::invalid))))
(unform* [_ x] x)
(explain* [_ path via in x]
(c/or (coll-prob x kind kind-form distinct count min-count max-count
path via in)
(apply concat
((if conform-all identity (partial take *coll-error-limit*))
(keep identity
(map (fn [i v]
(let [k (kfn i v)]
(when-not (check? v)
(let [prob (explain-1 form pred path via (conj in k) v)]
prob))))
(range) x))))))
(gen* [_ overrides path rmap]
(if gfn
(gfn)
(let [pgen (gensub pred overrides path rmap form)]
(gen/bind
(cond
gen-into (gen/return (empty gen-into))
kind (gen/fmap #(if (empty? %) % (empty %))
(gensub kind overrides path rmap form))
:else (gen/return []))
(fn [init]
(gen/fmap
#(if (vector? init) % (into init %))
(cond
distinct
(if count
(gen/vector-distinct pgen {:num-elements count :max-tries 100})
(gen/vector-distinct pgen {:min-elements (c/or min-count 0)
:max-elements (c/or max-count (max gen-max (c/* 2 (c/or min-count 0))))
:max-tries 100}))
count
(gen/vector pgen count)
(c/or min-count max-count)
(gen/vector pgen (c/or min-count 0) (c/or max-count (max gen-max (c/* 2 (c/or min-count 0)))))
:else
(gen/vector pgen 0 gen-max))))))))
(with-gen* [_ gfn] (every-impl form pred opts gfn))
(describe* [_] `(every ~form ~@(mapcat identity opts)))))))
;;;;;;;;;;;;;;;;;;;;;;; regex ;;;;;;;;;;;;;;;;;;;
;;See:
;; http://matt.might.net/articles/implementation-of-regular-expression-matching-in-scheme-with-derivatives/
;; http://www.ccs.neu.edu/home/turon/re-deriv.pdf
;;ctors
(defn- accept [x] {::op ::accept :ret x})
(defn- accept? [{:keys [::op]}]
(= ::accept op))
(defn- pcat* [{[p1 & pr :as ps] :ps, [k1 & kr :as ks] :ks, [f1 & fr :as forms] :forms, ret :ret, rep+ :rep+}]
(when (every? identity ps)
(if (accept? p1)
(let [rp (:ret p1)
ret (conj ret (if ks {k1 rp} rp))]
(if pr
(pcat* {:ps pr :ks kr :forms fr :ret ret})
(accept ret)))
{::op ::pcat, :ps ps, :ret ret, :ks ks, :forms forms :rep+ rep+})))
(defn- pcat [& ps] (pcat* {:ps ps :ret []}))
(defn ^:skip-wiki cat-impl
"Do not call this directly, use 'cat'"
[ks ps forms]
(pcat* {:ks ks, :ps ps, :forms forms, :ret {}}))
(defn- rep* [p1 p2 ret splice form]
(when p1
(let [r {::op ::rep, :p2 p2, :splice splice, :forms form :id (System.Guid.)}]
(if (accept? p1)
(assoc r :p1 p2 :ret (conj ret (:ret p1)))
(assoc r :p1 p1, :ret ret)))))
(defn ^:skip-wiki rep-impl
"Do not call this directly, use '*'"
[form p] (rep* p p [] false form))
(defn ^:skip-wiki rep+impl
"Do not call this directly, use '+'"
[form p]
(pcat* {:ps [p (rep* p p [] true form)] :forms `[~form (* ~form)] :ret [] :rep+ form}))
(defn ^:skip-wiki amp-impl
"Do not call this directly, use '&'"
[re preds pred-forms]
{::op ::amp :p1 re :ps preds :forms pred-forms})
(defn- filter-alt [ps ks forms f]
(if (c/or ks forms)
(let [pks (->> (map vector ps
(c/or (seq ks) (repeat nil))
(c/or (seq forms) (repeat nil)))
(filter #(-> % first f)))]
[(seq (map first pks)) (when ks (seq (map second pks))) (when forms (seq (map #(nth % 2) pks)))])
[(seq (filter f ps)) ks forms]))
(defn- alt* [ps ks forms]
(let [[[p1 & pr :as ps] [k1 :as ks] forms] (filter-alt ps ks forms identity)]
(when ps
(let [ret {::op ::alt, :ps ps, :ks ks :forms forms}]
(if (nil? pr)
(if k1
(if (accept? p1)
(accept (tagged-ret k1 (:ret p1)))
ret)
p1)
ret)))))
(defn- alts [& ps] (alt* ps nil nil))
(defn- alt2 [p1 p2] (if (c/and p1 p2) (alts p1 p2) (c/or p1 p2)))
(defn ^:skip-wiki alt-impl
"Do not call this directly, use 'alt'"
[ks ps forms] (assoc (alt* ps ks forms) :id (System.Guid.)))
(defn ^:skip-wiki maybe-impl
"Do not call this directly, use '?'"
[p form] (assoc (alt* [p (accept ::nil)] nil [form ::nil]) :maybe form))
(defn- noret? [p1 pret]
(c/or (= pret ::nil)
(c/and (#{::rep ::pcat} (::op (reg-resolve! p1))) ;;hrm, shouldn't know these
(empty? pret))
nil))
(declare preturn)
(defn- accept-nil? [p]
(let [{:keys [::op ps p1 p2 forms] :as p} (reg-resolve! p)]
(case op
::accept true
nil nil
::amp (c/and (accept-nil? p1)
(c/or (noret? p1 (preturn p1))
(let [ret (-> (preturn p1) (and-preds ps (next forms)))]
(not= ret ::invalid))))
::rep (c/or (identical? p1 p2) (accept-nil? p1))
::pcat (every? accept-nil? ps)
::alt (c/some accept-nil? ps))))
(declare add-ret)
(defn- preturn [p]
(let [{[p0 & pr :as ps] :ps, [k :as ks] :ks, :keys [::op p1 ret forms] :as p} (reg-resolve! p)]
(case op
::accept ret
nil nil
::amp (let [pret (preturn p1)]
(if (noret? p1 pret)
::nil
(and-preds pret ps forms)))
::rep (add-ret p1 ret k)
::pcat (add-ret p0 ret k)
::alt (let [[[p0] [k0]] (filter-alt ps ks forms accept-nil?)
r (if (nil? p0) ::nil (preturn p0))]
(if k0 (tagged-ret k0 r) r)))))
(defn- op-unform [p x]
;;(prn {:p p :x x})
(let [{[p0 & pr :as ps] :ps, [k :as ks] :ks, :keys [::op p1 ret forms rep+ maybe] :as p} (reg-resolve! p)
kps (zipmap ks ps)]
(case op
::accept [ret]
nil [(unform p x)]
::amp (let [px (reduce #(unform %2 %1) x (reverse ps))]
(op-unform p1 px))
::rep (mapcat #(op-unform p1 %) x)
::pcat (if rep+
(mapcat #(op-unform p0 %) x)
(mapcat (fn [k]
(when (contains? x k)
(op-unform (kps k) (get x k))))
ks))
::alt (if maybe
[(unform p0 x)]
(let [[k v] x]
(op-unform (kps k) v))))))
(defn- add-ret [p r k]
(let [{:keys [::op ps splice] :as p} (reg-resolve! p)
prop #(let [ret (preturn p)]
(if (empty? ret) r ((if splice into conj) r (if k {k ret} ret))))]
(case op
nil r
(::alt ::accept ::amp)
(let [ret (preturn p)]
;;(prn {:ret ret})
(if (= ret ::nil) r (conj r (if k {k ret} ret))))
(::rep ::pcat) (prop))))
(defn- deriv
[p x]
(let [{[p0 & pr :as ps] :ps, [k0 & kr :as ks] :ks, :keys [::op p1 p2 ret splice forms] :as p} (reg-resolve! p)]
(when p
(case op
::accept nil
nil (let [ret (dt p x p)]
(when-not (= ::invalid ret) (accept ret)))
::amp (when-let [p1 (deriv p1 x)]
(if (= ::accept (::op p1))
(let [ret (-> (preturn p1) (and-preds ps (next forms)))]
(when-not (= ret ::invalid)
(accept ret)))
(amp-impl p1 ps forms)))
::pcat (alt2 (pcat* {:ps (cons (deriv p0 x) pr), :ks ks, :forms forms, :ret ret})
(when (accept-nil? p0) (deriv (pcat* {:ps pr, :ks kr, :forms (next forms), :ret (add-ret p0 ret k0)}) x)))
::alt (alt* (map #(deriv % x) ps) ks forms)
::rep (alt2 (rep* (deriv p1 x) p2 ret splice forms)
(when (accept-nil? p1) (deriv (rep* p2 p2 (add-ret p1 ret nil) splice forms) x)))))))
(defn- op-describe [p]
(let [{:keys [::op ps ks forms splice p1 rep+ maybe] :as p} (reg-resolve! p)]
;;(prn {:op op :ks ks :forms forms :p p})
(when p
(case op
::accept nil
nil p
::amp (list* 'clojure.spec/& (op-describe p1) forms)
::pcat (if rep+
(list `+ rep+)
(cons `cat (mapcat vector (c/or (seq ks) (repeat :_)) forms)))
::alt (if maybe
(list `? maybe)
(cons `alt (mapcat vector ks forms)))
::rep (list (if splice `+ `*) forms)))))
(defn- op-explain [form p path via in input]
;;(prn {:form form :p p :path path :input input})
(let [[x :as input] input
{:keys [::op ps ks forms splice p1 p2] :as p} (reg-resolve! p)
via (if-let [name (spec-name p)] (conj via name) via)
insufficient (fn [path form]
[{:path path
:reason "Insufficient input"
:pred (abbrev form)
:val ()
:via via
:in in}])]
(when p
(case op
::accept nil
nil (if (empty? input)
(insufficient path form)
(explain-1 form p path via in x))
::amp (if (empty? input)
(if (accept-nil? p1)
(explain-pred-list forms ps path via in (preturn p1))
(insufficient path (op-describe p1)))
(if-let [p1 (deriv p1 x)]
(explain-pred-list forms ps path via in (preturn p1))
(op-explain (op-describe p1) p1 path via in input)))
::pcat (let [pkfs (map vector
ps
(c/or (seq ks) (repeat nil))
(c/or (seq forms) (repeat nil)))
[pred k form] (if (= 1 (count pkfs))
(first pkfs)
(first (remove (fn [[p]] (accept-nil? p)) pkfs)))
path (if k (conj path k) path)
form (c/or form (op-describe pred))]
(if (c/and (empty? input) (not pred))
(insufficient path form)
(op-explain form pred path via in input)))
::alt (if (empty? input)
(insufficient path (op-describe p))
(apply concat
(map (fn [k form pred]
(op-explain (c/or form (op-describe pred))
pred
(if k (conj path k) path)
via
in
input))
(c/or (seq ks) (repeat nil))
(c/or (seq forms) (repeat nil))
ps)))
::rep (op-explain (if (identical? p1 p2)
forms
(op-describe p1))
p1 path via in input)))))
(defn- re-gen [p overrides path rmap f]
;;(prn {:op op :ks ks :forms forms})
(let [{:keys [::op ps ks p1 p2 forms splice ret id ::gfn] :as p} (reg-resolve! p)
rmap (if id (inck rmap id) rmap)
ggens (fn [ps ks forms]
(let [gen (fn [p k f]
;;(prn {:k k :path path :rmap rmap :op op :id id})
(when-not (c/and rmap id k (recur-limit? rmap id path k))
(if id
(gen/delay (re-gen p overrides (if k (conj path k) path) rmap (c/or f p)))
(re-gen p overrides (if k (conj path k) path) rmap (c/or f p)))))]
(map gen ps (c/or (seq ks) (repeat nil)) (c/or (seq forms) (repeat nil)))))]
(c/or (when-let [g (get overrides path)]
(case op
(:accept nil) (gen/fmap vector g)
g))
(when gfn
(gfn))
(when p
(case op
::accept (if (= ret ::nil)
(gen/return [])
(gen/return [ret]))
nil (when-let [g (gensub p overrides path rmap f)]
(gen/fmap vector g))
::amp (re-gen p1 overrides path rmap (op-describe p1))
::pcat (let [gens (ggens ps ks forms)]
(when (every? identity gens)
(apply gen/cat gens)))
::alt (let [gens (remove nil? (ggens ps ks forms))]
(when-not (empty? gens)
(gen/one-of gens)))
::rep (if (recur-limit? rmap id [id] id)
(gen/return [])
(when-let [g (re-gen p2 overrides path rmap forms)]
(gen/fmap #(apply concat %)
(gen/vector g)))))))))
(defn- re-conform [p [x & xs :as data]]
;;(prn {:p p :x x :xs xs})
(if (empty? data)
(if (accept-nil? p)
(let [ret (preturn p)]
(if (= ret ::nil)
nil
ret))
::invalid)
(if-let [dp (deriv p x)]
(recur dp xs)
::invalid)))
(defn- re-explain [path via in re input]
(loop [p re [x & xs :as data] input i 0]
;;(prn {:p p :x x :xs xs :re re}) (prn)
(if (empty? data)
(if (accept-nil? p)
nil ;;success
(op-explain (op-describe p) p path via in nil))
(if-let [dp (deriv p x)]
(recur dp xs (inc i))
(if (accept? p)
(if (= (::op p) ::pcat)
(op-explain (op-describe p) p path via (conj in i) (seq data))
[{:path path
:reason "Extra input"
:pred (abbrev (op-describe re))
:val data
:via via
:in (conj in i)}])
(c/or (op-explain (op-describe p) p path via (conj in i) (seq data))
[{:path path
:reason "Extra input"
:pred (abbrev (op-describe p))
:val data
:via via
:in (conj in i)}]))))))
(defn ^:skip-wiki regex-spec-impl
"Do not call this directly, use 'spec' with a regex op argument"
[re gfn]
(reify
Spec
(conform* [_ x]
(if (c/or (nil? x) (coll? x))
(re-conform re (seq x))
::invalid))
(unform* [_ x] (op-unform re x))
(explain* [_ path via in x]
(if (c/or (nil? x) (coll? x))
(re-explain path via in re (seq x))
[{:path path :pred (abbrev (op-describe re)) :val x :via via :in in}]))
(gen* [_ overrides path rmap]
(if gfn
(gfn)
(re-gen re overrides path rmap (op-describe re))))
(with-gen* [_ gfn] (regex-spec-impl re gfn))
(describe* [_] (op-describe re))))
;;;;;;;;;;;;;;;;; HOFs ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- call-valid?
[f specs args]
(let [cargs (conform (:args specs) args)]
(when-not (= cargs ::invalid)
(let [ret (apply f args)
cret (conform (:ret specs) ret)]
(c/and (not= cret ::invalid)
(if (:fn specs)
(valid? (:fn specs) {:args cargs :ret cret})
true))))))
(defn- validate-fn
"returns f if valid, else smallest"
[f specs iters]
(let [g (gen (:args specs))
prop (gen/for-all* [g] #(call-valid? f specs %))]
(let [ret (gen/quick-check iters prop)]
(if-let [[smallest] (-> ret :shrunk :smallest)]
smallest
f))))
(defn ^:skip-wiki fspec-impl
"Do not call this directly, use 'fspec'"
[argspec aform retspec rform fnspec fform gfn]
(let [specs {:args argspec :ret retspec :fn fnspec}]
(reify
clojure.lang.ILookup
(valAt [this k] (get specs k))
(valAt [_ k not-found] (get specs k not-found))
Spec
(conform* [_ f] (if (ifn? f)
(if (identical? f (validate-fn f specs *fspec-iterations*)) f ::invalid)
::invalid))
(unform* [_ f] f)
(explain* [_ path via in f]
(if (ifn? f)
(let [args (validate-fn f specs 100)]
(if (identical? f args) ;;hrm, we might not be able to reproduce
nil
(let [ret (try (apply f args) (catch Exception ;;Throwable
t t))]
(if (instance? Exception ;;Throwable
ret)
;;TODO add exception data
{path {:pred '(apply fn) :val args :reason (.getMessage ^Exception ;;^Throwable
ret) :via via :in in}}
(let [cret (dt retspec ret rform)]
(if (= ::invalid cret)
(explain-1 rform retspec (conj path :ret) via in ret)
(when fnspec
(let [cargs (conform argspec args)]
(explain-1 fform fnspec (conj path :fn) via in {:args cargs :ret cret})))))))))
[{:path path :pred 'ifn? :val f :via via :in in}]))
(gen* [_ overrides _ _] (if gfn
(gfn)
(gen/return
(fn [& args]
(c/assert (valid? argspec args) (with-out-str (explain argspec args)))
(gen/generate (gen retspec overrides))))))
(with-gen* [_ gfn] (fspec-impl argspec aform retspec rform fnspec fform gfn))
(describe* [_] `(fspec :args ~aform :ret ~rform :fn ~fform)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; non-primitives ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(clojure.spec/def ::kvs->map (conformer #(zipmap (map ::k %) (map ::v %)) #(map (fn [[k v]] {::k k ::v v}) %)))
(defmacro keys*
"takes the same arguments as spec/keys and returns a regex op that matches sequences of key/values,
converts them into a map, and conforms that map with a corresponding
spec/keys call:
user=> (s/conform (s/keys :req-un [::a ::c]) {:a 1 :c 2})
{:a 1, :c 2}
user=> (s/conform (s/keys* :req-un [::a ::c]) [:a 1 :c 2])
{:a 1, :c 2}
the resulting regex op can be composed into a larger regex:
user=> (s/conform (s/cat :i1 integer? :m (s/keys* :req-un [::a ::c]) :i2 integer?) [42 :a 1 :c 2 :d 4 99])
{:i1 42, :m {:a 1, :c 2, :d 4}, :i2 99}"
[& kspecs]
`(let [mspec# (keys ~@kspecs)]
(with-gen (clojure.spec/& (* (cat ::k keyword? ::v any?)) ::kvs->map mspec#)
(fn [] (gen/fmap (fn [m#] (apply concat m#)) (gen mspec#))))))
(defmacro nilable
"returns a spec that accepts nil and values satisfiying pred"
[pred]
`(and (or ::nil nil? ::pred ~pred) (conformer second #(if (nil? %) [::nil nil] [::pred %]))))
(defn exercise
"generates a number (default 10) of values compatible with spec and maps conform over them,
returning a sequence of [val conformed-val] tuples. Optionally takes
a generator overrides map as per gen"
([spec] (exercise spec 10))
([spec n] (exercise spec n nil))
([spec n overrides]
(map #(vector % (conform spec %)) (gen/sample (gen spec overrides) n))))
(defn exercise-fn
"exercises the fn named by sym (a symbol) by applying it to
n (default 10) generated samples of its args spec. When fspec is
supplied its arg spec is used, and sym-or-f can be a fn. Returns a
sequence of tuples of [args ret]. "
([sym] (exercise-fn sym 10))
([sym n] (exercise-fn sym n (get-spec sym)))
([sym-or-f n fspec]
(let [f (if (symbol? sym-or-f) (resolve sym-or-f) sym-or-f)]
(for [args (gen/sample (gen (:args fspec)) n)]
[args (apply f args)]))))
(defn inst-in-range?
"Return true if inst at or after start and before end"
[start end inst]
(c/and (inst? inst)
(let [t (inst-ms inst)]
(c/and (<= (inst-ms start) t) (< t (inst-ms end))))))
(defmacro inst-in
"Returns a spec that validates insts in the range from start
(inclusive) to end (exclusive)."
[start end]
`(let [st# (inst-ms ~start)
et# (inst-ms ~end)
mkdate# (fn [d#] (java.util.Date. ^{:tag ~'long} d#))]
(spec (and inst? #(inst-in-range? ~start ~end %))
:gen (fn []
(gen/fmap mkdate#
(gen/large-integer* {:min st# :max et#}))))))
(defn int-in-range?
"Return true if start <= val and val < end"
[start end val]
(c/and int? (<= start val) (< val end)))
(defmacro int-in
"Returns a spec that validates ints in the range from start
(inclusive) to end (exclusive)."
[start end]
`(spec (and int? #(int-in-range? ~start ~end %))
:gen #(gen/large-integer* {:min ~start :max (dec ~end)})))
(defmacro double-in
"Specs a 64-bit floating point number. Options:
:infinite? - whether +/- infinity allowed (default true)
:NaN? - whether NaN allowed (default true)
:min - minimum value (inclusive, default none)
:max - maximum value (inclusive, default none)"
[& {:keys [infinite? NaN? min max]
:or {infinite? true NaN? true}
:as m}]
`(spec (and c/double?
~@(when-not infinite? '[#(not (Double/isInfinite %))])
~@(when-not NaN? '[#(not (Double/isNaN %))])
~@(when max `[#(<= % ~max)])
~@(when min `[#(<= ~min %)]))
:gen #(gen/double* ~m)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; assert ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defonce
^{:dynamic true
:doc "If true, compiler will enable spec asserts, which are then
subject to runtime control via check-asserts? If false, compiler
will eliminate all spec assert overhead. See 'assert'.
Initially set to boolean value of clojure.spec.compile-asserts
system property. Defaults to true."}
*compile-asserts*
(not= "false"
(System.Environment/GetEnvironmentVariable "CLOJURE_SPEC_COMPILE_ASSERTS")
;; (System/getProperty "clojure.spec.compile-asserts")
))
(def ^:private check-spec-asserts-ref
;; janky hack in absence of easier way to modify RT
(atom
;; ;; I guess? see https://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html
;; ;; Without some more work won't "default to true", though
;; (= "true"
;; (System.Environment/GetEnvironmentVariable "CLOJURE_SPEC_COMPILE_ASSERTS"))
true ;; fify
))
(defn check-asserts?
"Returns the value set by check-asserts."
[]
@check-spec-asserts-ref
;;clojure.lang.RT/checkSpecAsserts
)
(defn check-asserts
"Enable or disable spec asserts that have been compiled
with '*compile-asserts*' true. See 'assert'.
Initially set to boolean value of clojure.spec.check-asserts
system property. Defaults to false."
[flag]
(reset! check-spec-asserts-ref flag)
;;(set! (. clojure.lang.RT checkSpecAsserts) flag)
)
(defn assert*
"Do not call this directly, use 'assert'."
[spec x]
(if (valid? spec x)
x
(let [ed (c/merge (assoc (explain-data* spec [] [] [] x)
::failure :assertion-failed))]
(throw (ex-info
(str "Spec assertion failed\n" (with-out-str (explain-out ed)))
ed)))))
(defmacro assert
"spec-checking assert expression. Returns x if x is valid? according
to spec, else throws an ex-info with explain-data plus ::failure of
:assertion-failed.
Can be disabled at either compile time or runtime:
If *compile-asserts* is false at compile time, compiles to x. Defaults
to value of 'clojure.spec.compile-asserts' system property, or true if
not set.
If (check-asserts?) is false at runtime, always returns x. Defaults to
value of 'clojure.spec.check-asserts' system property, or false if not
set. You can toggle check-asserts? with (check-asserts bool)."
[spec x]
(if *compile-asserts*
`(if clojure.lang.RT/checkSpecAsserts
(assert* ~spec ~x)
~x)
x))
| true | ; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns clojure.spec
(:refer-clojure :exclude [+ * and assert or cat def keys merge])
(:require [clojure.walk :as walk]
[clojure.spec.gen :as gen]
[clojure.string :as str]))
(alias 'c 'clojure.core)
(set! *warn-on-reflection* true)
(def ^:dynamic *recursion-limit*
"A soft limit on how many times a branching spec (or/alt/*/opt-keys/multi-spec)
can be recursed through during generation. After this a
non-recursive branch will be chosen."
4)
(def ^:dynamic *fspec-iterations*
"The number of times an anonymous fn specified by fspec will be (generatively) tested during conform"
21)
(def ^:dynamic *coll-check-limit*
"The number of elements validated in a collection spec'ed with 'every'"
101)
(def ^:dynamic *coll-error-limit*
"The number of errors reported by explain in a collection spec'ed with 'every'"
20)
(defprotocol Spec
(conform* [spec x])
(unform* [spec y])
(explain* [spec path via in x])
(gen* [spec overrides path rmap])
(with-gen* [spec gfn])
(describe* [spec]))
(defonce ^:private registry-ref (atom {}))
(defn- named? [x] (instance? clojure.lang.Named x))
(defn- with-name [spec name]
(with-meta spec (assoc (meta spec) ::name name)))
(defn- spec-name [spec]
(cond
(keyword? spec) spec
(instance? clojure.lang.IObj spec)
(-> (meta spec) ::name)))
(defn- reg-resolve
"returns the spec/regex at end of alias chain starting with k, nil if not found, k if k not Named"
[k]
(if (named? k)
(let [reg @registry-ref]
(loop [spec k]
(if (named? spec)
(recur (get reg spec))
(when spec
(with-name spec k)))))
k))
(defn- reg-resolve!
"returns the spec/regex at end of alias chain starting with k, throws if not found, k if k not ident"
[k]
(if (ident? k)
(c/or (reg-resolve k)
(throw (Exception. (str "Unable to resolve spec: " k))))
k))
(defn spec?
"returns x if x is a spec object, else logical false"
[x]
(c/and (extends? Spec (class x)) x))
(defn regex?
"returns x if x is a (clojure.spec) regex op, else logical false"
[x]
(c/and (::op x) x))
(declare spec-impl)
(declare regex-spec-impl)
(defn- maybe-spec
"spec-or-k must be a spec, regex or resolvable kw/sym, else returns nil."
[spec-or-k]
(let [s (c/or (spec? spec-or-k)
(regex? spec-or-k)
(c/and (named? spec-or-k) (reg-resolve spec-or-k))
nil)]
(if (regex? s)
(with-name (regex-spec-impl s nil) (spec-name s))
s)))
(defn- the-spec
"spec-or-k must be a spec, regex or kw/sym, else returns nil. Throws if unresolvable kw/sym"
[spec-or-k]
(c/or (maybe-spec spec-or-k)
(when (named? spec-or-k)
(throw (Exception. (str "Unable to resolve spec: " spec-or-k))))))
(defn- specize [s]
(c/or (the-spec s) (spec-impl ::unknown s nil nil)))
(defn conform
"Given a spec and a value, returns :clojure.spec/invalid if value does not match spec,
else the (possibly destructured) value."
[spec x]
(conform* (specize spec) x))
(defn unform
"Given a spec and a value created by or compliant with a call to
'conform' with the same spec, returns a value with all conform
destructuring undone."
[spec x]
(unform* (specize spec) x))
(defn form
"returns the spec as data"
[spec]
;;TODO - incorporate gens
(describe* (specize spec)))
(defn abbrev [form]
(cond
(seq? form)
(walk/postwalk (fn [form]
(cond
(c/and (symbol? form) (namespace form))
(-> form name symbol)
(c/and (seq? form) (= 'fn (first form)) (= '[%] (second form)))
(last form)
:else form))
form)
(c/and (symbol? form) (namespace form))
(-> form name symbol)
:else form))
(defn describe
"returns an abbreviated description of the spec as data"
[spec]
(abbrev (form spec)))
(defn with-gen
"Takes a spec and a no-arg, generator-returning fn and returns a version of that spec that uses that generator"
[spec gen-fn]
(let [spec (reg-resolve spec)]
(if (regex? spec)
(assoc spec ::gfn gen-fn)
(with-gen* (specize spec) gen-fn))))
(defn explain-data* [spec path via in x]
(let [probs (explain* (specize spec) path via in x)]
(when-not (empty? probs)
{::problems probs})))
(defn explain-data
"Given a spec and a value x which ought to conform, returns nil if x
conforms, else a map with at least the key ::problems whose value is
a collection of problem-maps, where problem-map has at least :path :pred and :val
keys describing the predicate and the value that failed at that
path."
[spec x]
(explain-data* spec [] (if-let [name (spec-name spec)] [name] []) [] x))
(defn explain-out
"prints explanation data (per 'explain-data') to *out*."
[ed]
(if ed
(do
;;(prn {:ed ed})
(doseq [{:keys [path pred val reason via in] :as prob} (::problems ed)]
(when-not (empty? in)
(print "In:" (pr-str in) ""))
(print "val: ")
(pr val)
(print " fails")
(when-not (empty? via)
(print " spec:" (pr-str (last via))))
(when-not (empty? path)
(print " at:" (pr-str path)))
(print " predicate: ")
(pr (abbrev pred))
(when reason (print ", " reason))
(doseq [[k v] prob]
(when-not (#{:path :pred :val :reason :via :in} k)
(print "\n\t" (pr-str k) " ")
(pr v)))
(newline))
(doseq [[k v] ed]
(when-not (#{::problems} k)
(print (pr-str k) " ")
(pr v)
(newline))))
(println "Success!")))
(defn explain
"Given a spec and a value that fails to conform, prints an explanation to *out*."
[spec x]
(explain-out (explain-data spec x)))
(defn explain-str
"Given a spec and a value that fails to conform, returns an explanation as a string."
[spec x]
(with-out-str (explain spec x)))
(declare valid?)
(defn- gensub
[spec overrides path rmap form]
;;(prn {:spec spec :over overrides :path path :form form})
(let [spec (specize spec)]
(if-let [g (c/or (when-let [gfn (c/or (get overrides (c/or (spec-name spec) spec))
(get overrides path))]
(gfn))
(gen* spec overrides path rmap))]
(gen/such-that #(valid? spec %) g 100)
(let [abbr (abbrev form)]
(throw (ex-info (str "Unable to construct gen at: " path " for: " abbr)
{::path path ::form form ::failure :no-gen}))))))
(defn gen
"Given a spec, returns the generator for it, or throws if none can
be constructed. Optionally an overrides map can be provided which
should map spec names or paths (vectors of keywords) to no-arg
generator-creating fns. These will be used instead of the generators at those
names/paths. Note that parent generator (in the spec or overrides
map) will supersede those of any subtrees. A generator for a regex
op must always return a sequential collection (i.e. a generator for
s/? should return either an empty sequence/vector or a
sequence/vector with one item in it)"
([spec] (gen spec nil))
([spec overrides] (gensub spec overrides [] {::recursion-limit *recursion-limit*} spec)))
(defn- ->sym
"Returns a symbol from a symbol or var"
[x]
(if (var? x)
(let [^clojure.lang.Var v x]
(symbol (str (.Name (.ns v)))
(str (.sym v))))
x))
(defn- unfn [expr]
(if (c/and (seq? expr)
(symbol? (first expr))
(= "fn*" (name (first expr))))
(let [[[s] & form] (rest expr)]
(conj (walk/postwalk-replace {s '%} form) '[%] 'fn))
expr))
(defn- res [form]
(cond
(keyword? form) form
(symbol? form) (c/or (-> form resolve ->sym) form)
(sequential? form) (walk/postwalk #(if (symbol? %) (res %) %) (unfn form))
:else form))
(defn ^:skip-wiki def-impl
"Do not call this directly, use 'def'"
[k form spec]
(c/assert (c/and (named? k) (namespace k)) "k must be namespaced keyword or resolvable symbol")
(let [spec (if (c/or (spec? spec) (regex? spec) (get @registry-ref spec))
spec
(spec-impl form spec nil nil))]
(swap! registry-ref assoc k spec)
k))
(defn- ns-qualify
"Qualify symbol s by resolving it or using the current *ns*."
[s]
(if-let [ns-sym (some-> s namespace symbol)]
(c/or (some-> (get (ns-aliases *ns*) ns-sym) str (symbol (name s)))
s)
(symbol (str (.Name *ns*)) (str s))))
(defmacro def
"Given a namespace-qualified keyword or resolvable symbol k, and a
spec, spec-name, predicate or regex-op makes an entry in the
registry mapping k to the spec"
[k spec-form]
(let [k (if (symbol? k) (ns-qualify k) k)]
`(def-impl '~k '~(res spec-form) ~spec-form)))
(defn registry
"returns the registry map, prefer 'get-spec' to lookup a spec by name"
[]
@registry-ref)
(defn get-spec
"Returns spec registered for keyword/symbol/var k, or nil."
[k]
(get (registry) (if (keyword? k) k (->sym k))))
(declare map-spec)
(defmacro spec
"Takes a single predicate form, e.g. can be the name of a predicate,
like even?, or a fn literal like #(< % 42). Note that it is not
generally necessary to wrap predicates in spec when using the rest
of the spec macros, only to attach a unique generator
Can also be passed the result of one of the regex ops -
cat, alt, *, +, ?, in which case it will return a regex-conforming
spec, useful when nesting an independent regex.
---
Optionally takes :gen generator-fn, which must be a fn of no args that
returns a test.check generator.
Returns a spec."
[form & {:keys [gen]}]
(when form
`(spec-impl '~(res form) ~form ~gen nil)))
(defmacro multi-spec
"Takes the name of a spec/predicate-returning multimethod and a
tag-restoring keyword or fn (retag). Returns a spec that when
conforming or explaining data will pass it to the multimethod to get
an appropriate spec. You can e.g. use multi-spec to dynamically and
extensibly associate specs with 'tagged' data (i.e. data where one
of the fields indicates the shape of the rest of the structure).
(defmulti mspec :tag)
The methods should ignore their argument and return a predicate/spec:
(defmethod mspec :int [_] (s/keys :req-un [::tag ::i]))
retag is used during generation to retag generated values with
matching tags. retag can either be a keyword, at which key the
dispatch-tag will be assoc'ed, or a fn of generated value and
dispatch-tag that should return an appropriately retagged value.
Note that because the tags themselves comprise an open set,
the tag key spec cannot enumerate the values, but can e.g.
test for keyword?.
Note also that the dispatch values of the multimethod will be
included in the path, i.e. in reporting and gen overrides, even
though those values are not evident in the spec.
"
[mm retag]
`(multi-spec-impl '~(res mm) (var ~mm) ~retag))
(defmacro keys
"Creates and returns a map validating spec. :req and :opt are both
vectors of namespaced-qualified keywords. The validator will ensure
the :req keys are present. The :opt keys serve as documentation and
may be used by the generator.
The :req key vector supports 'and' and 'or' for key groups:
(s/keys :req [::x ::y (or ::secret (and ::user ::pwd))] :opt [::z])
There are also -un versions of :req and :opt. These allow
you to connect unqualified keys to specs. In each case, fully
qualfied keywords are passed, which name the specs, but unqualified
keys (with the same name component) are expected and checked at
conform-time, and generated during gen:
(s/keys :req-un [:my.ns/x :my.ns/y])
The above says keys :x and :y are required, and will be validated
and generated by specs (if they exist) named :my.ns/x :my.ns/y
respectively.
In addition, the values of *all* namespace-qualified keys will be validated
(and possibly destructured) by any registered specs. Note: there is
no support for inline value specification, by design.
Optionally takes :gen generator-fn, which must be a fn of no args that
returns a test.check generator."
[& {:keys [req req-un opt opt-un gen]}]
(let [unk #(-> % name keyword)
req-keys (filterv keyword? (flatten req))
req-un-specs (filterv keyword? (flatten req-un))
_ (c/assert (every? #(c/and (keyword? %) (namespace %)) (concat req-keys req-un-specs opt opt-un))
"all keys must be namespace-qualified keywords")
req-specs (into req-keys req-un-specs)
req-keys (into req-keys (map unk req-un-specs))
opt-keys (into (vec opt) (map unk opt-un))
opt-specs (into (vec opt) opt-un)
parse-req (fn [rk f]
(map (fn [x]
(if (keyword? x)
`#(contains? % ~(f x))
(let [gx (gensym)]
`(fn* [~gx]
~(walk/postwalk
(fn [y] (if (keyword? y) `(contains? ~gx ~(f y)) y))
x)))))
rk))
pred-exprs [`map?]
pred-exprs (into pred-exprs (parse-req req identity))
pred-exprs (into pred-exprs (parse-req req-un unk))
pred-forms (walk/postwalk res pred-exprs)]
;; `(map-spec-impl ~req-keys '~req ~opt '~pred-forms ~pred-exprs ~gen)
`(map-spec-impl {:req '~req :opt '~opt :req-un '~req-un :opt-un '~opt-un
:req-keys '~req-keys :req-specs '~req-specs
:opt-keys '~opt-keys :opt-specs '~opt-specs
:pred-forms '~pred-forms
:pred-exprs ~pred-exprs
:gfn ~gen})))
(defmacro or
"Takes key+pred pairs, e.g.
(s/or :even even? :small #(< % 42))
Returns a destructuring spec that returns a map entry containing the
key of the first matching pred and the corresponding value. Thus the
'key' and 'val' functions can be used to refer generically to the
components of the tagged return."
[& key-pred-forms]
(let [pairs (partition 2 key-pred-forms)
keys (mapv first pairs)
pred-forms (mapv second pairs)
pf (mapv res pred-forms)]
(c/assert (c/and (even? (count key-pred-forms)) (every? keyword? keys)) "spec/or expects k1 p1 k2 p2..., where ks are keywords")
`(or-spec-impl ~keys '~pf ~pred-forms nil)))
(defmacro and
"Takes predicate/spec-forms, e.g.
(s/and even? #(< % 42))
Returns a spec that returns the conformed value. Successive
conformed values propagate through rest of predicates."
[& pred-forms]
`(and-spec-impl '~(mapv res pred-forms) ~(vec pred-forms) nil))
(defmacro merge
"Takes map-validating specs (e.g. 'keys' specs) and
returns a spec that returns a conformed map satisfying all of the
specs. Successive conformed values propagate through rest of
predicates. Unlike 'and', merge can generate maps satisfying the
union of the predicates."
[& pred-forms]
`(merge-spec-impl '~(mapv res pred-forms) ~(vec pred-forms) nil))
(defmacro every
"takes a pred and validates collection elements against that pred.
Note that 'every' does not do exhaustive checking, rather it samples
*coll-check-limit* elements. Nor (as a result) does it do any
conforming of elements. 'explain' will report at most *coll-error-limit*
problems. Thus 'every' should be suitable for potentially large
collections.
Takes several kwargs options that further constrain the collection:
:kind - a pred/spec that the collection type must satisfy, e.g. vector?
(default nil) Note that if :kind is specified and :into is
not, this pred must generate in order for every to generate.
:count - specifies coll has exactly this count (default nil)
:min-count, :max-count - coll has count (<= min-count count max-count) (defaults nil)
:distinct - all the elements are distinct (default nil)
And additional args that control gen
:gen-max - the maximum coll size to generate (default 20)
:into - one of [], (), {}, #{} - the default collection to generate into
(default: empty coll as generated by :kind pred if supplied, else [])
Optionally takes :gen generator-fn, which must be a fn of no args that
returns a test.check generator
See also - coll-of, every-kv
"
[pred & {:keys [into kind count max-count min-count distinct gen-max gen] :as opts}]
(let [nopts (-> opts (dissoc :gen) (assoc ::kind-form `'~(res (:kind opts))))]
`(every-impl '~pred ~pred ~nopts ~gen)))
(defmacro every-kv
"like 'every' but takes separate key and val preds and works on associative collections.
Same options as 'every', :into defaults to {}
See also - map-of"
[kpred vpred & opts]
`(every (tuple ~kpred ~vpred) ::kfn (fn [i# v#] (nth v# 0)) :into {} ~@opts))
(defmacro coll-of
"Returns a spec for a collection of items satisfying pred. Unlike
'every', coll-of will exhaustively conform every value.
Same options as 'every'. conform will produce a collection
corresponding to :into if supplied, else will match the input collection,
avoiding rebuilding when possible.
See also - every, map-of"
[pred & opts]
`(every ~pred ::conform-all true ~@opts))
(defmacro map-of
"Returns a spec for a map whose keys satisfy kpred and vals satisfy
vpred. Unlike 'every-kv', map-of will exhaustively conform every
value.
Same options as 'every', :kind defaults to map?, with the addition of:
:conform-keys - conform keys as well as values (default false)
See also - every-kv"
[kpred vpred & opts]
`(every-kv ~kpred ~vpred ::conform-all true :kind map? ~@opts))
(defmacro *
"Returns a regex op that matches zero or more values matching
pred. Produces a vector of matches iff there is at least one match"
[pred-form]
`(rep-impl '~(res pred-form) ~pred-form))
(defmacro +
"Returns a regex op that matches one or more values matching
pred. Produces a vector of matches"
[pred-form]
`(rep+impl '~(res pred-form) ~pred-form))
(defmacro ?
"Returns a regex op that matches zero or one value matching
pred. Produces a single value (not a collection) if matched."
[pred-form]
`(maybe-impl ~pred-form '~pred-form))
(defmacro alt
"Takes key+pred pairs, e.g.
(s/alt :even even? :small #(< % 42))
Returns a regex op that returns a map entry containing the key of the
first matching pred and the corresponding value. Thus the
'key' and 'val' functions can be used to refer generically to the
components of the tagged return"
[& key-pred-forms]
(let [pairs (partition 2 key-pred-forms)
keys (mapv first pairs)
pred-forms (mapv second pairs)
pf (mapv res pred-forms)]
(c/assert (c/and (even? (count key-pred-forms)) (every? keyword? keys)) "alt expects k1 p1 k2 p2..., where ks are keywords")
`(alt-impl ~keys ~pred-forms '~pf)))
(defmacro cat
"Takes key+pred pairs, e.g.
(s/cat :e even? :o odd?)
Returns a regex op that matches (all) values in sequence, returning a map
containing the keys of each pred and the corresponding value."
[& key-pred-forms]
(let [pairs (partition 2 key-pred-forms)
keys (mapv first pairs)
pred-forms (mapv second pairs)
pf (mapv res pred-forms)]
;;(prn key-pred-forms)
(c/assert (c/and (even? (count key-pred-forms)) (every? keyword? keys)) "cat expects k1 p1 k2 p2..., where ks are keywords")
`(cat-impl ~keys ~pred-forms '~pf)))
(defmacro &
"takes a regex op re, and predicates. Returns a regex-op that consumes
input as per re but subjects the resulting value to the
conjunction of the predicates, and any conforming they might perform."
[re & preds]
(let [pv (vec preds)]
`(amp-impl ~re ~pv '~(mapv res pv))))
(defmacro conformer
"takes a predicate function with the semantics of conform i.e. it should return either a
(possibly converted) value or :clojure.spec/invalid, and returns a
spec that uses it as a predicate/conformer. Optionally takes a
second fn that does unform of result of first"
([f] `(spec-impl '~f ~f nil true))
([f unf] `(spec-impl '~f ~f nil true ~unf)))
(defmacro fspec
"takes :args :ret and (optional) :fn kwargs whose values are preds
and returns a spec whose conform/explain take a fn and validates it
using generative testing. The conformed value is always the fn itself.
See 'fdef' for a single operation that creates an fspec and
registers it, as well as a full description of :args, :ret and :fn
fspecs can generate functions that validate the arguments and
fabricate a return value compliant with the :ret spec, ignoring
the :fn spec if present.
Optionally takes :gen generator-fn, which must be a fn of no args
that returns a test.check generator."
[& {:keys [args ret fn gen]}]
`(fspec-impl (spec ~args) '~(res args)
(spec ~ret) '~(res ret)
(spec ~fn) '~(res fn) ~gen))
(defmacro tuple
"takes one or more preds and returns a spec for a tuple, a vector
where each element conforms to the corresponding pred. Each element
will be referred to in paths using its ordinal."
[& preds]
(c/assert (not (empty? preds)))
`(tuple-impl '~(mapv res preds) ~(vec preds)))
(defn- macroexpand-check
[v args]
(let [fn-spec (get-spec v)]
(when-let [arg-spec (:args fn-spec)]
(when (= ::invalid (conform arg-spec args))
(let [ed (assoc (explain-data* arg-spec [:args]
(if-let [name (spec-name arg-spec)] [name] []) [] args)
::args args)]
(throw (ArgumentException.
(str
"Call to " (->sym v) " did not conform to spec:\n"
(with-out-str (explain-out ed))))))))))
(defmacro fdef
"Takes a symbol naming a function, and one or more of the following:
:args A regex spec for the function arguments as they were a list to be
passed to apply - in this way, a single spec can handle functions with
multiple arities
:ret A spec for the function's return value
:fn A spec of the relationship between args and ret - the
value passed is {:args conformed-args :ret conformed-ret} and is
expected to contain predicates that relate those values
Qualifies fn-sym with resolve, or using *ns* if no resolution found.
Registers an fspec in the global registry, where it can be retrieved
by calling get-spec with the var or fully-qualified symbol.
Once registered, function specs are included in doc, checked by
instrument, tested by the runner clojure.spec.test/run-tests, and (if
a macro) used to explain errors during macroexpansion.
Note that :fn specs require the presence of :args and :ret specs to
conform values, and so :fn specs will be ignored if :args or :ret
are missing.
Returns the qualified fn-sym.
For example, to register function specs for the symbol function:
(s/fdef clojure.core/symbol
:args (s/alt :separate (s/cat :ns string? :n string?)
:str string?
:sym symbol?)
:ret symbol?)"
[fn-sym & specs]
`(clojure.spec/def ~fn-sym (clojure.spec/fspec ~@specs)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; impl ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- recur-limit? [rmap id path k]
(c/and (> (get rmap id) (::recursion-limit rmap))
(contains? (set path) k)))
(defn- inck [m k]
(assoc m k (inc (c/or (get m k) 0))))
(defn- dt
([pred x form] (dt pred x form nil))
([pred x form cpred?]
(if pred
(if-let [spec (the-spec pred)]
(conform spec x)
(if (ifn? pred)
(if cpred?
(pred x)
(if (pred x) x ::invalid))
(throw (Exception. (str (pr-str form) " is not a fn, expected predicate fn")))))
x)))
(defn valid?
"Helper function that returns true when x is valid for spec."
([spec x]
(not= ::invalid (dt spec x ::unknown)))
([spec x form]
(not= ::invalid (dt spec x form))))
(defn- explain-1 [form pred path via in v]
;;(prn {:form form :pred pred :path path :in in :v v})
(let [pred (maybe-spec pred)]
(if (spec? pred)
(explain* pred path (if-let [name (spec-name pred)] (conj via name) via) in v)
[{:path path :pred (abbrev form) :val v :via via :in in}])))
(defn ^:skip-wiki map-spec-impl
"Do not call this directly, use 'spec' with a map argument"
[{:keys [req-un opt-un pred-exprs opt-keys req-specs req req-keys opt-specs pred-forms opt gfn]
:as argm}]
(let [keys-pred (apply every-pred pred-exprs)
k->s (zipmap (concat req-keys opt-keys) (concat req-specs opt-specs))
keys->specs #(c/or (k->s %) %)
;; id (java.util.UUID/randomUUID)
id (System.Guid.) ;; maaaaybe?
]
(reify
clojure.lang.IFn
(invoke [this x] (valid? this x))
Spec
(conform* [_ m]
(if (keys-pred m)
(let [reg (registry)]
(loop [ret m, [k & ks :as keys] (c/keys m)]
(if keys
(if (contains? reg (keys->specs k))
(let [v (get m k)
cv (conform (keys->specs k) v)]
(if (= cv ::invalid)
::invalid
(recur (if (identical? cv v) ret (assoc ret k cv))
ks)))
(recur ret ks))
ret)))
::invalid))
(unform* [_ m]
(let [reg (registry)]
(loop [ret m, [k & ks :as keys] (c/keys m)]
(if keys
(if (contains? reg (keys->specs k))
(let [cv (get m k)
v (unform (keys->specs k) cv)]
(recur (if (identical? cv v) ret (assoc ret k v))
ks))
(recur ret ks))
ret))))
(explain* [_ path via in x]
(if-not (map? x)
[{:path path :pred 'map? :val x :via via :in in}]
(let [reg (registry)]
(apply concat
(when-let [probs (->> (map (fn [pred form] (when-not (pred x) (abbrev form)))
pred-exprs pred-forms)
(keep identity)
seq)]
(map
#(identity {:path path :pred % :val x :via via :in in})
probs))
(map (fn [[k v]]
(when-not (c/or (not (contains? reg (keys->specs k)))
(valid? (keys->specs k) v k))
(explain-1 (keys->specs k) (keys->specs k) (conj path k) via (conj in k) v)))
(seq x))))))
(gen* [_ overrides path rmap]
(if gfn
(gfn)
(let [rmap (inck rmap id)
gen (fn [k s] (gensub s overrides (conj path k) rmap k))
ogen (fn [k s]
(when-not (recur-limit? rmap id path k)
[k (gen/delay (gensub s overrides (conj path k) rmap k))]))
req-gens (map gen req-keys req-specs)
opt-gens (remove nil? (map ogen opt-keys opt-specs))]
(when (every? identity (concat req-gens opt-gens))
(let [reqs (zipmap req-keys req-gens)
opts (into {} opt-gens)]
(gen/bind (gen/choose 0 (count opts))
#(let [args (concat (seq reqs) (when (seq opts) (shuffle (seq opts))))]
(->> args
(take (c/+ % (count reqs)))
(apply concat)
(apply gen/hash-map)))))))))
(with-gen* [_ gfn] (map-spec-impl (assoc argm :gfn gfn)))
(describe* [_] (cons `keys
(cond-> []
req (conj :req req)
opt (conj :opt opt)
req-un (conj :req-un req-un)
opt-un (conj :opt-un opt-un)))))))
(defn ^:skip-wiki spec-impl
"Do not call this directly, use 'spec'"
([form pred gfn cpred?] (spec-impl form pred gfn cpred? nil))
([form pred gfn cpred? unc]
(cond
(spec? pred) (cond-> pred gfn (with-gen gfn))
(regex? pred) (regex-spec-impl pred gfn)
(named? pred) (cond-> (the-spec pred) gfn (with-gen gfn))
:else
(reify
Spec
(conform* [_ x] (dt pred x form cpred?))
(unform* [_ x] (if cpred?
(if unc
(unc x)
(throw (InvalidOperationException. "no unform fn for conformer")))
x))
(explain* [_ path via in x]
(when (= ::invalid (dt pred x form cpred?))
[{:path path :pred (abbrev form) :val x :via via :in in}]))
(gen* [_ _ _ _] (if gfn
(gfn)
(gen/gen-for-pred pred)))
(with-gen* [_ gfn] (spec-impl form pred gfn cpred?))
(describe* [_] form)))))
(defn ^:skip-wiki multi-spec-impl
"Do not call this directly, use 'multi-spec'"
([form mmvar retag] (multi-spec-impl form mmvar retag nil))
([form mmvar retag gfn]
(let [id (System.Guid.)
predx #(let [^clojure.lang.MultiFn mm @mmvar]
(c/and (contains? (methods mm)
((.dispatchFn mm) %))
(mm %)))
dval #((.dispatchFn ^clojure.lang.MultiFn @mmvar) %)
tag (if (keyword? retag)
#(assoc %1 retag %2)
retag)]
(reify
Spec
(conform* [_ x] (if-let [pred (predx x)]
(dt pred x form)
::invalid))
(unform* [_ x] (if-let [pred (predx x)]
(unform pred x)
(throw (InvalidOperationException. (str "No method of: " form " for dispatch value: " (dval x))))))
(explain* [_ path via in x]
(let [dv (dval x)
path (conj path dv)]
(if-let [pred (predx x)]
(explain-1 form pred path via in x)
[{:path path :pred (abbrev form) :val x :reason "no method" :via via :in in}])))
(gen* [_ overrides path rmap]
(if gfn
(gfn)
(let [gen (fn [[k f]]
(let [p (f nil)]
(let [rmap (inck rmap id)]
(when-not (recur-limit? rmap id path k)
(gen/delay
(gen/fmap
#(tag % k)
(gensub p overrides (conj path k) rmap (list 'method form k))))))))
gs (->> (methods @mmvar)
(remove (fn [[k]] (= k ::invalid)))
(map gen)
(remove nil?))]
(when (every? identity gs)
(gen/one-of gs)))))
(with-gen* [_ gfn] (multi-spec-impl form mmvar retag gfn))
(describe* [_] `(multi-spec ~form))))))
(defn ^:skip-wiki tuple-impl
"Do not call this directly, use 'tuple'"
([forms preds] (tuple-impl forms preds nil))
([forms preds gfn]
(reify
Spec
(conform* [_ x]
(if-not (c/and (vector? x)
(= (count x) (count preds)))
::invalid
(loop [ret x, i 0]
(if (= i (count x))
ret
(let [v (x i)
cv (dt (preds i) v (forms i))]
(if (= ::invalid cv)
::invalid
(recur (if (identical? cv v) ret (assoc ret i cv))
(inc i))))))))
(unform* [_ x]
(c/assert (c/and (vector? x)
(= (count x) (count preds))))
(loop [ret x, i 0]
(if (= i (count x))
ret
(let [cv (x i)
v (unform (preds i) cv)]
(recur (if (identical? cv v) ret (assoc ret i v))
(inc i))))))
(explain* [_ path via in x]
(cond
(not (vector? x))
[{:path path :pred 'vector? :val x :via via :in in}]
(not= (count x) (count preds))
[{:path path :pred `(= (count ~'%) ~(count preds)) :val x :via via :in in}]
:else
(apply concat
(map (fn [i form pred]
(let [v (x i)]
(when-not (valid? pred v)
(explain-1 form pred (conj path i) via (conj in i) v))))
(range (count preds)) forms preds))))
(gen* [_ overrides path rmap]
(if gfn
(gfn)
(let [gen (fn [i p f]
(gensub p overrides (conj path i) rmap f))
gs (map gen (range (count preds)) preds forms)]
(when (every? identity gs)
(apply gen/tuple gs)))))
(with-gen* [_ gfn] (tuple-impl forms preds gfn))
(describe* [_] `(tuple ~@forms)))))
(defn- tagged-ret [tag ret]
(clojure.lang.MapEntry. tag ret))
(defn ^:skip-wiki or-spec-impl
"Do not call this directly, use 'or'"
[keys forms preds gfn]
(let [id (System.Guid.)
kps (zipmap keys preds)
cform (fn [x]
(loop [i 0]
(if (< i (count preds))
(let [pred (preds i)]
(let [ret (dt pred x (nth forms i))]
(if (= ::invalid ret)
(recur (inc i))
(tagged-ret (keys i) ret))))
::invalid)))]
(reify
Spec
(conform* [_ x] (cform x))
(unform* [_ [k x]] (unform (kps k) x))
(explain* [this path via in x]
(when-not (valid? this x)
(apply concat
(map (fn [k form pred]
(when-not (valid? pred x)
(explain-1 form pred (conj path k) via in x)))
keys forms preds))))
(gen* [_ overrides path rmap]
(if gfn
(gfn)
(let [gen (fn [k p f]
(let [rmap (inck rmap id)]
(when-not (recur-limit? rmap id path k)
(gen/delay
(gensub p overrides (conj path k) rmap f)))))
gs (remove nil? (map gen keys preds forms))]
(when-not (empty? gs)
(gen/one-of gs)))))
(with-gen* [_ gfn] (or-spec-impl keys forms preds gfn))
(describe* [_] `(or ~@(mapcat vector keys forms))))))
(defn- and-preds [x preds forms]
(loop [ret x
[pred & preds] preds
[form & forms] forms]
(if pred
(let [nret (dt pred ret form)]
(if (= ::invalid nret)
::invalid
;;propagate conformed values
(recur nret preds forms)))
ret)))
(defn- explain-pred-list
[forms preds path via in x]
(loop [ret x
[form & forms] forms
[pred & preds] preds]
(when pred
(let [nret (dt pred ret form)]
(if (not= ::invalid nret)
(recur nret forms preds)
(explain-1 form pred path via in ret))))))
(defn ^:skip-wiki and-spec-impl
"Do not call this directly, use 'and'"
[forms preds gfn]
(reify
Spec
(conform* [_ x] (and-preds x preds forms))
(unform* [_ x] (reduce #(unform %2 %1) x (reverse preds)))
(explain* [_ path via in x] (explain-pred-list forms preds path via in x))
(gen* [_ overrides path rmap] (if gfn (gfn) (gensub (first preds) overrides path rmap (first forms))))
(with-gen* [_ gfn] (and-spec-impl forms preds gfn))
(describe* [_] `(and ~@forms))))
(defn ^:skip-wiki merge-spec-impl
"Do not call this directly, use 'merge'"
[forms preds gfn]
(reify
Spec
(conform* [_ x] (let [ms (map #(dt %1 x %2) preds forms)]
(if (some #{::invalid} ms)
::invalid
(apply c/merge ms))))
(unform* [_ x] (apply c/merge (map #(unform % x) (reverse preds))))
(explain* [_ path via in x]
(apply concat
(map #(explain-1 %1 %2 path via in x)
forms preds)))
(gen* [_ overrides path rmap]
(if gfn
(gfn)
(gen/fmap
#(apply c/merge %)
(apply gen/tuple (map #(gensub %1 overrides path rmap %2)
preds forms)))))
(with-gen* [_ gfn] (merge-spec-impl forms preds gfn))
(describe* [_] `(merge ~@forms))))
(defn- coll-prob [x kfn kform distinct count min-count max-count
path via in]
(let [pred (c/or kfn coll?)
kform (c/or kform `coll?)]
(cond
(not (valid? pred x))
(explain-1 kform pred path via in x)
(c/and distinct (not (empty? x)) (not (apply distinct? x)))
[{:path path :pred 'distinct? :val x :via via :in in}]
(c/and count (not= count (bounded-count count x)))
[{:path path :pred `(= ~count (c/count ~'%)) :val x :via via :in in}]
(c/and (c/or min-count max-count)
(not (<= (c/or min-count 0)
(bounded-count (if max-count (inc max-count) min-count) x)
(c/or max-count System.Int32/MaxValue))))
[{:path path :pred `(<= ~(c/or min-count 0) (c/count ~'%) ~(c/or max-count 'System.Int32/MaxValue)) :val x :via via :in in}])))
(defn ^:skip-wiki every-impl
"Do not call this directly, use 'every', 'every-kv', 'coll-of' or 'map-of'"
([form pred opts] (every-impl form pred opts nil))
([form pred {gen-into :into
:keys [kind ::kind-form count max-count min-count distinct gen-max ::kfn
conform-keys ::conform-all]
:or {gen-max 20}
:as opts}
gfn]
(let [conform-into gen-into
check? #(valid? pred %)
kfn (c/or kfn (fn [i v] i))
addcv (fn [ret i v cv] (conj ret cv))
cfns (fn [x]
;;returns a tuple of [init add complete] fns
(cond
(c/and (vector? x) (c/or (not conform-into) (vector? conform-into)))
[identity
(fn [ret i v cv]
(if (identical? v cv)
ret
(assoc ret i cv)))
identity]
(c/and (map? x) (c/or (c/and kind (not conform-into)) (map? conform-into)))
[(if conform-keys empty identity)
(fn [ret i v cv]
(if (c/and (identical? v cv) (not conform-keys))
ret
(assoc ret (nth (if conform-keys cv v) 0) (nth cv 1))))
identity]
(c/or (list? conform-into) (c/and (not conform-into) (list? x)))
[(constantly ()) addcv reverse]
:else [#(empty (c/or conform-into %)) addcv identity]))]
(reify
Spec
(conform* [_ x]
(cond
(coll-prob x kind kind-form distinct count min-count max-count
nil nil nil)
::invalid
conform-all
(let [[init add complete] (cfns x)]
(loop [ret (init x), i 0, [v & vs :as vseq] (seq x)]
(if vseq
(let [cv (dt pred v nil)]
(if (= ::invalid cv)
::invalid
(recur (add ret i v cv) (inc i) vs)))
(complete ret))))
:else
(if (indexed? x)
(let [step (max 1 (long (/ (c/count x) *coll-check-limit*)))]
(loop [i 0]
(if (>= i (c/count x))
x
(if (check? (nth x i))
(recur (c/+ i step))
::invalid))))
(c/or (c/and (every? check? (take *coll-check-limit* x)) x)
::invalid))))
(unform* [_ x] x)
(explain* [_ path via in x]
(c/or (coll-prob x kind kind-form distinct count min-count max-count
path via in)
(apply concat
((if conform-all identity (partial take *coll-error-limit*))
(keep identity
(map (fn [i v]
(let [k (kfn i v)]
(when-not (check? v)
(let [prob (explain-1 form pred path via (conj in k) v)]
prob))))
(range) x))))))
(gen* [_ overrides path rmap]
(if gfn
(gfn)
(let [pgen (gensub pred overrides path rmap form)]
(gen/bind
(cond
gen-into (gen/return (empty gen-into))
kind (gen/fmap #(if (empty? %) % (empty %))
(gensub kind overrides path rmap form))
:else (gen/return []))
(fn [init]
(gen/fmap
#(if (vector? init) % (into init %))
(cond
distinct
(if count
(gen/vector-distinct pgen {:num-elements count :max-tries 100})
(gen/vector-distinct pgen {:min-elements (c/or min-count 0)
:max-elements (c/or max-count (max gen-max (c/* 2 (c/or min-count 0))))
:max-tries 100}))
count
(gen/vector pgen count)
(c/or min-count max-count)
(gen/vector pgen (c/or min-count 0) (c/or max-count (max gen-max (c/* 2 (c/or min-count 0)))))
:else
(gen/vector pgen 0 gen-max))))))))
(with-gen* [_ gfn] (every-impl form pred opts gfn))
(describe* [_] `(every ~form ~@(mapcat identity opts)))))))
;;;;;;;;;;;;;;;;;;;;;;; regex ;;;;;;;;;;;;;;;;;;;
;;See:
;; http://matt.might.net/articles/implementation-of-regular-expression-matching-in-scheme-with-derivatives/
;; http://www.ccs.neu.edu/home/turon/re-deriv.pdf
;;ctors
(defn- accept [x] {::op ::accept :ret x})
(defn- accept? [{:keys [::op]}]
(= ::accept op))
(defn- pcat* [{[p1 & pr :as ps] :ps, [k1 & kr :as ks] :ks, [f1 & fr :as forms] :forms, ret :ret, rep+ :rep+}]
(when (every? identity ps)
(if (accept? p1)
(let [rp (:ret p1)
ret (conj ret (if ks {k1 rp} rp))]
(if pr
(pcat* {:ps pr :ks kr :forms fr :ret ret})
(accept ret)))
{::op ::pcat, :ps ps, :ret ret, :ks ks, :forms forms :rep+ rep+})))
(defn- pcat [& ps] (pcat* {:ps ps :ret []}))
(defn ^:skip-wiki cat-impl
"Do not call this directly, use 'cat'"
[ks ps forms]
(pcat* {:ks ks, :ps ps, :forms forms, :ret {}}))
(defn- rep* [p1 p2 ret splice form]
(when p1
(let [r {::op ::rep, :p2 p2, :splice splice, :forms form :id (System.Guid.)}]
(if (accept? p1)
(assoc r :p1 p2 :ret (conj ret (:ret p1)))
(assoc r :p1 p1, :ret ret)))))
(defn ^:skip-wiki rep-impl
"Do not call this directly, use '*'"
[form p] (rep* p p [] false form))
(defn ^:skip-wiki rep+impl
"Do not call this directly, use '+'"
[form p]
(pcat* {:ps [p (rep* p p [] true form)] :forms `[~form (* ~form)] :ret [] :rep+ form}))
(defn ^:skip-wiki amp-impl
"Do not call this directly, use '&'"
[re preds pred-forms]
{::op ::amp :p1 re :ps preds :forms pred-forms})
(defn- filter-alt [ps ks forms f]
(if (c/or ks forms)
(let [pks (->> (map vector ps
(c/or (seq ks) (repeat nil))
(c/or (seq forms) (repeat nil)))
(filter #(-> % first f)))]
[(seq (map first pks)) (when ks (seq (map second pks))) (when forms (seq (map #(nth % 2) pks)))])
[(seq (filter f ps)) ks forms]))
(defn- alt* [ps ks forms]
(let [[[p1 & pr :as ps] [k1 :as ks] forms] (filter-alt ps ks forms identity)]
(when ps
(let [ret {::op ::alt, :ps ps, :ks ks :forms forms}]
(if (nil? pr)
(if k1
(if (accept? p1)
(accept (tagged-ret k1 (:ret p1)))
ret)
p1)
ret)))))
(defn- alts [& ps] (alt* ps nil nil))
(defn- alt2 [p1 p2] (if (c/and p1 p2) (alts p1 p2) (c/or p1 p2)))
(defn ^:skip-wiki alt-impl
"Do not call this directly, use 'alt'"
[ks ps forms] (assoc (alt* ps ks forms) :id (System.Guid.)))
(defn ^:skip-wiki maybe-impl
"Do not call this directly, use '?'"
[p form] (assoc (alt* [p (accept ::nil)] nil [form ::nil]) :maybe form))
(defn- noret? [p1 pret]
(c/or (= pret ::nil)
(c/and (#{::rep ::pcat} (::op (reg-resolve! p1))) ;;hrm, shouldn't know these
(empty? pret))
nil))
(declare preturn)
(defn- accept-nil? [p]
(let [{:keys [::op ps p1 p2 forms] :as p} (reg-resolve! p)]
(case op
::accept true
nil nil
::amp (c/and (accept-nil? p1)
(c/or (noret? p1 (preturn p1))
(let [ret (-> (preturn p1) (and-preds ps (next forms)))]
(not= ret ::invalid))))
::rep (c/or (identical? p1 p2) (accept-nil? p1))
::pcat (every? accept-nil? ps)
::alt (c/some accept-nil? ps))))
(declare add-ret)
(defn- preturn [p]
(let [{[p0 & pr :as ps] :ps, [k :as ks] :ks, :keys [::op p1 ret forms] :as p} (reg-resolve! p)]
(case op
::accept ret
nil nil
::amp (let [pret (preturn p1)]
(if (noret? p1 pret)
::nil
(and-preds pret ps forms)))
::rep (add-ret p1 ret k)
::pcat (add-ret p0 ret k)
::alt (let [[[p0] [k0]] (filter-alt ps ks forms accept-nil?)
r (if (nil? p0) ::nil (preturn p0))]
(if k0 (tagged-ret k0 r) r)))))
(defn- op-unform [p x]
;;(prn {:p p :x x})
(let [{[p0 & pr :as ps] :ps, [k :as ks] :ks, :keys [::op p1 ret forms rep+ maybe] :as p} (reg-resolve! p)
kps (zipmap ks ps)]
(case op
::accept [ret]
nil [(unform p x)]
::amp (let [px (reduce #(unform %2 %1) x (reverse ps))]
(op-unform p1 px))
::rep (mapcat #(op-unform p1 %) x)
::pcat (if rep+
(mapcat #(op-unform p0 %) x)
(mapcat (fn [k]
(when (contains? x k)
(op-unform (kps k) (get x k))))
ks))
::alt (if maybe
[(unform p0 x)]
(let [[k v] x]
(op-unform (kps k) v))))))
(defn- add-ret [p r k]
(let [{:keys [::op ps splice] :as p} (reg-resolve! p)
prop #(let [ret (preturn p)]
(if (empty? ret) r ((if splice into conj) r (if k {k ret} ret))))]
(case op
nil r
(::alt ::accept ::amp)
(let [ret (preturn p)]
;;(prn {:ret ret})
(if (= ret ::nil) r (conj r (if k {k ret} ret))))
(::rep ::pcat) (prop))))
(defn- deriv
[p x]
(let [{[p0 & pr :as ps] :ps, [k0 & kr :as ks] :ks, :keys [::op p1 p2 ret splice forms] :as p} (reg-resolve! p)]
(when p
(case op
::accept nil
nil (let [ret (dt p x p)]
(when-not (= ::invalid ret) (accept ret)))
::amp (when-let [p1 (deriv p1 x)]
(if (= ::accept (::op p1))
(let [ret (-> (preturn p1) (and-preds ps (next forms)))]
(when-not (= ret ::invalid)
(accept ret)))
(amp-impl p1 ps forms)))
::pcat (alt2 (pcat* {:ps (cons (deriv p0 x) pr), :ks ks, :forms forms, :ret ret})
(when (accept-nil? p0) (deriv (pcat* {:ps pr, :ks kr, :forms (next forms), :ret (add-ret p0 ret k0)}) x)))
::alt (alt* (map #(deriv % x) ps) ks forms)
::rep (alt2 (rep* (deriv p1 x) p2 ret splice forms)
(when (accept-nil? p1) (deriv (rep* p2 p2 (add-ret p1 ret nil) splice forms) x)))))))
(defn- op-describe [p]
(let [{:keys [::op ps ks forms splice p1 rep+ maybe] :as p} (reg-resolve! p)]
;;(prn {:op op :ks ks :forms forms :p p})
(when p
(case op
::accept nil
nil p
::amp (list* 'clojure.spec/& (op-describe p1) forms)
::pcat (if rep+
(list `+ rep+)
(cons `cat (mapcat vector (c/or (seq ks) (repeat :_)) forms)))
::alt (if maybe
(list `? maybe)
(cons `alt (mapcat vector ks forms)))
::rep (list (if splice `+ `*) forms)))))
(defn- op-explain [form p path via in input]
;;(prn {:form form :p p :path path :input input})
(let [[x :as input] input
{:keys [::op ps ks forms splice p1 p2] :as p} (reg-resolve! p)
via (if-let [name (spec-name p)] (conj via name) via)
insufficient (fn [path form]
[{:path path
:reason "Insufficient input"
:pred (abbrev form)
:val ()
:via via
:in in}])]
(when p
(case op
::accept nil
nil (if (empty? input)
(insufficient path form)
(explain-1 form p path via in x))
::amp (if (empty? input)
(if (accept-nil? p1)
(explain-pred-list forms ps path via in (preturn p1))
(insufficient path (op-describe p1)))
(if-let [p1 (deriv p1 x)]
(explain-pred-list forms ps path via in (preturn p1))
(op-explain (op-describe p1) p1 path via in input)))
::pcat (let [pkfs (map vector
ps
(c/or (seq ks) (repeat nil))
(c/or (seq forms) (repeat nil)))
[pred k form] (if (= 1 (count pkfs))
(first pkfs)
(first (remove (fn [[p]] (accept-nil? p)) pkfs)))
path (if k (conj path k) path)
form (c/or form (op-describe pred))]
(if (c/and (empty? input) (not pred))
(insufficient path form)
(op-explain form pred path via in input)))
::alt (if (empty? input)
(insufficient path (op-describe p))
(apply concat
(map (fn [k form pred]
(op-explain (c/or form (op-describe pred))
pred
(if k (conj path k) path)
via
in
input))
(c/or (seq ks) (repeat nil))
(c/or (seq forms) (repeat nil))
ps)))
::rep (op-explain (if (identical? p1 p2)
forms
(op-describe p1))
p1 path via in input)))))
(defn- re-gen [p overrides path rmap f]
;;(prn {:op op :ks ks :forms forms})
(let [{:keys [::op ps ks p1 p2 forms splice ret id ::gfn] :as p} (reg-resolve! p)
rmap (if id (inck rmap id) rmap)
ggens (fn [ps ks forms]
(let [gen (fn [p k f]
;;(prn {:k k :path path :rmap rmap :op op :id id})
(when-not (c/and rmap id k (recur-limit? rmap id path k))
(if id
(gen/delay (re-gen p overrides (if k (conj path k) path) rmap (c/or f p)))
(re-gen p overrides (if k (conj path k) path) rmap (c/or f p)))))]
(map gen ps (c/or (seq ks) (repeat nil)) (c/or (seq forms) (repeat nil)))))]
(c/or (when-let [g (get overrides path)]
(case op
(:accept nil) (gen/fmap vector g)
g))
(when gfn
(gfn))
(when p
(case op
::accept (if (= ret ::nil)
(gen/return [])
(gen/return [ret]))
nil (when-let [g (gensub p overrides path rmap f)]
(gen/fmap vector g))
::amp (re-gen p1 overrides path rmap (op-describe p1))
::pcat (let [gens (ggens ps ks forms)]
(when (every? identity gens)
(apply gen/cat gens)))
::alt (let [gens (remove nil? (ggens ps ks forms))]
(when-not (empty? gens)
(gen/one-of gens)))
::rep (if (recur-limit? rmap id [id] id)
(gen/return [])
(when-let [g (re-gen p2 overrides path rmap forms)]
(gen/fmap #(apply concat %)
(gen/vector g)))))))))
(defn- re-conform [p [x & xs :as data]]
;;(prn {:p p :x x :xs xs})
(if (empty? data)
(if (accept-nil? p)
(let [ret (preturn p)]
(if (= ret ::nil)
nil
ret))
::invalid)
(if-let [dp (deriv p x)]
(recur dp xs)
::invalid)))
(defn- re-explain [path via in re input]
(loop [p re [x & xs :as data] input i 0]
;;(prn {:p p :x x :xs xs :re re}) (prn)
(if (empty? data)
(if (accept-nil? p)
nil ;;success
(op-explain (op-describe p) p path via in nil))
(if-let [dp (deriv p x)]
(recur dp xs (inc i))
(if (accept? p)
(if (= (::op p) ::pcat)
(op-explain (op-describe p) p path via (conj in i) (seq data))
[{:path path
:reason "Extra input"
:pred (abbrev (op-describe re))
:val data
:via via
:in (conj in i)}])
(c/or (op-explain (op-describe p) p path via (conj in i) (seq data))
[{:path path
:reason "Extra input"
:pred (abbrev (op-describe p))
:val data
:via via
:in (conj in i)}]))))))
(defn ^:skip-wiki regex-spec-impl
"Do not call this directly, use 'spec' with a regex op argument"
[re gfn]
(reify
Spec
(conform* [_ x]
(if (c/or (nil? x) (coll? x))
(re-conform re (seq x))
::invalid))
(unform* [_ x] (op-unform re x))
(explain* [_ path via in x]
(if (c/or (nil? x) (coll? x))
(re-explain path via in re (seq x))
[{:path path :pred (abbrev (op-describe re)) :val x :via via :in in}]))
(gen* [_ overrides path rmap]
(if gfn
(gfn)
(re-gen re overrides path rmap (op-describe re))))
(with-gen* [_ gfn] (regex-spec-impl re gfn))
(describe* [_] (op-describe re))))
;;;;;;;;;;;;;;;;; HOFs ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- call-valid?
[f specs args]
(let [cargs (conform (:args specs) args)]
(when-not (= cargs ::invalid)
(let [ret (apply f args)
cret (conform (:ret specs) ret)]
(c/and (not= cret ::invalid)
(if (:fn specs)
(valid? (:fn specs) {:args cargs :ret cret})
true))))))
(defn- validate-fn
"returns f if valid, else smallest"
[f specs iters]
(let [g (gen (:args specs))
prop (gen/for-all* [g] #(call-valid? f specs %))]
(let [ret (gen/quick-check iters prop)]
(if-let [[smallest] (-> ret :shrunk :smallest)]
smallest
f))))
(defn ^:skip-wiki fspec-impl
"Do not call this directly, use 'fspec'"
[argspec aform retspec rform fnspec fform gfn]
(let [specs {:args argspec :ret retspec :fn fnspec}]
(reify
clojure.lang.ILookup
(valAt [this k] (get specs k))
(valAt [_ k not-found] (get specs k not-found))
Spec
(conform* [_ f] (if (ifn? f)
(if (identical? f (validate-fn f specs *fspec-iterations*)) f ::invalid)
::invalid))
(unform* [_ f] f)
(explain* [_ path via in f]
(if (ifn? f)
(let [args (validate-fn f specs 100)]
(if (identical? f args) ;;hrm, we might not be able to reproduce
nil
(let [ret (try (apply f args) (catch Exception ;;Throwable
t t))]
(if (instance? Exception ;;Throwable
ret)
;;TODO add exception data
{path {:pred '(apply fn) :val args :reason (.getMessage ^Exception ;;^Throwable
ret) :via via :in in}}
(let [cret (dt retspec ret rform)]
(if (= ::invalid cret)
(explain-1 rform retspec (conj path :ret) via in ret)
(when fnspec
(let [cargs (conform argspec args)]
(explain-1 fform fnspec (conj path :fn) via in {:args cargs :ret cret})))))))))
[{:path path :pred 'ifn? :val f :via via :in in}]))
(gen* [_ overrides _ _] (if gfn
(gfn)
(gen/return
(fn [& args]
(c/assert (valid? argspec args) (with-out-str (explain argspec args)))
(gen/generate (gen retspec overrides))))))
(with-gen* [_ gfn] (fspec-impl argspec aform retspec rform fnspec fform gfn))
(describe* [_] `(fspec :args ~aform :ret ~rform :fn ~fform)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; non-primitives ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(clojure.spec/def ::kvs->map (conformer #(zipmap (map ::k %) (map ::v %)) #(map (fn [[k v]] {::k k ::v v}) %)))
(defmacro keys*
"takes the same arguments as spec/keys and returns a regex op that matches sequences of key/values,
converts them into a map, and conforms that map with a corresponding
spec/keys call:
user=> (s/conform (s/keys :req-un [::a ::c]) {:a 1 :c 2})
{:a 1, :c 2}
user=> (s/conform (s/keys* :req-un [::a ::c]) [:a 1 :c 2])
{:a 1, :c 2}
the resulting regex op can be composed into a larger regex:
user=> (s/conform (s/cat :i1 integer? :m (s/keys* :req-un [::a ::c]) :i2 integer?) [42 :a 1 :c 2 :d 4 99])
{:i1 42, :m {:a 1, :c 2, :d 4}, :i2 99}"
[& kspecs]
`(let [mspec# (keys ~@kspecs)]
(with-gen (clojure.spec/& (* (cat ::k keyword? ::v any?)) ::kvs->map mspec#)
(fn [] (gen/fmap (fn [m#] (apply concat m#)) (gen mspec#))))))
(defmacro nilable
"returns a spec that accepts nil and values satisfiying pred"
[pred]
`(and (or ::nil nil? ::pred ~pred) (conformer second #(if (nil? %) [::nil nil] [::pred %]))))
(defn exercise
"generates a number (default 10) of values compatible with spec and maps conform over them,
returning a sequence of [val conformed-val] tuples. Optionally takes
a generator overrides map as per gen"
([spec] (exercise spec 10))
([spec n] (exercise spec n nil))
([spec n overrides]
(map #(vector % (conform spec %)) (gen/sample (gen spec overrides) n))))
(defn exercise-fn
"exercises the fn named by sym (a symbol) by applying it to
n (default 10) generated samples of its args spec. When fspec is
supplied its arg spec is used, and sym-or-f can be a fn. Returns a
sequence of tuples of [args ret]. "
([sym] (exercise-fn sym 10))
([sym n] (exercise-fn sym n (get-spec sym)))
([sym-or-f n fspec]
(let [f (if (symbol? sym-or-f) (resolve sym-or-f) sym-or-f)]
(for [args (gen/sample (gen (:args fspec)) n)]
[args (apply f args)]))))
(defn inst-in-range?
"Return true if inst at or after start and before end"
[start end inst]
(c/and (inst? inst)
(let [t (inst-ms inst)]
(c/and (<= (inst-ms start) t) (< t (inst-ms end))))))
(defmacro inst-in
"Returns a spec that validates insts in the range from start
(inclusive) to end (exclusive)."
[start end]
`(let [st# (inst-ms ~start)
et# (inst-ms ~end)
mkdate# (fn [d#] (java.util.Date. ^{:tag ~'long} d#))]
(spec (and inst? #(inst-in-range? ~start ~end %))
:gen (fn []
(gen/fmap mkdate#
(gen/large-integer* {:min st# :max et#}))))))
(defn int-in-range?
"Return true if start <= val and val < end"
[start end val]
(c/and int? (<= start val) (< val end)))
(defmacro int-in
"Returns a spec that validates ints in the range from start
(inclusive) to end (exclusive)."
[start end]
`(spec (and int? #(int-in-range? ~start ~end %))
:gen #(gen/large-integer* {:min ~start :max (dec ~end)})))
(defmacro double-in
"Specs a 64-bit floating point number. Options:
:infinite? - whether +/- infinity allowed (default true)
:NaN? - whether NaN allowed (default true)
:min - minimum value (inclusive, default none)
:max - maximum value (inclusive, default none)"
[& {:keys [infinite? NaN? min max]
:or {infinite? true NaN? true}
:as m}]
`(spec (and c/double?
~@(when-not infinite? '[#(not (Double/isInfinite %))])
~@(when-not NaN? '[#(not (Double/isNaN %))])
~@(when max `[#(<= % ~max)])
~@(when min `[#(<= ~min %)]))
:gen #(gen/double* ~m)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; assert ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defonce
^{:dynamic true
:doc "If true, compiler will enable spec asserts, which are then
subject to runtime control via check-asserts? If false, compiler
will eliminate all spec assert overhead. See 'assert'.
Initially set to boolean value of clojure.spec.compile-asserts
system property. Defaults to true."}
*compile-asserts*
(not= "false"
(System.Environment/GetEnvironmentVariable "CLOJURE_SPEC_COMPILE_ASSERTS")
;; (System/getProperty "clojure.spec.compile-asserts")
))
(def ^:private check-spec-asserts-ref
;; janky hack in absence of easier way to modify RT
(atom
;; ;; I guess? see https://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html
;; ;; Without some more work won't "default to true", though
;; (= "true"
;; (System.Environment/GetEnvironmentVariable "CLOJURE_SPEC_COMPILE_ASSERTS"))
true ;; fify
))
(defn check-asserts?
"Returns the value set by check-asserts."
[]
@check-spec-asserts-ref
;;clojure.lang.RT/checkSpecAsserts
)
(defn check-asserts
"Enable or disable spec asserts that have been compiled
with '*compile-asserts*' true. See 'assert'.
Initially set to boolean value of clojure.spec.check-asserts
system property. Defaults to false."
[flag]
(reset! check-spec-asserts-ref flag)
;;(set! (. clojure.lang.RT checkSpecAsserts) flag)
)
(defn assert*
"Do not call this directly, use 'assert'."
[spec x]
(if (valid? spec x)
x
(let [ed (c/merge (assoc (explain-data* spec [] [] [] x)
::failure :assertion-failed))]
(throw (ex-info
(str "Spec assertion failed\n" (with-out-str (explain-out ed)))
ed)))))
(defmacro assert
"spec-checking assert expression. Returns x if x is valid? according
to spec, else throws an ex-info with explain-data plus ::failure of
:assertion-failed.
Can be disabled at either compile time or runtime:
If *compile-asserts* is false at compile time, compiles to x. Defaults
to value of 'clojure.spec.compile-asserts' system property, or true if
not set.
If (check-asserts?) is false at runtime, always returns x. Defaults to
value of 'clojure.spec.check-asserts' system property, or false if not
set. You can toggle check-asserts? with (check-asserts bool)."
[spec x]
(if *compile-asserts*
`(if clojure.lang.RT/checkSpecAsserts
(assert* ~spec ~x)
~x)
x))
|
[
{
"context": " base-context\n {:users [(factory :user, {:email \"john@doe.com\"})]\n :entities [{:name \"Personal\"}]\n :commodi",
"end": 1670,
"score": 0.99989253282547,
"start": 1658,
"tag": "EMAIL",
"value": "john@doe.com"
},
{
"context": "t\n :account-id \"Groceries\"\n :quantity 100",
"end": 10100,
"score": 0.7498331069946289,
"start": 10091,
"tag": "NAME",
"value": "Groceries"
},
{
"context": "t\n :account-id \"Groceries\"\n :quantity 100",
"end": 12629,
"score": 0.9700214862823486,
"start": 12620,
"tag": "NAME",
"value": "Groceries"
},
{
"context": "t\n :account-id \"Groceries\"\n :quantity 99}",
"end": 13113,
"score": 0.9843606948852539,
"start": 13104,
"tag": "NAME",
"value": "Groceries"
},
{
"context": "onal\"\n :description \"Kroger\"\n :items [{:action :",
"end": 15352,
"score": 0.701705276966095,
"start": 15346,
"tag": "NAME",
"value": "Kroger"
},
{
"context": "Personal\"\n :description \"Paycheck\"\n :items [{:action :debi",
"end": 16709,
"score": 0.6563125848770142,
"start": 16701,
"tag": "NAME",
"value": "Paycheck"
},
{
"context": "Personal\"\n :description \"Kroger\"\n :items [{:action :debi",
"end": 17192,
"score": 0.9808946251869202,
"start": 17186,
"tag": "NAME",
"value": "Kroger"
},
{
"context": "t\n :account-id \"Groceries\"\n :quantity 101",
"end": 17301,
"score": 0.9961509108543396,
"start": 17292,
"tag": "NAME",
"value": "Groceries"
},
{
"context": "Personal\"\n :description \"Kroger\"\n :items [{:action :debi",
"end": 17676,
"score": 0.9846704602241516,
"start": 17670,
"tag": "NAME",
"value": "Kroger"
},
{
"context": "t\n :account-id \"Groceries\"\n :quantity 102",
"end": 17785,
"score": 0.9942922592163086,
"start": 17776,
"tag": "NAME",
"value": "Groceries"
},
{
"context": "y-id \"Personal\"\n :description \"Kroger\"\n :items [{:action :debit\n ",
"end": 20265,
"score": 0.5644181370735168,
"start": 20259,
"tag": "NAME",
"value": "Kroger"
},
{
"context": " :debit\n :account-id \"Groceries\"\n :quantity 101}\n ",
"end": 20362,
"score": 0.9460797309875488,
"start": 20353,
"tag": "NAME",
"value": "Groceries"
},
{
"context": "-id \"Personal\"\n :description \"Kroger\"\n :items [{:action :debit\n ",
"end": 20693,
"score": 0.5744539499282837,
"start": 20691,
"tag": "NAME",
"value": "ro"
},
{
"context": " :debit\n :account-id \"Groceries\"\n :quantity 102}\n ",
"end": 20793,
"score": 0.9635806679725647,
"start": 20784,
"tag": "NAME",
"value": "Groceries"
},
{
"context": "y-id \"Personal\"\n :description \"Kroger\"\n :items [{:action :debit\n ",
"end": 33144,
"score": 0.9933624267578125,
"start": 33138,
"tag": "NAME",
"value": "Kroger"
},
{
"context": " :debit\n :account-id \"Groceries\"\n :quantity 101}\n ",
"end": 33241,
"score": 0.9904690384864807,
"start": 33232,
"tag": "NAME",
"value": "Groceries"
},
{
"context": "y-id \"Personal\"\n :description \"Kroger\"\n :items [{:action :debit\n ",
"end": 33575,
"score": 0.9916855692863464,
"start": 33569,
"tag": "NAME",
"value": "Kroger"
},
{
"context": " :debit\n :account-id \"Groceries\"\n :quantity 102}\n ",
"end": 33672,
"score": 0.9912083745002747,
"start": 33663,
"tag": "NAME",
"value": "Groceries"
},
{
"context": "y-id \"Personal\"\n :description \"Kroger\"\n :items [{:action :debit\n ",
"end": 34006,
"score": 0.993535578250885,
"start": 34000,
"tag": "NAME",
"value": "Kroger"
},
{
"context": " :debit\n :account-id \"Groceries\"\n :quantity 103}\n ",
"end": 34103,
"score": 0.9917994141578674,
"start": 34094,
"tag": "NAME",
"value": "Groceries"
},
{
"context": "y-id \"Personal\"\n :description \"Kroger\"\n :items [{:action :debit\n ",
"end": 34437,
"score": 0.9921281933784485,
"start": 34431,
"tag": "NAME",
"value": "Kroger"
},
{
"context": " :debit\n :account-id \"Groceries\"\n :quantity 104}\n ",
"end": 34534,
"score": 0.9912802577018738,
"start": 34525,
"tag": "NAME",
"value": "Groceries"
},
{
"context": "x (find-transaction ctx (t/local-date 2016 3 16) \"Kroger\")\n updated (change-date trx (t/local-",
"end": 35509,
"score": 0.5686289668083191,
"start": 35508,
"tag": "NAME",
"value": "K"
},
{
"context": " \"Personal\"\n :description \"Kroger\"\n :items [{:action :d",
"end": 37544,
"score": 0.7044636607170105,
"start": 37543,
"tag": "NAME",
"value": "K"
},
{
"context": "it\n :account-id \"Groceries\"\n :quantity 101}\n",
"end": 37654,
"score": 0.6785029172897339,
"start": 37646,
"tag": "NAME",
"value": "roceries"
},
{
"context": " \"Personal\"\n :description \"Kroger\"\n :items [{:action :debit\n",
"end": 38016,
"score": 0.9850508570671082,
"start": 38010,
"tag": "NAME",
"value": "Kroger"
},
{
"context": "bit\n :account-id \"Groceries\"\n :quantity 102}\n",
"end": 38121,
"score": 0.9723539352416992,
"start": 38112,
"tag": "NAME",
"value": "Groceries"
},
{
"context": " \"Personal\"\n :description \"Kroger\"\n :items [{:action :debit\n",
"end": 38483,
"score": 0.9904492497444153,
"start": 38477,
"tag": "NAME",
"value": "Kroger"
},
{
"context": "bit\n :account-id \"Groceries\"\n :quantity 103}\n",
"end": 38588,
"score": 0.9477348327636719,
"start": 38579,
"tag": "NAME",
"value": "Groceries"
},
{
"context": "y-id \"Personal\"\n :description \"Kroger\"\n :items [{:action :debit\n ",
"end": 40472,
"score": 0.9372528195381165,
"start": 40466,
"tag": "NAME",
"value": "Kroger"
},
{
"context": " :debit\n :account-id \"Groceries\"\n :quantity 103}\n ",
"end": 40569,
"score": 0.997565507888794,
"start": 40560,
"tag": "NAME",
"value": "Groceries"
},
{
"context": "y-id \"Personal\"\n :description \"Kroger\"\n :items [{:action :debit\n ",
"end": 40903,
"score": 0.9322234988212585,
"start": 40897,
"tag": "NAME",
"value": "Kroger"
},
{
"context": " :debit\n :account-id \"Groceries\"\n :quantity 12}\n ",
"end": 41000,
"score": 0.9962131381034851,
"start": 40991,
"tag": "NAME",
"value": "Groceries"
},
{
"context": "y-id \"Personal\"\n :description \"Kroger\"\n :items [{:action :debit\n ",
"end": 41332,
"score": 0.901028573513031,
"start": 41326,
"tag": "NAME",
"value": "Kroger"
},
{
"context": " :debit\n :account-id \"Groceries\"\n :quantity 101}\n ",
"end": 41429,
"score": 0.9965667724609375,
"start": 41420,
"tag": "NAME",
"value": "Groceries"
},
{
"context": "ext\n (update-in [:accounts] #(conj % {:name \"Pets\"\n :type :ex",
"end": 42704,
"score": 0.8398089408874512,
"start": 42700,
"tag": "NAME",
"value": "Pets"
},
{
"context": " :account-id \"Groceries\"\n :quantity",
"end": 43634,
"score": 0.6647253036499023,
"start": 43625,
"tag": "NAME",
"value": "Groceries"
},
{
"context": " :account-id \"Groceries\"\n :quantity",
"end": 44155,
"score": 0.6514050960540771,
"start": 44146,
"tag": "NAME",
"value": "Groceries"
},
{
"context": " :account-id \"Groceries\"\n :quantity",
"end": 44840,
"score": 0.8124227523803711,
"start": 44831,
"tag": "NAME",
"value": "Groceries"
},
{
"context": "\"\n :debit-account-id \"Groceries\"\n :credit-account-id ",
"end": 56961,
"score": 0.6103469729423523,
"start": 56952,
"tag": "NAME",
"value": "Groceries"
},
{
"context": "\n :debit-account-id \"Groceries\"\n :credit-account-id ",
"end": 57247,
"score": 0.561902642250061,
"start": 57239,
"tag": "NAME",
"value": "roceries"
}
] | test/clj_money/models/transactions_test.clj | dgknght/clj-money | 5 | (ns clj-money.models.transactions-test
(:require [clojure.test :refer [deftest use-fixtures testing is]]
[clj-time.core :as t]
[clj-factory.core :refer [factory]]
[dgknght.app-lib.core :refer [index-by]]
[dgknght.app-lib.test]
[dgknght.app-lib.validation :as v]
[clj-money.transactions :refer [change-date]]
[clj-money.models.accounts :as accounts]
[clj-money.models.transactions :as transactions]
[clj-money.models.lots :as lots]
[clj-money.factories.user-factory]
[clj-money.factories.entity-factory]
[clj-money.test-context :refer [realize
with-context
basic-context
find-entity
find-account
find-accounts
find-transaction]]
[clj-money.test-helpers :refer [reset-db]]))
(use-fixtures :each reset-db)
(defn- assert-account-quantities
[& args]
(->> args
(partition 2)
(map (fn [[account balance]]
(is (= balance (:quantity (accounts/reload account)))
(format "%s should have the quantity %s"
(:name account)
balance))))
dorun))
(defn items-by-account
[account]
(transactions/items-by-account
account
[(t/local-date 2015 1 1)
(t/local-date 2017 12 31)]))
(def base-context
{:users [(factory :user, {:email "john@doe.com"})]
:entities [{:name "Personal"}]
:commodities [{:name "US Dollar"
:symbol "USD"
:type :currency}]
:accounts [{:name "Checking"
:type :asset}
{:name "Salary"
:type :income}
{:name "Groceries"
:type :expense}]})
(defn attributes
[context]
(let [[checking
salary] (:accounts context)]
{:transaction-date (t/local-date 2016 3 2)
:description "Paycheck"
:memo "final, partial"
:entity-id (-> context :entities first :id)
:items [{:account-id (:id checking)
:action :debit
:memo "conf # 123"
:quantity 1000M}
{:account-id (:id salary)
:action :credit
:quantity 1000M}]}))
(deftest create-a-transaction
(let [context (realize base-context)
transaction (transactions/create (attributes context))]
(is transaction "A non-nil value is returned")
(testing "return value includes the new id"
(is (valid? transaction))
(is (:id transaction) "A map with the new ID is returned"))
(testing "transaction can be retrieved"
(let [actual (transactions/find transaction)
expected {:transaction-date (t/local-date 2016 3 2)
:description "Paycheck"
:memo "final, partial"
:entity-id (-> context :entities first :id)
:value 1000M}
expected-items [{:description "Paycheck"
:account-id (:id (find-account context "Checking"))
:index 0
:transaction-date (t/local-date 2016 3 2)
:action :debit
:negative false
:memo "conf # 123"
:quantity 1000M
:polarized-quantity 1000M
:balance 1000M
:value 1000M
:reconciliation-status nil
:reconciliation-id nil
:reconciled? false}
{:description "Paycheck"
:account-id (:id (find-account context "Salary"))
:index 0
:transaction-date (t/local-date 2016 3 2)
:action :credit
:negative false
:memo nil
:quantity 1000M
:polarized-quantity 1000M
:balance 1000M
:value 1000M
:reconciliation-status nil
:reconciliation-id nil
:reconciled? false}]]
(is (comparable? expected actual "The correct data is retrieved"))
(doseq [[e a] (partition 2 (interleave expected-items (:items actual)))]
(is (comparable? e a) "Each item is retrieved correctly"))))))
(deftest rollback-on-failure
(let [call-count (atom 0)]
(with-redefs [transactions/before-save-item (fn [item]
(if (= 1 @call-count)
(throw (RuntimeException. "Induced error"))
(do
(swap! call-count inc)
(update-in item [:action] name))))]
(let [context (realize base-context)
[checking
salary] (:accounts context)
_ (try
(transactions/create (attributes context))
(catch RuntimeException _
nil))]
(testing "records are not created"
(is (= 0 (count (transactions/search
{:entity-id (-> context :entities first :id)
:transaction-date "2016"})))
"The transaction should not be saved")
(is (= 0 (count (items-by-account checking)))
"The transaction item for checking should not be created")
(is (= 0 (count (items-by-account salary)))
"The transaction item for salary should not be created"))
(assert-account-quantities checking 0M salary 0M)))))
(deftest transaction-date-is-required
(let [context (realize base-context)
transaction (transactions/create (dissoc (attributes context)
:transaction-date))]
(is (invalid? transaction [:transaction-date] "Transaction date is required"))))
(deftest entity-id-is-required
(let [context (realize base-context)
result (transactions/create (dissoc (attributes context)
:entity-id))]
(is (invalid? result [:entity-id] "Entity is required"))))
(deftest items-are-required
(let [context (realize base-context)
result (transactions/create
(-> context
attributes
(assoc :items [])))]
(is (invalid? result [:items] "Items must contain at least 1 item(s)"))))
(deftest item-account-id-is-required
(let [context (realize base-context)
transaction (transactions/create
(update-in
(attributes context)
[:items 0]
#(dissoc % :account-id)))]
(is (invalid? transaction [:items 0 :account-id] "Account is required"))))
(deftest item-quantity-is-required
(let [context (realize base-context)
transaction (transactions/create
(update-in
(attributes context)
[:items 0]
#(dissoc % :quantity)))]
(is (invalid? transaction [:items 0 :quantity] "Quantity is required"))))
(deftest item-quantity-must-be-greater-than-zero
(let [context (realize base-context)
transaction (transactions/create
(update-in
(attributes context)
[:items 0]
#(assoc % :quantity -1000M)))]
(is (invalid? transaction [:items 0 :quantity] "Quantity cannot be less than zero"))))
(deftest item-action-is-required
(let [context (realize base-context)
transaction (transactions/create
(update-in
(attributes context)
[:items 0]
#(dissoc % :action)))]
(is (invalid? transaction [:items 0 :action] "Action is required"))))
(deftest item-action-must-be-debit-or-credit
(let [context (realize base-context)
transaction (transactions/create
(update-in
(attributes context)
[:items 0]
#(assoc % :action :not-valid)))]
(is (invalid? transaction [:items 0 :action] "Action must be debit or credit"))))
(deftest sum-of-debits-must-equal-sum-of-credits
(let [context (realize base-context)
transaction (transactions/create
(update-in
(attributes context)
[:items 0]
#(assoc % :quantity 1001M)))]
(is (invalid? transaction [:items] "Sum of debits must equal the sum of credits"))))
(def balance-context
(merge base-context
{:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :credit
:account-id "Salary"
:quantity 1000}]}
{:transaction-date (t/local-date 2016 3 3)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "Groceries"
:quantity 100}
{:action :credit
:account-id "Checking"
:quantity 100}]}]}))
(deftest item-balances-are-set-when-saved
(let [context (realize balance-context)
[checking-items
salary-items
groceries-items] (map #(items-by-account (:id %))
(:accounts context))]
; Transactions are returned with most recent first
(is (= [900M 1000M]
(map :balance checking-items))
"The checking account balances are correct")
(is (= [1000M] (map :balance salary-items))
"The salary account balances are correct")
(is (= [100M] (map :balance groceries-items))
"The groceries account balances are correct")))
(deftest item-indexes-are-set-when-saved
(let [context (realize balance-context)
[checking-items
salary-items
groceries-items] (map items-by-account
(:accounts context))]
(is (= [1 0] (map :index checking-items)) "The checking transaction items have correct indexes")
(is (= [0] (map :index salary-items)) "The salary transaction items have the correct indexes")
(is (= [0] (map :index groceries-items)) "The groceries transaction items have the correct indexes")))
(deftest account-balances-are-set-when-saved
(let [context (realize balance-context)
[checking
salary
groceries] (find-accounts context "Checking"
"Salary"
"Groceries")]
(assert-account-quantities checking 900M salary 1000M groceries 100M)))
(def insert-context
(merge base-context
{:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :credit
:account-id "Salary"
:quantity 1000}]}
{:transaction-date (t/local-date 2016 3 10)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "Groceries"
:quantity 100}
{:action :credit
:account-id "Checking"
:quantity 100}]}
{:transaction-date (t/local-date 2016 3 3)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "Groceries"
:quantity 99}
{:action :credit
:account-id "Checking"
:quantity 99}]}]}))
(deftest insert-transaction-before-the-end
(let [ctx (realize insert-context)
checking (find-account ctx "Checking")
items (items-by-account (:id checking))]
(is (= [{:index 2
:quantity 100M
:balance 801M}
{:index 1
:quantity 99M
:balance 901M}
{:index 0
:quantity 1000M
:balance 1000M}]
(map #(select-keys % [:index :quantity :balance]) items))
"The checking item balances should be correct")
(is (= [801M 1000M 199M]
(map (comp :quantity
accounts/find)
(:accounts ctx)))
"The accounts have the correct balances")))
(def multi-context
(-> base-context
(update-in [:accounts] #(conj % {:name "Bonus"
:type :income
:entity-id "Personal"
:commodity-id "USD"}))
(merge {:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :debit
:account-id "Checking"
:quantity 100}
{:action :credit
:account-id "Salary"
:quantity 1000}
{:action :credit
:account-id "Bonus"
:quantity 100}]}
{:transaction-date (t/local-date 2016 3 10)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "Groceries"
:quantity 100}
{:action :credit
:account-id "Checking"
:quantity 100}]}]})))
(deftest create-a-transaction-with-multiple-items-for-one-account
(let [context (realize multi-context)
checking (find-account context "Checking")
checking-items (items-by-account (:id checking))
expected-checking-items #{{:transaction-date (t/local-date 2016 3 10) :quantity 100M}
{:transaction-date (t/local-date 2016 3 2) :quantity 1000M}
{:transaction-date (t/local-date 2016 3 2) :quantity 100M}}
actual-checking-items (->> checking-items
(map #(select-keys % [:transaction-date :quantity]))
set)]
(is (= expected-checking-items
actual-checking-items)
"The checking account items are correct")))
(def delete-context
(merge base-context
{:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :credit
:account-id "Salary"
:quantity 1000}]}
{:transaction-date (t/local-date 2016 3 3)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "Groceries"
:quantity 101}
{:action :credit
:account-id "Checking"
:quantity 101}]}
{:transaction-date (t/local-date 2016 3 4)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "Groceries"
:quantity 102}
{:action :credit
:account-id "Checking"
:quantity 102}]}]}))
(deftest delete-a-transaction
(let [context (realize delete-context)
[checking
_
groceries] (:accounts context)
checking-items-before (items-by-account (:id checking))
trans (-> context
:transactions
second)
_ (transactions/delete trans)
checking-items-after (items-by-account (:id checking))]
(testing "transaction item balances are adjusted"
(let [expected-before [{:index 2 :quantity 102M :balance 797M}
{:index 1 :quantity 101M :balance 899M}
{:index 0 :quantity 1000M :balance 1000M}]
actual-before (map #(select-keys % [:index :quantity :balance])
checking-items-before)
expected-after [{:index 1 :quantity 102M :balance 898M}
{:index 0 :quantity 1000M :balance 1000M}]
actual-after (map #(select-keys % [:index :quantity :balance]) checking-items-after)]
(is (= expected-before actual-before)
"Checking should have the correct items before delete")
(is (= expected-after actual-after)
"Checking should have the correct items after delete")))
(testing "account balances are adjusted"
(let [checking-after (accounts/find checking)
groceries-after (accounts/find groceries)]
(is (= 898M (:quantity checking-after))
"Checking should have the correct balance after delete")
(is (= 102M (:quantity groceries-after))
"Groceries should have the correct balance after delete")))))
(def update-context
(merge
base-context
{:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :credit
:account-id "Salary"
:quantity 1000}]}
{:transaction-date (t/local-date 2016 3 12)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "Groceries"
:quantity 101}
{:action :credit
:account-id "Checking"
:quantity 101}]}
{:transaction-date (t/local-date 2016 3 22)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "Groceries"
:quantity 102}
{:action :credit
:account-id "Checking"
:quantity 102}]}]}))
(deftest get-a-transaction
(let [context (realize update-context)
{:keys [id transaction-date]} (find-transaction context (t/local-date 2016 3 2) "Paycheck")]
(testing "items are not included if not specified"
(let [transaction (first (transactions/search {:id id
:transaction-date transaction-date}))]
(is transaction "The transaction is retrieved successfully")
(is (nil? (:items transaction)) "The items are not included")
(is (= 1000M (:value transaction)) "The correct value is returned")))
(testing "items are included if specified"
(let [transaction (first (transactions/search {:id id
:transaction-date transaction-date}
{:include-items? true}))]
(is transaction "The transaction is retrieved successfully")
(is (:items transaction) "The items are included")))))
(def search-context
(merge
base-context
{:transactions [{:transaction-date #local-date "2016-01-01"
:entity-id "Personal"
:description "Paycheck"
:quantity 160101M
:debit-account-id "Checking"
:credit-account-id "Salary"}
{:transaction-date #local-date "2016-06-01"
:entity-id "Personal"
:description "Paycheck"
:quantity 160601M
:debit-account-id "Checking"
:credit-account-id "Salary"}
{:transaction-date #local-date "2017-01-01"
:entity-id "Personal"
:description "Paycheck"
:quantity 170101M
:debit-account-id "Checking"
:credit-account-id "Salary"}
{:transaction-date #local-date "2017-06-01"
:entity-id "Personal"
:description "Paycheck"
:quantity 170601M
:debit-account-id "Checking"
:credit-account-id "Salary"}
{:transaction-date #local-date "2017-06-15"
:entity-id "Personal"
:description "Paycheck"
:quantity 170615
:debit-account-id "Checking"
:credit-account-id "Salary"}]}))
(deftest search-by-year
(let [context (realize search-context)
entity (find-entity context "Personal")
actual (transactions/search {:transaction-date "2016"
:entity-id (:id entity)})]
(is (= [(t/local-date 2016 1 1)
(t/local-date 2016 6 1)]
(map :transaction-date actual))
"The transactions from the specified year are returned")))
(deftest search-by-month
(let [context (realize search-context)
entity (find-entity context "Personal")
actual (transactions/search {:transaction-date "2017-06"
:entity-id (:id entity)})]
(is (= [(t/local-date 2017 6 1)
(t/local-date 2017 6 15)]
(map :transaction-date actual))
"The transactions from the specified month are returned")))
(deftest search-by-date-string
(let [context (realize search-context)
entity (find-entity context "Personal")
actual (transactions/search {:transaction-date "2017-06-01"
:entity-id (:id entity)})]
(is (= [(t/local-date 2017 6 1)] (map :transaction-date actual))
"The transactions from the specified day are returned")))
(deftest search-by-date
(let [context (realize search-context)
entity (find-entity context "Personal")
actual (transactions/search {:transaction-date (t/local-date 2017 6 15)
:entity-id (:id entity)})]
(is (= [(t/local-date 2017 6 15)] (map :transaction-date actual))
"The transactions from the specified day are returned")))
(deftest search-by-date-vector
(let [context (realize search-context)
entity (find-entity context "Personal")
actual (transactions/search {:transaction-date [:between
(t/local-date 2017 6 1)
(t/local-date 2017 6 30)]
:entity-id (:id entity)})]
(is (= [(t/local-date 2017 6 1)
(t/local-date 2017 6 15)]
(map :transaction-date actual))
"The transactions from the specified day are returned")))
(defn- update-items
[{:keys [items] :as transaction} change-map]
(let [indexed-items (index-by :account-id items)
updated-items (reduce (fn [items [account-id item]]
(update-in items [account-id] merge item))
indexed-items
change-map)]
(assoc transaction :items (vals updated-items))))
(deftest update-a-transaction-change-quantity
(let [ctx (realize update-context)
checking (find-account ctx "Checking")
groceries (find-account ctx "Groceries")
result (-> (find-transaction ctx (t/local-date 2016 3 12) "Kroger")
(update-items {(:id groceries) {:quantity 99.99M}
(:id checking) {:quantity 99.99M}})
transactions/update)]
(is (valid? result))
(is (seq-of-maps-like? [{:index 2 :quantity 102.00M :balance 798.01M}
{:index 1 :quantity 99.99M :balance 900.01M}
{:index 0 :quantity 1000.00M :balance 1000.00M}]
(items-by-account (:id checking)))
"Expected the checking account items to be updated.")
(is (seq-of-maps-like? [{:index 1 :quantity 102.00M :balance 201.99M}
{:index 0 :quantity 99.99M :balance 99.99M}]
(items-by-account (:id groceries)))
"Expected the groceries account items to be updated.")
(assert-account-quantities checking 798.01M groceries 201.99M)))
(deftest rollback-a-failed-update
(let [real-reload transactions/reload
ctx (realize update-context)
checking (find-account ctx "Checking")
groceries (find-account ctx "Groceries")
trx (find-transaction ctx (t/local-date 2016 3 12) "Kroger")
call-count (atom 0)]
(with-redefs [transactions/reload (fn [transaction]
(swap! call-count inc)
(if (= 2 @call-count)
(throw (RuntimeException. "Induced exception"))
(real-reload transaction)))]
(try
(-> trx
(update-items {(:id groceries) {:quantity 99.99M}
(:id checking) {:quantity 99.99M}})
transactions/update)
(catch RuntimeException _ nil)))
(testing "transaction items are not updated"
(is (= #{101M} (->> (:items (transactions/reload trx))
(map :quantity)
(into #{})))))
(assert-account-quantities checking 797M groceries 203M)))
(deftest update-a-transaction-change-date
(let [ctx (realize update-context)
checking (find-account ctx "Checking")
groceries (find-account ctx "Groceries")
trx (find-transaction ctx (t/local-date 2016 3 22) "Kroger")
result (-> trx
(change-date (t/local-date 2016 3 10))
transactions/update)]
(is (valid? result))
(is (seq-of-maps-like? [{:index 2 :transaction-date (t/local-date 2016 3 12) :quantity 101M :balance 797M}
{:index 1 :transaction-date (t/local-date 2016 3 10) :quantity 102M :balance 898M}
{:index 0 :transaction-date (t/local-date 2016 3 2) :quantity 1000M :balance 1000M}]
(items-by-account (:id checking)))
"Expected the checking items to be updated")
(is (seq-of-maps-like? [{:index 1 :transaction-date (t/local-date 2016 3 12) :quantity 101M :balance 203M}
{:index 0 :transaction-date (t/local-date 2016 3 10) :quantity 102M :balance 102M}]
(items-by-account (:id groceries)))
"Expected the groceries items to be updated")
(assert-account-quantities checking 797M groceries 203M)
(testing "transaction is updated"
(is (= (t/local-date 2016 3 10)
(:transaction-date (transactions/reload result)))
"The transaction should be updated"))))
(def ^:private trading-update-context
(-> basic-context
(update-in [:commodities] concat [{:name "Apple, Inc."
:symbol "AAPL"
:type :stock
:exchange :nasdaq}])
(update-in [:accounts] concat [{:name "IRA"
:entity-id "Personal"
:type :asset}])
(assoc :trades [{:trade-date (t/local-date 2015 1 1)
:type :buy
:commodity-id "AAPL"
:account-id "IRA"
:shares 100M
:value 1000M}])))
(deftest update-a-trading-transaction-change-date
(with-context trading-update-context
(let [trx (transactions/find-by {:description "Purchase 100 shares of AAPL at 10.000"
:transaction-date (t/local-date 2015 1 1)}
{:include-items? true})
result (transactions/update (assoc trx :transaction-date (t/local-date 2015 2 1)))
account (find-account "IRA")
retrieved (lots/find-by {:account-id (:id account)})]
(is (empty? (v/error-messages result))
"There are no validation errors")
(is (= (t/local-date 2015 2 1)
(:purchase-date retrieved))
"The lot is updated with the correct purchase date"))))
(deftest update-a-transaction-cross-partition-boundary
(let [ctx (realize update-context)
checking (find-account ctx "Checking")
groceries (find-account ctx "Groceries")
trx (find-transaction ctx (t/local-date 2016 3 12) "Kroger")
result (-> trx
(assoc :transaction-date (t/local-date 2016 4 12))
transactions/update)]
(is (valid? result))
(is (seq-of-maps-like? [{:index 2 :quantity 101M :balance 797M}
{:index 1 :quantity 102M :balance 898M}
{:index 0 :quantity 1000M :balance 1000M}]
(items-by-account (:id checking)))
"Expected the checking items to be updated")
(is (seq-of-maps-like? [{:index 1 :quantity 101M :balance 203M}
{:index 0 :quantity 102M :balance 102M}]
(items-by-account (:id groceries)))
"Expected the groceries items to be updated")
(assert-account-quantities checking 797M groceries 203M)
(testing "transaction is updated"
(is (= (t/local-date 2016 4 12)
(:transaction-date (transactions/reload result)))
"The transaction should be updated"))))
(def short-circuit-context
(merge
base-context
{:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :credit
:account-id "Salary"
:quantity 1000}]}
{:transaction-date (t/local-date 2016 3 9)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "Groceries"
:quantity 101}
{:action :credit
:account-id "Checking"
:quantity 101}]}
{:transaction-date (t/local-date 2016 3 16)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "Groceries"
:quantity 102}
{:action :credit
:account-id "Checking"
:quantity 102}]}
{:transaction-date (t/local-date 2016 3 23)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "Groceries"
:quantity 103}
{:action :credit
:account-id "Checking"
:quantity 103}]}
{:transaction-date (t/local-date 2016 3 30)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "Groceries"
:quantity 104}
{:action :credit
:account-id "Checking"
:quantity 104}]}]}))
(defn- record-update-call
[item result]
(update-in result
[(:account-id item)]
#((fnil conj #{}) % (select-keys item [:index
:quantity
:balance]))))
(def ^:dynamic update-item nil)
; Trans. Date quantity Debit Credit
; 2016-03-02 1000 Checking Salary
; 2016-03-09 101 Groceries Checking
; 2016-03-16 102 Groceries Checking move this to 3/8
; 2016-03-23 103 Groceries Checking
; 2016-03-30 104 Groceries Checking
(deftest update-a-transaction-short-circuit-updates
(let [ctx (realize short-circuit-context)
checking (find-account ctx "Checking")
trx (find-transaction ctx (t/local-date 2016 3 16) "Kroger")
updated (change-date trx (t/local-date 2016 3 8))
update-calls (atom {})]
(binding [update-item transactions/update-item-index-and-balance]
(with-redefs [transactions/update-item-index-and-balance (fn [item]
(swap! update-calls
(partial record-update-call item))
(update-item item))]
(let [result (transactions/update updated)
expected #{{:index 1
:quantity 102M
:balance 898M}
{:index 2
:quantity 101M
:balance 797M}}
actual (get @update-calls (:id checking))]
(is (valid? result))
(testing "the expected transactions are updated"
(is (= expected actual)
"Only items with changes are updated")
(is (not-any? #(= (:index %) 4) actual) "The last item is never updated"))
(assert-account-quantities checking 590M))))))
(def change-account-context
(-> base-context
(update-in [:accounts] #(conj % {:name "Rent"
:type :expense
:commodity-id "USD"}))
(merge
{:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :credit
:account-id "Salary"
:quantity 1000}]}
{:transaction-date (t/local-date 2016 3 9)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "Groceries"
:quantity 101}
{:action :credit
:account-id "Checking"
:quantity 101}]}
{:transaction-date (t/local-date 2016 3 16)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "Groceries"
:quantity 102}
{:action :credit
:account-id "Checking"
:quantity 102}]}
{:transaction-date (t/local-date 2016 3 23)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "Groceries"
:quantity 103}
{:action :credit
:account-id "Checking"
:quantity 103}]}]})))
(deftest update-a-transaction-change-account
(let [ctx (realize change-account-context)
[rent
groceries] (find-accounts ctx "Rent" "Groceries")
result (-> (find-transaction ctx (t/local-date 2016 3 16) "Kroger")
(update-items {(:id groceries) {:account-id (:id rent)}})
transactions/update)]
(is (valid? result))
(is (seq-of-maps-like? [{:index 1
:quantity 103M
:balance 204M}
{:index 0
:quantity 101M
:balance 101M}]
(items-by-account (:id groceries)))
"Expected the groceries items to be updated")
(is (seq-of-maps-like? [{:index 0
:quantity 102M
:balance 102M}]
(items-by-account (:id rent)))
"Expected the rent items to be updated")
(assert-account-quantities groceries 204M rent 102M)))
(def change-action-context
(merge
base-context
{:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :credit
:account-id "Salary"
:quantity 1000}]}
{:transaction-date (t/local-date 2016 3 9)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "Groceries"
:quantity 103}
{:action :credit
:account-id "Checking"
:quantity 103}]}
{:transaction-date (t/local-date 2016 3 16)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "Groceries"
:quantity 12}
{:action :credit
:account-id "Checking"
:quantity 12}]}
{:transaction-date (t/local-date 2016 3 23)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "Groceries"
:quantity 101}
{:action :credit
:account-id "Checking"
:quantity 101}]}]}))
(deftest update-a-transaction-change-action
(let [context (realize change-action-context)
[checking _ groceries] (:accounts context)
result (-> (find-transaction context (t/local-date 2016 3 16) "Kroger")
(update-items {(:id groceries) {:action :credit}
(:id checking) {:action :debit}})
transactions/update)]
(is (valid? result))
(is (seq-of-maps-like? [{:index 2
:quantity 101M
:balance 192M}
{:index 1
:quantity 12M
:balance 91M}
{:index 0
:quantity 103M
:balance 103M}]
(items-by-account (:id groceries)))
"Expected the groceries items to be updated")
(assert-account-quantities groceries 192M checking 808M)))
(def add-remove-item-context
(-> base-context
(update-in [:accounts] #(conj % {:name "Pets"
:type :expense
:commodity-id "USD"}))
(merge {:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :credit
:account-id "Salary"
:quantity 1000}]}
{:transaction-date (t/local-date 2016 3 9)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "Groceries"
:quantity 103}
{:action :credit
:account-id "Checking"
:quantity 103}]}
{:transaction-date (t/local-date 2016 3 16)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "Groceries"
:quantity 90}
{:action :debit
:account-id "Pets"
:quantity 12}
{:action :credit
:account-id "Checking"
:quantity 102}]}
{:transaction-date (t/local-date 2016 3 23)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "Groceries"
:quantity 101}
{:action :credit
:account-id "Checking"
:quantity 101}]}]})))
(deftest update-a-transaction-remove-item
(let [context (realize add-remove-item-context)
[checking
pets
groceries] (find-accounts context "Checking" "Pets" "Groceries")
result (-> (find-transaction context (t/local-date 2016 3 16) "Kroger")
(update-items {(:id groceries) {:quantity 102M
:value 102M}})
(update-in [:items] #(remove (fn [item]
(= (:account-id item)
(:id pets)))
%))
transactions/update)
expected-items [{:index 2
:quantity 101M
:balance 306M}
{:index 1
:quantity 102M
:balance 205M}
{:index 0
:quantity 103M
:balance 103M}]
actual-items (map #(select-keys % [:index :quantity :balance])
(items-by-account (:id groceries)))]
(is (valid? result) (str "Expected the transaction to be valid: " (prn-str (dissoc result :v/explanation))))
(assert-account-quantities pets 0M groceries 306M checking 694M)
(is (= expected-items actual-items)
"The account for the changed item should have the correct items")))
(deftest update-a-transaction-add-item
(let [context (realize add-remove-item-context)
[pets
groceries
checking] (find-accounts context "Pets" "Groceries" "Checking")
t2 (find-transaction context (t/local-date 2016 3 9) "Kroger")
to-update (-> t2
(update-items {(:id groceries) {:quantity 90M
:value 90M}})
(update-in [:items] #(conj % {:action :debit
:account-id (:id pets)
:quantity 13M
:value 13M})))
_ (transactions/update to-update)
expected-items [{:index 1
:quantity 12M
:balance 25M}
{:index 0
:quantity 13M
:balance 13M}]
actual-items (map #(select-keys % [:index :quantity :balance])
(items-by-account (:id pets)))]
(testing "item values are correct"
(is (= expected-items actual-items)
"The Pets account should have the correct items"))
(assert-account-quantities pets 25M groceries 281M checking 694M)))
(def balance-delta-context
(merge
base-context
{:transactions [{:transaction-date (t/local-date 2016 1 1)
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000M}
{:action :credit
:account-id "Salary"
:quantity 1000M}]}
{:transaction-date (t/local-date 2016 1 15)
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1001M}
{:action :credit
:account-id "Salary"
:quantity 1001M}]}
{:transaction-date (t/local-date 2016 2 1)
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1100M}
{:action :credit
:account-id "Salary"
:quantity 1100M}]}
{:transaction-date (t/local-date 2016 2 15)
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1102M}
{:action :credit
:account-id "Salary"
:quantity 1102M}]}
{:transaction-date (t/local-date 2016 3 1)
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1200M}
{:action :credit
:account-id "Salary"
:quantity 1200M}]}]}))
(deftest get-a-balance-delta
(let [context (realize balance-delta-context)
[_ salary] (:accounts context)
january (transactions/balance-delta salary
(t/local-date 2016 1 1)
(t/local-date 2016 1 31))
february (transactions/balance-delta salary
(t/local-date 2016 2 1)
(t/local-date 2016 2 29))]
(is (= 2001M january) "The January value is the sum of polarized quantitys for the period")
(is (= 2202M february) "The February value is the sum of the polarized quantitys for the period")))
(deftest get-a-balance-as-of
(let [context (realize balance-delta-context)
[checking] (:accounts context)
january (transactions/balance-as-of checking
(t/local-date 2016 1 31))
february (transactions/balance-as-of checking
(t/local-date 2016 2 29))]
(is (= 2001M january) "The January value is the balance for the last item in the period")
(is (= 4203M february) "The February value is the balance for the last item in the period")))
(deftest create-multiple-transactions-then-recalculate-balances
(let [context (realize base-context)
entity (-> context :entities first)
[checking
salary
groceries] (:accounts context)]
(transactions/with-delayed-balancing (:id entity)
(transactions/create {:entity-id (:id entity)
:transaction-date (t/local-date 2017 1 1)
:description "Paycheck"
:items [{:action :debit
:account-id (:id checking)
:quantity 1000M}
{:action :credit
:account-id (:id salary)
:quantity 1000M}]})
(transactions/create {:entity-id (:id entity)
:transaction-date (t/local-date 2017 1 15)
:description "Market Street"
:items [{:action :debit
:account-id (:id groceries)
:quantity 100M}
{:action :credit
:account-id (:id checking)
:quantity 100M}]})
(transactions/create {:entity-id (:id entity)
:transaction-date (t/local-date 2017 2 1)
:description "Paycheck"
:items [{:action :debit
:account-id (:id checking)
:quantity 1000M}
{:action :credit
:account-id (:id salary)
:quantity 1000M}]})
(is (= 0M (:quantity (accounts/reload checking)))
"The account balance is not recalculated before the form exits"))
(is (= 1900M (:quantity (accounts/reload checking)))
"The account balance is recalculated after the form exits")))
(deftest use-simplified-items
(let [context (realize base-context)
entity (find-entity context "Personal")
[checking salary] (find-accounts context "Checking" "Salary")
trx (transactions/create {:entity-id (:id entity)
:transaction-date (t/local-date 2017 3 2)
:description "Paycheck"
:quantity 1000M
:debit-account-id (:id checking)
:credit-account-id (:id salary)})
actual-items (map #(select-keys % [:account-id :quantity :action]) (:items trx))
expected-items [{:account-id (:id checking)
:action :debit
:quantity 1000M}
{:account-id (:id salary)
:action :credit
:quantity 1000M}]]
(is (valid? trx))
(is (= expected-items actual-items) "The items are created correctly")))
(deftest set-account-boundaries
(let [context (realize base-context)
entity (find-entity context "Personal")
[checking
salary
groceries] (find-accounts context "Checking" "Salary" "Groceries")
created (->> [{:transaction-date (t/local-date 2017 2 27)
:description "Paycheck"
:quantity 1000M
:debit-account-id (:id checking)
:credit-account-id (:id salary)}
{:transaction-date (t/local-date 2017 3 2)
:description "Kroger"
:quantity 100M
:debit-account-id (:id groceries)
:credit-account-id (:id checking)}]
(map #(assoc % :entity-id (:id entity)))
(mapv transactions/create))
[checking
salary
groceries] (map accounts/reload [checking salary groceries])]
(is (valid? created))
(is (= (t/local-date 2017 2 27) (:earliest-transaction-date checking))
"The checking account's earliest is the paycheck")
(is (= (t/local-date 2017 3 2) (:latest-transaction-date checking))
"The checking account's latest is the grocery purchase")
(is (= (t/local-date 2017 2 27) (:earliest-transaction-date salary))
"The salary account's earliest is the paycheck")
(is (= (t/local-date 2017 2 27) (:latest-transaction-date salary))
"The salary account's latest is the paycheck")
(is (= (t/local-date 2017 3 2) (:earliest-transaction-date groceries))
"The groceries account's earliest is the grocery purchase")
(is (= (t/local-date 2017 3 2) (:latest-transaction-date groceries))
"The groceries account's latest is the grocery purchase")))
(def ^:private existing-reconciliation-context
(-> base-context
(update-in [:accounts] conj {:name "Rent"
:type :expense
:entity-id "Personal"})
(assoc :transactions [{:transaction-date (t/local-date 2017 1 1)
:description "Paycheck"
:debit-account-id "Checking"
:credit-account-id "Salary"
:quantity 1000M}
{:transaction-date (t/local-date 2017 1 2)
:description "Landlord"
:debit-account-id "Rent"
:credit-account-id "Checking"
:quantity 500M}
{:transaction-date (t/local-date 2017 1 3)
:description "Kroger"
:debit-account-id "Groceries"
:credit-account-id "Checking"
:quantity 45M}
{:transaction-date (t/local-date 2017 1 10)
:description "Safeway"
:debit-account-id "Groceries"
:credit-account-id "Checking"
:quantity 53M}]
:reconciliations
[{:account-id "Checking"
:end-of-period (t/local-date 2017 1 1)
:balance 1000M
:status :completed
:item-refs [{:transaction-date (t/local-date 2017 1 1)
:quantity 1000M}]}])))
(deftest the-quantity-and-action-of-a-reconciled-item-cannot-be-changed
(let [context (realize existing-reconciliation-context)
transaction (find-transaction context (t/local-date 2017 1 1) "Paycheck")
result1 (transactions/update (update-in transaction [:items]
#(map (fn [item]
(assoc item :quantity 1M))
%)))
result2 (transactions/update (update-in transaction [:items]
#(map (fn [item]
(update-in item [:action] (fn [a] (if (= :credit a)
:debit
:credit))))
%)))]
(is (invalid? result1 [:items] "A reconciled item cannot be updated"))
(is (invalid? result2 [:items] "A reconciled item cannot be updated"))))
(deftest a-reconciled-transaction-item-cannot-be-deleted
(let [context (realize existing-reconciliation-context)
[item-id date] (-> context :reconciliations first :item-refs first)
transaction (transactions/find-by-item-id item-id date)]
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"A transaction with reconciled items cannot be deleted."
(transactions/delete transaction))
"An exception is raised")
(is (do
(try
(transactions/delete transaction)
(catch clojure.lang.ExceptionInfo _ nil))
(transactions/find-by-item-id item-id date))
"The transaction can be retrieved after the delete has been denied")))
| 4857 | (ns clj-money.models.transactions-test
(:require [clojure.test :refer [deftest use-fixtures testing is]]
[clj-time.core :as t]
[clj-factory.core :refer [factory]]
[dgknght.app-lib.core :refer [index-by]]
[dgknght.app-lib.test]
[dgknght.app-lib.validation :as v]
[clj-money.transactions :refer [change-date]]
[clj-money.models.accounts :as accounts]
[clj-money.models.transactions :as transactions]
[clj-money.models.lots :as lots]
[clj-money.factories.user-factory]
[clj-money.factories.entity-factory]
[clj-money.test-context :refer [realize
with-context
basic-context
find-entity
find-account
find-accounts
find-transaction]]
[clj-money.test-helpers :refer [reset-db]]))
(use-fixtures :each reset-db)
(defn- assert-account-quantities
[& args]
(->> args
(partition 2)
(map (fn [[account balance]]
(is (= balance (:quantity (accounts/reload account)))
(format "%s should have the quantity %s"
(:name account)
balance))))
dorun))
(defn items-by-account
[account]
(transactions/items-by-account
account
[(t/local-date 2015 1 1)
(t/local-date 2017 12 31)]))
(def base-context
{:users [(factory :user, {:email "<EMAIL>"})]
:entities [{:name "Personal"}]
:commodities [{:name "US Dollar"
:symbol "USD"
:type :currency}]
:accounts [{:name "Checking"
:type :asset}
{:name "Salary"
:type :income}
{:name "Groceries"
:type :expense}]})
(defn attributes
[context]
(let [[checking
salary] (:accounts context)]
{:transaction-date (t/local-date 2016 3 2)
:description "Paycheck"
:memo "final, partial"
:entity-id (-> context :entities first :id)
:items [{:account-id (:id checking)
:action :debit
:memo "conf # 123"
:quantity 1000M}
{:account-id (:id salary)
:action :credit
:quantity 1000M}]}))
(deftest create-a-transaction
(let [context (realize base-context)
transaction (transactions/create (attributes context))]
(is transaction "A non-nil value is returned")
(testing "return value includes the new id"
(is (valid? transaction))
(is (:id transaction) "A map with the new ID is returned"))
(testing "transaction can be retrieved"
(let [actual (transactions/find transaction)
expected {:transaction-date (t/local-date 2016 3 2)
:description "Paycheck"
:memo "final, partial"
:entity-id (-> context :entities first :id)
:value 1000M}
expected-items [{:description "Paycheck"
:account-id (:id (find-account context "Checking"))
:index 0
:transaction-date (t/local-date 2016 3 2)
:action :debit
:negative false
:memo "conf # 123"
:quantity 1000M
:polarized-quantity 1000M
:balance 1000M
:value 1000M
:reconciliation-status nil
:reconciliation-id nil
:reconciled? false}
{:description "Paycheck"
:account-id (:id (find-account context "Salary"))
:index 0
:transaction-date (t/local-date 2016 3 2)
:action :credit
:negative false
:memo nil
:quantity 1000M
:polarized-quantity 1000M
:balance 1000M
:value 1000M
:reconciliation-status nil
:reconciliation-id nil
:reconciled? false}]]
(is (comparable? expected actual "The correct data is retrieved"))
(doseq [[e a] (partition 2 (interleave expected-items (:items actual)))]
(is (comparable? e a) "Each item is retrieved correctly"))))))
(deftest rollback-on-failure
(let [call-count (atom 0)]
(with-redefs [transactions/before-save-item (fn [item]
(if (= 1 @call-count)
(throw (RuntimeException. "Induced error"))
(do
(swap! call-count inc)
(update-in item [:action] name))))]
(let [context (realize base-context)
[checking
salary] (:accounts context)
_ (try
(transactions/create (attributes context))
(catch RuntimeException _
nil))]
(testing "records are not created"
(is (= 0 (count (transactions/search
{:entity-id (-> context :entities first :id)
:transaction-date "2016"})))
"The transaction should not be saved")
(is (= 0 (count (items-by-account checking)))
"The transaction item for checking should not be created")
(is (= 0 (count (items-by-account salary)))
"The transaction item for salary should not be created"))
(assert-account-quantities checking 0M salary 0M)))))
(deftest transaction-date-is-required
(let [context (realize base-context)
transaction (transactions/create (dissoc (attributes context)
:transaction-date))]
(is (invalid? transaction [:transaction-date] "Transaction date is required"))))
(deftest entity-id-is-required
(let [context (realize base-context)
result (transactions/create (dissoc (attributes context)
:entity-id))]
(is (invalid? result [:entity-id] "Entity is required"))))
(deftest items-are-required
(let [context (realize base-context)
result (transactions/create
(-> context
attributes
(assoc :items [])))]
(is (invalid? result [:items] "Items must contain at least 1 item(s)"))))
(deftest item-account-id-is-required
(let [context (realize base-context)
transaction (transactions/create
(update-in
(attributes context)
[:items 0]
#(dissoc % :account-id)))]
(is (invalid? transaction [:items 0 :account-id] "Account is required"))))
(deftest item-quantity-is-required
(let [context (realize base-context)
transaction (transactions/create
(update-in
(attributes context)
[:items 0]
#(dissoc % :quantity)))]
(is (invalid? transaction [:items 0 :quantity] "Quantity is required"))))
(deftest item-quantity-must-be-greater-than-zero
(let [context (realize base-context)
transaction (transactions/create
(update-in
(attributes context)
[:items 0]
#(assoc % :quantity -1000M)))]
(is (invalid? transaction [:items 0 :quantity] "Quantity cannot be less than zero"))))
(deftest item-action-is-required
(let [context (realize base-context)
transaction (transactions/create
(update-in
(attributes context)
[:items 0]
#(dissoc % :action)))]
(is (invalid? transaction [:items 0 :action] "Action is required"))))
(deftest item-action-must-be-debit-or-credit
(let [context (realize base-context)
transaction (transactions/create
(update-in
(attributes context)
[:items 0]
#(assoc % :action :not-valid)))]
(is (invalid? transaction [:items 0 :action] "Action must be debit or credit"))))
(deftest sum-of-debits-must-equal-sum-of-credits
(let [context (realize base-context)
transaction (transactions/create
(update-in
(attributes context)
[:items 0]
#(assoc % :quantity 1001M)))]
(is (invalid? transaction [:items] "Sum of debits must equal the sum of credits"))))
(def balance-context
(merge base-context
{:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :credit
:account-id "Salary"
:quantity 1000}]}
{:transaction-date (t/local-date 2016 3 3)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "<NAME>"
:quantity 100}
{:action :credit
:account-id "Checking"
:quantity 100}]}]}))
(deftest item-balances-are-set-when-saved
(let [context (realize balance-context)
[checking-items
salary-items
groceries-items] (map #(items-by-account (:id %))
(:accounts context))]
; Transactions are returned with most recent first
(is (= [900M 1000M]
(map :balance checking-items))
"The checking account balances are correct")
(is (= [1000M] (map :balance salary-items))
"The salary account balances are correct")
(is (= [100M] (map :balance groceries-items))
"The groceries account balances are correct")))
(deftest item-indexes-are-set-when-saved
(let [context (realize balance-context)
[checking-items
salary-items
groceries-items] (map items-by-account
(:accounts context))]
(is (= [1 0] (map :index checking-items)) "The checking transaction items have correct indexes")
(is (= [0] (map :index salary-items)) "The salary transaction items have the correct indexes")
(is (= [0] (map :index groceries-items)) "The groceries transaction items have the correct indexes")))
(deftest account-balances-are-set-when-saved
(let [context (realize balance-context)
[checking
salary
groceries] (find-accounts context "Checking"
"Salary"
"Groceries")]
(assert-account-quantities checking 900M salary 1000M groceries 100M)))
(def insert-context
(merge base-context
{:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :credit
:account-id "Salary"
:quantity 1000}]}
{:transaction-date (t/local-date 2016 3 10)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "<NAME>"
:quantity 100}
{:action :credit
:account-id "Checking"
:quantity 100}]}
{:transaction-date (t/local-date 2016 3 3)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "<NAME>"
:quantity 99}
{:action :credit
:account-id "Checking"
:quantity 99}]}]}))
(deftest insert-transaction-before-the-end
(let [ctx (realize insert-context)
checking (find-account ctx "Checking")
items (items-by-account (:id checking))]
(is (= [{:index 2
:quantity 100M
:balance 801M}
{:index 1
:quantity 99M
:balance 901M}
{:index 0
:quantity 1000M
:balance 1000M}]
(map #(select-keys % [:index :quantity :balance]) items))
"The checking item balances should be correct")
(is (= [801M 1000M 199M]
(map (comp :quantity
accounts/find)
(:accounts ctx)))
"The accounts have the correct balances")))
(def multi-context
(-> base-context
(update-in [:accounts] #(conj % {:name "Bonus"
:type :income
:entity-id "Personal"
:commodity-id "USD"}))
(merge {:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :debit
:account-id "Checking"
:quantity 100}
{:action :credit
:account-id "Salary"
:quantity 1000}
{:action :credit
:account-id "Bonus"
:quantity 100}]}
{:transaction-date (t/local-date 2016 3 10)
:entity-id "Personal"
:description "<NAME>"
:items [{:action :debit
:account-id "Groceries"
:quantity 100}
{:action :credit
:account-id "Checking"
:quantity 100}]}]})))
(deftest create-a-transaction-with-multiple-items-for-one-account
(let [context (realize multi-context)
checking (find-account context "Checking")
checking-items (items-by-account (:id checking))
expected-checking-items #{{:transaction-date (t/local-date 2016 3 10) :quantity 100M}
{:transaction-date (t/local-date 2016 3 2) :quantity 1000M}
{:transaction-date (t/local-date 2016 3 2) :quantity 100M}}
actual-checking-items (->> checking-items
(map #(select-keys % [:transaction-date :quantity]))
set)]
(is (= expected-checking-items
actual-checking-items)
"The checking account items are correct")))
(def delete-context
(merge base-context
{:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "<NAME>"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :credit
:account-id "Salary"
:quantity 1000}]}
{:transaction-date (t/local-date 2016 3 3)
:entity-id "Personal"
:description "<NAME>"
:items [{:action :debit
:account-id "<NAME>"
:quantity 101}
{:action :credit
:account-id "Checking"
:quantity 101}]}
{:transaction-date (t/local-date 2016 3 4)
:entity-id "Personal"
:description "<NAME>"
:items [{:action :debit
:account-id "<NAME>"
:quantity 102}
{:action :credit
:account-id "Checking"
:quantity 102}]}]}))
(deftest delete-a-transaction
(let [context (realize delete-context)
[checking
_
groceries] (:accounts context)
checking-items-before (items-by-account (:id checking))
trans (-> context
:transactions
second)
_ (transactions/delete trans)
checking-items-after (items-by-account (:id checking))]
(testing "transaction item balances are adjusted"
(let [expected-before [{:index 2 :quantity 102M :balance 797M}
{:index 1 :quantity 101M :balance 899M}
{:index 0 :quantity 1000M :balance 1000M}]
actual-before (map #(select-keys % [:index :quantity :balance])
checking-items-before)
expected-after [{:index 1 :quantity 102M :balance 898M}
{:index 0 :quantity 1000M :balance 1000M}]
actual-after (map #(select-keys % [:index :quantity :balance]) checking-items-after)]
(is (= expected-before actual-before)
"Checking should have the correct items before delete")
(is (= expected-after actual-after)
"Checking should have the correct items after delete")))
(testing "account balances are adjusted"
(let [checking-after (accounts/find checking)
groceries-after (accounts/find groceries)]
(is (= 898M (:quantity checking-after))
"Checking should have the correct balance after delete")
(is (= 102M (:quantity groceries-after))
"Groceries should have the correct balance after delete")))))
(def update-context
(merge
base-context
{:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :credit
:account-id "Salary"
:quantity 1000}]}
{:transaction-date (t/local-date 2016 3 12)
:entity-id "Personal"
:description "<NAME>"
:items [{:action :debit
:account-id "<NAME>"
:quantity 101}
{:action :credit
:account-id "Checking"
:quantity 101}]}
{:transaction-date (t/local-date 2016 3 22)
:entity-id "Personal"
:description "K<NAME>ger"
:items [{:action :debit
:account-id "<NAME>"
:quantity 102}
{:action :credit
:account-id "Checking"
:quantity 102}]}]}))
(deftest get-a-transaction
(let [context (realize update-context)
{:keys [id transaction-date]} (find-transaction context (t/local-date 2016 3 2) "Paycheck")]
(testing "items are not included if not specified"
(let [transaction (first (transactions/search {:id id
:transaction-date transaction-date}))]
(is transaction "The transaction is retrieved successfully")
(is (nil? (:items transaction)) "The items are not included")
(is (= 1000M (:value transaction)) "The correct value is returned")))
(testing "items are included if specified"
(let [transaction (first (transactions/search {:id id
:transaction-date transaction-date}
{:include-items? true}))]
(is transaction "The transaction is retrieved successfully")
(is (:items transaction) "The items are included")))))
(def search-context
(merge
base-context
{:transactions [{:transaction-date #local-date "2016-01-01"
:entity-id "Personal"
:description "Paycheck"
:quantity 160101M
:debit-account-id "Checking"
:credit-account-id "Salary"}
{:transaction-date #local-date "2016-06-01"
:entity-id "Personal"
:description "Paycheck"
:quantity 160601M
:debit-account-id "Checking"
:credit-account-id "Salary"}
{:transaction-date #local-date "2017-01-01"
:entity-id "Personal"
:description "Paycheck"
:quantity 170101M
:debit-account-id "Checking"
:credit-account-id "Salary"}
{:transaction-date #local-date "2017-06-01"
:entity-id "Personal"
:description "Paycheck"
:quantity 170601M
:debit-account-id "Checking"
:credit-account-id "Salary"}
{:transaction-date #local-date "2017-06-15"
:entity-id "Personal"
:description "Paycheck"
:quantity 170615
:debit-account-id "Checking"
:credit-account-id "Salary"}]}))
(deftest search-by-year
(let [context (realize search-context)
entity (find-entity context "Personal")
actual (transactions/search {:transaction-date "2016"
:entity-id (:id entity)})]
(is (= [(t/local-date 2016 1 1)
(t/local-date 2016 6 1)]
(map :transaction-date actual))
"The transactions from the specified year are returned")))
(deftest search-by-month
(let [context (realize search-context)
entity (find-entity context "Personal")
actual (transactions/search {:transaction-date "2017-06"
:entity-id (:id entity)})]
(is (= [(t/local-date 2017 6 1)
(t/local-date 2017 6 15)]
(map :transaction-date actual))
"The transactions from the specified month are returned")))
(deftest search-by-date-string
(let [context (realize search-context)
entity (find-entity context "Personal")
actual (transactions/search {:transaction-date "2017-06-01"
:entity-id (:id entity)})]
(is (= [(t/local-date 2017 6 1)] (map :transaction-date actual))
"The transactions from the specified day are returned")))
(deftest search-by-date
(let [context (realize search-context)
entity (find-entity context "Personal")
actual (transactions/search {:transaction-date (t/local-date 2017 6 15)
:entity-id (:id entity)})]
(is (= [(t/local-date 2017 6 15)] (map :transaction-date actual))
"The transactions from the specified day are returned")))
(deftest search-by-date-vector
(let [context (realize search-context)
entity (find-entity context "Personal")
actual (transactions/search {:transaction-date [:between
(t/local-date 2017 6 1)
(t/local-date 2017 6 30)]
:entity-id (:id entity)})]
(is (= [(t/local-date 2017 6 1)
(t/local-date 2017 6 15)]
(map :transaction-date actual))
"The transactions from the specified day are returned")))
(defn- update-items
[{:keys [items] :as transaction} change-map]
(let [indexed-items (index-by :account-id items)
updated-items (reduce (fn [items [account-id item]]
(update-in items [account-id] merge item))
indexed-items
change-map)]
(assoc transaction :items (vals updated-items))))
(deftest update-a-transaction-change-quantity
(let [ctx (realize update-context)
checking (find-account ctx "Checking")
groceries (find-account ctx "Groceries")
result (-> (find-transaction ctx (t/local-date 2016 3 12) "Kroger")
(update-items {(:id groceries) {:quantity 99.99M}
(:id checking) {:quantity 99.99M}})
transactions/update)]
(is (valid? result))
(is (seq-of-maps-like? [{:index 2 :quantity 102.00M :balance 798.01M}
{:index 1 :quantity 99.99M :balance 900.01M}
{:index 0 :quantity 1000.00M :balance 1000.00M}]
(items-by-account (:id checking)))
"Expected the checking account items to be updated.")
(is (seq-of-maps-like? [{:index 1 :quantity 102.00M :balance 201.99M}
{:index 0 :quantity 99.99M :balance 99.99M}]
(items-by-account (:id groceries)))
"Expected the groceries account items to be updated.")
(assert-account-quantities checking 798.01M groceries 201.99M)))
(deftest rollback-a-failed-update
(let [real-reload transactions/reload
ctx (realize update-context)
checking (find-account ctx "Checking")
groceries (find-account ctx "Groceries")
trx (find-transaction ctx (t/local-date 2016 3 12) "Kroger")
call-count (atom 0)]
(with-redefs [transactions/reload (fn [transaction]
(swap! call-count inc)
(if (= 2 @call-count)
(throw (RuntimeException. "Induced exception"))
(real-reload transaction)))]
(try
(-> trx
(update-items {(:id groceries) {:quantity 99.99M}
(:id checking) {:quantity 99.99M}})
transactions/update)
(catch RuntimeException _ nil)))
(testing "transaction items are not updated"
(is (= #{101M} (->> (:items (transactions/reload trx))
(map :quantity)
(into #{})))))
(assert-account-quantities checking 797M groceries 203M)))
(deftest update-a-transaction-change-date
(let [ctx (realize update-context)
checking (find-account ctx "Checking")
groceries (find-account ctx "Groceries")
trx (find-transaction ctx (t/local-date 2016 3 22) "Kroger")
result (-> trx
(change-date (t/local-date 2016 3 10))
transactions/update)]
(is (valid? result))
(is (seq-of-maps-like? [{:index 2 :transaction-date (t/local-date 2016 3 12) :quantity 101M :balance 797M}
{:index 1 :transaction-date (t/local-date 2016 3 10) :quantity 102M :balance 898M}
{:index 0 :transaction-date (t/local-date 2016 3 2) :quantity 1000M :balance 1000M}]
(items-by-account (:id checking)))
"Expected the checking items to be updated")
(is (seq-of-maps-like? [{:index 1 :transaction-date (t/local-date 2016 3 12) :quantity 101M :balance 203M}
{:index 0 :transaction-date (t/local-date 2016 3 10) :quantity 102M :balance 102M}]
(items-by-account (:id groceries)))
"Expected the groceries items to be updated")
(assert-account-quantities checking 797M groceries 203M)
(testing "transaction is updated"
(is (= (t/local-date 2016 3 10)
(:transaction-date (transactions/reload result)))
"The transaction should be updated"))))
(def ^:private trading-update-context
(-> basic-context
(update-in [:commodities] concat [{:name "Apple, Inc."
:symbol "AAPL"
:type :stock
:exchange :nasdaq}])
(update-in [:accounts] concat [{:name "IRA"
:entity-id "Personal"
:type :asset}])
(assoc :trades [{:trade-date (t/local-date 2015 1 1)
:type :buy
:commodity-id "AAPL"
:account-id "IRA"
:shares 100M
:value 1000M}])))
(deftest update-a-trading-transaction-change-date
(with-context trading-update-context
(let [trx (transactions/find-by {:description "Purchase 100 shares of AAPL at 10.000"
:transaction-date (t/local-date 2015 1 1)}
{:include-items? true})
result (transactions/update (assoc trx :transaction-date (t/local-date 2015 2 1)))
account (find-account "IRA")
retrieved (lots/find-by {:account-id (:id account)})]
(is (empty? (v/error-messages result))
"There are no validation errors")
(is (= (t/local-date 2015 2 1)
(:purchase-date retrieved))
"The lot is updated with the correct purchase date"))))
(deftest update-a-transaction-cross-partition-boundary
(let [ctx (realize update-context)
checking (find-account ctx "Checking")
groceries (find-account ctx "Groceries")
trx (find-transaction ctx (t/local-date 2016 3 12) "Kroger")
result (-> trx
(assoc :transaction-date (t/local-date 2016 4 12))
transactions/update)]
(is (valid? result))
(is (seq-of-maps-like? [{:index 2 :quantity 101M :balance 797M}
{:index 1 :quantity 102M :balance 898M}
{:index 0 :quantity 1000M :balance 1000M}]
(items-by-account (:id checking)))
"Expected the checking items to be updated")
(is (seq-of-maps-like? [{:index 1 :quantity 101M :balance 203M}
{:index 0 :quantity 102M :balance 102M}]
(items-by-account (:id groceries)))
"Expected the groceries items to be updated")
(assert-account-quantities checking 797M groceries 203M)
(testing "transaction is updated"
(is (= (t/local-date 2016 4 12)
(:transaction-date (transactions/reload result)))
"The transaction should be updated"))))
(def short-circuit-context
(merge
base-context
{:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :credit
:account-id "Salary"
:quantity 1000}]}
{:transaction-date (t/local-date 2016 3 9)
:entity-id "Personal"
:description "<NAME>"
:items [{:action :debit
:account-id "<NAME>"
:quantity 101}
{:action :credit
:account-id "Checking"
:quantity 101}]}
{:transaction-date (t/local-date 2016 3 16)
:entity-id "Personal"
:description "<NAME>"
:items [{:action :debit
:account-id "<NAME>"
:quantity 102}
{:action :credit
:account-id "Checking"
:quantity 102}]}
{:transaction-date (t/local-date 2016 3 23)
:entity-id "Personal"
:description "<NAME>"
:items [{:action :debit
:account-id "<NAME>"
:quantity 103}
{:action :credit
:account-id "Checking"
:quantity 103}]}
{:transaction-date (t/local-date 2016 3 30)
:entity-id "Personal"
:description "<NAME>"
:items [{:action :debit
:account-id "<NAME>"
:quantity 104}
{:action :credit
:account-id "Checking"
:quantity 104}]}]}))
(defn- record-update-call
[item result]
(update-in result
[(:account-id item)]
#((fnil conj #{}) % (select-keys item [:index
:quantity
:balance]))))
(def ^:dynamic update-item nil)
; Trans. Date quantity Debit Credit
; 2016-03-02 1000 Checking Salary
; 2016-03-09 101 Groceries Checking
; 2016-03-16 102 Groceries Checking move this to 3/8
; 2016-03-23 103 Groceries Checking
; 2016-03-30 104 Groceries Checking
(deftest update-a-transaction-short-circuit-updates
(let [ctx (realize short-circuit-context)
checking (find-account ctx "Checking")
trx (find-transaction ctx (t/local-date 2016 3 16) "<NAME>roger")
updated (change-date trx (t/local-date 2016 3 8))
update-calls (atom {})]
(binding [update-item transactions/update-item-index-and-balance]
(with-redefs [transactions/update-item-index-and-balance (fn [item]
(swap! update-calls
(partial record-update-call item))
(update-item item))]
(let [result (transactions/update updated)
expected #{{:index 1
:quantity 102M
:balance 898M}
{:index 2
:quantity 101M
:balance 797M}}
actual (get @update-calls (:id checking))]
(is (valid? result))
(testing "the expected transactions are updated"
(is (= expected actual)
"Only items with changes are updated")
(is (not-any? #(= (:index %) 4) actual) "The last item is never updated"))
(assert-account-quantities checking 590M))))))
(def change-account-context
(-> base-context
(update-in [:accounts] #(conj % {:name "Rent"
:type :expense
:commodity-id "USD"}))
(merge
{:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :credit
:account-id "Salary"
:quantity 1000}]}
{:transaction-date (t/local-date 2016 3 9)
:entity-id "Personal"
:description "<NAME>roger"
:items [{:action :debit
:account-id "G<NAME>"
:quantity 101}
{:action :credit
:account-id "Checking"
:quantity 101}]}
{:transaction-date (t/local-date 2016 3 16)
:entity-id "Personal"
:description "<NAME>"
:items [{:action :debit
:account-id "<NAME>"
:quantity 102}
{:action :credit
:account-id "Checking"
:quantity 102}]}
{:transaction-date (t/local-date 2016 3 23)
:entity-id "Personal"
:description "<NAME>"
:items [{:action :debit
:account-id "<NAME>"
:quantity 103}
{:action :credit
:account-id "Checking"
:quantity 103}]}]})))
(deftest update-a-transaction-change-account
(let [ctx (realize change-account-context)
[rent
groceries] (find-accounts ctx "Rent" "Groceries")
result (-> (find-transaction ctx (t/local-date 2016 3 16) "Kroger")
(update-items {(:id groceries) {:account-id (:id rent)}})
transactions/update)]
(is (valid? result))
(is (seq-of-maps-like? [{:index 1
:quantity 103M
:balance 204M}
{:index 0
:quantity 101M
:balance 101M}]
(items-by-account (:id groceries)))
"Expected the groceries items to be updated")
(is (seq-of-maps-like? [{:index 0
:quantity 102M
:balance 102M}]
(items-by-account (:id rent)))
"Expected the rent items to be updated")
(assert-account-quantities groceries 204M rent 102M)))
(def change-action-context
(merge
base-context
{:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :credit
:account-id "Salary"
:quantity 1000}]}
{:transaction-date (t/local-date 2016 3 9)
:entity-id "Personal"
:description "<NAME>"
:items [{:action :debit
:account-id "<NAME>"
:quantity 103}
{:action :credit
:account-id "Checking"
:quantity 103}]}
{:transaction-date (t/local-date 2016 3 16)
:entity-id "Personal"
:description "<NAME>"
:items [{:action :debit
:account-id "<NAME>"
:quantity 12}
{:action :credit
:account-id "Checking"
:quantity 12}]}
{:transaction-date (t/local-date 2016 3 23)
:entity-id "Personal"
:description "<NAME>"
:items [{:action :debit
:account-id "<NAME>"
:quantity 101}
{:action :credit
:account-id "Checking"
:quantity 101}]}]}))
(deftest update-a-transaction-change-action
(let [context (realize change-action-context)
[checking _ groceries] (:accounts context)
result (-> (find-transaction context (t/local-date 2016 3 16) "Kroger")
(update-items {(:id groceries) {:action :credit}
(:id checking) {:action :debit}})
transactions/update)]
(is (valid? result))
(is (seq-of-maps-like? [{:index 2
:quantity 101M
:balance 192M}
{:index 1
:quantity 12M
:balance 91M}
{:index 0
:quantity 103M
:balance 103M}]
(items-by-account (:id groceries)))
"Expected the groceries items to be updated")
(assert-account-quantities groceries 192M checking 808M)))
(def add-remove-item-context
(-> base-context
(update-in [:accounts] #(conj % {:name "<NAME>"
:type :expense
:commodity-id "USD"}))
(merge {:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :credit
:account-id "Salary"
:quantity 1000}]}
{:transaction-date (t/local-date 2016 3 9)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "<NAME>"
:quantity 103}
{:action :credit
:account-id "Checking"
:quantity 103}]}
{:transaction-date (t/local-date 2016 3 16)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "<NAME>"
:quantity 90}
{:action :debit
:account-id "Pets"
:quantity 12}
{:action :credit
:account-id "Checking"
:quantity 102}]}
{:transaction-date (t/local-date 2016 3 23)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "<NAME>"
:quantity 101}
{:action :credit
:account-id "Checking"
:quantity 101}]}]})))
(deftest update-a-transaction-remove-item
(let [context (realize add-remove-item-context)
[checking
pets
groceries] (find-accounts context "Checking" "Pets" "Groceries")
result (-> (find-transaction context (t/local-date 2016 3 16) "Kroger")
(update-items {(:id groceries) {:quantity 102M
:value 102M}})
(update-in [:items] #(remove (fn [item]
(= (:account-id item)
(:id pets)))
%))
transactions/update)
expected-items [{:index 2
:quantity 101M
:balance 306M}
{:index 1
:quantity 102M
:balance 205M}
{:index 0
:quantity 103M
:balance 103M}]
actual-items (map #(select-keys % [:index :quantity :balance])
(items-by-account (:id groceries)))]
(is (valid? result) (str "Expected the transaction to be valid: " (prn-str (dissoc result :v/explanation))))
(assert-account-quantities pets 0M groceries 306M checking 694M)
(is (= expected-items actual-items)
"The account for the changed item should have the correct items")))
(deftest update-a-transaction-add-item
(let [context (realize add-remove-item-context)
[pets
groceries
checking] (find-accounts context "Pets" "Groceries" "Checking")
t2 (find-transaction context (t/local-date 2016 3 9) "Kroger")
to-update (-> t2
(update-items {(:id groceries) {:quantity 90M
:value 90M}})
(update-in [:items] #(conj % {:action :debit
:account-id (:id pets)
:quantity 13M
:value 13M})))
_ (transactions/update to-update)
expected-items [{:index 1
:quantity 12M
:balance 25M}
{:index 0
:quantity 13M
:balance 13M}]
actual-items (map #(select-keys % [:index :quantity :balance])
(items-by-account (:id pets)))]
(testing "item values are correct"
(is (= expected-items actual-items)
"The Pets account should have the correct items"))
(assert-account-quantities pets 25M groceries 281M checking 694M)))
(def balance-delta-context
(merge
base-context
{:transactions [{:transaction-date (t/local-date 2016 1 1)
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000M}
{:action :credit
:account-id "Salary"
:quantity 1000M}]}
{:transaction-date (t/local-date 2016 1 15)
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1001M}
{:action :credit
:account-id "Salary"
:quantity 1001M}]}
{:transaction-date (t/local-date 2016 2 1)
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1100M}
{:action :credit
:account-id "Salary"
:quantity 1100M}]}
{:transaction-date (t/local-date 2016 2 15)
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1102M}
{:action :credit
:account-id "Salary"
:quantity 1102M}]}
{:transaction-date (t/local-date 2016 3 1)
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1200M}
{:action :credit
:account-id "Salary"
:quantity 1200M}]}]}))
(deftest get-a-balance-delta
(let [context (realize balance-delta-context)
[_ salary] (:accounts context)
january (transactions/balance-delta salary
(t/local-date 2016 1 1)
(t/local-date 2016 1 31))
february (transactions/balance-delta salary
(t/local-date 2016 2 1)
(t/local-date 2016 2 29))]
(is (= 2001M january) "The January value is the sum of polarized quantitys for the period")
(is (= 2202M february) "The February value is the sum of the polarized quantitys for the period")))
(deftest get-a-balance-as-of
(let [context (realize balance-delta-context)
[checking] (:accounts context)
january (transactions/balance-as-of checking
(t/local-date 2016 1 31))
february (transactions/balance-as-of checking
(t/local-date 2016 2 29))]
(is (= 2001M january) "The January value is the balance for the last item in the period")
(is (= 4203M february) "The February value is the balance for the last item in the period")))
(deftest create-multiple-transactions-then-recalculate-balances
(let [context (realize base-context)
entity (-> context :entities first)
[checking
salary
groceries] (:accounts context)]
(transactions/with-delayed-balancing (:id entity)
(transactions/create {:entity-id (:id entity)
:transaction-date (t/local-date 2017 1 1)
:description "Paycheck"
:items [{:action :debit
:account-id (:id checking)
:quantity 1000M}
{:action :credit
:account-id (:id salary)
:quantity 1000M}]})
(transactions/create {:entity-id (:id entity)
:transaction-date (t/local-date 2017 1 15)
:description "Market Street"
:items [{:action :debit
:account-id (:id groceries)
:quantity 100M}
{:action :credit
:account-id (:id checking)
:quantity 100M}]})
(transactions/create {:entity-id (:id entity)
:transaction-date (t/local-date 2017 2 1)
:description "Paycheck"
:items [{:action :debit
:account-id (:id checking)
:quantity 1000M}
{:action :credit
:account-id (:id salary)
:quantity 1000M}]})
(is (= 0M (:quantity (accounts/reload checking)))
"The account balance is not recalculated before the form exits"))
(is (= 1900M (:quantity (accounts/reload checking)))
"The account balance is recalculated after the form exits")))
(deftest use-simplified-items
(let [context (realize base-context)
entity (find-entity context "Personal")
[checking salary] (find-accounts context "Checking" "Salary")
trx (transactions/create {:entity-id (:id entity)
:transaction-date (t/local-date 2017 3 2)
:description "Paycheck"
:quantity 1000M
:debit-account-id (:id checking)
:credit-account-id (:id salary)})
actual-items (map #(select-keys % [:account-id :quantity :action]) (:items trx))
expected-items [{:account-id (:id checking)
:action :debit
:quantity 1000M}
{:account-id (:id salary)
:action :credit
:quantity 1000M}]]
(is (valid? trx))
(is (= expected-items actual-items) "The items are created correctly")))
(deftest set-account-boundaries
(let [context (realize base-context)
entity (find-entity context "Personal")
[checking
salary
groceries] (find-accounts context "Checking" "Salary" "Groceries")
created (->> [{:transaction-date (t/local-date 2017 2 27)
:description "Paycheck"
:quantity 1000M
:debit-account-id (:id checking)
:credit-account-id (:id salary)}
{:transaction-date (t/local-date 2017 3 2)
:description "Kroger"
:quantity 100M
:debit-account-id (:id groceries)
:credit-account-id (:id checking)}]
(map #(assoc % :entity-id (:id entity)))
(mapv transactions/create))
[checking
salary
groceries] (map accounts/reload [checking salary groceries])]
(is (valid? created))
(is (= (t/local-date 2017 2 27) (:earliest-transaction-date checking))
"The checking account's earliest is the paycheck")
(is (= (t/local-date 2017 3 2) (:latest-transaction-date checking))
"The checking account's latest is the grocery purchase")
(is (= (t/local-date 2017 2 27) (:earliest-transaction-date salary))
"The salary account's earliest is the paycheck")
(is (= (t/local-date 2017 2 27) (:latest-transaction-date salary))
"The salary account's latest is the paycheck")
(is (= (t/local-date 2017 3 2) (:earliest-transaction-date groceries))
"The groceries account's earliest is the grocery purchase")
(is (= (t/local-date 2017 3 2) (:latest-transaction-date groceries))
"The groceries account's latest is the grocery purchase")))
(def ^:private existing-reconciliation-context
(-> base-context
(update-in [:accounts] conj {:name "Rent"
:type :expense
:entity-id "Personal"})
(assoc :transactions [{:transaction-date (t/local-date 2017 1 1)
:description "Paycheck"
:debit-account-id "Checking"
:credit-account-id "Salary"
:quantity 1000M}
{:transaction-date (t/local-date 2017 1 2)
:description "Landlord"
:debit-account-id "Rent"
:credit-account-id "Checking"
:quantity 500M}
{:transaction-date (t/local-date 2017 1 3)
:description "Kroger"
:debit-account-id "<NAME>"
:credit-account-id "Checking"
:quantity 45M}
{:transaction-date (t/local-date 2017 1 10)
:description "Safeway"
:debit-account-id "G<NAME>"
:credit-account-id "Checking"
:quantity 53M}]
:reconciliations
[{:account-id "Checking"
:end-of-period (t/local-date 2017 1 1)
:balance 1000M
:status :completed
:item-refs [{:transaction-date (t/local-date 2017 1 1)
:quantity 1000M}]}])))
(deftest the-quantity-and-action-of-a-reconciled-item-cannot-be-changed
(let [context (realize existing-reconciliation-context)
transaction (find-transaction context (t/local-date 2017 1 1) "Paycheck")
result1 (transactions/update (update-in transaction [:items]
#(map (fn [item]
(assoc item :quantity 1M))
%)))
result2 (transactions/update (update-in transaction [:items]
#(map (fn [item]
(update-in item [:action] (fn [a] (if (= :credit a)
:debit
:credit))))
%)))]
(is (invalid? result1 [:items] "A reconciled item cannot be updated"))
(is (invalid? result2 [:items] "A reconciled item cannot be updated"))))
(deftest a-reconciled-transaction-item-cannot-be-deleted
(let [context (realize existing-reconciliation-context)
[item-id date] (-> context :reconciliations first :item-refs first)
transaction (transactions/find-by-item-id item-id date)]
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"A transaction with reconciled items cannot be deleted."
(transactions/delete transaction))
"An exception is raised")
(is (do
(try
(transactions/delete transaction)
(catch clojure.lang.ExceptionInfo _ nil))
(transactions/find-by-item-id item-id date))
"The transaction can be retrieved after the delete has been denied")))
| true | (ns clj-money.models.transactions-test
(:require [clojure.test :refer [deftest use-fixtures testing is]]
[clj-time.core :as t]
[clj-factory.core :refer [factory]]
[dgknght.app-lib.core :refer [index-by]]
[dgknght.app-lib.test]
[dgknght.app-lib.validation :as v]
[clj-money.transactions :refer [change-date]]
[clj-money.models.accounts :as accounts]
[clj-money.models.transactions :as transactions]
[clj-money.models.lots :as lots]
[clj-money.factories.user-factory]
[clj-money.factories.entity-factory]
[clj-money.test-context :refer [realize
with-context
basic-context
find-entity
find-account
find-accounts
find-transaction]]
[clj-money.test-helpers :refer [reset-db]]))
(use-fixtures :each reset-db)
(defn- assert-account-quantities
[& args]
(->> args
(partition 2)
(map (fn [[account balance]]
(is (= balance (:quantity (accounts/reload account)))
(format "%s should have the quantity %s"
(:name account)
balance))))
dorun))
(defn items-by-account
[account]
(transactions/items-by-account
account
[(t/local-date 2015 1 1)
(t/local-date 2017 12 31)]))
(def base-context
{:users [(factory :user, {:email "PI:EMAIL:<EMAIL>END_PI"})]
:entities [{:name "Personal"}]
:commodities [{:name "US Dollar"
:symbol "USD"
:type :currency}]
:accounts [{:name "Checking"
:type :asset}
{:name "Salary"
:type :income}
{:name "Groceries"
:type :expense}]})
(defn attributes
[context]
(let [[checking
salary] (:accounts context)]
{:transaction-date (t/local-date 2016 3 2)
:description "Paycheck"
:memo "final, partial"
:entity-id (-> context :entities first :id)
:items [{:account-id (:id checking)
:action :debit
:memo "conf # 123"
:quantity 1000M}
{:account-id (:id salary)
:action :credit
:quantity 1000M}]}))
(deftest create-a-transaction
(let [context (realize base-context)
transaction (transactions/create (attributes context))]
(is transaction "A non-nil value is returned")
(testing "return value includes the new id"
(is (valid? transaction))
(is (:id transaction) "A map with the new ID is returned"))
(testing "transaction can be retrieved"
(let [actual (transactions/find transaction)
expected {:transaction-date (t/local-date 2016 3 2)
:description "Paycheck"
:memo "final, partial"
:entity-id (-> context :entities first :id)
:value 1000M}
expected-items [{:description "Paycheck"
:account-id (:id (find-account context "Checking"))
:index 0
:transaction-date (t/local-date 2016 3 2)
:action :debit
:negative false
:memo "conf # 123"
:quantity 1000M
:polarized-quantity 1000M
:balance 1000M
:value 1000M
:reconciliation-status nil
:reconciliation-id nil
:reconciled? false}
{:description "Paycheck"
:account-id (:id (find-account context "Salary"))
:index 0
:transaction-date (t/local-date 2016 3 2)
:action :credit
:negative false
:memo nil
:quantity 1000M
:polarized-quantity 1000M
:balance 1000M
:value 1000M
:reconciliation-status nil
:reconciliation-id nil
:reconciled? false}]]
(is (comparable? expected actual "The correct data is retrieved"))
(doseq [[e a] (partition 2 (interleave expected-items (:items actual)))]
(is (comparable? e a) "Each item is retrieved correctly"))))))
(deftest rollback-on-failure
(let [call-count (atom 0)]
(with-redefs [transactions/before-save-item (fn [item]
(if (= 1 @call-count)
(throw (RuntimeException. "Induced error"))
(do
(swap! call-count inc)
(update-in item [:action] name))))]
(let [context (realize base-context)
[checking
salary] (:accounts context)
_ (try
(transactions/create (attributes context))
(catch RuntimeException _
nil))]
(testing "records are not created"
(is (= 0 (count (transactions/search
{:entity-id (-> context :entities first :id)
:transaction-date "2016"})))
"The transaction should not be saved")
(is (= 0 (count (items-by-account checking)))
"The transaction item for checking should not be created")
(is (= 0 (count (items-by-account salary)))
"The transaction item for salary should not be created"))
(assert-account-quantities checking 0M salary 0M)))))
(deftest transaction-date-is-required
(let [context (realize base-context)
transaction (transactions/create (dissoc (attributes context)
:transaction-date))]
(is (invalid? transaction [:transaction-date] "Transaction date is required"))))
(deftest entity-id-is-required
(let [context (realize base-context)
result (transactions/create (dissoc (attributes context)
:entity-id))]
(is (invalid? result [:entity-id] "Entity is required"))))
(deftest items-are-required
(let [context (realize base-context)
result (transactions/create
(-> context
attributes
(assoc :items [])))]
(is (invalid? result [:items] "Items must contain at least 1 item(s)"))))
(deftest item-account-id-is-required
(let [context (realize base-context)
transaction (transactions/create
(update-in
(attributes context)
[:items 0]
#(dissoc % :account-id)))]
(is (invalid? transaction [:items 0 :account-id] "Account is required"))))
(deftest item-quantity-is-required
(let [context (realize base-context)
transaction (transactions/create
(update-in
(attributes context)
[:items 0]
#(dissoc % :quantity)))]
(is (invalid? transaction [:items 0 :quantity] "Quantity is required"))))
(deftest item-quantity-must-be-greater-than-zero
(let [context (realize base-context)
transaction (transactions/create
(update-in
(attributes context)
[:items 0]
#(assoc % :quantity -1000M)))]
(is (invalid? transaction [:items 0 :quantity] "Quantity cannot be less than zero"))))
(deftest item-action-is-required
(let [context (realize base-context)
transaction (transactions/create
(update-in
(attributes context)
[:items 0]
#(dissoc % :action)))]
(is (invalid? transaction [:items 0 :action] "Action is required"))))
(deftest item-action-must-be-debit-or-credit
(let [context (realize base-context)
transaction (transactions/create
(update-in
(attributes context)
[:items 0]
#(assoc % :action :not-valid)))]
(is (invalid? transaction [:items 0 :action] "Action must be debit or credit"))))
(deftest sum-of-debits-must-equal-sum-of-credits
(let [context (realize base-context)
transaction (transactions/create
(update-in
(attributes context)
[:items 0]
#(assoc % :quantity 1001M)))]
(is (invalid? transaction [:items] "Sum of debits must equal the sum of credits"))))
(def balance-context
(merge base-context
{:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :credit
:account-id "Salary"
:quantity 1000}]}
{:transaction-date (t/local-date 2016 3 3)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "PI:NAME:<NAME>END_PI"
:quantity 100}
{:action :credit
:account-id "Checking"
:quantity 100}]}]}))
(deftest item-balances-are-set-when-saved
(let [context (realize balance-context)
[checking-items
salary-items
groceries-items] (map #(items-by-account (:id %))
(:accounts context))]
; Transactions are returned with most recent first
(is (= [900M 1000M]
(map :balance checking-items))
"The checking account balances are correct")
(is (= [1000M] (map :balance salary-items))
"The salary account balances are correct")
(is (= [100M] (map :balance groceries-items))
"The groceries account balances are correct")))
(deftest item-indexes-are-set-when-saved
(let [context (realize balance-context)
[checking-items
salary-items
groceries-items] (map items-by-account
(:accounts context))]
(is (= [1 0] (map :index checking-items)) "The checking transaction items have correct indexes")
(is (= [0] (map :index salary-items)) "The salary transaction items have the correct indexes")
(is (= [0] (map :index groceries-items)) "The groceries transaction items have the correct indexes")))
(deftest account-balances-are-set-when-saved
(let [context (realize balance-context)
[checking
salary
groceries] (find-accounts context "Checking"
"Salary"
"Groceries")]
(assert-account-quantities checking 900M salary 1000M groceries 100M)))
(def insert-context
(merge base-context
{:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :credit
:account-id "Salary"
:quantity 1000}]}
{:transaction-date (t/local-date 2016 3 10)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "PI:NAME:<NAME>END_PI"
:quantity 100}
{:action :credit
:account-id "Checking"
:quantity 100}]}
{:transaction-date (t/local-date 2016 3 3)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "PI:NAME:<NAME>END_PI"
:quantity 99}
{:action :credit
:account-id "Checking"
:quantity 99}]}]}))
(deftest insert-transaction-before-the-end
(let [ctx (realize insert-context)
checking (find-account ctx "Checking")
items (items-by-account (:id checking))]
(is (= [{:index 2
:quantity 100M
:balance 801M}
{:index 1
:quantity 99M
:balance 901M}
{:index 0
:quantity 1000M
:balance 1000M}]
(map #(select-keys % [:index :quantity :balance]) items))
"The checking item balances should be correct")
(is (= [801M 1000M 199M]
(map (comp :quantity
accounts/find)
(:accounts ctx)))
"The accounts have the correct balances")))
(def multi-context
(-> base-context
(update-in [:accounts] #(conj % {:name "Bonus"
:type :income
:entity-id "Personal"
:commodity-id "USD"}))
(merge {:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :debit
:account-id "Checking"
:quantity 100}
{:action :credit
:account-id "Salary"
:quantity 1000}
{:action :credit
:account-id "Bonus"
:quantity 100}]}
{:transaction-date (t/local-date 2016 3 10)
:entity-id "Personal"
:description "PI:NAME:<NAME>END_PI"
:items [{:action :debit
:account-id "Groceries"
:quantity 100}
{:action :credit
:account-id "Checking"
:quantity 100}]}]})))
(deftest create-a-transaction-with-multiple-items-for-one-account
(let [context (realize multi-context)
checking (find-account context "Checking")
checking-items (items-by-account (:id checking))
expected-checking-items #{{:transaction-date (t/local-date 2016 3 10) :quantity 100M}
{:transaction-date (t/local-date 2016 3 2) :quantity 1000M}
{:transaction-date (t/local-date 2016 3 2) :quantity 100M}}
actual-checking-items (->> checking-items
(map #(select-keys % [:transaction-date :quantity]))
set)]
(is (= expected-checking-items
actual-checking-items)
"The checking account items are correct")))
(def delete-context
(merge base-context
{:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "PI:NAME:<NAME>END_PI"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :credit
:account-id "Salary"
:quantity 1000}]}
{:transaction-date (t/local-date 2016 3 3)
:entity-id "Personal"
:description "PI:NAME:<NAME>END_PI"
:items [{:action :debit
:account-id "PI:NAME:<NAME>END_PI"
:quantity 101}
{:action :credit
:account-id "Checking"
:quantity 101}]}
{:transaction-date (t/local-date 2016 3 4)
:entity-id "Personal"
:description "PI:NAME:<NAME>END_PI"
:items [{:action :debit
:account-id "PI:NAME:<NAME>END_PI"
:quantity 102}
{:action :credit
:account-id "Checking"
:quantity 102}]}]}))
(deftest delete-a-transaction
(let [context (realize delete-context)
[checking
_
groceries] (:accounts context)
checking-items-before (items-by-account (:id checking))
trans (-> context
:transactions
second)
_ (transactions/delete trans)
checking-items-after (items-by-account (:id checking))]
(testing "transaction item balances are adjusted"
(let [expected-before [{:index 2 :quantity 102M :balance 797M}
{:index 1 :quantity 101M :balance 899M}
{:index 0 :quantity 1000M :balance 1000M}]
actual-before (map #(select-keys % [:index :quantity :balance])
checking-items-before)
expected-after [{:index 1 :quantity 102M :balance 898M}
{:index 0 :quantity 1000M :balance 1000M}]
actual-after (map #(select-keys % [:index :quantity :balance]) checking-items-after)]
(is (= expected-before actual-before)
"Checking should have the correct items before delete")
(is (= expected-after actual-after)
"Checking should have the correct items after delete")))
(testing "account balances are adjusted"
(let [checking-after (accounts/find checking)
groceries-after (accounts/find groceries)]
(is (= 898M (:quantity checking-after))
"Checking should have the correct balance after delete")
(is (= 102M (:quantity groceries-after))
"Groceries should have the correct balance after delete")))))
(def update-context
(merge
base-context
{:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :credit
:account-id "Salary"
:quantity 1000}]}
{:transaction-date (t/local-date 2016 3 12)
:entity-id "Personal"
:description "PI:NAME:<NAME>END_PI"
:items [{:action :debit
:account-id "PI:NAME:<NAME>END_PI"
:quantity 101}
{:action :credit
:account-id "Checking"
:quantity 101}]}
{:transaction-date (t/local-date 2016 3 22)
:entity-id "Personal"
:description "KPI:NAME:<NAME>END_PIger"
:items [{:action :debit
:account-id "PI:NAME:<NAME>END_PI"
:quantity 102}
{:action :credit
:account-id "Checking"
:quantity 102}]}]}))
(deftest get-a-transaction
(let [context (realize update-context)
{:keys [id transaction-date]} (find-transaction context (t/local-date 2016 3 2) "Paycheck")]
(testing "items are not included if not specified"
(let [transaction (first (transactions/search {:id id
:transaction-date transaction-date}))]
(is transaction "The transaction is retrieved successfully")
(is (nil? (:items transaction)) "The items are not included")
(is (= 1000M (:value transaction)) "The correct value is returned")))
(testing "items are included if specified"
(let [transaction (first (transactions/search {:id id
:transaction-date transaction-date}
{:include-items? true}))]
(is transaction "The transaction is retrieved successfully")
(is (:items transaction) "The items are included")))))
(def search-context
(merge
base-context
{:transactions [{:transaction-date #local-date "2016-01-01"
:entity-id "Personal"
:description "Paycheck"
:quantity 160101M
:debit-account-id "Checking"
:credit-account-id "Salary"}
{:transaction-date #local-date "2016-06-01"
:entity-id "Personal"
:description "Paycheck"
:quantity 160601M
:debit-account-id "Checking"
:credit-account-id "Salary"}
{:transaction-date #local-date "2017-01-01"
:entity-id "Personal"
:description "Paycheck"
:quantity 170101M
:debit-account-id "Checking"
:credit-account-id "Salary"}
{:transaction-date #local-date "2017-06-01"
:entity-id "Personal"
:description "Paycheck"
:quantity 170601M
:debit-account-id "Checking"
:credit-account-id "Salary"}
{:transaction-date #local-date "2017-06-15"
:entity-id "Personal"
:description "Paycheck"
:quantity 170615
:debit-account-id "Checking"
:credit-account-id "Salary"}]}))
(deftest search-by-year
(let [context (realize search-context)
entity (find-entity context "Personal")
actual (transactions/search {:transaction-date "2016"
:entity-id (:id entity)})]
(is (= [(t/local-date 2016 1 1)
(t/local-date 2016 6 1)]
(map :transaction-date actual))
"The transactions from the specified year are returned")))
(deftest search-by-month
(let [context (realize search-context)
entity (find-entity context "Personal")
actual (transactions/search {:transaction-date "2017-06"
:entity-id (:id entity)})]
(is (= [(t/local-date 2017 6 1)
(t/local-date 2017 6 15)]
(map :transaction-date actual))
"The transactions from the specified month are returned")))
(deftest search-by-date-string
(let [context (realize search-context)
entity (find-entity context "Personal")
actual (transactions/search {:transaction-date "2017-06-01"
:entity-id (:id entity)})]
(is (= [(t/local-date 2017 6 1)] (map :transaction-date actual))
"The transactions from the specified day are returned")))
(deftest search-by-date
(let [context (realize search-context)
entity (find-entity context "Personal")
actual (transactions/search {:transaction-date (t/local-date 2017 6 15)
:entity-id (:id entity)})]
(is (= [(t/local-date 2017 6 15)] (map :transaction-date actual))
"The transactions from the specified day are returned")))
(deftest search-by-date-vector
(let [context (realize search-context)
entity (find-entity context "Personal")
actual (transactions/search {:transaction-date [:between
(t/local-date 2017 6 1)
(t/local-date 2017 6 30)]
:entity-id (:id entity)})]
(is (= [(t/local-date 2017 6 1)
(t/local-date 2017 6 15)]
(map :transaction-date actual))
"The transactions from the specified day are returned")))
(defn- update-items
[{:keys [items] :as transaction} change-map]
(let [indexed-items (index-by :account-id items)
updated-items (reduce (fn [items [account-id item]]
(update-in items [account-id] merge item))
indexed-items
change-map)]
(assoc transaction :items (vals updated-items))))
(deftest update-a-transaction-change-quantity
(let [ctx (realize update-context)
checking (find-account ctx "Checking")
groceries (find-account ctx "Groceries")
result (-> (find-transaction ctx (t/local-date 2016 3 12) "Kroger")
(update-items {(:id groceries) {:quantity 99.99M}
(:id checking) {:quantity 99.99M}})
transactions/update)]
(is (valid? result))
(is (seq-of-maps-like? [{:index 2 :quantity 102.00M :balance 798.01M}
{:index 1 :quantity 99.99M :balance 900.01M}
{:index 0 :quantity 1000.00M :balance 1000.00M}]
(items-by-account (:id checking)))
"Expected the checking account items to be updated.")
(is (seq-of-maps-like? [{:index 1 :quantity 102.00M :balance 201.99M}
{:index 0 :quantity 99.99M :balance 99.99M}]
(items-by-account (:id groceries)))
"Expected the groceries account items to be updated.")
(assert-account-quantities checking 798.01M groceries 201.99M)))
(deftest rollback-a-failed-update
(let [real-reload transactions/reload
ctx (realize update-context)
checking (find-account ctx "Checking")
groceries (find-account ctx "Groceries")
trx (find-transaction ctx (t/local-date 2016 3 12) "Kroger")
call-count (atom 0)]
(with-redefs [transactions/reload (fn [transaction]
(swap! call-count inc)
(if (= 2 @call-count)
(throw (RuntimeException. "Induced exception"))
(real-reload transaction)))]
(try
(-> trx
(update-items {(:id groceries) {:quantity 99.99M}
(:id checking) {:quantity 99.99M}})
transactions/update)
(catch RuntimeException _ nil)))
(testing "transaction items are not updated"
(is (= #{101M} (->> (:items (transactions/reload trx))
(map :quantity)
(into #{})))))
(assert-account-quantities checking 797M groceries 203M)))
(deftest update-a-transaction-change-date
(let [ctx (realize update-context)
checking (find-account ctx "Checking")
groceries (find-account ctx "Groceries")
trx (find-transaction ctx (t/local-date 2016 3 22) "Kroger")
result (-> trx
(change-date (t/local-date 2016 3 10))
transactions/update)]
(is (valid? result))
(is (seq-of-maps-like? [{:index 2 :transaction-date (t/local-date 2016 3 12) :quantity 101M :balance 797M}
{:index 1 :transaction-date (t/local-date 2016 3 10) :quantity 102M :balance 898M}
{:index 0 :transaction-date (t/local-date 2016 3 2) :quantity 1000M :balance 1000M}]
(items-by-account (:id checking)))
"Expected the checking items to be updated")
(is (seq-of-maps-like? [{:index 1 :transaction-date (t/local-date 2016 3 12) :quantity 101M :balance 203M}
{:index 0 :transaction-date (t/local-date 2016 3 10) :quantity 102M :balance 102M}]
(items-by-account (:id groceries)))
"Expected the groceries items to be updated")
(assert-account-quantities checking 797M groceries 203M)
(testing "transaction is updated"
(is (= (t/local-date 2016 3 10)
(:transaction-date (transactions/reload result)))
"The transaction should be updated"))))
(def ^:private trading-update-context
(-> basic-context
(update-in [:commodities] concat [{:name "Apple, Inc."
:symbol "AAPL"
:type :stock
:exchange :nasdaq}])
(update-in [:accounts] concat [{:name "IRA"
:entity-id "Personal"
:type :asset}])
(assoc :trades [{:trade-date (t/local-date 2015 1 1)
:type :buy
:commodity-id "AAPL"
:account-id "IRA"
:shares 100M
:value 1000M}])))
(deftest update-a-trading-transaction-change-date
(with-context trading-update-context
(let [trx (transactions/find-by {:description "Purchase 100 shares of AAPL at 10.000"
:transaction-date (t/local-date 2015 1 1)}
{:include-items? true})
result (transactions/update (assoc trx :transaction-date (t/local-date 2015 2 1)))
account (find-account "IRA")
retrieved (lots/find-by {:account-id (:id account)})]
(is (empty? (v/error-messages result))
"There are no validation errors")
(is (= (t/local-date 2015 2 1)
(:purchase-date retrieved))
"The lot is updated with the correct purchase date"))))
(deftest update-a-transaction-cross-partition-boundary
(let [ctx (realize update-context)
checking (find-account ctx "Checking")
groceries (find-account ctx "Groceries")
trx (find-transaction ctx (t/local-date 2016 3 12) "Kroger")
result (-> trx
(assoc :transaction-date (t/local-date 2016 4 12))
transactions/update)]
(is (valid? result))
(is (seq-of-maps-like? [{:index 2 :quantity 101M :balance 797M}
{:index 1 :quantity 102M :balance 898M}
{:index 0 :quantity 1000M :balance 1000M}]
(items-by-account (:id checking)))
"Expected the checking items to be updated")
(is (seq-of-maps-like? [{:index 1 :quantity 101M :balance 203M}
{:index 0 :quantity 102M :balance 102M}]
(items-by-account (:id groceries)))
"Expected the groceries items to be updated")
(assert-account-quantities checking 797M groceries 203M)
(testing "transaction is updated"
(is (= (t/local-date 2016 4 12)
(:transaction-date (transactions/reload result)))
"The transaction should be updated"))))
(def short-circuit-context
(merge
base-context
{:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :credit
:account-id "Salary"
:quantity 1000}]}
{:transaction-date (t/local-date 2016 3 9)
:entity-id "Personal"
:description "PI:NAME:<NAME>END_PI"
:items [{:action :debit
:account-id "PI:NAME:<NAME>END_PI"
:quantity 101}
{:action :credit
:account-id "Checking"
:quantity 101}]}
{:transaction-date (t/local-date 2016 3 16)
:entity-id "Personal"
:description "PI:NAME:<NAME>END_PI"
:items [{:action :debit
:account-id "PI:NAME:<NAME>END_PI"
:quantity 102}
{:action :credit
:account-id "Checking"
:quantity 102}]}
{:transaction-date (t/local-date 2016 3 23)
:entity-id "Personal"
:description "PI:NAME:<NAME>END_PI"
:items [{:action :debit
:account-id "PI:NAME:<NAME>END_PI"
:quantity 103}
{:action :credit
:account-id "Checking"
:quantity 103}]}
{:transaction-date (t/local-date 2016 3 30)
:entity-id "Personal"
:description "PI:NAME:<NAME>END_PI"
:items [{:action :debit
:account-id "PI:NAME:<NAME>END_PI"
:quantity 104}
{:action :credit
:account-id "Checking"
:quantity 104}]}]}))
(defn- record-update-call
[item result]
(update-in result
[(:account-id item)]
#((fnil conj #{}) % (select-keys item [:index
:quantity
:balance]))))
(def ^:dynamic update-item nil)
; Trans. Date quantity Debit Credit
; 2016-03-02 1000 Checking Salary
; 2016-03-09 101 Groceries Checking
; 2016-03-16 102 Groceries Checking move this to 3/8
; 2016-03-23 103 Groceries Checking
; 2016-03-30 104 Groceries Checking
(deftest update-a-transaction-short-circuit-updates
(let [ctx (realize short-circuit-context)
checking (find-account ctx "Checking")
trx (find-transaction ctx (t/local-date 2016 3 16) "PI:NAME:<NAME>END_PIroger")
updated (change-date trx (t/local-date 2016 3 8))
update-calls (atom {})]
(binding [update-item transactions/update-item-index-and-balance]
(with-redefs [transactions/update-item-index-and-balance (fn [item]
(swap! update-calls
(partial record-update-call item))
(update-item item))]
(let [result (transactions/update updated)
expected #{{:index 1
:quantity 102M
:balance 898M}
{:index 2
:quantity 101M
:balance 797M}}
actual (get @update-calls (:id checking))]
(is (valid? result))
(testing "the expected transactions are updated"
(is (= expected actual)
"Only items with changes are updated")
(is (not-any? #(= (:index %) 4) actual) "The last item is never updated"))
(assert-account-quantities checking 590M))))))
(def change-account-context
(-> base-context
(update-in [:accounts] #(conj % {:name "Rent"
:type :expense
:commodity-id "USD"}))
(merge
{:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :credit
:account-id "Salary"
:quantity 1000}]}
{:transaction-date (t/local-date 2016 3 9)
:entity-id "Personal"
:description "PI:NAME:<NAME>END_PIroger"
:items [{:action :debit
:account-id "GPI:NAME:<NAME>END_PI"
:quantity 101}
{:action :credit
:account-id "Checking"
:quantity 101}]}
{:transaction-date (t/local-date 2016 3 16)
:entity-id "Personal"
:description "PI:NAME:<NAME>END_PI"
:items [{:action :debit
:account-id "PI:NAME:<NAME>END_PI"
:quantity 102}
{:action :credit
:account-id "Checking"
:quantity 102}]}
{:transaction-date (t/local-date 2016 3 23)
:entity-id "Personal"
:description "PI:NAME:<NAME>END_PI"
:items [{:action :debit
:account-id "PI:NAME:<NAME>END_PI"
:quantity 103}
{:action :credit
:account-id "Checking"
:quantity 103}]}]})))
(deftest update-a-transaction-change-account
(let [ctx (realize change-account-context)
[rent
groceries] (find-accounts ctx "Rent" "Groceries")
result (-> (find-transaction ctx (t/local-date 2016 3 16) "Kroger")
(update-items {(:id groceries) {:account-id (:id rent)}})
transactions/update)]
(is (valid? result))
(is (seq-of-maps-like? [{:index 1
:quantity 103M
:balance 204M}
{:index 0
:quantity 101M
:balance 101M}]
(items-by-account (:id groceries)))
"Expected the groceries items to be updated")
(is (seq-of-maps-like? [{:index 0
:quantity 102M
:balance 102M}]
(items-by-account (:id rent)))
"Expected the rent items to be updated")
(assert-account-quantities groceries 204M rent 102M)))
(def change-action-context
(merge
base-context
{:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :credit
:account-id "Salary"
:quantity 1000}]}
{:transaction-date (t/local-date 2016 3 9)
:entity-id "Personal"
:description "PI:NAME:<NAME>END_PI"
:items [{:action :debit
:account-id "PI:NAME:<NAME>END_PI"
:quantity 103}
{:action :credit
:account-id "Checking"
:quantity 103}]}
{:transaction-date (t/local-date 2016 3 16)
:entity-id "Personal"
:description "PI:NAME:<NAME>END_PI"
:items [{:action :debit
:account-id "PI:NAME:<NAME>END_PI"
:quantity 12}
{:action :credit
:account-id "Checking"
:quantity 12}]}
{:transaction-date (t/local-date 2016 3 23)
:entity-id "Personal"
:description "PI:NAME:<NAME>END_PI"
:items [{:action :debit
:account-id "PI:NAME:<NAME>END_PI"
:quantity 101}
{:action :credit
:account-id "Checking"
:quantity 101}]}]}))
(deftest update-a-transaction-change-action
(let [context (realize change-action-context)
[checking _ groceries] (:accounts context)
result (-> (find-transaction context (t/local-date 2016 3 16) "Kroger")
(update-items {(:id groceries) {:action :credit}
(:id checking) {:action :debit}})
transactions/update)]
(is (valid? result))
(is (seq-of-maps-like? [{:index 2
:quantity 101M
:balance 192M}
{:index 1
:quantity 12M
:balance 91M}
{:index 0
:quantity 103M
:balance 103M}]
(items-by-account (:id groceries)))
"Expected the groceries items to be updated")
(assert-account-quantities groceries 192M checking 808M)))
(def add-remove-item-context
(-> base-context
(update-in [:accounts] #(conj % {:name "PI:NAME:<NAME>END_PI"
:type :expense
:commodity-id "USD"}))
(merge {:transactions [{:transaction-date (t/local-date 2016 3 2)
:entity-id "Personal"
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000}
{:action :credit
:account-id "Salary"
:quantity 1000}]}
{:transaction-date (t/local-date 2016 3 9)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "PI:NAME:<NAME>END_PI"
:quantity 103}
{:action :credit
:account-id "Checking"
:quantity 103}]}
{:transaction-date (t/local-date 2016 3 16)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "PI:NAME:<NAME>END_PI"
:quantity 90}
{:action :debit
:account-id "Pets"
:quantity 12}
{:action :credit
:account-id "Checking"
:quantity 102}]}
{:transaction-date (t/local-date 2016 3 23)
:entity-id "Personal"
:description "Kroger"
:items [{:action :debit
:account-id "PI:NAME:<NAME>END_PI"
:quantity 101}
{:action :credit
:account-id "Checking"
:quantity 101}]}]})))
(deftest update-a-transaction-remove-item
(let [context (realize add-remove-item-context)
[checking
pets
groceries] (find-accounts context "Checking" "Pets" "Groceries")
result (-> (find-transaction context (t/local-date 2016 3 16) "Kroger")
(update-items {(:id groceries) {:quantity 102M
:value 102M}})
(update-in [:items] #(remove (fn [item]
(= (:account-id item)
(:id pets)))
%))
transactions/update)
expected-items [{:index 2
:quantity 101M
:balance 306M}
{:index 1
:quantity 102M
:balance 205M}
{:index 0
:quantity 103M
:balance 103M}]
actual-items (map #(select-keys % [:index :quantity :balance])
(items-by-account (:id groceries)))]
(is (valid? result) (str "Expected the transaction to be valid: " (prn-str (dissoc result :v/explanation))))
(assert-account-quantities pets 0M groceries 306M checking 694M)
(is (= expected-items actual-items)
"The account for the changed item should have the correct items")))
(deftest update-a-transaction-add-item
(let [context (realize add-remove-item-context)
[pets
groceries
checking] (find-accounts context "Pets" "Groceries" "Checking")
t2 (find-transaction context (t/local-date 2016 3 9) "Kroger")
to-update (-> t2
(update-items {(:id groceries) {:quantity 90M
:value 90M}})
(update-in [:items] #(conj % {:action :debit
:account-id (:id pets)
:quantity 13M
:value 13M})))
_ (transactions/update to-update)
expected-items [{:index 1
:quantity 12M
:balance 25M}
{:index 0
:quantity 13M
:balance 13M}]
actual-items (map #(select-keys % [:index :quantity :balance])
(items-by-account (:id pets)))]
(testing "item values are correct"
(is (= expected-items actual-items)
"The Pets account should have the correct items"))
(assert-account-quantities pets 25M groceries 281M checking 694M)))
(def balance-delta-context
(merge
base-context
{:transactions [{:transaction-date (t/local-date 2016 1 1)
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1000M}
{:action :credit
:account-id "Salary"
:quantity 1000M}]}
{:transaction-date (t/local-date 2016 1 15)
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1001M}
{:action :credit
:account-id "Salary"
:quantity 1001M}]}
{:transaction-date (t/local-date 2016 2 1)
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1100M}
{:action :credit
:account-id "Salary"
:quantity 1100M}]}
{:transaction-date (t/local-date 2016 2 15)
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1102M}
{:action :credit
:account-id "Salary"
:quantity 1102M}]}
{:transaction-date (t/local-date 2016 3 1)
:description "Paycheck"
:items [{:action :debit
:account-id "Checking"
:quantity 1200M}
{:action :credit
:account-id "Salary"
:quantity 1200M}]}]}))
(deftest get-a-balance-delta
(let [context (realize balance-delta-context)
[_ salary] (:accounts context)
january (transactions/balance-delta salary
(t/local-date 2016 1 1)
(t/local-date 2016 1 31))
february (transactions/balance-delta salary
(t/local-date 2016 2 1)
(t/local-date 2016 2 29))]
(is (= 2001M january) "The January value is the sum of polarized quantitys for the period")
(is (= 2202M february) "The February value is the sum of the polarized quantitys for the period")))
(deftest get-a-balance-as-of
(let [context (realize balance-delta-context)
[checking] (:accounts context)
january (transactions/balance-as-of checking
(t/local-date 2016 1 31))
february (transactions/balance-as-of checking
(t/local-date 2016 2 29))]
(is (= 2001M january) "The January value is the balance for the last item in the period")
(is (= 4203M february) "The February value is the balance for the last item in the period")))
(deftest create-multiple-transactions-then-recalculate-balances
(let [context (realize base-context)
entity (-> context :entities first)
[checking
salary
groceries] (:accounts context)]
(transactions/with-delayed-balancing (:id entity)
(transactions/create {:entity-id (:id entity)
:transaction-date (t/local-date 2017 1 1)
:description "Paycheck"
:items [{:action :debit
:account-id (:id checking)
:quantity 1000M}
{:action :credit
:account-id (:id salary)
:quantity 1000M}]})
(transactions/create {:entity-id (:id entity)
:transaction-date (t/local-date 2017 1 15)
:description "Market Street"
:items [{:action :debit
:account-id (:id groceries)
:quantity 100M}
{:action :credit
:account-id (:id checking)
:quantity 100M}]})
(transactions/create {:entity-id (:id entity)
:transaction-date (t/local-date 2017 2 1)
:description "Paycheck"
:items [{:action :debit
:account-id (:id checking)
:quantity 1000M}
{:action :credit
:account-id (:id salary)
:quantity 1000M}]})
(is (= 0M (:quantity (accounts/reload checking)))
"The account balance is not recalculated before the form exits"))
(is (= 1900M (:quantity (accounts/reload checking)))
"The account balance is recalculated after the form exits")))
(deftest use-simplified-items
(let [context (realize base-context)
entity (find-entity context "Personal")
[checking salary] (find-accounts context "Checking" "Salary")
trx (transactions/create {:entity-id (:id entity)
:transaction-date (t/local-date 2017 3 2)
:description "Paycheck"
:quantity 1000M
:debit-account-id (:id checking)
:credit-account-id (:id salary)})
actual-items (map #(select-keys % [:account-id :quantity :action]) (:items trx))
expected-items [{:account-id (:id checking)
:action :debit
:quantity 1000M}
{:account-id (:id salary)
:action :credit
:quantity 1000M}]]
(is (valid? trx))
(is (= expected-items actual-items) "The items are created correctly")))
(deftest set-account-boundaries
(let [context (realize base-context)
entity (find-entity context "Personal")
[checking
salary
groceries] (find-accounts context "Checking" "Salary" "Groceries")
created (->> [{:transaction-date (t/local-date 2017 2 27)
:description "Paycheck"
:quantity 1000M
:debit-account-id (:id checking)
:credit-account-id (:id salary)}
{:transaction-date (t/local-date 2017 3 2)
:description "Kroger"
:quantity 100M
:debit-account-id (:id groceries)
:credit-account-id (:id checking)}]
(map #(assoc % :entity-id (:id entity)))
(mapv transactions/create))
[checking
salary
groceries] (map accounts/reload [checking salary groceries])]
(is (valid? created))
(is (= (t/local-date 2017 2 27) (:earliest-transaction-date checking))
"The checking account's earliest is the paycheck")
(is (= (t/local-date 2017 3 2) (:latest-transaction-date checking))
"The checking account's latest is the grocery purchase")
(is (= (t/local-date 2017 2 27) (:earliest-transaction-date salary))
"The salary account's earliest is the paycheck")
(is (= (t/local-date 2017 2 27) (:latest-transaction-date salary))
"The salary account's latest is the paycheck")
(is (= (t/local-date 2017 3 2) (:earliest-transaction-date groceries))
"The groceries account's earliest is the grocery purchase")
(is (= (t/local-date 2017 3 2) (:latest-transaction-date groceries))
"The groceries account's latest is the grocery purchase")))
(def ^:private existing-reconciliation-context
(-> base-context
(update-in [:accounts] conj {:name "Rent"
:type :expense
:entity-id "Personal"})
(assoc :transactions [{:transaction-date (t/local-date 2017 1 1)
:description "Paycheck"
:debit-account-id "Checking"
:credit-account-id "Salary"
:quantity 1000M}
{:transaction-date (t/local-date 2017 1 2)
:description "Landlord"
:debit-account-id "Rent"
:credit-account-id "Checking"
:quantity 500M}
{:transaction-date (t/local-date 2017 1 3)
:description "Kroger"
:debit-account-id "PI:NAME:<NAME>END_PI"
:credit-account-id "Checking"
:quantity 45M}
{:transaction-date (t/local-date 2017 1 10)
:description "Safeway"
:debit-account-id "GPI:NAME:<NAME>END_PI"
:credit-account-id "Checking"
:quantity 53M}]
:reconciliations
[{:account-id "Checking"
:end-of-period (t/local-date 2017 1 1)
:balance 1000M
:status :completed
:item-refs [{:transaction-date (t/local-date 2017 1 1)
:quantity 1000M}]}])))
(deftest the-quantity-and-action-of-a-reconciled-item-cannot-be-changed
(let [context (realize existing-reconciliation-context)
transaction (find-transaction context (t/local-date 2017 1 1) "Paycheck")
result1 (transactions/update (update-in transaction [:items]
#(map (fn [item]
(assoc item :quantity 1M))
%)))
result2 (transactions/update (update-in transaction [:items]
#(map (fn [item]
(update-in item [:action] (fn [a] (if (= :credit a)
:debit
:credit))))
%)))]
(is (invalid? result1 [:items] "A reconciled item cannot be updated"))
(is (invalid? result2 [:items] "A reconciled item cannot be updated"))))
(deftest a-reconciled-transaction-item-cannot-be-deleted
(let [context (realize existing-reconciliation-context)
[item-id date] (-> context :reconciliations first :item-refs first)
transaction (transactions/find-by-item-id item-id date)]
(is (thrown-with-msg? clojure.lang.ExceptionInfo #"A transaction with reconciled items cannot be deleted."
(transactions/delete transaction))
"An exception is raised")
(is (do
(try
(transactions/delete transaction)
(catch clojure.lang.ExceptionInfo _ nil))
(transactions/find-by-item-id item-id date))
"The transaction can be retrieved after the delete has been denied")))
|
[
{
"context": ";; Copyright 2014-2015 Andrey Antukh <niwi@niwi.nz>\n;;\n;; Licensed under the Apache Li",
"end": 36,
"score": 0.9998844265937805,
"start": 23,
"tag": "NAME",
"value": "Andrey Antukh"
},
{
"context": ";; Copyright 2014-2015 Andrey Antukh <niwi@niwi.nz>\n;;\n;; Licensed under the Apache License, Version",
"end": 50,
"score": 0.9999309778213501,
"start": 38,
"tag": "EMAIL",
"value": "niwi@niwi.nz"
}
] | test/buddy/core/dsa_tests.clj | shilder/buddy-core | 121 | ;; Copyright 2014-2015 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.core.dsa-tests
(:require [clojure.test :refer :all]
[buddy.core.codecs :as codecs :refer :all]
[buddy.core.bytes :as bytes]
[buddy.core.keys :refer :all]
[buddy.core.dsa :as dsa]
[clojure.java.io :as io]))
(deftest low-level-sign
(let [rsa-privkey (private-key "test/_files/privkey.3des.rsa.pem" "secret")
rsa-pubkey (public-key "test/_files/pubkey.3des.rsa.pem")
ec-privkey (private-key "test/_files/privkey.ecdsa.pem")
ec-pubkey (public-key "test/_files/pubkey.ecdsa.pem")]
(testing "Multiple sign using rsassa-pkcs"
(let [opts {:key rsa-privkey :alg :rsassa-pkcs15+sha256}]
(is (bytes/equals? (dsa/sign "foobar" opts)
(dsa/sign "foobar" opts)))))
(testing "Sign/Verify using rsassa-pkcs"
(let [sign-opts {:key rsa-privkey :alg :rsassa-pkcs15+sha256}
verify-opts {:key rsa-pubkey :alg :rsassa-pkcs15+sha256}
sig (dsa/sign "foobar" sign-opts)]
(is (dsa/verify "foobar" sig verify-opts))))
(testing "Multiple sign using rsassa-pss"
(let [opts {:key rsa-privkey :alg :rsassa-pss+sha256}]
(is (not (bytes/equals? (dsa/sign "foobar" opts)
(dsa/sign "foobar" opts))))))
(testing "Sign/Verify using rsassa-pss"
(let [sign-opts {:key rsa-privkey :alg :rsassa-pss+sha256}
verify-opts {:key rsa-pubkey :alg :rsassa-pss+sha256}
sig (dsa/sign "foobar" sign-opts)]
(is (dsa/verify "foobar" sig verify-opts))))
(testing "Multiple sign using ecdsa"
(let [opts {:key ec-privkey :alg :ecdsa+sha256}]
(is (not (bytes/equals? (dsa/sign "foobar" opts)
(dsa/sign "foobar" opts))))))
(testing "Sign/Verify using ecdsa"
(let [sign-opts {:key ec-privkey :alg :ecdsa+sha256}
verify-opts {:key ec-pubkey :alg :ecdsa+sha256}
sig (dsa/sign "foobar" sign-opts)]
(is (dsa/verify "foobar" sig verify-opts))))
(testing "Sign/Verify input stream"
(let [sign-opts {:key ec-privkey :alg :ecdsa+sha384}
verify-opts {:key ec-pubkey :alg :ecdsa+sha384}
path "test/_files/pubkey.ecdsa.pem"
sig (dsa/sign (io/input-stream path) sign-opts)]
(is (dsa/verify (io/input-stream path) sig verify-opts))))
(testing "Sign/Verify file"
(let [sign-opts {:key ec-privkey :alg :ecdsa+sha512}
verify-opts {:key ec-pubkey :alg :ecdsa+sha512}
path "test/_files/pubkey.ecdsa.pem"
sig (dsa/sign (java.io.File. path) sign-opts)]
(is (dsa/verify (java.io.File. path) sig verify-opts))))
(testing "Sign/Verify URL"
(let [sign-opts {:key ec-privkey :alg :ecdsa+sha512}
verify-opts {:key ec-pubkey :alg :ecdsa+sha512}
path "test/_files/pubkey.ecdsa.pem"
sig (dsa/sign (.toURL (java.io.File. path)) sign-opts)]
(is (dsa/verify (.toURL (java.io.File. path)) sig verify-opts))))
(testing "Sign/Verify URI"
(let [sign-opts {:key ec-privkey :alg :ecdsa+sha512}
verify-opts {:key ec-pubkey :alg :ecdsa+sha512}
path "test/_files/pubkey.ecdsa.pem"
sig (dsa/sign (.toURI (java.io.File. path)) sign-opts)]
(is (dsa/verify (.toURI (java.io.File. path)) sig verify-opts))))
))
| 62606 | ;; Copyright 2014-2015 <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.core.dsa-tests
(:require [clojure.test :refer :all]
[buddy.core.codecs :as codecs :refer :all]
[buddy.core.bytes :as bytes]
[buddy.core.keys :refer :all]
[buddy.core.dsa :as dsa]
[clojure.java.io :as io]))
(deftest low-level-sign
(let [rsa-privkey (private-key "test/_files/privkey.3des.rsa.pem" "secret")
rsa-pubkey (public-key "test/_files/pubkey.3des.rsa.pem")
ec-privkey (private-key "test/_files/privkey.ecdsa.pem")
ec-pubkey (public-key "test/_files/pubkey.ecdsa.pem")]
(testing "Multiple sign using rsassa-pkcs"
(let [opts {:key rsa-privkey :alg :rsassa-pkcs15+sha256}]
(is (bytes/equals? (dsa/sign "foobar" opts)
(dsa/sign "foobar" opts)))))
(testing "Sign/Verify using rsassa-pkcs"
(let [sign-opts {:key rsa-privkey :alg :rsassa-pkcs15+sha256}
verify-opts {:key rsa-pubkey :alg :rsassa-pkcs15+sha256}
sig (dsa/sign "foobar" sign-opts)]
(is (dsa/verify "foobar" sig verify-opts))))
(testing "Multiple sign using rsassa-pss"
(let [opts {:key rsa-privkey :alg :rsassa-pss+sha256}]
(is (not (bytes/equals? (dsa/sign "foobar" opts)
(dsa/sign "foobar" opts))))))
(testing "Sign/Verify using rsassa-pss"
(let [sign-opts {:key rsa-privkey :alg :rsassa-pss+sha256}
verify-opts {:key rsa-pubkey :alg :rsassa-pss+sha256}
sig (dsa/sign "foobar" sign-opts)]
(is (dsa/verify "foobar" sig verify-opts))))
(testing "Multiple sign using ecdsa"
(let [opts {:key ec-privkey :alg :ecdsa+sha256}]
(is (not (bytes/equals? (dsa/sign "foobar" opts)
(dsa/sign "foobar" opts))))))
(testing "Sign/Verify using ecdsa"
(let [sign-opts {:key ec-privkey :alg :ecdsa+sha256}
verify-opts {:key ec-pubkey :alg :ecdsa+sha256}
sig (dsa/sign "foobar" sign-opts)]
(is (dsa/verify "foobar" sig verify-opts))))
(testing "Sign/Verify input stream"
(let [sign-opts {:key ec-privkey :alg :ecdsa+sha384}
verify-opts {:key ec-pubkey :alg :ecdsa+sha384}
path "test/_files/pubkey.ecdsa.pem"
sig (dsa/sign (io/input-stream path) sign-opts)]
(is (dsa/verify (io/input-stream path) sig verify-opts))))
(testing "Sign/Verify file"
(let [sign-opts {:key ec-privkey :alg :ecdsa+sha512}
verify-opts {:key ec-pubkey :alg :ecdsa+sha512}
path "test/_files/pubkey.ecdsa.pem"
sig (dsa/sign (java.io.File. path) sign-opts)]
(is (dsa/verify (java.io.File. path) sig verify-opts))))
(testing "Sign/Verify URL"
(let [sign-opts {:key ec-privkey :alg :ecdsa+sha512}
verify-opts {:key ec-pubkey :alg :ecdsa+sha512}
path "test/_files/pubkey.ecdsa.pem"
sig (dsa/sign (.toURL (java.io.File. path)) sign-opts)]
(is (dsa/verify (.toURL (java.io.File. path)) sig verify-opts))))
(testing "Sign/Verify URI"
(let [sign-opts {:key ec-privkey :alg :ecdsa+sha512}
verify-opts {:key ec-pubkey :alg :ecdsa+sha512}
path "test/_files/pubkey.ecdsa.pem"
sig (dsa/sign (.toURI (java.io.File. path)) sign-opts)]
(is (dsa/verify (.toURI (java.io.File. path)) sig verify-opts))))
))
| true | ;; Copyright 2014-2015 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.core.dsa-tests
(:require [clojure.test :refer :all]
[buddy.core.codecs :as codecs :refer :all]
[buddy.core.bytes :as bytes]
[buddy.core.keys :refer :all]
[buddy.core.dsa :as dsa]
[clojure.java.io :as io]))
(deftest low-level-sign
(let [rsa-privkey (private-key "test/_files/privkey.3des.rsa.pem" "secret")
rsa-pubkey (public-key "test/_files/pubkey.3des.rsa.pem")
ec-privkey (private-key "test/_files/privkey.ecdsa.pem")
ec-pubkey (public-key "test/_files/pubkey.ecdsa.pem")]
(testing "Multiple sign using rsassa-pkcs"
(let [opts {:key rsa-privkey :alg :rsassa-pkcs15+sha256}]
(is (bytes/equals? (dsa/sign "foobar" opts)
(dsa/sign "foobar" opts)))))
(testing "Sign/Verify using rsassa-pkcs"
(let [sign-opts {:key rsa-privkey :alg :rsassa-pkcs15+sha256}
verify-opts {:key rsa-pubkey :alg :rsassa-pkcs15+sha256}
sig (dsa/sign "foobar" sign-opts)]
(is (dsa/verify "foobar" sig verify-opts))))
(testing "Multiple sign using rsassa-pss"
(let [opts {:key rsa-privkey :alg :rsassa-pss+sha256}]
(is (not (bytes/equals? (dsa/sign "foobar" opts)
(dsa/sign "foobar" opts))))))
(testing "Sign/Verify using rsassa-pss"
(let [sign-opts {:key rsa-privkey :alg :rsassa-pss+sha256}
verify-opts {:key rsa-pubkey :alg :rsassa-pss+sha256}
sig (dsa/sign "foobar" sign-opts)]
(is (dsa/verify "foobar" sig verify-opts))))
(testing "Multiple sign using ecdsa"
(let [opts {:key ec-privkey :alg :ecdsa+sha256}]
(is (not (bytes/equals? (dsa/sign "foobar" opts)
(dsa/sign "foobar" opts))))))
(testing "Sign/Verify using ecdsa"
(let [sign-opts {:key ec-privkey :alg :ecdsa+sha256}
verify-opts {:key ec-pubkey :alg :ecdsa+sha256}
sig (dsa/sign "foobar" sign-opts)]
(is (dsa/verify "foobar" sig verify-opts))))
(testing "Sign/Verify input stream"
(let [sign-opts {:key ec-privkey :alg :ecdsa+sha384}
verify-opts {:key ec-pubkey :alg :ecdsa+sha384}
path "test/_files/pubkey.ecdsa.pem"
sig (dsa/sign (io/input-stream path) sign-opts)]
(is (dsa/verify (io/input-stream path) sig verify-opts))))
(testing "Sign/Verify file"
(let [sign-opts {:key ec-privkey :alg :ecdsa+sha512}
verify-opts {:key ec-pubkey :alg :ecdsa+sha512}
path "test/_files/pubkey.ecdsa.pem"
sig (dsa/sign (java.io.File. path) sign-opts)]
(is (dsa/verify (java.io.File. path) sig verify-opts))))
(testing "Sign/Verify URL"
(let [sign-opts {:key ec-privkey :alg :ecdsa+sha512}
verify-opts {:key ec-pubkey :alg :ecdsa+sha512}
path "test/_files/pubkey.ecdsa.pem"
sig (dsa/sign (.toURL (java.io.File. path)) sign-opts)]
(is (dsa/verify (.toURL (java.io.File. path)) sig verify-opts))))
(testing "Sign/Verify URI"
(let [sign-opts {:key ec-privkey :alg :ecdsa+sha512}
verify-opts {:key ec-pubkey :alg :ecdsa+sha512}
path "test/_files/pubkey.ecdsa.pem"
sig (dsa/sign (.toURI (java.io.File. path)) sign-opts)]
(is (dsa/verify (.toURI (java.io.File. path)) sig verify-opts))))
))
|
[
{
"context": " keyword indexed integer counters\"\n :author \"Jeff Rose and Sam Aaron\"}\n overtone.libs.counters)\n\n(defon",
"end": 89,
"score": 0.9998765587806702,
"start": 80,
"tag": "NAME",
"value": "Jeff Rose"
},
{
"context": "xed integer counters\"\n :author \"Jeff Rose and Sam Aaron\"}\n overtone.libs.counters)\n\n(defonce counters* (",
"end": 103,
"score": 0.9998769760131836,
"start": 94,
"tag": "NAME",
"value": "Sam Aaron"
}
] | src/overtone/libs/counters.clj | ABaldwinHunter/overtone | 1 | (ns
^{:doc "Basic stateful keyword indexed integer counters"
:author "Jeff Rose and Sam Aaron"}
overtone.libs.counters)
(defonce counters* (atom {}))
(defn- inc-or-set-cnt
"Either increment the count associated with the specified key in map counters
or create a new key with val 0"
[counters key]
(let [count (or (get counters key) -1)]
(assoc counters key (inc count))))
(defn next-id
"Increments and returns the next integer for the specified key. ids start at 0
and each key's id is independent of the other ids."
[key]
(let [updated (swap! counters* inc-or-set-cnt key)]
(get updated key)))
(defn reset-counter!
"Reset specified counter"
[key]
(swap! counters* dissoc key))
(defn reset-all-counters!
"Reset all counters"
[]
(reset! counters* {}))
| 95634 | (ns
^{:doc "Basic stateful keyword indexed integer counters"
:author "<NAME> and <NAME>"}
overtone.libs.counters)
(defonce counters* (atom {}))
(defn- inc-or-set-cnt
"Either increment the count associated with the specified key in map counters
or create a new key with val 0"
[counters key]
(let [count (or (get counters key) -1)]
(assoc counters key (inc count))))
(defn next-id
"Increments and returns the next integer for the specified key. ids start at 0
and each key's id is independent of the other ids."
[key]
(let [updated (swap! counters* inc-or-set-cnt key)]
(get updated key)))
(defn reset-counter!
"Reset specified counter"
[key]
(swap! counters* dissoc key))
(defn reset-all-counters!
"Reset all counters"
[]
(reset! counters* {}))
| true | (ns
^{:doc "Basic stateful keyword indexed integer counters"
:author "PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI"}
overtone.libs.counters)
(defonce counters* (atom {}))
(defn- inc-or-set-cnt
"Either increment the count associated with the specified key in map counters
or create a new key with val 0"
[counters key]
(let [count (or (get counters key) -1)]
(assoc counters key (inc count))))
(defn next-id
"Increments and returns the next integer for the specified key. ids start at 0
and each key's id is independent of the other ids."
[key]
(let [updated (swap! counters* inc-or-set-cnt key)]
(get updated key)))
(defn reset-counter!
"Reset specified counter"
[key]
(swap! counters* dissoc key))
(defn reset-all-counters!
"Reset all counters"
[]
(reset! counters* {}))
|
[
{
"context": "et [record {:topic \"test\"\n :key \"anykey\"\n :value (json/write-str (:json-pa",
"end": 799,
"score": 0.8836619853973389,
"start": 793,
"tag": "KEY",
"value": "anykey"
}
] | server/src/spacon/components/http/ping.clj | martinwilkerson-scisys/spatialconnect-server | 1 | (ns spacon.components.http.ping
(:require [spacon.components.http.response :as response]
[spacon.components.mqtt.core :as mqttapi]
[spacon.components.http.intercept :as intercept]
[clojure.core.async :as async]
[clojure.data.json :as json]
[spacon.components.kafka.core :as kafka]))
(defn http-mq-post [mqtt context]
(let [m (:json-params context)]
(mqttapi/publish-map mqtt (:topic m) (:payload m)))
(response/ok "success"))
(defn- pong
"Responds with pong as a way to ensure http service is reachable"
[_]
(response/ok "pong"))
(defn pong-kafka
"Subscribes to test topic and awaits pong message to ensure kafka cluster is reachable"
[kafka-comp request]
(let [record {:topic "test"
:key "anykey"
:value (json/write-str (:json-params request))}
promise-chan (kafka/send! kafka-comp record)
[val _] (async/alts!! [promise-chan (async/timeout 2000)])]
(if (nil? val)
(response/error "Error writing to Kafka or timeout")
(response/ok val))))
(defn routes
[kafka-comp]
#{["/api/ping" :get (conj intercept/common-interceptors `pong)]
["/api/ping/kafka" :post (conj intercept/common-interceptors (partial pong-kafka kafka-comp)) :route-name :pong-kafka]})
| 75626 | (ns spacon.components.http.ping
(:require [spacon.components.http.response :as response]
[spacon.components.mqtt.core :as mqttapi]
[spacon.components.http.intercept :as intercept]
[clojure.core.async :as async]
[clojure.data.json :as json]
[spacon.components.kafka.core :as kafka]))
(defn http-mq-post [mqtt context]
(let [m (:json-params context)]
(mqttapi/publish-map mqtt (:topic m) (:payload m)))
(response/ok "success"))
(defn- pong
"Responds with pong as a way to ensure http service is reachable"
[_]
(response/ok "pong"))
(defn pong-kafka
"Subscribes to test topic and awaits pong message to ensure kafka cluster is reachable"
[kafka-comp request]
(let [record {:topic "test"
:key "<KEY>"
:value (json/write-str (:json-params request))}
promise-chan (kafka/send! kafka-comp record)
[val _] (async/alts!! [promise-chan (async/timeout 2000)])]
(if (nil? val)
(response/error "Error writing to Kafka or timeout")
(response/ok val))))
(defn routes
[kafka-comp]
#{["/api/ping" :get (conj intercept/common-interceptors `pong)]
["/api/ping/kafka" :post (conj intercept/common-interceptors (partial pong-kafka kafka-comp)) :route-name :pong-kafka]})
| true | (ns spacon.components.http.ping
(:require [spacon.components.http.response :as response]
[spacon.components.mqtt.core :as mqttapi]
[spacon.components.http.intercept :as intercept]
[clojure.core.async :as async]
[clojure.data.json :as json]
[spacon.components.kafka.core :as kafka]))
(defn http-mq-post [mqtt context]
(let [m (:json-params context)]
(mqttapi/publish-map mqtt (:topic m) (:payload m)))
(response/ok "success"))
(defn- pong
"Responds with pong as a way to ensure http service is reachable"
[_]
(response/ok "pong"))
(defn pong-kafka
"Subscribes to test topic and awaits pong message to ensure kafka cluster is reachable"
[kafka-comp request]
(let [record {:topic "test"
:key "PI:KEY:<KEY>END_PI"
:value (json/write-str (:json-params request))}
promise-chan (kafka/send! kafka-comp record)
[val _] (async/alts!! [promise-chan (async/timeout 2000)])]
(if (nil? val)
(response/error "Error writing to Kafka or timeout")
(response/ok val))))
(defn routes
[kafka-comp]
#{["/api/ping" :get (conj intercept/common-interceptors `pong)]
["/api/ping/kafka" :post (conj intercept/common-interceptors (partial pong-kafka kafka-comp)) :route-name :pong-kafka]})
|
[
{
"context": "a :b))\n(peek stack)\n(pop stack)\n\n\n(def players #{\"Alice\" \"Bob\" \"Kelly\"})\n\n(conj players \"Fred\")\n\n(disj pl",
"end": 508,
"score": 0.9998378157615662,
"start": 503,
"tag": "NAME",
"value": "Alice"
},
{
"context": "peek stack)\n(pop stack)\n\n\n(def players #{\"Alice\" \"Bob\" \"Kelly\"})\n\n(conj players \"Fred\")\n\n(disj players ",
"end": 514,
"score": 0.9998264908790588,
"start": 511,
"tag": "NAME",
"value": "Bob"
},
{
"context": "tack)\n(pop stack)\n\n\n(def players #{\"Alice\" \"Bob\" \"Kelly\"})\n\n(conj players \"Fred\")\n\n(disj players \"Bob\" \"S",
"end": 522,
"score": 0.9997465014457703,
"start": 517,
"tag": "NAME",
"value": "Kelly"
},
{
"context": "players #{\"Alice\" \"Bob\" \"Kelly\"})\n\n(conj players \"Fred\")\n\n(disj players \"Bob\" \"Sal\")\n\n(contains? players",
"end": 546,
"score": 0.9997713565826416,
"start": 542,
"tag": "NAME",
"value": "Fred"
},
{
"context": " \"Kelly\"})\n\n(conj players \"Fred\")\n\n(disj players \"Bob\" \"Sal\")\n\n(contains? players \"Kelly\")\n(contains? (",
"end": 568,
"score": 0.9998308420181274,
"start": 565,
"tag": "NAME",
"value": "Bob"
},
{
"context": "y\"})\n\n(conj players \"Fred\")\n\n(disj players \"Bob\" \"Sal\")\n\n(contains? players \"Kelly\")\n(contains? (disj p",
"end": 574,
"score": 0.99978107213974,
"start": 571,
"tag": "NAME",
"value": "Sal"
},
{
"context": "\n\n(disj players \"Bob\" \"Sal\")\n\n(contains? players \"Kelly\")\n(contains? (disj players \"Kelly\") \"Kelly\")\n\n(co",
"end": 603,
"score": 0.99958336353302,
"start": 598,
"tag": "NAME",
"value": "Kelly"
},
{
"context": "tains? players \"Kelly\")\n(contains? (disj players \"Kelly\") \"Kelly\")\n\n(conj (sorted-set) \"Bravo\" \"Charlie\" ",
"end": 637,
"score": 0.9996811747550964,
"start": 632,
"tag": "NAME",
"value": "Kelly"
},
{
"context": "ayers \"Kelly\")\n(contains? (disj players \"Kelly\") \"Kelly\")\n\n(conj (sorted-set) \"Bravo\" \"Charlie\" \"Sigma\" \"",
"end": 646,
"score": 0.9995747208595276,
"start": 641,
"tag": "NAME",
"value": "Kelly"
},
{
"context": "harlie\" \"Sigma\" \"Alpha\")\n(sorted-set \"Bravo\" \"Charlie\" \"Sigma\" \"Alpha\")\n\n\n(def players #{\"Alice\" \"Bob\" ",
"end": 732,
"score": 0.8535857796669006,
"start": 729,
"tag": "NAME",
"value": "lie"
},
{
"context": "avo\" \"Charlie\" \"Sigma\" \"Alpha\")\n\n\n(def players #{\"Alice\" \"Bob\" \"Kelly\"})\n(def new-players [\"Tim\" \"Sue\" \"G",
"end": 774,
"score": 0.9998396039009094,
"start": 769,
"tag": "NAME",
"value": "Alice"
},
{
"context": "arlie\" \"Sigma\" \"Alpha\")\n\n\n(def players #{\"Alice\" \"Bob\" \"Kelly\"})\n(def new-players [\"Tim\" \"Sue\" \"Greg\"])",
"end": 780,
"score": 0.9998334050178528,
"start": 777,
"tag": "NAME",
"value": "Bob"
},
{
"context": " \"Sigma\" \"Alpha\")\n\n\n(def players #{\"Alice\" \"Bob\" \"Kelly\"})\n(def new-players [\"Tim\" \"Sue\" \"Greg\"])\n(into p",
"end": 788,
"score": 0.9996854066848755,
"start": 783,
"tag": "NAME",
"value": "Kelly"
},
{
"context": "yers #{\"Alice\" \"Bob\" \"Kelly\"})\n(def new-players [\"Tim\" \"Sue\" \"Greg\"])\n(into players new-players)\n\n\n(def",
"end": 814,
"score": 0.9998223185539246,
"start": 811,
"tag": "NAME",
"value": "Tim"
},
{
"context": "{\"Alice\" \"Bob\" \"Kelly\"})\n(def new-players [\"Tim\" \"Sue\" \"Greg\"])\n(into players new-players)\n\n\n(def score",
"end": 820,
"score": 0.999805748462677,
"start": 817,
"tag": "NAME",
"value": "Sue"
},
{
"context": "e\" \"Bob\" \"Kelly\"})\n(def new-players [\"Tim\" \"Sue\" \"Greg\"])\n(into players new-players)\n\n\n(def scores {\"Fre",
"end": 827,
"score": 0.9998142123222351,
"start": 823,
"tag": "NAME",
"value": "Greg"
},
{
"context": "reg\"])\n(into players new-players)\n\n\n(def scores {\"Fred\" 1400\n \"Bob\" 1240\n \"Angel",
"end": 878,
"score": 0.9997653961181641,
"start": 874,
"tag": "NAME",
"value": "Fred"
},
{
"context": "players)\n\n\n(def scores {\"Fred\" 1400\n \"Bob\" 1240\n \"Angela\" 1024})\n\n(def scores {",
"end": 902,
"score": 0.9998186230659485,
"start": 899,
"tag": "NAME",
"value": "Bob"
},
{
"context": "\"Fred\" 1400\n \"Bob\" 1240\n \"Angela\" 1024})\n\n(def scores {\"Fred\" 1400, \"Bob\" 1240, \"A",
"end": 929,
"score": 0.9996950030326843,
"start": 923,
"tag": "NAME",
"value": "Angela"
},
{
"context": " 1240\n \"Angela\" 1024})\n\n(def scores {\"Fred\" 1400, \"Bob\" 1240, \"Angela\" 1024})\n\n(assoc scores",
"end": 957,
"score": 0.9997406005859375,
"start": 953,
"tag": "NAME",
"value": "Fred"
},
{
"context": " \"Angela\" 1024})\n\n(def scores {\"Fred\" 1400, \"Bob\" 1240, \"Angela\" 1024})\n\n(assoc scores \"Sally\" 0)\n",
"end": 969,
"score": 0.999804675579071,
"start": 966,
"tag": "NAME",
"value": "Bob"
},
{
"context": "a\" 1024})\n\n(def scores {\"Fred\" 1400, \"Bob\" 1240, \"Angela\" 1024})\n\n(assoc scores \"Sally\" 0)\n(assoc scores \"",
"end": 984,
"score": 0.9997283816337585,
"start": 978,
"tag": "NAME",
"value": "Angela"
},
{
"context": "1400, \"Bob\" 1240, \"Angela\" 1024})\n\n(assoc scores \"Sally\" 0)\n(assoc scores \"Bob\" 0)\n\n(dissoc scores \"Bob\")",
"end": 1014,
"score": 0.9996252059936523,
"start": 1009,
"tag": "NAME",
"value": "Sally"
},
{
"context": "\" 1024})\n\n(assoc scores \"Sally\" 0)\n(assoc scores \"Bob\" 0)\n\n(dissoc scores \"Bob\")\n\n(get scores \"Angela\")",
"end": 1037,
"score": 0.9997857213020325,
"start": 1034,
"tag": "NAME",
"value": "Bob"
},
{
"context": "Sally\" 0)\n(assoc scores \"Bob\" 0)\n\n(dissoc scores \"Bob\")\n\n(get scores \"Angela\")\n\n(def directions {:north",
"end": 1062,
"score": 0.999810516834259,
"start": 1059,
"tag": "NAME",
"value": "Bob"
},
{
"context": "res \"Bob\" 0)\n\n(dissoc scores \"Bob\")\n\n(get scores \"Angela\")\n\n(def directions {:north 0\n :ea",
"end": 1085,
"score": 0.9995160698890686,
"start": 1079,
"tag": "NAME",
"value": "Angela"
},
{
"context": "up-map :foo)\n(:foo bad-lookup-map)\n\n\n(get scores \"Sam\" 0)\n(directions :northwest -1)\n(:foo bad-lookup-m",
"end": 1323,
"score": 0.9996788501739502,
"start": 1320,
"tag": "NAME",
"value": "Sam"
},
{
"context": "t -1)\n(:foo bad-lookup-map 1)\n\n(contains? scores \"Fred\")\n(find scores \"Fred\")\n(find scores \"Sam\")\n\n(keys",
"end": 1403,
"score": 0.9995427131652832,
"start": 1399,
"tag": "NAME",
"value": "Fred"
},
{
"context": "p-map 1)\n\n(contains? scores \"Fred\")\n(find scores \"Fred\")\n(find scores \"Sam\")\n\n(keys scores)\n(vals scores",
"end": 1424,
"score": 0.9996036887168884,
"start": 1420,
"tag": "NAME",
"value": "Fred"
},
{
"context": "scores \"Fred\")\n(find scores \"Fred\")\n(find scores \"Sam\")\n\n(keys scores)\n(vals scores)\n\n\n(def players #{\"",
"end": 1444,
"score": 0.9993982315063477,
"start": 1441,
"tag": "NAME",
"value": "Sam"
},
{
"context": "\")\n\n(keys scores)\n(vals scores)\n\n\n(def players #{\"Alice\" \"Bob\" \"Kelly\"})\n\n(zipmap players (repeat 0))\n\n(d",
"end": 1499,
"score": 0.9998071193695068,
"start": 1494,
"tag": "NAME",
"value": "Alice"
},
{
"context": "s scores)\n(vals scores)\n\n\n(def players #{\"Alice\" \"Bob\" \"Kelly\"})\n\n(zipmap players (repeat 0))\n\n(doc rep",
"end": 1505,
"score": 0.9998395442962646,
"start": 1502,
"tag": "NAME",
"value": "Bob"
},
{
"context": "es)\n(vals scores)\n\n\n(def players #{\"Alice\" \"Bob\" \"Kelly\"})\n\n(zipmap players (repeat 0))\n\n(doc repeat)\n(do",
"end": 1513,
"score": 0.9998111724853516,
"start": 1508,
"tag": "NAME",
"value": "Kelly"
},
{
"context": " {}\n players)\n\n(def new-scores {\"Angela\" 300, \"Jeff\" 900})\n(merge scores new-scores)\n\n(do",
"end": 1734,
"score": 0.9995408654212952,
"start": 1728,
"tag": "NAME",
"value": "Angela"
},
{
"context": " players)\n\n(def new-scores {\"Angela\" 300, \"Jeff\" 900})\n(merge scores new-scores)\n\n(doc merge)\n\n(s",
"end": 1746,
"score": 0.9996957778930664,
"start": 1742,
"tag": "NAME",
"value": "Jeff"
},
{
"context": "-with + scores new-scores)\n\n\n(def sm (sorted-map \"Bravo\" 204\n \"Alpha\" 35\n ",
"end": 1871,
"score": 0.9418706893920898,
"start": 1866,
"tag": "NAME",
"value": "Bravo"
},
{
"context": " \"Sigma\" 99\n \"Charlie\" 100))\n\n(keys sm)\n(vals sm)\n\n\n(def person\n {:fir",
"end": 1967,
"score": 0.9970741271972656,
"start": 1960,
"tag": "NAME",
"value": "Charlie"
},
{
"context": "(keys sm)\n(vals sm)\n\n\n(def person\n {:first-name \"Kelly\"\n :last-name \"Keen\"\n :age 32\n :occupation \"",
"end": 2031,
"score": 0.999765157699585,
"start": 2026,
"tag": "NAME",
"value": "Kelly"
},
{
"context": "(def person\n {:first-name \"Kelly\"\n :last-name \"Keen\"\n :age 32\n :occupation \"Programmer\"})\n\n(get p",
"end": 2052,
"score": 0.9998198747634888,
"start": 2048,
"tag": "NAME",
"value": "Keen"
},
{
"context": "last-name age occupation])\n\n(def kelly (->Person \"Kelly\" \"Keen\" 32 \"Programmer\"))\n\n(def kelly (map->Perso",
"end": 2599,
"score": 0.9998020529747009,
"start": 2594,
"tag": "NAME",
"value": "Kelly"
},
{
"context": "e age occupation])\n\n(def kelly (->Person \"Kelly\" \"Keen\" 32 \"Programmer\"))\n\n(def kelly (map->Person {:fir",
"end": 2606,
"score": 0.9993033409118652,
"start": 2602,
"tag": "NAME",
"value": "Keen"
},
{
"context": "grammer\"))\n\n(def kelly (map->Person {:first-name \"Kelly\"\n :last-name \"Keen\"\n ",
"end": 2670,
"score": 0.9997855424880981,
"start": 2665,
"tag": "NAME",
"value": "Kelly"
},
{
"context": "name \"Kelly\"\n :last-name \"Keen\"\n :age 32\n ",
"end": 2713,
"score": 0.9996998906135559,
"start": 2709,
"tag": "NAME",
"value": "Keen"
},
{
"context": " \"Programmer\"}))\n\n(kelly :first-name)\n(:first-name kelly)\n\n\n(str \"2 is \" (if (even? 2) \"even\" \"odd\"))\n\n(if",
"end": 2840,
"score": 0.980746328830719,
"start": 2835,
"tag": "NAME",
"value": "kelly"
}
] | 2020/clj-guide/2.clj | axvr/codedump | 1 | ;;;; <https://clojure.org/guides/learn/sequential_colls>
;;;; Public domain. No rights reserved.
[1 2 3] ; Vector
(get ["abc" false 99] 0)
(get ["abc" false 99] 1)
(get ["abc" false 99] 14)
(get ["abc" nil 99] 1)
(count [1 2 3])
(count "foobar")
(vector 1 2 3)
(conj [1 2 3] 4 5 6)
(conj [1 2 3] [4 5 6])
(def v [1 2 3])
(conj v 4 5 6)
(def cards '(10 :ace :jack 9))
(first cards)
(second cards)
(rest cards)
(conj cards :queen)
(def stack '(:a :b))
(peek stack)
(pop stack)
(def players #{"Alice" "Bob" "Kelly"})
(conj players "Fred")
(disj players "Bob" "Sal")
(contains? players "Kelly")
(contains? (disj players "Kelly") "Kelly")
(conj (sorted-set) "Bravo" "Charlie" "Sigma" "Alpha")
(sorted-set "Bravo" "Charlie" "Sigma" "Alpha")
(def players #{"Alice" "Bob" "Kelly"})
(def new-players ["Tim" "Sue" "Greg"])
(into players new-players)
(def scores {"Fred" 1400
"Bob" 1240
"Angela" 1024})
(def scores {"Fred" 1400, "Bob" 1240, "Angela" 1024})
(assoc scores "Sally" 0)
(assoc scores "Bob" 0)
(dissoc scores "Bob")
(get scores "Angela")
(def directions {:north 0
:east 1
:south 2
:west 3})
(directions :north)
(:north directions)
(def bad-lookup-map nil)
(bad-lookup-map :foo)
(:foo bad-lookup-map)
(get scores "Sam" 0)
(directions :northwest -1)
(:foo bad-lookup-map 1)
(contains? scores "Fred")
(find scores "Fred")
(find scores "Sam")
(keys scores)
(vals scores)
(def players #{"Alice" "Bob" "Kelly"})
(zipmap players (repeat 0))
(doc repeat)
(doc zipmap)
(into {} (map (fn [player] [player 0]) players))
(reduce (fn [m player]
(assoc m player 0))
{}
players)
(def new-scores {"Angela" 300, "Jeff" 900})
(merge scores new-scores)
(doc merge)
(source merge)
(merge-with + scores new-scores)
(def sm (sorted-map "Bravo" 204
"Alpha" 35
"Sigma" 99
"Charlie" 100))
(keys sm)
(vals sm)
(def person
{:first-name "Kelly"
:last-name "Keen"
:age 32
:occupation "Programmer"})
(get person :occupation)
(person :occupation)
(:occupation person)
(:favourite-colour person "beige")
(assoc person :occupation "Baker")
(dissoc person :age)
(def company
{:name "WidgetCo"
:address {:street "123 Main St"
:city "Springfield"
:state "IL"}})
(get-in company [:address :city])
(doc assoc-in)
(doc update-in)
(assoc-in company [:address :street] "303 Broadway")
(defrecord Person [first-name last-name age occupation])
(def kelly (->Person "Kelly" "Keen" 32 "Programmer"))
(def kelly (map->Person {:first-name "Kelly"
:last-name "Keen"
:age 32
:occupation "Programmer"}))
(kelly :first-name)
(:first-name kelly)
(str "2 is " (if (even? 2) "even" "odd"))
(if (true? false) "impossible")
(if true :truthy :falsey)
(if (Object.) :truthy :falsey)
(if [] :truthy :falsey)
(if 0 :truthy :falsey)
(if false :truthy :falsey)
(if nil :truthy :falsey)
(if (even? 5)
(do (println "even")
true)
(do (println "odd")
false))
(when (neg? x)
(throw (RuntimeException. (str "x must be positive: " x))))
(let [x 5]
(cond
(< x 2) "x is less than 2"
(< x 10) "x is less than 10"))
(let [x 11]
(cond
(< x 2) "x is less than 2"
(< x 10) "x is less than 10"
:else "x is greater than or equal to 10"))
(defn foo [x]
(case x
5 "x is 5"
10 "x is 10"))
(foo 10)
(foo 11)
(defn foo [x]
(case x
5 "x is 5"
10 "x is 10"
"x isn't 5 or 10"))
(foo 10)
(foo 11)
(dotimes [i 3]
(println i))
(range 3)
(range 3 9)
(doseq [n (range 3)]
(println n))
(doseq [n (range 3 9)]
(println n))
(doseq [letter [:a :b]
number (range 3)]
(prn [letter number]))
(for [letter [:a :b]
number (range 3)]
[letter number])
(loop [i 0]
(if (< i 10)
(recur (inc i))
i))
(defn increase [i]
(if (< i 10)
(recur (inc i))
i))
(try
(/ 2 0)
(catch ArithmeticException e
"divide by zero")
(finally
(println "cleanup")))
(try
(throw (Exception. "something went wrong"))
(catch Exception e (.getMessage e)))
(try
(throw (ex-info "There was a problem" {:detail 42}))
(catch Exception e
(prn (:detail (ex-data e)))))
(let [f (clojure.java.io/writer "/tmp/new")]
(try
(.write f "some text")
(finally
(.close f))))
(with-open [f (clojure.java.io/writer "/tmp/new")]
(.write f "some text"))
| 118814 | ;;;; <https://clojure.org/guides/learn/sequential_colls>
;;;; Public domain. No rights reserved.
[1 2 3] ; Vector
(get ["abc" false 99] 0)
(get ["abc" false 99] 1)
(get ["abc" false 99] 14)
(get ["abc" nil 99] 1)
(count [1 2 3])
(count "foobar")
(vector 1 2 3)
(conj [1 2 3] 4 5 6)
(conj [1 2 3] [4 5 6])
(def v [1 2 3])
(conj v 4 5 6)
(def cards '(10 :ace :jack 9))
(first cards)
(second cards)
(rest cards)
(conj cards :queen)
(def stack '(:a :b))
(peek stack)
(pop stack)
(def players #{"<NAME>" "<NAME>" "<NAME>"})
(conj players "<NAME>")
(disj players "<NAME>" "<NAME>")
(contains? players "<NAME>")
(contains? (disj players "<NAME>") "<NAME>")
(conj (sorted-set) "Bravo" "Charlie" "Sigma" "Alpha")
(sorted-set "Bravo" "Char<NAME>" "Sigma" "Alpha")
(def players #{"<NAME>" "<NAME>" "<NAME>"})
(def new-players ["<NAME>" "<NAME>" "<NAME>"])
(into players new-players)
(def scores {"<NAME>" 1400
"<NAME>" 1240
"<NAME>" 1024})
(def scores {"<NAME>" 1400, "<NAME>" 1240, "<NAME>" 1024})
(assoc scores "<NAME>" 0)
(assoc scores "<NAME>" 0)
(dissoc scores "<NAME>")
(get scores "<NAME>")
(def directions {:north 0
:east 1
:south 2
:west 3})
(directions :north)
(:north directions)
(def bad-lookup-map nil)
(bad-lookup-map :foo)
(:foo bad-lookup-map)
(get scores "<NAME>" 0)
(directions :northwest -1)
(:foo bad-lookup-map 1)
(contains? scores "<NAME>")
(find scores "<NAME>")
(find scores "<NAME>")
(keys scores)
(vals scores)
(def players #{"<NAME>" "<NAME>" "<NAME>"})
(zipmap players (repeat 0))
(doc repeat)
(doc zipmap)
(into {} (map (fn [player] [player 0]) players))
(reduce (fn [m player]
(assoc m player 0))
{}
players)
(def new-scores {"<NAME>" 300, "<NAME>" 900})
(merge scores new-scores)
(doc merge)
(source merge)
(merge-with + scores new-scores)
(def sm (sorted-map "<NAME>" 204
"Alpha" 35
"Sigma" 99
"<NAME>" 100))
(keys sm)
(vals sm)
(def person
{:first-name "<NAME>"
:last-name "<NAME>"
:age 32
:occupation "Programmer"})
(get person :occupation)
(person :occupation)
(:occupation person)
(:favourite-colour person "beige")
(assoc person :occupation "Baker")
(dissoc person :age)
(def company
{:name "WidgetCo"
:address {:street "123 Main St"
:city "Springfield"
:state "IL"}})
(get-in company [:address :city])
(doc assoc-in)
(doc update-in)
(assoc-in company [:address :street] "303 Broadway")
(defrecord Person [first-name last-name age occupation])
(def kelly (->Person "<NAME>" "<NAME>" 32 "Programmer"))
(def kelly (map->Person {:first-name "<NAME>"
:last-name "<NAME>"
:age 32
:occupation "Programmer"}))
(kelly :first-name)
(:first-name <NAME>)
(str "2 is " (if (even? 2) "even" "odd"))
(if (true? false) "impossible")
(if true :truthy :falsey)
(if (Object.) :truthy :falsey)
(if [] :truthy :falsey)
(if 0 :truthy :falsey)
(if false :truthy :falsey)
(if nil :truthy :falsey)
(if (even? 5)
(do (println "even")
true)
(do (println "odd")
false))
(when (neg? x)
(throw (RuntimeException. (str "x must be positive: " x))))
(let [x 5]
(cond
(< x 2) "x is less than 2"
(< x 10) "x is less than 10"))
(let [x 11]
(cond
(< x 2) "x is less than 2"
(< x 10) "x is less than 10"
:else "x is greater than or equal to 10"))
(defn foo [x]
(case x
5 "x is 5"
10 "x is 10"))
(foo 10)
(foo 11)
(defn foo [x]
(case x
5 "x is 5"
10 "x is 10"
"x isn't 5 or 10"))
(foo 10)
(foo 11)
(dotimes [i 3]
(println i))
(range 3)
(range 3 9)
(doseq [n (range 3)]
(println n))
(doseq [n (range 3 9)]
(println n))
(doseq [letter [:a :b]
number (range 3)]
(prn [letter number]))
(for [letter [:a :b]
number (range 3)]
[letter number])
(loop [i 0]
(if (< i 10)
(recur (inc i))
i))
(defn increase [i]
(if (< i 10)
(recur (inc i))
i))
(try
(/ 2 0)
(catch ArithmeticException e
"divide by zero")
(finally
(println "cleanup")))
(try
(throw (Exception. "something went wrong"))
(catch Exception e (.getMessage e)))
(try
(throw (ex-info "There was a problem" {:detail 42}))
(catch Exception e
(prn (:detail (ex-data e)))))
(let [f (clojure.java.io/writer "/tmp/new")]
(try
(.write f "some text")
(finally
(.close f))))
(with-open [f (clojure.java.io/writer "/tmp/new")]
(.write f "some text"))
| true | ;;;; <https://clojure.org/guides/learn/sequential_colls>
;;;; Public domain. No rights reserved.
[1 2 3] ; Vector
(get ["abc" false 99] 0)
(get ["abc" false 99] 1)
(get ["abc" false 99] 14)
(get ["abc" nil 99] 1)
(count [1 2 3])
(count "foobar")
(vector 1 2 3)
(conj [1 2 3] 4 5 6)
(conj [1 2 3] [4 5 6])
(def v [1 2 3])
(conj v 4 5 6)
(def cards '(10 :ace :jack 9))
(first cards)
(second cards)
(rest cards)
(conj cards :queen)
(def stack '(:a :b))
(peek stack)
(pop stack)
(def players #{"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"})
(conj players "PI:NAME:<NAME>END_PI")
(disj players "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI")
(contains? players "PI:NAME:<NAME>END_PI")
(contains? (disj players "PI:NAME:<NAME>END_PI") "PI:NAME:<NAME>END_PI")
(conj (sorted-set) "Bravo" "Charlie" "Sigma" "Alpha")
(sorted-set "Bravo" "CharPI:NAME:<NAME>END_PI" "Sigma" "Alpha")
(def players #{"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"})
(def new-players ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"])
(into players new-players)
(def scores {"PI:NAME:<NAME>END_PI" 1400
"PI:NAME:<NAME>END_PI" 1240
"PI:NAME:<NAME>END_PI" 1024})
(def scores {"PI:NAME:<NAME>END_PI" 1400, "PI:NAME:<NAME>END_PI" 1240, "PI:NAME:<NAME>END_PI" 1024})
(assoc scores "PI:NAME:<NAME>END_PI" 0)
(assoc scores "PI:NAME:<NAME>END_PI" 0)
(dissoc scores "PI:NAME:<NAME>END_PI")
(get scores "PI:NAME:<NAME>END_PI")
(def directions {:north 0
:east 1
:south 2
:west 3})
(directions :north)
(:north directions)
(def bad-lookup-map nil)
(bad-lookup-map :foo)
(:foo bad-lookup-map)
(get scores "PI:NAME:<NAME>END_PI" 0)
(directions :northwest -1)
(:foo bad-lookup-map 1)
(contains? scores "PI:NAME:<NAME>END_PI")
(find scores "PI:NAME:<NAME>END_PI")
(find scores "PI:NAME:<NAME>END_PI")
(keys scores)
(vals scores)
(def players #{"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"})
(zipmap players (repeat 0))
(doc repeat)
(doc zipmap)
(into {} (map (fn [player] [player 0]) players))
(reduce (fn [m player]
(assoc m player 0))
{}
players)
(def new-scores {"PI:NAME:<NAME>END_PI" 300, "PI:NAME:<NAME>END_PI" 900})
(merge scores new-scores)
(doc merge)
(source merge)
(merge-with + scores new-scores)
(def sm (sorted-map "PI:NAME:<NAME>END_PI" 204
"Alpha" 35
"Sigma" 99
"PI:NAME:<NAME>END_PI" 100))
(keys sm)
(vals sm)
(def person
{:first-name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"
:age 32
:occupation "Programmer"})
(get person :occupation)
(person :occupation)
(:occupation person)
(:favourite-colour person "beige")
(assoc person :occupation "Baker")
(dissoc person :age)
(def company
{:name "WidgetCo"
:address {:street "123 Main St"
:city "Springfield"
:state "IL"}})
(get-in company [:address :city])
(doc assoc-in)
(doc update-in)
(assoc-in company [:address :street] "303 Broadway")
(defrecord Person [first-name last-name age occupation])
(def kelly (->Person "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" 32 "Programmer"))
(def kelly (map->Person {:first-name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"
:age 32
:occupation "Programmer"}))
(kelly :first-name)
(:first-name PI:NAME:<NAME>END_PI)
(str "2 is " (if (even? 2) "even" "odd"))
(if (true? false) "impossible")
(if true :truthy :falsey)
(if (Object.) :truthy :falsey)
(if [] :truthy :falsey)
(if 0 :truthy :falsey)
(if false :truthy :falsey)
(if nil :truthy :falsey)
(if (even? 5)
(do (println "even")
true)
(do (println "odd")
false))
(when (neg? x)
(throw (RuntimeException. (str "x must be positive: " x))))
(let [x 5]
(cond
(< x 2) "x is less than 2"
(< x 10) "x is less than 10"))
(let [x 11]
(cond
(< x 2) "x is less than 2"
(< x 10) "x is less than 10"
:else "x is greater than or equal to 10"))
(defn foo [x]
(case x
5 "x is 5"
10 "x is 10"))
(foo 10)
(foo 11)
(defn foo [x]
(case x
5 "x is 5"
10 "x is 10"
"x isn't 5 or 10"))
(foo 10)
(foo 11)
(dotimes [i 3]
(println i))
(range 3)
(range 3 9)
(doseq [n (range 3)]
(println n))
(doseq [n (range 3 9)]
(println n))
(doseq [letter [:a :b]
number (range 3)]
(prn [letter number]))
(for [letter [:a :b]
number (range 3)]
[letter number])
(loop [i 0]
(if (< i 10)
(recur (inc i))
i))
(defn increase [i]
(if (< i 10)
(recur (inc i))
i))
(try
(/ 2 0)
(catch ArithmeticException e
"divide by zero")
(finally
(println "cleanup")))
(try
(throw (Exception. "something went wrong"))
(catch Exception e (.getMessage e)))
(try
(throw (ex-info "There was a problem" {:detail 42}))
(catch Exception e
(prn (:detail (ex-data e)))))
(let [f (clojure.java.io/writer "/tmp/new")]
(try
(.write f "some text")
(finally
(.close f))))
(with-open [f (clojure.java.io/writer "/tmp/new")]
(.write f "some text"))
|
[
{
"context": " false}\n {:name \"toucan\"\n :database-type \"OBJECT\"\n ",
"end": 2235,
"score": 0.6970667839050293,
"start": 2229,
"tag": "NAME",
"value": "toucan"
}
] | c#-metabase/test/metabase/sync/sync_metadata/fields/fetch_metadata_test.clj | hanakhry/Crime_Admin | 0 | (ns metabase.sync.sync-metadata.fields.fetch-metadata-test
(:require [clojure.test :refer :all]
[clojure.walk :as walk]
[medley.core :as m]
[metabase.models.database :refer [Database]]
[metabase.models.table :refer [Table]]
[metabase.sync.sync-metadata :as sync-metadata]
[metabase.sync.sync-metadata.fields.fetch-metadata :as sync-fields.fetch-metadata]
[metabase.test :as mt]
[metabase.test.mock.toucanery :as toucanery]
[metabase.util :as u]
[toucan.db :as db]))
;; `our-metadata` should match up with what we have in the DB
(deftest does-metadata-match-test
(mt/with-temp Database [db {:engine ::toucanery/toucanery}]
(sync-metadata/sync-db-metadata! db)
(is (= #{{:name "id"
:database-type "SERIAL"
:base-type :type/Integer
:effective-type :type/Integer
:semantic-type :type/PK
:pk? true}
{:name "buyer"
:database-type "OBJECT"
:base-type :type/Dictionary
:effective-type :type/Dictionary
:pk? false
:nested-fields #{{:name "name"
:database-type "VARCHAR"
:base-type :type/Text
:effective-type :type/Text
:pk? false}
{:name "cc"
:database-type "VARCHAR"
:base-type :type/Text
:effective-type :type/Text
:pk? false}}}
{:name "ts"
:database-type "BIGINT"
:base-type :type/BigInteger
:effective-type :type/DateTime
:coercion-strategy :Coercion/UNIXMilliSeconds->DateTime
:pk? false}
{:name "toucan"
:database-type "OBJECT"
:base-type :type/Dictionary
:effective-type :type/Dictionary
:pk? false
:nested-fields #{{:name "name"
:database-type "VARCHAR"
:base-type :type/Text
:effective-type :type/Text
:pk? false}
{:name "details"
:database-type "OBJECT"
:base-type :type/Dictionary
:effective-type :type/Dictionary
:pk? false
:nested-fields #{{:name "weight"
:database-type "DECIMAL"
:base-type :type/Decimal
:effective-type :type/Decimal
:semantic-type :type/Category
:pk? false}
{:name "age"
:database-type "INT"
:base-type :type/Integer
:effective-type :type/Integer
:pk? false}}}}}}
(let [transactions-table-id (u/the-id (db/select-one-id Table :db_id (u/the-id db), :name "transactions"))
remove-ids-and-nil-vals (partial walk/postwalk #(if-not (map? %)
%
;; database-position isn't stable since they are
;; defined in sets. changing keys will change the
;; order in the set implementation
(m/filter-vals some? (dissoc % :id :database-position))))]
(remove-ids-and-nil-vals (#'sync-fields.fetch-metadata/our-metadata (Table transactions-table-id))))))))
| 37786 | (ns metabase.sync.sync-metadata.fields.fetch-metadata-test
(:require [clojure.test :refer :all]
[clojure.walk :as walk]
[medley.core :as m]
[metabase.models.database :refer [Database]]
[metabase.models.table :refer [Table]]
[metabase.sync.sync-metadata :as sync-metadata]
[metabase.sync.sync-metadata.fields.fetch-metadata :as sync-fields.fetch-metadata]
[metabase.test :as mt]
[metabase.test.mock.toucanery :as toucanery]
[metabase.util :as u]
[toucan.db :as db]))
;; `our-metadata` should match up with what we have in the DB
(deftest does-metadata-match-test
(mt/with-temp Database [db {:engine ::toucanery/toucanery}]
(sync-metadata/sync-db-metadata! db)
(is (= #{{:name "id"
:database-type "SERIAL"
:base-type :type/Integer
:effective-type :type/Integer
:semantic-type :type/PK
:pk? true}
{:name "buyer"
:database-type "OBJECT"
:base-type :type/Dictionary
:effective-type :type/Dictionary
:pk? false
:nested-fields #{{:name "name"
:database-type "VARCHAR"
:base-type :type/Text
:effective-type :type/Text
:pk? false}
{:name "cc"
:database-type "VARCHAR"
:base-type :type/Text
:effective-type :type/Text
:pk? false}}}
{:name "ts"
:database-type "BIGINT"
:base-type :type/BigInteger
:effective-type :type/DateTime
:coercion-strategy :Coercion/UNIXMilliSeconds->DateTime
:pk? false}
{:name "<NAME>"
:database-type "OBJECT"
:base-type :type/Dictionary
:effective-type :type/Dictionary
:pk? false
:nested-fields #{{:name "name"
:database-type "VARCHAR"
:base-type :type/Text
:effective-type :type/Text
:pk? false}
{:name "details"
:database-type "OBJECT"
:base-type :type/Dictionary
:effective-type :type/Dictionary
:pk? false
:nested-fields #{{:name "weight"
:database-type "DECIMAL"
:base-type :type/Decimal
:effective-type :type/Decimal
:semantic-type :type/Category
:pk? false}
{:name "age"
:database-type "INT"
:base-type :type/Integer
:effective-type :type/Integer
:pk? false}}}}}}
(let [transactions-table-id (u/the-id (db/select-one-id Table :db_id (u/the-id db), :name "transactions"))
remove-ids-and-nil-vals (partial walk/postwalk #(if-not (map? %)
%
;; database-position isn't stable since they are
;; defined in sets. changing keys will change the
;; order in the set implementation
(m/filter-vals some? (dissoc % :id :database-position))))]
(remove-ids-and-nil-vals (#'sync-fields.fetch-metadata/our-metadata (Table transactions-table-id))))))))
| true | (ns metabase.sync.sync-metadata.fields.fetch-metadata-test
(:require [clojure.test :refer :all]
[clojure.walk :as walk]
[medley.core :as m]
[metabase.models.database :refer [Database]]
[metabase.models.table :refer [Table]]
[metabase.sync.sync-metadata :as sync-metadata]
[metabase.sync.sync-metadata.fields.fetch-metadata :as sync-fields.fetch-metadata]
[metabase.test :as mt]
[metabase.test.mock.toucanery :as toucanery]
[metabase.util :as u]
[toucan.db :as db]))
;; `our-metadata` should match up with what we have in the DB
(deftest does-metadata-match-test
(mt/with-temp Database [db {:engine ::toucanery/toucanery}]
(sync-metadata/sync-db-metadata! db)
(is (= #{{:name "id"
:database-type "SERIAL"
:base-type :type/Integer
:effective-type :type/Integer
:semantic-type :type/PK
:pk? true}
{:name "buyer"
:database-type "OBJECT"
:base-type :type/Dictionary
:effective-type :type/Dictionary
:pk? false
:nested-fields #{{:name "name"
:database-type "VARCHAR"
:base-type :type/Text
:effective-type :type/Text
:pk? false}
{:name "cc"
:database-type "VARCHAR"
:base-type :type/Text
:effective-type :type/Text
:pk? false}}}
{:name "ts"
:database-type "BIGINT"
:base-type :type/BigInteger
:effective-type :type/DateTime
:coercion-strategy :Coercion/UNIXMilliSeconds->DateTime
:pk? false}
{:name "PI:NAME:<NAME>END_PI"
:database-type "OBJECT"
:base-type :type/Dictionary
:effective-type :type/Dictionary
:pk? false
:nested-fields #{{:name "name"
:database-type "VARCHAR"
:base-type :type/Text
:effective-type :type/Text
:pk? false}
{:name "details"
:database-type "OBJECT"
:base-type :type/Dictionary
:effective-type :type/Dictionary
:pk? false
:nested-fields #{{:name "weight"
:database-type "DECIMAL"
:base-type :type/Decimal
:effective-type :type/Decimal
:semantic-type :type/Category
:pk? false}
{:name "age"
:database-type "INT"
:base-type :type/Integer
:effective-type :type/Integer
:pk? false}}}}}}
(let [transactions-table-id (u/the-id (db/select-one-id Table :db_id (u/the-id db), :name "transactions"))
remove-ids-and-nil-vals (partial walk/postwalk #(if-not (map? %)
%
;; database-position isn't stable since they are
;; defined in sets. changing keys will change the
;; order in the set implementation
(m/filter-vals some? (dissoc % :id :database-position))))]
(remove-ids-and-nil-vals (#'sync-fields.fetch-metadata/our-metadata (Table transactions-table-id))))))))
|
[
{
"context": "sync\n (md/make\n :name \"Bob\"\n :action (cI nil\n ",
"end": 7214,
"score": 0.9986059069633484,
"start": 7211,
"tag": "NAME",
"value": "Bob"
},
{
"context": " (vals (md-cz res))))))\n (is (= \"Bob\" (:name @res)))\n (is (= \"Bob\" (md-name res)))",
"end": 8247,
"score": 0.9983822107315063,
"start": 8244,
"tag": "NAME",
"value": "Bob"
},
{
"context": ")))\n (is (= \"Bob\" (:name @res)))\n (is (= \"Bob\" (md-name res)))\n (println :res @res)\n (i",
"end": 8280,
"score": 0.998314380645752,
"start": 8277,
"tag": "NAME",
"value": "Bob"
}
] | cljs/matrix/test/tiltontec/model/core_test.cljc | kennytilton/matrix | 84 | (ns tiltontec.model.core-test
(:require
#?(:clj [clojure.test :refer :all]
:cljs [cljs.test
:refer-macros [deftest is are]])
#?(:cljs [tiltontec.util.base
:refer-macros [trx prog1 *trx?*]]
:clj [tiltontec.util.base
:refer :all])
[tiltontec.util.core :refer [type-of err]]
#?(:clj [tiltontec.cell.base :refer :all :as cty]
:cljs [tiltontec.cell.base
:refer-macros [without-c-dependency]
:refer [cells-init c-optimized-away? c-formula? c-value c-optimize
c-unbound? c-input? ia-type?
c-model mdead? c-valid? c-useds c-ref? md-ref?
c-state +pulse+ c-pulse-observed
*call-stack* *defer-changes* unbound
c-rule c-me c-value-state c-callers caller-ensure
unlink-from-callers *causation*
c-slot-name c-synaptic? caller-drop
c-pulse c-pulse-last-changed c-ephemeral? c-slot c-slots
*depender* *not-to-be*
*c-prop-depth* md-slot-owning? c-lazy] :as cty])
#?(:cljs [tiltontec.cell.integrity
:refer-macros [with-integrity]]
:clj [tiltontec.cell.integrity :refer [with-integrity]])
#?(:clj [tiltontec.cell.observer
:refer [defobserver fn-obs]]
:cljs [tiltontec.cell.observer
:refer-macros [defobserver fn-obs]])
#?(:cljs [tiltontec.cell.core
:refer-macros [cF cF+ c-reset-next! cFonce cFn]
:refer [cI c-reset! make-cell make-c-formula]]
:clj [tiltontec.cell.core :refer :all])
[tiltontec.cell.evaluate :refer [c-get c-awaken]]
[tiltontec.model.base :refer [md-cz md-cell]]
#?(:clj [tiltontec.model.core :refer :all :as md]
:cljs [tiltontec.model.core
:refer-macros [cFkids the-kids mdv!]
:refer [md-get md-name fget fm! make md-reset! md-getx]
:as md])
))
#?(:cljs
(set! *print-level* 2)
:clj (set! *print-level* 2))
(deftest fm-0
(cells-init)
(let [u (md/make
:kon (cI false :slot :kon)
:kids (cF ;;(trx :kids-run! *depender*)
(when (md-get me :kon)
(vector
(md/make
:par me
:name :konzo
:kzo (cI 3))))))]
(is (nil? (:kids @u)))
(let [kc (md-cell u :kids)
kon (md-cell u :kon)]
(c-reset! kon true)
(is (= 1 (count (:kids @u))))
(is (md/fget :konzo u :inside? true))
)))
(deftest fm-2
(let [u (md/make
:name :uni
:kids (cF (vector
(md/make
:par me
:name :aa)
(md/make
:par me
:name :bb
:kids (cF (vector
(md/make
:par me
:name :bba)
(md/make
:par me
:name :bbb)))))))]
;; (is (fget :bba u :inside? true :must? true))
;; (is (thrown-with-msg?
;; Exception #"fget-must-failed"
;; (fget :bbax u :inside? true :must? true)))
;; (is (nil? (fget :bbax u :inside? true :must? false)))
(let [bba (fget :bba u :inside? true :must? true)]
(is bba)
(is (md/fget :uni bba :inside? true :up? true))
(is (fget :aa bba :inside? false :up? true))
(is (fget :bb bba :inside? true :up? true))
(is (fget :bbb bba :inside? false :up? true))
)
))
(deftest fm-3
(let [u (md/make
:u63 (cF (+ (mdv! :aa :aa42)
(mdv! :bb :bb21)))
:kon (cI false)
:kids (cF (remove nil?
(vector
(md/make
:par me
:name :aa
:aa42 (cF (* 2 (mdv! :bb :bb21)))
:aa3 (cI 3))
(when (md-get me :kon)
(md/make
:par me
:name :konzo
:kzo (cI 3)))
(md/make
:par me
:name :bb
:bb21 (cF (* 7 (mdv! :aa :aa3))))))))]
(is (= 63 (md-get u :u63)))
(is (= 42 (mdv! :aa :aa42 u)))
(is (= 21 (mdv! :bb :bb21 u)))
(is (nil? (fget :konzo u :must? false)))
(c-reset! (md-cell u :kon) true)
(is (:kon @u))
(is (md-cell u :kon))
(is (= 3 (count (:kids @u))))
(is (fget :konzo u :inside? true))
))
(deftest fm-3x
(let [u (md/make
:u63 (cF (+ (mdv! :aa :aa42)
(mdv! :bb :bb21)))
:kon (cI false)
:kids (cF (the-kids
(md/make
:name :aa
:aa42 (cF (* 2 (mdv! :bb :bb21)))
:aa3 (cI 3))
(when (md-get me :kon)
(md/make
:name :konzo
:kzo (cI 3)))
(md/make
:name :bb
:bb21 (cF (* 7 (mdv! :aa :aa3)))))))]
(is (= 63 (md-get u :u63)))
(is (= 42 (mdv! :aa :aa42 u)))
(is (= 21 (mdv! :bb :bb21 u)))
(is (nil? (fget :konzo u :must? false)))
(c-reset! (md-cell u :kon) true)
(is (:kon @u))
(is (md-cell u :kon))
(is (= 3 (count (:kids @u))))
(is (fget :konzo u :inside? true))
))
(deftest fm-picker
(let [u (md/make
:kids (cF (the-kids
(md/make :name :picker
:value (cI 42)
:kids (cF (the-kids
(md/make
:name :aax)
(md/make
:name :bbx))))
(md/make :name :dd
:kzo (cF (let [p (fget :picker me)]
(println :bingo p)
(md-get p :value)))))))]
(is (= 42 (mdv! :picker :value u)))
(is (= 42 (mdv! :dd :kzo u)))))
(derive ::typetest ::cty/model)
(deftest mm-typed
(let [me (md/make
:type ::typetest
:x2 (cI 2)
:age (cF (* (md-get me :x2)
21)))]
(is (= 42 (md-get me :age)))
(is (ia-type? me ::typetest))))
(deftest mm-opti-1
(let [me (md/make
:x2 2
:age (cF (* 21 (md-get me :x2)))
)]
(is (= 2 (md-get me :x2)))
(is (= 42 (md-get me :age)))
(is (nil? (md-cell me :age)))
))
(deftest mm-install-alive
(let [bct (atom 0)
res (do ;; sync
(md/make
:name "Bob"
:action (cI nil
:ephemeral? true)
:bogus (cF (if-let [be (md-get me :bogus-e)]
(do
(trx :bingo-e!!!!!!!! be @bct)
(swap! bct inc)
(* 2 be))
(trx :bogus-no-e (:bogus-e @me))))
:bogus-e (cI 21 :ephemeral? true)
:loc (cF (case (md-get me :action)
:leave :away
:return :home
:missing))))]
(println :meta (meta res))
(is (= (:cz (meta res)) (md-cz res)))
(is (= 4 (count (md-cz res))))
(is (every? c-ref? (vals (md-cz res))))
(is (= #{:action :loc :bogus :bogus-e} (set (keys (md-cz res)))))
(is (every? #(= res (c-me %)) (vals (md-cz res))))
(is (= #{:action :loc :bogus :bogus-e}
(set (map #(c-slot %)
(vals (md-cz res))))))
(is (= "Bob" (:name @res)))
(is (= "Bob" (md-name res)))
(println :res @res)
(is (= 42 (:bogus @res)))
(is (= nil (:bogus-e @res))) ;; ephemeral, so reset to nil silently
(is (= nil (:action @res)))
(println :loc (:loc @res))
(is (= :missing (:loc @res)))
(is (= 1 @bct))
(reset! bct 0)
(md-reset! res :action :return)
(is (= :home (:loc @res)))
(is (zero? @bct))
))
(deftest hello-model
(let [uni (md/make
::md/family
:kids (cF (the-kids
(md/make
:name :visitor
:moniker "World"
:action (cI nil
:ephemeral? true
:obs (fn [slot me new old c]
(when new (trx visitor-did new)))))
(md/make
:name :resident
:action (cI nil :ephemeral? true)
:location (cF+ [:obs (fn-obs (when new (trx :honey-im new)))]
(case (md-get me :action)
:leave :away
:return :home
:missing))
:response (cF+ [:obs (fn-obs (when new
(trx :r-response new)))
:ephemeral? true]
(when (= :home (md-get me :location))
(when-let [act (mdv! :visitor :action)]
(case act
:knock-knock "hello, world")))))
(md/make
:name :alarm
:on-off (cF+ [:obs (fn-obs
(trx :telling-alarm-api new))]
(if (= :home (mdv! :resident :location)) :off :on))
:activity (cF+ [:obs (fn-obs
(case new
:call-police (trx :auto-dialing-911)
nil))]
(when (= :on (md-get me :on-off))
(when-let [action (mdv! :visitor :action)]
(case action
:smashing-window :call-police
nil))))))))]
(let [viz (fm! :visitor uni)
rez (fm! :resident uni)]
(is (not (nil? viz)))
(is (not (nil? rez)))
(is (not (nil? (md-cell rez :action))))
(is (= :missing (mdv! :resident :location uni)))
(md-reset! viz :action :knock-knock)
(md-reset! viz :action :smashing-window)
(is (not (nil? (md-cell rez :action))))
(md-reset! rez :action :return)
(is (= :home (mdv! :resident :location uni)))
(md-reset! viz :action :knock-knock))))
#?(:cljs (do
(cljs.test/run-tests)
))
| 104921 | (ns tiltontec.model.core-test
(:require
#?(:clj [clojure.test :refer :all]
:cljs [cljs.test
:refer-macros [deftest is are]])
#?(:cljs [tiltontec.util.base
:refer-macros [trx prog1 *trx?*]]
:clj [tiltontec.util.base
:refer :all])
[tiltontec.util.core :refer [type-of err]]
#?(:clj [tiltontec.cell.base :refer :all :as cty]
:cljs [tiltontec.cell.base
:refer-macros [without-c-dependency]
:refer [cells-init c-optimized-away? c-formula? c-value c-optimize
c-unbound? c-input? ia-type?
c-model mdead? c-valid? c-useds c-ref? md-ref?
c-state +pulse+ c-pulse-observed
*call-stack* *defer-changes* unbound
c-rule c-me c-value-state c-callers caller-ensure
unlink-from-callers *causation*
c-slot-name c-synaptic? caller-drop
c-pulse c-pulse-last-changed c-ephemeral? c-slot c-slots
*depender* *not-to-be*
*c-prop-depth* md-slot-owning? c-lazy] :as cty])
#?(:cljs [tiltontec.cell.integrity
:refer-macros [with-integrity]]
:clj [tiltontec.cell.integrity :refer [with-integrity]])
#?(:clj [tiltontec.cell.observer
:refer [defobserver fn-obs]]
:cljs [tiltontec.cell.observer
:refer-macros [defobserver fn-obs]])
#?(:cljs [tiltontec.cell.core
:refer-macros [cF cF+ c-reset-next! cFonce cFn]
:refer [cI c-reset! make-cell make-c-formula]]
:clj [tiltontec.cell.core :refer :all])
[tiltontec.cell.evaluate :refer [c-get c-awaken]]
[tiltontec.model.base :refer [md-cz md-cell]]
#?(:clj [tiltontec.model.core :refer :all :as md]
:cljs [tiltontec.model.core
:refer-macros [cFkids the-kids mdv!]
:refer [md-get md-name fget fm! make md-reset! md-getx]
:as md])
))
#?(:cljs
(set! *print-level* 2)
:clj (set! *print-level* 2))
(deftest fm-0
(cells-init)
(let [u (md/make
:kon (cI false :slot :kon)
:kids (cF ;;(trx :kids-run! *depender*)
(when (md-get me :kon)
(vector
(md/make
:par me
:name :konzo
:kzo (cI 3))))))]
(is (nil? (:kids @u)))
(let [kc (md-cell u :kids)
kon (md-cell u :kon)]
(c-reset! kon true)
(is (= 1 (count (:kids @u))))
(is (md/fget :konzo u :inside? true))
)))
(deftest fm-2
(let [u (md/make
:name :uni
:kids (cF (vector
(md/make
:par me
:name :aa)
(md/make
:par me
:name :bb
:kids (cF (vector
(md/make
:par me
:name :bba)
(md/make
:par me
:name :bbb)))))))]
;; (is (fget :bba u :inside? true :must? true))
;; (is (thrown-with-msg?
;; Exception #"fget-must-failed"
;; (fget :bbax u :inside? true :must? true)))
;; (is (nil? (fget :bbax u :inside? true :must? false)))
(let [bba (fget :bba u :inside? true :must? true)]
(is bba)
(is (md/fget :uni bba :inside? true :up? true))
(is (fget :aa bba :inside? false :up? true))
(is (fget :bb bba :inside? true :up? true))
(is (fget :bbb bba :inside? false :up? true))
)
))
(deftest fm-3
(let [u (md/make
:u63 (cF (+ (mdv! :aa :aa42)
(mdv! :bb :bb21)))
:kon (cI false)
:kids (cF (remove nil?
(vector
(md/make
:par me
:name :aa
:aa42 (cF (* 2 (mdv! :bb :bb21)))
:aa3 (cI 3))
(when (md-get me :kon)
(md/make
:par me
:name :konzo
:kzo (cI 3)))
(md/make
:par me
:name :bb
:bb21 (cF (* 7 (mdv! :aa :aa3))))))))]
(is (= 63 (md-get u :u63)))
(is (= 42 (mdv! :aa :aa42 u)))
(is (= 21 (mdv! :bb :bb21 u)))
(is (nil? (fget :konzo u :must? false)))
(c-reset! (md-cell u :kon) true)
(is (:kon @u))
(is (md-cell u :kon))
(is (= 3 (count (:kids @u))))
(is (fget :konzo u :inside? true))
))
(deftest fm-3x
(let [u (md/make
:u63 (cF (+ (mdv! :aa :aa42)
(mdv! :bb :bb21)))
:kon (cI false)
:kids (cF (the-kids
(md/make
:name :aa
:aa42 (cF (* 2 (mdv! :bb :bb21)))
:aa3 (cI 3))
(when (md-get me :kon)
(md/make
:name :konzo
:kzo (cI 3)))
(md/make
:name :bb
:bb21 (cF (* 7 (mdv! :aa :aa3)))))))]
(is (= 63 (md-get u :u63)))
(is (= 42 (mdv! :aa :aa42 u)))
(is (= 21 (mdv! :bb :bb21 u)))
(is (nil? (fget :konzo u :must? false)))
(c-reset! (md-cell u :kon) true)
(is (:kon @u))
(is (md-cell u :kon))
(is (= 3 (count (:kids @u))))
(is (fget :konzo u :inside? true))
))
(deftest fm-picker
(let [u (md/make
:kids (cF (the-kids
(md/make :name :picker
:value (cI 42)
:kids (cF (the-kids
(md/make
:name :aax)
(md/make
:name :bbx))))
(md/make :name :dd
:kzo (cF (let [p (fget :picker me)]
(println :bingo p)
(md-get p :value)))))))]
(is (= 42 (mdv! :picker :value u)))
(is (= 42 (mdv! :dd :kzo u)))))
(derive ::typetest ::cty/model)
(deftest mm-typed
(let [me (md/make
:type ::typetest
:x2 (cI 2)
:age (cF (* (md-get me :x2)
21)))]
(is (= 42 (md-get me :age)))
(is (ia-type? me ::typetest))))
(deftest mm-opti-1
(let [me (md/make
:x2 2
:age (cF (* 21 (md-get me :x2)))
)]
(is (= 2 (md-get me :x2)))
(is (= 42 (md-get me :age)))
(is (nil? (md-cell me :age)))
))
(deftest mm-install-alive
(let [bct (atom 0)
res (do ;; sync
(md/make
:name "<NAME>"
:action (cI nil
:ephemeral? true)
:bogus (cF (if-let [be (md-get me :bogus-e)]
(do
(trx :bingo-e!!!!!!!! be @bct)
(swap! bct inc)
(* 2 be))
(trx :bogus-no-e (:bogus-e @me))))
:bogus-e (cI 21 :ephemeral? true)
:loc (cF (case (md-get me :action)
:leave :away
:return :home
:missing))))]
(println :meta (meta res))
(is (= (:cz (meta res)) (md-cz res)))
(is (= 4 (count (md-cz res))))
(is (every? c-ref? (vals (md-cz res))))
(is (= #{:action :loc :bogus :bogus-e} (set (keys (md-cz res)))))
(is (every? #(= res (c-me %)) (vals (md-cz res))))
(is (= #{:action :loc :bogus :bogus-e}
(set (map #(c-slot %)
(vals (md-cz res))))))
(is (= "<NAME>" (:name @res)))
(is (= "<NAME>" (md-name res)))
(println :res @res)
(is (= 42 (:bogus @res)))
(is (= nil (:bogus-e @res))) ;; ephemeral, so reset to nil silently
(is (= nil (:action @res)))
(println :loc (:loc @res))
(is (= :missing (:loc @res)))
(is (= 1 @bct))
(reset! bct 0)
(md-reset! res :action :return)
(is (= :home (:loc @res)))
(is (zero? @bct))
))
(deftest hello-model
(let [uni (md/make
::md/family
:kids (cF (the-kids
(md/make
:name :visitor
:moniker "World"
:action (cI nil
:ephemeral? true
:obs (fn [slot me new old c]
(when new (trx visitor-did new)))))
(md/make
:name :resident
:action (cI nil :ephemeral? true)
:location (cF+ [:obs (fn-obs (when new (trx :honey-im new)))]
(case (md-get me :action)
:leave :away
:return :home
:missing))
:response (cF+ [:obs (fn-obs (when new
(trx :r-response new)))
:ephemeral? true]
(when (= :home (md-get me :location))
(when-let [act (mdv! :visitor :action)]
(case act
:knock-knock "hello, world")))))
(md/make
:name :alarm
:on-off (cF+ [:obs (fn-obs
(trx :telling-alarm-api new))]
(if (= :home (mdv! :resident :location)) :off :on))
:activity (cF+ [:obs (fn-obs
(case new
:call-police (trx :auto-dialing-911)
nil))]
(when (= :on (md-get me :on-off))
(when-let [action (mdv! :visitor :action)]
(case action
:smashing-window :call-police
nil))))))))]
(let [viz (fm! :visitor uni)
rez (fm! :resident uni)]
(is (not (nil? viz)))
(is (not (nil? rez)))
(is (not (nil? (md-cell rez :action))))
(is (= :missing (mdv! :resident :location uni)))
(md-reset! viz :action :knock-knock)
(md-reset! viz :action :smashing-window)
(is (not (nil? (md-cell rez :action))))
(md-reset! rez :action :return)
(is (= :home (mdv! :resident :location uni)))
(md-reset! viz :action :knock-knock))))
#?(:cljs (do
(cljs.test/run-tests)
))
| true | (ns tiltontec.model.core-test
(:require
#?(:clj [clojure.test :refer :all]
:cljs [cljs.test
:refer-macros [deftest is are]])
#?(:cljs [tiltontec.util.base
:refer-macros [trx prog1 *trx?*]]
:clj [tiltontec.util.base
:refer :all])
[tiltontec.util.core :refer [type-of err]]
#?(:clj [tiltontec.cell.base :refer :all :as cty]
:cljs [tiltontec.cell.base
:refer-macros [without-c-dependency]
:refer [cells-init c-optimized-away? c-formula? c-value c-optimize
c-unbound? c-input? ia-type?
c-model mdead? c-valid? c-useds c-ref? md-ref?
c-state +pulse+ c-pulse-observed
*call-stack* *defer-changes* unbound
c-rule c-me c-value-state c-callers caller-ensure
unlink-from-callers *causation*
c-slot-name c-synaptic? caller-drop
c-pulse c-pulse-last-changed c-ephemeral? c-slot c-slots
*depender* *not-to-be*
*c-prop-depth* md-slot-owning? c-lazy] :as cty])
#?(:cljs [tiltontec.cell.integrity
:refer-macros [with-integrity]]
:clj [tiltontec.cell.integrity :refer [with-integrity]])
#?(:clj [tiltontec.cell.observer
:refer [defobserver fn-obs]]
:cljs [tiltontec.cell.observer
:refer-macros [defobserver fn-obs]])
#?(:cljs [tiltontec.cell.core
:refer-macros [cF cF+ c-reset-next! cFonce cFn]
:refer [cI c-reset! make-cell make-c-formula]]
:clj [tiltontec.cell.core :refer :all])
[tiltontec.cell.evaluate :refer [c-get c-awaken]]
[tiltontec.model.base :refer [md-cz md-cell]]
#?(:clj [tiltontec.model.core :refer :all :as md]
:cljs [tiltontec.model.core
:refer-macros [cFkids the-kids mdv!]
:refer [md-get md-name fget fm! make md-reset! md-getx]
:as md])
))
#?(:cljs
(set! *print-level* 2)
:clj (set! *print-level* 2))
(deftest fm-0
(cells-init)
(let [u (md/make
:kon (cI false :slot :kon)
:kids (cF ;;(trx :kids-run! *depender*)
(when (md-get me :kon)
(vector
(md/make
:par me
:name :konzo
:kzo (cI 3))))))]
(is (nil? (:kids @u)))
(let [kc (md-cell u :kids)
kon (md-cell u :kon)]
(c-reset! kon true)
(is (= 1 (count (:kids @u))))
(is (md/fget :konzo u :inside? true))
)))
(deftest fm-2
(let [u (md/make
:name :uni
:kids (cF (vector
(md/make
:par me
:name :aa)
(md/make
:par me
:name :bb
:kids (cF (vector
(md/make
:par me
:name :bba)
(md/make
:par me
:name :bbb)))))))]
;; (is (fget :bba u :inside? true :must? true))
;; (is (thrown-with-msg?
;; Exception #"fget-must-failed"
;; (fget :bbax u :inside? true :must? true)))
;; (is (nil? (fget :bbax u :inside? true :must? false)))
(let [bba (fget :bba u :inside? true :must? true)]
(is bba)
(is (md/fget :uni bba :inside? true :up? true))
(is (fget :aa bba :inside? false :up? true))
(is (fget :bb bba :inside? true :up? true))
(is (fget :bbb bba :inside? false :up? true))
)
))
(deftest fm-3
(let [u (md/make
:u63 (cF (+ (mdv! :aa :aa42)
(mdv! :bb :bb21)))
:kon (cI false)
:kids (cF (remove nil?
(vector
(md/make
:par me
:name :aa
:aa42 (cF (* 2 (mdv! :bb :bb21)))
:aa3 (cI 3))
(when (md-get me :kon)
(md/make
:par me
:name :konzo
:kzo (cI 3)))
(md/make
:par me
:name :bb
:bb21 (cF (* 7 (mdv! :aa :aa3))))))))]
(is (= 63 (md-get u :u63)))
(is (= 42 (mdv! :aa :aa42 u)))
(is (= 21 (mdv! :bb :bb21 u)))
(is (nil? (fget :konzo u :must? false)))
(c-reset! (md-cell u :kon) true)
(is (:kon @u))
(is (md-cell u :kon))
(is (= 3 (count (:kids @u))))
(is (fget :konzo u :inside? true))
))
(deftest fm-3x
(let [u (md/make
:u63 (cF (+ (mdv! :aa :aa42)
(mdv! :bb :bb21)))
:kon (cI false)
:kids (cF (the-kids
(md/make
:name :aa
:aa42 (cF (* 2 (mdv! :bb :bb21)))
:aa3 (cI 3))
(when (md-get me :kon)
(md/make
:name :konzo
:kzo (cI 3)))
(md/make
:name :bb
:bb21 (cF (* 7 (mdv! :aa :aa3)))))))]
(is (= 63 (md-get u :u63)))
(is (= 42 (mdv! :aa :aa42 u)))
(is (= 21 (mdv! :bb :bb21 u)))
(is (nil? (fget :konzo u :must? false)))
(c-reset! (md-cell u :kon) true)
(is (:kon @u))
(is (md-cell u :kon))
(is (= 3 (count (:kids @u))))
(is (fget :konzo u :inside? true))
))
(deftest fm-picker
(let [u (md/make
:kids (cF (the-kids
(md/make :name :picker
:value (cI 42)
:kids (cF (the-kids
(md/make
:name :aax)
(md/make
:name :bbx))))
(md/make :name :dd
:kzo (cF (let [p (fget :picker me)]
(println :bingo p)
(md-get p :value)))))))]
(is (= 42 (mdv! :picker :value u)))
(is (= 42 (mdv! :dd :kzo u)))))
(derive ::typetest ::cty/model)
(deftest mm-typed
(let [me (md/make
:type ::typetest
:x2 (cI 2)
:age (cF (* (md-get me :x2)
21)))]
(is (= 42 (md-get me :age)))
(is (ia-type? me ::typetest))))
(deftest mm-opti-1
(let [me (md/make
:x2 2
:age (cF (* 21 (md-get me :x2)))
)]
(is (= 2 (md-get me :x2)))
(is (= 42 (md-get me :age)))
(is (nil? (md-cell me :age)))
))
(deftest mm-install-alive
(let [bct (atom 0)
res (do ;; sync
(md/make
:name "PI:NAME:<NAME>END_PI"
:action (cI nil
:ephemeral? true)
:bogus (cF (if-let [be (md-get me :bogus-e)]
(do
(trx :bingo-e!!!!!!!! be @bct)
(swap! bct inc)
(* 2 be))
(trx :bogus-no-e (:bogus-e @me))))
:bogus-e (cI 21 :ephemeral? true)
:loc (cF (case (md-get me :action)
:leave :away
:return :home
:missing))))]
(println :meta (meta res))
(is (= (:cz (meta res)) (md-cz res)))
(is (= 4 (count (md-cz res))))
(is (every? c-ref? (vals (md-cz res))))
(is (= #{:action :loc :bogus :bogus-e} (set (keys (md-cz res)))))
(is (every? #(= res (c-me %)) (vals (md-cz res))))
(is (= #{:action :loc :bogus :bogus-e}
(set (map #(c-slot %)
(vals (md-cz res))))))
(is (= "PI:NAME:<NAME>END_PI" (:name @res)))
(is (= "PI:NAME:<NAME>END_PI" (md-name res)))
(println :res @res)
(is (= 42 (:bogus @res)))
(is (= nil (:bogus-e @res))) ;; ephemeral, so reset to nil silently
(is (= nil (:action @res)))
(println :loc (:loc @res))
(is (= :missing (:loc @res)))
(is (= 1 @bct))
(reset! bct 0)
(md-reset! res :action :return)
(is (= :home (:loc @res)))
(is (zero? @bct))
))
(deftest hello-model
(let [uni (md/make
::md/family
:kids (cF (the-kids
(md/make
:name :visitor
:moniker "World"
:action (cI nil
:ephemeral? true
:obs (fn [slot me new old c]
(when new (trx visitor-did new)))))
(md/make
:name :resident
:action (cI nil :ephemeral? true)
:location (cF+ [:obs (fn-obs (when new (trx :honey-im new)))]
(case (md-get me :action)
:leave :away
:return :home
:missing))
:response (cF+ [:obs (fn-obs (when new
(trx :r-response new)))
:ephemeral? true]
(when (= :home (md-get me :location))
(when-let [act (mdv! :visitor :action)]
(case act
:knock-knock "hello, world")))))
(md/make
:name :alarm
:on-off (cF+ [:obs (fn-obs
(trx :telling-alarm-api new))]
(if (= :home (mdv! :resident :location)) :off :on))
:activity (cF+ [:obs (fn-obs
(case new
:call-police (trx :auto-dialing-911)
nil))]
(when (= :on (md-get me :on-off))
(when-let [action (mdv! :visitor :action)]
(case action
:smashing-window :call-police
nil))))))))]
(let [viz (fm! :visitor uni)
rez (fm! :resident uni)]
(is (not (nil? viz)))
(is (not (nil? rez)))
(is (not (nil? (md-cell rez :action))))
(is (= :missing (mdv! :resident :location uni)))
(md-reset! viz :action :knock-knock)
(md-reset! viz :action :smashing-window)
(is (not (nil? (md-cell rez :action))))
(md-reset! rez :action :return)
(is (= :home (mdv! :resident :location uni)))
(md-reset! viz :action :knock-knock))))
#?(:cljs (do
(cljs.test/run-tests)
))
|
[
{
"context": ":password@juxt.pro:8080\"\n \"userinfo\" \"jon:password\"\n \"host\" \"juxt.pro\"\n \"port\" \"8080",
"end": 781,
"score": 0.9421775341033936,
"start": 773,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "t\n (let [m (patterns/matched regex/addr-spec \"mal@juxt.pro\")]\n (are [group expected] (= expected (patt",
"end": 1015,
"score": 0.9997337460517883,
"start": 1003,
"tag": "EMAIL",
"value": "mal@juxt.pro"
},
{
"context": "(= y (patterns/parse \"addr-spec-test\" x))\n \"mal@juxt.pro\"\n [\"mal\" \"juxt.pro\"]))\n\n (deftest iri-tes",
"end": 1311,
"score": 0.9996122121810913,
"start": 1299,
"tag": "EMAIL",
"value": "mal@juxt.pro"
},
{
"context": "e/index.html?debug=true#bar\"\n [\"https\" \"jon:password\" \"juxt.pro\" \"8080\" \"/site/index.html\" \"debug=tru",
"end": 1519,
"score": 0.7384647727012634,
"start": 1511,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "?debug=true#bar\"\n [\"https\" \"jon:password\" \"juxt.pro\" \"8080\" \"/site/index.html\" \"debug=true\" \"bar\" ]\n",
"end": 1531,
"score": 0.6907459497451782,
"start": 1523,
"tag": "PASSWORD",
"value": "juxt.pro"
}
] | test/juxt/jinx/regex_test.cljc | The-Alchemist/jinx | 73 | ;; Copyright © 2019, JUXT LTD.
(ns juxt.jinx.regex-test
#?@(:clj [(:require
[juxt.jinx.alpha.regex :as regex]
[juxt.jinx.alpha.patterns :as patterns]
[clojure.test :refer [deftest is are testing]])]
:cljs [(:require
[juxt.jinx.alpha.regex :as regex]
[juxt.jinx.alpha.patterns :as patterns]
[cljs.test :refer-macros [deftest is are testing run-tests ]])]))
#?(:clj
(do
(deftest iri-test
(let [m (patterns/matched regex/IRI "https://jon:password@juxt.pro:8080/site/index.html?debug=true#bar")]
(are [group expected] (= expected (patterns/re-group-by-name m group))
"scheme" "https"
"authority" "jon:password@juxt.pro:8080"
"userinfo" "jon:password"
"host" "juxt.pro"
"port" "8080"
"path" "/site/index.html"
"query" "debug=true"
"fragment" "bar")))
(deftest addr-spec-test
(let [m (patterns/matched regex/addr-spec "mal@juxt.pro")]
(are [group expected] (= expected (patterns/re-group-by-name m group))
"localpart" "mal"
"domain" "juxt.pro"))))
;; TODO: ipv6 tests from rfc2234
:cljs
(do
(deftest addr-spec-test
(are [x y] (= y (patterns/parse "addr-spec-test" x))
"mal@juxt.pro"
["mal" "juxt.pro"]))
(deftest iri-test
(are [x y] (= y (patterns/parse "iri-test" x))
"https://jon:password@juxt.pro:8080/site/index.html?debug=true#bar"
["https" "jon:password" "juxt.pro" "8080" "/site/index.html" "debug=true" "bar" ]
"http://user:password@example.com:8080/path?query=value#fragment"
["http" "user:password" "example.com" "8080" "/path" "query=value" "fragment"]
"http://example.com"
["http" nil "example.com" nil "" nil nil]
))))
| 98751 | ;; Copyright © 2019, JUXT LTD.
(ns juxt.jinx.regex-test
#?@(:clj [(:require
[juxt.jinx.alpha.regex :as regex]
[juxt.jinx.alpha.patterns :as patterns]
[clojure.test :refer [deftest is are testing]])]
:cljs [(:require
[juxt.jinx.alpha.regex :as regex]
[juxt.jinx.alpha.patterns :as patterns]
[cljs.test :refer-macros [deftest is are testing run-tests ]])]))
#?(:clj
(do
(deftest iri-test
(let [m (patterns/matched regex/IRI "https://jon:password@juxt.pro:8080/site/index.html?debug=true#bar")]
(are [group expected] (= expected (patterns/re-group-by-name m group))
"scheme" "https"
"authority" "jon:password@juxt.pro:8080"
"userinfo" "jon:<PASSWORD>"
"host" "juxt.pro"
"port" "8080"
"path" "/site/index.html"
"query" "debug=true"
"fragment" "bar")))
(deftest addr-spec-test
(let [m (patterns/matched regex/addr-spec "<EMAIL>")]
(are [group expected] (= expected (patterns/re-group-by-name m group))
"localpart" "mal"
"domain" "juxt.pro"))))
;; TODO: ipv6 tests from rfc2234
:cljs
(do
(deftest addr-spec-test
(are [x y] (= y (patterns/parse "addr-spec-test" x))
"<EMAIL>"
["mal" "juxt.pro"]))
(deftest iri-test
(are [x y] (= y (patterns/parse "iri-test" x))
"https://jon:password@juxt.pro:8080/site/index.html?debug=true#bar"
["https" "jon:<PASSWORD>" "<PASSWORD>" "8080" "/site/index.html" "debug=true" "bar" ]
"http://user:password@example.com:8080/path?query=value#fragment"
["http" "user:password" "example.com" "8080" "/path" "query=value" "fragment"]
"http://example.com"
["http" nil "example.com" nil "" nil nil]
))))
| true | ;; Copyright © 2019, JUXT LTD.
(ns juxt.jinx.regex-test
#?@(:clj [(:require
[juxt.jinx.alpha.regex :as regex]
[juxt.jinx.alpha.patterns :as patterns]
[clojure.test :refer [deftest is are testing]])]
:cljs [(:require
[juxt.jinx.alpha.regex :as regex]
[juxt.jinx.alpha.patterns :as patterns]
[cljs.test :refer-macros [deftest is are testing run-tests ]])]))
#?(:clj
(do
(deftest iri-test
(let [m (patterns/matched regex/IRI "https://jon:password@juxt.pro:8080/site/index.html?debug=true#bar")]
(are [group expected] (= expected (patterns/re-group-by-name m group))
"scheme" "https"
"authority" "jon:password@juxt.pro:8080"
"userinfo" "jon:PI:PASSWORD:<PASSWORD>END_PI"
"host" "juxt.pro"
"port" "8080"
"path" "/site/index.html"
"query" "debug=true"
"fragment" "bar")))
(deftest addr-spec-test
(let [m (patterns/matched regex/addr-spec "PI:EMAIL:<EMAIL>END_PI")]
(are [group expected] (= expected (patterns/re-group-by-name m group))
"localpart" "mal"
"domain" "juxt.pro"))))
;; TODO: ipv6 tests from rfc2234
:cljs
(do
(deftest addr-spec-test
(are [x y] (= y (patterns/parse "addr-spec-test" x))
"PI:EMAIL:<EMAIL>END_PI"
["mal" "juxt.pro"]))
(deftest iri-test
(are [x y] (= y (patterns/parse "iri-test" x))
"https://jon:password@juxt.pro:8080/site/index.html?debug=true#bar"
["https" "jon:PI:PASSWORD:<PASSWORD>END_PI" "PI:PASSWORD:<PASSWORD>END_PI" "8080" "/site/index.html" "debug=true" "bar" ]
"http://user:password@example.com:8080/path?query=value#fragment"
["http" "user:password" "example.com" "8080" "/path" "query=value" "fragment"]
"http://example.com"
["http" nil "example.com" nil "" nil nil]
))))
|
[
{
"context": "asic auth\"\n \"JENKINS_PASSWORD Password for basic auth\"]))\n\n(defn parse-options [c-args]\n (let [args (p",
"end": 1035,
"score": 0.9985702037811279,
"start": 1012,
"tag": "PASSWORD",
"value": "Password for basic auth"
}
] | src/build_facts/jenkins.clj | cburgmer/build-facts | 5 | (ns build-facts.jenkins
(:require [build-facts.shared :as shared]
[build-facts.sync :as sync]
[build-facts.jenkins.builds :as builds]
[build-facts.util.url :as url]
[clojure.string :as string]
[clojure.tools.cli :refer [parse-opts]]))
(defn jenkins-usage [options-summary]
(string/join "\n"
["Syncs Jenkins build history"
""
"Usage: build-facts.main [OPTIONS] jenkins JENKINS_URL"
""
"Options:"
options-summary
""
"Action arguments:"
""
"JENKINS_URL The URL of the Jenkins installation. Provide the URL of"
" a view to limit the sync to respective jobs."
""
"Environment variables:"
""
"JENKINS_USER Username for basic auth"
"JENKINS_PASSWORD Password for basic auth"]))
(defn parse-options [c-args]
(let [args (parse-opts c-args shared/cli-options)]
(when (:help (:options args))
(println (jenkins-usage (:summary args)))
(System/exit 0))
(when (:errors args)
(println (string/join "\n" (:errors args)))
(System/exit 1))
(let [base-url (first (:arguments args))]
(shared/assert-parameter #(some? base-url) "The URL for Jenkins is required. Try --help.")
(merge (:options args)
{:base-url (url/url base-url)}))))
(defn run [options]
(let [jenkins-options (merge options
(parse-options (:action-args options)))]
(sync/sync-builds jenkins-options
#(builds/jenkins-builds jenkins-options))))
| 121797 | (ns build-facts.jenkins
(:require [build-facts.shared :as shared]
[build-facts.sync :as sync]
[build-facts.jenkins.builds :as builds]
[build-facts.util.url :as url]
[clojure.string :as string]
[clojure.tools.cli :refer [parse-opts]]))
(defn jenkins-usage [options-summary]
(string/join "\n"
["Syncs Jenkins build history"
""
"Usage: build-facts.main [OPTIONS] jenkins JENKINS_URL"
""
"Options:"
options-summary
""
"Action arguments:"
""
"JENKINS_URL The URL of the Jenkins installation. Provide the URL of"
" a view to limit the sync to respective jobs."
""
"Environment variables:"
""
"JENKINS_USER Username for basic auth"
"JENKINS_PASSWORD <PASSWORD>"]))
(defn parse-options [c-args]
(let [args (parse-opts c-args shared/cli-options)]
(when (:help (:options args))
(println (jenkins-usage (:summary args)))
(System/exit 0))
(when (:errors args)
(println (string/join "\n" (:errors args)))
(System/exit 1))
(let [base-url (first (:arguments args))]
(shared/assert-parameter #(some? base-url) "The URL for Jenkins is required. Try --help.")
(merge (:options args)
{:base-url (url/url base-url)}))))
(defn run [options]
(let [jenkins-options (merge options
(parse-options (:action-args options)))]
(sync/sync-builds jenkins-options
#(builds/jenkins-builds jenkins-options))))
| true | (ns build-facts.jenkins
(:require [build-facts.shared :as shared]
[build-facts.sync :as sync]
[build-facts.jenkins.builds :as builds]
[build-facts.util.url :as url]
[clojure.string :as string]
[clojure.tools.cli :refer [parse-opts]]))
(defn jenkins-usage [options-summary]
(string/join "\n"
["Syncs Jenkins build history"
""
"Usage: build-facts.main [OPTIONS] jenkins JENKINS_URL"
""
"Options:"
options-summary
""
"Action arguments:"
""
"JENKINS_URL The URL of the Jenkins installation. Provide the URL of"
" a view to limit the sync to respective jobs."
""
"Environment variables:"
""
"JENKINS_USER Username for basic auth"
"JENKINS_PASSWORD PI:PASSWORD:<PASSWORD>END_PI"]))
(defn parse-options [c-args]
(let [args (parse-opts c-args shared/cli-options)]
(when (:help (:options args))
(println (jenkins-usage (:summary args)))
(System/exit 0))
(when (:errors args)
(println (string/join "\n" (:errors args)))
(System/exit 1))
(let [base-url (first (:arguments args))]
(shared/assert-parameter #(some? base-url) "The URL for Jenkins is required. Try --help.")
(merge (:options args)
{:base-url (url/url base-url)}))))
(defn run [options]
(let [jenkins-options (merge options
(parse-options (:action-args options)))]
(sync/sync-builds jenkins-options
#(builds/jenkins-builds jenkins-options))))
|
[
{
"context": "(ns repliclj.utils\n ^{:author \"Thomas Bock <wactbprot@gmail.com>\"\n :doc \"Simple replicati",
"end": 43,
"score": 0.9998579025268555,
"start": 32,
"tag": "NAME",
"value": "Thomas Bock"
},
{
"context": "(ns repliclj.utils\n ^{:author \"Thomas Bock <wactbprot@gmail.com>\"\n :doc \"Simple replication state overview pag",
"end": 64,
"score": 0.9999312162399292,
"start": 45,
"tag": "EMAIL",
"value": "wactbprot@gmail.com"
}
] | src/repliclj/utils.clj | wactbprot/repliclj | 0 | (ns repliclj.utils
^{:author "Thomas Bock <wactbprot@gmail.com>"
:doc "Simple replication state overview page delivered by server.clj."}
(:require [clojure.string :as string]))
(defn date [] (.format (new java.text.SimpleDateFormat "yyyy-MM-dd HH:mm") (java.util.Date.)))
(defn url
"Return a vector containing the url parts.
```clojure
[http://admin:*****@e75467.berlin.ptb.de:5984/vl_db
http
admin
*****
e75467
berlin.ptb.de
5984
vl_db]
```"
[s]
(let [r #"^(http[s]?)\://(\w*\:?[\*]*@?)?([a-z0-9]*\.?[\w\.]*):([0-9]*)\/([\w\_]*)"
v (filterv seq (re-find r s))
n (count v)]
{:db (get v (- n 1))
:port (get v (- n 2))
:host (get v (- n 3))
:prot (get v 1)}))
(defn url->db [s] (:db (url s)))
(defn url->host [s] (:host (url s)))
(defn url->prot [s] (:prot (url s)))
(defn url->port [s] (:port (url s)))
(defn host->host-name [s] (first (string/split s #"\.")))
(defn url->host-name [s] (host->host-name (:host (url s))))
(defn nice-date [s] (string/replace s #"[TZ]" " "))
(defn gen-repli-id [{ad :db as :server} {bd :db bs :server}]
(str ad "@" (host->host-name as) "--" bd "@" (host->host-name bs)))
(defn repli-doc-link [m]
(str (url->prot (:source m)) "://"
(url->host (:source m)) ":"
(url->port (:source m)) "/_utils/#database/" (:database m)"/" (:doc_id m)))
(defn id->target-host-name [s]
(let [v (string/split s #"@")]
(when (and (string/includes? s "--") (= 3 (count v))) (last v))))
| 110685 | (ns repliclj.utils
^{:author "<NAME> <<EMAIL>>"
:doc "Simple replication state overview page delivered by server.clj."}
(:require [clojure.string :as string]))
(defn date [] (.format (new java.text.SimpleDateFormat "yyyy-MM-dd HH:mm") (java.util.Date.)))
(defn url
"Return a vector containing the url parts.
```clojure
[http://admin:*****@e75467.berlin.ptb.de:5984/vl_db
http
admin
*****
e75467
berlin.ptb.de
5984
vl_db]
```"
[s]
(let [r #"^(http[s]?)\://(\w*\:?[\*]*@?)?([a-z0-9]*\.?[\w\.]*):([0-9]*)\/([\w\_]*)"
v (filterv seq (re-find r s))
n (count v)]
{:db (get v (- n 1))
:port (get v (- n 2))
:host (get v (- n 3))
:prot (get v 1)}))
(defn url->db [s] (:db (url s)))
(defn url->host [s] (:host (url s)))
(defn url->prot [s] (:prot (url s)))
(defn url->port [s] (:port (url s)))
(defn host->host-name [s] (first (string/split s #"\.")))
(defn url->host-name [s] (host->host-name (:host (url s))))
(defn nice-date [s] (string/replace s #"[TZ]" " "))
(defn gen-repli-id [{ad :db as :server} {bd :db bs :server}]
(str ad "@" (host->host-name as) "--" bd "@" (host->host-name bs)))
(defn repli-doc-link [m]
(str (url->prot (:source m)) "://"
(url->host (:source m)) ":"
(url->port (:source m)) "/_utils/#database/" (:database m)"/" (:doc_id m)))
(defn id->target-host-name [s]
(let [v (string/split s #"@")]
(when (and (string/includes? s "--") (= 3 (count v))) (last v))))
| true | (ns repliclj.utils
^{:author "PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>"
:doc "Simple replication state overview page delivered by server.clj."}
(:require [clojure.string :as string]))
(defn date [] (.format (new java.text.SimpleDateFormat "yyyy-MM-dd HH:mm") (java.util.Date.)))
(defn url
"Return a vector containing the url parts.
```clojure
[http://admin:*****@e75467.berlin.ptb.de:5984/vl_db
http
admin
*****
e75467
berlin.ptb.de
5984
vl_db]
```"
[s]
(let [r #"^(http[s]?)\://(\w*\:?[\*]*@?)?([a-z0-9]*\.?[\w\.]*):([0-9]*)\/([\w\_]*)"
v (filterv seq (re-find r s))
n (count v)]
{:db (get v (- n 1))
:port (get v (- n 2))
:host (get v (- n 3))
:prot (get v 1)}))
(defn url->db [s] (:db (url s)))
(defn url->host [s] (:host (url s)))
(defn url->prot [s] (:prot (url s)))
(defn url->port [s] (:port (url s)))
(defn host->host-name [s] (first (string/split s #"\.")))
(defn url->host-name [s] (host->host-name (:host (url s))))
(defn nice-date [s] (string/replace s #"[TZ]" " "))
(defn gen-repli-id [{ad :db as :server} {bd :db bs :server}]
(str ad "@" (host->host-name as) "--" bd "@" (host->host-name bs)))
(defn repli-doc-link [m]
(str (url->prot (:source m)) "://"
(url->host (:source m)) ":"
(url->port (:source m)) "/_utils/#database/" (:database m)"/" (:doc_id m)))
(defn id->target-host-name [s]
(let [v (string/split s #"@")]
(when (and (string/includes? s "--") (= 3 (count v))) (last v))))
|
[
{
"context": ";;\n;; Copyright © 2020 Sam Ritchie.\n;; This work is based on the Scmutils system of ",
"end": 34,
"score": 0.9998037219047546,
"start": 23,
"tag": "NAME",
"value": "Sam Ritchie"
}
] | test/numerical/quadrature/substitute_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.substitute-test
(:require [clojure.test :refer [is deftest testing]]
[same :refer [ish? with-comparator]
#?@(:cljs [:include-macros true])]
[sicmutils.numerical.quadrature.simpson :as simp]
[sicmutils.numerical.quadrature.romberg :as qr]
[sicmutils.numerical.quadrature.substitute :as qs]
[sicmutils.value :as v]))
(deftest infinitize-tests
(testing "1 => inf calculation of 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
:terms-checked 7
:result 0.2193839343960799}
((qs/infinitize qr/open-integral) f 1 ##Inf))
"This is a piece of the proper calculation of Euler's constant.")
(with-comparator (v/within 1e-8)
(is (ish? (:result ((qs/infinitize qr/open-integral) f 1 10))
(:result (qr/open-integral f 1 10)))
"This is a piece of the proper calculation of Euler's constant.")))))
(deftest power-law-tests
(let [f (fn [x] (Math/sin x))
[a b] [0 10]]
(testing "Substitution methods shouldn't change results."
(let [expected {:converged? true
:terms-checked 9
:result 1.8390715305632985}]
(is (ish? expected (simp/integral f a b))
"Baseline Simpson's rule test, with no variable substitution.")
(with-comparator (v/within 1e-8)
(is (ish? (:result expected)
(:result
((qs/inverse-power-law-lower simp/integral 0.8) f a b))
(:result
((qs/inverse-power-law-lower simp/integral 0.2) f a b)))
"lower inverse power law singularities with different gamma values
~equal the original, untransformed result."))
(with-comparator (v/within 1e-7)
(is (ish? (:result expected)
(:result
((qs/inverse-power-law-upper simp/integral 0.8) f a b)))
"UPPER inverse power law singularities with different gamma values ~equal
the original, untransformed result."))))
(testing "inverse-sqrt is a general inverse power law with gamma=0.5"
(is (ish? ((qs/inverse-sqrt-lower simp/integral) f a b)
((qs/inverse-power-law-lower simp/integral 0.5) f a b))
"lower inverse sqrt")
(is (ish? ((qs/inverse-sqrt-upper simp/integral) f a b)
((qs/inverse-power-law-upper simp/integral 0.5) f a b))
"upper inverse sqrt"))))
(deftest exponential-tests
(testing "Exponentially decaying upper endpoint"
(let [f (fn [x] (Math/exp (- x)))]
(is (ish? {:converged? true
:terms-checked 5
:result 0.6321205588285578}
((qs/exponential-upper qr/open-integral) f 0 ##Inf))
"Calculation converges."))))
| 31798 | ;;
;; 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.substitute-test
(:require [clojure.test :refer [is deftest testing]]
[same :refer [ish? with-comparator]
#?@(:cljs [:include-macros true])]
[sicmutils.numerical.quadrature.simpson :as simp]
[sicmutils.numerical.quadrature.romberg :as qr]
[sicmutils.numerical.quadrature.substitute :as qs]
[sicmutils.value :as v]))
(deftest infinitize-tests
(testing "1 => inf calculation of 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
:terms-checked 7
:result 0.2193839343960799}
((qs/infinitize qr/open-integral) f 1 ##Inf))
"This is a piece of the proper calculation of Euler's constant.")
(with-comparator (v/within 1e-8)
(is (ish? (:result ((qs/infinitize qr/open-integral) f 1 10))
(:result (qr/open-integral f 1 10)))
"This is a piece of the proper calculation of Euler's constant.")))))
(deftest power-law-tests
(let [f (fn [x] (Math/sin x))
[a b] [0 10]]
(testing "Substitution methods shouldn't change results."
(let [expected {:converged? true
:terms-checked 9
:result 1.8390715305632985}]
(is (ish? expected (simp/integral f a b))
"Baseline Simpson's rule test, with no variable substitution.")
(with-comparator (v/within 1e-8)
(is (ish? (:result expected)
(:result
((qs/inverse-power-law-lower simp/integral 0.8) f a b))
(:result
((qs/inverse-power-law-lower simp/integral 0.2) f a b)))
"lower inverse power law singularities with different gamma values
~equal the original, untransformed result."))
(with-comparator (v/within 1e-7)
(is (ish? (:result expected)
(:result
((qs/inverse-power-law-upper simp/integral 0.8) f a b)))
"UPPER inverse power law singularities with different gamma values ~equal
the original, untransformed result."))))
(testing "inverse-sqrt is a general inverse power law with gamma=0.5"
(is (ish? ((qs/inverse-sqrt-lower simp/integral) f a b)
((qs/inverse-power-law-lower simp/integral 0.5) f a b))
"lower inverse sqrt")
(is (ish? ((qs/inverse-sqrt-upper simp/integral) f a b)
((qs/inverse-power-law-upper simp/integral 0.5) f a b))
"upper inverse sqrt"))))
(deftest exponential-tests
(testing "Exponentially decaying upper endpoint"
(let [f (fn [x] (Math/exp (- x)))]
(is (ish? {:converged? true
:terms-checked 5
:result 0.6321205588285578}
((qs/exponential-upper qr/open-integral) f 0 ##Inf))
"Calculation converges."))))
| 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.substitute-test
(:require [clojure.test :refer [is deftest testing]]
[same :refer [ish? with-comparator]
#?@(:cljs [:include-macros true])]
[sicmutils.numerical.quadrature.simpson :as simp]
[sicmutils.numerical.quadrature.romberg :as qr]
[sicmutils.numerical.quadrature.substitute :as qs]
[sicmutils.value :as v]))
(deftest infinitize-tests
(testing "1 => inf calculation of 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
:terms-checked 7
:result 0.2193839343960799}
((qs/infinitize qr/open-integral) f 1 ##Inf))
"This is a piece of the proper calculation of Euler's constant.")
(with-comparator (v/within 1e-8)
(is (ish? (:result ((qs/infinitize qr/open-integral) f 1 10))
(:result (qr/open-integral f 1 10)))
"This is a piece of the proper calculation of Euler's constant.")))))
(deftest power-law-tests
(let [f (fn [x] (Math/sin x))
[a b] [0 10]]
(testing "Substitution methods shouldn't change results."
(let [expected {:converged? true
:terms-checked 9
:result 1.8390715305632985}]
(is (ish? expected (simp/integral f a b))
"Baseline Simpson's rule test, with no variable substitution.")
(with-comparator (v/within 1e-8)
(is (ish? (:result expected)
(:result
((qs/inverse-power-law-lower simp/integral 0.8) f a b))
(:result
((qs/inverse-power-law-lower simp/integral 0.2) f a b)))
"lower inverse power law singularities with different gamma values
~equal the original, untransformed result."))
(with-comparator (v/within 1e-7)
(is (ish? (:result expected)
(:result
((qs/inverse-power-law-upper simp/integral 0.8) f a b)))
"UPPER inverse power law singularities with different gamma values ~equal
the original, untransformed result."))))
(testing "inverse-sqrt is a general inverse power law with gamma=0.5"
(is (ish? ((qs/inverse-sqrt-lower simp/integral) f a b)
((qs/inverse-power-law-lower simp/integral 0.5) f a b))
"lower inverse sqrt")
(is (ish? ((qs/inverse-sqrt-upper simp/integral) f a b)
((qs/inverse-power-law-upper simp/integral 0.5) f a b))
"upper inverse sqrt"))))
(deftest exponential-tests
(testing "Exponentially decaying upper endpoint"
(let [f (fn [x] (Math/exp (- x)))]
(is (ish? {:converged? true
:terms-checked 5
:result 0.6321205588285578}
((qs/exponential-upper qr/open-integral) f 0 ##Inf))
"Calculation converges."))))
|
[
{
"context": ";; The MIT License (MIT)\n;;\n;; Copyright (c) 2016 Richard Hull\n;;\n;; Permission is hereby granted, free of charg",
"end": 62,
"score": 0.9997870922088623,
"start": 50,
"tag": "NAME",
"value": "Richard Hull"
}
] | test/base58/core_test.clj | rm-hull/base58 | 1 | ;; The MIT License (MIT)
;;
;; Copyright (c) 2016 Richard Hull
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in all
;; copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(ns base58.core-test
(:require
[clojure.test :refer :all]
[base58.core :refer :all]))
(deftest check-leading-zeros
(is (= 0 (count-leading zero? nil)))
(is (= 0 (count-leading zero? "hello world")))
(is (= 0 (count-leading zero? "hello\000world")))
(is (= 3 (count-leading zero? "\000\000\000hello world"))))
(deftest check-string->bigint
(is (= 0 (string->bigint 256 byte nil)))
(is (= 0 (string->bigint 256 byte "")))
(is (= 104M (string->bigint 256 byte "h")))
(is (= (+ 101M (* 256 104)) (string->bigint 256 byte "he"))))
(deftest check-encoding
(is (= "" (encode nil)))
(is (= "" (encode "")))
(is (= "StV1DL6CwTryKyV" (encode "hello world")))
(is (= "11StV1DL6CwTryKyV" (encode "\000\000hello world"))))
(deftest check-decoding
(is (= "" (decode nil)))
(is (= "" (decode "")))
(is (= "hello world" (decode "StV1DL6CwTryKyV")))
(is (= "\000\000hello world" (decode "11StV1DL6CwTryKyV"))))
| 95829 | ;; The MIT License (MIT)
;;
;; Copyright (c) 2016 <NAME>
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in all
;; copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(ns base58.core-test
(:require
[clojure.test :refer :all]
[base58.core :refer :all]))
(deftest check-leading-zeros
(is (= 0 (count-leading zero? nil)))
(is (= 0 (count-leading zero? "hello world")))
(is (= 0 (count-leading zero? "hello\000world")))
(is (= 3 (count-leading zero? "\000\000\000hello world"))))
(deftest check-string->bigint
(is (= 0 (string->bigint 256 byte nil)))
(is (= 0 (string->bigint 256 byte "")))
(is (= 104M (string->bigint 256 byte "h")))
(is (= (+ 101M (* 256 104)) (string->bigint 256 byte "he"))))
(deftest check-encoding
(is (= "" (encode nil)))
(is (= "" (encode "")))
(is (= "StV1DL6CwTryKyV" (encode "hello world")))
(is (= "11StV1DL6CwTryKyV" (encode "\000\000hello world"))))
(deftest check-decoding
(is (= "" (decode nil)))
(is (= "" (decode "")))
(is (= "hello world" (decode "StV1DL6CwTryKyV")))
(is (= "\000\000hello world" (decode "11StV1DL6CwTryKyV"))))
| true | ;; The MIT License (MIT)
;;
;; Copyright (c) 2016 PI:NAME:<NAME>END_PI
;;
;; Permission is hereby granted, free of charge, to any person obtaining a copy
;; of this software and associated documentation files (the "Software"), to deal
;; in the Software without restriction, including without limitation the rights
;; to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
;; copies of the Software, and to permit persons to whom the Software is
;; furnished to do so, subject to the following conditions:
;;
;; The above copyright notice and this permission notice shall be included in all
;; copies or substantial portions of the Software.
;;
;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
;; IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
;; FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
;; AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
;; LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
;; SOFTWARE.
(ns base58.core-test
(:require
[clojure.test :refer :all]
[base58.core :refer :all]))
(deftest check-leading-zeros
(is (= 0 (count-leading zero? nil)))
(is (= 0 (count-leading zero? "hello world")))
(is (= 0 (count-leading zero? "hello\000world")))
(is (= 3 (count-leading zero? "\000\000\000hello world"))))
(deftest check-string->bigint
(is (= 0 (string->bigint 256 byte nil)))
(is (= 0 (string->bigint 256 byte "")))
(is (= 104M (string->bigint 256 byte "h")))
(is (= (+ 101M (* 256 104)) (string->bigint 256 byte "he"))))
(deftest check-encoding
(is (= "" (encode nil)))
(is (= "" (encode "")))
(is (= "StV1DL6CwTryKyV" (encode "hello world")))
(is (= "11StV1DL6CwTryKyV" (encode "\000\000hello world"))))
(deftest check-decoding
(is (= "" (decode nil)))
(is (= "" (decode "")))
(is (= "hello world" (decode "StV1DL6CwTryKyV")))
(is (= "\000\000hello world" (decode "11StV1DL6CwTryKyV"))))
|
[
{
"context": " host\n :database database\n :username username\n :password password})\n (when ssl\n ",
"end": 1193,
"score": 0.9987278580665588,
"start": 1185,
"tag": "USERNAME",
"value": "username"
},
{
"context": "abase\n :username username\n :password password})\n (when ssl\n {:ssl ssl})\n (when re",
"end": 1220,
"score": 0.9978923201560974,
"start": 1212,
"tag": "PASSWORD",
"value": "password"
}
] | src/macchiato/migrations/core.cljs | arichiardi/macchiato-migrations | 0 | (ns macchiato.migrations.core
(:require [cljs.nodejs :as node]
[macchiato.fs.path :as path]
[taoensso.timbre :as timbre
:refer-macros [info error]]
["postgrator" :as Postgrator]))
(defn- translate-config [{:keys [migration-dir
schema-table
driver
host
port
database
username
password
connection-string
request-timeout
options
ssl]
:or {migration-dir (str js/__dirname path/separator "migrations")
schema-table "schema_migrations"}}]
(clj->js
(merge
{:migrationDirectory migration-dir
:schemaTable schema-table
:driver driver}
(if connection-string
{:connectionString connection-string}
{:host host
:database database
:username username
:password password})
(when ssl
{:ssl ssl})
(when request-timeout
{:requestTimeout request-timeout})
(when options
{:options (clj->js options)}))))
(defn- error-handler [e]
(error e "An error occured while running migrations!")
(error (js->clj (.-appliedMigrations e))))
(defn- info-handler [message]
(fn [i]
(info message (dissoc (js->clj i) "getSql"))))
(defn migrate
([config] (migrate config :max nil error-handler))
([config version] (migrate config version nil error-handler))
([config version cb] (migrate config version cb error-handler))
([config version cb err-cb]
(let [postgrator (Postgrator. (translate-config config))]
(.on postgrator "migration-started" (info-handler "starting migration:"))
(.on postgrator "migration-finished" (info-handler "ending migration:"))
(-> (if (= :max version)
(.migrate postgrator)
(.migrate postgrator version))
(.then (or #(cb (js->clj %)) (info-handler "applied migrations:")))
(.catch err-cb)))))
| 93172 | (ns macchiato.migrations.core
(:require [cljs.nodejs :as node]
[macchiato.fs.path :as path]
[taoensso.timbre :as timbre
:refer-macros [info error]]
["postgrator" :as Postgrator]))
(defn- translate-config [{:keys [migration-dir
schema-table
driver
host
port
database
username
password
connection-string
request-timeout
options
ssl]
:or {migration-dir (str js/__dirname path/separator "migrations")
schema-table "schema_migrations"}}]
(clj->js
(merge
{:migrationDirectory migration-dir
:schemaTable schema-table
:driver driver}
(if connection-string
{:connectionString connection-string}
{:host host
:database database
:username username
:password <PASSWORD>})
(when ssl
{:ssl ssl})
(when request-timeout
{:requestTimeout request-timeout})
(when options
{:options (clj->js options)}))))
(defn- error-handler [e]
(error e "An error occured while running migrations!")
(error (js->clj (.-appliedMigrations e))))
(defn- info-handler [message]
(fn [i]
(info message (dissoc (js->clj i) "getSql"))))
(defn migrate
([config] (migrate config :max nil error-handler))
([config version] (migrate config version nil error-handler))
([config version cb] (migrate config version cb error-handler))
([config version cb err-cb]
(let [postgrator (Postgrator. (translate-config config))]
(.on postgrator "migration-started" (info-handler "starting migration:"))
(.on postgrator "migration-finished" (info-handler "ending migration:"))
(-> (if (= :max version)
(.migrate postgrator)
(.migrate postgrator version))
(.then (or #(cb (js->clj %)) (info-handler "applied migrations:")))
(.catch err-cb)))))
| true | (ns macchiato.migrations.core
(:require [cljs.nodejs :as node]
[macchiato.fs.path :as path]
[taoensso.timbre :as timbre
:refer-macros [info error]]
["postgrator" :as Postgrator]))
(defn- translate-config [{:keys [migration-dir
schema-table
driver
host
port
database
username
password
connection-string
request-timeout
options
ssl]
:or {migration-dir (str js/__dirname path/separator "migrations")
schema-table "schema_migrations"}}]
(clj->js
(merge
{:migrationDirectory migration-dir
:schemaTable schema-table
:driver driver}
(if connection-string
{:connectionString connection-string}
{:host host
:database database
:username username
:password PI:PASSWORD:<PASSWORD>END_PI})
(when ssl
{:ssl ssl})
(when request-timeout
{:requestTimeout request-timeout})
(when options
{:options (clj->js options)}))))
(defn- error-handler [e]
(error e "An error occured while running migrations!")
(error (js->clj (.-appliedMigrations e))))
(defn- info-handler [message]
(fn [i]
(info message (dissoc (js->clj i) "getSql"))))
(defn migrate
([config] (migrate config :max nil error-handler))
([config version] (migrate config version nil error-handler))
([config version cb] (migrate config version cb error-handler))
([config version cb err-cb]
(let [postgrator (Postgrator. (translate-config config))]
(.on postgrator "migration-started" (info-handler "starting migration:"))
(.on postgrator "migration-finished" (info-handler "ending migration:"))
(-> (if (= :max version)
(.migrate postgrator)
(.migrate postgrator version))
(.then (or #(cb (js->clj %)) (info-handler "applied migrations:")))
(.catch err-cb)))))
|
[
{
"context": "ost\n :port port\n :user user\n :password password}))\n\n(defn joplin-spec []\n {:db {:type :sql\n ",
"end": 1113,
"score": 0.9985356330871582,
"start": 1105,
"tag": "PASSWORD",
"value": "password"
}
] | src/vip/data_processor/db/postgres.clj | votinginfoproject/data-processor | 10 | (ns vip.data-processor.db.postgres
(:require [clojure.tools.logging :as log]
[clojure.string :as str]
[joplin.core :as j]
[joplin.jdbc.database]
[clojure.java.jdbc :as jdbc]
[korma.db :as db]
[korma.core :as korma]
[turbovote.resource-config :refer [config]]
[vip.data-processor.db.util :as db.util]
[vip.data-processor.util :as util]
[vip.data-processor.validation.data-spec :as data-spec])
(:import [org.postgresql.util PGobject]
[java.net URLEncoder]
[java.text Normalizer]))
(defn url []
(let [{:keys [host port user password database]} (config [:postgres])]
(apply format
"jdbc:postgresql://%s:%s/%s?user=%s&password=%s"
(map (comp #(URLEncoder/encode % "UTF-8") str)
[host port database user password]))))
(defn db-spec []
(let [{:keys [host port user password database]} (config [:postgres])]
{:dbtype "postgresql"
:dbname database
:host host
:port port
:user user
:password password}))
(defn joplin-spec []
{:db {:type :sql
:url (url)}
:migrator "resources/migrations"})
(defn migrate
"Migrate forward any pending migrations."
[]
(j/migrate-db (joplin-spec)))
(defn pending
"List any migrations that haven't been applied yet."
[]
(j/pending-migrations (joplin-spec)))
(defn rollback
"With no parameters, rolls the db back 1 migrations. You can also send a
parameter that is either an integer or the id of a migration. When it's
and integer it rolls back that many migrations. When it's a string, it
should be the id of a migration and it rolls back any migrations up to
but not including that migration."
([]
(j/rollback-db (joplin-spec) 1))
([num-or-id]
(letfn [(parse-int [n-or-i]
(try
(Integer/parseInt n-or-i)
(catch Exception e
nil)))]
(if-let [num (parse-int num-or-id)]
;; we got a int, use it
(j/rollback-db (joplin-spec) num)
;; assume it was a String id
(j/rollback-db (joplin-spec) num-or-id)))))
(defn create
"Creates a new migration up/down with the id suffix. Joplin automatically
prepends the date in YYYYMMDD- format before this provided id, so if you
intend to write multiple migrations on the same day that need to be applied
in a particular order, it's ideal to start your id with 01-, 02-, 03-, etc"
[id]
(j/create-migration (joplin-spec) id))
(declare results-db results
validations
v3-0-import-entities
statistics)
(defn initialize []
(log/info "Initializing Postgres")
(migrate)
(let [opts (-> [:postgres]
config
(assoc :db (config [:postgres :database])))]
(db/defdb results-db (db/postgres opts)))
(korma/defentity results
(korma/database results-db))
(korma/defentity validations
(korma/database results-db))
(korma/defentity statistics
(korma/database results-db))
(korma/defentity election_approvals
(korma/database results-db))
(korma/defentity xml-tree-values
(korma/table "xml_tree_values")
(korma/database results-db))
(korma/defentity xml-tree-validations
(korma/table "xml_tree_validations")
(korma/database results-db))
(korma/defentity v5-statistics
(korma/table "v5_statistics")
(korma/database results-db))
(korma/defentity v5-dashboard-localities
(korma/table "v5_dashboard.localities")
(korma/database results-db))
(korma/defentity v5-2-street-segments
(korma/table "v5_2_street_segments"))
(korma/defentity v5-dashboard-paths-by-locality
(korma/table "v5_dashboard.paths_by_locality"))
(def v5-2-tables
(db.util/make-entities "5.2" results-db [:ballot-measure-contests
:ballot-measure-selections
:ballot-selections
:ballot-styles
:candidates
:candidate-contests
:candidate-selections
:contact-information
:contests
:departments
:elections
:election-administrations
:electoral-districts
:localities
:offices
:ordered-contests
:parties
:party-contests
:party-selections
:people
:polling-locations
:precincts
:retention-contests
:schedules
:sources
:states
:street-segments
:voter-services]))
(def v3-0-import-entities
(db.util/make-entities "3.0" results-db db.util/import-entity-names)))
(defn path->ltree [path]
(doto (PGobject.)
(.setType "ltree")
(.setValue path)))
(defn ltree-match
"Helper function for generating WHERE clases using ~. Accepts a keyword as a
table alias, or a korma entity"
[table column path]
(let [tablename (if (keyword? table)
(name table)
(korma.sql.engine/table-alias table))]
(korma/raw (str tablename
"." (name column)
" ~ '" path "'"))))
(defn find-value-for-simple-path [import-id simple-path]
(-> (korma/select xml-tree-values
(korma/fields :value)
(korma/where {:results_id import-id
:simple_path (path->ltree simple-path)}))
first
:value))
(defn find-single-xml-tree-value [results-id path]
(-> (korma/select xml-tree-values
(korma/fields :value)
(korma/where {:results_id results-id})
(korma/where (ltree-match xml-tree-values
:path
path)))
first
:value))
(defn start-run [ctx]
(let [results (korma/insert results
(korma/values {:start_time (korma/sqlfn now)
:complete false}))
import-id (:id results)]
(log/info "Starting run with import_id:" import-id)
(assoc ctx :import-id import-id)))
(defn build-public-id [date election-type state import-id]
(let [nil-or-empty? (some-fn nil? empty?)
formatted-date (util/format-date date)
good-parts (->> [formatted-date election-type state]
(remove nil-or-empty?)
(map #(str/trim %))
(map #(Normalizer/normalize % java.text.Normalizer$Form/NFKD))
(map #(str/replace % #"\p{Space}" "-"))
(map #(str/replace % #"[\p{Punct}\P{ASCII}&&[^-]]" "")))]
(if (empty? good-parts)
(str "invalid-" import-id)
(str/join "-" (concat good-parts [import-id])))))
(defn build-election-id [date election-type state]
(let [components [date election-type state]]
(when (every? seq components)
(->> components
(map str/trim)
(str/join "-")))))
(defn get-v3-public-id-data [{:keys [import-id] :as ctx}]
(let [state (-> ctx
(get-in [:tables :states])
(korma/select (korma/fields :name))
first
:name)
{:keys [date election_type]} (-> ctx
(get-in [:tables :elections])
(korma/select (korma/fields :date :election_type))
first)
vip-id (-> ctx
(get-in [:tables :sources])
(korma/select (korma/fields :vip_id))
first
:vip_id)]
{:date date
:election-type election_type
:state state
:vip-id vip-id
:import-id import-id}))
(defn get-xml-tree-public-id-data [{:keys [import-id] :as ctx}]
(let [state (find-value-for-simple-path
import-id
"VipObject.State.Name")
date (find-value-for-simple-path
import-id
"VipObject.Election.Date")
election-type (find-value-for-simple-path
import-id
"VipObject.Election.ElectionType.Text")
vip-id (find-value-for-simple-path
import-id
"VipObject.Source.VipId")]
{:date date
:election-type election-type
:state state
:import-id import-id
:vip-id vip-id}))
(defn get-public-id-data [{:keys [spec-family] :as ctx}]
(condp = spec-family
"3.0" (get-v3-public-id-data ctx)
"5.2" (get-xml-tree-public-id-data ctx)
{}))
(defn generate-public-id [ctx]
(let [{:keys [date election-type state import-id]} (get-public-id-data ctx)]
(log/info "Building public id")
(build-public-id date election-type state import-id)))
(defn generate-election-id [ctx]
(log/info "Building election id")
(let [{:keys [date election-type state]} (get-public-id-data ctx)]
(build-election-id date election-type state)))
(defn store-public-id [ctx]
(let [id (:import-id ctx)
public-id (generate-public-id ctx)
public-id-data (get-public-id-data ctx)]
(log/info "Storing public id")
(korma/update results
(korma/set-fields {:public_id public-id
:state (:state public-id-data)
:election_type (:election-type public-id-data)
:election_date (:date public-id-data)
:vip_id (:vip-id public-id-data)})
(korma/where {:id id}))
(assoc ctx :public-id public-id)))
(defn save-election-id! [election-id]
(binding [db/*current-conn* (db/get-connection (:db election_approvals))]
(db/transaction
(when-not (seq (korma/select election_approvals
(korma/where {:election_id election-id})))
(korma/insert election_approvals
(korma/values {:election_id election-id}))))))
(defn store-election-id [ctx]
(if-let [election-id (generate-election-id ctx)]
(let [id (:import-id ctx)]
(log/info "Storing election id")
(save-election-id! election-id)
(korma/update results
(korma/set-fields {:election_id election-id})
(korma/where {:id id}))
(assoc ctx :election-id election-id))
ctx))
(defn store-spec-version [{:keys [spec-version import-id] :as ctx}]
(when spec-version
(log/info "Storing spec-verion," spec-version)
(korma/update results
(korma/set-fields {:spec_version spec-version})
(korma/where {:id import-id})))
ctx)
(defn analyze-xtv [ctx]
(log/info "Analyzing xml_tree_values")
(korma/exec-raw
(:conn xml-tree-values)
["analyze xml_tree_values"])
ctx)
(defn populate-locality-table
[ctx]
(let [id (:import-id ctx)]
(log/info "Populating v5_dashboard.paths_by_locality")
(korma/exec-raw
(:conn xml-tree-values)
["select v5_dashboard.populate_locality_table(?)" [id]]))
ctx)
(defn populate-i18n-table
[{:keys [import-id] :as ctx}]
(log/info "Populating v5_dashboard.i18n table")
(korma/exec-raw
(:conn xml-tree-values)
["select v5_dashboard.populate_i18n_table(?)" [import-id]])
ctx)
(defn populate-sources-table
[{:keys [import-id] :as ctx}]
(log/info "Populating v5_dashboard.sources table")
(korma/exec-raw
(:conn xml-tree-values)
["select v5_dashboard.populate_sources_table(?)" [import-id]])
ctx)
(defn populate-elections-table
[{:keys [import-id] :as ctx}]
(log/info "Populating v5_dashboard.elections table")
(korma/exec-raw
(:conn xml-tree-values)
["select v5_dashboard.populate_elections_table(?)" [import-id]])
ctx)
(defn delete-from-xml-tree-values
[{:keys [import-id] :as ctx}]
(when-not (:keep-feed-on-complete? ctx)
(log/info "Dropping from xml_tree_values")
(korma/exec-raw
(:conn xml-tree-values)
["delete from xml_tree_values where results_id = ?" [import-id]]))
ctx)
(defn v5-summary-branch
[{:keys [spec-family] :as ctx}]
(log/info "In v5-summary-branch")
(if (= spec-family "5.2")
(update ctx :pipeline (partial concat [populate-locality-table
populate-i18n-table
populate-sources-table
populate-elections-table]))
ctx))
(defn complete-run [ctx]
(let [id (:import-id ctx)
filename (:generated-xml-filename ctx)]
(korma/update results
(korma/set-fields {:filename filename
:complete true
:end_time (korma/sqlfn now)})
(korma/where {:id id}))))
(defn fail-run [id exception]
(korma/update results
(korma/set-fields {:exception exception
:end_time (korma/sqlfn now)})
(korma/where {:id id})))
(defn get-run
"Retrieves a record from the results table that corresponds to the current feed."
[ctx]
(korma/select results
(korma/where {:id (:import-id ctx)})))
(defn get-run-field
"Retrieves a column of the record from the results table that corresponds to the current feed."
[ctx field]
(let [response (korma/select results
(korma/fields field)
(korma/where {:id (:import-id ctx)}))]
(->> response
(first)
(field))))
(defn delete-run [id]
(korma/delete results
(korma/where {:id id})))
(def global-identifier -1)
(def invalid-identifier -2)
(def coercable-identifier?
(some-fn string? number? nil? #{:global}))
(defn coerce-identifier
"Coerce an error identifier to something that can be inserted as a
Postgres BIGINT or NULL"
[identifier]
(cond
(not (coercable-identifier? identifier)) invalid-identifier
(= :global identifier) global-identifier
(string? identifier) (try
(BigDecimal. identifier)
(catch java.lang.NumberFormatException _
invalid-identifier))
:else identifier))
(defn validation-value
[{:keys [ctx severity scope identifier error-type error-value]}]
{:results_id (:import-id ctx)
:severity (name severity)
:scope (name scope)
:identifier (coerce-identifier identifier)
:error_type (name error-type)
:error_data (pr-str error-value)})
(defn xml-tree-validation-value
[{:keys [ctx severity scope identifier error-type parent-element-id error-value]}]
{:results_id (:import-id ctx)
:parent_element_id parent-element-id
:severity (name severity)
:scope (name scope)
:error_type (name error-type)
:error_data (pr-str error-value)
:path (when-not (#{:global :post-process-street-segments} identifier)
(path->ltree identifier))})
(def statement-parameter-limit 10000)
(def bulk-import (partial db.util/bulk-import statement-parameter-limit))
(defn import-from-sqlite [{:keys [import-id db data-specs] :as ctx}]
(reduce (fn [ctx ent]
(let [table (get-in ctx [:tables ent])
columns (->> data-specs
(filter #(= ent (:table %)))
first
:columns)]
(bulk-import ctx
(ent v3-0-import-entities) ; TODO: choose import-entities based on import version
(->> table
(db.util/lazy-select 5000)
(map #(assoc % :results_id import-id))
(data-spec/coerce-rows columns)))))
ctx
db.util/import-entity-names))
(defn columns [table]
(let [table-name (:table table)]
(korma/select "information_schema.columns"
(korma/where {:table_name table-name}))))
(defn column-names [table]
(map :column_name (columns table)))
(defn fetch-from-cursor
"Given a database connection, `conn`, and a cursor named `cursor`,
fetch chunks of `n` rows until the cursor is exhausted. Returns a
lazy-seq of results and closes the cursor when it is finished. Throws
a `java.sql.SQLException` if anything goes awry (e.g., the cursor
doesn't exist in the given `conn`)"
[conn cursor n]
(try
(jdbc/query conn [(str "FETCH " n " FROM " cursor)])
(catch java.sql.SQLException e
(log/error (str "Can't fetch from " cursor " on " conn))
(throw e))))
(defn setup-cursor
"Given a database connection `conn` and a query `q`, setup a uniquely
named cursor, returning its name. The caller is responsible for
closing the cursor appropriately. Throws a `java.sql.SQLException` if
anything goes awry."
[conn q]
(let [cursor (str (gensym "cursor"))]
(try
(jdbc/execute! conn [(str "DECLARE " cursor " NO SCROLL CURSOR "
"WITH HOLD FOR " q)])
(catch java.sql.SQLException e
(log/error "Failed to create cursor" cursor " on " (pr-str conn))
(throw e)))
cursor))
(defn close
"Closes `cursor` on `conn`, throwing a java.sql.SQLException on
failure."
[conn cursor]
(try
(jdbc/execute! conn [(str "close " cursor)])
(catch java.sql.SQLException e
(log/error (str "Can't close " cursor " on " (pr-str conn)))
(throw e))))
(defn lazy-select-xml-tree-values
"Given a database connection `conn`, a chunk-size `n`, and an
`import-id`, return a lazy-seq containing the subset of
xml_tree_values in insertion order. Must be used - the lazy-seq fully
consumed - within a `jdbc/with-db-connection` context."
[conn n import-id]
(let [q (str "select path, simple_path, value "
"from xml_tree_values "
"where results_id = " import-id
"order by insert_counter asc;")
cursor (setup-cursor conn q)]
(letfn [(chunked-rows []
(try
(let [this-chunk (fetch-from-cursor conn cursor n)]
(if (seq this-chunk)
(lazy-cat this-chunk (trampoline chunked-rows))
(do
(close conn cursor)
nil)))
(catch java.sql.SQLException e
(log/error "Lazy failure case: " (.getMessage e))
chunked-rows)))]
(trampoline chunked-rows))))
(defn lazy-cursor-fetch
"Returns a function that gives you a lazy-seq from apply the query-fn
`q` to a cursor, in chunks of `n`, on a single database connection
`conn`. Must be used within a `jdbc/with-database-connection` form.
Example: (apply (lazy-cursor-fetch 10000 query-fn) conn import-id)"
[n query-fn]
(fn [conn & args]
(let [query (apply query-fn args)
cursor (setup-cursor conn query)]
(letfn [(chunked-rows []
(try
(let [this-chunk (fetch-from-cursor conn cursor n)]
(if (seq this-chunk)
(lazy-cat this-chunk (trampoline chunked-rows))
(do
(close conn cursor)
nil)))
(catch java.sql.SQLException e
(log/error "Lazy failure case: " (.getMessage e))
chunked-rows)))]
(trampoline chunked-rows)))))
(defn prep-v5-2-run [ctx]
(-> ctx
(assoc :tables v5-2-tables)
(assoc :ltree-index 0)))
| 64600 | (ns vip.data-processor.db.postgres
(:require [clojure.tools.logging :as log]
[clojure.string :as str]
[joplin.core :as j]
[joplin.jdbc.database]
[clojure.java.jdbc :as jdbc]
[korma.db :as db]
[korma.core :as korma]
[turbovote.resource-config :refer [config]]
[vip.data-processor.db.util :as db.util]
[vip.data-processor.util :as util]
[vip.data-processor.validation.data-spec :as data-spec])
(:import [org.postgresql.util PGobject]
[java.net URLEncoder]
[java.text Normalizer]))
(defn url []
(let [{:keys [host port user password database]} (config [:postgres])]
(apply format
"jdbc:postgresql://%s:%s/%s?user=%s&password=%s"
(map (comp #(URLEncoder/encode % "UTF-8") str)
[host port database user password]))))
(defn db-spec []
(let [{:keys [host port user password database]} (config [:postgres])]
{:dbtype "postgresql"
:dbname database
:host host
:port port
:user user
:password <PASSWORD>}))
(defn joplin-spec []
{:db {:type :sql
:url (url)}
:migrator "resources/migrations"})
(defn migrate
"Migrate forward any pending migrations."
[]
(j/migrate-db (joplin-spec)))
(defn pending
"List any migrations that haven't been applied yet."
[]
(j/pending-migrations (joplin-spec)))
(defn rollback
"With no parameters, rolls the db back 1 migrations. You can also send a
parameter that is either an integer or the id of a migration. When it's
and integer it rolls back that many migrations. When it's a string, it
should be the id of a migration and it rolls back any migrations up to
but not including that migration."
([]
(j/rollback-db (joplin-spec) 1))
([num-or-id]
(letfn [(parse-int [n-or-i]
(try
(Integer/parseInt n-or-i)
(catch Exception e
nil)))]
(if-let [num (parse-int num-or-id)]
;; we got a int, use it
(j/rollback-db (joplin-spec) num)
;; assume it was a String id
(j/rollback-db (joplin-spec) num-or-id)))))
(defn create
"Creates a new migration up/down with the id suffix. Joplin automatically
prepends the date in YYYYMMDD- format before this provided id, so if you
intend to write multiple migrations on the same day that need to be applied
in a particular order, it's ideal to start your id with 01-, 02-, 03-, etc"
[id]
(j/create-migration (joplin-spec) id))
(declare results-db results
validations
v3-0-import-entities
statistics)
(defn initialize []
(log/info "Initializing Postgres")
(migrate)
(let [opts (-> [:postgres]
config
(assoc :db (config [:postgres :database])))]
(db/defdb results-db (db/postgres opts)))
(korma/defentity results
(korma/database results-db))
(korma/defentity validations
(korma/database results-db))
(korma/defentity statistics
(korma/database results-db))
(korma/defentity election_approvals
(korma/database results-db))
(korma/defentity xml-tree-values
(korma/table "xml_tree_values")
(korma/database results-db))
(korma/defentity xml-tree-validations
(korma/table "xml_tree_validations")
(korma/database results-db))
(korma/defentity v5-statistics
(korma/table "v5_statistics")
(korma/database results-db))
(korma/defentity v5-dashboard-localities
(korma/table "v5_dashboard.localities")
(korma/database results-db))
(korma/defentity v5-2-street-segments
(korma/table "v5_2_street_segments"))
(korma/defentity v5-dashboard-paths-by-locality
(korma/table "v5_dashboard.paths_by_locality"))
(def v5-2-tables
(db.util/make-entities "5.2" results-db [:ballot-measure-contests
:ballot-measure-selections
:ballot-selections
:ballot-styles
:candidates
:candidate-contests
:candidate-selections
:contact-information
:contests
:departments
:elections
:election-administrations
:electoral-districts
:localities
:offices
:ordered-contests
:parties
:party-contests
:party-selections
:people
:polling-locations
:precincts
:retention-contests
:schedules
:sources
:states
:street-segments
:voter-services]))
(def v3-0-import-entities
(db.util/make-entities "3.0" results-db db.util/import-entity-names)))
(defn path->ltree [path]
(doto (PGobject.)
(.setType "ltree")
(.setValue path)))
(defn ltree-match
"Helper function for generating WHERE clases using ~. Accepts a keyword as a
table alias, or a korma entity"
[table column path]
(let [tablename (if (keyword? table)
(name table)
(korma.sql.engine/table-alias table))]
(korma/raw (str tablename
"." (name column)
" ~ '" path "'"))))
(defn find-value-for-simple-path [import-id simple-path]
(-> (korma/select xml-tree-values
(korma/fields :value)
(korma/where {:results_id import-id
:simple_path (path->ltree simple-path)}))
first
:value))
(defn find-single-xml-tree-value [results-id path]
(-> (korma/select xml-tree-values
(korma/fields :value)
(korma/where {:results_id results-id})
(korma/where (ltree-match xml-tree-values
:path
path)))
first
:value))
(defn start-run [ctx]
(let [results (korma/insert results
(korma/values {:start_time (korma/sqlfn now)
:complete false}))
import-id (:id results)]
(log/info "Starting run with import_id:" import-id)
(assoc ctx :import-id import-id)))
(defn build-public-id [date election-type state import-id]
(let [nil-or-empty? (some-fn nil? empty?)
formatted-date (util/format-date date)
good-parts (->> [formatted-date election-type state]
(remove nil-or-empty?)
(map #(str/trim %))
(map #(Normalizer/normalize % java.text.Normalizer$Form/NFKD))
(map #(str/replace % #"\p{Space}" "-"))
(map #(str/replace % #"[\p{Punct}\P{ASCII}&&[^-]]" "")))]
(if (empty? good-parts)
(str "invalid-" import-id)
(str/join "-" (concat good-parts [import-id])))))
(defn build-election-id [date election-type state]
(let [components [date election-type state]]
(when (every? seq components)
(->> components
(map str/trim)
(str/join "-")))))
(defn get-v3-public-id-data [{:keys [import-id] :as ctx}]
(let [state (-> ctx
(get-in [:tables :states])
(korma/select (korma/fields :name))
first
:name)
{:keys [date election_type]} (-> ctx
(get-in [:tables :elections])
(korma/select (korma/fields :date :election_type))
first)
vip-id (-> ctx
(get-in [:tables :sources])
(korma/select (korma/fields :vip_id))
first
:vip_id)]
{:date date
:election-type election_type
:state state
:vip-id vip-id
:import-id import-id}))
(defn get-xml-tree-public-id-data [{:keys [import-id] :as ctx}]
(let [state (find-value-for-simple-path
import-id
"VipObject.State.Name")
date (find-value-for-simple-path
import-id
"VipObject.Election.Date")
election-type (find-value-for-simple-path
import-id
"VipObject.Election.ElectionType.Text")
vip-id (find-value-for-simple-path
import-id
"VipObject.Source.VipId")]
{:date date
:election-type election-type
:state state
:import-id import-id
:vip-id vip-id}))
(defn get-public-id-data [{:keys [spec-family] :as ctx}]
(condp = spec-family
"3.0" (get-v3-public-id-data ctx)
"5.2" (get-xml-tree-public-id-data ctx)
{}))
(defn generate-public-id [ctx]
(let [{:keys [date election-type state import-id]} (get-public-id-data ctx)]
(log/info "Building public id")
(build-public-id date election-type state import-id)))
(defn generate-election-id [ctx]
(log/info "Building election id")
(let [{:keys [date election-type state]} (get-public-id-data ctx)]
(build-election-id date election-type state)))
(defn store-public-id [ctx]
(let [id (:import-id ctx)
public-id (generate-public-id ctx)
public-id-data (get-public-id-data ctx)]
(log/info "Storing public id")
(korma/update results
(korma/set-fields {:public_id public-id
:state (:state public-id-data)
:election_type (:election-type public-id-data)
:election_date (:date public-id-data)
:vip_id (:vip-id public-id-data)})
(korma/where {:id id}))
(assoc ctx :public-id public-id)))
(defn save-election-id! [election-id]
(binding [db/*current-conn* (db/get-connection (:db election_approvals))]
(db/transaction
(when-not (seq (korma/select election_approvals
(korma/where {:election_id election-id})))
(korma/insert election_approvals
(korma/values {:election_id election-id}))))))
(defn store-election-id [ctx]
(if-let [election-id (generate-election-id ctx)]
(let [id (:import-id ctx)]
(log/info "Storing election id")
(save-election-id! election-id)
(korma/update results
(korma/set-fields {:election_id election-id})
(korma/where {:id id}))
(assoc ctx :election-id election-id))
ctx))
(defn store-spec-version [{:keys [spec-version import-id] :as ctx}]
(when spec-version
(log/info "Storing spec-verion," spec-version)
(korma/update results
(korma/set-fields {:spec_version spec-version})
(korma/where {:id import-id})))
ctx)
(defn analyze-xtv [ctx]
(log/info "Analyzing xml_tree_values")
(korma/exec-raw
(:conn xml-tree-values)
["analyze xml_tree_values"])
ctx)
(defn populate-locality-table
[ctx]
(let [id (:import-id ctx)]
(log/info "Populating v5_dashboard.paths_by_locality")
(korma/exec-raw
(:conn xml-tree-values)
["select v5_dashboard.populate_locality_table(?)" [id]]))
ctx)
(defn populate-i18n-table
[{:keys [import-id] :as ctx}]
(log/info "Populating v5_dashboard.i18n table")
(korma/exec-raw
(:conn xml-tree-values)
["select v5_dashboard.populate_i18n_table(?)" [import-id]])
ctx)
(defn populate-sources-table
[{:keys [import-id] :as ctx}]
(log/info "Populating v5_dashboard.sources table")
(korma/exec-raw
(:conn xml-tree-values)
["select v5_dashboard.populate_sources_table(?)" [import-id]])
ctx)
(defn populate-elections-table
[{:keys [import-id] :as ctx}]
(log/info "Populating v5_dashboard.elections table")
(korma/exec-raw
(:conn xml-tree-values)
["select v5_dashboard.populate_elections_table(?)" [import-id]])
ctx)
(defn delete-from-xml-tree-values
[{:keys [import-id] :as ctx}]
(when-not (:keep-feed-on-complete? ctx)
(log/info "Dropping from xml_tree_values")
(korma/exec-raw
(:conn xml-tree-values)
["delete from xml_tree_values where results_id = ?" [import-id]]))
ctx)
(defn v5-summary-branch
[{:keys [spec-family] :as ctx}]
(log/info "In v5-summary-branch")
(if (= spec-family "5.2")
(update ctx :pipeline (partial concat [populate-locality-table
populate-i18n-table
populate-sources-table
populate-elections-table]))
ctx))
(defn complete-run [ctx]
(let [id (:import-id ctx)
filename (:generated-xml-filename ctx)]
(korma/update results
(korma/set-fields {:filename filename
:complete true
:end_time (korma/sqlfn now)})
(korma/where {:id id}))))
(defn fail-run [id exception]
(korma/update results
(korma/set-fields {:exception exception
:end_time (korma/sqlfn now)})
(korma/where {:id id})))
(defn get-run
"Retrieves a record from the results table that corresponds to the current feed."
[ctx]
(korma/select results
(korma/where {:id (:import-id ctx)})))
(defn get-run-field
"Retrieves a column of the record from the results table that corresponds to the current feed."
[ctx field]
(let [response (korma/select results
(korma/fields field)
(korma/where {:id (:import-id ctx)}))]
(->> response
(first)
(field))))
(defn delete-run [id]
(korma/delete results
(korma/where {:id id})))
(def global-identifier -1)
(def invalid-identifier -2)
(def coercable-identifier?
(some-fn string? number? nil? #{:global}))
(defn coerce-identifier
"Coerce an error identifier to something that can be inserted as a
Postgres BIGINT or NULL"
[identifier]
(cond
(not (coercable-identifier? identifier)) invalid-identifier
(= :global identifier) global-identifier
(string? identifier) (try
(BigDecimal. identifier)
(catch java.lang.NumberFormatException _
invalid-identifier))
:else identifier))
(defn validation-value
[{:keys [ctx severity scope identifier error-type error-value]}]
{:results_id (:import-id ctx)
:severity (name severity)
:scope (name scope)
:identifier (coerce-identifier identifier)
:error_type (name error-type)
:error_data (pr-str error-value)})
(defn xml-tree-validation-value
[{:keys [ctx severity scope identifier error-type parent-element-id error-value]}]
{:results_id (:import-id ctx)
:parent_element_id parent-element-id
:severity (name severity)
:scope (name scope)
:error_type (name error-type)
:error_data (pr-str error-value)
:path (when-not (#{:global :post-process-street-segments} identifier)
(path->ltree identifier))})
(def statement-parameter-limit 10000)
(def bulk-import (partial db.util/bulk-import statement-parameter-limit))
(defn import-from-sqlite [{:keys [import-id db data-specs] :as ctx}]
(reduce (fn [ctx ent]
(let [table (get-in ctx [:tables ent])
columns (->> data-specs
(filter #(= ent (:table %)))
first
:columns)]
(bulk-import ctx
(ent v3-0-import-entities) ; TODO: choose import-entities based on import version
(->> table
(db.util/lazy-select 5000)
(map #(assoc % :results_id import-id))
(data-spec/coerce-rows columns)))))
ctx
db.util/import-entity-names))
(defn columns [table]
(let [table-name (:table table)]
(korma/select "information_schema.columns"
(korma/where {:table_name table-name}))))
(defn column-names [table]
(map :column_name (columns table)))
(defn fetch-from-cursor
"Given a database connection, `conn`, and a cursor named `cursor`,
fetch chunks of `n` rows until the cursor is exhausted. Returns a
lazy-seq of results and closes the cursor when it is finished. Throws
a `java.sql.SQLException` if anything goes awry (e.g., the cursor
doesn't exist in the given `conn`)"
[conn cursor n]
(try
(jdbc/query conn [(str "FETCH " n " FROM " cursor)])
(catch java.sql.SQLException e
(log/error (str "Can't fetch from " cursor " on " conn))
(throw e))))
(defn setup-cursor
"Given a database connection `conn` and a query `q`, setup a uniquely
named cursor, returning its name. The caller is responsible for
closing the cursor appropriately. Throws a `java.sql.SQLException` if
anything goes awry."
[conn q]
(let [cursor (str (gensym "cursor"))]
(try
(jdbc/execute! conn [(str "DECLARE " cursor " NO SCROLL CURSOR "
"WITH HOLD FOR " q)])
(catch java.sql.SQLException e
(log/error "Failed to create cursor" cursor " on " (pr-str conn))
(throw e)))
cursor))
(defn close
"Closes `cursor` on `conn`, throwing a java.sql.SQLException on
failure."
[conn cursor]
(try
(jdbc/execute! conn [(str "close " cursor)])
(catch java.sql.SQLException e
(log/error (str "Can't close " cursor " on " (pr-str conn)))
(throw e))))
(defn lazy-select-xml-tree-values
"Given a database connection `conn`, a chunk-size `n`, and an
`import-id`, return a lazy-seq containing the subset of
xml_tree_values in insertion order. Must be used - the lazy-seq fully
consumed - within a `jdbc/with-db-connection` context."
[conn n import-id]
(let [q (str "select path, simple_path, value "
"from xml_tree_values "
"where results_id = " import-id
"order by insert_counter asc;")
cursor (setup-cursor conn q)]
(letfn [(chunked-rows []
(try
(let [this-chunk (fetch-from-cursor conn cursor n)]
(if (seq this-chunk)
(lazy-cat this-chunk (trampoline chunked-rows))
(do
(close conn cursor)
nil)))
(catch java.sql.SQLException e
(log/error "Lazy failure case: " (.getMessage e))
chunked-rows)))]
(trampoline chunked-rows))))
(defn lazy-cursor-fetch
"Returns a function that gives you a lazy-seq from apply the query-fn
`q` to a cursor, in chunks of `n`, on a single database connection
`conn`. Must be used within a `jdbc/with-database-connection` form.
Example: (apply (lazy-cursor-fetch 10000 query-fn) conn import-id)"
[n query-fn]
(fn [conn & args]
(let [query (apply query-fn args)
cursor (setup-cursor conn query)]
(letfn [(chunked-rows []
(try
(let [this-chunk (fetch-from-cursor conn cursor n)]
(if (seq this-chunk)
(lazy-cat this-chunk (trampoline chunked-rows))
(do
(close conn cursor)
nil)))
(catch java.sql.SQLException e
(log/error "Lazy failure case: " (.getMessage e))
chunked-rows)))]
(trampoline chunked-rows)))))
(defn prep-v5-2-run [ctx]
(-> ctx
(assoc :tables v5-2-tables)
(assoc :ltree-index 0)))
| true | (ns vip.data-processor.db.postgres
(:require [clojure.tools.logging :as log]
[clojure.string :as str]
[joplin.core :as j]
[joplin.jdbc.database]
[clojure.java.jdbc :as jdbc]
[korma.db :as db]
[korma.core :as korma]
[turbovote.resource-config :refer [config]]
[vip.data-processor.db.util :as db.util]
[vip.data-processor.util :as util]
[vip.data-processor.validation.data-spec :as data-spec])
(:import [org.postgresql.util PGobject]
[java.net URLEncoder]
[java.text Normalizer]))
(defn url []
(let [{:keys [host port user password database]} (config [:postgres])]
(apply format
"jdbc:postgresql://%s:%s/%s?user=%s&password=%s"
(map (comp #(URLEncoder/encode % "UTF-8") str)
[host port database user password]))))
(defn db-spec []
(let [{:keys [host port user password database]} (config [:postgres])]
{:dbtype "postgresql"
:dbname database
:host host
:port port
:user user
:password PI:PASSWORD:<PASSWORD>END_PI}))
(defn joplin-spec []
{:db {:type :sql
:url (url)}
:migrator "resources/migrations"})
(defn migrate
"Migrate forward any pending migrations."
[]
(j/migrate-db (joplin-spec)))
(defn pending
"List any migrations that haven't been applied yet."
[]
(j/pending-migrations (joplin-spec)))
(defn rollback
"With no parameters, rolls the db back 1 migrations. You can also send a
parameter that is either an integer or the id of a migration. When it's
and integer it rolls back that many migrations. When it's a string, it
should be the id of a migration and it rolls back any migrations up to
but not including that migration."
([]
(j/rollback-db (joplin-spec) 1))
([num-or-id]
(letfn [(parse-int [n-or-i]
(try
(Integer/parseInt n-or-i)
(catch Exception e
nil)))]
(if-let [num (parse-int num-or-id)]
;; we got a int, use it
(j/rollback-db (joplin-spec) num)
;; assume it was a String id
(j/rollback-db (joplin-spec) num-or-id)))))
(defn create
"Creates a new migration up/down with the id suffix. Joplin automatically
prepends the date in YYYYMMDD- format before this provided id, so if you
intend to write multiple migrations on the same day that need to be applied
in a particular order, it's ideal to start your id with 01-, 02-, 03-, etc"
[id]
(j/create-migration (joplin-spec) id))
(declare results-db results
validations
v3-0-import-entities
statistics)
(defn initialize []
(log/info "Initializing Postgres")
(migrate)
(let [opts (-> [:postgres]
config
(assoc :db (config [:postgres :database])))]
(db/defdb results-db (db/postgres opts)))
(korma/defentity results
(korma/database results-db))
(korma/defentity validations
(korma/database results-db))
(korma/defentity statistics
(korma/database results-db))
(korma/defentity election_approvals
(korma/database results-db))
(korma/defentity xml-tree-values
(korma/table "xml_tree_values")
(korma/database results-db))
(korma/defentity xml-tree-validations
(korma/table "xml_tree_validations")
(korma/database results-db))
(korma/defentity v5-statistics
(korma/table "v5_statistics")
(korma/database results-db))
(korma/defentity v5-dashboard-localities
(korma/table "v5_dashboard.localities")
(korma/database results-db))
(korma/defentity v5-2-street-segments
(korma/table "v5_2_street_segments"))
(korma/defentity v5-dashboard-paths-by-locality
(korma/table "v5_dashboard.paths_by_locality"))
(def v5-2-tables
(db.util/make-entities "5.2" results-db [:ballot-measure-contests
:ballot-measure-selections
:ballot-selections
:ballot-styles
:candidates
:candidate-contests
:candidate-selections
:contact-information
:contests
:departments
:elections
:election-administrations
:electoral-districts
:localities
:offices
:ordered-contests
:parties
:party-contests
:party-selections
:people
:polling-locations
:precincts
:retention-contests
:schedules
:sources
:states
:street-segments
:voter-services]))
(def v3-0-import-entities
(db.util/make-entities "3.0" results-db db.util/import-entity-names)))
(defn path->ltree [path]
(doto (PGobject.)
(.setType "ltree")
(.setValue path)))
(defn ltree-match
"Helper function for generating WHERE clases using ~. Accepts a keyword as a
table alias, or a korma entity"
[table column path]
(let [tablename (if (keyword? table)
(name table)
(korma.sql.engine/table-alias table))]
(korma/raw (str tablename
"." (name column)
" ~ '" path "'"))))
(defn find-value-for-simple-path [import-id simple-path]
(-> (korma/select xml-tree-values
(korma/fields :value)
(korma/where {:results_id import-id
:simple_path (path->ltree simple-path)}))
first
:value))
(defn find-single-xml-tree-value [results-id path]
(-> (korma/select xml-tree-values
(korma/fields :value)
(korma/where {:results_id results-id})
(korma/where (ltree-match xml-tree-values
:path
path)))
first
:value))
(defn start-run [ctx]
(let [results (korma/insert results
(korma/values {:start_time (korma/sqlfn now)
:complete false}))
import-id (:id results)]
(log/info "Starting run with import_id:" import-id)
(assoc ctx :import-id import-id)))
(defn build-public-id [date election-type state import-id]
(let [nil-or-empty? (some-fn nil? empty?)
formatted-date (util/format-date date)
good-parts (->> [formatted-date election-type state]
(remove nil-or-empty?)
(map #(str/trim %))
(map #(Normalizer/normalize % java.text.Normalizer$Form/NFKD))
(map #(str/replace % #"\p{Space}" "-"))
(map #(str/replace % #"[\p{Punct}\P{ASCII}&&[^-]]" "")))]
(if (empty? good-parts)
(str "invalid-" import-id)
(str/join "-" (concat good-parts [import-id])))))
(defn build-election-id [date election-type state]
(let [components [date election-type state]]
(when (every? seq components)
(->> components
(map str/trim)
(str/join "-")))))
(defn get-v3-public-id-data [{:keys [import-id] :as ctx}]
(let [state (-> ctx
(get-in [:tables :states])
(korma/select (korma/fields :name))
first
:name)
{:keys [date election_type]} (-> ctx
(get-in [:tables :elections])
(korma/select (korma/fields :date :election_type))
first)
vip-id (-> ctx
(get-in [:tables :sources])
(korma/select (korma/fields :vip_id))
first
:vip_id)]
{:date date
:election-type election_type
:state state
:vip-id vip-id
:import-id import-id}))
(defn get-xml-tree-public-id-data [{:keys [import-id] :as ctx}]
(let [state (find-value-for-simple-path
import-id
"VipObject.State.Name")
date (find-value-for-simple-path
import-id
"VipObject.Election.Date")
election-type (find-value-for-simple-path
import-id
"VipObject.Election.ElectionType.Text")
vip-id (find-value-for-simple-path
import-id
"VipObject.Source.VipId")]
{:date date
:election-type election-type
:state state
:import-id import-id
:vip-id vip-id}))
(defn get-public-id-data [{:keys [spec-family] :as ctx}]
(condp = spec-family
"3.0" (get-v3-public-id-data ctx)
"5.2" (get-xml-tree-public-id-data ctx)
{}))
(defn generate-public-id [ctx]
(let [{:keys [date election-type state import-id]} (get-public-id-data ctx)]
(log/info "Building public id")
(build-public-id date election-type state import-id)))
(defn generate-election-id [ctx]
(log/info "Building election id")
(let [{:keys [date election-type state]} (get-public-id-data ctx)]
(build-election-id date election-type state)))
(defn store-public-id [ctx]
(let [id (:import-id ctx)
public-id (generate-public-id ctx)
public-id-data (get-public-id-data ctx)]
(log/info "Storing public id")
(korma/update results
(korma/set-fields {:public_id public-id
:state (:state public-id-data)
:election_type (:election-type public-id-data)
:election_date (:date public-id-data)
:vip_id (:vip-id public-id-data)})
(korma/where {:id id}))
(assoc ctx :public-id public-id)))
(defn save-election-id! [election-id]
(binding [db/*current-conn* (db/get-connection (:db election_approvals))]
(db/transaction
(when-not (seq (korma/select election_approvals
(korma/where {:election_id election-id})))
(korma/insert election_approvals
(korma/values {:election_id election-id}))))))
(defn store-election-id [ctx]
(if-let [election-id (generate-election-id ctx)]
(let [id (:import-id ctx)]
(log/info "Storing election id")
(save-election-id! election-id)
(korma/update results
(korma/set-fields {:election_id election-id})
(korma/where {:id id}))
(assoc ctx :election-id election-id))
ctx))
(defn store-spec-version [{:keys [spec-version import-id] :as ctx}]
(when spec-version
(log/info "Storing spec-verion," spec-version)
(korma/update results
(korma/set-fields {:spec_version spec-version})
(korma/where {:id import-id})))
ctx)
(defn analyze-xtv [ctx]
(log/info "Analyzing xml_tree_values")
(korma/exec-raw
(:conn xml-tree-values)
["analyze xml_tree_values"])
ctx)
(defn populate-locality-table
[ctx]
(let [id (:import-id ctx)]
(log/info "Populating v5_dashboard.paths_by_locality")
(korma/exec-raw
(:conn xml-tree-values)
["select v5_dashboard.populate_locality_table(?)" [id]]))
ctx)
(defn populate-i18n-table
[{:keys [import-id] :as ctx}]
(log/info "Populating v5_dashboard.i18n table")
(korma/exec-raw
(:conn xml-tree-values)
["select v5_dashboard.populate_i18n_table(?)" [import-id]])
ctx)
(defn populate-sources-table
[{:keys [import-id] :as ctx}]
(log/info "Populating v5_dashboard.sources table")
(korma/exec-raw
(:conn xml-tree-values)
["select v5_dashboard.populate_sources_table(?)" [import-id]])
ctx)
(defn populate-elections-table
[{:keys [import-id] :as ctx}]
(log/info "Populating v5_dashboard.elections table")
(korma/exec-raw
(:conn xml-tree-values)
["select v5_dashboard.populate_elections_table(?)" [import-id]])
ctx)
(defn delete-from-xml-tree-values
[{:keys [import-id] :as ctx}]
(when-not (:keep-feed-on-complete? ctx)
(log/info "Dropping from xml_tree_values")
(korma/exec-raw
(:conn xml-tree-values)
["delete from xml_tree_values where results_id = ?" [import-id]]))
ctx)
(defn v5-summary-branch
[{:keys [spec-family] :as ctx}]
(log/info "In v5-summary-branch")
(if (= spec-family "5.2")
(update ctx :pipeline (partial concat [populate-locality-table
populate-i18n-table
populate-sources-table
populate-elections-table]))
ctx))
(defn complete-run [ctx]
(let [id (:import-id ctx)
filename (:generated-xml-filename ctx)]
(korma/update results
(korma/set-fields {:filename filename
:complete true
:end_time (korma/sqlfn now)})
(korma/where {:id id}))))
(defn fail-run [id exception]
(korma/update results
(korma/set-fields {:exception exception
:end_time (korma/sqlfn now)})
(korma/where {:id id})))
(defn get-run
"Retrieves a record from the results table that corresponds to the current feed."
[ctx]
(korma/select results
(korma/where {:id (:import-id ctx)})))
(defn get-run-field
"Retrieves a column of the record from the results table that corresponds to the current feed."
[ctx field]
(let [response (korma/select results
(korma/fields field)
(korma/where {:id (:import-id ctx)}))]
(->> response
(first)
(field))))
(defn delete-run [id]
(korma/delete results
(korma/where {:id id})))
(def global-identifier -1)
(def invalid-identifier -2)
(def coercable-identifier?
(some-fn string? number? nil? #{:global}))
(defn coerce-identifier
"Coerce an error identifier to something that can be inserted as a
Postgres BIGINT or NULL"
[identifier]
(cond
(not (coercable-identifier? identifier)) invalid-identifier
(= :global identifier) global-identifier
(string? identifier) (try
(BigDecimal. identifier)
(catch java.lang.NumberFormatException _
invalid-identifier))
:else identifier))
(defn validation-value
[{:keys [ctx severity scope identifier error-type error-value]}]
{:results_id (:import-id ctx)
:severity (name severity)
:scope (name scope)
:identifier (coerce-identifier identifier)
:error_type (name error-type)
:error_data (pr-str error-value)})
(defn xml-tree-validation-value
[{:keys [ctx severity scope identifier error-type parent-element-id error-value]}]
{:results_id (:import-id ctx)
:parent_element_id parent-element-id
:severity (name severity)
:scope (name scope)
:error_type (name error-type)
:error_data (pr-str error-value)
:path (when-not (#{:global :post-process-street-segments} identifier)
(path->ltree identifier))})
(def statement-parameter-limit 10000)
(def bulk-import (partial db.util/bulk-import statement-parameter-limit))
(defn import-from-sqlite [{:keys [import-id db data-specs] :as ctx}]
(reduce (fn [ctx ent]
(let [table (get-in ctx [:tables ent])
columns (->> data-specs
(filter #(= ent (:table %)))
first
:columns)]
(bulk-import ctx
(ent v3-0-import-entities) ; TODO: choose import-entities based on import version
(->> table
(db.util/lazy-select 5000)
(map #(assoc % :results_id import-id))
(data-spec/coerce-rows columns)))))
ctx
db.util/import-entity-names))
(defn columns [table]
(let [table-name (:table table)]
(korma/select "information_schema.columns"
(korma/where {:table_name table-name}))))
(defn column-names [table]
(map :column_name (columns table)))
(defn fetch-from-cursor
"Given a database connection, `conn`, and a cursor named `cursor`,
fetch chunks of `n` rows until the cursor is exhausted. Returns a
lazy-seq of results and closes the cursor when it is finished. Throws
a `java.sql.SQLException` if anything goes awry (e.g., the cursor
doesn't exist in the given `conn`)"
[conn cursor n]
(try
(jdbc/query conn [(str "FETCH " n " FROM " cursor)])
(catch java.sql.SQLException e
(log/error (str "Can't fetch from " cursor " on " conn))
(throw e))))
(defn setup-cursor
"Given a database connection `conn` and a query `q`, setup a uniquely
named cursor, returning its name. The caller is responsible for
closing the cursor appropriately. Throws a `java.sql.SQLException` if
anything goes awry."
[conn q]
(let [cursor (str (gensym "cursor"))]
(try
(jdbc/execute! conn [(str "DECLARE " cursor " NO SCROLL CURSOR "
"WITH HOLD FOR " q)])
(catch java.sql.SQLException e
(log/error "Failed to create cursor" cursor " on " (pr-str conn))
(throw e)))
cursor))
(defn close
"Closes `cursor` on `conn`, throwing a java.sql.SQLException on
failure."
[conn cursor]
(try
(jdbc/execute! conn [(str "close " cursor)])
(catch java.sql.SQLException e
(log/error (str "Can't close " cursor " on " (pr-str conn)))
(throw e))))
(defn lazy-select-xml-tree-values
"Given a database connection `conn`, a chunk-size `n`, and an
`import-id`, return a lazy-seq containing the subset of
xml_tree_values in insertion order. Must be used - the lazy-seq fully
consumed - within a `jdbc/with-db-connection` context."
[conn n import-id]
(let [q (str "select path, simple_path, value "
"from xml_tree_values "
"where results_id = " import-id
"order by insert_counter asc;")
cursor (setup-cursor conn q)]
(letfn [(chunked-rows []
(try
(let [this-chunk (fetch-from-cursor conn cursor n)]
(if (seq this-chunk)
(lazy-cat this-chunk (trampoline chunked-rows))
(do
(close conn cursor)
nil)))
(catch java.sql.SQLException e
(log/error "Lazy failure case: " (.getMessage e))
chunked-rows)))]
(trampoline chunked-rows))))
(defn lazy-cursor-fetch
"Returns a function that gives you a lazy-seq from apply the query-fn
`q` to a cursor, in chunks of `n`, on a single database connection
`conn`. Must be used within a `jdbc/with-database-connection` form.
Example: (apply (lazy-cursor-fetch 10000 query-fn) conn import-id)"
[n query-fn]
(fn [conn & args]
(let [query (apply query-fn args)
cursor (setup-cursor conn query)]
(letfn [(chunked-rows []
(try
(let [this-chunk (fetch-from-cursor conn cursor n)]
(if (seq this-chunk)
(lazy-cat this-chunk (trampoline chunked-rows))
(do
(close conn cursor)
nil)))
(catch java.sql.SQLException e
(log/error "Lazy failure case: " (.getMessage e))
chunked-rows)))]
(trampoline chunked-rows)))))
(defn prep-v5-2-run [ctx]
(-> ctx
(assoc :tables v5-2-tables)
(assoc :ltree-index 0)))
|
[
{
"context": " {:headers headers})))\n 200 {\"postman-token\" \"12345\"\n \"other\" \"value\"}\n 203 {\"random\" \"str",
"end": 2043,
"score": 0.973432183265686,
"start": 2038,
"tag": "PASSWORD",
"value": "12345"
}
] | test/prone/middleware_test.clj | cjohansen/prone | 0 | (ns prone.middleware-test
(:require [clojure.test :refer :all]
[prone.debug :refer [debug *debug-data*]]
[prone.middleware :refer :all]))
(deftest resets-debug-on-every-request-test
(declare inner-debug-data)
((wrap-exceptions (fn [req] (def inner-debug-data @*debug-data*))) {})
(is (= [] inner-debug-data))
((wrap-exceptions (fn [req]
(debug "Oh noes")
(def inner-debug-data @*debug-data*))) {})
(is (= ["Oh noes"] (map :message inner-debug-data)))
((wrap-exceptions (fn [req]
(debug "Oh noes")
(debug "Halp!")
(def inner-debug-data @*debug-data*))) {})
(is (= ["Oh noes" "Halp!"] (map :message inner-debug-data))))
(defn test-handler [handler]
((wrap-exceptions handler {:print-stacktraces? false}) {}))
(deftest catches-exceptions-and-assertion-errors
(let [response (test-handler (fn [req] (/ 1 0)))]
(is (= 500 (:status response)))
(is (re-find #"prone-data" (:body response))))
(let [response (test-handler (fn [req] (assert false)))]
(is (= 500 (:status response)))
(is (re-find #"prone-data" (:body response))))
(is (thrown? Error
(test-handler (fn [req] (throw (Error.)))))))
(deftest renders-debug-page-on-debug
(is (= 203 (:status ((wrap-exceptions (fn [req]
(debug "I need help")
{:status 200})) {})))))
(deftest excludes-unwanted-clients
(are [status headers] (= status (:status
((wrap-exceptions
(fn [req]
(debug "I need help")
{:status 200})
{:skip-prone? (fn [req]
(contains? (:headers req) "postman-token"))})
{:headers headers})))
200 {"postman-token" "12345"
"other" "value"}
203 {"random" "string"}
203 {}))
(defn async-test-handler [handler]
(let [response (atom nil)]
((wrap-exceptions handler {:print-stacktraces? false})
{}
(partial reset! response)
(fn []))
@response))
(deftest async-catches-exceptions-and-assertion-errors
(let [response (async-test-handler (fn [req respond raise]
(try
(/ 1 0)
(catch Exception e
(raise e)))))]
(is (= 500 (:status response)))
(is (re-find #"prone-data" (:body response))))
(let [response (async-test-handler (fn [req respond raise]
(/ 1 0)))]
(is (= 500 (:status response)))
(is (re-find #"prone-data" (:body response))))
(let [response (test-handler (fn [req respond raise]
(try
(assert false)
(catch AssertionError e
(raise e)))))]
(is (= 500 (:status response)))
(is (re-find #"prone-data" (:body response)))))
(deftest async-renders-debug-page-on-debug
(is (= 203
(-> (async-test-handler (fn [req respond raise]
(debug "I need help")
(respond {:status 200})))
:status))))
(deftest finds-application-name
(is (= 'prone (find-application-name-in-project-clj "(defproject prone ...)")))
(is (= 'parens-of-the-dead (find-application-name-in-project-clj "(defproject parens-of-the-dead ...)")))
(is (= 'prone (find-application-name-in-project-clj "
(defproject
prone ...)")))
(is (= nil (find-application-name-in-project-clj "(def prone ...)")))
(is (= nil (find-application-name-in-project-clj "(defprojectprone ...)"))))
| 22442 | (ns prone.middleware-test
(:require [clojure.test :refer :all]
[prone.debug :refer [debug *debug-data*]]
[prone.middleware :refer :all]))
(deftest resets-debug-on-every-request-test
(declare inner-debug-data)
((wrap-exceptions (fn [req] (def inner-debug-data @*debug-data*))) {})
(is (= [] inner-debug-data))
((wrap-exceptions (fn [req]
(debug "Oh noes")
(def inner-debug-data @*debug-data*))) {})
(is (= ["Oh noes"] (map :message inner-debug-data)))
((wrap-exceptions (fn [req]
(debug "Oh noes")
(debug "Halp!")
(def inner-debug-data @*debug-data*))) {})
(is (= ["Oh noes" "Halp!"] (map :message inner-debug-data))))
(defn test-handler [handler]
((wrap-exceptions handler {:print-stacktraces? false}) {}))
(deftest catches-exceptions-and-assertion-errors
(let [response (test-handler (fn [req] (/ 1 0)))]
(is (= 500 (:status response)))
(is (re-find #"prone-data" (:body response))))
(let [response (test-handler (fn [req] (assert false)))]
(is (= 500 (:status response)))
(is (re-find #"prone-data" (:body response))))
(is (thrown? Error
(test-handler (fn [req] (throw (Error.)))))))
(deftest renders-debug-page-on-debug
(is (= 203 (:status ((wrap-exceptions (fn [req]
(debug "I need help")
{:status 200})) {})))))
(deftest excludes-unwanted-clients
(are [status headers] (= status (:status
((wrap-exceptions
(fn [req]
(debug "I need help")
{:status 200})
{:skip-prone? (fn [req]
(contains? (:headers req) "postman-token"))})
{:headers headers})))
200 {"postman-token" "<PASSWORD>"
"other" "value"}
203 {"random" "string"}
203 {}))
(defn async-test-handler [handler]
(let [response (atom nil)]
((wrap-exceptions handler {:print-stacktraces? false})
{}
(partial reset! response)
(fn []))
@response))
(deftest async-catches-exceptions-and-assertion-errors
(let [response (async-test-handler (fn [req respond raise]
(try
(/ 1 0)
(catch Exception e
(raise e)))))]
(is (= 500 (:status response)))
(is (re-find #"prone-data" (:body response))))
(let [response (async-test-handler (fn [req respond raise]
(/ 1 0)))]
(is (= 500 (:status response)))
(is (re-find #"prone-data" (:body response))))
(let [response (test-handler (fn [req respond raise]
(try
(assert false)
(catch AssertionError e
(raise e)))))]
(is (= 500 (:status response)))
(is (re-find #"prone-data" (:body response)))))
(deftest async-renders-debug-page-on-debug
(is (= 203
(-> (async-test-handler (fn [req respond raise]
(debug "I need help")
(respond {:status 200})))
:status))))
(deftest finds-application-name
(is (= 'prone (find-application-name-in-project-clj "(defproject prone ...)")))
(is (= 'parens-of-the-dead (find-application-name-in-project-clj "(defproject parens-of-the-dead ...)")))
(is (= 'prone (find-application-name-in-project-clj "
(defproject
prone ...)")))
(is (= nil (find-application-name-in-project-clj "(def prone ...)")))
(is (= nil (find-application-name-in-project-clj "(defprojectprone ...)"))))
| true | (ns prone.middleware-test
(:require [clojure.test :refer :all]
[prone.debug :refer [debug *debug-data*]]
[prone.middleware :refer :all]))
(deftest resets-debug-on-every-request-test
(declare inner-debug-data)
((wrap-exceptions (fn [req] (def inner-debug-data @*debug-data*))) {})
(is (= [] inner-debug-data))
((wrap-exceptions (fn [req]
(debug "Oh noes")
(def inner-debug-data @*debug-data*))) {})
(is (= ["Oh noes"] (map :message inner-debug-data)))
((wrap-exceptions (fn [req]
(debug "Oh noes")
(debug "Halp!")
(def inner-debug-data @*debug-data*))) {})
(is (= ["Oh noes" "Halp!"] (map :message inner-debug-data))))
(defn test-handler [handler]
((wrap-exceptions handler {:print-stacktraces? false}) {}))
(deftest catches-exceptions-and-assertion-errors
(let [response (test-handler (fn [req] (/ 1 0)))]
(is (= 500 (:status response)))
(is (re-find #"prone-data" (:body response))))
(let [response (test-handler (fn [req] (assert false)))]
(is (= 500 (:status response)))
(is (re-find #"prone-data" (:body response))))
(is (thrown? Error
(test-handler (fn [req] (throw (Error.)))))))
(deftest renders-debug-page-on-debug
(is (= 203 (:status ((wrap-exceptions (fn [req]
(debug "I need help")
{:status 200})) {})))))
(deftest excludes-unwanted-clients
(are [status headers] (= status (:status
((wrap-exceptions
(fn [req]
(debug "I need help")
{:status 200})
{:skip-prone? (fn [req]
(contains? (:headers req) "postman-token"))})
{:headers headers})))
200 {"postman-token" "PI:PASSWORD:<PASSWORD>END_PI"
"other" "value"}
203 {"random" "string"}
203 {}))
(defn async-test-handler [handler]
(let [response (atom nil)]
((wrap-exceptions handler {:print-stacktraces? false})
{}
(partial reset! response)
(fn []))
@response))
(deftest async-catches-exceptions-and-assertion-errors
(let [response (async-test-handler (fn [req respond raise]
(try
(/ 1 0)
(catch Exception e
(raise e)))))]
(is (= 500 (:status response)))
(is (re-find #"prone-data" (:body response))))
(let [response (async-test-handler (fn [req respond raise]
(/ 1 0)))]
(is (= 500 (:status response)))
(is (re-find #"prone-data" (:body response))))
(let [response (test-handler (fn [req respond raise]
(try
(assert false)
(catch AssertionError e
(raise e)))))]
(is (= 500 (:status response)))
(is (re-find #"prone-data" (:body response)))))
(deftest async-renders-debug-page-on-debug
(is (= 203
(-> (async-test-handler (fn [req respond raise]
(debug "I need help")
(respond {:status 200})))
:status))))
(deftest finds-application-name
(is (= 'prone (find-application-name-in-project-clj "(defproject prone ...)")))
(is (= 'parens-of-the-dead (find-application-name-in-project-clj "(defproject parens-of-the-dead ...)")))
(is (= 'prone (find-application-name-in-project-clj "
(defproject
prone ...)")))
(is (= nil (find-application-name-in-project-clj "(def prone ...)")))
(is (= nil (find-application-name-in-project-clj "(defprojectprone ...)"))))
|
[
{
"context": "messi #type:note\" :line 0}\n {:text \"#name:messi #type:person\" :line 1}])\n (is (= \"person\"\n ",
"end": 1772,
"score": 0.9695711135864258,
"start": 1767,
"tag": "NAME",
"value": "messi"
},
{
"context": " (= \"person\"\n (:type (d/find-first :name \"messi\")))))\n\n(deftest add-blank-node-is-ignored\n (sync",
"end": 1858,
"score": 0.9917948842048645,
"start": 1853,
"tag": "NAME",
"value": "messi"
},
{
"context": " [node])\n\n (let [existing (d/find-first :name \"fan\")]\n (sync updated-nodes)\n (is (= (nth u",
"end": 3250,
"score": 0.7807755470275879,
"start": 3247,
"tag": "NAME",
"value": "fan"
},
{
"context": " :line 0}])\n (let [existing (d/find-first :name \"messi\")]\n (sync [{:text \"rooting for #messi #type:no",
"end": 3555,
"score": 0.8481990098953247,
"start": 3550,
"tag": "NAME",
"value": "messi"
}
] | test/lt/plugins/kukui/sync_test.cljs | cldwalker/kukui | 0 | (ns lt.plugins.kukui.sync-test
(:require-macros [cemerick.cljs.test :refer [is deftest testing use-fixtures]])
(:require [lt.plugins.kukui.sync :as sync]
[lt.plugins.kukui.db :as db]
[lt.plugins.kukui.datascript :as d]
[lt.plugins.kukui.core :as kc]
[cemerick.cljs.test :as t]))
(use-fixtures :each (fn [f]
(sync/reset-sync!)
(f)))
(def default-file "/some/path")
(defn ->nodes [nodes file]
(->> nodes
kc/add-attributes-to-nodes
(mapv
#(assoc %
:file file
:indent (count (re-find #"^\s*" (:text %)))))))
(defn sync [nodes]
(sync/sync (->nodes nodes default-file) default-file))
;; Add
(deftest add-on-first-edit
(let [new-node {:text "drink coffee #type:td #food" :line 0}]
(sync [new-node])
(is (seq (d/q '[:find ?e
:in $ ?text
:where
[?e :text ?text]
[?e :tags ?tag]
[?tag :name "food"]]
(:text new-node))))))
(deftest add-on-second-edit
(let [nodes [{:text "drink chocolate #type:td" :line 0}]]
(sync nodes)
(sync (conj nodes {:text "drink coffee #type:td" :line 1})))
(is (= 2
(count (d/q '[:find ?e
:where [?e :text]])))))
(deftest add-with-tag-from-other-node
(sync [{:text "#name:some? #type:fn" :line 0}
{:text "such a great name #some? #type:td" :line 1}])
(is (seq (d/q '[:find ?e
:where
[?e :tags ?tag]
[?tag :name "some?"]]))))
(deftest named-entity-uses-last-type-in-sync
(sync [{:text "rooting for #messi #type:note" :line 0}
{:text "#name:messi #type:person" :line 1}])
(is (= "person"
(:type (d/find-first :name "messi")))))
(deftest add-blank-node-is-ignored
(sync [{:text " " :line 0}])
(is (empty? (d/q '[:find ?e :where [?e :line 0]])))
(is (seq (d/last-tx))
"Last-tx should reflect last actual transaction - not empty one"))
(deftest add-default-type-if-none-given
(sync [{:text "What is this?" :line 0}])
(is (= db/unknown-type
(:type (db/find-by-file-and-line default-file 0)))))
;; Delete
(deftest delete-text-line
(sync [{:text "drink chocolate #type:td" :line 0}])
(sync [{:text "drink coffee #type:td" :line 1}])
(is (= '(1)
(d/qf '[:find ?line
:where [?e :line ?line]]))))
;; Update
(deftest update-line
(let [node {:text "drink coffee #type:td" :line 0}
updated-nodes [{:text "drink chocolate #type:td" :line 0}
(assoc node :line 1)]]
(sync [node])
(let [existing (db/find-by-file-and-line default-file 0)]
(sync updated-nodes)
(is (= (nth updated-nodes 1)
(select-keys (d/entity (:db/id existing))
[:text :line]))))))
(deftest named-entity-updates-line-or-text
(let [node {:text "#name:fan blows oh so nicely #type:note" :line 0}
updated-nodes [{:text "#summer #type:note" :line 0}
(-> node (update-in [:text] #(str " " %)) (assoc :line 1))]]
(sync [node])
(let [existing (d/find-first :name "fan")]
(sync updated-nodes)
(is (= (nth updated-nodes 1)
(select-keys (d/entity (:db/id existing))
[:text :line]))))))
(deftest named-entity-updates-type
(sync [{:text "rooting for #messi #type:note" :line 0}])
(let [existing (d/find-first :name "messi")]
(sync [{:text "rooting for #messi #type:note" :line 0}
{:text "#name:messi #type:person" :line 1}])
(is (= "person"
(:type (d/entity (:db/id existing)))))))
(deftest url-entity-updates-type
(sync [{:text "nice tabs #type:note #url:youtab.me" :line 0}])
(let [existing (d/find-first :url "youtab.me")]
(sync [{:text "nice tabs #type:note #url:youtab.me" :line 0}
{:text "#url:youtab.me #type:wapp" :line 1}])
(is (= "wapp"
(:type (d/entity (:db/id existing)))))))
(deftest update-same-line-when-multiple-files
(sync [{:text "file 1 #type:td" :line 0}])
(sync/sync (->nodes [{:text "file 2 #type:td" :line 0}] "/another/path") "/another/path")
(sync [{:text "pre file 1 #type:td" :line 0}
{:text "file 1 #type:td" :line 1}])
(is (=
#{["/another/path" 0 "file 2 #type:td"]
["/some/path" 1 "file 1 #type:td"]
["/some/path" 0 "pre file 1 #type:td"]}
(d/q '[:find ?file ?line ?text
:where
[?e :file ?file]
[?e :text ?text]
[?e :line ?line]]))))
;; Query sync
(defn ->ent-id [m]
(d/transact! (sync/expand-tags (->nodes [m] default-file)))
(:db/id (d/find-first :text (:text m))))
(defn query-sync [& ents]
(map #(dissoc % :db/id :indent :tags)
(apply sync/query-sync ents)))
(deftest query-sync-updates
(testing "text without file update"
(is
(d/transact! [{:text " wow"}])
(when-let [id (:db/id (d/find-first :text " wow"))]
(and (empty? (sync/query-sync [{:id id :text "really wow"}]))
(= " really wow" (:text (d/entity id)))))))
(testing "text with file update"
(is
(let [node {:text " wowz" :line 0 :file default-file}]
(when-let [id (->ent-id node)]
(= (list (assoc node :text " really wowz"))
(query-sync [{:id id :text "really wowz"}]))))))
(testing "text with import file update"
(is
(let [node {:text " wowd"}]
(when-let [id (->ent-id node)]
(= (list {:text " really wowd" :update-type :append :file default-file})
(query-sync [{:id id :text "really wowd"}] default-file true))))))
(testing "text and tags"
(is
(when-let [id (->ent-id {:text "this #is #awesome" :line 0 :file default-file})]
(and
(= (list {:line 0 :file default-file :text "this #was #awesome"})
(query-sync [{:id id :text "this #was #awesome" :tags #{"was" "awesome"}}]
default-file true))
(= #{"was" "awesome"}
(->> (d/entity id) :tags (map (comp :name d/entity)) set))))))
(testing "desc attribute"
(is
(let [node {:text "oh the possibilities" :url "http://gifsound.com" :line 0 :file default-file}]
(when-let [id (->ent-id node)]
(= (list (assoc node :url "http://giphy.com"))
(query-sync [{:id id :text (:text node) :url "http://giphy.com"}]))))))
(testing "desc and preserves whitespace"
(is
(let [node {:text "jetblue" :line 0 :file default-file :desc [{:text " + decent leg room"}]}]
(when-let [id (->ent-id node)]
(= (list (assoc node :desc [{:text " + no wifi ya bastards"}]))
(query-sync [{:id id
:text " jetblue"
:desc [{:text " + no wifi ya bastards"}]}]))))))
(testing "except if no-text chars"
(is
(when-let [id (->ent-id {:text ""})]
(sync/query-sync [{:id id :text " ---"}])
(= "" (:text (d/entity id)))))))
(comment
(sync/reset-sync!)
(sync/sync [{:text "whoop" :type "td"}] "/ok/path")
(d/qe '[:find ?e
:where [?e]])
(d/transact! [{:db/id 3 :tags [2]}])
(d/entity 3)
(d/transact! [[:db/retract 3 :tags 2]])
(-> @sync/last-edits vals first)
(reset! sync/last-edits {})
(-> @d/reports last :tx-data (filter))
(:max-eid (:db-after (last @d/reports))))
| 44854 | (ns lt.plugins.kukui.sync-test
(:require-macros [cemerick.cljs.test :refer [is deftest testing use-fixtures]])
(:require [lt.plugins.kukui.sync :as sync]
[lt.plugins.kukui.db :as db]
[lt.plugins.kukui.datascript :as d]
[lt.plugins.kukui.core :as kc]
[cemerick.cljs.test :as t]))
(use-fixtures :each (fn [f]
(sync/reset-sync!)
(f)))
(def default-file "/some/path")
(defn ->nodes [nodes file]
(->> nodes
kc/add-attributes-to-nodes
(mapv
#(assoc %
:file file
:indent (count (re-find #"^\s*" (:text %)))))))
(defn sync [nodes]
(sync/sync (->nodes nodes default-file) default-file))
;; Add
(deftest add-on-first-edit
(let [new-node {:text "drink coffee #type:td #food" :line 0}]
(sync [new-node])
(is (seq (d/q '[:find ?e
:in $ ?text
:where
[?e :text ?text]
[?e :tags ?tag]
[?tag :name "food"]]
(:text new-node))))))
(deftest add-on-second-edit
(let [nodes [{:text "drink chocolate #type:td" :line 0}]]
(sync nodes)
(sync (conj nodes {:text "drink coffee #type:td" :line 1})))
(is (= 2
(count (d/q '[:find ?e
:where [?e :text]])))))
(deftest add-with-tag-from-other-node
(sync [{:text "#name:some? #type:fn" :line 0}
{:text "such a great name #some? #type:td" :line 1}])
(is (seq (d/q '[:find ?e
:where
[?e :tags ?tag]
[?tag :name "some?"]]))))
(deftest named-entity-uses-last-type-in-sync
(sync [{:text "rooting for #messi #type:note" :line 0}
{:text "#name:<NAME> #type:person" :line 1}])
(is (= "person"
(:type (d/find-first :name "<NAME>")))))
(deftest add-blank-node-is-ignored
(sync [{:text " " :line 0}])
(is (empty? (d/q '[:find ?e :where [?e :line 0]])))
(is (seq (d/last-tx))
"Last-tx should reflect last actual transaction - not empty one"))
(deftest add-default-type-if-none-given
(sync [{:text "What is this?" :line 0}])
(is (= db/unknown-type
(:type (db/find-by-file-and-line default-file 0)))))
;; Delete
(deftest delete-text-line
(sync [{:text "drink chocolate #type:td" :line 0}])
(sync [{:text "drink coffee #type:td" :line 1}])
(is (= '(1)
(d/qf '[:find ?line
:where [?e :line ?line]]))))
;; Update
(deftest update-line
(let [node {:text "drink coffee #type:td" :line 0}
updated-nodes [{:text "drink chocolate #type:td" :line 0}
(assoc node :line 1)]]
(sync [node])
(let [existing (db/find-by-file-and-line default-file 0)]
(sync updated-nodes)
(is (= (nth updated-nodes 1)
(select-keys (d/entity (:db/id existing))
[:text :line]))))))
(deftest named-entity-updates-line-or-text
(let [node {:text "#name:fan blows oh so nicely #type:note" :line 0}
updated-nodes [{:text "#summer #type:note" :line 0}
(-> node (update-in [:text] #(str " " %)) (assoc :line 1))]]
(sync [node])
(let [existing (d/find-first :name "<NAME>")]
(sync updated-nodes)
(is (= (nth updated-nodes 1)
(select-keys (d/entity (:db/id existing))
[:text :line]))))))
(deftest named-entity-updates-type
(sync [{:text "rooting for #messi #type:note" :line 0}])
(let [existing (d/find-first :name "<NAME>")]
(sync [{:text "rooting for #messi #type:note" :line 0}
{:text "#name:messi #type:person" :line 1}])
(is (= "person"
(:type (d/entity (:db/id existing)))))))
(deftest url-entity-updates-type
(sync [{:text "nice tabs #type:note #url:youtab.me" :line 0}])
(let [existing (d/find-first :url "youtab.me")]
(sync [{:text "nice tabs #type:note #url:youtab.me" :line 0}
{:text "#url:youtab.me #type:wapp" :line 1}])
(is (= "wapp"
(:type (d/entity (:db/id existing)))))))
(deftest update-same-line-when-multiple-files
(sync [{:text "file 1 #type:td" :line 0}])
(sync/sync (->nodes [{:text "file 2 #type:td" :line 0}] "/another/path") "/another/path")
(sync [{:text "pre file 1 #type:td" :line 0}
{:text "file 1 #type:td" :line 1}])
(is (=
#{["/another/path" 0 "file 2 #type:td"]
["/some/path" 1 "file 1 #type:td"]
["/some/path" 0 "pre file 1 #type:td"]}
(d/q '[:find ?file ?line ?text
:where
[?e :file ?file]
[?e :text ?text]
[?e :line ?line]]))))
;; Query sync
(defn ->ent-id [m]
(d/transact! (sync/expand-tags (->nodes [m] default-file)))
(:db/id (d/find-first :text (:text m))))
(defn query-sync [& ents]
(map #(dissoc % :db/id :indent :tags)
(apply sync/query-sync ents)))
(deftest query-sync-updates
(testing "text without file update"
(is
(d/transact! [{:text " wow"}])
(when-let [id (:db/id (d/find-first :text " wow"))]
(and (empty? (sync/query-sync [{:id id :text "really wow"}]))
(= " really wow" (:text (d/entity id)))))))
(testing "text with file update"
(is
(let [node {:text " wowz" :line 0 :file default-file}]
(when-let [id (->ent-id node)]
(= (list (assoc node :text " really wowz"))
(query-sync [{:id id :text "really wowz"}]))))))
(testing "text with import file update"
(is
(let [node {:text " wowd"}]
(when-let [id (->ent-id node)]
(= (list {:text " really wowd" :update-type :append :file default-file})
(query-sync [{:id id :text "really wowd"}] default-file true))))))
(testing "text and tags"
(is
(when-let [id (->ent-id {:text "this #is #awesome" :line 0 :file default-file})]
(and
(= (list {:line 0 :file default-file :text "this #was #awesome"})
(query-sync [{:id id :text "this #was #awesome" :tags #{"was" "awesome"}}]
default-file true))
(= #{"was" "awesome"}
(->> (d/entity id) :tags (map (comp :name d/entity)) set))))))
(testing "desc attribute"
(is
(let [node {:text "oh the possibilities" :url "http://gifsound.com" :line 0 :file default-file}]
(when-let [id (->ent-id node)]
(= (list (assoc node :url "http://giphy.com"))
(query-sync [{:id id :text (:text node) :url "http://giphy.com"}]))))))
(testing "desc and preserves whitespace"
(is
(let [node {:text "jetblue" :line 0 :file default-file :desc [{:text " + decent leg room"}]}]
(when-let [id (->ent-id node)]
(= (list (assoc node :desc [{:text " + no wifi ya bastards"}]))
(query-sync [{:id id
:text " jetblue"
:desc [{:text " + no wifi ya bastards"}]}]))))))
(testing "except if no-text chars"
(is
(when-let [id (->ent-id {:text ""})]
(sync/query-sync [{:id id :text " ---"}])
(= "" (:text (d/entity id)))))))
(comment
(sync/reset-sync!)
(sync/sync [{:text "whoop" :type "td"}] "/ok/path")
(d/qe '[:find ?e
:where [?e]])
(d/transact! [{:db/id 3 :tags [2]}])
(d/entity 3)
(d/transact! [[:db/retract 3 :tags 2]])
(-> @sync/last-edits vals first)
(reset! sync/last-edits {})
(-> @d/reports last :tx-data (filter))
(:max-eid (:db-after (last @d/reports))))
| true | (ns lt.plugins.kukui.sync-test
(:require-macros [cemerick.cljs.test :refer [is deftest testing use-fixtures]])
(:require [lt.plugins.kukui.sync :as sync]
[lt.plugins.kukui.db :as db]
[lt.plugins.kukui.datascript :as d]
[lt.plugins.kukui.core :as kc]
[cemerick.cljs.test :as t]))
(use-fixtures :each (fn [f]
(sync/reset-sync!)
(f)))
(def default-file "/some/path")
(defn ->nodes [nodes file]
(->> nodes
kc/add-attributes-to-nodes
(mapv
#(assoc %
:file file
:indent (count (re-find #"^\s*" (:text %)))))))
(defn sync [nodes]
(sync/sync (->nodes nodes default-file) default-file))
;; Add
(deftest add-on-first-edit
(let [new-node {:text "drink coffee #type:td #food" :line 0}]
(sync [new-node])
(is (seq (d/q '[:find ?e
:in $ ?text
:where
[?e :text ?text]
[?e :tags ?tag]
[?tag :name "food"]]
(:text new-node))))))
(deftest add-on-second-edit
(let [nodes [{:text "drink chocolate #type:td" :line 0}]]
(sync nodes)
(sync (conj nodes {:text "drink coffee #type:td" :line 1})))
(is (= 2
(count (d/q '[:find ?e
:where [?e :text]])))))
(deftest add-with-tag-from-other-node
(sync [{:text "#name:some? #type:fn" :line 0}
{:text "such a great name #some? #type:td" :line 1}])
(is (seq (d/q '[:find ?e
:where
[?e :tags ?tag]
[?tag :name "some?"]]))))
(deftest named-entity-uses-last-type-in-sync
(sync [{:text "rooting for #messi #type:note" :line 0}
{:text "#name:PI:NAME:<NAME>END_PI #type:person" :line 1}])
(is (= "person"
(:type (d/find-first :name "PI:NAME:<NAME>END_PI")))))
(deftest add-blank-node-is-ignored
(sync [{:text " " :line 0}])
(is (empty? (d/q '[:find ?e :where [?e :line 0]])))
(is (seq (d/last-tx))
"Last-tx should reflect last actual transaction - not empty one"))
(deftest add-default-type-if-none-given
(sync [{:text "What is this?" :line 0}])
(is (= db/unknown-type
(:type (db/find-by-file-and-line default-file 0)))))
;; Delete
(deftest delete-text-line
(sync [{:text "drink chocolate #type:td" :line 0}])
(sync [{:text "drink coffee #type:td" :line 1}])
(is (= '(1)
(d/qf '[:find ?line
:where [?e :line ?line]]))))
;; Update
(deftest update-line
(let [node {:text "drink coffee #type:td" :line 0}
updated-nodes [{:text "drink chocolate #type:td" :line 0}
(assoc node :line 1)]]
(sync [node])
(let [existing (db/find-by-file-and-line default-file 0)]
(sync updated-nodes)
(is (= (nth updated-nodes 1)
(select-keys (d/entity (:db/id existing))
[:text :line]))))))
(deftest named-entity-updates-line-or-text
(let [node {:text "#name:fan blows oh so nicely #type:note" :line 0}
updated-nodes [{:text "#summer #type:note" :line 0}
(-> node (update-in [:text] #(str " " %)) (assoc :line 1))]]
(sync [node])
(let [existing (d/find-first :name "PI:NAME:<NAME>END_PI")]
(sync updated-nodes)
(is (= (nth updated-nodes 1)
(select-keys (d/entity (:db/id existing))
[:text :line]))))))
(deftest named-entity-updates-type
(sync [{:text "rooting for #messi #type:note" :line 0}])
(let [existing (d/find-first :name "PI:NAME:<NAME>END_PI")]
(sync [{:text "rooting for #messi #type:note" :line 0}
{:text "#name:messi #type:person" :line 1}])
(is (= "person"
(:type (d/entity (:db/id existing)))))))
(deftest url-entity-updates-type
(sync [{:text "nice tabs #type:note #url:youtab.me" :line 0}])
(let [existing (d/find-first :url "youtab.me")]
(sync [{:text "nice tabs #type:note #url:youtab.me" :line 0}
{:text "#url:youtab.me #type:wapp" :line 1}])
(is (= "wapp"
(:type (d/entity (:db/id existing)))))))
(deftest update-same-line-when-multiple-files
(sync [{:text "file 1 #type:td" :line 0}])
(sync/sync (->nodes [{:text "file 2 #type:td" :line 0}] "/another/path") "/another/path")
(sync [{:text "pre file 1 #type:td" :line 0}
{:text "file 1 #type:td" :line 1}])
(is (=
#{["/another/path" 0 "file 2 #type:td"]
["/some/path" 1 "file 1 #type:td"]
["/some/path" 0 "pre file 1 #type:td"]}
(d/q '[:find ?file ?line ?text
:where
[?e :file ?file]
[?e :text ?text]
[?e :line ?line]]))))
;; Query sync
(defn ->ent-id [m]
(d/transact! (sync/expand-tags (->nodes [m] default-file)))
(:db/id (d/find-first :text (:text m))))
(defn query-sync [& ents]
(map #(dissoc % :db/id :indent :tags)
(apply sync/query-sync ents)))
(deftest query-sync-updates
(testing "text without file update"
(is
(d/transact! [{:text " wow"}])
(when-let [id (:db/id (d/find-first :text " wow"))]
(and (empty? (sync/query-sync [{:id id :text "really wow"}]))
(= " really wow" (:text (d/entity id)))))))
(testing "text with file update"
(is
(let [node {:text " wowz" :line 0 :file default-file}]
(when-let [id (->ent-id node)]
(= (list (assoc node :text " really wowz"))
(query-sync [{:id id :text "really wowz"}]))))))
(testing "text with import file update"
(is
(let [node {:text " wowd"}]
(when-let [id (->ent-id node)]
(= (list {:text " really wowd" :update-type :append :file default-file})
(query-sync [{:id id :text "really wowd"}] default-file true))))))
(testing "text and tags"
(is
(when-let [id (->ent-id {:text "this #is #awesome" :line 0 :file default-file})]
(and
(= (list {:line 0 :file default-file :text "this #was #awesome"})
(query-sync [{:id id :text "this #was #awesome" :tags #{"was" "awesome"}}]
default-file true))
(= #{"was" "awesome"}
(->> (d/entity id) :tags (map (comp :name d/entity)) set))))))
(testing "desc attribute"
(is
(let [node {:text "oh the possibilities" :url "http://gifsound.com" :line 0 :file default-file}]
(when-let [id (->ent-id node)]
(= (list (assoc node :url "http://giphy.com"))
(query-sync [{:id id :text (:text node) :url "http://giphy.com"}]))))))
(testing "desc and preserves whitespace"
(is
(let [node {:text "jetblue" :line 0 :file default-file :desc [{:text " + decent leg room"}]}]
(when-let [id (->ent-id node)]
(= (list (assoc node :desc [{:text " + no wifi ya bastards"}]))
(query-sync [{:id id
:text " jetblue"
:desc [{:text " + no wifi ya bastards"}]}]))))))
(testing "except if no-text chars"
(is
(when-let [id (->ent-id {:text ""})]
(sync/query-sync [{:id id :text " ---"}])
(= "" (:text (d/entity id)))))))
(comment
(sync/reset-sync!)
(sync/sync [{:text "whoop" :type "td"}] "/ok/path")
(d/qe '[:find ?e
:where [?e]])
(d/transact! [{:db/id 3 :tags [2]}])
(d/entity 3)
(d/transact! [[:db/retract 3 :tags 2]])
(-> @sync/last-edits vals first)
(reset! sync/last-edits {})
(-> @d/reports last :tx-data (filter))
(:max-eid (:db-after (last @d/reports))))
|
[
{
"context": ";; Ben Fry's Visualizing Data, Chapter 6 zipcode scatterplot, ",
"end": 12,
"score": 0.9961156845092773,
"start": 3,
"tag": "NAME",
"value": "Ben Fry's"
},
{
"context": "erted from Processing to Clojure as an exercise by Dave Liepmann\n\n(ns vdquil.chapter6.zoom-animated\n (:use [quil.",
"end": 152,
"score": 0.9998592138290405,
"start": 139,
"tag": "NAME",
"value": "Dave Liepmann"
},
{
"context": "bounds-queue midpoints))))\n\n(def deletion-key? #{\\backspace}) ;; TODO test this key on a Windows machine\n(def",
"end": 8790,
"score": 0.6216570138931274,
"start": 8781,
"tag": "KEY",
"value": "backspace"
}
] | src/vdquil/chapter6/zoom-animated.clj | Jjunior130/vdquil | 33 | ;; Ben Fry's Visualizing Data, Chapter 6 zipcode scatterplot, with animated zoom
;; Converted from Processing to Clojure as an exercise by Dave Liepmann
(ns vdquil.chapter6.zoom-animated
(:use [quil.core]
[vdquil.util])
(:require [clojure.string :as string]))
;; Test cases: 48529, 91110, 12561,
;; 98350 (northernmost and westernmost, but not uppermost), 33040 (southernmost)
;; 04652 (easternmost), 95456 (leftmost), 98281 (uppermost)
;; 59544 and 33242 (both marked as problematic in Processing source)
(def canvas-height 453)
(def canvas-width 720)
(def aspect-ratio (/ canvas-width canvas-height))
(def x-min 30)
(def x-max (- canvas-width x-min))
(def y-max 20)
(def y-min (- canvas-height y-max))
(def typed-chars (atom ""))
(def zoom-enabled (atom false))
(def palette (atom {}))
(def matched-zips (atom ()))
;; constants pulled from 1st line of data:
(def bounds-queue
(atom [[0.4181981 0.87044954 -0.3668288878807947 0.3519813478807947]]))
(defn create-zip
"Given a line of zipcode data, create a zipcode data structure"
[data]
(let [[zip longitude latitude desc] (string/split data #"\t")]
{:zip zip :longitude (read-string longitude)
:latitude (read-string latitude) :desc desc}))
(def zip-trie (reduce (fn [acc line]
(let [zip (create-zip line)]
(assoc-in acc (vec (:zip zip)) zip)))
{}
(string/split-lines (slurp "data/zips-modified.tsv"))))
(defn zipcodes-from-trie
"Return a vector of all child zipcodes in `trie`."
[trie]
(into [] (filter :zip (tree-seq (comp char? first keys) vals trie))))
(defn setup []
(frame-rate 20)
(text-font (load-font "ScalaSans-Regular-14.vlw"))
(text-mode :screen)
(no-stroke)
(text-align :left)
(reset! palette {:dormant (hex-to-color "#999966")
:highlight (hex-to-color "#CBCBCB")
:unhighlight (hex-to-color "#66664C")
:bad (hex-to-color "#FFFF66")}))
(defn draw-instructions
"Tell the user how to use the interface"
[clr]
(text-align :left)
(fill clr)
(if (= @typed-chars "")
(text "type the digits of a zip code" 40 (- canvas-height 40))
(text @typed-chars 40 (- canvas-height 40)))
(text-align :right)
(fill (if @zoom-enabled
(@palette :highlight)
(@palette :unhighlight)))
(text "zoom" (- canvas-width 40) (- canvas-height 40)))
(defn draw-zip-detail
"Highlight a single zip code by showing its information"
[zip zip-desc x y]
(no-stroke)
(fill (@palette :highlight))
(let [size (if @zoom-enabled 6 4)] (rect x y size size))
(text-align :center)
(text (str zip-desc ", " zip)
(if (> x (/ canvas-width 3))
(- x (+ 8 (text-width zip)))
(+ x (text-width zip) 8))
(- y 4)))
(defn calc-bounds
"Calculate bounding box of `zips`, a sequence of lat/long-containing maps."
[zips]
(reduce (fn [[min-lat max-lat min-long max-long] {:keys [longitude latitude]}]
(vector (min min-lat latitude) (max max-lat latitude)
(min min-long longitude) (max max-long longitude)))
[Float/MAX_VALUE (- Float/MAX_VALUE) Float/MAX_VALUE (- Float/MAX_VALUE)]
zips))
;; NB: though one would think that we could check only
;; (empty? (zipcodes-from-trie (get-in trie partial-zip)))
;; ...this is not the case. To see why, consider:
;; (pprint (zipcodes-from-trie (get-in zip-trie (vec "901"))))
;; Sets of urban zips often have *identical* coordinates.
(defn find-bounds
"Find the appropriate bounding box for the zipcodes matching `partial-zip`."
[partial-zip trie]
(let [b (calc-bounds (zipcodes-from-trie (get-in trie partial-zip)))]
(if (and (seq partial-zip)
(or (= (first b) (second b))
(= (nth b 2) (last b))
(= (first b) (nth b 2))
(= (second b) (last b))))
(find-bounds (butlast partial-zip) trie)
b)))
(defn preserve-aspect-ratio
"Adjusts one dimension of `bounding-box` to preserve
`aspect-ratio`. Returns a map describing the outer bounds."
[[min-lat max-lat min-long max-long] aspect-ratio]
(let [bounds-aspect (/ (- max-long min-long) (- max-lat min-lat))]
(cond (> bounds-aspect aspect-ratio)
(let [mid-lat (/ (+ max-lat min-lat) 2)
span-lat (* (/ (- max-long min-long)
canvas-width) canvas-height)]
[(- mid-lat (/ span-lat 2)) (+ mid-lat (/ span-lat 2))
min-long max-long])
(< bounds-aspect aspect-ratio)
(let [mid-long (/ (+ max-long min-long) 2)
span-long (* (/ (- max-lat min-lat)
canvas-height) canvas-width)]
[min-lat max-lat
(- mid-long (/ span-long 2)) (+ mid-long (/ span-long 2))])
:else [min-lat max-lat min-long max-long])))
(defn lat-long-to-point
"Returns a vector containing the on-screen x/y position of this
point's latitude/longitude based on the supplied bounds."
[{:keys [longitude latitude]} [min-lat max-lat min-long max-long]]
(vector (map-range longitude min-long max-long 30 (- canvas-width 30))
(map-range latitude min-lat max-lat (- canvas-height 20) 20)))
(defn render-zips
"Render `zips` within `bounds` using `color`."
[zips bounds color]
(doseq [zip zips]
(let [[x y] (lat-long-to-point zip bounds)]
(set-pixel x y color))))
;; Grabbed from clojure.core.incubator
;; https://github.com/clojure/core.incubator/blob/master/src/main/clojure/clojure/core/incubator.clj#L56
(defn dissoc-in
"Dissociates an entry from a nested associative structure returning a new
nested structure. keys is a sequence of keys. Any empty maps that result
will not be present in the new structure."
[m [k & ks :as keys]]
(if ks
(if-let [nextmap (get m k)]
(let [newmap (dissoc-in nextmap ks)]
(if (seq newmap)
(assoc m k newmap)
(dissoc m k)))
m)
(dissoc m k)))
(defn center-on-zip
"Adjusts all dimensions of `bounding-box` to center on `chosen-zip`.
Returns a map describing the outer bounds."
[chosen-zip [min-lat max-lat min-long max-long]]
(let [span-lat (- max-lat min-lat)
span-long (- max-long min-long)]
[(- (chosen-zip :latitude) (/ span-lat 2))
(+ (chosen-zip :latitude) (/ span-lat 2))
(- (chosen-zip :longitude) (/ span-long 2))
(+ (chosen-zip :longitude) (/ span-long 2))]))
(defn draw-zips
"Given 0-5 digits, draw a map of matching zipcodes, highlighting matches"
[inputted-zip bounds]
(let [partial-zip (vec inputted-zip)
unmatched-zips (zipcodes-from-trie (dissoc-in zip-trie partial-zip))]
(if (empty? inputted-zip)
(render-zips unmatched-zips bounds (@palette :dormant))
(do (render-zips unmatched-zips bounds (@palette :unhighlight))
(render-zips @matched-zips bounds (@palette :highlight))))
(when (and (= 5 (count partial-zip)) (= 1 (count @matched-zips)))
(let [exact-match (first @matched-zips)
[x y] (lat-long-to-point exact-match bounds)]
(draw-zip-detail (exact-match :zip) (exact-match :desc) x y)))
(draw-instructions (if (and (empty? @matched-zips) (seq inputted-zip))
(@palette :bad) (@palette :highlight)))))
(defn draw []
(background (hex-to-color "#333333"))
(draw-zips @typed-chars (first @bounds-queue))
(if (> (count @bounds-queue) 1)
(swap! bounds-queue #(vec (rest %)))))
(defn load-bounds-queue
"Populate `@bounds-queue` with midpoint bounds on the way to
calculated destination `bounds`"
[]
(let [partial-zip (vec @typed-chars)
zip-matches (if (empty? partial-zip) []
(zipcodes-from-trie (get-in zip-trie partial-zip)))
bounds (preserve-aspect-ratio
(cond (not @zoom-enabled)
(calc-bounds (zipcodes-from-trie zip-trie))
(empty? zip-matches)
(find-bounds (butlast partial-zip) zip-trie)
(= 1 (count zip-matches))
(center-on-zip (first zip-matches)
(find-bounds partial-zip zip-trie))
:else (find-bounds partial-zip zip-trie))
aspect-ratio)
start (last @bounds-queue)
stop bounds
;; TODO choose better easing method -- linear is jarring.
midpoints (mapv (fn [step] (map #(lerp %1 %2 step) start stop))
(range 1/10 11/10 1/10))]
(reset! matched-zips zip-matches)
(when (not= start stop)
(reset! bounds-queue midpoints))))
(def deletion-key? #{\backspace}) ;; TODO test this key on a Windows machine
(def number-key? (set (map char (range 48 58))))
(defn key-handler
"Manage keyboard input of 0 to 5 digits"
[]
(let [key (if (= processing.core.PConstants/CODED (int (raw-key)))
(key-code) (raw-key))]
(cond (and (deletion-key? key) (> (count @typed-chars) 0))
(swap! typed-chars #(apply str (butlast %)))
(and (number-key? key) (< (count @typed-chars) 5))
(swap! typed-chars #(str % key))))
(load-bounds-queue))
(defn toggle-zoom []
(when (and (< (mouse-x) (- canvas-width 35))
(> (mouse-x) (- canvas-width 45 (text-width "zoom")))
(> (- canvas-height 30) (mouse-y) (- canvas-height 55)))
(reset! zoom-enabled (not @zoom-enabled))
(load-bounds-queue)))
(defsketch zips
:title "Zip codes with animated zooming"
:setup setup
:draw draw
:size [canvas-width canvas-height]
:renderer :p2d
:key-pressed key-handler
:mouse-released toggle-zoom)
| 104526 | ;; <NAME> Visualizing Data, Chapter 6 zipcode scatterplot, with animated zoom
;; Converted from Processing to Clojure as an exercise by <NAME>
(ns vdquil.chapter6.zoom-animated
(:use [quil.core]
[vdquil.util])
(:require [clojure.string :as string]))
;; Test cases: 48529, 91110, 12561,
;; 98350 (northernmost and westernmost, but not uppermost), 33040 (southernmost)
;; 04652 (easternmost), 95456 (leftmost), 98281 (uppermost)
;; 59544 and 33242 (both marked as problematic in Processing source)
(def canvas-height 453)
(def canvas-width 720)
(def aspect-ratio (/ canvas-width canvas-height))
(def x-min 30)
(def x-max (- canvas-width x-min))
(def y-max 20)
(def y-min (- canvas-height y-max))
(def typed-chars (atom ""))
(def zoom-enabled (atom false))
(def palette (atom {}))
(def matched-zips (atom ()))
;; constants pulled from 1st line of data:
(def bounds-queue
(atom [[0.4181981 0.87044954 -0.3668288878807947 0.3519813478807947]]))
(defn create-zip
"Given a line of zipcode data, create a zipcode data structure"
[data]
(let [[zip longitude latitude desc] (string/split data #"\t")]
{:zip zip :longitude (read-string longitude)
:latitude (read-string latitude) :desc desc}))
(def zip-trie (reduce (fn [acc line]
(let [zip (create-zip line)]
(assoc-in acc (vec (:zip zip)) zip)))
{}
(string/split-lines (slurp "data/zips-modified.tsv"))))
(defn zipcodes-from-trie
"Return a vector of all child zipcodes in `trie`."
[trie]
(into [] (filter :zip (tree-seq (comp char? first keys) vals trie))))
(defn setup []
(frame-rate 20)
(text-font (load-font "ScalaSans-Regular-14.vlw"))
(text-mode :screen)
(no-stroke)
(text-align :left)
(reset! palette {:dormant (hex-to-color "#999966")
:highlight (hex-to-color "#CBCBCB")
:unhighlight (hex-to-color "#66664C")
:bad (hex-to-color "#FFFF66")}))
(defn draw-instructions
"Tell the user how to use the interface"
[clr]
(text-align :left)
(fill clr)
(if (= @typed-chars "")
(text "type the digits of a zip code" 40 (- canvas-height 40))
(text @typed-chars 40 (- canvas-height 40)))
(text-align :right)
(fill (if @zoom-enabled
(@palette :highlight)
(@palette :unhighlight)))
(text "zoom" (- canvas-width 40) (- canvas-height 40)))
(defn draw-zip-detail
"Highlight a single zip code by showing its information"
[zip zip-desc x y]
(no-stroke)
(fill (@palette :highlight))
(let [size (if @zoom-enabled 6 4)] (rect x y size size))
(text-align :center)
(text (str zip-desc ", " zip)
(if (> x (/ canvas-width 3))
(- x (+ 8 (text-width zip)))
(+ x (text-width zip) 8))
(- y 4)))
(defn calc-bounds
"Calculate bounding box of `zips`, a sequence of lat/long-containing maps."
[zips]
(reduce (fn [[min-lat max-lat min-long max-long] {:keys [longitude latitude]}]
(vector (min min-lat latitude) (max max-lat latitude)
(min min-long longitude) (max max-long longitude)))
[Float/MAX_VALUE (- Float/MAX_VALUE) Float/MAX_VALUE (- Float/MAX_VALUE)]
zips))
;; NB: though one would think that we could check only
;; (empty? (zipcodes-from-trie (get-in trie partial-zip)))
;; ...this is not the case. To see why, consider:
;; (pprint (zipcodes-from-trie (get-in zip-trie (vec "901"))))
;; Sets of urban zips often have *identical* coordinates.
(defn find-bounds
"Find the appropriate bounding box for the zipcodes matching `partial-zip`."
[partial-zip trie]
(let [b (calc-bounds (zipcodes-from-trie (get-in trie partial-zip)))]
(if (and (seq partial-zip)
(or (= (first b) (second b))
(= (nth b 2) (last b))
(= (first b) (nth b 2))
(= (second b) (last b))))
(find-bounds (butlast partial-zip) trie)
b)))
(defn preserve-aspect-ratio
"Adjusts one dimension of `bounding-box` to preserve
`aspect-ratio`. Returns a map describing the outer bounds."
[[min-lat max-lat min-long max-long] aspect-ratio]
(let [bounds-aspect (/ (- max-long min-long) (- max-lat min-lat))]
(cond (> bounds-aspect aspect-ratio)
(let [mid-lat (/ (+ max-lat min-lat) 2)
span-lat (* (/ (- max-long min-long)
canvas-width) canvas-height)]
[(- mid-lat (/ span-lat 2)) (+ mid-lat (/ span-lat 2))
min-long max-long])
(< bounds-aspect aspect-ratio)
(let [mid-long (/ (+ max-long min-long) 2)
span-long (* (/ (- max-lat min-lat)
canvas-height) canvas-width)]
[min-lat max-lat
(- mid-long (/ span-long 2)) (+ mid-long (/ span-long 2))])
:else [min-lat max-lat min-long max-long])))
(defn lat-long-to-point
"Returns a vector containing the on-screen x/y position of this
point's latitude/longitude based on the supplied bounds."
[{:keys [longitude latitude]} [min-lat max-lat min-long max-long]]
(vector (map-range longitude min-long max-long 30 (- canvas-width 30))
(map-range latitude min-lat max-lat (- canvas-height 20) 20)))
(defn render-zips
"Render `zips` within `bounds` using `color`."
[zips bounds color]
(doseq [zip zips]
(let [[x y] (lat-long-to-point zip bounds)]
(set-pixel x y color))))
;; Grabbed from clojure.core.incubator
;; https://github.com/clojure/core.incubator/blob/master/src/main/clojure/clojure/core/incubator.clj#L56
(defn dissoc-in
"Dissociates an entry from a nested associative structure returning a new
nested structure. keys is a sequence of keys. Any empty maps that result
will not be present in the new structure."
[m [k & ks :as keys]]
(if ks
(if-let [nextmap (get m k)]
(let [newmap (dissoc-in nextmap ks)]
(if (seq newmap)
(assoc m k newmap)
(dissoc m k)))
m)
(dissoc m k)))
(defn center-on-zip
"Adjusts all dimensions of `bounding-box` to center on `chosen-zip`.
Returns a map describing the outer bounds."
[chosen-zip [min-lat max-lat min-long max-long]]
(let [span-lat (- max-lat min-lat)
span-long (- max-long min-long)]
[(- (chosen-zip :latitude) (/ span-lat 2))
(+ (chosen-zip :latitude) (/ span-lat 2))
(- (chosen-zip :longitude) (/ span-long 2))
(+ (chosen-zip :longitude) (/ span-long 2))]))
(defn draw-zips
"Given 0-5 digits, draw a map of matching zipcodes, highlighting matches"
[inputted-zip bounds]
(let [partial-zip (vec inputted-zip)
unmatched-zips (zipcodes-from-trie (dissoc-in zip-trie partial-zip))]
(if (empty? inputted-zip)
(render-zips unmatched-zips bounds (@palette :dormant))
(do (render-zips unmatched-zips bounds (@palette :unhighlight))
(render-zips @matched-zips bounds (@palette :highlight))))
(when (and (= 5 (count partial-zip)) (= 1 (count @matched-zips)))
(let [exact-match (first @matched-zips)
[x y] (lat-long-to-point exact-match bounds)]
(draw-zip-detail (exact-match :zip) (exact-match :desc) x y)))
(draw-instructions (if (and (empty? @matched-zips) (seq inputted-zip))
(@palette :bad) (@palette :highlight)))))
(defn draw []
(background (hex-to-color "#333333"))
(draw-zips @typed-chars (first @bounds-queue))
(if (> (count @bounds-queue) 1)
(swap! bounds-queue #(vec (rest %)))))
(defn load-bounds-queue
"Populate `@bounds-queue` with midpoint bounds on the way to
calculated destination `bounds`"
[]
(let [partial-zip (vec @typed-chars)
zip-matches (if (empty? partial-zip) []
(zipcodes-from-trie (get-in zip-trie partial-zip)))
bounds (preserve-aspect-ratio
(cond (not @zoom-enabled)
(calc-bounds (zipcodes-from-trie zip-trie))
(empty? zip-matches)
(find-bounds (butlast partial-zip) zip-trie)
(= 1 (count zip-matches))
(center-on-zip (first zip-matches)
(find-bounds partial-zip zip-trie))
:else (find-bounds partial-zip zip-trie))
aspect-ratio)
start (last @bounds-queue)
stop bounds
;; TODO choose better easing method -- linear is jarring.
midpoints (mapv (fn [step] (map #(lerp %1 %2 step) start stop))
(range 1/10 11/10 1/10))]
(reset! matched-zips zip-matches)
(when (not= start stop)
(reset! bounds-queue midpoints))))
(def deletion-key? #{\<KEY>}) ;; TODO test this key on a Windows machine
(def number-key? (set (map char (range 48 58))))
(defn key-handler
"Manage keyboard input of 0 to 5 digits"
[]
(let [key (if (= processing.core.PConstants/CODED (int (raw-key)))
(key-code) (raw-key))]
(cond (and (deletion-key? key) (> (count @typed-chars) 0))
(swap! typed-chars #(apply str (butlast %)))
(and (number-key? key) (< (count @typed-chars) 5))
(swap! typed-chars #(str % key))))
(load-bounds-queue))
(defn toggle-zoom []
(when (and (< (mouse-x) (- canvas-width 35))
(> (mouse-x) (- canvas-width 45 (text-width "zoom")))
(> (- canvas-height 30) (mouse-y) (- canvas-height 55)))
(reset! zoom-enabled (not @zoom-enabled))
(load-bounds-queue)))
(defsketch zips
:title "Zip codes with animated zooming"
:setup setup
:draw draw
:size [canvas-width canvas-height]
:renderer :p2d
:key-pressed key-handler
:mouse-released toggle-zoom)
| true | ;; PI:NAME:<NAME>END_PI Visualizing Data, Chapter 6 zipcode scatterplot, with animated zoom
;; Converted from Processing to Clojure as an exercise by PI:NAME:<NAME>END_PI
(ns vdquil.chapter6.zoom-animated
(:use [quil.core]
[vdquil.util])
(:require [clojure.string :as string]))
;; Test cases: 48529, 91110, 12561,
;; 98350 (northernmost and westernmost, but not uppermost), 33040 (southernmost)
;; 04652 (easternmost), 95456 (leftmost), 98281 (uppermost)
;; 59544 and 33242 (both marked as problematic in Processing source)
(def canvas-height 453)
(def canvas-width 720)
(def aspect-ratio (/ canvas-width canvas-height))
(def x-min 30)
(def x-max (- canvas-width x-min))
(def y-max 20)
(def y-min (- canvas-height y-max))
(def typed-chars (atom ""))
(def zoom-enabled (atom false))
(def palette (atom {}))
(def matched-zips (atom ()))
;; constants pulled from 1st line of data:
(def bounds-queue
(atom [[0.4181981 0.87044954 -0.3668288878807947 0.3519813478807947]]))
(defn create-zip
"Given a line of zipcode data, create a zipcode data structure"
[data]
(let [[zip longitude latitude desc] (string/split data #"\t")]
{:zip zip :longitude (read-string longitude)
:latitude (read-string latitude) :desc desc}))
(def zip-trie (reduce (fn [acc line]
(let [zip (create-zip line)]
(assoc-in acc (vec (:zip zip)) zip)))
{}
(string/split-lines (slurp "data/zips-modified.tsv"))))
(defn zipcodes-from-trie
"Return a vector of all child zipcodes in `trie`."
[trie]
(into [] (filter :zip (tree-seq (comp char? first keys) vals trie))))
(defn setup []
(frame-rate 20)
(text-font (load-font "ScalaSans-Regular-14.vlw"))
(text-mode :screen)
(no-stroke)
(text-align :left)
(reset! palette {:dormant (hex-to-color "#999966")
:highlight (hex-to-color "#CBCBCB")
:unhighlight (hex-to-color "#66664C")
:bad (hex-to-color "#FFFF66")}))
(defn draw-instructions
"Tell the user how to use the interface"
[clr]
(text-align :left)
(fill clr)
(if (= @typed-chars "")
(text "type the digits of a zip code" 40 (- canvas-height 40))
(text @typed-chars 40 (- canvas-height 40)))
(text-align :right)
(fill (if @zoom-enabled
(@palette :highlight)
(@palette :unhighlight)))
(text "zoom" (- canvas-width 40) (- canvas-height 40)))
(defn draw-zip-detail
"Highlight a single zip code by showing its information"
[zip zip-desc x y]
(no-stroke)
(fill (@palette :highlight))
(let [size (if @zoom-enabled 6 4)] (rect x y size size))
(text-align :center)
(text (str zip-desc ", " zip)
(if (> x (/ canvas-width 3))
(- x (+ 8 (text-width zip)))
(+ x (text-width zip) 8))
(- y 4)))
(defn calc-bounds
"Calculate bounding box of `zips`, a sequence of lat/long-containing maps."
[zips]
(reduce (fn [[min-lat max-lat min-long max-long] {:keys [longitude latitude]}]
(vector (min min-lat latitude) (max max-lat latitude)
(min min-long longitude) (max max-long longitude)))
[Float/MAX_VALUE (- Float/MAX_VALUE) Float/MAX_VALUE (- Float/MAX_VALUE)]
zips))
;; NB: though one would think that we could check only
;; (empty? (zipcodes-from-trie (get-in trie partial-zip)))
;; ...this is not the case. To see why, consider:
;; (pprint (zipcodes-from-trie (get-in zip-trie (vec "901"))))
;; Sets of urban zips often have *identical* coordinates.
(defn find-bounds
"Find the appropriate bounding box for the zipcodes matching `partial-zip`."
[partial-zip trie]
(let [b (calc-bounds (zipcodes-from-trie (get-in trie partial-zip)))]
(if (and (seq partial-zip)
(or (= (first b) (second b))
(= (nth b 2) (last b))
(= (first b) (nth b 2))
(= (second b) (last b))))
(find-bounds (butlast partial-zip) trie)
b)))
(defn preserve-aspect-ratio
"Adjusts one dimension of `bounding-box` to preserve
`aspect-ratio`. Returns a map describing the outer bounds."
[[min-lat max-lat min-long max-long] aspect-ratio]
(let [bounds-aspect (/ (- max-long min-long) (- max-lat min-lat))]
(cond (> bounds-aspect aspect-ratio)
(let [mid-lat (/ (+ max-lat min-lat) 2)
span-lat (* (/ (- max-long min-long)
canvas-width) canvas-height)]
[(- mid-lat (/ span-lat 2)) (+ mid-lat (/ span-lat 2))
min-long max-long])
(< bounds-aspect aspect-ratio)
(let [mid-long (/ (+ max-long min-long) 2)
span-long (* (/ (- max-lat min-lat)
canvas-height) canvas-width)]
[min-lat max-lat
(- mid-long (/ span-long 2)) (+ mid-long (/ span-long 2))])
:else [min-lat max-lat min-long max-long])))
(defn lat-long-to-point
"Returns a vector containing the on-screen x/y position of this
point's latitude/longitude based on the supplied bounds."
[{:keys [longitude latitude]} [min-lat max-lat min-long max-long]]
(vector (map-range longitude min-long max-long 30 (- canvas-width 30))
(map-range latitude min-lat max-lat (- canvas-height 20) 20)))
(defn render-zips
"Render `zips` within `bounds` using `color`."
[zips bounds color]
(doseq [zip zips]
(let [[x y] (lat-long-to-point zip bounds)]
(set-pixel x y color))))
;; Grabbed from clojure.core.incubator
;; https://github.com/clojure/core.incubator/blob/master/src/main/clojure/clojure/core/incubator.clj#L56
(defn dissoc-in
"Dissociates an entry from a nested associative structure returning a new
nested structure. keys is a sequence of keys. Any empty maps that result
will not be present in the new structure."
[m [k & ks :as keys]]
(if ks
(if-let [nextmap (get m k)]
(let [newmap (dissoc-in nextmap ks)]
(if (seq newmap)
(assoc m k newmap)
(dissoc m k)))
m)
(dissoc m k)))
(defn center-on-zip
"Adjusts all dimensions of `bounding-box` to center on `chosen-zip`.
Returns a map describing the outer bounds."
[chosen-zip [min-lat max-lat min-long max-long]]
(let [span-lat (- max-lat min-lat)
span-long (- max-long min-long)]
[(- (chosen-zip :latitude) (/ span-lat 2))
(+ (chosen-zip :latitude) (/ span-lat 2))
(- (chosen-zip :longitude) (/ span-long 2))
(+ (chosen-zip :longitude) (/ span-long 2))]))
(defn draw-zips
"Given 0-5 digits, draw a map of matching zipcodes, highlighting matches"
[inputted-zip bounds]
(let [partial-zip (vec inputted-zip)
unmatched-zips (zipcodes-from-trie (dissoc-in zip-trie partial-zip))]
(if (empty? inputted-zip)
(render-zips unmatched-zips bounds (@palette :dormant))
(do (render-zips unmatched-zips bounds (@palette :unhighlight))
(render-zips @matched-zips bounds (@palette :highlight))))
(when (and (= 5 (count partial-zip)) (= 1 (count @matched-zips)))
(let [exact-match (first @matched-zips)
[x y] (lat-long-to-point exact-match bounds)]
(draw-zip-detail (exact-match :zip) (exact-match :desc) x y)))
(draw-instructions (if (and (empty? @matched-zips) (seq inputted-zip))
(@palette :bad) (@palette :highlight)))))
(defn draw []
(background (hex-to-color "#333333"))
(draw-zips @typed-chars (first @bounds-queue))
(if (> (count @bounds-queue) 1)
(swap! bounds-queue #(vec (rest %)))))
(defn load-bounds-queue
"Populate `@bounds-queue` with midpoint bounds on the way to
calculated destination `bounds`"
[]
(let [partial-zip (vec @typed-chars)
zip-matches (if (empty? partial-zip) []
(zipcodes-from-trie (get-in zip-trie partial-zip)))
bounds (preserve-aspect-ratio
(cond (not @zoom-enabled)
(calc-bounds (zipcodes-from-trie zip-trie))
(empty? zip-matches)
(find-bounds (butlast partial-zip) zip-trie)
(= 1 (count zip-matches))
(center-on-zip (first zip-matches)
(find-bounds partial-zip zip-trie))
:else (find-bounds partial-zip zip-trie))
aspect-ratio)
start (last @bounds-queue)
stop bounds
;; TODO choose better easing method -- linear is jarring.
midpoints (mapv (fn [step] (map #(lerp %1 %2 step) start stop))
(range 1/10 11/10 1/10))]
(reset! matched-zips zip-matches)
(when (not= start stop)
(reset! bounds-queue midpoints))))
(def deletion-key? #{\PI:KEY:<KEY>END_PI}) ;; TODO test this key on a Windows machine
(def number-key? (set (map char (range 48 58))))
(defn key-handler
"Manage keyboard input of 0 to 5 digits"
[]
(let [key (if (= processing.core.PConstants/CODED (int (raw-key)))
(key-code) (raw-key))]
(cond (and (deletion-key? key) (> (count @typed-chars) 0))
(swap! typed-chars #(apply str (butlast %)))
(and (number-key? key) (< (count @typed-chars) 5))
(swap! typed-chars #(str % key))))
(load-bounds-queue))
(defn toggle-zoom []
(when (and (< (mouse-x) (- canvas-width 35))
(> (mouse-x) (- canvas-width 45 (text-width "zoom")))
(> (- canvas-height 30) (mouse-y) (- canvas-height 55)))
(reset! zoom-enabled (not @zoom-enabled))
(load-bounds-queue)))
(defsketch zips
:title "Zip codes with animated zooming"
:setup setup
:draw draw
:size [canvas-width canvas-height]
:renderer :p2d
:key-pressed key-handler
:mouse-released toggle-zoom)
|
[
{
"context": ";;; clods.http\n\n;; Copyright 2015 Tom Regan\n;;\n;; Licensed under the Apache License, Version ",
"end": 43,
"score": 0.9998457431793213,
"start": 34,
"tag": "NAME",
"value": "Tom Regan"
}
] | clods/src/clods/http.clj | TomRegan/hollaen | 0 | ;;; clods.http
;; Copyright 2015 Tom Regan
;;
;; 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.
;;; Commentary:
;; Downloads a webpage
;;; Code:
(ns clods.http
(require [clj-http.client :as request]))
(defn request
[url]
(println (request/get url {:as :clojure})))
;; clods.http ends here
| 35464 | ;;; clods.http
;; 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.
;;; Commentary:
;; Downloads a webpage
;;; Code:
(ns clods.http
(require [clj-http.client :as request]))
(defn request
[url]
(println (request/get url {:as :clojure})))
;; clods.http ends here
| true | ;;; clods.http
;; 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.
;;; Commentary:
;; Downloads a webpage
;;; Code:
(ns clods.http
(require [clj-http.client :as request]))
(defn request
[url]
(println (request/get url {:as :clojure})))
;; clods.http ends here
|
[
{
"context": "}))\n ([config]\n (let [transport (-> {:api-key \"227d8cbbbe455977dbea9f98a126d1da\"}\n create-udp-transport)\n ",
"end": 302,
"score": 0.9997674226760864,
"start": 270,
"tag": "KEY",
"value": "227d8cbbbe455977dbea9f98a126d1da"
}
] | src/clojure/org/clojure/metrics/test.clj | DimkaGorhover/metrics-datadog-clj | 0 | (ns org.clojure.metrics.test
(:require [org.clojure.metrics.connectors :refer :all]
[org.clojure.metrics.metrics :refer :all]))
(def max-time 600)
(def min-time 300)
(defn metric-test
([] (metric-test {}))
([config]
(let [transport (-> {:api-key "227d8cbbbe455977dbea9f98a126d1da"}
create-udp-transport)
metric-registry (create-metric-registry)
reporter (-> {:metric-registry metric-registry
:transport transport
:tags '("app:api_ads" "test:true")}
create-datadog-reporter)
counter (counter:create)
const (gauge:create (Math/round (* 100 (Math/random))))
timeout (gauge:fn #(- max-time (* (- max-time min-time) (Math/random))))
queue (gauge:fn #(Math/round (- max-time (* (- max-time min-time) (Math/random)))))
timer (gauge:create)
func (fn [a]
(gauge:timed-macro
timer
(let [t (-> (Math/random) (* 1000) Math/round)]
(Thread/sleep t)
(str a "_" t))))
timer2 (timer:create)
func2 (fn [a]
(timer:macro
timer2
(let [t (-> (Math/random) (* 1000) Math/round)]
(Thread/sleep t)
(str a "_" t))))
]
(register-metric metric-registry "request_queuing" queue)
(-> metric-registry
(chain-register-metric "test_counter" counter)
(chain-register-metric "test_const" const)
(chain-register-metric "test_timeout" timeout)
(chain-register-metric "test_timer" timer)
(chain-register-metric "test_timer2" timer2)
(chain-register-metric "test_queue" queue))
(start-reporter reporter 2000)
(counter:inc counter)
(counter:dec counter)
(counter:inc counter)
(->> counter counter:get (println "test count:"))
(gauge:set const -1)
(->> const gauge:get (println "test_const:"))
(future
(dotimes [a 1000000]
(func a)
(func2 a)))
(let [test-time (or (:test-time-ms config) (* 1000 60 5))]
(println "test-time:" test-time "ms")
(Thread/sleep test-time))
(stop-reporter reporter))))
(comment
(println "run this command for manual test")
(metric-test)
) | 120059 | (ns org.clojure.metrics.test
(:require [org.clojure.metrics.connectors :refer :all]
[org.clojure.metrics.metrics :refer :all]))
(def max-time 600)
(def min-time 300)
(defn metric-test
([] (metric-test {}))
([config]
(let [transport (-> {:api-key "<KEY>"}
create-udp-transport)
metric-registry (create-metric-registry)
reporter (-> {:metric-registry metric-registry
:transport transport
:tags '("app:api_ads" "test:true")}
create-datadog-reporter)
counter (counter:create)
const (gauge:create (Math/round (* 100 (Math/random))))
timeout (gauge:fn #(- max-time (* (- max-time min-time) (Math/random))))
queue (gauge:fn #(Math/round (- max-time (* (- max-time min-time) (Math/random)))))
timer (gauge:create)
func (fn [a]
(gauge:timed-macro
timer
(let [t (-> (Math/random) (* 1000) Math/round)]
(Thread/sleep t)
(str a "_" t))))
timer2 (timer:create)
func2 (fn [a]
(timer:macro
timer2
(let [t (-> (Math/random) (* 1000) Math/round)]
(Thread/sleep t)
(str a "_" t))))
]
(register-metric metric-registry "request_queuing" queue)
(-> metric-registry
(chain-register-metric "test_counter" counter)
(chain-register-metric "test_const" const)
(chain-register-metric "test_timeout" timeout)
(chain-register-metric "test_timer" timer)
(chain-register-metric "test_timer2" timer2)
(chain-register-metric "test_queue" queue))
(start-reporter reporter 2000)
(counter:inc counter)
(counter:dec counter)
(counter:inc counter)
(->> counter counter:get (println "test count:"))
(gauge:set const -1)
(->> const gauge:get (println "test_const:"))
(future
(dotimes [a 1000000]
(func a)
(func2 a)))
(let [test-time (or (:test-time-ms config) (* 1000 60 5))]
(println "test-time:" test-time "ms")
(Thread/sleep test-time))
(stop-reporter reporter))))
(comment
(println "run this command for manual test")
(metric-test)
) | true | (ns org.clojure.metrics.test
(:require [org.clojure.metrics.connectors :refer :all]
[org.clojure.metrics.metrics :refer :all]))
(def max-time 600)
(def min-time 300)
(defn metric-test
([] (metric-test {}))
([config]
(let [transport (-> {:api-key "PI:KEY:<KEY>END_PI"}
create-udp-transport)
metric-registry (create-metric-registry)
reporter (-> {:metric-registry metric-registry
:transport transport
:tags '("app:api_ads" "test:true")}
create-datadog-reporter)
counter (counter:create)
const (gauge:create (Math/round (* 100 (Math/random))))
timeout (gauge:fn #(- max-time (* (- max-time min-time) (Math/random))))
queue (gauge:fn #(Math/round (- max-time (* (- max-time min-time) (Math/random)))))
timer (gauge:create)
func (fn [a]
(gauge:timed-macro
timer
(let [t (-> (Math/random) (* 1000) Math/round)]
(Thread/sleep t)
(str a "_" t))))
timer2 (timer:create)
func2 (fn [a]
(timer:macro
timer2
(let [t (-> (Math/random) (* 1000) Math/round)]
(Thread/sleep t)
(str a "_" t))))
]
(register-metric metric-registry "request_queuing" queue)
(-> metric-registry
(chain-register-metric "test_counter" counter)
(chain-register-metric "test_const" const)
(chain-register-metric "test_timeout" timeout)
(chain-register-metric "test_timer" timer)
(chain-register-metric "test_timer2" timer2)
(chain-register-metric "test_queue" queue))
(start-reporter reporter 2000)
(counter:inc counter)
(counter:dec counter)
(counter:inc counter)
(->> counter counter:get (println "test count:"))
(gauge:set const -1)
(->> const gauge:get (println "test_const:"))
(future
(dotimes [a 1000000]
(func a)
(func2 a)))
(let [test-time (or (:test-time-ms config) (* 1000 60 5))]
(println "test-time:" test-time "ms")
(Thread/sleep test-time))
(stop-reporter reporter))))
(comment
(println "run this command for manual test")
(metric-test)
) |
[
{
"context": ";; Copyright (c) 2015, Dmitry Kozlov <kozlov.dmitry.a@gmail.com>\n;; Code is published ",
"end": 36,
"score": 0.9998643398284912,
"start": 23,
"tag": "NAME",
"value": "Dmitry Kozlov"
},
{
"context": ";; Copyright (c) 2015, Dmitry Kozlov <kozlov.dmitry.a@gmail.com>\n;; Code is published under BSD 2-clause license.",
"end": 63,
"score": 0.9999317526817322,
"start": 38,
"tag": "EMAIL",
"value": "kozlov.dmitry.a@gmail.com"
}
] | src/illya/orientdb/mapper.clj | dkz/illya | 2 | ;; Copyright (c) 2015, Dmitry Kozlov <kozlov.dmitry.a@gmail.com>
;; Code is published under BSD 2-clause license.
(ns illya.orientdb.mapper
(:require
[spyscope.core :as spy]
[cats.core :as cats]
[cats.monad.reader :as reader]
[illya.orientdb.dsl :as ograph])
(:import
[com.tinkerpop.blueprints Direction]
[com.orientechnologies.orient.core.record ORecord]))
;; Monadic function
(defn fetch [object fetch-plan]
(if (empty? fetch-plan)
(cats/return {})
(cats/mlet
[graph reader/ask
:let [entity (transient {})]]
(cats/>>
(cats/sequence
(for [fm fetch-plan]
(fm object entity)))
(cats/bind
(cats/return #(persistent! entity))
(fn [lazy]
(cats/return (lazy))))))))
(defn property
([property-name property-key]
(fn [object transient-entity]
(assoc! transient-entity property-key (.getProperty object property-name))
(cats/return ())))
([property-name property-key fetch-plan]
(fn [object transient-entity]
(cats/mlet
[nested (fetch (.getProperty object property-name) fetch-plan)]
(assoc! transient-entity property-key nested)
(cats/return ())))))
(defn incoming-edges [edge-class-key property-key fetch-plan]
(fn [object transient-entity]
(let [edges (.getEdges object Direction/IN (into-array String [(name edge-class-key)]))]
(cats/bind
(if (empty? edges)
(cats/return [])
(cats/sequence
(doall (for [edge edges]
(fetch (.getVertex edge Direction/OUT) fetch-plan)))))
(fn [fetched]
(assoc! transient-entity property-key fetched)
(cats/return ()))))))
(defn outgoing-edges [edge-class-key property-key fetch-plan]
(fn [object transient-entity]
(let [edges (.getEdges object Direction/OUT (into-array String [(name edge-class-key)]))]
(cats/bind
(if (empty? edges)
(cats/return [])
(cats/sequence
(doall (for [edge edges]
(fetch (.getVertex edge Direction/IN) fetch-plan)))))
(fn [fetched]
(assoc! transient-entity property-key fetched)
(cats/return ()))))))
(comment
(ograph/do-transaction
(cats/mlet
[threads (ograph/vertices :MessageThread)
:let [thread (first threads)]]
(fetch thread
(list (incoming-edges :PostedTo :replies
(property "title" :title)
(property "contents" :contents))
(property "message" :message
(property "title" :title)
(property "contents" :contents))))))
)
| 93872 | ;; Copyright (c) 2015, <NAME> <<EMAIL>>
;; Code is published under BSD 2-clause license.
(ns illya.orientdb.mapper
(:require
[spyscope.core :as spy]
[cats.core :as cats]
[cats.monad.reader :as reader]
[illya.orientdb.dsl :as ograph])
(:import
[com.tinkerpop.blueprints Direction]
[com.orientechnologies.orient.core.record ORecord]))
;; Monadic function
(defn fetch [object fetch-plan]
(if (empty? fetch-plan)
(cats/return {})
(cats/mlet
[graph reader/ask
:let [entity (transient {})]]
(cats/>>
(cats/sequence
(for [fm fetch-plan]
(fm object entity)))
(cats/bind
(cats/return #(persistent! entity))
(fn [lazy]
(cats/return (lazy))))))))
(defn property
([property-name property-key]
(fn [object transient-entity]
(assoc! transient-entity property-key (.getProperty object property-name))
(cats/return ())))
([property-name property-key fetch-plan]
(fn [object transient-entity]
(cats/mlet
[nested (fetch (.getProperty object property-name) fetch-plan)]
(assoc! transient-entity property-key nested)
(cats/return ())))))
(defn incoming-edges [edge-class-key property-key fetch-plan]
(fn [object transient-entity]
(let [edges (.getEdges object Direction/IN (into-array String [(name edge-class-key)]))]
(cats/bind
(if (empty? edges)
(cats/return [])
(cats/sequence
(doall (for [edge edges]
(fetch (.getVertex edge Direction/OUT) fetch-plan)))))
(fn [fetched]
(assoc! transient-entity property-key fetched)
(cats/return ()))))))
(defn outgoing-edges [edge-class-key property-key fetch-plan]
(fn [object transient-entity]
(let [edges (.getEdges object Direction/OUT (into-array String [(name edge-class-key)]))]
(cats/bind
(if (empty? edges)
(cats/return [])
(cats/sequence
(doall (for [edge edges]
(fetch (.getVertex edge Direction/IN) fetch-plan)))))
(fn [fetched]
(assoc! transient-entity property-key fetched)
(cats/return ()))))))
(comment
(ograph/do-transaction
(cats/mlet
[threads (ograph/vertices :MessageThread)
:let [thread (first threads)]]
(fetch thread
(list (incoming-edges :PostedTo :replies
(property "title" :title)
(property "contents" :contents))
(property "message" :message
(property "title" :title)
(property "contents" :contents))))))
)
| true | ;; Copyright (c) 2015, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; Code is published under BSD 2-clause license.
(ns illya.orientdb.mapper
(:require
[spyscope.core :as spy]
[cats.core :as cats]
[cats.monad.reader :as reader]
[illya.orientdb.dsl :as ograph])
(:import
[com.tinkerpop.blueprints Direction]
[com.orientechnologies.orient.core.record ORecord]))
;; Monadic function
(defn fetch [object fetch-plan]
(if (empty? fetch-plan)
(cats/return {})
(cats/mlet
[graph reader/ask
:let [entity (transient {})]]
(cats/>>
(cats/sequence
(for [fm fetch-plan]
(fm object entity)))
(cats/bind
(cats/return #(persistent! entity))
(fn [lazy]
(cats/return (lazy))))))))
(defn property
([property-name property-key]
(fn [object transient-entity]
(assoc! transient-entity property-key (.getProperty object property-name))
(cats/return ())))
([property-name property-key fetch-plan]
(fn [object transient-entity]
(cats/mlet
[nested (fetch (.getProperty object property-name) fetch-plan)]
(assoc! transient-entity property-key nested)
(cats/return ())))))
(defn incoming-edges [edge-class-key property-key fetch-plan]
(fn [object transient-entity]
(let [edges (.getEdges object Direction/IN (into-array String [(name edge-class-key)]))]
(cats/bind
(if (empty? edges)
(cats/return [])
(cats/sequence
(doall (for [edge edges]
(fetch (.getVertex edge Direction/OUT) fetch-plan)))))
(fn [fetched]
(assoc! transient-entity property-key fetched)
(cats/return ()))))))
(defn outgoing-edges [edge-class-key property-key fetch-plan]
(fn [object transient-entity]
(let [edges (.getEdges object Direction/OUT (into-array String [(name edge-class-key)]))]
(cats/bind
(if (empty? edges)
(cats/return [])
(cats/sequence
(doall (for [edge edges]
(fetch (.getVertex edge Direction/IN) fetch-plan)))))
(fn [fetched]
(assoc! transient-entity property-key fetched)
(cats/return ()))))))
(comment
(ograph/do-transaction
(cats/mlet
[threads (ograph/vertices :MessageThread)
:let [thread (first threads)]]
(fetch thread
(list (incoming-edges :PostedTo :replies
(property "title" :title)
(property "contents" :contents))
(property "message" :message
(property "title" :title)
(property "contents" :contents))))))
)
|
[
{
"context": "(ns startrek.main\n {:author \"David Harrigan\"}\n (:require\n [aero.core :refer [read-config]]",
"end": 44,
"score": 0.9998659491539001,
"start": 30,
"tag": "NAME",
"value": "David Harrigan"
}
] | src/startrek/main.clj | dharrigan/startrek | 17 | (ns startrek.main
{:author "David Harrigan"}
(:require
[aero.core :refer [read-config]]
[clojure.java.io :as io]
[clojure.tools.cli :refer [parse-opts]]
[juxt.clip.core :as clip])
(:gen-class))
(set! *warn-on-reflection* true)
(defn ^:private load-config
[opts]
(-> (io/resource (:config opts))
(read-config opts)))
(def ^:private cli-options
[["-c" "--config FILE" "Config file, found on the classpath, to use."
:default "config/config.edn"]
["-p" "--profile PROFILE" "Profile to use, i.e., local."
:default :default
:parse-fn #(keyword %)]])
#_{:clj-kondo/ignore [:clojure-lsp/unused-public-var :unused-binding]}
(defn ^:private process
[arguments system-config {:keys [app-config] :as system}]
;; process arguments here...
(clip/stop system-config system)
(shutdown-agents))
(defn -main
[& args]
(let [{{:keys [config profile]} :options :keys [arguments]} (parse-opts args cli-options)
system-config (load-config {:config config :profile profile})
system (clip/start system-config)]
(.addShutdownHook
(Runtime/getRuntime)
(new Thread #(clip/stop system-config system)))
(if (seq arguments)
(process arguments system-config system) ;; application run from the command line with arguments.
@(promise)))) ;; application run from the command line, no arguments, keep webserver running.
(comment
;; paste (or eval) into the repl
(do
(require
'[startrek.main :as main]
'[juxt.clip.repl :refer [start stop set-init! system]])
(def profile :local) ;; rename "config/config-example.edn" to "config/config-local.edn" and change values to suit your setup.
(def config (str "config/config" (when-not (= :default profile) (str "-" (name profile))) ".edn"))
(def system-config (#'main/load-config {:config config :profile profile}))
(set-init! (constantly system-config))
(start)
(def app-config (:app-config system))
(intern (find-ns 'startrek.main) 'app-config app-config)) ; shove the value of app-config into this namespace
(do
(stop)
(start))
,)
| 25272 | (ns startrek.main
{:author "<NAME>"}
(:require
[aero.core :refer [read-config]]
[clojure.java.io :as io]
[clojure.tools.cli :refer [parse-opts]]
[juxt.clip.core :as clip])
(:gen-class))
(set! *warn-on-reflection* true)
(defn ^:private load-config
[opts]
(-> (io/resource (:config opts))
(read-config opts)))
(def ^:private cli-options
[["-c" "--config FILE" "Config file, found on the classpath, to use."
:default "config/config.edn"]
["-p" "--profile PROFILE" "Profile to use, i.e., local."
:default :default
:parse-fn #(keyword %)]])
#_{:clj-kondo/ignore [:clojure-lsp/unused-public-var :unused-binding]}
(defn ^:private process
[arguments system-config {:keys [app-config] :as system}]
;; process arguments here...
(clip/stop system-config system)
(shutdown-agents))
(defn -main
[& args]
(let [{{:keys [config profile]} :options :keys [arguments]} (parse-opts args cli-options)
system-config (load-config {:config config :profile profile})
system (clip/start system-config)]
(.addShutdownHook
(Runtime/getRuntime)
(new Thread #(clip/stop system-config system)))
(if (seq arguments)
(process arguments system-config system) ;; application run from the command line with arguments.
@(promise)))) ;; application run from the command line, no arguments, keep webserver running.
(comment
;; paste (or eval) into the repl
(do
(require
'[startrek.main :as main]
'[juxt.clip.repl :refer [start stop set-init! system]])
(def profile :local) ;; rename "config/config-example.edn" to "config/config-local.edn" and change values to suit your setup.
(def config (str "config/config" (when-not (= :default profile) (str "-" (name profile))) ".edn"))
(def system-config (#'main/load-config {:config config :profile profile}))
(set-init! (constantly system-config))
(start)
(def app-config (:app-config system))
(intern (find-ns 'startrek.main) 'app-config app-config)) ; shove the value of app-config into this namespace
(do
(stop)
(start))
,)
| true | (ns startrek.main
{:author "PI:NAME:<NAME>END_PI"}
(:require
[aero.core :refer [read-config]]
[clojure.java.io :as io]
[clojure.tools.cli :refer [parse-opts]]
[juxt.clip.core :as clip])
(:gen-class))
(set! *warn-on-reflection* true)
(defn ^:private load-config
[opts]
(-> (io/resource (:config opts))
(read-config opts)))
(def ^:private cli-options
[["-c" "--config FILE" "Config file, found on the classpath, to use."
:default "config/config.edn"]
["-p" "--profile PROFILE" "Profile to use, i.e., local."
:default :default
:parse-fn #(keyword %)]])
#_{:clj-kondo/ignore [:clojure-lsp/unused-public-var :unused-binding]}
(defn ^:private process
[arguments system-config {:keys [app-config] :as system}]
;; process arguments here...
(clip/stop system-config system)
(shutdown-agents))
(defn -main
[& args]
(let [{{:keys [config profile]} :options :keys [arguments]} (parse-opts args cli-options)
system-config (load-config {:config config :profile profile})
system (clip/start system-config)]
(.addShutdownHook
(Runtime/getRuntime)
(new Thread #(clip/stop system-config system)))
(if (seq arguments)
(process arguments system-config system) ;; application run from the command line with arguments.
@(promise)))) ;; application run from the command line, no arguments, keep webserver running.
(comment
;; paste (or eval) into the repl
(do
(require
'[startrek.main :as main]
'[juxt.clip.repl :refer [start stop set-init! system]])
(def profile :local) ;; rename "config/config-example.edn" to "config/config-local.edn" and change values to suit your setup.
(def config (str "config/config" (when-not (= :default profile) (str "-" (name profile))) ".edn"))
(def system-config (#'main/load-config {:config config :profile profile}))
(set-init! (constantly system-config))
(start)
(def app-config (:app-config system))
(intern (find-ns 'startrek.main) 'app-config app-config)) ; shove the value of app-config into this namespace
(do
(stop)
(start))
,)
|
[
{
"context": "; Copyright (c) 2021-present Walmart, Inc.\n;\n; Licensed under the Apache License, ",
"end": 32,
"score": 0.7214064598083496,
"start": 29,
"tag": "NAME",
"value": "Wal"
}
] | build.clj | green-labs/lacinia | 0 | ; Copyright (c) 2021-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.
;; clj -T:build <var>
(ns build
(:require [clojure.tools.build.api :as b]
[net.lewisship.build :refer [requiring-invoke]]))
(def lib 'com.walmartlabs/lacinia)
(def version "1.1")
(def jar-params {:project-name lib
:version version})
(defn clean
[_params]
(b/delete {:path "target"}))
(defn jar
[_params]
(requiring-invoke net.lewisship.build.jar/create-jar jar-params))
(defn deploy
[_params]
(clean nil)
(jar nil)
(requiring-invoke net.lewisship.build.jar/deploy-jar jar-params))
(defn codox
[_params]
(requiring-invoke net.lewisship.build.codox/generate
{:project-name lib
:version version
:aliases [:dev]}))
| 76554 | ; Copyright (c) 2021-present <NAME>mart, 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.
;; clj -T:build <var>
(ns build
(:require [clojure.tools.build.api :as b]
[net.lewisship.build :refer [requiring-invoke]]))
(def lib 'com.walmartlabs/lacinia)
(def version "1.1")
(def jar-params {:project-name lib
:version version})
(defn clean
[_params]
(b/delete {:path "target"}))
(defn jar
[_params]
(requiring-invoke net.lewisship.build.jar/create-jar jar-params))
(defn deploy
[_params]
(clean nil)
(jar nil)
(requiring-invoke net.lewisship.build.jar/deploy-jar jar-params))
(defn codox
[_params]
(requiring-invoke net.lewisship.build.codox/generate
{:project-name lib
:version version
:aliases [:dev]}))
| true | ; Copyright (c) 2021-present PI:NAME:<NAME>END_PImart, 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.
;; clj -T:build <var>
(ns build
(:require [clojure.tools.build.api :as b]
[net.lewisship.build :refer [requiring-invoke]]))
(def lib 'com.walmartlabs/lacinia)
(def version "1.1")
(def jar-params {:project-name lib
:version version})
(defn clean
[_params]
(b/delete {:path "target"}))
(defn jar
[_params]
(requiring-invoke net.lewisship.build.jar/create-jar jar-params))
(defn deploy
[_params]
(clean nil)
(jar nil)
(requiring-invoke net.lewisship.build.jar/deploy-jar jar-params))
(defn codox
[_params]
(requiring-invoke net.lewisship.build.codox/generate
{:project-name lib
:version version
:aliases [:dev]}))
|
[
{
"context": ";; Copyright 2020, Di Sera Luca\n;; Contacts: disera.luca@gmail.com\n;; ",
"end": 31,
"score": 0.9998747110366821,
"start": 19,
"tag": "NAME",
"value": "Di Sera Luca"
},
{
"context": " Copyright 2020, Di Sera Luca\n;; Contacts: disera.luca@gmail.com\n;; https://github.com/diseraluc",
"end": 74,
"score": 0.9999303817749023,
"start": 53,
"tag": "EMAIL",
"value": "disera.luca@gmail.com"
},
{
"context": "gmail.com\n;; https://github.com/diseraluca\n;; https://www.linkedin.com/in/",
"end": 125,
"score": 0.9996964931488037,
"start": 115,
"tag": "USERNAME",
"value": "diseraluca"
},
{
"context": "\n;; https://www.linkedin.com/in/luca-di-sera-200023167\n;;\n;; This code is licensed under the MIT License",
"end": 197,
"score": 0.9994851350784302,
"start": 175,
"tag": "USERNAME",
"value": "luca-di-sera-200023167"
}
] | pmal/src/pmal/server/routes/api.clj | diseraluca/pmal | 0 | ;; Copyright 2020, Di Sera Luca
;; Contacts: disera.luca@gmail.com
;; https://github.com/diseraluca
;; https://www.linkedin.com/in/luca-di-sera-200023167
;;
;; This code is licensed under the MIT License.
;; More information can be found in the LICENSE file in the root of this repository
(ns pmal.server.routes.api
(:require [ring.middleware.json :refer [wrap-json-response]]
[ring.util.http-response :as response]
[pmal.backend.core :as be]))
(def request-package-details
"Retrieves and provides the details about the requested package.
If the requested package is one that is known to the system, the body of the response will
contain a mapped structure, under the package key in the json-encoded body, that presents
the details of the package.
In the case that the package cannot be retrieved, a not-found response will be sent to the client."
["/details/:pkgname" {:get (fn [{{:keys [pkgname]} :path-params}]
(if-let [package (be/package pkgname)]
(response/ok {:package package})
(response/not-found (format "Unknown package %s" pkgname))))}])
(def routes
["/api" {:middleware [wrap-json-response]}
request-package-details])
| 79792 | ;; Copyright 2020, <NAME>
;; Contacts: <EMAIL>
;; https://github.com/diseraluca
;; https://www.linkedin.com/in/luca-di-sera-200023167
;;
;; This code is licensed under the MIT License.
;; More information can be found in the LICENSE file in the root of this repository
(ns pmal.server.routes.api
(:require [ring.middleware.json :refer [wrap-json-response]]
[ring.util.http-response :as response]
[pmal.backend.core :as be]))
(def request-package-details
"Retrieves and provides the details about the requested package.
If the requested package is one that is known to the system, the body of the response will
contain a mapped structure, under the package key in the json-encoded body, that presents
the details of the package.
In the case that the package cannot be retrieved, a not-found response will be sent to the client."
["/details/:pkgname" {:get (fn [{{:keys [pkgname]} :path-params}]
(if-let [package (be/package pkgname)]
(response/ok {:package package})
(response/not-found (format "Unknown package %s" pkgname))))}])
(def routes
["/api" {:middleware [wrap-json-response]}
request-package-details])
| true | ;; Copyright 2020, PI:NAME:<NAME>END_PI
;; Contacts: PI:EMAIL:<EMAIL>END_PI
;; https://github.com/diseraluca
;; https://www.linkedin.com/in/luca-di-sera-200023167
;;
;; This code is licensed under the MIT License.
;; More information can be found in the LICENSE file in the root of this repository
(ns pmal.server.routes.api
(:require [ring.middleware.json :refer [wrap-json-response]]
[ring.util.http-response :as response]
[pmal.backend.core :as be]))
(def request-package-details
"Retrieves and provides the details about the requested package.
If the requested package is one that is known to the system, the body of the response will
contain a mapped structure, under the package key in the json-encoded body, that presents
the details of the package.
In the case that the package cannot be retrieved, a not-found response will be sent to the client."
["/details/:pkgname" {:get (fn [{{:keys [pkgname]} :path-params}]
(if-let [package (be/package pkgname)]
(response/ok {:package package})
(response/not-found (format "Unknown package %s" pkgname))))}])
(def routes
["/api" {:middleware [wrap-json-response]}
request-package-details])
|
[
{
"context": ";; Copyright 2013-2020 Andrey Antukh <niwi@niwi.nz>\n;;\n;; Licensed under the Apache Li",
"end": 36,
"score": 0.9998840093612671,
"start": 23,
"tag": "NAME",
"value": "Andrey Antukh"
},
{
"context": ";; Copyright 2013-2020 Andrey Antukh <niwi@niwi.nz>\n;;\n;; Licensed under the Apache License, Version",
"end": 50,
"score": 0.9999319314956665,
"start": 38,
"tag": "EMAIL",
"value": "niwi@niwi.nz"
},
{
"context": "ameters pgen dsize))]\n {:alg alg\n :password password\n :salt salt\n :iterations iterations}))\n\n(",
"end": 3409,
"score": 0.9970852136611938,
"start": 3401,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "2 :digest :sha512)))\n\n(defmethod derive-password :pbkdf2+blake2b-512\n [options]\n (derive-password (assoc options :al",
"end": 3863,
"score": 0.990145742893219,
"start": 3845,
"tag": "PASSWORD",
"value": "pbkdf2+blake2b-512"
},
{
"context": "gest :blake2b-512)))\n\n(defmethod derive-password :pbkdf2+sha3-256\n [options]\n (derive-password (assoc options :al",
"end": 3991,
"score": 0.9643511176109314,
"start": 3976,
"tag": "PASSWORD",
"value": "pbkdf2+sha3-256"
},
{
"context": "ha3-256)))\n\n(defmethod derive-password :bcrypt+sha512\n [{:keys [alg password salt iterations]}]\n (let",
"end": 4114,
"score": 0.5608818531036377,
"start": 4111,
"tag": "PASSWORD",
"value": "512"
},
{
"context": "erations iterations\n :salt salt\n :password password}))\n\n(defmethod derive-password :bcrypt+blake2b-51",
"end": 4463,
"score": 0.7277949452400208,
"start": 4455,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "password password}))\n\n(defmethod derive-password :bcrypt+blake2b-512\n [{:keys [alg password salt iterations] :as pwdp",
"end": 4514,
"score": 0.8630415201187134,
"start": 4496,
"tag": "PASSWORD",
"value": "bcrypt+blake2b-512"
},
{
"context": "mcost\n :parallelism parallelism\n :password password\n :salt salt}))\n\n(defmethod derive-password :a",
"end": 5965,
"score": 0.9281948804855347,
"start": 5957,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "tions\n :parallelism parallelism\n :password hash\n :salt salt}))\n\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 6905,
"score": 0.9664815068244934,
"start": 6901,
"tag": "PASSWORD",
"value": "hash"
},
{
"context": ";;;;;;;;;;;;;;;;;;;;;\n\n(defmethod check-password :bcrypt+sha512\n [params attempt]\n (let [pwdbytes (:password pa",
"end": 7123,
"score": 0.6735979914665222,
"start": 7110,
"tag": "USERNAME",
"value": "bcrypt+sha512"
},
{
"context": "parseInt pll)}))\n\n(defmethod parse-password :argon2id\n [encryptedpassword]\n (let [[alg salt mem ite",
"end": 10958,
"score": 0.8194675445556641,
"start": 10957,
"tag": "USERNAME",
"value": "2"
}
] | src/clj/buddy/hashers.clj | akosilov/buddy-hashers | 0 | ;; Copyright 2013-2020 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.hashers
(:refer-clojure :exclude [derive])
(:require [buddy.core.codecs :as codecs]
[buddy.core.hash :as hash]
[buddy.core.nonce :as nonce]
[buddy.core.bytes :as bytes]
[clojure.string :as str]
[clojurewerkz.scrypt.core :as scrypt])
(:import org.bouncycastle.crypto.digests.SHA1Digest
org.bouncycastle.crypto.digests.SHA256Digest
org.bouncycastle.crypto.digests.SHA3Digest
org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator
org.bouncycastle.crypto.generators.BCrypt
org.bouncycastle.crypto.generators.Argon2BytesGenerator
org.bouncycastle.crypto.params.Argon2Parameters
org.bouncycastle.crypto.params.Argon2Parameters$Builder
java.security.Security))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Constants
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^:no-doc ^:static
+iterations+
{:pbkdf2+sha1 100000
:pbkdf2+sha256 100000
:pbkdf2+sha512 100000
:pbkdf2+blake2b-512 50000
:pbkdf2+sha3-256 5000
:bcrypt+sha512 12
:bcrypt+sha384 12
:bcrypt+blake2b-512 12
:scrypt {:cpucost 65536
:memcost 8}
:argon2id {:memory 65536
:iterations 2}})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Impl Interface
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmulti parse-password
"Parse password from string to parts."
(fn [encryptedpassword]
(-> encryptedpassword
(str/split #"\$")
(first)
(keyword))))
(defn- dispatch
[opts & args]
(:alg opts))
(defmulti derive-password
"Derive key depending on algorithm."
dispatch)
(defmulti check-password
"Password verification implementation."
dispatch)
(defmulti format-password
"Format password depending on algorithm."
dispatch)
(defmulti must-update?
"Check if the current password configuration
is succeptible to be updatable."
dispatch)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Key Derivation
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod derive-password :pbkdf2
[{:keys [alg password salt iterations digest] :as pwdparams}]
(let [salt (codecs/to-bytes (or salt (nonce/random-bytes 12)))
alg (keyword (str "pbkdf2+" (name digest)))
iterations (or iterations (get +iterations+ alg))
digest (hash/resolve-digest-engine digest)
dsize (* 8 (.getDigestSize digest))
pgen (doto (PKCS5S2ParametersGenerator. digest)
(.init password salt iterations))
password (.getKey (.generateDerivedParameters pgen dsize))]
{:alg alg
:password password
:salt salt
:iterations iterations}))
(defmethod derive-password :pbkdf2+sha1
[options]
(derive-password (assoc options :alg :pbkdf2 :digest :sha1)))
(defmethod derive-password :pbkdf2+sha256
[options]
(derive-password (assoc options :alg :pbkdf2 :digest :sha256)))
(defmethod derive-password :pbkdf2+sha512
[options]
(derive-password (assoc options :alg :pbkdf2 :digest :sha512)))
(defmethod derive-password :pbkdf2+blake2b-512
[options]
(derive-password (assoc options :alg :pbkdf2 :digest :blake2b-512)))
(defmethod derive-password :pbkdf2+sha3-256
[options]
(derive-password (assoc options :alg :pbkdf2 :digest :sha3-256)))
(defmethod derive-password :bcrypt+sha512
[{:keys [alg password salt iterations]}]
(let [salt (codecs/to-bytes (or salt (nonce/random-bytes 16)))
iterations (or iterations (get +iterations+ alg))
password (-> (hash/sha512 password)
(BCrypt/generate salt iterations))]
{:alg alg
:iterations iterations
:salt salt
:password password}))
(defmethod derive-password :bcrypt+blake2b-512
[{:keys [alg password salt iterations] :as pwdparams}]
(let [salt (codecs/to-bytes (or salt (nonce/random-bytes 16)))
iterations (or iterations (get +iterations+ alg))
password (-> (hash/blake2b-512 password)
(BCrypt/generate salt iterations))]
{:alg alg
:iterations iterations
:salt salt
:password password}))
(defmethod derive-password :bcrypt+sha384
[{:keys [alg password salt iterations] :as pwdparams}]
(let [salt (codecs/to-bytes (or salt (nonce/random-bytes 16)))
iterations (or iterations (get +iterations+ alg))
password (-> (hash/sha384 password)
(BCrypt/generate salt iterations))]
{:alg alg
:iterations iterations
:salt salt
:password password}))
(defmethod derive-password :scrypt
[{:keys [alg password salt cpucost memcost parallelism] :as pwdparams}]
(let [salt (codecs/to-bytes (or salt (nonce/random-bytes 12)))
cpucost (or cpucost (get-in +iterations+ [:scrypt :cpucost]))
memcost (or memcost (get-in +iterations+ [:scrypt :memcost]))
parallelism (or parallelism 1)
password (-> (bytes/concat salt password salt)
(codecs/bytes->hex)
(scrypt/encrypt cpucost memcost parallelism)
(codecs/str->bytes))]
{:alg alg
:cpucost cpucost
:memcost memcost
:parallelism parallelism
:password password
:salt salt}))
(defmethod derive-password :argon2id
[{:keys [alg password salt memory iterations parallelism] :as pwdparams}]
(let [salt (codecs/to-bytes (or salt (nonce/random-bytes 16)))
memory (or memory (get-in +iterations+ [:argon2id :memory])) ;; KiB
iterations (or iterations (get-in +iterations+ [:argon2id :iterations]))
parallelism (or parallelism 1)
params (-> (Argon2Parameters$Builder. Argon2Parameters/ARGON2_id)
(.withSalt salt)
(.withMemoryAsKB memory)
(.withIterations iterations)
(.withParallelism parallelism)
(.build))
generator (Argon2BytesGenerator.)
hash (byte-array 32)]
(.init generator params)
(.generateBytes generator ^bytes password hash)
{:alg alg
:memory memory
:iterations iterations
:parallelism parallelism
:password hash
:salt salt}))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Key Verification
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod check-password :bcrypt+sha512
[params attempt]
(let [pwdbytes (:password params)]
(if (= (count pwdbytes) 24)
(let [params' (assoc params :password attempt)
candidate (derive-password params')]
(bytes/equals? (:password params)
(:password candidate)))
;; Backward compatibility for password checking
;; for old algorithm
(let [candidate (-> (bytes/concat attempt (:salt params))
(hash/sha512))]
(buddy.impl.bcrypt.BCrypt/checkpw
(codecs/bytes->hex candidate)
(codecs/bytes->str (:password params)))))))
(defmethod check-password :scrypt
[pwdparams attempt]
(let [salt (:salt pwdparams)
candidate (bytes/concat salt attempt salt)]
(scrypt/verify (codecs/bytes->hex candidate)
(codecs/bytes->str (:password pwdparams)))))
(defn- derive-password-for-legacy-pbkdf2+sha256
[{:keys [alg password salt saltsize iterations]}]
(let [salt (codecs/to-bytes (or salt (nonce/random-bytes 12)))
iterations (or iterations (get +iterations+ alg))
pgen (doto (PKCS5S2ParametersGenerator. (SHA256Digest.))
(.init password salt iterations))
password (.getKey (.generateDerivedParameters pgen 160))]
{:alg alg
:password password
:salt salt
:iterations iterations}))
(defmethod check-password :pbkdf2+sha256
[params attempt]
(let [pwdbytes (:password params)]
(if (= (count pwdbytes) 20)
;; Backward compatibility with older passwords
(let [params' (assoc params :password attempt)
candidate (derive-password-for-legacy-pbkdf2+sha256 params')]
(bytes/equals? (:password params)
(:password candidate)))
(let [params' (assoc params :password attempt)
candidate (derive-password params')]
(bytes/equals? (:password params)
(:password candidate))))))
(defmethod check-password :default
[pwdparams attempt]
(let [candidate (-> (assoc pwdparams :password attempt)
(derive-password))]
(bytes/equals? (:password pwdparams)
(:password candidate))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Key Formatting
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod format-password :scrypt
[{:keys [password salt cpucost memcost parallelism]}]
(let [salt (codecs/bytes->hex salt)
password (codecs/bytes->hex password)]
(format "scrypt$%s$%s$%s$%s$%s" salt cpucost memcost parallelism password)))
(defmethod format-password :argon2id
[{:keys [password salt memory iterations parallelism]}]
(let [salt (codecs/bytes->hex salt)
password (codecs/bytes->hex password)]
(format "argon2id$%s$%s$%s$%s$%s" salt memory iterations parallelism password)))
(defmethod format-password :default
[{:keys [alg password salt iterations]}]
(let [algname (name alg)
salt (codecs/bytes->hex salt)
password (codecs/bytes->hex password)]
(if (nil? iterations)
(format "%s$%s$%s" algname salt password)
(format "%s$%s$%s$%s" algname salt iterations password))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Key Parsing
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod parse-password :scrypt
[encryptedpassword]
(let [[alg salt cc mc pll password] (str/split encryptedpassword #"\$")
alg (keyword alg)]
(if (some nil? [salt cc mc pll password])
(throw (ex-info "Malformed hash" {})))
{:alg alg
:salt (codecs/hex->bytes salt)
:password (codecs/hex->bytes password)
:cpucost (Integer/parseInt cc)
:memcost (Integer/parseInt mc)
:parallelism (Integer/parseInt pll)}))
(defmethod parse-password :argon2id
[encryptedpassword]
(let [[alg salt mem iters pll password] (str/split encryptedpassword #"\$")
alg (keyword alg)]
(if (some nil? [salt mem iters pll password])
(throw (ex-info "Malformed hash" {})))
{:alg alg
:salt (codecs/hex->bytes salt)
:password (codecs/hex->bytes password)
:memory (Integer/parseInt mem)
:iterations (Integer/parseInt iters)
:parallelism (Integer/parseInt pll)}))
(defmethod parse-password :default
[encryptedpassword]
(let [[alg salt iterations password] (str/split encryptedpassword #"\$")
alg (keyword alg)]
(if (some nil? [salt iterations password])
(throw (ex-info "Malformed hash" {})))
{:alg alg
:salt (codecs/hex->bytes salt)
:password (codecs/hex->bytes password)
:iterations (Integer/parseInt iterations)}))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Update Algorithm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod must-update? :default
[{:keys [alg iterations]}]
(let [desired-iterations (get +iterations+ alg)]
(and desired-iterations (> desired-iterations iterations))))
(defmethod must-update? :bcrypt+sha512
[{:keys [password iterations alg]}]
(or (not= (count password) 24)
(let [desired-iterations (get +iterations+ alg)]
(and desired-iterations (> desired-iterations iterations)))))
(defmethod must-update? :pbkdf2+sha256
[{:keys [password iterations alg]}]
(or (< (count password) 32)
(let [desired-iterations (get +iterations+ alg)]
(and desired-iterations (> desired-iterations iterations)))))
(defmethod must-update? :scrypt
[{:keys [alg memcost cpucost]}]
(let [desired-memcost (get-in +iterations+ [:scrypt :memcost])
desired-cpucost (get-in +iterations+ [:scrypt :cpucost])]
(and desired-cpucost
desired-memcost
(or (> desired-memcost memcost)
(> desired-cpucost cpucost)))))
(defmethod must-update? :argon2id
[{:keys [alg memory iterations]}]
(let [desired-memory (get-in +iterations+ [:argon2id :memory])
desired-iterations (get-in +iterations+ [:argon2id :iterations])]
(and desired-memory
desired-iterations
(or (> desired-memory memory)
(> desired-iterations iterations)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Public Api
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn derive
"Encrypts a raw string password."
([password] (derive password {}))
([password options]
(-> (assoc options
:alg (:alg options :bcrypt+sha512)
:password (codecs/str->bytes password))
(derive-password)
(format-password))))
(def encrypt
"Backward compatibility alias for `derive`."
derive)
(defn check
"Check if a unencrypted password matches with another encrypted
password."
([attempt encrypted]
(check attempt encrypted {}))
([attempt encrypted {:keys [limit setter prefered]}]
(when (and attempt encrypted)
(let [pwdparams (parse-password encrypted)]
(if (and (set? limit) (not (contains? limit (:alg pwdparams))))
false
(let [attempt' (codecs/str->bytes attempt)
result (check-password pwdparams attempt')]
(when (and result (fn? setter) (must-update? pwdparams))
(setter attempt))
result))))))
(defn verify
"Check if a unencrypted password matches with another encrypted
password. Analogous to `check` with different call signature."
([attempt encrypted]
(verify attempt encrypted {}))
([attempt encrypted {:keys [limit prefered]}]
(when-not (and attempt encrypted)
(throw (java.lang.IllegalArgumentException. "invalid arguments")))
(let [pparams (parse-password encrypted)
attempt (codecs/str->bytes attempt)
result (check-password pparams attempt)]
(if (and (set? limit)
(not (limit (:alg pparams))))
{:valid false
:update false}
{:valid result
:update (and result (must-update? pparams))}))))
| 49027 | ;; Copyright 2013-2020 <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.hashers
(:refer-clojure :exclude [derive])
(:require [buddy.core.codecs :as codecs]
[buddy.core.hash :as hash]
[buddy.core.nonce :as nonce]
[buddy.core.bytes :as bytes]
[clojure.string :as str]
[clojurewerkz.scrypt.core :as scrypt])
(:import org.bouncycastle.crypto.digests.SHA1Digest
org.bouncycastle.crypto.digests.SHA256Digest
org.bouncycastle.crypto.digests.SHA3Digest
org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator
org.bouncycastle.crypto.generators.BCrypt
org.bouncycastle.crypto.generators.Argon2BytesGenerator
org.bouncycastle.crypto.params.Argon2Parameters
org.bouncycastle.crypto.params.Argon2Parameters$Builder
java.security.Security))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Constants
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^:no-doc ^:static
+iterations+
{:pbkdf2+sha1 100000
:pbkdf2+sha256 100000
:pbkdf2+sha512 100000
:pbkdf2+blake2b-512 50000
:pbkdf2+sha3-256 5000
:bcrypt+sha512 12
:bcrypt+sha384 12
:bcrypt+blake2b-512 12
:scrypt {:cpucost 65536
:memcost 8}
:argon2id {:memory 65536
:iterations 2}})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Impl Interface
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmulti parse-password
"Parse password from string to parts."
(fn [encryptedpassword]
(-> encryptedpassword
(str/split #"\$")
(first)
(keyword))))
(defn- dispatch
[opts & args]
(:alg opts))
(defmulti derive-password
"Derive key depending on algorithm."
dispatch)
(defmulti check-password
"Password verification implementation."
dispatch)
(defmulti format-password
"Format password depending on algorithm."
dispatch)
(defmulti must-update?
"Check if the current password configuration
is succeptible to be updatable."
dispatch)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Key Derivation
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod derive-password :pbkdf2
[{:keys [alg password salt iterations digest] :as pwdparams}]
(let [salt (codecs/to-bytes (or salt (nonce/random-bytes 12)))
alg (keyword (str "pbkdf2+" (name digest)))
iterations (or iterations (get +iterations+ alg))
digest (hash/resolve-digest-engine digest)
dsize (* 8 (.getDigestSize digest))
pgen (doto (PKCS5S2ParametersGenerator. digest)
(.init password salt iterations))
password (.getKey (.generateDerivedParameters pgen dsize))]
{:alg alg
:password <PASSWORD>
:salt salt
:iterations iterations}))
(defmethod derive-password :pbkdf2+sha1
[options]
(derive-password (assoc options :alg :pbkdf2 :digest :sha1)))
(defmethod derive-password :pbkdf2+sha256
[options]
(derive-password (assoc options :alg :pbkdf2 :digest :sha256)))
(defmethod derive-password :pbkdf2+sha512
[options]
(derive-password (assoc options :alg :pbkdf2 :digest :sha512)))
(defmethod derive-password :<PASSWORD>
[options]
(derive-password (assoc options :alg :pbkdf2 :digest :blake2b-512)))
(defmethod derive-password :<PASSWORD>
[options]
(derive-password (assoc options :alg :pbkdf2 :digest :sha3-256)))
(defmethod derive-password :bcrypt+sha<PASSWORD>
[{:keys [alg password salt iterations]}]
(let [salt (codecs/to-bytes (or salt (nonce/random-bytes 16)))
iterations (or iterations (get +iterations+ alg))
password (-> (hash/sha512 password)
(BCrypt/generate salt iterations))]
{:alg alg
:iterations iterations
:salt salt
:password <PASSWORD>}))
(defmethod derive-password :<PASSWORD>
[{:keys [alg password salt iterations] :as pwdparams}]
(let [salt (codecs/to-bytes (or salt (nonce/random-bytes 16)))
iterations (or iterations (get +iterations+ alg))
password (-> (hash/blake2b-512 password)
(BCrypt/generate salt iterations))]
{:alg alg
:iterations iterations
:salt salt
:password password}))
(defmethod derive-password :bcrypt+sha384
[{:keys [alg password salt iterations] :as pwdparams}]
(let [salt (codecs/to-bytes (or salt (nonce/random-bytes 16)))
iterations (or iterations (get +iterations+ alg))
password (-> (hash/sha384 password)
(BCrypt/generate salt iterations))]
{:alg alg
:iterations iterations
:salt salt
:password password}))
(defmethod derive-password :scrypt
[{:keys [alg password salt cpucost memcost parallelism] :as pwdparams}]
(let [salt (codecs/to-bytes (or salt (nonce/random-bytes 12)))
cpucost (or cpucost (get-in +iterations+ [:scrypt :cpucost]))
memcost (or memcost (get-in +iterations+ [:scrypt :memcost]))
parallelism (or parallelism 1)
password (-> (bytes/concat salt password salt)
(codecs/bytes->hex)
(scrypt/encrypt cpucost memcost parallelism)
(codecs/str->bytes))]
{:alg alg
:cpucost cpucost
:memcost memcost
:parallelism parallelism
:password <PASSWORD>
:salt salt}))
(defmethod derive-password :argon2id
[{:keys [alg password salt memory iterations parallelism] :as pwdparams}]
(let [salt (codecs/to-bytes (or salt (nonce/random-bytes 16)))
memory (or memory (get-in +iterations+ [:argon2id :memory])) ;; KiB
iterations (or iterations (get-in +iterations+ [:argon2id :iterations]))
parallelism (or parallelism 1)
params (-> (Argon2Parameters$Builder. Argon2Parameters/ARGON2_id)
(.withSalt salt)
(.withMemoryAsKB memory)
(.withIterations iterations)
(.withParallelism parallelism)
(.build))
generator (Argon2BytesGenerator.)
hash (byte-array 32)]
(.init generator params)
(.generateBytes generator ^bytes password hash)
{:alg alg
:memory memory
:iterations iterations
:parallelism parallelism
:password <PASSWORD>
:salt salt}))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Key Verification
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod check-password :bcrypt+sha512
[params attempt]
(let [pwdbytes (:password params)]
(if (= (count pwdbytes) 24)
(let [params' (assoc params :password attempt)
candidate (derive-password params')]
(bytes/equals? (:password params)
(:password candidate)))
;; Backward compatibility for password checking
;; for old algorithm
(let [candidate (-> (bytes/concat attempt (:salt params))
(hash/sha512))]
(buddy.impl.bcrypt.BCrypt/checkpw
(codecs/bytes->hex candidate)
(codecs/bytes->str (:password params)))))))
(defmethod check-password :scrypt
[pwdparams attempt]
(let [salt (:salt pwdparams)
candidate (bytes/concat salt attempt salt)]
(scrypt/verify (codecs/bytes->hex candidate)
(codecs/bytes->str (:password pwdparams)))))
(defn- derive-password-for-legacy-pbkdf2+sha256
[{:keys [alg password salt saltsize iterations]}]
(let [salt (codecs/to-bytes (or salt (nonce/random-bytes 12)))
iterations (or iterations (get +iterations+ alg))
pgen (doto (PKCS5S2ParametersGenerator. (SHA256Digest.))
(.init password salt iterations))
password (.getKey (.generateDerivedParameters pgen 160))]
{:alg alg
:password password
:salt salt
:iterations iterations}))
(defmethod check-password :pbkdf2+sha256
[params attempt]
(let [pwdbytes (:password params)]
(if (= (count pwdbytes) 20)
;; Backward compatibility with older passwords
(let [params' (assoc params :password attempt)
candidate (derive-password-for-legacy-pbkdf2+sha256 params')]
(bytes/equals? (:password params)
(:password candidate)))
(let [params' (assoc params :password attempt)
candidate (derive-password params')]
(bytes/equals? (:password params)
(:password candidate))))))
(defmethod check-password :default
[pwdparams attempt]
(let [candidate (-> (assoc pwdparams :password attempt)
(derive-password))]
(bytes/equals? (:password pwdparams)
(:password candidate))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Key Formatting
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod format-password :scrypt
[{:keys [password salt cpucost memcost parallelism]}]
(let [salt (codecs/bytes->hex salt)
password (codecs/bytes->hex password)]
(format "scrypt$%s$%s$%s$%s$%s" salt cpucost memcost parallelism password)))
(defmethod format-password :argon2id
[{:keys [password salt memory iterations parallelism]}]
(let [salt (codecs/bytes->hex salt)
password (codecs/bytes->hex password)]
(format "argon2id$%s$%s$%s$%s$%s" salt memory iterations parallelism password)))
(defmethod format-password :default
[{:keys [alg password salt iterations]}]
(let [algname (name alg)
salt (codecs/bytes->hex salt)
password (codecs/bytes->hex password)]
(if (nil? iterations)
(format "%s$%s$%s" algname salt password)
(format "%s$%s$%s$%s" algname salt iterations password))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Key Parsing
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod parse-password :scrypt
[encryptedpassword]
(let [[alg salt cc mc pll password] (str/split encryptedpassword #"\$")
alg (keyword alg)]
(if (some nil? [salt cc mc pll password])
(throw (ex-info "Malformed hash" {})))
{:alg alg
:salt (codecs/hex->bytes salt)
:password (codecs/hex->bytes password)
:cpucost (Integer/parseInt cc)
:memcost (Integer/parseInt mc)
:parallelism (Integer/parseInt pll)}))
(defmethod parse-password :argon2id
[encryptedpassword]
(let [[alg salt mem iters pll password] (str/split encryptedpassword #"\$")
alg (keyword alg)]
(if (some nil? [salt mem iters pll password])
(throw (ex-info "Malformed hash" {})))
{:alg alg
:salt (codecs/hex->bytes salt)
:password (codecs/hex->bytes password)
:memory (Integer/parseInt mem)
:iterations (Integer/parseInt iters)
:parallelism (Integer/parseInt pll)}))
(defmethod parse-password :default
[encryptedpassword]
(let [[alg salt iterations password] (str/split encryptedpassword #"\$")
alg (keyword alg)]
(if (some nil? [salt iterations password])
(throw (ex-info "Malformed hash" {})))
{:alg alg
:salt (codecs/hex->bytes salt)
:password (codecs/hex->bytes password)
:iterations (Integer/parseInt iterations)}))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Update Algorithm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod must-update? :default
[{:keys [alg iterations]}]
(let [desired-iterations (get +iterations+ alg)]
(and desired-iterations (> desired-iterations iterations))))
(defmethod must-update? :bcrypt+sha512
[{:keys [password iterations alg]}]
(or (not= (count password) 24)
(let [desired-iterations (get +iterations+ alg)]
(and desired-iterations (> desired-iterations iterations)))))
(defmethod must-update? :pbkdf2+sha256
[{:keys [password iterations alg]}]
(or (< (count password) 32)
(let [desired-iterations (get +iterations+ alg)]
(and desired-iterations (> desired-iterations iterations)))))
(defmethod must-update? :scrypt
[{:keys [alg memcost cpucost]}]
(let [desired-memcost (get-in +iterations+ [:scrypt :memcost])
desired-cpucost (get-in +iterations+ [:scrypt :cpucost])]
(and desired-cpucost
desired-memcost
(or (> desired-memcost memcost)
(> desired-cpucost cpucost)))))
(defmethod must-update? :argon2id
[{:keys [alg memory iterations]}]
(let [desired-memory (get-in +iterations+ [:argon2id :memory])
desired-iterations (get-in +iterations+ [:argon2id :iterations])]
(and desired-memory
desired-iterations
(or (> desired-memory memory)
(> desired-iterations iterations)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Public Api
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn derive
"Encrypts a raw string password."
([password] (derive password {}))
([password options]
(-> (assoc options
:alg (:alg options :bcrypt+sha512)
:password (codecs/str->bytes password))
(derive-password)
(format-password))))
(def encrypt
"Backward compatibility alias for `derive`."
derive)
(defn check
"Check if a unencrypted password matches with another encrypted
password."
([attempt encrypted]
(check attempt encrypted {}))
([attempt encrypted {:keys [limit setter prefered]}]
(when (and attempt encrypted)
(let [pwdparams (parse-password encrypted)]
(if (and (set? limit) (not (contains? limit (:alg pwdparams))))
false
(let [attempt' (codecs/str->bytes attempt)
result (check-password pwdparams attempt')]
(when (and result (fn? setter) (must-update? pwdparams))
(setter attempt))
result))))))
(defn verify
"Check if a unencrypted password matches with another encrypted
password. Analogous to `check` with different call signature."
([attempt encrypted]
(verify attempt encrypted {}))
([attempt encrypted {:keys [limit prefered]}]
(when-not (and attempt encrypted)
(throw (java.lang.IllegalArgumentException. "invalid arguments")))
(let [pparams (parse-password encrypted)
attempt (codecs/str->bytes attempt)
result (check-password pparams attempt)]
(if (and (set? limit)
(not (limit (:alg pparams))))
{:valid false
:update false}
{:valid result
:update (and result (must-update? pparams))}))))
| true | ;; Copyright 2013-2020 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.hashers
(:refer-clojure :exclude [derive])
(:require [buddy.core.codecs :as codecs]
[buddy.core.hash :as hash]
[buddy.core.nonce :as nonce]
[buddy.core.bytes :as bytes]
[clojure.string :as str]
[clojurewerkz.scrypt.core :as scrypt])
(:import org.bouncycastle.crypto.digests.SHA1Digest
org.bouncycastle.crypto.digests.SHA256Digest
org.bouncycastle.crypto.digests.SHA3Digest
org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator
org.bouncycastle.crypto.generators.BCrypt
org.bouncycastle.crypto.generators.Argon2BytesGenerator
org.bouncycastle.crypto.params.Argon2Parameters
org.bouncycastle.crypto.params.Argon2Parameters$Builder
java.security.Security))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Constants
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^:no-doc ^:static
+iterations+
{:pbkdf2+sha1 100000
:pbkdf2+sha256 100000
:pbkdf2+sha512 100000
:pbkdf2+blake2b-512 50000
:pbkdf2+sha3-256 5000
:bcrypt+sha512 12
:bcrypt+sha384 12
:bcrypt+blake2b-512 12
:scrypt {:cpucost 65536
:memcost 8}
:argon2id {:memory 65536
:iterations 2}})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Impl Interface
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmulti parse-password
"Parse password from string to parts."
(fn [encryptedpassword]
(-> encryptedpassword
(str/split #"\$")
(first)
(keyword))))
(defn- dispatch
[opts & args]
(:alg opts))
(defmulti derive-password
"Derive key depending on algorithm."
dispatch)
(defmulti check-password
"Password verification implementation."
dispatch)
(defmulti format-password
"Format password depending on algorithm."
dispatch)
(defmulti must-update?
"Check if the current password configuration
is succeptible to be updatable."
dispatch)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Key Derivation
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod derive-password :pbkdf2
[{:keys [alg password salt iterations digest] :as pwdparams}]
(let [salt (codecs/to-bytes (or salt (nonce/random-bytes 12)))
alg (keyword (str "pbkdf2+" (name digest)))
iterations (or iterations (get +iterations+ alg))
digest (hash/resolve-digest-engine digest)
dsize (* 8 (.getDigestSize digest))
pgen (doto (PKCS5S2ParametersGenerator. digest)
(.init password salt iterations))
password (.getKey (.generateDerivedParameters pgen dsize))]
{:alg alg
:password PI:PASSWORD:<PASSWORD>END_PI
:salt salt
:iterations iterations}))
(defmethod derive-password :pbkdf2+sha1
[options]
(derive-password (assoc options :alg :pbkdf2 :digest :sha1)))
(defmethod derive-password :pbkdf2+sha256
[options]
(derive-password (assoc options :alg :pbkdf2 :digest :sha256)))
(defmethod derive-password :pbkdf2+sha512
[options]
(derive-password (assoc options :alg :pbkdf2 :digest :sha512)))
(defmethod derive-password :PI:PASSWORD:<PASSWORD>END_PI
[options]
(derive-password (assoc options :alg :pbkdf2 :digest :blake2b-512)))
(defmethod derive-password :PI:PASSWORD:<PASSWORD>END_PI
[options]
(derive-password (assoc options :alg :pbkdf2 :digest :sha3-256)))
(defmethod derive-password :bcrypt+shaPI:PASSWORD:<PASSWORD>END_PI
[{:keys [alg password salt iterations]}]
(let [salt (codecs/to-bytes (or salt (nonce/random-bytes 16)))
iterations (or iterations (get +iterations+ alg))
password (-> (hash/sha512 password)
(BCrypt/generate salt iterations))]
{:alg alg
:iterations iterations
:salt salt
:password PI:PASSWORD:<PASSWORD>END_PI}))
(defmethod derive-password :PI:PASSWORD:<PASSWORD>END_PI
[{:keys [alg password salt iterations] :as pwdparams}]
(let [salt (codecs/to-bytes (or salt (nonce/random-bytes 16)))
iterations (or iterations (get +iterations+ alg))
password (-> (hash/blake2b-512 password)
(BCrypt/generate salt iterations))]
{:alg alg
:iterations iterations
:salt salt
:password password}))
(defmethod derive-password :bcrypt+sha384
[{:keys [alg password salt iterations] :as pwdparams}]
(let [salt (codecs/to-bytes (or salt (nonce/random-bytes 16)))
iterations (or iterations (get +iterations+ alg))
password (-> (hash/sha384 password)
(BCrypt/generate salt iterations))]
{:alg alg
:iterations iterations
:salt salt
:password password}))
(defmethod derive-password :scrypt
[{:keys [alg password salt cpucost memcost parallelism] :as pwdparams}]
(let [salt (codecs/to-bytes (or salt (nonce/random-bytes 12)))
cpucost (or cpucost (get-in +iterations+ [:scrypt :cpucost]))
memcost (or memcost (get-in +iterations+ [:scrypt :memcost]))
parallelism (or parallelism 1)
password (-> (bytes/concat salt password salt)
(codecs/bytes->hex)
(scrypt/encrypt cpucost memcost parallelism)
(codecs/str->bytes))]
{:alg alg
:cpucost cpucost
:memcost memcost
:parallelism parallelism
:password PI:PASSWORD:<PASSWORD>END_PI
:salt salt}))
(defmethod derive-password :argon2id
[{:keys [alg password salt memory iterations parallelism] :as pwdparams}]
(let [salt (codecs/to-bytes (or salt (nonce/random-bytes 16)))
memory (or memory (get-in +iterations+ [:argon2id :memory])) ;; KiB
iterations (or iterations (get-in +iterations+ [:argon2id :iterations]))
parallelism (or parallelism 1)
params (-> (Argon2Parameters$Builder. Argon2Parameters/ARGON2_id)
(.withSalt salt)
(.withMemoryAsKB memory)
(.withIterations iterations)
(.withParallelism parallelism)
(.build))
generator (Argon2BytesGenerator.)
hash (byte-array 32)]
(.init generator params)
(.generateBytes generator ^bytes password hash)
{:alg alg
:memory memory
:iterations iterations
:parallelism parallelism
:password PI:PASSWORD:<PASSWORD>END_PI
:salt salt}))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Key Verification
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod check-password :bcrypt+sha512
[params attempt]
(let [pwdbytes (:password params)]
(if (= (count pwdbytes) 24)
(let [params' (assoc params :password attempt)
candidate (derive-password params')]
(bytes/equals? (:password params)
(:password candidate)))
;; Backward compatibility for password checking
;; for old algorithm
(let [candidate (-> (bytes/concat attempt (:salt params))
(hash/sha512))]
(buddy.impl.bcrypt.BCrypt/checkpw
(codecs/bytes->hex candidate)
(codecs/bytes->str (:password params)))))))
(defmethod check-password :scrypt
[pwdparams attempt]
(let [salt (:salt pwdparams)
candidate (bytes/concat salt attempt salt)]
(scrypt/verify (codecs/bytes->hex candidate)
(codecs/bytes->str (:password pwdparams)))))
(defn- derive-password-for-legacy-pbkdf2+sha256
[{:keys [alg password salt saltsize iterations]}]
(let [salt (codecs/to-bytes (or salt (nonce/random-bytes 12)))
iterations (or iterations (get +iterations+ alg))
pgen (doto (PKCS5S2ParametersGenerator. (SHA256Digest.))
(.init password salt iterations))
password (.getKey (.generateDerivedParameters pgen 160))]
{:alg alg
:password password
:salt salt
:iterations iterations}))
(defmethod check-password :pbkdf2+sha256
[params attempt]
(let [pwdbytes (:password params)]
(if (= (count pwdbytes) 20)
;; Backward compatibility with older passwords
(let [params' (assoc params :password attempt)
candidate (derive-password-for-legacy-pbkdf2+sha256 params')]
(bytes/equals? (:password params)
(:password candidate)))
(let [params' (assoc params :password attempt)
candidate (derive-password params')]
(bytes/equals? (:password params)
(:password candidate))))))
(defmethod check-password :default
[pwdparams attempt]
(let [candidate (-> (assoc pwdparams :password attempt)
(derive-password))]
(bytes/equals? (:password pwdparams)
(:password candidate))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Key Formatting
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod format-password :scrypt
[{:keys [password salt cpucost memcost parallelism]}]
(let [salt (codecs/bytes->hex salt)
password (codecs/bytes->hex password)]
(format "scrypt$%s$%s$%s$%s$%s" salt cpucost memcost parallelism password)))
(defmethod format-password :argon2id
[{:keys [password salt memory iterations parallelism]}]
(let [salt (codecs/bytes->hex salt)
password (codecs/bytes->hex password)]
(format "argon2id$%s$%s$%s$%s$%s" salt memory iterations parallelism password)))
(defmethod format-password :default
[{:keys [alg password salt iterations]}]
(let [algname (name alg)
salt (codecs/bytes->hex salt)
password (codecs/bytes->hex password)]
(if (nil? iterations)
(format "%s$%s$%s" algname salt password)
(format "%s$%s$%s$%s" algname salt iterations password))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Key Parsing
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod parse-password :scrypt
[encryptedpassword]
(let [[alg salt cc mc pll password] (str/split encryptedpassword #"\$")
alg (keyword alg)]
(if (some nil? [salt cc mc pll password])
(throw (ex-info "Malformed hash" {})))
{:alg alg
:salt (codecs/hex->bytes salt)
:password (codecs/hex->bytes password)
:cpucost (Integer/parseInt cc)
:memcost (Integer/parseInt mc)
:parallelism (Integer/parseInt pll)}))
(defmethod parse-password :argon2id
[encryptedpassword]
(let [[alg salt mem iters pll password] (str/split encryptedpassword #"\$")
alg (keyword alg)]
(if (some nil? [salt mem iters pll password])
(throw (ex-info "Malformed hash" {})))
{:alg alg
:salt (codecs/hex->bytes salt)
:password (codecs/hex->bytes password)
:memory (Integer/parseInt mem)
:iterations (Integer/parseInt iters)
:parallelism (Integer/parseInt pll)}))
(defmethod parse-password :default
[encryptedpassword]
(let [[alg salt iterations password] (str/split encryptedpassword #"\$")
alg (keyword alg)]
(if (some nil? [salt iterations password])
(throw (ex-info "Malformed hash" {})))
{:alg alg
:salt (codecs/hex->bytes salt)
:password (codecs/hex->bytes password)
:iterations (Integer/parseInt iterations)}))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Update Algorithm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod must-update? :default
[{:keys [alg iterations]}]
(let [desired-iterations (get +iterations+ alg)]
(and desired-iterations (> desired-iterations iterations))))
(defmethod must-update? :bcrypt+sha512
[{:keys [password iterations alg]}]
(or (not= (count password) 24)
(let [desired-iterations (get +iterations+ alg)]
(and desired-iterations (> desired-iterations iterations)))))
(defmethod must-update? :pbkdf2+sha256
[{:keys [password iterations alg]}]
(or (< (count password) 32)
(let [desired-iterations (get +iterations+ alg)]
(and desired-iterations (> desired-iterations iterations)))))
(defmethod must-update? :scrypt
[{:keys [alg memcost cpucost]}]
(let [desired-memcost (get-in +iterations+ [:scrypt :memcost])
desired-cpucost (get-in +iterations+ [:scrypt :cpucost])]
(and desired-cpucost
desired-memcost
(or (> desired-memcost memcost)
(> desired-cpucost cpucost)))))
(defmethod must-update? :argon2id
[{:keys [alg memory iterations]}]
(let [desired-memory (get-in +iterations+ [:argon2id :memory])
desired-iterations (get-in +iterations+ [:argon2id :iterations])]
(and desired-memory
desired-iterations
(or (> desired-memory memory)
(> desired-iterations iterations)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Public Api
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn derive
"Encrypts a raw string password."
([password] (derive password {}))
([password options]
(-> (assoc options
:alg (:alg options :bcrypt+sha512)
:password (codecs/str->bytes password))
(derive-password)
(format-password))))
(def encrypt
"Backward compatibility alias for `derive`."
derive)
(defn check
"Check if a unencrypted password matches with another encrypted
password."
([attempt encrypted]
(check attempt encrypted {}))
([attempt encrypted {:keys [limit setter prefered]}]
(when (and attempt encrypted)
(let [pwdparams (parse-password encrypted)]
(if (and (set? limit) (not (contains? limit (:alg pwdparams))))
false
(let [attempt' (codecs/str->bytes attempt)
result (check-password pwdparams attempt')]
(when (and result (fn? setter) (must-update? pwdparams))
(setter attempt))
result))))))
(defn verify
"Check if a unencrypted password matches with another encrypted
password. Analogous to `check` with different call signature."
([attempt encrypted]
(verify attempt encrypted {}))
([attempt encrypted {:keys [limit prefered]}]
(when-not (and attempt encrypted)
(throw (java.lang.IllegalArgumentException. "invalid arguments")))
(let [pparams (parse-password encrypted)
attempt (codecs/str->bytes attempt)
result (check-password pparams attempt)]
(if (and (set? limit)
(not (limit (:alg pparams))))
{:valid false
:update false}
{:valid result
:update (and result (must-update? pparams))}))))
|
[
{
"context": "ndler]\n (let [session-store (cookie-store {:key (b/slice secret 0 16)})]\n (-> ((:middleware defaults) handler)\n ",
"end": 2679,
"score": 0.8205506205558777,
"start": 2663,
"tag": "KEY",
"value": "b/slice secret 0"
},
{
"context": "ssion-store (cookie-store {:key (b/slice secret 0 16)})]\n (-> ((:middleware defaults) handler)\n ",
"end": 2682,
"score": 0.6945815086364746,
"start": 2680,
"tag": "KEY",
"value": "16"
}
] | src/main/dinsro/middleware.clj | duck1123/dinsro | 2 | (ns dinsro.middleware
(:require
[buddy.auth.backends :as backends]
[buddy.auth.middleware :refer [wrap-authentication wrap-authorization]]
[buddy.core.bytes :as b]
[clojure.core.async :as async]
[com.fulcrologic.fulcro.server.api-middleware :as server]
[com.wsscode.pathom.connect :as pc]
[com.wsscode.pathom.core :as p]
[dinsro.config :refer [secret]]
[dinsro.env :refer [defaults]]
[dinsro.layout :refer [error-page]]
[dinsro.resolvers :as dr]
[mount.core :refer [defstate]]
[ring.middleware.anti-forgery :refer [wrap-anti-forgery]]
[ring.middleware.defaults :refer [site-defaults wrap-defaults]]
[ring.middleware.session.cookie :refer [cookie-store]]
[taoensso.timbre :as log]))
(def pathom-endpoint "/pathom")
(def my-resolvers [dr/resolvers])
(defn wrap-internal-error [handler]
(fn [req]
(try
(handler req)
(catch Throwable t
(log/error (.getCause t))
(log/error t (.getMessage t))
(error-page {:status 500
:title "Something very bad has happened!"
:message "We've dispatched a team of highly trained gnomes to take care of the problem."})))))
(defn wrap-csrf [handler]
(wrap-anti-forgery
handler
{:error-response
(error-page
{:status 403
:title "Invalid anti-forgery token"})}))
(defstate ^{:on-reload :noop} token-backend
:start
(backends/jws {:secret secret}))
(defn wrap-auth [handler]
(let [backend token-backend]
(-> handler
(wrap-authentication backend)
(wrap-authorization backend))))
(def parser
(p/parallel-parser
{::p/env {::p/reader [p/map-reader
pc/parallel-reader
pc/open-ident-reader
p/env-placeholder-reader]
::pc/mutation-join-globals [:tempids]
::p/placeholder-prefixes #{">"}}
::p/mutate pc/mutate-async
::p/plugins [(pc/connect-plugin {::pc/register my-resolvers})
(p/post-process-parser-plugin p/elide-not-found)
p/error-handler-plugin
;; p/request-cache-plugin
p/trace-plugin]}))
(defn wrap-api
[handler]
(let [parser (fn [env query] (async/<!! (parser env (log/spy query))))]
(fn [{:keys [uri] :as request}]
(if (= pathom-endpoint uri)
(server/handle-api-request
(:transit-params request)
(partial parser {:request request}))
(handler request)))))
(defn wrap-base [handler]
(let [session-store (cookie-store {:key (b/slice secret 0 16)})]
(-> ((:middleware defaults) handler)
(wrap-api)
(server/wrap-transit-params)
(server/wrap-transit-response)
wrap-auth
wrap-csrf
(wrap-defaults
(assoc-in site-defaults [:session :store] session-store))
wrap-internal-error)))
| 117491 | (ns dinsro.middleware
(:require
[buddy.auth.backends :as backends]
[buddy.auth.middleware :refer [wrap-authentication wrap-authorization]]
[buddy.core.bytes :as b]
[clojure.core.async :as async]
[com.fulcrologic.fulcro.server.api-middleware :as server]
[com.wsscode.pathom.connect :as pc]
[com.wsscode.pathom.core :as p]
[dinsro.config :refer [secret]]
[dinsro.env :refer [defaults]]
[dinsro.layout :refer [error-page]]
[dinsro.resolvers :as dr]
[mount.core :refer [defstate]]
[ring.middleware.anti-forgery :refer [wrap-anti-forgery]]
[ring.middleware.defaults :refer [site-defaults wrap-defaults]]
[ring.middleware.session.cookie :refer [cookie-store]]
[taoensso.timbre :as log]))
(def pathom-endpoint "/pathom")
(def my-resolvers [dr/resolvers])
(defn wrap-internal-error [handler]
(fn [req]
(try
(handler req)
(catch Throwable t
(log/error (.getCause t))
(log/error t (.getMessage t))
(error-page {:status 500
:title "Something very bad has happened!"
:message "We've dispatched a team of highly trained gnomes to take care of the problem."})))))
(defn wrap-csrf [handler]
(wrap-anti-forgery
handler
{:error-response
(error-page
{:status 403
:title "Invalid anti-forgery token"})}))
(defstate ^{:on-reload :noop} token-backend
:start
(backends/jws {:secret secret}))
(defn wrap-auth [handler]
(let [backend token-backend]
(-> handler
(wrap-authentication backend)
(wrap-authorization backend))))
(def parser
(p/parallel-parser
{::p/env {::p/reader [p/map-reader
pc/parallel-reader
pc/open-ident-reader
p/env-placeholder-reader]
::pc/mutation-join-globals [:tempids]
::p/placeholder-prefixes #{">"}}
::p/mutate pc/mutate-async
::p/plugins [(pc/connect-plugin {::pc/register my-resolvers})
(p/post-process-parser-plugin p/elide-not-found)
p/error-handler-plugin
;; p/request-cache-plugin
p/trace-plugin]}))
(defn wrap-api
[handler]
(let [parser (fn [env query] (async/<!! (parser env (log/spy query))))]
(fn [{:keys [uri] :as request}]
(if (= pathom-endpoint uri)
(server/handle-api-request
(:transit-params request)
(partial parser {:request request}))
(handler request)))))
(defn wrap-base [handler]
(let [session-store (cookie-store {:key (<KEY> <KEY>)})]
(-> ((:middleware defaults) handler)
(wrap-api)
(server/wrap-transit-params)
(server/wrap-transit-response)
wrap-auth
wrap-csrf
(wrap-defaults
(assoc-in site-defaults [:session :store] session-store))
wrap-internal-error)))
| true | (ns dinsro.middleware
(:require
[buddy.auth.backends :as backends]
[buddy.auth.middleware :refer [wrap-authentication wrap-authorization]]
[buddy.core.bytes :as b]
[clojure.core.async :as async]
[com.fulcrologic.fulcro.server.api-middleware :as server]
[com.wsscode.pathom.connect :as pc]
[com.wsscode.pathom.core :as p]
[dinsro.config :refer [secret]]
[dinsro.env :refer [defaults]]
[dinsro.layout :refer [error-page]]
[dinsro.resolvers :as dr]
[mount.core :refer [defstate]]
[ring.middleware.anti-forgery :refer [wrap-anti-forgery]]
[ring.middleware.defaults :refer [site-defaults wrap-defaults]]
[ring.middleware.session.cookie :refer [cookie-store]]
[taoensso.timbre :as log]))
(def pathom-endpoint "/pathom")
(def my-resolvers [dr/resolvers])
(defn wrap-internal-error [handler]
(fn [req]
(try
(handler req)
(catch Throwable t
(log/error (.getCause t))
(log/error t (.getMessage t))
(error-page {:status 500
:title "Something very bad has happened!"
:message "We've dispatched a team of highly trained gnomes to take care of the problem."})))))
(defn wrap-csrf [handler]
(wrap-anti-forgery
handler
{:error-response
(error-page
{:status 403
:title "Invalid anti-forgery token"})}))
(defstate ^{:on-reload :noop} token-backend
:start
(backends/jws {:secret secret}))
(defn wrap-auth [handler]
(let [backend token-backend]
(-> handler
(wrap-authentication backend)
(wrap-authorization backend))))
(def parser
(p/parallel-parser
{::p/env {::p/reader [p/map-reader
pc/parallel-reader
pc/open-ident-reader
p/env-placeholder-reader]
::pc/mutation-join-globals [:tempids]
::p/placeholder-prefixes #{">"}}
::p/mutate pc/mutate-async
::p/plugins [(pc/connect-plugin {::pc/register my-resolvers})
(p/post-process-parser-plugin p/elide-not-found)
p/error-handler-plugin
;; p/request-cache-plugin
p/trace-plugin]}))
(defn wrap-api
[handler]
(let [parser (fn [env query] (async/<!! (parser env (log/spy query))))]
(fn [{:keys [uri] :as request}]
(if (= pathom-endpoint uri)
(server/handle-api-request
(:transit-params request)
(partial parser {:request request}))
(handler request)))))
(defn wrap-base [handler]
(let [session-store (cookie-store {:key (PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI)})]
(-> ((:middleware defaults) handler)
(wrap-api)
(server/wrap-transit-params)
(server/wrap-transit-response)
wrap-auth
wrap-csrf
(wrap-defaults
(assoc-in site-defaults [:session :store] session-store))
wrap-internal-error)))
|
[
{
"context": ")\n '{:find [e]\n :where [[e :name \"Pablo\"]]})\n;; end::query-valid-time[]\n)\n\n(defn query-ex",
"end": 1133,
"score": 0.9989749193191528,
"start": 1128,
"tag": "NAME",
"value": "Pablo"
},
{
"context": " ;; tag::query-input[]\n [{:crux.db/id :ivan\n :name \"Ivan\"\n :last-name \"Ivan",
"end": 1272,
"score": 0.8670274019241333,
"start": 1268,
"tag": "NAME",
"value": "ivan"
},
{
"context": "ut[]\n [{:crux.db/id :ivan\n :name \"Ivan\"\n :last-name \"Ivanov\"}\n\n {:crux.",
"end": 1294,
"score": 0.9996418952941895,
"start": 1290,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "ivan\n :name \"Ivan\"\n :last-name \"Ivanov\"}\n\n {:crux.db/id :petr\n :name \"P",
"end": 1324,
"score": 0.9996941685676575,
"start": 1318,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": " :last-name \"Ivanov\"}\n\n {:crux.db/id :petr\n :name \"Petr\"\n :last-name \"Petr",
"end": 1355,
"score": 0.6990002989768982,
"start": 1351,
"tag": "NAME",
"value": "petr"
},
{
"context": "v\"}\n\n {:crux.db/id :petr\n :name \"Petr\"\n :last-name \"Petrov\"}\n\n {:crux.",
"end": 1377,
"score": 0.9997525215148926,
"start": 1373,
"tag": "NAME",
"value": "Petr"
},
{
"context": "petr\n :name \"Petr\"\n :last-name \"Petrov\"}\n\n {:crux.db/id :smith\n :name \"",
"end": 1407,
"score": 0.9996426105499268,
"start": 1401,
"tag": "NAME",
"value": "Petrov"
},
{
"context": " :last-name \"Petrov\"}\n\n {:crux.db/id :smith\n :name \"Smith\"\n :last-name \"Smi",
"end": 1439,
"score": 0.49918726086616516,
"start": 1434,
"tag": "USERNAME",
"value": "smith"
},
{
"context": "\"}\n\n {:crux.db/id :smith\n :name \"Smith\"\n :last-name \"Smith\"}]\n ;; end::q",
"end": 1462,
"score": 0.9997307062149048,
"start": 1457,
"tag": "NAME",
"value": "Smith"
},
{
"context": "ith\n :name \"Smith\"\n :last-name \"Smith\"}]\n ;; end::query-input[]\n ]\n\n (",
"end": 1491,
"score": 0.9997768402099609,
"start": 1486,
"tag": "NAME",
"value": "Smith"
},
{
"context": " [p1 :last-name n]\n [p1 :name \"Smith\"]]}\n ;; end::basic-query[]\n))\n\n;; tag::basic-quer",
"end": 1830,
"score": 0.9996545910835266,
"start": 1825,
"tag": "NAME",
"value": "Smith"
},
{
"context": "e '[[e :name n]]\n :args [{'e :ivan\n 'n \"Ivan\"}]}\n ;; end::query-with-arguments1[]\n))\n\n;; tag::",
"end": 2100,
"score": 0.9981175661087036,
"start": 2096,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "ents1[]\n))\n\n;; tag::query-with-arguments1-r[]\n#{[\"Ivan\"]}\n;; end::query-with-arguments1-r[]\n\n(defn query",
"end": 2184,
"score": 0.9967451095581055,
"start": 2180,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "{:find '[e]\n :where '[[e :name n]]\n :args [{'n \"Ivan\"}\n {'n \"Petr\"}]}\n ;; end::query-with-arg",
"end": 2382,
"score": 0.9989819526672363,
"start": 2378,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "'[[e :name n]]\n :args [{'n \"Ivan\"}\n {'n \"Petr\"}]}\n ;; end::query-with-arguments2[]\n))\n\n;; tag:",
"end": 2403,
"score": 0.9991098642349243,
"start": 2399,
"tag": "NAME",
"value": "Petr"
},
{
"context": "ame n]\n [e :last-name l]]\n :args [{'n \"Ivan\" 'l \"Ivanov\"}\n {'n \"Petr\" 'l \"Petrov\"}]}\n",
"end": 2721,
"score": 0.9991058707237244,
"start": 2717,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " [e :last-name l]]\n :args [{'n \"Ivan\" 'l \"Ivanov\"}\n {'n \"Petr\" 'l \"Petrov\"}]}\n ;; end::que",
"end": 2733,
"score": 0.9973311424255371,
"start": 2727,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "]]\n :args [{'n \"Ivan\" 'l \"Ivanov\"}\n {'n \"Petr\" 'l \"Petrov\"}]}\n ;; end::query-with-arguments3[]\n",
"end": 2754,
"score": 0.9993174076080322,
"start": 2750,
"tag": "NAME",
"value": "Petr"
},
{
"context": " [{'n \"Ivan\" 'l \"Ivanov\"}\n {'n \"Petr\" 'l \"Petrov\"}]}\n ;; end::query-with-arguments3[]\n))\n\n;; tag::",
"end": 2766,
"score": 0.998919665813446,
"start": 2760,
"tag": "NAME",
"value": "Petrov"
},
{
"context": "]\n :where '[[(re-find #\"I\" n)]\n [(= l \"Ivanov\")]]\n :args [{'n \"Ivan\" 'l \"Ivanov\"}\n {",
"end": 3064,
"score": 0.9186696410179138,
"start": 3060,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "I\" n)]\n [(= l \"Ivanov\")]]\n :args [{'n \"Ivan\" 'l \"Ivanov\"}\n {'n \"Petr\" 'l \"Petrov\"}]}\n",
"end": 3089,
"score": 0.9995787143707275,
"start": 3085,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " [(= l \"Ivanov\")]]\n :args [{'n \"Ivan\" 'l \"Ivanov\"}\n {'n \"Petr\" 'l \"Petrov\"}]}\n ;; end::que",
"end": 3101,
"score": 0.9993853569030762,
"start": 3095,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "]]\n :args [{'n \"Ivan\" 'l \"Ivanov\"}\n {'n \"Petr\" 'l \"Petrov\"}]}\n ;; end::query-with-arguments4[]\n",
"end": 3122,
"score": 0.9995687007904053,
"start": 3118,
"tag": "NAME",
"value": "Petr"
},
{
"context": " [{'n \"Ivan\" 'l \"Ivanov\"}\n {'n \"Petr\" 'l \"Petrov\"}]}\n ;; end::query-with-arguments4[]\n ))\n\n;; tag:",
"end": 3134,
"score": 0.9993485808372498,
"start": 3128,
"tag": "NAME",
"value": "Petrov"
},
{
"context": "nts4[]\n ))\n\n;; tag::query-with-arguments4-r[]\n#{[\"Ivan\"]}\n;; end::query-with-arguments4-r[]\n\n(defn query",
"end": 3219,
"score": 0.996323823928833,
"start": 3215,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " [p1 :name \"Smith\"]]})]\n (doseq [tuple (iterator-seq res)]\n ",
"end": 4152,
"score": 0.9996719360351562,
"start": 4147,
"tag": "NAME",
"value": "Smith"
},
{
"context": ":query-at-t-d1[]\n {:crux.db/id :malcolm :name \"Malcolm\" :last-name \"Sparks\"}\n #inst \"1986-10-22\"\n ",
"end": 4400,
"score": 0.9998616576194763,
"start": 4393,
"tag": "NAME",
"value": "Malcolm"
},
{
"context": "{:crux.db/id :malcolm :name \"Malcolm\" :last-name \"Sparks\"}\n #inst \"1986-10-22\"\n ;; end::query-at-t-d",
"end": 4420,
"score": 0.9998167157173157,
"start": 4414,
"tag": "NAME",
"value": "Sparks"
},
{
"context": ":query-at-t-d2[]\n {:crux.db/id :malcolm :name \"Malcolma\" :last-name \"Sparks\"}\n #inst \"1986-10-24\"\n ",
"end": 4593,
"score": 0.9998631477355957,
"start": 4585,
"tag": "NAME",
"value": "Malcolma"
},
{
"context": ":crux.db/id :malcolm :name \"Malcolma\" :last-name \"Sparks\"}\n #inst \"1986-10-24\"\n ;; end::query-at-t-d",
"end": 4613,
"score": 0.9997805953025818,
"start": 4607,
"tag": "NAME",
"value": "Sparks"
},
{
"context": "ery-at-t-q1[]\n '{:find [e]\n :where [[e :name \"Malcolma\"]\n [e :last-name \"Sparks\"]]}\n ;; end:",
"end": 4833,
"score": 0.9998534321784973,
"start": 4825,
"tag": "NAME",
"value": "Malcolma"
},
{
"context": " [[e :name \"Malcolma\"]\n [e :last-name \"Sparks\"]]}\n ;; end::query-at-t-q1[]\n))\n\n;; tag::query-a",
"end": 4869,
"score": 0.9997575283050537,
"start": 4863,
"tag": "NAME",
"value": "Sparks"
},
{
"context": "ux/db node)\n '{:find [e]\n :where [[e :name \"Malcolma\"]\n [e :last-name \"Sparks\"]]}))\n\n;; ta",
"end": 5196,
"score": 0.9998566508293152,
"start": 5188,
"tag": "NAME",
"value": "Malcolma"
},
{
"context": "[[e :name \"Malcolma\"]\n [e :last-name \"Sparks\"]]}))\n\n;; tag::query-at-t-q2-q[]\n; Using Clojure:",
"end": 5233,
"score": 0.9997705817222595,
"start": 5227,
"tag": "NAME",
"value": "Sparks"
},
{
"context": "{:crux.db/id :ids.persons/Jeff\n :person/name \"Jeff\"\n :person/wealth 100}\n #inst \"2018-05-18T0",
"end": 5543,
"score": 0.9997620582580566,
"start": 5539,
"tag": "NAME",
"value": "Jeff"
},
{
"context": "{:crux.db/id :ids.persons/Jeff\n :person/name \"Jeff\"\n :person/wealth 1000}\n #inst \"2015-05-18T",
"end": 5682,
"score": 0.999771237373352,
"start": 5678,
"tag": "NAME",
"value": "Jeff"
},
{
"context": " {:crux.db/id :ids.persons/Jeff\n :person/name \"Jeff\"\n :person/wealth 100}}\n {:crux.tx/tx-time #inst",
"end": 6923,
"score": 0.9997379779815674,
"start": 6919,
"tag": "NAME",
"value": "Jeff"
},
{
"context": " {:crux.db/id :ids.persons/Jeff\n :person/name \"Jeff\"\n :person/wealth 1000}}]\n;; end::history-with-d",
"end": 7236,
"score": 0.9995418190956116,
"start": 7232,
"tag": "NAME",
"value": "Jeff"
},
{
"context": " tag::join-d[]\n [{:crux.db/id :ivan :name \"Ivan\"}\n {:crux.db/id :petr :name \"Petr\"}\n ",
"end": 8594,
"score": 0.9814175367355347,
"start": 8590,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " :name \"Ivan\"}\n {:crux.db/id :petr :name \"Petr\"}\n {:crux.db/id :sergei :name \"Sergei\"}\n ",
"end": 8636,
"score": 0.8945067524909973,
"start": 8632,
"tag": "NAME",
"value": "Petr"
},
{
"context": "name \"Petr\"}\n {:crux.db/id :sergei :name \"Sergei\"}\n {:crux.db/id :denis-a :name \"Denis\"}\n ",
"end": 8682,
"score": 0.9169917702674866,
"start": 8676,
"tag": "NAME",
"value": "Sergei"
},
{
"context": "e \"Sergei\"}\n {:crux.db/id :denis-a :name \"Denis\"}\n {:crux.db/id :denis-b :name \"Denis\"}]\n",
"end": 8728,
"score": 0.8265758752822876,
"start": 8723,
"tag": "NAME",
"value": "Denis"
},
{
"context": "me \"Denis\"}\n {:crux.db/id :denis-b :name \"Denis\"}]\n ;; end::join-d[]\n ]\n (crux/s",
"end": 8774,
"score": 0.8501074910163879,
"start": 8769,
"tag": "NAME",
"value": "Denis"
},
{
"context": "[]\n))\n\n;; tag::join-r[]\n#{[:ivan :ivan]\n [:petr :petr]\n [:sergei :sergei]\n [:denis-a :denis-a]\n [:",
"end": 9140,
"score": 0.3809885084629059,
"start": 9138,
"tag": "NAME",
"value": "pe"
},
{
"context": "tag::join-r[]\n#{[:ivan :ivan]\n [:petr :petr]\n [:sergei :sergei]\n [:denis-a :denis-a]\n [:denis-b :denis",
"end": 9154,
"score": 0.8808771967887878,
"start": 9148,
"tag": "USERNAME",
"value": "sergei"
},
{
"context": "n-r[]\n#{[:ivan :ivan]\n [:petr :petr]\n [:sergei :sergei]\n [:denis-a :denis-a]\n [:denis-b :denis-b]\n [:",
"end": 9162,
"score": 0.6726284623146057,
"start": 9156,
"tag": "USERNAME",
"value": "sergei"
},
{
"context": "maps\n ;; tag::join2-d[]\n [{:crux.db/id :ivan :name \"Ivan\" :last-name \"Ivanov\"}\n {:crux",
"end": 9372,
"score": 0.5488917231559753,
"start": 9370,
"tag": "USERNAME",
"value": "iv"
},
{
"context": "; tag::join2-d[]\n [{:crux.db/id :ivan :name \"Ivan\" :last-name \"Ivanov\"}\n {:crux.db/id :petr :",
"end": 9386,
"score": 0.9998041391372681,
"start": 9382,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " [{:crux.db/id :ivan :name \"Ivan\" :last-name \"Ivanov\"}\n {:crux.db/id :petr :name \"Petr\" :follows",
"end": 9406,
"score": 0.9997989535331726,
"start": 9400,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "t-name \"Ivanov\"}\n {:crux.db/id :petr :name \"Petr\" :follows #{\"Ivanov\"}}]\n ;; end::join2-d[]\n ",
"end": 9446,
"score": 0.999653697013855,
"start": 9442,
"tag": "NAME",
"value": "Petr"
},
{
"context": " {:crux.db/id :petr :name \"Petr\" :follows #{\"Ivanov\"}}]\n ;; end::join2-d[]\n ]\n (crux/submi",
"end": 9466,
"score": 0.848859429359436,
"start": 9461,
"tag": "NAME",
"value": "vanov"
},
{
"context": "]\n [e2 :follows l]\n [e :name \"Ivan\"]]}\n ;; end::join2-q[]\n))\n\n;; tag::join2-r[]\n#{[:",
"end": 9786,
"score": 0.9997599124908447,
"start": 9782,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "test-blanks\n (f/transact-people! *kv* [{:name \"Ivan\"} {:name \"Petr\"} {:name \"Sergei\"}])\n\n (t/is (=",
"end": 13120,
"score": 0.9996485710144043,
"start": 13116,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " (f/transact-people! *kv* [{:name \"Ivan\"} {:name \"Petr\"} {:name \"Sergei\"}])\n\n (t/is (= #{[\"Ivan\"] [\"P",
"end": 13135,
"score": 0.9998300671577454,
"start": 13131,
"tag": "NAME",
"value": "Petr"
},
{
"context": "ople! *kv* [{:name \"Ivan\"} {:name \"Petr\"} {:name \"Sergei\"}])\n\n (t/is (= #{[\"Ivan\"] [\"Petr\"] [\"Sergei\"]}",
"end": 13152,
"score": 0.9998317360877991,
"start": 13146,
"tag": "NAME",
"value": "Sergei"
},
{
"context": "name \"Petr\"} {:name \"Sergei\"}])\n\n (t/is (= #{[\"Ivan\"] [\"Petr\"] [\"Sergei\"]}\n (api/q (api/d",
"end": 13179,
"score": 0.9998079538345337,
"start": 13175,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "r\"} {:name \"Sergei\"}])\n\n (t/is (= #{[\"Ivan\"] [\"Petr\"] [\"Sergei\"]}\n (api/q (api/db *kv*) '",
"end": 13188,
"score": 0.9998391270637512,
"start": 13184,
"tag": "NAME",
"value": "Petr"
},
{
"context": "e \"Sergei\"}])\n\n (t/is (= #{[\"Ivan\"] [\"Petr\"] [\"Sergei\"]}\n (api/q (api/db *kv*) '{:find [nam",
"end": 13199,
"score": 0.9998435974121094,
"start": 13193,
"tag": "NAME",
"value": "Sergei"
},
{
"context": "-people! *kv* [{:crux.db/id :ivan-ivanov-1 :name \"Ivan\" :last-name \"Ivanov\"}\n ",
"end": 13450,
"score": 0.9997650980949402,
"start": 13446,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "rux.db/id :ivan-ivanov-1 :name \"Ivan\" :last-name \"Ivanov\"}\n {:crux.db/id :iva",
"end": 13470,
"score": 0.9997574687004089,
"start": 13464,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": " {:crux.db/id :ivan-ivanov-2 :name \"Ivan\" :last-name \"Ivanov\"}\n ",
"end": 13542,
"score": 0.9997844696044922,
"start": 13538,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "rux.db/id :ivan-ivanov-2 :name \"Ivan\" :last-name \"Ivanov\"}\n {:crux.db/id :iva",
"end": 13562,
"score": 0.9998087286949158,
"start": 13556,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": " {:crux.db/id :ivan-ivanovtov-1 :name \"Ivan\" :last-name \"Ivannotov\"}])\n\n (t/testing \"liter",
"end": 13637,
"score": 0.9998354911804199,
"start": 13633,
"tag": "NAME",
"value": "Ivan"
},
{
"context": ".db/id :ivan-ivanovtov-1 :name \"Ivan\" :last-name \"Ivannotov\"}])\n\n (t/testing \"literal v\"\n (t/is (= 2 ",
"end": 13660,
"score": 0.9998178482055664,
"start": 13651,
"tag": "NAME",
"value": "Ivannotov"
},
{
"context": " [e :name \"Ivan\"]\n ",
"end": 13889,
"score": 0.9997996091842651,
"start": 13885,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " (not [e :last-name \"Ivannotov\"])]}))))\n\n (t/testing \"multiple clauses in n",
"end": 13976,
"score": 0.999812126159668,
"start": 13967,
"tag": "NAME",
"value": "Ivannotov"
},
{
"context": " [e :name \"Ivan\"]\n ",
"end": 14232,
"score": 0.9997910261154175,
"start": 14228,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " (not [e :last-name \"Ivannotov\"]\n ",
"end": 14321,
"score": 0.999722421169281,
"start": 14312,
"tag": "NAME",
"value": "Ivannotov"
},
{
"context": "st-or-query\n (f/transact-people! *kv* [{:name \"Ivan\" :last-name \"Ivanov\"}\n ",
"end": 14853,
"score": 0.9998173117637634,
"start": 14849,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "/transact-people! *kv* [{:name \"Ivan\" :last-name \"Ivanov\"}\n {:name \"Ivan\" :la",
"end": 14873,
"score": 0.9997687935829163,
"start": 14867,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "e \"Ivanov\"}\n {:name \"Ivan\" :last-name \"Ivanov\"}\n ",
"end": 14918,
"score": 0.9998184442520142,
"start": 14914,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " {:name \"Ivan\" :last-name \"Ivanov\"}\n {:name \"Ivan\" :la",
"end": 14938,
"score": 0.9998064637184143,
"start": 14932,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "e \"Ivanov\"}\n {:name \"Ivan\" :last-name \"Ivannotov\"}\n ",
"end": 14983,
"score": 0.9998418092727661,
"start": 14979,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " {:name \"Ivan\" :last-name \"Ivannotov\"}\n {:name \"Bob\" :las",
"end": 15006,
"score": 0.9998219609260559,
"start": 14997,
"tag": "NAME",
"value": "Ivannotov"
},
{
"context": "Ivannotov\"}\n {:name \"Bob\" :last-name \"Controlguy\"}])\n\n (t/testing \"Or w",
"end": 15050,
"score": 0.9997109174728394,
"start": 15047,
"tag": "NAME",
"value": "Bob"
},
{
"context": " {:name \"Bob\" :last-name \"Controlguy\"}])\n\n (t/testing \"Or works as expected\"\n ",
"end": 15074,
"score": 0.9953194260597229,
"start": 15064,
"tag": "NAME",
"value": "Controlguy"
},
{
"context": " [e :name \"Ivan\"]\n ",
"end": 15314,
"score": 0.9997811913490295,
"start": 15310,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " (or [e :last-name \"Ivanov\"]\n ",
"end": 15397,
"score": 0.9998243451118469,
"start": 15391,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": " [e :last-name \"Ivannotov\"])]}))))))\n ;; end::or[]\n\n ;; tag::or-and[]\n (",
"end": 15483,
"score": 0.9998144507408142,
"start": 15474,
"tag": "NAME",
"value": "Ivannotov"
},
{
"context": " (let [[ivan] (f/transact-people! *kv* [{:name \"Ivan\" :sex :male}\n ",
"end": 15624,
"score": 0.9998023509979248,
"start": 15620,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " {:name \"Bob\" :sex :male}\n ",
"end": 15692,
"score": 0.999856173992157,
"start": 15689,
"tag": "NAME",
"value": "Bob"
},
{
"context": " {:name \"Ivana\" :sex :female}])]\n\n (t/is (= #{[\"Ivan\"]\n ",
"end": 15762,
"score": 0.9997996091842651,
"start": 15757,
"tag": "NAME",
"value": "Ivana"
},
{
"context": "name \"Ivana\" :sex :female}])]\n\n (t/is (= #{[\"Ivan\"]\n [\"Ivana\"]}\n (api",
"end": 15805,
"score": 0.9998111724853516,
"start": 15801,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "])]\n\n (t/is (= #{[\"Ivan\"]\n [\"Ivana\"]}\n (api/q (api/db *kv*) '{:find [n",
"end": 15832,
"score": 0.9998172521591187,
"start": 15827,
"tag": "NAME",
"value": "Ivana"
},
{
"context": " [e :name \"Ivan\"]))]})))))\n ;; end::or-and[]\n\n ;; tag::or-and2[",
"end": 16154,
"score": 0.9998342990875244,
"start": 16150,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "r ivan ivanova] (f/transact-people! *kv* [{:name \"Petr\" :last-name \"Smith\" :sex :male}\n ",
"end": 16323,
"score": 0.9998167753219604,
"start": 16319,
"tag": "NAME",
"value": "Petr"
},
{
"context": "/transact-people! *kv* [{:name \"Petr\" :last-name \"Smith\" :sex :male}\n ",
"end": 16342,
"score": 0.9997014999389648,
"start": 16337,
"tag": "NAME",
"value": "Smith"
},
{
"context": " {:name \"Ivan\" :last-name \"Ivanov\" :sex :male}\n ",
"end": 16424,
"score": 0.9998107552528381,
"start": 16420,
"tag": "NAME",
"value": "Ivan"
},
{
"context": " {:name \"Ivan\" :last-name \"Ivanov\" :sex :male}\n ",
"end": 16444,
"score": 0.9993665814399719,
"start": 16438,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": " {:name \"Ivanova\" :last-name \"Ivanov\" :sex :female}])]\n\n (t/t",
"end": 16529,
"score": 0.9998054504394531,
"start": 16522,
"tag": "NAME",
"value": "Ivanova"
},
{
"context": " {:name \"Ivanova\" :last-name \"Ivanov\" :sex :female}])]\n\n (t/testing \"?p2 introduc",
"end": 16549,
"score": 0.9997654557228088,
"start": 16543,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": " :where [(or (and [?p2 :name \"Petr\"]\n ",
"end": 16797,
"score": 0.9997857809066772,
"start": 16793,
"tag": "NAME",
"value": "Petr"
},
{
"context": " (and [?p2 :last-name \"Ivanov\"]\n ",
"end": 17005,
"score": 0.9997757077217102,
"start": 16999,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "st-not-join\n (f/transact-people! *kv* [{:name \"Ivan\" :last-name \"Ivanov\"}\n ",
"end": 17227,
"score": 0.9998366832733154,
"start": 17223,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "/transact-people! *kv* [{:name \"Ivan\" :last-name \"Ivanov\"}\n {:name \"Malcolm\" ",
"end": 17247,
"score": 0.9997756481170654,
"start": 17241,
"tag": "NAME",
"value": "Ivanov"
},
{
"context": "e \"Ivanov\"}\n {:name \"Malcolm\" :last-name \"Ofsparks\"}\n ",
"end": 17295,
"score": 0.9998366236686707,
"start": 17288,
"tag": "NAME",
"value": "Malcolm"
},
{
"context": " {:name \"Malcolm\" :last-name \"Ofsparks\"}\n {:name \"Dominic\" ",
"end": 17317,
"score": 0.9996095299720764,
"start": 17309,
"tag": "NAME",
"value": "Ofsparks"
},
{
"context": "\"Ofsparks\"}\n {:name \"Dominic\" :last-name \"Monroe\"}])\n\n (t/testing \"Rudiment",
"end": 17365,
"score": 0.9998456835746765,
"start": 17358,
"tag": "NAME",
"value": "Dominic"
},
{
"context": " {:name \"Dominic\" :last-name \"Monroe\"}])\n\n (t/testing \"Rudimentary not-join\"\n ",
"end": 17385,
"score": 0.9998269081115723,
"start": 17379,
"tag": "NAME",
"value": "Monroe"
},
{
"context": "testing \"Rudimentary not-join\"\n (t/is (= #{[\"Ivan\"] [\"Malcolm\"]}\n (api/q (api/db *kv*",
"end": 17452,
"score": 0.9998378753662109,
"start": 17448,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "Rudimentary not-join\"\n (t/is (= #{[\"Ivan\"] [\"Malcolm\"]}\n (api/q (api/db *kv*) '{:find [n",
"end": 17464,
"score": 0.9998117089271545,
"start": 17457,
"tag": "NAME",
"value": "Malcolm"
},
{
"context": " [e :last-name \"Monroe\"])]})))))\n ;; end::not-join[]\n\n )\n",
"end": 17717,
"score": 0.9997406005859375,
"start": 17711,
"tag": "NAME",
"value": "Monroe"
}
] | docs/reference/modules/ROOT/examples/src/docs/examples.clj | deobald/crux | 0 | (ns docs.examples
(:require [clojure.java.io :as io]
[crux.api :as crux]))
;; tag::require-ek[]
(require '[crux.kafka.embedded :as ek])
;; end::require-ek[]
;; tag::ek-example[]
(defn start-embedded-kafka [kafka-port storage-dir]
(ek/start-embedded-kafka {:crux.kafka.embedded/zookeeper-data-dir (io/file storage-dir "zk-data")
:crux.kafka.embedded/kafka-log-dir (io/file storage-dir "kafka-log")
:crux.kafka.embedded/kafka-port kafka-port}))
;; end::ek-example[]
(defn stop-embedded-kafka [^java.io.Closeable embedded-kafka]
;; tag::ek-close[]
(.close embedded-kafka)
;; end::ek-close[]
)
;; tag::start-http-client[]
(defn start-http-client [port]
(crux/new-api-client (str "http://localhost:" port)))
;; end::start-http-client[]
(defn example-query-entity [node]
;; tag::query-entity[]
(crux/entity (crux/db node) :dbpedia.resource/Pablo-Picasso)
;; end::query-entity[]
)
(defn example-query-valid-time [node]
;; tag::query-valid-time[]
(crux/q (crux/db node #inst "2018-05-19T09:20:27.966-00:00")
'{:find [e]
:where [[e :name "Pablo"]]})
;; end::query-valid-time[]
)
(defn query-example-setup [node]
(let [maps
;; tag::query-input[]
[{:crux.db/id :ivan
:name "Ivan"
:last-name "Ivanov"}
{:crux.db/id :petr
:name "Petr"
:last-name "Petrov"}
{:crux.db/id :smith
:name "Smith"
:last-name "Smith"}]
;; end::query-input[]
]
(crux/submit-tx node
(vec (for [m maps]
[:crux.tx/put m])))))
(defn query-example-basic-query [node]
(crux/q
(crux/db node)
;; tag::basic-query[]
'{:find [p1]
:where [[p1 :name n]
[p1 :last-name n]
[p1 :name "Smith"]]}
;; end::basic-query[]
))
;; tag::basic-query-r[]
#{[:smith]}
;; end::basic-query-r[]
(defn query-example-with-arguments-1 [node]
(crux/q
(crux/db node)
;; tag::query-with-arguments1[]
{:find '[n]
:where '[[e :name n]]
:args [{'e :ivan
'n "Ivan"}]}
;; end::query-with-arguments1[]
))
;; tag::query-with-arguments1-r[]
#{["Ivan"]}
;; end::query-with-arguments1-r[]
(defn query-example-with-arguments-2 [node]
(crux/q
(crux/db node)
;; tag::query-with-arguments2[]
{:find '[e]
:where '[[e :name n]]
:args [{'n "Ivan"}
{'n "Petr"}]}
;; end::query-with-arguments2[]
))
;; tag::query-with-arguments2-r[]
#{[:petr] [:ivan]}
;; end::query-with-arguments2-r[]
(defn query-example-with-arguments-3 [node]
(crux/q
(crux/db node)
;; tag::query-with-arguments3[]
{:find '[e]
:where '[[e :name n]
[e :last-name l]]
:args [{'n "Ivan" 'l "Ivanov"}
{'n "Petr" 'l "Petrov"}]}
;; end::query-with-arguments3[]
))
;; tag::query-with-arguments3-r[]
#{[:petr] [:ivan]}
;; end::query-with-arguments3-r[]
(defn query-example-with-arguments-4 [node]
(crux/q
(crux/db node)
;; tag::query-with-arguments4[]
{:find '[n]
:where '[[(re-find #"I" n)]
[(= l "Ivanov")]]
:args [{'n "Ivan" 'l "Ivanov"}
{'n "Petr" 'l "Petrov"}]}
;; end::query-with-arguments4[]
))
;; tag::query-with-arguments4-r[]
#{["Ivan"]}
;; end::query-with-arguments4-r[]
(defn query-example-with-arguments-5 [node]
(crux/q
(crux/db node)
;; tag::query-with-arguments5[]
{:find '[age]
:where '[[(>= age 21)]]
:args [{'age 22}]}
;; end::query-with-arguments5[]
))
;; tag::query-with-arguments5-r[]
#{[22]}
;; end::query-with-arguments5-r[]
(defn query-example-with-predicate-1 [node]
(crux/q
(crux/db node)
;; tag::query-with-pred-1[]
{:find '[age]
:where '[[(odd? age)]]
:args [{'age 22} {'age 21}]}
;; end::query-with-pred-1[]
))
;; tag::query-with-pred-1-r[]
#{[21]}
;; end::query-with-pred-1-r[]
(defn query-example-streaming [node prn]
;; tag::streaming-query[]
(with-open [res (crux/open-q (crux/db node)
'{:find [p1]
:where [[p1 :name n]
[p1 :last-name n]
[p1 :name "Smith"]]})]
(doseq [tuple (iterator-seq res)]
(prn tuple)))
;; end::streaming-query[]
)
(defn query-example-at-time-setup [node]
(crux/submit-tx
node
[[:crux.tx/put
;; tag::query-at-t-d1[]
{:crux.db/id :malcolm :name "Malcolm" :last-name "Sparks"}
#inst "1986-10-22"
;; end::query-at-t-d1[]
]])
(crux/submit-tx
node
[[:crux.tx/put
;; tag::query-at-t-d2[]
{:crux.db/id :malcolm :name "Malcolma" :last-name "Sparks"}
#inst "1986-10-24"
;; end::query-at-t-d2[]
]]))
(defn query-example-at-time-q1 [node]
(crux/q
(crux/db
node #inst "1986-10-23")
;; tag::query-at-t-q1[]
'{:find [e]
:where [[e :name "Malcolma"]
[e :last-name "Sparks"]]}
;; end::query-at-t-q1[]
))
;; tag::query-at-t-q1-q[]
; Using Clojure: `(api/q (api/db my-crux-node #inst "1986-10-23") q)`
;; end::query-at-t-q1-q[]
;; tag::query-at-t-q1-r[]
#{}
;; end::query-at-t-q1-r[]
(defn query-example-at-time-q2 [node]
(crux/q
(crux/db node)
'{:find [e]
:where [[e :name "Malcolma"]
[e :last-name "Sparks"]]}))
;; tag::query-at-t-q2-q[]
; Using Clojure: `(api/q (api/db my-crux-node) q)`
;; end::query-at-t-q2-q[]
;; tag::query-at-t-q2-r[]
#{[:malcolm]}
;; end::query-at-t-q2-r[]
#_(comment
;; tag::history-full[]
(api/submit-tx
node
[[:crux.tx/put
{:crux.db/id :ids.persons/Jeff
:person/name "Jeff"
:person/wealth 100}
#inst "2018-05-18T09:20:27.966"]
[:crux.tx/put
{:crux.db/id :ids.persons/Jeff
:person/name "Jeff"
:person/wealth 1000}
#inst "2015-05-18T09:20:27.966"]])
; yields
{:crux.tx/tx-id 1555314836178,
:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00"}
; Returning the history in descending order
; To return in ascending order, use :asc in place of :desc
(api/entity-history (api/db node) :ids.persons/Jeff :desc)
; yields
[{:crux.tx/tx-time #inst "2019-04-15T07:53:55.817-00:00",
:crux.tx/tx-id 1555314835817,
:crux.db/valid-time #inst "2018-05-18T09:20:27.966-00:00",
:crux.db/content-hash ; sha1 hash of document contents
"6ca48d3bf05a16cd8d30e6b466f76d5cc281b561"}
{:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00",
:crux.tx/tx-id 1555314836178,
:crux.db/valid-time #inst "2015-05-18T09:20:27.966-00:00",
:crux.db/content-hash "a95f149636e0a10a78452298e2135791c0203529"}]
;; end::history-full[]
;; tag::history-with-docs[]
(api/entity-history (api/db node) :ids.persons/Jeff :desc {:with-docs? true})
; yields
[{:crux.tx/tx-time #inst "2019-04-15T07:53:55.817-00:00",
:crux.tx/tx-id 1555314835817,
:crux.db/valid-time #inst "2018-05-18T09:20:27.966-00:00",
:crux.db/content-hash
"6ca48d3bf05a16cd8d30e6b466f76d5cc281b561"
:crux.db/doc
{:crux.db/id :ids.persons/Jeff
:person/name "Jeff"
:person/wealth 100}}
{:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00",
:crux.tx/tx-id 1555314836178,
:crux.db/valid-time #inst "2015-05-18T09:20:27.966-00:00",
:crux.db/content-hash "a95f149636e0a10a78452298e2135791c0203529"
:crux.db/doc
{:crux.db/id :ids.persons/Jeff
:person/name "Jeff"
:person/wealth 1000}}]
;; end::history-with-docs[]
;; tag::history-range[]
; Passing the aditional 'opts' map with the start/end bounds.
; As we are returning results in :asc order, the :start map contains the earlier co-ordinates -
; If returning history range in descending order, we pass the later co-ordinates to the :start map
(api/entity-history
(api/db node)
:ids.persons/Jeff
:asc
{:start {:crux.db/valid-time #inst "2015-05-18T09:20:27.966" ; valid-time-start
:crux.tx/tx-time #inst "2015-05-18T09:20:27.966"} ; tx-time-start
:end {:crux.db/valid-time #inst "2020-05-18T09:20:27.966" ; valid-time-end
:crux.tx/tx-time #inst "2020-05-18T09:20:27.966"} ; tx-time-end
})
; yields
[{:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00",
:crux.tx/tx-id 1555314836178,
:crux.db/valid-time #inst "2015-05-18T09:20:27.966-00:00",
:crux.db/content-hash
"a95f149636e0a10a78452298e2135791c0203529"}
{:crux.tx/tx-time #inst "2019-04-15T07:53:55.817-00:00",
:crux.tx/tx-id 1555314835817
:crux.db/valid-time #inst "2018-05-18T09:20:27.966-00:00",
:crux.db/content-hash "6ca48d3bf05a16cd8d30e6b466f76d5cc281b561"}]
;; end::history-range[]
)
(defn query-example-join-q1-setup [node]
;; Five people, two of which share the same name:
(let [maps
;; tag::join-d[]
[{:crux.db/id :ivan :name "Ivan"}
{:crux.db/id :petr :name "Petr"}
{:crux.db/id :sergei :name "Sergei"}
{:crux.db/id :denis-a :name "Denis"}
{:crux.db/id :denis-b :name "Denis"}]
;; end::join-d[]
]
(crux/submit-tx node
(vec (for [m maps]
[:crux.tx/put m])))))
(defn query-example-join-q1 [node]
(crux/q
(crux/db node)
;; tag::join-q[]
'{:find [p1 p2]
:where [[p1 :name n]
[p2 :name n]]}
;; end::join-q[]
))
;; tag::join-r[]
#{[:ivan :ivan]
[:petr :petr]
[:sergei :sergei]
[:denis-a :denis-a]
[:denis-b :denis-b]
[:denis-a :denis-b]
[:denis-b :denis-a]}
;; end::join-r[]
(defn query-example-join-q2-setup [node]
(let [maps
;; tag::join2-d[]
[{:crux.db/id :ivan :name "Ivan" :last-name "Ivanov"}
{:crux.db/id :petr :name "Petr" :follows #{"Ivanov"}}]
;; end::join2-d[]
]
(crux/submit-tx node
(vec (for [m maps]
[:crux.tx/put m])))))
(defn query-example-join-q2 [node]
(crux/q
(crux/db node)
;; tag::join2-q[]
'{:find [e2]
:where [[e :last-name l]
[e2 :follows l]
[e :name "Ivan"]]}
;; end::join2-q[]
))
;; tag::join2-r[]
#{[:petr]}
;; end::join2-r[]
(comment
;; tag::bitemp0[]
{:crux.db/id :p2
:entry-pt :SFO
:arrival-time #inst "2018-12-31"
:departure-time :na}
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2018-12-31"
;; end::bitemp0[]
;; tag::bitemp2[]
{:crux.db/id :p4
:entry-pt :NY
:arrival-time #inst "2019-01-02"
:departure-time :na}
#inst "2019-01-02"
;; end::bitemp2[]
;; tag::bitemp3[]
{:crux.db/id :p4
:entry-pt :NY
:arrival-time #inst "2019-01-02"
:departure-time #inst "2019-01-03"}
#inst "2019-01-03"
;; end::bitemp3[]
;; tag::bitemp4[]
{:crux.db/id :p1
:entry-pt :NY
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2018-12-31"
;; end::bitemp4[]
;; tag::bitemp4b[]
{:crux.db/id :p1
:entry-pt :NY
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-03"}
#inst "2019-01-03"
;; end::bitemp4b[]
;; tag::bitemp4c[]
{:crux.db/id :p1
:entry-pt :LA
:arrival-time #inst "2019-01-04"
:departure-time :na}
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-04"}
#inst "2019-01-04"
;; end::bitemp4c[]
;; tag::bitemp5[]
{:crux.db/id :p2
:entry-pt :SFO
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-05"}
#inst "2019-01-05"
;; end::bitemp5[]
;; tag::bitemp7[]
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2019-01-04"
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-07"}
#inst "2019-01-07"
;; end::bitemp7[]
;; tag::bitemp8[]
{:crux.db/id :p3
:entry-pt :SFO
:arrival-time #inst "2019-01-08"
:departure-time :na}
#inst "2019-01-08"
{:crux.db/id :p4
:entry-pt :LA
:arrival-time #inst "2019-01-08"
:departure-time :na}
#inst "2019-01-08"
;; end::bitemp8[]
;; tag::bitemp9[]
{:crux.db/id :p3
:entry-pt :SFO
:arrival-time #inst "2019-01-08"
:departure-time #inst "2019-01-08"}
#inst "2019-01-09"
;; end::bitemp9[]
;; tag::bitemp10[]
{:crux.db/id :p5
:entry-pt :LA
:arrival-time #inst "2019-01-10"
:departure-time :na}
#inst "2019-01-10"
;; end::bitemp10[]
;; tag::bitemp11[]
{:crux.db/id :p7
:entry-pt :NY
:arrival-time #inst "2019-01-11"
:departure-time :na}
#inst "2019-01-11"
;; end::bitemp11[]
;; tag::bitemp12[]
{:crux.db/id :p6
:entry-pt :NY
:arrival-time #inst "2019-01-12"
:departure-time :na}
#inst "2019-01-12"
;; end::bitemp12[]
;; tag::bitempq[]
{:find [p entry-pt arrival-time departure-time]
:where [[p :entry-pt entry-pt]
[p :arrival-time arrival-time]
[p :departure-time departure-time]]}
#inst "2019-01-03" ; `as of` transaction time
#inst "2019-01-02" ; `as at` valid time
;; end::bitempq[]
;; tag::bitempr[]
#{[:p2 :SFO #inst "2018-12-31" :na]
[:p3 :LA #inst "2018-12-31" :na]
[:p4 :NY #inst "2019-01-02" :na]}
;; end::bitempr[]
)
(comment ;; Not currently used, but could be useful after some reworking.
;; tag::blanks[]
(t/deftest test-blanks
(f/transact-people! *kv* [{:name "Ivan"} {:name "Petr"} {:name "Sergei"}])
(t/is (= #{["Ivan"] ["Petr"] ["Sergei"]}
(api/q (api/db *kv*) '{:find [name]
:where [[_ :name name]]}))))
;; end::blanks[]
;; tag::not[]
(t/deftest test-not-query
(f/transact-people! *kv* [{:crux.db/id :ivan-ivanov-1 :name "Ivan" :last-name "Ivanov"}
{:crux.db/id :ivan-ivanov-2 :name "Ivan" :last-name "Ivanov"}
{:crux.db/id :ivan-ivanovtov-1 :name "Ivan" :last-name "Ivannotov"}])
(t/testing "literal v"
(t/is (= 2 (count (api/q (api/db *kv*) '{:find [e]
:where [[e :name name]
[e :name "Ivan"]
(not [e :last-name "Ivannotov"])]}))))
(t/testing "multiple clauses in not"
(t/is (= 2 (count (api/q (api/db *kv*) '{:find [e]
:where [[e :name name]
[e :name "Ivan"]
(not [e :last-name "Ivannotov"]
[(string? name)])]}))))))
(t/testing "variable v"
(t/is (= 2 (count (api/q (api/db *kv*) '{:find [e]
:where [[e :name name]
[:ivan-ivanovtov-1 :last-name i-name]
(not [e :last-name i-name])]}))))))
;; end::not[]
;; tag::or[]
(t/deftest test-or-query
(f/transact-people! *kv* [{:name "Ivan" :last-name "Ivanov"}
{:name "Ivan" :last-name "Ivanov"}
{:name "Ivan" :last-name "Ivannotov"}
{:name "Bob" :last-name "Controlguy"}])
(t/testing "Or works as expected"
(t/is (= 3 (count (api/q (api/db *kv*) '{:find [e]
:where [[e :name name]
[e :name "Ivan"]
(or [e :last-name "Ivanov"]
[e :last-name "Ivannotov"])]}))))))
;; end::or[]
;; tag::or-and[]
(t/deftest test-or-query-can-use-and
(let [[ivan] (f/transact-people! *kv* [{:name "Ivan" :sex :male}
{:name "Bob" :sex :male}
{:name "Ivana" :sex :female}])]
(t/is (= #{["Ivan"]
["Ivana"]}
(api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
(or [e :sex :female]
(and [e :sex :male]
[e :name "Ivan"]))]})))))
;; end::or-and[]
;; tag::or-and2[]
(t/deftest test-ors-can-introduce-new-bindings
(let [[petr ivan ivanova] (f/transact-people! *kv* [{:name "Petr" :last-name "Smith" :sex :male}
{:name "Ivan" :last-name "Ivanov" :sex :male}
{:name "Ivanova" :last-name "Ivanov" :sex :female}])]
(t/testing "?p2 introduced only inside of an Or"
(t/is (= #{[(:crux.db/id ivan)]} (api/q (api/db *kv*) '{:find [?p2]
:where [(or (and [?p2 :name "Petr"]
[?p2 :sex :female])
(and [?p2 :last-name "Ivanov"]
[?p2 :sex :male]))]}))))))
;; end::or-and2[]
;; tag::not-join[]
(t/deftest test-not-join
(f/transact-people! *kv* [{:name "Ivan" :last-name "Ivanov"}
{:name "Malcolm" :last-name "Ofsparks"}
{:name "Dominic" :last-name "Monroe"}])
(t/testing "Rudimentary not-join"
(t/is (= #{["Ivan"] ["Malcolm"]}
(api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
(not-join [e]
[e :last-name "Monroe"])]})))))
;; end::not-join[]
)
| 56777 | (ns docs.examples
(:require [clojure.java.io :as io]
[crux.api :as crux]))
;; tag::require-ek[]
(require '[crux.kafka.embedded :as ek])
;; end::require-ek[]
;; tag::ek-example[]
(defn start-embedded-kafka [kafka-port storage-dir]
(ek/start-embedded-kafka {:crux.kafka.embedded/zookeeper-data-dir (io/file storage-dir "zk-data")
:crux.kafka.embedded/kafka-log-dir (io/file storage-dir "kafka-log")
:crux.kafka.embedded/kafka-port kafka-port}))
;; end::ek-example[]
(defn stop-embedded-kafka [^java.io.Closeable embedded-kafka]
;; tag::ek-close[]
(.close embedded-kafka)
;; end::ek-close[]
)
;; tag::start-http-client[]
(defn start-http-client [port]
(crux/new-api-client (str "http://localhost:" port)))
;; end::start-http-client[]
(defn example-query-entity [node]
;; tag::query-entity[]
(crux/entity (crux/db node) :dbpedia.resource/Pablo-Picasso)
;; end::query-entity[]
)
(defn example-query-valid-time [node]
;; tag::query-valid-time[]
(crux/q (crux/db node #inst "2018-05-19T09:20:27.966-00:00")
'{:find [e]
:where [[e :name "<NAME>"]]})
;; end::query-valid-time[]
)
(defn query-example-setup [node]
(let [maps
;; tag::query-input[]
[{:crux.db/id :<NAME>
:name "<NAME>"
:last-name "<NAME>"}
{:crux.db/id :<NAME>
:name "<NAME>"
:last-name "<NAME>"}
{:crux.db/id :smith
:name "<NAME>"
:last-name "<NAME>"}]
;; end::query-input[]
]
(crux/submit-tx node
(vec (for [m maps]
[:crux.tx/put m])))))
(defn query-example-basic-query [node]
(crux/q
(crux/db node)
;; tag::basic-query[]
'{:find [p1]
:where [[p1 :name n]
[p1 :last-name n]
[p1 :name "<NAME>"]]}
;; end::basic-query[]
))
;; tag::basic-query-r[]
#{[:smith]}
;; end::basic-query-r[]
(defn query-example-with-arguments-1 [node]
(crux/q
(crux/db node)
;; tag::query-with-arguments1[]
{:find '[n]
:where '[[e :name n]]
:args [{'e :ivan
'n "<NAME>"}]}
;; end::query-with-arguments1[]
))
;; tag::query-with-arguments1-r[]
#{["<NAME>"]}
;; end::query-with-arguments1-r[]
(defn query-example-with-arguments-2 [node]
(crux/q
(crux/db node)
;; tag::query-with-arguments2[]
{:find '[e]
:where '[[e :name n]]
:args [{'n "<NAME>"}
{'n "<NAME>"}]}
;; end::query-with-arguments2[]
))
;; tag::query-with-arguments2-r[]
#{[:petr] [:ivan]}
;; end::query-with-arguments2-r[]
(defn query-example-with-arguments-3 [node]
(crux/q
(crux/db node)
;; tag::query-with-arguments3[]
{:find '[e]
:where '[[e :name n]
[e :last-name l]]
:args [{'n "<NAME>" 'l "<NAME>"}
{'n "<NAME>" 'l "<NAME>"}]}
;; end::query-with-arguments3[]
))
;; tag::query-with-arguments3-r[]
#{[:petr] [:ivan]}
;; end::query-with-arguments3-r[]
(defn query-example-with-arguments-4 [node]
(crux/q
(crux/db node)
;; tag::query-with-arguments4[]
{:find '[n]
:where '[[(re-find #"I" n)]
[(= l "<NAME>ov")]]
:args [{'n "<NAME>" 'l "<NAME>"}
{'n "<NAME>" 'l "<NAME>"}]}
;; end::query-with-arguments4[]
))
;; tag::query-with-arguments4-r[]
#{["<NAME>"]}
;; end::query-with-arguments4-r[]
(defn query-example-with-arguments-5 [node]
(crux/q
(crux/db node)
;; tag::query-with-arguments5[]
{:find '[age]
:where '[[(>= age 21)]]
:args [{'age 22}]}
;; end::query-with-arguments5[]
))
;; tag::query-with-arguments5-r[]
#{[22]}
;; end::query-with-arguments5-r[]
(defn query-example-with-predicate-1 [node]
(crux/q
(crux/db node)
;; tag::query-with-pred-1[]
{:find '[age]
:where '[[(odd? age)]]
:args [{'age 22} {'age 21}]}
;; end::query-with-pred-1[]
))
;; tag::query-with-pred-1-r[]
#{[21]}
;; end::query-with-pred-1-r[]
(defn query-example-streaming [node prn]
;; tag::streaming-query[]
(with-open [res (crux/open-q (crux/db node)
'{:find [p1]
:where [[p1 :name n]
[p1 :last-name n]
[p1 :name "<NAME>"]]})]
(doseq [tuple (iterator-seq res)]
(prn tuple)))
;; end::streaming-query[]
)
(defn query-example-at-time-setup [node]
(crux/submit-tx
node
[[:crux.tx/put
;; tag::query-at-t-d1[]
{:crux.db/id :malcolm :name "<NAME>" :last-name "<NAME>"}
#inst "1986-10-22"
;; end::query-at-t-d1[]
]])
(crux/submit-tx
node
[[:crux.tx/put
;; tag::query-at-t-d2[]
{:crux.db/id :malcolm :name "<NAME>" :last-name "<NAME>"}
#inst "1986-10-24"
;; end::query-at-t-d2[]
]]))
(defn query-example-at-time-q1 [node]
(crux/q
(crux/db
node #inst "1986-10-23")
;; tag::query-at-t-q1[]
'{:find [e]
:where [[e :name "<NAME>"]
[e :last-name "<NAME>"]]}
;; end::query-at-t-q1[]
))
;; tag::query-at-t-q1-q[]
; Using Clojure: `(api/q (api/db my-crux-node #inst "1986-10-23") q)`
;; end::query-at-t-q1-q[]
;; tag::query-at-t-q1-r[]
#{}
;; end::query-at-t-q1-r[]
(defn query-example-at-time-q2 [node]
(crux/q
(crux/db node)
'{:find [e]
:where [[e :name "<NAME>"]
[e :last-name "<NAME>"]]}))
;; tag::query-at-t-q2-q[]
; Using Clojure: `(api/q (api/db my-crux-node) q)`
;; end::query-at-t-q2-q[]
;; tag::query-at-t-q2-r[]
#{[:malcolm]}
;; end::query-at-t-q2-r[]
#_(comment
;; tag::history-full[]
(api/submit-tx
node
[[:crux.tx/put
{:crux.db/id :ids.persons/Jeff
:person/name "<NAME>"
:person/wealth 100}
#inst "2018-05-18T09:20:27.966"]
[:crux.tx/put
{:crux.db/id :ids.persons/Jeff
:person/name "<NAME>"
:person/wealth 1000}
#inst "2015-05-18T09:20:27.966"]])
; yields
{:crux.tx/tx-id 1555314836178,
:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00"}
; Returning the history in descending order
; To return in ascending order, use :asc in place of :desc
(api/entity-history (api/db node) :ids.persons/Jeff :desc)
; yields
[{:crux.tx/tx-time #inst "2019-04-15T07:53:55.817-00:00",
:crux.tx/tx-id 1555314835817,
:crux.db/valid-time #inst "2018-05-18T09:20:27.966-00:00",
:crux.db/content-hash ; sha1 hash of document contents
"6ca48d3bf05a16cd8d30e6b466f76d5cc281b561"}
{:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00",
:crux.tx/tx-id 1555314836178,
:crux.db/valid-time #inst "2015-05-18T09:20:27.966-00:00",
:crux.db/content-hash "a95f149636e0a10a78452298e2135791c0203529"}]
;; end::history-full[]
;; tag::history-with-docs[]
(api/entity-history (api/db node) :ids.persons/Jeff :desc {:with-docs? true})
; yields
[{:crux.tx/tx-time #inst "2019-04-15T07:53:55.817-00:00",
:crux.tx/tx-id 1555314835817,
:crux.db/valid-time #inst "2018-05-18T09:20:27.966-00:00",
:crux.db/content-hash
"6ca48d3bf05a16cd8d30e6b466f76d5cc281b561"
:crux.db/doc
{:crux.db/id :ids.persons/Jeff
:person/name "<NAME>"
:person/wealth 100}}
{:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00",
:crux.tx/tx-id 1555314836178,
:crux.db/valid-time #inst "2015-05-18T09:20:27.966-00:00",
:crux.db/content-hash "a95f149636e0a10a78452298e2135791c0203529"
:crux.db/doc
{:crux.db/id :ids.persons/Jeff
:person/name "<NAME>"
:person/wealth 1000}}]
;; end::history-with-docs[]
;; tag::history-range[]
; Passing the aditional 'opts' map with the start/end bounds.
; As we are returning results in :asc order, the :start map contains the earlier co-ordinates -
; If returning history range in descending order, we pass the later co-ordinates to the :start map
(api/entity-history
(api/db node)
:ids.persons/Jeff
:asc
{:start {:crux.db/valid-time #inst "2015-05-18T09:20:27.966" ; valid-time-start
:crux.tx/tx-time #inst "2015-05-18T09:20:27.966"} ; tx-time-start
:end {:crux.db/valid-time #inst "2020-05-18T09:20:27.966" ; valid-time-end
:crux.tx/tx-time #inst "2020-05-18T09:20:27.966"} ; tx-time-end
})
; yields
[{:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00",
:crux.tx/tx-id 1555314836178,
:crux.db/valid-time #inst "2015-05-18T09:20:27.966-00:00",
:crux.db/content-hash
"a95f149636e0a10a78452298e2135791c0203529"}
{:crux.tx/tx-time #inst "2019-04-15T07:53:55.817-00:00",
:crux.tx/tx-id 1555314835817
:crux.db/valid-time #inst "2018-05-18T09:20:27.966-00:00",
:crux.db/content-hash "6ca48d3bf05a16cd8d30e6b466f76d5cc281b561"}]
;; end::history-range[]
)
(defn query-example-join-q1-setup [node]
;; Five people, two of which share the same name:
(let [maps
;; tag::join-d[]
[{:crux.db/id :ivan :name "<NAME>"}
{:crux.db/id :petr :name "<NAME>"}
{:crux.db/id :sergei :name "<NAME>"}
{:crux.db/id :denis-a :name "<NAME>"}
{:crux.db/id :denis-b :name "<NAME>"}]
;; end::join-d[]
]
(crux/submit-tx node
(vec (for [m maps]
[:crux.tx/put m])))))
(defn query-example-join-q1 [node]
(crux/q
(crux/db node)
;; tag::join-q[]
'{:find [p1 p2]
:where [[p1 :name n]
[p2 :name n]]}
;; end::join-q[]
))
;; tag::join-r[]
#{[:ivan :ivan]
[:petr :<NAME>tr]
[:sergei :sergei]
[:denis-a :denis-a]
[:denis-b :denis-b]
[:denis-a :denis-b]
[:denis-b :denis-a]}
;; end::join-r[]
(defn query-example-join-q2-setup [node]
(let [maps
;; tag::join2-d[]
[{:crux.db/id :ivan :name "<NAME>" :last-name "<NAME>"}
{:crux.db/id :petr :name "<NAME>" :follows #{"I<NAME>"}}]
;; end::join2-d[]
]
(crux/submit-tx node
(vec (for [m maps]
[:crux.tx/put m])))))
(defn query-example-join-q2 [node]
(crux/q
(crux/db node)
;; tag::join2-q[]
'{:find [e2]
:where [[e :last-name l]
[e2 :follows l]
[e :name "<NAME>"]]}
;; end::join2-q[]
))
;; tag::join2-r[]
#{[:petr]}
;; end::join2-r[]
(comment
;; tag::bitemp0[]
{:crux.db/id :p2
:entry-pt :SFO
:arrival-time #inst "2018-12-31"
:departure-time :na}
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2018-12-31"
;; end::bitemp0[]
;; tag::bitemp2[]
{:crux.db/id :p4
:entry-pt :NY
:arrival-time #inst "2019-01-02"
:departure-time :na}
#inst "2019-01-02"
;; end::bitemp2[]
;; tag::bitemp3[]
{:crux.db/id :p4
:entry-pt :NY
:arrival-time #inst "2019-01-02"
:departure-time #inst "2019-01-03"}
#inst "2019-01-03"
;; end::bitemp3[]
;; tag::bitemp4[]
{:crux.db/id :p1
:entry-pt :NY
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2018-12-31"
;; end::bitemp4[]
;; tag::bitemp4b[]
{:crux.db/id :p1
:entry-pt :NY
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-03"}
#inst "2019-01-03"
;; end::bitemp4b[]
;; tag::bitemp4c[]
{:crux.db/id :p1
:entry-pt :LA
:arrival-time #inst "2019-01-04"
:departure-time :na}
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-04"}
#inst "2019-01-04"
;; end::bitemp4c[]
;; tag::bitemp5[]
{:crux.db/id :p2
:entry-pt :SFO
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-05"}
#inst "2019-01-05"
;; end::bitemp5[]
;; tag::bitemp7[]
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2019-01-04"
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-07"}
#inst "2019-01-07"
;; end::bitemp7[]
;; tag::bitemp8[]
{:crux.db/id :p3
:entry-pt :SFO
:arrival-time #inst "2019-01-08"
:departure-time :na}
#inst "2019-01-08"
{:crux.db/id :p4
:entry-pt :LA
:arrival-time #inst "2019-01-08"
:departure-time :na}
#inst "2019-01-08"
;; end::bitemp8[]
;; tag::bitemp9[]
{:crux.db/id :p3
:entry-pt :SFO
:arrival-time #inst "2019-01-08"
:departure-time #inst "2019-01-08"}
#inst "2019-01-09"
;; end::bitemp9[]
;; tag::bitemp10[]
{:crux.db/id :p5
:entry-pt :LA
:arrival-time #inst "2019-01-10"
:departure-time :na}
#inst "2019-01-10"
;; end::bitemp10[]
;; tag::bitemp11[]
{:crux.db/id :p7
:entry-pt :NY
:arrival-time #inst "2019-01-11"
:departure-time :na}
#inst "2019-01-11"
;; end::bitemp11[]
;; tag::bitemp12[]
{:crux.db/id :p6
:entry-pt :NY
:arrival-time #inst "2019-01-12"
:departure-time :na}
#inst "2019-01-12"
;; end::bitemp12[]
;; tag::bitempq[]
{:find [p entry-pt arrival-time departure-time]
:where [[p :entry-pt entry-pt]
[p :arrival-time arrival-time]
[p :departure-time departure-time]]}
#inst "2019-01-03" ; `as of` transaction time
#inst "2019-01-02" ; `as at` valid time
;; end::bitempq[]
;; tag::bitempr[]
#{[:p2 :SFO #inst "2018-12-31" :na]
[:p3 :LA #inst "2018-12-31" :na]
[:p4 :NY #inst "2019-01-02" :na]}
;; end::bitempr[]
)
(comment ;; Not currently used, but could be useful after some reworking.
;; tag::blanks[]
(t/deftest test-blanks
(f/transact-people! *kv* [{:name "<NAME>"} {:name "<NAME>"} {:name "<NAME>"}])
(t/is (= #{["<NAME>"] ["<NAME>"] ["<NAME>"]}
(api/q (api/db *kv*) '{:find [name]
:where [[_ :name name]]}))))
;; end::blanks[]
;; tag::not[]
(t/deftest test-not-query
(f/transact-people! *kv* [{:crux.db/id :ivan-ivanov-1 :name "<NAME>" :last-name "<NAME>"}
{:crux.db/id :ivan-ivanov-2 :name "<NAME>" :last-name "<NAME>"}
{:crux.db/id :ivan-ivanovtov-1 :name "<NAME>" :last-name "<NAME>"}])
(t/testing "literal v"
(t/is (= 2 (count (api/q (api/db *kv*) '{:find [e]
:where [[e :name name]
[e :name "<NAME>"]
(not [e :last-name "<NAME>"])]}))))
(t/testing "multiple clauses in not"
(t/is (= 2 (count (api/q (api/db *kv*) '{:find [e]
:where [[e :name name]
[e :name "<NAME>"]
(not [e :last-name "<NAME>"]
[(string? name)])]}))))))
(t/testing "variable v"
(t/is (= 2 (count (api/q (api/db *kv*) '{:find [e]
:where [[e :name name]
[:ivan-ivanovtov-1 :last-name i-name]
(not [e :last-name i-name])]}))))))
;; end::not[]
;; tag::or[]
(t/deftest test-or-query
(f/transact-people! *kv* [{:name "<NAME>" :last-name "<NAME>"}
{:name "<NAME>" :last-name "<NAME>"}
{:name "<NAME>" :last-name "<NAME>"}
{:name "<NAME>" :last-name "<NAME>"}])
(t/testing "Or works as expected"
(t/is (= 3 (count (api/q (api/db *kv*) '{:find [e]
:where [[e :name name]
[e :name "<NAME>"]
(or [e :last-name "<NAME>"]
[e :last-name "<NAME>"])]}))))))
;; end::or[]
;; tag::or-and[]
(t/deftest test-or-query-can-use-and
(let [[ivan] (f/transact-people! *kv* [{:name "<NAME>" :sex :male}
{:name "<NAME>" :sex :male}
{:name "<NAME>" :sex :female}])]
(t/is (= #{["<NAME>"]
["<NAME>"]}
(api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
(or [e :sex :female]
(and [e :sex :male]
[e :name "<NAME>"]))]})))))
;; end::or-and[]
;; tag::or-and2[]
(t/deftest test-ors-can-introduce-new-bindings
(let [[petr ivan ivanova] (f/transact-people! *kv* [{:name "<NAME>" :last-name "<NAME>" :sex :male}
{:name "<NAME>" :last-name "<NAME>" :sex :male}
{:name "<NAME>" :last-name "<NAME>" :sex :female}])]
(t/testing "?p2 introduced only inside of an Or"
(t/is (= #{[(:crux.db/id ivan)]} (api/q (api/db *kv*) '{:find [?p2]
:where [(or (and [?p2 :name "<NAME>"]
[?p2 :sex :female])
(and [?p2 :last-name "<NAME>"]
[?p2 :sex :male]))]}))))))
;; end::or-and2[]
;; tag::not-join[]
(t/deftest test-not-join
(f/transact-people! *kv* [{:name "<NAME>" :last-name "<NAME>"}
{:name "<NAME>" :last-name "<NAME>"}
{:name "<NAME>" :last-name "<NAME>"}])
(t/testing "Rudimentary not-join"
(t/is (= #{["<NAME>"] ["<NAME>"]}
(api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
(not-join [e]
[e :last-name "<NAME>"])]})))))
;; end::not-join[]
)
| true | (ns docs.examples
(:require [clojure.java.io :as io]
[crux.api :as crux]))
;; tag::require-ek[]
(require '[crux.kafka.embedded :as ek])
;; end::require-ek[]
;; tag::ek-example[]
(defn start-embedded-kafka [kafka-port storage-dir]
(ek/start-embedded-kafka {:crux.kafka.embedded/zookeeper-data-dir (io/file storage-dir "zk-data")
:crux.kafka.embedded/kafka-log-dir (io/file storage-dir "kafka-log")
:crux.kafka.embedded/kafka-port kafka-port}))
;; end::ek-example[]
(defn stop-embedded-kafka [^java.io.Closeable embedded-kafka]
;; tag::ek-close[]
(.close embedded-kafka)
;; end::ek-close[]
)
;; tag::start-http-client[]
(defn start-http-client [port]
(crux/new-api-client (str "http://localhost:" port)))
;; end::start-http-client[]
(defn example-query-entity [node]
;; tag::query-entity[]
(crux/entity (crux/db node) :dbpedia.resource/Pablo-Picasso)
;; end::query-entity[]
)
(defn example-query-valid-time [node]
;; tag::query-valid-time[]
(crux/q (crux/db node #inst "2018-05-19T09:20:27.966-00:00")
'{:find [e]
:where [[e :name "PI:NAME:<NAME>END_PI"]]})
;; end::query-valid-time[]
)
(defn query-example-setup [node]
(let [maps
;; tag::query-input[]
[{:crux.db/id :PI:NAME:<NAME>END_PI
:name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"}
{:crux.db/id :PI:NAME:<NAME>END_PI
:name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"}
{:crux.db/id :smith
:name "PI:NAME:<NAME>END_PI"
:last-name "PI:NAME:<NAME>END_PI"}]
;; end::query-input[]
]
(crux/submit-tx node
(vec (for [m maps]
[:crux.tx/put m])))))
(defn query-example-basic-query [node]
(crux/q
(crux/db node)
;; tag::basic-query[]
'{:find [p1]
:where [[p1 :name n]
[p1 :last-name n]
[p1 :name "PI:NAME:<NAME>END_PI"]]}
;; end::basic-query[]
))
;; tag::basic-query-r[]
#{[:smith]}
;; end::basic-query-r[]
(defn query-example-with-arguments-1 [node]
(crux/q
(crux/db node)
;; tag::query-with-arguments1[]
{:find '[n]
:where '[[e :name n]]
:args [{'e :ivan
'n "PI:NAME:<NAME>END_PI"}]}
;; end::query-with-arguments1[]
))
;; tag::query-with-arguments1-r[]
#{["PI:NAME:<NAME>END_PI"]}
;; end::query-with-arguments1-r[]
(defn query-example-with-arguments-2 [node]
(crux/q
(crux/db node)
;; tag::query-with-arguments2[]
{:find '[e]
:where '[[e :name n]]
:args [{'n "PI:NAME:<NAME>END_PI"}
{'n "PI:NAME:<NAME>END_PI"}]}
;; end::query-with-arguments2[]
))
;; tag::query-with-arguments2-r[]
#{[:petr] [:ivan]}
;; end::query-with-arguments2-r[]
(defn query-example-with-arguments-3 [node]
(crux/q
(crux/db node)
;; tag::query-with-arguments3[]
{:find '[e]
:where '[[e :name n]
[e :last-name l]]
:args [{'n "PI:NAME:<NAME>END_PI" 'l "PI:NAME:<NAME>END_PI"}
{'n "PI:NAME:<NAME>END_PI" 'l "PI:NAME:<NAME>END_PI"}]}
;; end::query-with-arguments3[]
))
;; tag::query-with-arguments3-r[]
#{[:petr] [:ivan]}
;; end::query-with-arguments3-r[]
(defn query-example-with-arguments-4 [node]
(crux/q
(crux/db node)
;; tag::query-with-arguments4[]
{:find '[n]
:where '[[(re-find #"I" n)]
[(= l "PI:NAME:<NAME>END_PIov")]]
:args [{'n "PI:NAME:<NAME>END_PI" 'l "PI:NAME:<NAME>END_PI"}
{'n "PI:NAME:<NAME>END_PI" 'l "PI:NAME:<NAME>END_PI"}]}
;; end::query-with-arguments4[]
))
;; tag::query-with-arguments4-r[]
#{["PI:NAME:<NAME>END_PI"]}
;; end::query-with-arguments4-r[]
(defn query-example-with-arguments-5 [node]
(crux/q
(crux/db node)
;; tag::query-with-arguments5[]
{:find '[age]
:where '[[(>= age 21)]]
:args [{'age 22}]}
;; end::query-with-arguments5[]
))
;; tag::query-with-arguments5-r[]
#{[22]}
;; end::query-with-arguments5-r[]
(defn query-example-with-predicate-1 [node]
(crux/q
(crux/db node)
;; tag::query-with-pred-1[]
{:find '[age]
:where '[[(odd? age)]]
:args [{'age 22} {'age 21}]}
;; end::query-with-pred-1[]
))
;; tag::query-with-pred-1-r[]
#{[21]}
;; end::query-with-pred-1-r[]
(defn query-example-streaming [node prn]
;; tag::streaming-query[]
(with-open [res (crux/open-q (crux/db node)
'{:find [p1]
:where [[p1 :name n]
[p1 :last-name n]
[p1 :name "PI:NAME:<NAME>END_PI"]]})]
(doseq [tuple (iterator-seq res)]
(prn tuple)))
;; end::streaming-query[]
)
(defn query-example-at-time-setup [node]
(crux/submit-tx
node
[[:crux.tx/put
;; tag::query-at-t-d1[]
{:crux.db/id :malcolm :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
#inst "1986-10-22"
;; end::query-at-t-d1[]
]])
(crux/submit-tx
node
[[:crux.tx/put
;; tag::query-at-t-d2[]
{:crux.db/id :malcolm :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
#inst "1986-10-24"
;; end::query-at-t-d2[]
]]))
(defn query-example-at-time-q1 [node]
(crux/q
(crux/db
node #inst "1986-10-23")
;; tag::query-at-t-q1[]
'{:find [e]
:where [[e :name "PI:NAME:<NAME>END_PI"]
[e :last-name "PI:NAME:<NAME>END_PI"]]}
;; end::query-at-t-q1[]
))
;; tag::query-at-t-q1-q[]
; Using Clojure: `(api/q (api/db my-crux-node #inst "1986-10-23") q)`
;; end::query-at-t-q1-q[]
;; tag::query-at-t-q1-r[]
#{}
;; end::query-at-t-q1-r[]
(defn query-example-at-time-q2 [node]
(crux/q
(crux/db node)
'{:find [e]
:where [[e :name "PI:NAME:<NAME>END_PI"]
[e :last-name "PI:NAME:<NAME>END_PI"]]}))
;; tag::query-at-t-q2-q[]
; Using Clojure: `(api/q (api/db my-crux-node) q)`
;; end::query-at-t-q2-q[]
;; tag::query-at-t-q2-r[]
#{[:malcolm]}
;; end::query-at-t-q2-r[]
#_(comment
;; tag::history-full[]
(api/submit-tx
node
[[:crux.tx/put
{:crux.db/id :ids.persons/Jeff
:person/name "PI:NAME:<NAME>END_PI"
:person/wealth 100}
#inst "2018-05-18T09:20:27.966"]
[:crux.tx/put
{:crux.db/id :ids.persons/Jeff
:person/name "PI:NAME:<NAME>END_PI"
:person/wealth 1000}
#inst "2015-05-18T09:20:27.966"]])
; yields
{:crux.tx/tx-id 1555314836178,
:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00"}
; Returning the history in descending order
; To return in ascending order, use :asc in place of :desc
(api/entity-history (api/db node) :ids.persons/Jeff :desc)
; yields
[{:crux.tx/tx-time #inst "2019-04-15T07:53:55.817-00:00",
:crux.tx/tx-id 1555314835817,
:crux.db/valid-time #inst "2018-05-18T09:20:27.966-00:00",
:crux.db/content-hash ; sha1 hash of document contents
"6ca48d3bf05a16cd8d30e6b466f76d5cc281b561"}
{:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00",
:crux.tx/tx-id 1555314836178,
:crux.db/valid-time #inst "2015-05-18T09:20:27.966-00:00",
:crux.db/content-hash "a95f149636e0a10a78452298e2135791c0203529"}]
;; end::history-full[]
;; tag::history-with-docs[]
(api/entity-history (api/db node) :ids.persons/Jeff :desc {:with-docs? true})
; yields
[{:crux.tx/tx-time #inst "2019-04-15T07:53:55.817-00:00",
:crux.tx/tx-id 1555314835817,
:crux.db/valid-time #inst "2018-05-18T09:20:27.966-00:00",
:crux.db/content-hash
"6ca48d3bf05a16cd8d30e6b466f76d5cc281b561"
:crux.db/doc
{:crux.db/id :ids.persons/Jeff
:person/name "PI:NAME:<NAME>END_PI"
:person/wealth 100}}
{:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00",
:crux.tx/tx-id 1555314836178,
:crux.db/valid-time #inst "2015-05-18T09:20:27.966-00:00",
:crux.db/content-hash "a95f149636e0a10a78452298e2135791c0203529"
:crux.db/doc
{:crux.db/id :ids.persons/Jeff
:person/name "PI:NAME:<NAME>END_PI"
:person/wealth 1000}}]
;; end::history-with-docs[]
;; tag::history-range[]
; Passing the aditional 'opts' map with the start/end bounds.
; As we are returning results in :asc order, the :start map contains the earlier co-ordinates -
; If returning history range in descending order, we pass the later co-ordinates to the :start map
(api/entity-history
(api/db node)
:ids.persons/Jeff
:asc
{:start {:crux.db/valid-time #inst "2015-05-18T09:20:27.966" ; valid-time-start
:crux.tx/tx-time #inst "2015-05-18T09:20:27.966"} ; tx-time-start
:end {:crux.db/valid-time #inst "2020-05-18T09:20:27.966" ; valid-time-end
:crux.tx/tx-time #inst "2020-05-18T09:20:27.966"} ; tx-time-end
})
; yields
[{:crux.tx/tx-time #inst "2019-04-15T07:53:56.178-00:00",
:crux.tx/tx-id 1555314836178,
:crux.db/valid-time #inst "2015-05-18T09:20:27.966-00:00",
:crux.db/content-hash
"a95f149636e0a10a78452298e2135791c0203529"}
{:crux.tx/tx-time #inst "2019-04-15T07:53:55.817-00:00",
:crux.tx/tx-id 1555314835817
:crux.db/valid-time #inst "2018-05-18T09:20:27.966-00:00",
:crux.db/content-hash "6ca48d3bf05a16cd8d30e6b466f76d5cc281b561"}]
;; end::history-range[]
)
(defn query-example-join-q1-setup [node]
;; Five people, two of which share the same name:
(let [maps
;; tag::join-d[]
[{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI"}
{:crux.db/id :petr :name "PI:NAME:<NAME>END_PI"}
{:crux.db/id :sergei :name "PI:NAME:<NAME>END_PI"}
{:crux.db/id :denis-a :name "PI:NAME:<NAME>END_PI"}
{:crux.db/id :denis-b :name "PI:NAME:<NAME>END_PI"}]
;; end::join-d[]
]
(crux/submit-tx node
(vec (for [m maps]
[:crux.tx/put m])))))
(defn query-example-join-q1 [node]
(crux/q
(crux/db node)
;; tag::join-q[]
'{:find [p1 p2]
:where [[p1 :name n]
[p2 :name n]]}
;; end::join-q[]
))
;; tag::join-r[]
#{[:ivan :ivan]
[:petr :PI:NAME:<NAME>END_PItr]
[:sergei :sergei]
[:denis-a :denis-a]
[:denis-b :denis-b]
[:denis-a :denis-b]
[:denis-b :denis-a]}
;; end::join-r[]
(defn query-example-join-q2-setup [node]
(let [maps
;; tag::join2-d[]
[{:crux.db/id :ivan :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
{:crux.db/id :petr :name "PI:NAME:<NAME>END_PI" :follows #{"IPI:NAME:<NAME>END_PI"}}]
;; end::join2-d[]
]
(crux/submit-tx node
(vec (for [m maps]
[:crux.tx/put m])))))
(defn query-example-join-q2 [node]
(crux/q
(crux/db node)
;; tag::join2-q[]
'{:find [e2]
:where [[e :last-name l]
[e2 :follows l]
[e :name "PI:NAME:<NAME>END_PI"]]}
;; end::join2-q[]
))
;; tag::join2-r[]
#{[:petr]}
;; end::join2-r[]
(comment
;; tag::bitemp0[]
{:crux.db/id :p2
:entry-pt :SFO
:arrival-time #inst "2018-12-31"
:departure-time :na}
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2018-12-31"
;; end::bitemp0[]
;; tag::bitemp2[]
{:crux.db/id :p4
:entry-pt :NY
:arrival-time #inst "2019-01-02"
:departure-time :na}
#inst "2019-01-02"
;; end::bitemp2[]
;; tag::bitemp3[]
{:crux.db/id :p4
:entry-pt :NY
:arrival-time #inst "2019-01-02"
:departure-time #inst "2019-01-03"}
#inst "2019-01-03"
;; end::bitemp3[]
;; tag::bitemp4[]
{:crux.db/id :p1
:entry-pt :NY
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2018-12-31"
;; end::bitemp4[]
;; tag::bitemp4b[]
{:crux.db/id :p1
:entry-pt :NY
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-03"}
#inst "2019-01-03"
;; end::bitemp4b[]
;; tag::bitemp4c[]
{:crux.db/id :p1
:entry-pt :LA
:arrival-time #inst "2019-01-04"
:departure-time :na}
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-04"}
#inst "2019-01-04"
;; end::bitemp4c[]
;; tag::bitemp5[]
{:crux.db/id :p2
:entry-pt :SFO
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-05"}
#inst "2019-01-05"
;; end::bitemp5[]
;; tag::bitemp7[]
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time :na}
#inst "2019-01-04"
{:crux.db/id :p3
:entry-pt :LA
:arrival-time #inst "2018-12-31"
:departure-time #inst "2019-01-07"}
#inst "2019-01-07"
;; end::bitemp7[]
;; tag::bitemp8[]
{:crux.db/id :p3
:entry-pt :SFO
:arrival-time #inst "2019-01-08"
:departure-time :na}
#inst "2019-01-08"
{:crux.db/id :p4
:entry-pt :LA
:arrival-time #inst "2019-01-08"
:departure-time :na}
#inst "2019-01-08"
;; end::bitemp8[]
;; tag::bitemp9[]
{:crux.db/id :p3
:entry-pt :SFO
:arrival-time #inst "2019-01-08"
:departure-time #inst "2019-01-08"}
#inst "2019-01-09"
;; end::bitemp9[]
;; tag::bitemp10[]
{:crux.db/id :p5
:entry-pt :LA
:arrival-time #inst "2019-01-10"
:departure-time :na}
#inst "2019-01-10"
;; end::bitemp10[]
;; tag::bitemp11[]
{:crux.db/id :p7
:entry-pt :NY
:arrival-time #inst "2019-01-11"
:departure-time :na}
#inst "2019-01-11"
;; end::bitemp11[]
;; tag::bitemp12[]
{:crux.db/id :p6
:entry-pt :NY
:arrival-time #inst "2019-01-12"
:departure-time :na}
#inst "2019-01-12"
;; end::bitemp12[]
;; tag::bitempq[]
{:find [p entry-pt arrival-time departure-time]
:where [[p :entry-pt entry-pt]
[p :arrival-time arrival-time]
[p :departure-time departure-time]]}
#inst "2019-01-03" ; `as of` transaction time
#inst "2019-01-02" ; `as at` valid time
;; end::bitempq[]
;; tag::bitempr[]
#{[:p2 :SFO #inst "2018-12-31" :na]
[:p3 :LA #inst "2018-12-31" :na]
[:p4 :NY #inst "2019-01-02" :na]}
;; end::bitempr[]
)
(comment ;; Not currently used, but could be useful after some reworking.
;; tag::blanks[]
(t/deftest test-blanks
(f/transact-people! *kv* [{:name "PI:NAME:<NAME>END_PI"} {:name "PI:NAME:<NAME>END_PI"} {:name "PI:NAME:<NAME>END_PI"}])
(t/is (= #{["PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI"]}
(api/q (api/db *kv*) '{:find [name]
:where [[_ :name name]]}))))
;; end::blanks[]
;; tag::not[]
(t/deftest test-not-query
(f/transact-people! *kv* [{:crux.db/id :ivan-ivanov-1 :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
{:crux.db/id :ivan-ivanov-2 :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
{:crux.db/id :ivan-ivanovtov-1 :name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}])
(t/testing "literal v"
(t/is (= 2 (count (api/q (api/db *kv*) '{:find [e]
:where [[e :name name]
[e :name "PI:NAME:<NAME>END_PI"]
(not [e :last-name "PI:NAME:<NAME>END_PI"])]}))))
(t/testing "multiple clauses in not"
(t/is (= 2 (count (api/q (api/db *kv*) '{:find [e]
:where [[e :name name]
[e :name "PI:NAME:<NAME>END_PI"]
(not [e :last-name "PI:NAME:<NAME>END_PI"]
[(string? name)])]}))))))
(t/testing "variable v"
(t/is (= 2 (count (api/q (api/db *kv*) '{:find [e]
:where [[e :name name]
[:ivan-ivanovtov-1 :last-name i-name]
(not [e :last-name i-name])]}))))))
;; end::not[]
;; tag::or[]
(t/deftest test-or-query
(f/transact-people! *kv* [{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}])
(t/testing "Or works as expected"
(t/is (= 3 (count (api/q (api/db *kv*) '{:find [e]
:where [[e :name name]
[e :name "PI:NAME:<NAME>END_PI"]
(or [e :last-name "PI:NAME:<NAME>END_PI"]
[e :last-name "PI:NAME:<NAME>END_PI"])]}))))))
;; end::or[]
;; tag::or-and[]
(t/deftest test-or-query-can-use-and
(let [[ivan] (f/transact-people! *kv* [{:name "PI:NAME:<NAME>END_PI" :sex :male}
{:name "PI:NAME:<NAME>END_PI" :sex :male}
{:name "PI:NAME:<NAME>END_PI" :sex :female}])]
(t/is (= #{["PI:NAME:<NAME>END_PI"]
["PI:NAME:<NAME>END_PI"]}
(api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
(or [e :sex :female]
(and [e :sex :male]
[e :name "PI:NAME:<NAME>END_PI"]))]})))))
;; end::or-and[]
;; tag::or-and2[]
(t/deftest test-ors-can-introduce-new-bindings
(let [[petr ivan ivanova] (f/transact-people! *kv* [{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :sex :male}
{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :sex :male}
{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :sex :female}])]
(t/testing "?p2 introduced only inside of an Or"
(t/is (= #{[(:crux.db/id ivan)]} (api/q (api/db *kv*) '{:find [?p2]
:where [(or (and [?p2 :name "PI:NAME:<NAME>END_PI"]
[?p2 :sex :female])
(and [?p2 :last-name "PI:NAME:<NAME>END_PI"]
[?p2 :sex :male]))]}))))))
;; end::or-and2[]
;; tag::not-join[]
(t/deftest test-not-join
(f/transact-people! *kv* [{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
{:name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}])
(t/testing "Rudimentary not-join"
(t/is (= #{["PI:NAME:<NAME>END_PI"] ["PI:NAME:<NAME>END_PI"]}
(api/q (api/db *kv*) '{:find [name]
:where [[e :name name]
(not-join [e]
[e :last-name "PI:NAME:<NAME>END_PI"])]})))))
;; end::not-join[]
)
|
[
{
"context": "}\n :author \"someone\"\n :commit ",
"end": 2265,
"score": 0.8839691281318665,
"start": 2261,
"tag": "USERNAME",
"value": "some"
},
{
"context": " :author \"someone\"\n :commit \"",
"end": 2268,
"score": 0.6687425971031189,
"start": 2265,
"tag": "NAME",
"value": "one"
}
] | cimi-resources/test/com/sixsq/slipstream/ssclj/resources/deployment_template_lifecycle_test.clj | slipstream/SlipStreamServer | 6 | (ns com.sixsq.slipstream.ssclj.resources.deployment-template-lifecycle-test
(:require
[clojure.data.json :as json]
[clojure.test :refer [deftest is use-fixtures]]
[com.sixsq.slipstream.ssclj.app.params :as p]
[com.sixsq.slipstream.ssclj.middleware.authn-info-header :refer [authn-info-header]]
[com.sixsq.slipstream.ssclj.resources.common.utils :as u]
[com.sixsq.slipstream.ssclj.resources.deployment-template :as dt]
[com.sixsq.slipstream.ssclj.resources.lifecycle-test-utils :as ltu]
[com.sixsq.slipstream.ssclj.resources.module :as module]
[com.sixsq.slipstream.ssclj.resources.module-lifecycle-test :as module-test]
[peridot.core :refer :all]))
(use-fixtures :each ltu/with-test-server-fixture)
(def collection-uri (str p/service-context (u/de-camelcase dt/resource-name)))
(defn valid-comp [image-id] {:parentModule {:href image-id}
:networkType "public"
:disk 200
:inputParameters [{:parameter "iparam-1" :description "desc2" :value "100"}
{:parameter "iparam-2" :description "desc2"}
{:parameter "iparam-3"}]
:outputParameters [{:parameter "oparam-1" :description "desc2" :value "100"}
{:parameter "oparam-2" :description "desc2"}
{:parameter "oparam-3"}]
:targets {:preinstall "preinstall"
:packages ["emacs-nox" "vim"]
:postinstall "postinstall"
:deployment "deployment"
:reporting "reporting"
:onVmAdd "onVmAdd"
:onVmRemove "onVmRemove"
:prescale "prescale"
:postscale "postscale"}
:author "someone"
:commit "wip"})
(deftest lifecycle
(let [session-anon (-> (ltu/ring-app)
session
(content-type "application/json"))
session-user (header session-anon authn-info-header "jane USER")
session-tarzan (header session-anon authn-info-header "tarzan USER")
session-admin (header session-anon authn-info-header "root ADMIN")
module-img-uri (-> session-user
(request module-test/base-uri
:request-method :post
:body (json/write-str (assoc module-test/valid-entry
:content module-test/valid-image)))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location))
module-uri (-> session-user
(request module-test/base-uri
:request-method :post
:body (json/write-str (assoc {:resourceURI module/resource-uri
:parentPath "a/b"
:path "a/b/c"
:type "COMPONENT"}
:content (valid-comp module-img-uri))))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location))
valid-create {:module {:href module-uri}}]
(-> session-user
(request (str p/service-context module-uri))
(ltu/body->edn)
(ltu/is-status 200))
;; anonymous create should fail
(-> session-anon
(request collection-uri
:request-method :post
:body (json/write-str valid-create))
(ltu/body->edn)
(ltu/is-status 403))
;; full deployment template lifecycle as user should work
(let [deployment-template-uri (-> session-user
(request collection-uri
:request-method :post
:body (json/write-str valid-create))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location))
resource-uri (str p/service-context (u/de-camelcase deployment-template-uri))]
;; admin get succeeds
(-> session-admin
(request resource-uri)
(ltu/body->edn)
(ltu/is-status 200))
;; user get succeeds
(-> session-user
(request resource-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-key-value #(-> % :module :path) (:path module-test/valid-entry)))
;; user tarzan get fails
(-> session-tarzan
(request resource-uri)
(ltu/body->edn)
(ltu/is-status 403))
;; user update works
(-> session-user
(request resource-uri
:request-method :put
:body (json/write-str {}))
(ltu/body->edn)
(ltu/is-status 200))
;; user query succeeds
(-> session-user
(request collection-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count 1))
;; anonymous query fails
(-> session-anon
(request collection-uri)
(ltu/body->edn)
(ltu/is-status 403))
;; user delete succeeds
(-> session-user
(request resource-uri
:request-method :delete)
(ltu/body->edn)
(ltu/is-status 200))
;; ensure entry is really gone
(-> session-admin
(request resource-uri)
(ltu/body->edn)
(ltu/is-status 404)))))
(deftest bad-methods
(let [resource-uri (str p/service-context (u/new-resource-id dt/resource-name))]
(ltu/verify-405-status [[collection-uri :options]
[collection-uri :delete]
[resource-uri :options]
[resource-uri :post]])))
| 70106 | (ns com.sixsq.slipstream.ssclj.resources.deployment-template-lifecycle-test
(:require
[clojure.data.json :as json]
[clojure.test :refer [deftest is use-fixtures]]
[com.sixsq.slipstream.ssclj.app.params :as p]
[com.sixsq.slipstream.ssclj.middleware.authn-info-header :refer [authn-info-header]]
[com.sixsq.slipstream.ssclj.resources.common.utils :as u]
[com.sixsq.slipstream.ssclj.resources.deployment-template :as dt]
[com.sixsq.slipstream.ssclj.resources.lifecycle-test-utils :as ltu]
[com.sixsq.slipstream.ssclj.resources.module :as module]
[com.sixsq.slipstream.ssclj.resources.module-lifecycle-test :as module-test]
[peridot.core :refer :all]))
(use-fixtures :each ltu/with-test-server-fixture)
(def collection-uri (str p/service-context (u/de-camelcase dt/resource-name)))
(defn valid-comp [image-id] {:parentModule {:href image-id}
:networkType "public"
:disk 200
:inputParameters [{:parameter "iparam-1" :description "desc2" :value "100"}
{:parameter "iparam-2" :description "desc2"}
{:parameter "iparam-3"}]
:outputParameters [{:parameter "oparam-1" :description "desc2" :value "100"}
{:parameter "oparam-2" :description "desc2"}
{:parameter "oparam-3"}]
:targets {:preinstall "preinstall"
:packages ["emacs-nox" "vim"]
:postinstall "postinstall"
:deployment "deployment"
:reporting "reporting"
:onVmAdd "onVmAdd"
:onVmRemove "onVmRemove"
:prescale "prescale"
:postscale "postscale"}
:author "some<NAME>"
:commit "wip"})
(deftest lifecycle
(let [session-anon (-> (ltu/ring-app)
session
(content-type "application/json"))
session-user (header session-anon authn-info-header "jane USER")
session-tarzan (header session-anon authn-info-header "tarzan USER")
session-admin (header session-anon authn-info-header "root ADMIN")
module-img-uri (-> session-user
(request module-test/base-uri
:request-method :post
:body (json/write-str (assoc module-test/valid-entry
:content module-test/valid-image)))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location))
module-uri (-> session-user
(request module-test/base-uri
:request-method :post
:body (json/write-str (assoc {:resourceURI module/resource-uri
:parentPath "a/b"
:path "a/b/c"
:type "COMPONENT"}
:content (valid-comp module-img-uri))))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location))
valid-create {:module {:href module-uri}}]
(-> session-user
(request (str p/service-context module-uri))
(ltu/body->edn)
(ltu/is-status 200))
;; anonymous create should fail
(-> session-anon
(request collection-uri
:request-method :post
:body (json/write-str valid-create))
(ltu/body->edn)
(ltu/is-status 403))
;; full deployment template lifecycle as user should work
(let [deployment-template-uri (-> session-user
(request collection-uri
:request-method :post
:body (json/write-str valid-create))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location))
resource-uri (str p/service-context (u/de-camelcase deployment-template-uri))]
;; admin get succeeds
(-> session-admin
(request resource-uri)
(ltu/body->edn)
(ltu/is-status 200))
;; user get succeeds
(-> session-user
(request resource-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-key-value #(-> % :module :path) (:path module-test/valid-entry)))
;; user tarzan get fails
(-> session-tarzan
(request resource-uri)
(ltu/body->edn)
(ltu/is-status 403))
;; user update works
(-> session-user
(request resource-uri
:request-method :put
:body (json/write-str {}))
(ltu/body->edn)
(ltu/is-status 200))
;; user query succeeds
(-> session-user
(request collection-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count 1))
;; anonymous query fails
(-> session-anon
(request collection-uri)
(ltu/body->edn)
(ltu/is-status 403))
;; user delete succeeds
(-> session-user
(request resource-uri
:request-method :delete)
(ltu/body->edn)
(ltu/is-status 200))
;; ensure entry is really gone
(-> session-admin
(request resource-uri)
(ltu/body->edn)
(ltu/is-status 404)))))
(deftest bad-methods
(let [resource-uri (str p/service-context (u/new-resource-id dt/resource-name))]
(ltu/verify-405-status [[collection-uri :options]
[collection-uri :delete]
[resource-uri :options]
[resource-uri :post]])))
| true | (ns com.sixsq.slipstream.ssclj.resources.deployment-template-lifecycle-test
(:require
[clojure.data.json :as json]
[clojure.test :refer [deftest is use-fixtures]]
[com.sixsq.slipstream.ssclj.app.params :as p]
[com.sixsq.slipstream.ssclj.middleware.authn-info-header :refer [authn-info-header]]
[com.sixsq.slipstream.ssclj.resources.common.utils :as u]
[com.sixsq.slipstream.ssclj.resources.deployment-template :as dt]
[com.sixsq.slipstream.ssclj.resources.lifecycle-test-utils :as ltu]
[com.sixsq.slipstream.ssclj.resources.module :as module]
[com.sixsq.slipstream.ssclj.resources.module-lifecycle-test :as module-test]
[peridot.core :refer :all]))
(use-fixtures :each ltu/with-test-server-fixture)
(def collection-uri (str p/service-context (u/de-camelcase dt/resource-name)))
(defn valid-comp [image-id] {:parentModule {:href image-id}
:networkType "public"
:disk 200
:inputParameters [{:parameter "iparam-1" :description "desc2" :value "100"}
{:parameter "iparam-2" :description "desc2"}
{:parameter "iparam-3"}]
:outputParameters [{:parameter "oparam-1" :description "desc2" :value "100"}
{:parameter "oparam-2" :description "desc2"}
{:parameter "oparam-3"}]
:targets {:preinstall "preinstall"
:packages ["emacs-nox" "vim"]
:postinstall "postinstall"
:deployment "deployment"
:reporting "reporting"
:onVmAdd "onVmAdd"
:onVmRemove "onVmRemove"
:prescale "prescale"
:postscale "postscale"}
:author "somePI:NAME:<NAME>END_PI"
:commit "wip"})
(deftest lifecycle
(let [session-anon (-> (ltu/ring-app)
session
(content-type "application/json"))
session-user (header session-anon authn-info-header "jane USER")
session-tarzan (header session-anon authn-info-header "tarzan USER")
session-admin (header session-anon authn-info-header "root ADMIN")
module-img-uri (-> session-user
(request module-test/base-uri
:request-method :post
:body (json/write-str (assoc module-test/valid-entry
:content module-test/valid-image)))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location))
module-uri (-> session-user
(request module-test/base-uri
:request-method :post
:body (json/write-str (assoc {:resourceURI module/resource-uri
:parentPath "a/b"
:path "a/b/c"
:type "COMPONENT"}
:content (valid-comp module-img-uri))))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location))
valid-create {:module {:href module-uri}}]
(-> session-user
(request (str p/service-context module-uri))
(ltu/body->edn)
(ltu/is-status 200))
;; anonymous create should fail
(-> session-anon
(request collection-uri
:request-method :post
:body (json/write-str valid-create))
(ltu/body->edn)
(ltu/is-status 403))
;; full deployment template lifecycle as user should work
(let [deployment-template-uri (-> session-user
(request collection-uri
:request-method :post
:body (json/write-str valid-create))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location))
resource-uri (str p/service-context (u/de-camelcase deployment-template-uri))]
;; admin get succeeds
(-> session-admin
(request resource-uri)
(ltu/body->edn)
(ltu/is-status 200))
;; user get succeeds
(-> session-user
(request resource-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-key-value #(-> % :module :path) (:path module-test/valid-entry)))
;; user tarzan get fails
(-> session-tarzan
(request resource-uri)
(ltu/body->edn)
(ltu/is-status 403))
;; user update works
(-> session-user
(request resource-uri
:request-method :put
:body (json/write-str {}))
(ltu/body->edn)
(ltu/is-status 200))
;; user query succeeds
(-> session-user
(request collection-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count 1))
;; anonymous query fails
(-> session-anon
(request collection-uri)
(ltu/body->edn)
(ltu/is-status 403))
;; user delete succeeds
(-> session-user
(request resource-uri
:request-method :delete)
(ltu/body->edn)
(ltu/is-status 200))
;; ensure entry is really gone
(-> session-admin
(request resource-uri)
(ltu/body->edn)
(ltu/is-status 404)))))
(deftest bad-methods
(let [resource-uri (str p/service-context (u/new-resource-id dt/resource-name))]
(ltu/verify-405-status [[collection-uri :options]
[collection-uri :delete]
[resource-uri :options]
[resource-uri :post]])))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.