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": "esentation of time for the server\"\n :author \"Sam Aaron\"}\n overtone.sc.clock\n (:use [overtone.sc sy",
"end": 81,
"score": 0.999884307384491,
"start": 72,
"tag": "NAME",
"value": "Sam Aaron"
}
] | src/overtone/sc/clock.clj | ABaldwinHunter/overtone | 3,870 | (ns
^{:doc "A representation of time for the server"
:author "Sam Aaron"}
overtone.sc.clock
(:use [overtone.sc synth ugens node bus server info foundation-groups]
[overtone.libs deps])
(:require [overtone.sc.defaults :as defaults]))
(defonce server-clock-start-time (atom nil))
(defonce wall-clock-s (atom nil ))
;; should only be modified by a 'singleton' wall-clock synth
;; global shared state FTW!
(defonce ^{:doc (str "2 Channel server clock bus.
First channel is the small tick, second is big tick. Every
SC-MAX-FLOAT-VAL ticks, small tick resets back to 0 and big tick
increments by one.")}
server-clock-b
(control-bus 2 "Server Clock Buses"))
;; Only one of these should ever be created...
(defonce __SERVER-CLOCK-SYNTH__
(defsynth __internal-wall-clock__ [tick-bus-2c 0]
(let [[s-tick b-tick] (in:kr tick-bus-2c 2)
maxed? (= defaults/SC-MAX-FLOAT-VAL s-tick)
small-tick (select:kr maxed?
[(+ s-tick 1)
0])
big-tick (pulse-count maxed?)]
(replace-out:kr tick-bus-2c [small-tick big-tick]))))
(defn- server-clock-reset-tick-b
[]
(control-bus-set-range! server-clock-b [0 0]))
(defn- server-clock-start
[]
(ensure-connected!)
(assert (foundation-timing-group) "Couldn't find timing group")
(kill __internal-wall-clock__)
(server-clock-reset-tick-b)
(let [start-t (+ (System/currentTimeMillis) 500)]
(reset! server-clock-start-time start-t)
(at start-t (__internal-wall-clock__ [:head (foundation-timing-group)] server-clock-b))))
(defn server-clock-n-ticks
"Returns the number of internal ticks since the server clock was
started. The server clock is implemented internally with a synth and
the duration of each tick is measured in terms of the server's
control rate.
See server-clock-uptime and server-clock-time for functions that
return time in milliseconds."
[]
(let [[s-t b-t] (control-bus-get-range server-clock-b 2)]
(+ (* b-t defaults/SC-MAX-FLOAT-VAL)
s-t)))
(defn server-clock-uptime
"Returns the uptime of the server clock in milliseconds."
[]
(* 1000 (server-clock-n-ticks) (server-control-dur)))
(defn server-clock-time
"Returns the time of the server in number of milliseconds since the
epoch. Similar to system time, although not kept in sync. See
server-clock-drift for the difference between the system and server
clocks."
[]
(+ @server-clock-start-time (server-clock-uptime)))
(defn server-clock-drift
"Returns the difference between the server's clock and the system
clock in ms.
The system clock is accessed with the function (now). The server
clock is internal to a running instance of a SuperCollider server and
is implemented with a specific synth.
The server clock was started in absolute synchronisation with the
system clock, however it isn't kept in sync and will drift apart over
time. This function returns the amount of drift."
[]
(- (System/currentTimeMillis) (server-clock-time)))
(on-deps [:foundation-groups-created :synthdefs-loaded] ::start-clock server-clock-start)
| 44150 | (ns
^{:doc "A representation of time for the server"
:author "<NAME>"}
overtone.sc.clock
(:use [overtone.sc synth ugens node bus server info foundation-groups]
[overtone.libs deps])
(:require [overtone.sc.defaults :as defaults]))
(defonce server-clock-start-time (atom nil))
(defonce wall-clock-s (atom nil ))
;; should only be modified by a 'singleton' wall-clock synth
;; global shared state FTW!
(defonce ^{:doc (str "2 Channel server clock bus.
First channel is the small tick, second is big tick. Every
SC-MAX-FLOAT-VAL ticks, small tick resets back to 0 and big tick
increments by one.")}
server-clock-b
(control-bus 2 "Server Clock Buses"))
;; Only one of these should ever be created...
(defonce __SERVER-CLOCK-SYNTH__
(defsynth __internal-wall-clock__ [tick-bus-2c 0]
(let [[s-tick b-tick] (in:kr tick-bus-2c 2)
maxed? (= defaults/SC-MAX-FLOAT-VAL s-tick)
small-tick (select:kr maxed?
[(+ s-tick 1)
0])
big-tick (pulse-count maxed?)]
(replace-out:kr tick-bus-2c [small-tick big-tick]))))
(defn- server-clock-reset-tick-b
[]
(control-bus-set-range! server-clock-b [0 0]))
(defn- server-clock-start
[]
(ensure-connected!)
(assert (foundation-timing-group) "Couldn't find timing group")
(kill __internal-wall-clock__)
(server-clock-reset-tick-b)
(let [start-t (+ (System/currentTimeMillis) 500)]
(reset! server-clock-start-time start-t)
(at start-t (__internal-wall-clock__ [:head (foundation-timing-group)] server-clock-b))))
(defn server-clock-n-ticks
"Returns the number of internal ticks since the server clock was
started. The server clock is implemented internally with a synth and
the duration of each tick is measured in terms of the server's
control rate.
See server-clock-uptime and server-clock-time for functions that
return time in milliseconds."
[]
(let [[s-t b-t] (control-bus-get-range server-clock-b 2)]
(+ (* b-t defaults/SC-MAX-FLOAT-VAL)
s-t)))
(defn server-clock-uptime
"Returns the uptime of the server clock in milliseconds."
[]
(* 1000 (server-clock-n-ticks) (server-control-dur)))
(defn server-clock-time
"Returns the time of the server in number of milliseconds since the
epoch. Similar to system time, although not kept in sync. See
server-clock-drift for the difference between the system and server
clocks."
[]
(+ @server-clock-start-time (server-clock-uptime)))
(defn server-clock-drift
"Returns the difference between the server's clock and the system
clock in ms.
The system clock is accessed with the function (now). The server
clock is internal to a running instance of a SuperCollider server and
is implemented with a specific synth.
The server clock was started in absolute synchronisation with the
system clock, however it isn't kept in sync and will drift apart over
time. This function returns the amount of drift."
[]
(- (System/currentTimeMillis) (server-clock-time)))
(on-deps [:foundation-groups-created :synthdefs-loaded] ::start-clock server-clock-start)
| true | (ns
^{:doc "A representation of time for the server"
:author "PI:NAME:<NAME>END_PI"}
overtone.sc.clock
(:use [overtone.sc synth ugens node bus server info foundation-groups]
[overtone.libs deps])
(:require [overtone.sc.defaults :as defaults]))
(defonce server-clock-start-time (atom nil))
(defonce wall-clock-s (atom nil ))
;; should only be modified by a 'singleton' wall-clock synth
;; global shared state FTW!
(defonce ^{:doc (str "2 Channel server clock bus.
First channel is the small tick, second is big tick. Every
SC-MAX-FLOAT-VAL ticks, small tick resets back to 0 and big tick
increments by one.")}
server-clock-b
(control-bus 2 "Server Clock Buses"))
;; Only one of these should ever be created...
(defonce __SERVER-CLOCK-SYNTH__
(defsynth __internal-wall-clock__ [tick-bus-2c 0]
(let [[s-tick b-tick] (in:kr tick-bus-2c 2)
maxed? (= defaults/SC-MAX-FLOAT-VAL s-tick)
small-tick (select:kr maxed?
[(+ s-tick 1)
0])
big-tick (pulse-count maxed?)]
(replace-out:kr tick-bus-2c [small-tick big-tick]))))
(defn- server-clock-reset-tick-b
[]
(control-bus-set-range! server-clock-b [0 0]))
(defn- server-clock-start
[]
(ensure-connected!)
(assert (foundation-timing-group) "Couldn't find timing group")
(kill __internal-wall-clock__)
(server-clock-reset-tick-b)
(let [start-t (+ (System/currentTimeMillis) 500)]
(reset! server-clock-start-time start-t)
(at start-t (__internal-wall-clock__ [:head (foundation-timing-group)] server-clock-b))))
(defn server-clock-n-ticks
"Returns the number of internal ticks since the server clock was
started. The server clock is implemented internally with a synth and
the duration of each tick is measured in terms of the server's
control rate.
See server-clock-uptime and server-clock-time for functions that
return time in milliseconds."
[]
(let [[s-t b-t] (control-bus-get-range server-clock-b 2)]
(+ (* b-t defaults/SC-MAX-FLOAT-VAL)
s-t)))
(defn server-clock-uptime
"Returns the uptime of the server clock in milliseconds."
[]
(* 1000 (server-clock-n-ticks) (server-control-dur)))
(defn server-clock-time
"Returns the time of the server in number of milliseconds since the
epoch. Similar to system time, although not kept in sync. See
server-clock-drift for the difference between the system and server
clocks."
[]
(+ @server-clock-start-time (server-clock-uptime)))
(defn server-clock-drift
"Returns the difference between the server's clock and the system
clock in ms.
The system clock is accessed with the function (now). The server
clock is internal to a running instance of a SuperCollider server and
is implemented with a specific synth.
The server clock was started in absolute synchronisation with the
system clock, however it isn't kept in sync and will drift apart over
time. This function returns the amount of drift."
[]
(- (System/currentTimeMillis) (server-clock-time)))
(on-deps [:foundation-groups-created :synthdefs-loaded] ::start-clock server-clock-start)
|
[
{
"context": " utils\n\n;;;; begin \"2. Transactions\"\n(def users {:alice {:name \"Alice\"\n :symmetric-key",
"end": 714,
"score": 0.7642388939857483,
"start": 709,
"tag": "USERNAME",
"value": "alice"
},
{
"context": "egin \"2. Transactions\"\n(def users {:alice {:name \"Alice\"\n :symmetric-key \"alice's key\"",
"end": 728,
"score": 0.9996553659439087,
"start": 723,
"tag": "NAME",
"value": "Alice"
},
{
"context": ":name \"Alice\"\n :symmetric-key \"alice's key\"}\n :bob {:name \"Bob\"\n ",
"end": 771,
"score": 0.9874343276023865,
"start": 766,
"tag": "NAME",
"value": "alice"
},
{
"context": " :symmetric-key \"alice's key\"}\n :bob {:name \"Bob\"\n :symmetric-key \"bo",
"end": 796,
"score": 0.7001545429229736,
"start": 793,
"tag": "NAME",
"value": "bob"
},
{
"context": "etric-key \"alice's key\"}\n :bob {:name \"Bob\"\n :symmetric-key \"bob's key\"}\n ",
"end": 808,
"score": 0.9996733069419861,
"start": 805,
"tag": "NAME",
"value": "Bob"
},
{
"context": " :symmetric-key \"bob's key\"}\n :charlie {:name \"Charlie\"\n :symmetric",
"end": 876,
"score": 0.7832069993019104,
"start": 869,
"tag": "USERNAME",
"value": "charlie"
},
{
"context": "ric-key \"bob's key\"}\n :charlie {:name \"Charlie\"\n :symmetric-key \"charlie's ",
"end": 892,
"score": 0.9992471933364868,
"start": 885,
"tag": "NAME",
"value": "Charlie"
},
{
"context": "e \"Charlie\"\n :symmetric-key \"charlie's key\"}\n :dave {:name \"Dave\"\n ",
"end": 939,
"score": 0.9132356643676758,
"start": 932,
"tag": "NAME",
"value": "charlie"
},
{
"context": " :symmetric-key \"charlie's key\"}\n :dave {:name \"Dave\"\n :symmetric-key \"",
"end": 965,
"score": 0.5770871639251709,
"start": 961,
"tag": "NAME",
"value": "dave"
},
{
"context": "ic-key \"charlie's key\"}\n :dave {:name \"Dave\"\n :symmetric-key \"dave's key\"}}",
"end": 978,
"score": 0.9994677901268005,
"start": 974,
"tag": "NAME",
"value": "Dave"
},
{
"context": " {:name \"Dave\"\n :symmetric-key \"dave's key\"}})\n\n(defn sign\n \"Returns the signature of",
"end": 1019,
"score": 0.7589424848556519,
"start": 1015,
"tag": "NAME",
"value": "dave"
},
{
"context": "]\n (<= (count coin) 1))\n\n(new? [])\n(new? [{:bah \"humbug\"}])\n\n(defn valid?\n \"Returns true if sig is a val",
"end": 1316,
"score": 0.7368810176849365,
"start": 1310,
"tag": "USERNAME",
"value": "humbug"
},
{
"context": " 1234 \"prev hash\"\n [{:payee-pub-key \"alice\",\n :signature \"zero:332913733\"}]\n",
"end": 3225,
"score": 0.7976321578025818,
"start": 3220,
"tag": "NAME",
"value": "alice"
},
{
"context": "zero:332913733\"}]\n [{:payee-pub-key \"charlie\",\n :signature \"hector:332913733\"}",
"end": 3314,
"score": 0.9638943076133728,
"start": 3307,
"tag": "NAME",
"value": "charlie"
}
] | src/botcoin/core.clj | jreber/Botcoin | 0 | (ns botcoin.core
(:gen-class))
;;;; Open Questions
(comment
"1. How does Bitcoin handle bootstrapping new coins? What does a new coin look like?
-> I resolved it by allowing the first transaction to contain whatever sig
it wants. Unfortunately, this allows nodes to create coin unchecked.
2. How does Bitcoin prevent node operators from running the presses all day
long? What prevents node operators from creating blocks with nothing but
new coins?")
;;;; end Open Questions
;;;; start misc utils
(defn create-valid-coin
[] ())
(defn create-invalid-coin
[] ())
(defn create-valid-blockchain
[] ())
;;;; end misc utils
;;;; begin "2. Transactions"
(def users {:alice {:name "Alice"
:symmetric-key "alice's key"}
:bob {:name "Bob"
:symmetric-key "bob's key"}
:charlie {:name "Charlie"
:symmetric-key "charlie's key"}
:dave {:name "Dave"
:symmetric-key "dave's key"}})
(defn sign
"Returns the signature of o using key."
[key o]
;; I call this "symmetric key cryptography." Super secure.
(str key ":" (hash o)))
(defn new?
"Returns true if the given coin is new, false otherwise."
[coin]
(<= (count coin) 1))
(new? [])
(new? [{:bah "humbug"}])
(defn valid?
"Returns true if sig is a valid signature of o using to key, false otherwise."
([coin]
(or (new? coin)
(and (valid? (:payee-pub-key (second coin))
(:signature (first coin))
(assoc (second coin)
:new-payee-pub-key (:payee-pub-key (first coin))))
(valid? (rest coin)))))
([key sig o]
(= sig (str key ":" (hash o)))))
(defn transfer
"Transfers funds from player payor to payee, returning an updated coin.
This is from the payor's point of view, so the payee must distrust the
result of this function."
[coin {payor-priv-key :symmetric-key payor-pub-key :symmetric-key}
{payee-pub-key :symmetric-key}]
(if (valid? coin)
(let [payor-signing-f (partial sign payor-priv-key)]
(cons {:payee-pub-key payee-pub-key
:signature (payor-signing-f
(assoc (first coin) :new-payee-pub-key payee-pub-key))}
coin))
(throw (Exception. (str "Invalid coin: " coin)))))
(def coin [])
(transfer coin (:alice users) (:bob users))
;;;; end "2. Transactions"
;;;; begin "3. Timestamp Server" and "4. Proof-of-Work"
(defn create-block
"Collects transactions into a block. The first element of the resulting sequence
is the nonce, the second is the hash of the previous block, and all subsequent
values are the transactions in the block."
[target-prefix prev-hash & coins]
; find a nonce that will make the hash be our magic number
(when-let [trans (seq (map first (filter valid? coins)))]
(let [block (cons prev-hash trans)] (cons (first
(filter #(.startsWith (str (hash (cons % block)))
(str target-prefix))
(range Long/MAX_VALUE)))
block))))
(create-block 1234 "prev hash"
[{:payee-pub-key "alice",
:signature "zero:332913733"}]
[{:payee-pub-key "charlie",
:signature "hector:332913733"}])
(defn new-blockchain?
[chain]
(<= (count chain) 1))
(defn valid-block?
"Confirms that the most recent block is valid."
[target-prefix chain]
(or (new-blockchain? chain)
(let [block (first chain)
prev-chain (rest chain)]
(and (.startsWith (str (hash block))
(str target-prefix))
(= (second block)
(hash (first prev-chain)))
(every? valid? (rest (rest block)))))))
(defn valid-blockchain?
"Confirms that the entire blockchain is valid."
[chain]
())
(defn valid-tran?
"Confirms, for a payee, that the most recent transaction is valid given a
previous record of blocks."
[chain coin]
; to be valid, a coin must (1) be internally consistent (see valid?)
; and (2) the most recent transaction must appear in an accepted block.
(or (new? coin)
(and (valid? coin)
(contains? (:payee-pub-key (second coin))
(mapcat #(map :payee-pub-key %)
chain)))))
;;;; end "3. Timestamp Server" and "4. Proof-of-Work"
(defn -main
"I don't do a whole lot ... yet."
[& args]
(println "Hello, World!"))
| 26696 | (ns botcoin.core
(:gen-class))
;;;; Open Questions
(comment
"1. How does Bitcoin handle bootstrapping new coins? What does a new coin look like?
-> I resolved it by allowing the first transaction to contain whatever sig
it wants. Unfortunately, this allows nodes to create coin unchecked.
2. How does Bitcoin prevent node operators from running the presses all day
long? What prevents node operators from creating blocks with nothing but
new coins?")
;;;; end Open Questions
;;;; start misc utils
(defn create-valid-coin
[] ())
(defn create-invalid-coin
[] ())
(defn create-valid-blockchain
[] ())
;;;; end misc utils
;;;; begin "2. Transactions"
(def users {:alice {:name "<NAME>"
:symmetric-key "<NAME>'s key"}
:<NAME> {:name "<NAME>"
:symmetric-key "bob's key"}
:charlie {:name "<NAME>"
:symmetric-key "<NAME>'s key"}
:<NAME> {:name "<NAME>"
:symmetric-key "<NAME>'s key"}})
(defn sign
"Returns the signature of o using key."
[key o]
;; I call this "symmetric key cryptography." Super secure.
(str key ":" (hash o)))
(defn new?
"Returns true if the given coin is new, false otherwise."
[coin]
(<= (count coin) 1))
(new? [])
(new? [{:bah "humbug"}])
(defn valid?
"Returns true if sig is a valid signature of o using to key, false otherwise."
([coin]
(or (new? coin)
(and (valid? (:payee-pub-key (second coin))
(:signature (first coin))
(assoc (second coin)
:new-payee-pub-key (:payee-pub-key (first coin))))
(valid? (rest coin)))))
([key sig o]
(= sig (str key ":" (hash o)))))
(defn transfer
"Transfers funds from player payor to payee, returning an updated coin.
This is from the payor's point of view, so the payee must distrust the
result of this function."
[coin {payor-priv-key :symmetric-key payor-pub-key :symmetric-key}
{payee-pub-key :symmetric-key}]
(if (valid? coin)
(let [payor-signing-f (partial sign payor-priv-key)]
(cons {:payee-pub-key payee-pub-key
:signature (payor-signing-f
(assoc (first coin) :new-payee-pub-key payee-pub-key))}
coin))
(throw (Exception. (str "Invalid coin: " coin)))))
(def coin [])
(transfer coin (:alice users) (:bob users))
;;;; end "2. Transactions"
;;;; begin "3. Timestamp Server" and "4. Proof-of-Work"
(defn create-block
"Collects transactions into a block. The first element of the resulting sequence
is the nonce, the second is the hash of the previous block, and all subsequent
values are the transactions in the block."
[target-prefix prev-hash & coins]
; find a nonce that will make the hash be our magic number
(when-let [trans (seq (map first (filter valid? coins)))]
(let [block (cons prev-hash trans)] (cons (first
(filter #(.startsWith (str (hash (cons % block)))
(str target-prefix))
(range Long/MAX_VALUE)))
block))))
(create-block 1234 "prev hash"
[{:payee-pub-key "<NAME>",
:signature "zero:332913733"}]
[{:payee-pub-key "<NAME>",
:signature "hector:332913733"}])
(defn new-blockchain?
[chain]
(<= (count chain) 1))
(defn valid-block?
"Confirms that the most recent block is valid."
[target-prefix chain]
(or (new-blockchain? chain)
(let [block (first chain)
prev-chain (rest chain)]
(and (.startsWith (str (hash block))
(str target-prefix))
(= (second block)
(hash (first prev-chain)))
(every? valid? (rest (rest block)))))))
(defn valid-blockchain?
"Confirms that the entire blockchain is valid."
[chain]
())
(defn valid-tran?
"Confirms, for a payee, that the most recent transaction is valid given a
previous record of blocks."
[chain coin]
; to be valid, a coin must (1) be internally consistent (see valid?)
; and (2) the most recent transaction must appear in an accepted block.
(or (new? coin)
(and (valid? coin)
(contains? (:payee-pub-key (second coin))
(mapcat #(map :payee-pub-key %)
chain)))))
;;;; end "3. Timestamp Server" and "4. Proof-of-Work"
(defn -main
"I don't do a whole lot ... yet."
[& args]
(println "Hello, World!"))
| true | (ns botcoin.core
(:gen-class))
;;;; Open Questions
(comment
"1. How does Bitcoin handle bootstrapping new coins? What does a new coin look like?
-> I resolved it by allowing the first transaction to contain whatever sig
it wants. Unfortunately, this allows nodes to create coin unchecked.
2. How does Bitcoin prevent node operators from running the presses all day
long? What prevents node operators from creating blocks with nothing but
new coins?")
;;;; end Open Questions
;;;; start misc utils
(defn create-valid-coin
[] ())
(defn create-invalid-coin
[] ())
(defn create-valid-blockchain
[] ())
;;;; end misc utils
;;;; begin "2. Transactions"
(def users {:alice {:name "PI:NAME:<NAME>END_PI"
:symmetric-key "PI:NAME:<NAME>END_PI's key"}
:PI:NAME:<NAME>END_PI {:name "PI:NAME:<NAME>END_PI"
:symmetric-key "bob's key"}
:charlie {:name "PI:NAME:<NAME>END_PI"
:symmetric-key "PI:NAME:<NAME>END_PI's key"}
:PI:NAME:<NAME>END_PI {:name "PI:NAME:<NAME>END_PI"
:symmetric-key "PI:NAME:<NAME>END_PI's key"}})
(defn sign
"Returns the signature of o using key."
[key o]
;; I call this "symmetric key cryptography." Super secure.
(str key ":" (hash o)))
(defn new?
"Returns true if the given coin is new, false otherwise."
[coin]
(<= (count coin) 1))
(new? [])
(new? [{:bah "humbug"}])
(defn valid?
"Returns true if sig is a valid signature of o using to key, false otherwise."
([coin]
(or (new? coin)
(and (valid? (:payee-pub-key (second coin))
(:signature (first coin))
(assoc (second coin)
:new-payee-pub-key (:payee-pub-key (first coin))))
(valid? (rest coin)))))
([key sig o]
(= sig (str key ":" (hash o)))))
(defn transfer
"Transfers funds from player payor to payee, returning an updated coin.
This is from the payor's point of view, so the payee must distrust the
result of this function."
[coin {payor-priv-key :symmetric-key payor-pub-key :symmetric-key}
{payee-pub-key :symmetric-key}]
(if (valid? coin)
(let [payor-signing-f (partial sign payor-priv-key)]
(cons {:payee-pub-key payee-pub-key
:signature (payor-signing-f
(assoc (first coin) :new-payee-pub-key payee-pub-key))}
coin))
(throw (Exception. (str "Invalid coin: " coin)))))
(def coin [])
(transfer coin (:alice users) (:bob users))
;;;; end "2. Transactions"
;;;; begin "3. Timestamp Server" and "4. Proof-of-Work"
(defn create-block
"Collects transactions into a block. The first element of the resulting sequence
is the nonce, the second is the hash of the previous block, and all subsequent
values are the transactions in the block."
[target-prefix prev-hash & coins]
; find a nonce that will make the hash be our magic number
(when-let [trans (seq (map first (filter valid? coins)))]
(let [block (cons prev-hash trans)] (cons (first
(filter #(.startsWith (str (hash (cons % block)))
(str target-prefix))
(range Long/MAX_VALUE)))
block))))
(create-block 1234 "prev hash"
[{:payee-pub-key "PI:NAME:<NAME>END_PI",
:signature "zero:332913733"}]
[{:payee-pub-key "PI:NAME:<NAME>END_PI",
:signature "hector:332913733"}])
(defn new-blockchain?
[chain]
(<= (count chain) 1))
(defn valid-block?
"Confirms that the most recent block is valid."
[target-prefix chain]
(or (new-blockchain? chain)
(let [block (first chain)
prev-chain (rest chain)]
(and (.startsWith (str (hash block))
(str target-prefix))
(= (second block)
(hash (first prev-chain)))
(every? valid? (rest (rest block)))))))
(defn valid-blockchain?
"Confirms that the entire blockchain is valid."
[chain]
())
(defn valid-tran?
"Confirms, for a payee, that the most recent transaction is valid given a
previous record of blocks."
[chain coin]
; to be valid, a coin must (1) be internally consistent (see valid?)
; and (2) the most recent transaction must appear in an accepted block.
(or (new? coin)
(and (valid? coin)
(contains? (:payee-pub-key (second coin))
(mapcat #(map :payee-pub-key %)
chain)))))
;;;; end "3. Timestamp Server" and "4. Proof-of-Work"
(defn -main
"I don't do a whole lot ... yet."
[& args]
(println "Hello, World!"))
|
[
{
"context": " :http-port 8069\n :env :prd\n :db {:username \"postgres\"\n :password \"123\"\n :server-name ",
"end": 76,
"score": 0.9995012283325195,
"start": 68,
"tag": "USERNAME",
"value": "postgres"
},
{
"context": " {:username \"postgres\"\n :password \"123\"\n :server-name \"192.168.1.47\"\n :port-",
"end": 103,
"score": 0.9991170763969421,
"start": 100,
"tag": "PASSWORD",
"value": "123"
},
{
"context": "\n :password \"123\"\n :server-name \"192.168.1.47\"\n :port-number 5432\n :database-name \"",
"end": 139,
"score": 0.9990975260734558,
"start": 127,
"tag": "IP_ADDRESS",
"value": "192.168.1.47"
}
] | conf/config.clj | sealchain/explorer-backend | 1 | {:nrepl-port 7467
:http-port 8069
:env :prd
:db {:username "postgres"
:password "123"
:server-name "192.168.1.47"
:port-number 5432
:database-name "wallet"}}
| 92120 | {:nrepl-port 7467
:http-port 8069
:env :prd
:db {:username "postgres"
:password "<PASSWORD>"
:server-name "192.168.1.47"
:port-number 5432
:database-name "wallet"}}
| true | {:nrepl-port 7467
:http-port 8069
:env :prd
:db {:username "postgres"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:server-name "192.168.1.47"
:port-number 5432
:database-name "wallet"}}
|
[
{
"context": "name \"stack-editor\"\n :key \"stack-editor\"\n :validations \"isValidCompose\"\n :multi",
"end": 962,
"score": 0.9922299981117249,
"start": 950,
"tag": "KEY",
"value": "stack-editor"
}
] | ch16/swarmpit/src/cljs/swarmpit/component/stack/edit.cljs | vincestorm/Docker-on-Amazon-Web-Services | 0 | (ns swarmpit.component.stack.edit
(:require [material.icon :as icon]
[material.component :as comp]
[material.component.form :as form]
[material.component.panel :as panel]
[swarmpit.component.editor :as editor]
[swarmpit.component.state :as state]
[swarmpit.component.mixin :as mixin]
[swarmpit.component.message :as message]
[swarmpit.component.progress :as progress]
[swarmpit.component.stack.compose :as compose]
[swarmpit.ajax :as ajax]
[swarmpit.routes :as routes]
[swarmpit.url :refer [dispatch!]]
[sablono.core :refer-macros [html]]
[rum.core :as rum]
[clojure.set :as set]))
(enable-console-print!)
(def editor-id "compose")
(defn- form-editor [value]
(comp/vtext-field
{:id editor-id
:name "stack-editor"
:key "stack-editor"
:validations "isValidCompose"
:multiLine true
:rows 10
:rowsMax 10
:value value
:underlineShow false
:fullWidth true}))
(defn- update-stack-handler
[name]
(ajax/post
(routes/path-for-backend :stack-update {:name name})
{:params (state/get-value state/form-value-cursor)
:state [:processing?]
:on-success (fn [{:keys [origin?]}]
(when origin?
(dispatch!
(routes/path-for-frontend :stack-info {:name name})))
(message/info
(str "Stack " name " has been updated.")))
:on-error (fn [{:keys [response]}]
(message/error
(str "Stack update failed. " (:error response))))}))
(defn- stackfile-handler
[name handler]
(ajax/get
(routes/path-for-backend :stack-file {:name name})
{:state [:loading?]
:on-success (fn [{:keys [response]}]
(state/set-value (case handler :stack-previous (set/rename-keys response {:previousSpec :spec}) response) state/form-value-cursor)
(state/update-value [:previous?] (:previousSpec response) state/form-state-cursor))}))
(def mixin-init-editor
{:did-mount
(fn [state]
(let [editor (editor/yaml editor-id)]
(.on editor "change" (fn [cm] (state/update-value [:spec :compose] (-> cm .getValue) state/form-value-cursor))))
state)})
(defn- init-form-state
[]
(state/set-value {:valid? false
:previous? false
:loading? true
:processing? false} state/form-state-cursor))
(defn- init-form-value
[name]
(state/set-value {:name name
:spec {:compose ""}} state/form-value-cursor))
(def mixin-init-form
(mixin/init-form
(fn [{{:keys [name]} :params :keys [handler]}]
(init-form-state)
(init-form-value name)
(stackfile-handler name handler))))
(rum/defc form-edit < mixin-init-editor [{:keys [name spec]}
select
{:keys [processing? valid? previous?]}]
[:div
[:div.form-panel
[:div.form-panel-left
(panel/info icon/stacks name)]
[:div.form-panel-right
(comp/progress-button
{:label "Deploy"
:disabled (not valid?)
:primary true
:onTouchTap #(update-stack-handler name)} processing?)]]
(form/form
{:onValid #(state/update-value [:valid?] true state/form-state-cursor)
:onInvalid #(state/update-value [:valid?] false state/form-state-cursor)}
(compose/form-name name)
(html (compose/file-select name select true previous?))
(form-editor (:compose spec)))])
(rum/defc form-last < rum/reactive
mixin-init-form [_]
(let [state (state/react state/form-state-cursor)
stackfile (state/react state/form-value-cursor)]
(progress/form
(:loading? state)
(form-edit stackfile :last state))))
(rum/defc form-previous < rum/reactive
mixin-init-form [_]
(let [state (state/react state/form-state-cursor)
stackfile (state/react state/form-value-cursor)]
(progress/form
(:loading? state)
(form-edit stackfile :previous state)))) | 6665 | (ns swarmpit.component.stack.edit
(:require [material.icon :as icon]
[material.component :as comp]
[material.component.form :as form]
[material.component.panel :as panel]
[swarmpit.component.editor :as editor]
[swarmpit.component.state :as state]
[swarmpit.component.mixin :as mixin]
[swarmpit.component.message :as message]
[swarmpit.component.progress :as progress]
[swarmpit.component.stack.compose :as compose]
[swarmpit.ajax :as ajax]
[swarmpit.routes :as routes]
[swarmpit.url :refer [dispatch!]]
[sablono.core :refer-macros [html]]
[rum.core :as rum]
[clojure.set :as set]))
(enable-console-print!)
(def editor-id "compose")
(defn- form-editor [value]
(comp/vtext-field
{:id editor-id
:name "stack-editor"
:key "<KEY>"
:validations "isValidCompose"
:multiLine true
:rows 10
:rowsMax 10
:value value
:underlineShow false
:fullWidth true}))
(defn- update-stack-handler
[name]
(ajax/post
(routes/path-for-backend :stack-update {:name name})
{:params (state/get-value state/form-value-cursor)
:state [:processing?]
:on-success (fn [{:keys [origin?]}]
(when origin?
(dispatch!
(routes/path-for-frontend :stack-info {:name name})))
(message/info
(str "Stack " name " has been updated.")))
:on-error (fn [{:keys [response]}]
(message/error
(str "Stack update failed. " (:error response))))}))
(defn- stackfile-handler
[name handler]
(ajax/get
(routes/path-for-backend :stack-file {:name name})
{:state [:loading?]
:on-success (fn [{:keys [response]}]
(state/set-value (case handler :stack-previous (set/rename-keys response {:previousSpec :spec}) response) state/form-value-cursor)
(state/update-value [:previous?] (:previousSpec response) state/form-state-cursor))}))
(def mixin-init-editor
{:did-mount
(fn [state]
(let [editor (editor/yaml editor-id)]
(.on editor "change" (fn [cm] (state/update-value [:spec :compose] (-> cm .getValue) state/form-value-cursor))))
state)})
(defn- init-form-state
[]
(state/set-value {:valid? false
:previous? false
:loading? true
:processing? false} state/form-state-cursor))
(defn- init-form-value
[name]
(state/set-value {:name name
:spec {:compose ""}} state/form-value-cursor))
(def mixin-init-form
(mixin/init-form
(fn [{{:keys [name]} :params :keys [handler]}]
(init-form-state)
(init-form-value name)
(stackfile-handler name handler))))
(rum/defc form-edit < mixin-init-editor [{:keys [name spec]}
select
{:keys [processing? valid? previous?]}]
[:div
[:div.form-panel
[:div.form-panel-left
(panel/info icon/stacks name)]
[:div.form-panel-right
(comp/progress-button
{:label "Deploy"
:disabled (not valid?)
:primary true
:onTouchTap #(update-stack-handler name)} processing?)]]
(form/form
{:onValid #(state/update-value [:valid?] true state/form-state-cursor)
:onInvalid #(state/update-value [:valid?] false state/form-state-cursor)}
(compose/form-name name)
(html (compose/file-select name select true previous?))
(form-editor (:compose spec)))])
(rum/defc form-last < rum/reactive
mixin-init-form [_]
(let [state (state/react state/form-state-cursor)
stackfile (state/react state/form-value-cursor)]
(progress/form
(:loading? state)
(form-edit stackfile :last state))))
(rum/defc form-previous < rum/reactive
mixin-init-form [_]
(let [state (state/react state/form-state-cursor)
stackfile (state/react state/form-value-cursor)]
(progress/form
(:loading? state)
(form-edit stackfile :previous state)))) | true | (ns swarmpit.component.stack.edit
(:require [material.icon :as icon]
[material.component :as comp]
[material.component.form :as form]
[material.component.panel :as panel]
[swarmpit.component.editor :as editor]
[swarmpit.component.state :as state]
[swarmpit.component.mixin :as mixin]
[swarmpit.component.message :as message]
[swarmpit.component.progress :as progress]
[swarmpit.component.stack.compose :as compose]
[swarmpit.ajax :as ajax]
[swarmpit.routes :as routes]
[swarmpit.url :refer [dispatch!]]
[sablono.core :refer-macros [html]]
[rum.core :as rum]
[clojure.set :as set]))
(enable-console-print!)
(def editor-id "compose")
(defn- form-editor [value]
(comp/vtext-field
{:id editor-id
:name "stack-editor"
:key "PI:KEY:<KEY>END_PI"
:validations "isValidCompose"
:multiLine true
:rows 10
:rowsMax 10
:value value
:underlineShow false
:fullWidth true}))
(defn- update-stack-handler
[name]
(ajax/post
(routes/path-for-backend :stack-update {:name name})
{:params (state/get-value state/form-value-cursor)
:state [:processing?]
:on-success (fn [{:keys [origin?]}]
(when origin?
(dispatch!
(routes/path-for-frontend :stack-info {:name name})))
(message/info
(str "Stack " name " has been updated.")))
:on-error (fn [{:keys [response]}]
(message/error
(str "Stack update failed. " (:error response))))}))
(defn- stackfile-handler
[name handler]
(ajax/get
(routes/path-for-backend :stack-file {:name name})
{:state [:loading?]
:on-success (fn [{:keys [response]}]
(state/set-value (case handler :stack-previous (set/rename-keys response {:previousSpec :spec}) response) state/form-value-cursor)
(state/update-value [:previous?] (:previousSpec response) state/form-state-cursor))}))
(def mixin-init-editor
{:did-mount
(fn [state]
(let [editor (editor/yaml editor-id)]
(.on editor "change" (fn [cm] (state/update-value [:spec :compose] (-> cm .getValue) state/form-value-cursor))))
state)})
(defn- init-form-state
[]
(state/set-value {:valid? false
:previous? false
:loading? true
:processing? false} state/form-state-cursor))
(defn- init-form-value
[name]
(state/set-value {:name name
:spec {:compose ""}} state/form-value-cursor))
(def mixin-init-form
(mixin/init-form
(fn [{{:keys [name]} :params :keys [handler]}]
(init-form-state)
(init-form-value name)
(stackfile-handler name handler))))
(rum/defc form-edit < mixin-init-editor [{:keys [name spec]}
select
{:keys [processing? valid? previous?]}]
[:div
[:div.form-panel
[:div.form-panel-left
(panel/info icon/stacks name)]
[:div.form-panel-right
(comp/progress-button
{:label "Deploy"
:disabled (not valid?)
:primary true
:onTouchTap #(update-stack-handler name)} processing?)]]
(form/form
{:onValid #(state/update-value [:valid?] true state/form-state-cursor)
:onInvalid #(state/update-value [:valid?] false state/form-state-cursor)}
(compose/form-name name)
(html (compose/file-select name select true previous?))
(form-editor (:compose spec)))])
(rum/defc form-last < rum/reactive
mixin-init-form [_]
(let [state (state/react state/form-state-cursor)
stackfile (state/react state/form-value-cursor)]
(progress/form
(:loading? state)
(form-edit stackfile :last state))))
(rum/defc form-previous < rum/reactive
mixin-init-form [_]
(let [state (state/react state/form-state-cursor)
stackfile (state/react state/form-value-cursor)]
(progress/form
(:loading? state)
(form-edit stackfile :previous state)))) |
[
{
"context": "ure than\n;; 10 functions on 10 data structures.” —Alan Perlis\n\n\n;; 序列(sequence) 是clojure中重要的概念,表示一个逻辑list,抽象为IS",
"end": 200,
"score": 0.9998975992202759,
"start": 189,
"tag": "NAME",
"value": "Alan Perlis"
},
{
"context": " as follow:\n(list 1 2 3)\n\n\n;; set\n(def players #{\"Alice\", \"Bob\", \"Kelly\"})\n;; map\n(def scores {\"Fred\" 1",
"end": 2284,
"score": 0.9997544884681702,
"start": 2279,
"tag": "NAME",
"value": "Alice"
},
{
"context": "w:\n(list 1 2 3)\n\n\n;; set\n(def players #{\"Alice\", \"Bob\", \"Kelly\"})\n;; map\n(def scores {\"Fred\" 1400\n ",
"end": 2291,
"score": 0.9998303055763245,
"start": 2288,
"tag": "NAME",
"value": "Bob"
},
{
"context": "t 1 2 3)\n\n\n;; set\n(def players #{\"Alice\", \"Bob\", \"Kelly\"})\n;; map\n(def scores {\"Fred\" 1400\n ",
"end": 2300,
"score": 0.9998108148574829,
"start": 2295,
"tag": "NAME",
"value": "Kelly"
},
{
"context": " #{\"Alice\", \"Bob\", \"Kelly\"})\n;; map\n(def scores {\"Fred\" 1400\n \"Bob\" 1240\n \"",
"end": 2329,
"score": 0.9997517466545105,
"start": 2325,
"tag": "NAME",
"value": "Fred"
},
{
"context": ")\n;; map\n(def scores {\"Fred\" 1400\n \"Bob\" 1240\n \"Angela\" 1024})\n(assoc scor",
"end": 2355,
"score": 0.9998175501823425,
"start": 2352,
"tag": "NAME",
"value": "Bob"
},
{
"context": "\" 1400\n \"Bob\" 1240\n \"Angela\" 1024})\n(assoc scores \"Sally\" 0) ",
"end": 2385,
"score": 0.9997541904449463,
"start": 2379,
"tag": "NAME",
"value": "Angela"
},
{
"context": " 1240\n \"Angela\" 1024})\n(assoc scores \"Sally\" 0) ;;associat",
"end": 2414,
"score": 0.9995443224906921,
"start": 2409,
"tag": "NAME",
"value": "Sally"
},
{
"context": " ;;associate\n(dissoc scores \"Bob\") ;;dissoci",
"end": 2485,
"score": 0.9987673759460449,
"start": 2482,
"tag": "NAME",
"value": "Bob"
},
{
"context": " ;;dissociate\n(get scores \"Angela\")\n(contains? scores \"Fred\")\n(keys scores)\n\n(def p",
"end": 2558,
"score": 0.9991698265075684,
"start": 2552,
"tag": "NAME",
"value": "Angela"
},
{
"context": "ssociate\n(get scores \"Angela\")\n(contains? scores \"Fred\")\n(keys scores)\n\n(def players #{\"Alice\" \"Bob\" \"Ke",
"end": 2584,
"score": 0.9995720386505127,
"start": 2580,
"tag": "NAME",
"value": "Fred"
},
{
"context": "ns? scores \"Fred\")\n(keys scores)\n\n(def players #{\"Alice\" \"Bob\" \"Kelly\"})\n(zipmap players (repeat 0))\n\n;; ",
"end": 2623,
"score": 0.9997703433036804,
"start": 2618,
"tag": "NAME",
"value": "Alice"
},
{
"context": "es \"Fred\")\n(keys scores)\n\n(def players #{\"Alice\" \"Bob\" \"Kelly\"})\n(zipmap players (repeat 0))\n\n;; with m",
"end": 2629,
"score": 0.9998251795768738,
"start": 2626,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ed\")\n(keys scores)\n\n(def players #{\"Alice\" \"Bob\" \"Kelly\"})\n(zipmap players (repeat 0))\n\n;; with map and i",
"end": 2637,
"score": 0.9997873306274414,
"start": 2632,
"tag": "NAME",
"value": "Kelly"
},
{
"context": "ord, the keyword can be function\n(def stu {:name \"bob\" :age 10})\n(:name stu) ",
"end": 2977,
"score": 0.7354338765144348,
"start": 2974,
"tag": "USERNAME",
"value": "bob"
},
{
"context": "f sm (sorted-map\n \"Bravo\" 204\n \"Alfa\" 35\n \"Sigma\" 99\n \"Charlie\" 100)",
"end": 3581,
"score": 0.9981818795204163,
"start": 3577,
"tag": "NAME",
"value": "Alfa"
},
{
"context": " \"Alfa\" 35\n \"Sigma\" 99\n \"Charlie\" 100))\n;;{\"Alfa\" 35, \"Bravo\" 204, \"Charlie\" 10",
"end": 3622,
"score": 0.5982324481010437,
"start": 3618,
"tag": "NAME",
"value": "Char"
},
{
"context": " \"Sigma\" 99\n \"Charlie\" 100))\n;;{\"Alfa\" 35, \"Bravo\" 204, \"Charlie\" 100, \"Sigma\" 99}\n",
"end": 3641,
"score": 0.9986383318901062,
"start": 3637,
"tag": "NAME",
"value": "Alfa"
},
{
"context": "igma\" 99\n \"Charlie\" 100))\n;;{\"Alfa\" 35, \"Bravo\" 204, \"Charlie\" 100, \"Sigma\" 99}\n",
"end": 3653,
"score": 0.9506596326828003,
"start": 3648,
"tag": "NAME",
"value": "Bravo"
},
{
"context": " \"Charlie\" 100))\n;;{\"Alfa\" 35, \"Bravo\" 204, \"Charlie\" 100, \"Sigma\" 99}\n",
"end": 3668,
"score": 0.9499658346176147,
"start": 3661,
"tag": "NAME",
"value": "Charlie"
}
] | src/clj_notes/collections.clj | zhimoe/clj-notes | 0 | (ns clj-notes.collections)
;; 数据结构是编程中最重要的部分,clojure提供了丰富的集合类型,同时做到了抽象统一
;; “It is better to have 100 functions operate on one data structure than
;; 10 functions on 10 data structures.” —Alan Perlis
;; 序列(sequence) 是clojure中重要的概念,表示一个逻辑list,抽象为ISeq接口。
;; 序列clojure.lang.ISeq包含重要方法:
;; (first coll),(next coll),(cons item seq), (rest coll),(more coll), equiv,count, empty, seq方法
(def coll []) ;; vector
(let [s (seq coll)]
(if s
(comment "work on (first s) and recur on (rest s)")
(comment "all done - terminate")))
;; 可以生成序列的结构称为 Seqable
;; ======start
;; 几乎一切数据结构在clojure中都是序列,这些数据结构包括:
;; All iterable types (types that implement java.util.Iterable)
;; Java collections (java.util.Set, java.util.List, etc)
;; Java arrays
;; Java maps
;; All types that implement java.lang.CharSequence interface, including Java strings
;; nil
;; clojure.lang.ISeq - the sequence abstraction interface,更常用的是clojure.lang.ASeq,clojure.lang.LazySeq
;; clojure.lang.Seqable - seqable marker,只有一个方法:ISeq seq()
;; clojure.lang.Sequential - 遍历顺序和初始化顺序一致,Lists, vectors, and effectively all seqs are sequential.
;; ======end
;; Sequence functions (map, filter, etc) 会隐式call seq on the incoming (seqable) collection and
;; return a sequence (possibly empty, not nil)
;; 大部分情况下,开发者使用的都是map和seq两种数据结构,map有时也是当作seq来处理
;; clojure中4大数据结构,list是直接实现ISeq接口,而set,vector,map实现的是Seqable接口
;; ====== seq和sequence方法区别,sequence always return () when false
(seq nil) ;; => nil
(sequence nil) ;; => ()
(seq ()) ;; => nil
(sequence ()) ;; => ()
;; 创建seq的函数
;; range,repeat,iterate,cycle,interleave(交错取值),interpose(给序列插入一个间隔值)
;; 关于seq的全部方法,参考官方ref:https://clojure.org/reference/sequences
;; vector map list set四大数据结构
;; vector是arraylist,可以通过索引访问
;; literal
([1 2 3 5])
(vector 1 2 3)
(get ["abc" false 99] 0)
(conj [1 2 3] 4 5 6)
;; list是linked list,只能通过遍历或者first/rest/nth
(def cards '(10 :ace :jack 9))
;; literal list, 这里需要使用quote是因为clojure的语法就是list,不quote的话,会被认为是一个表达式,执行后发现第一个参数不是方法,抛异常
'(1 2 3)
;; same as follow:
(list 1 2 3)
;; set
(def players #{"Alice", "Bob", "Kelly"})
;; map
(def scores {"Fred" 1400
"Bob" 1240
"Angela" 1024})
(assoc scores "Sally" 0) ;;associate
(dissoc scores "Bob") ;;dissociate
(get scores "Angela")
(contains? scores "Fred")
(keys scores)
(def players #{"Alice" "Bob" "Kelly"})
(zipmap players (repeat 0))
;; with map and into
(into {} (map (fn [p layer] [players 0]) players))
;; with reduce
(reduce (fn [m player]
(assoc m player 0))
{} ; initial value
players)
;; when key is keyword, the keyword can be function
(def stu {:name "bob" :age 10})
(:name stu) ;;=> "bob"
;; map destructuring
(def my-hashmap {:a "A" :b "B" :c "C" :d "D"})
(def my-nested-hashmap {:a "A" :b "B" :c "C" :d "D" :q {:x "X" :y "Y" :z "Z"}})
(let [{a :a d :d} my-hashmap]
(println a d))
;; ;; => A D
(let [{a :a, b :b, {x :x, y :y} :q} my-nested-hashmap]
(println a b x y))
;; ;; => A B X Y
(let [{a :a, b :b, not-found :not-found, :or {not-found ":)"}, :as all} my-hashmap]
(println a b not-found all))
;; ;; => A B :) {:a A :b B :c C :d D}
;;
(def sm (sorted-map
"Bravo" 204
"Alfa" 35
"Sigma" 99
"Charlie" 100))
;;{"Alfa" 35, "Bravo" 204, "Charlie" 100, "Sigma" 99}
| 102720 | (ns clj-notes.collections)
;; 数据结构是编程中最重要的部分,clojure提供了丰富的集合类型,同时做到了抽象统一
;; “It is better to have 100 functions operate on one data structure than
;; 10 functions on 10 data structures.” —<NAME>
;; 序列(sequence) 是clojure中重要的概念,表示一个逻辑list,抽象为ISeq接口。
;; 序列clojure.lang.ISeq包含重要方法:
;; (first coll),(next coll),(cons item seq), (rest coll),(more coll), equiv,count, empty, seq方法
(def coll []) ;; vector
(let [s (seq coll)]
(if s
(comment "work on (first s) and recur on (rest s)")
(comment "all done - terminate")))
;; 可以生成序列的结构称为 Seqable
;; ======start
;; 几乎一切数据结构在clojure中都是序列,这些数据结构包括:
;; All iterable types (types that implement java.util.Iterable)
;; Java collections (java.util.Set, java.util.List, etc)
;; Java arrays
;; Java maps
;; All types that implement java.lang.CharSequence interface, including Java strings
;; nil
;; clojure.lang.ISeq - the sequence abstraction interface,更常用的是clojure.lang.ASeq,clojure.lang.LazySeq
;; clojure.lang.Seqable - seqable marker,只有一个方法:ISeq seq()
;; clojure.lang.Sequential - 遍历顺序和初始化顺序一致,Lists, vectors, and effectively all seqs are sequential.
;; ======end
;; Sequence functions (map, filter, etc) 会隐式call seq on the incoming (seqable) collection and
;; return a sequence (possibly empty, not nil)
;; 大部分情况下,开发者使用的都是map和seq两种数据结构,map有时也是当作seq来处理
;; clojure中4大数据结构,list是直接实现ISeq接口,而set,vector,map实现的是Seqable接口
;; ====== seq和sequence方法区别,sequence always return () when false
(seq nil) ;; => nil
(sequence nil) ;; => ()
(seq ()) ;; => nil
(sequence ()) ;; => ()
;; 创建seq的函数
;; range,repeat,iterate,cycle,interleave(交错取值),interpose(给序列插入一个间隔值)
;; 关于seq的全部方法,参考官方ref:https://clojure.org/reference/sequences
;; vector map list set四大数据结构
;; vector是arraylist,可以通过索引访问
;; literal
([1 2 3 5])
(vector 1 2 3)
(get ["abc" false 99] 0)
(conj [1 2 3] 4 5 6)
;; list是linked list,只能通过遍历或者first/rest/nth
(def cards '(10 :ace :jack 9))
;; literal list, 这里需要使用quote是因为clojure的语法就是list,不quote的话,会被认为是一个表达式,执行后发现第一个参数不是方法,抛异常
'(1 2 3)
;; same as follow:
(list 1 2 3)
;; set
(def players #{"<NAME>", "<NAME>", "<NAME>"})
;; map
(def scores {"<NAME>" 1400
"<NAME>" 1240
"<NAME>" 1024})
(assoc scores "<NAME>" 0) ;;associate
(dissoc scores "<NAME>") ;;dissociate
(get scores "<NAME>")
(contains? scores "<NAME>")
(keys scores)
(def players #{"<NAME>" "<NAME>" "<NAME>"})
(zipmap players (repeat 0))
;; with map and into
(into {} (map (fn [p layer] [players 0]) players))
;; with reduce
(reduce (fn [m player]
(assoc m player 0))
{} ; initial value
players)
;; when key is keyword, the keyword can be function
(def stu {:name "bob" :age 10})
(:name stu) ;;=> "bob"
;; map destructuring
(def my-hashmap {:a "A" :b "B" :c "C" :d "D"})
(def my-nested-hashmap {:a "A" :b "B" :c "C" :d "D" :q {:x "X" :y "Y" :z "Z"}})
(let [{a :a d :d} my-hashmap]
(println a d))
;; ;; => A D
(let [{a :a, b :b, {x :x, y :y} :q} my-nested-hashmap]
(println a b x y))
;; ;; => A B X Y
(let [{a :a, b :b, not-found :not-found, :or {not-found ":)"}, :as all} my-hashmap]
(println a b not-found all))
;; ;; => A B :) {:a A :b B :c C :d D}
;;
(def sm (sorted-map
"Bravo" 204
"<NAME>" 35
"Sigma" 99
"<NAME>lie" 100))
;;{"<NAME>" 35, "<NAME>" 204, "<NAME>" 100, "Sigma" 99}
| true | (ns clj-notes.collections)
;; 数据结构是编程中最重要的部分,clojure提供了丰富的集合类型,同时做到了抽象统一
;; “It is better to have 100 functions operate on one data structure than
;; 10 functions on 10 data structures.” —PI:NAME:<NAME>END_PI
;; 序列(sequence) 是clojure中重要的概念,表示一个逻辑list,抽象为ISeq接口。
;; 序列clojure.lang.ISeq包含重要方法:
;; (first coll),(next coll),(cons item seq), (rest coll),(more coll), equiv,count, empty, seq方法
(def coll []) ;; vector
(let [s (seq coll)]
(if s
(comment "work on (first s) and recur on (rest s)")
(comment "all done - terminate")))
;; 可以生成序列的结构称为 Seqable
;; ======start
;; 几乎一切数据结构在clojure中都是序列,这些数据结构包括:
;; All iterable types (types that implement java.util.Iterable)
;; Java collections (java.util.Set, java.util.List, etc)
;; Java arrays
;; Java maps
;; All types that implement java.lang.CharSequence interface, including Java strings
;; nil
;; clojure.lang.ISeq - the sequence abstraction interface,更常用的是clojure.lang.ASeq,clojure.lang.LazySeq
;; clojure.lang.Seqable - seqable marker,只有一个方法:ISeq seq()
;; clojure.lang.Sequential - 遍历顺序和初始化顺序一致,Lists, vectors, and effectively all seqs are sequential.
;; ======end
;; Sequence functions (map, filter, etc) 会隐式call seq on the incoming (seqable) collection and
;; return a sequence (possibly empty, not nil)
;; 大部分情况下,开发者使用的都是map和seq两种数据结构,map有时也是当作seq来处理
;; clojure中4大数据结构,list是直接实现ISeq接口,而set,vector,map实现的是Seqable接口
;; ====== seq和sequence方法区别,sequence always return () when false
(seq nil) ;; => nil
(sequence nil) ;; => ()
(seq ()) ;; => nil
(sequence ()) ;; => ()
;; 创建seq的函数
;; range,repeat,iterate,cycle,interleave(交错取值),interpose(给序列插入一个间隔值)
;; 关于seq的全部方法,参考官方ref:https://clojure.org/reference/sequences
;; vector map list set四大数据结构
;; vector是arraylist,可以通过索引访问
;; literal
([1 2 3 5])
(vector 1 2 3)
(get ["abc" false 99] 0)
(conj [1 2 3] 4 5 6)
;; list是linked list,只能通过遍历或者first/rest/nth
(def cards '(10 :ace :jack 9))
;; literal list, 这里需要使用quote是因为clojure的语法就是list,不quote的话,会被认为是一个表达式,执行后发现第一个参数不是方法,抛异常
'(1 2 3)
;; same as follow:
(list 1 2 3)
;; set
(def players #{"PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"})
;; map
(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) ;;associate
(dissoc scores "PI:NAME:<NAME>END_PI") ;;dissociate
(get scores "PI:NAME:<NAME>END_PI")
(contains? scores "PI:NAME:<NAME>END_PI")
(keys scores)
(def players #{"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"})
(zipmap players (repeat 0))
;; with map and into
(into {} (map (fn [p layer] [players 0]) players))
;; with reduce
(reduce (fn [m player]
(assoc m player 0))
{} ; initial value
players)
;; when key is keyword, the keyword can be function
(def stu {:name "bob" :age 10})
(:name stu) ;;=> "bob"
;; map destructuring
(def my-hashmap {:a "A" :b "B" :c "C" :d "D"})
(def my-nested-hashmap {:a "A" :b "B" :c "C" :d "D" :q {:x "X" :y "Y" :z "Z"}})
(let [{a :a d :d} my-hashmap]
(println a d))
;; ;; => A D
(let [{a :a, b :b, {x :x, y :y} :q} my-nested-hashmap]
(println a b x y))
;; ;; => A B X Y
(let [{a :a, b :b, not-found :not-found, :or {not-found ":)"}, :as all} my-hashmap]
(println a b not-found all))
;; ;; => A B :) {:a A :b B :c C :d D}
;;
(def sm (sorted-map
"Bravo" 204
"PI:NAME:<NAME>END_PI" 35
"Sigma" 99
"PI:NAME:<NAME>END_PIlie" 100))
;;{"PI:NAME:<NAME>END_PI" 35, "PI:NAME:<NAME>END_PI" 204, "PI:NAME:<NAME>END_PI" 100, "Sigma" 99}
|
[
{
"context": "deftest indices\n (let [data1 {:id 1 :first-name \"Aardvark\" :last-name \"Aardvarkov\"}\n data2 {:id 2 :f",
"end": 9041,
"score": 0.9998430013656616,
"start": 9033,
"tag": "NAME",
"value": "Aardvark"
},
{
"context": " [data1 {:id 1 :first-name \"Aardvark\" :last-name \"Aardvarkov\"}\n data2 {:id 2 :first-name \"Baran\" :last-",
"end": 9065,
"score": 0.9998223781585693,
"start": 9055,
"tag": "NAME",
"value": "Aardvarkov"
},
{
"context": "e \"Aardvarkov\"}\n data2 {:id 2 :first-name \"Baran\" :last-name \"Baranovich\"}\n data3 {:id 3 :f",
"end": 9107,
"score": 0.999830961227417,
"start": 9102,
"tag": "NAME",
"value": "Baran"
},
{
"context": " data2 {:id 2 :first-name \"Baran\" :last-name \"Baranovich\"}\n data3 {:id 3 :first-name \"Beleg\" :last-",
"end": 9131,
"score": 0.9998109936714172,
"start": 9121,
"tag": "NAME",
"value": "Baranovich"
},
{
"context": "e \"Baranovich\"}\n data3 {:id 3 :first-name \"Beleg\" :last-name \"Cuthalion\"}]\n (with-db-sec [idx1 ",
"end": 9173,
"score": 0.9998434782028198,
"start": 9168,
"tag": "NAME",
"value": "Beleg"
},
{
"context": " data3 {:id 3 :first-name \"Beleg\" :last-name \"Cuthalion\"}]\n (with-db-sec [idx1 *db-env* *db* \"idx1\" :a",
"end": 9196,
"score": 0.9997294545173645,
"start": 9187,
"tag": "NAME",
"value": "Cuthalion"
},
{
"context": "t index-cursors\n (let [data1 {:id 1 :first-name \"Aardvark\" :last-name \"Aardvarkov\"}\n data2 {:id 2 :f",
"end": 9718,
"score": 0.9998482465744019,
"start": 9710,
"tag": "NAME",
"value": "Aardvark"
},
{
"context": " [data1 {:id 1 :first-name \"Aardvark\" :last-name \"Aardvarkov\"}\n data2 {:id 2 :first-name \"Baran\" :last-",
"end": 9742,
"score": 0.9998199939727783,
"start": 9732,
"tag": "NAME",
"value": "Aardvarkov"
},
{
"context": "e \"Aardvarkov\"}\n data2 {:id 2 :first-name \"Baran\" :last-name \"Baranovich\"}\n data3 {:id 3 :f",
"end": 9784,
"score": 0.999841570854187,
"start": 9779,
"tag": "NAME",
"value": "Baran"
},
{
"context": " data2 {:id 2 :first-name \"Baran\" :last-name \"Baranovich\"}\n data3 {:id 3 :first-name \"Beleg\" :last-",
"end": 9808,
"score": 0.9998243451118469,
"start": 9798,
"tag": "NAME",
"value": "Baranovich"
},
{
"context": "e \"Baranovich\"}\n data3 {:id 3 :first-name \"Beleg\" :last-name \"Cuthalion\"}]\n (with-db-sec [idx1 ",
"end": 9850,
"score": 0.9998366236686707,
"start": 9845,
"tag": "NAME",
"value": "Beleg"
},
{
"context": " data3 {:id 3 :first-name \"Beleg\" :last-name \"Cuthalion\"}]\n (with-db-sec [idx1 *db-env* *db* \"idx1\" :a",
"end": 9873,
"score": 0.9997119903564453,
"start": 9864,
"tag": "NAME",
"value": "Cuthalion"
},
{
"context": "nality\n (db-put db 1 {:login \"gw\" :name \"George Washington\"})\n (db-put db 2 {:login \"ja\" :name \"Joh",
"end": 15811,
"score": 0.9969422817230225,
"start": 15794,
"tag": "NAME",
"value": "George Washington"
},
{
"context": "ton\"})\n (db-put db 2 {:login \"ja\" :name \"John Adams\"})\n (db-put db 3 {:login \"tj\" :name \"Tho",
"end": 15868,
"score": 0.9997889995574951,
"start": 15858,
"tag": "NAME",
"value": "John Adams"
},
{
"context": "ams\"})\n (db-put db 3 {:login \"tj\" :name \"Thomas Jefferson\"})\n (db-put db 4 {:login \"jm\" :name \"Jam",
"end": 15931,
"score": 0.9997360110282898,
"start": 15915,
"tag": "NAME",
"value": "Thomas Jefferson"
},
{
"context": "son\"})\n (db-put db 4 {:login \"jm\" :name \"James Madison\"})\n (with-db-txn [txn4 e]\n (w",
"end": 15991,
"score": 0.9998095035552979,
"start": 15978,
"tag": "NAME",
"value": "James Madison"
},
{
"context": " (is (= (db-get db 2) [2 {:login \"ja\" :name \"John Adams\"}]))\n (is (= (db-get db 4) [4 {:login \"j",
"end": 16329,
"score": 0.9997972846031189,
"start": 16319,
"tag": "NAME",
"value": "John Adams"
},
{
"context": " (is (= (db-get db 4) [4 {:login \"jm\" :name \"James Madison\"}]))\n (with-db-txn [txn5 e]\n ",
"end": 16402,
"score": 0.9997252821922302,
"start": 16389,
"tag": "NAME",
"value": "James Madison"
}
] | test/test/cupboard/bdb/je.clj | gcv/cupboard | 16 | (ns test.cupboard.bdb.je
(:use [clojure test])
(:use cupboard.utils cupboard.bdb.je)
(:import [com.sleepycat.je OperationStatus DatabaseException]))
;;; ----------------------------------------------------------------------------
;;; fixtures
;;; ----------------------------------------------------------------------------
(declare ^:dynamic *db-path* ^:dynamic *db-env* ^:dynamic *db*)
(defn fixture-db-path [f]
(binding [*db-path* (.getAbsolutePath (make-temp-dir))]
(f)
(rmdir-recursive *db-path*)))
(defn fixture-db-env [f]
(binding [*db-env* (db-env-open *db-path* :allow-create true)]
(f)
(db-env-close *db-env*)))
(defn fixture-db [f]
(binding [*db* (db-open *db-env* "db" :allow-create true)]
(f)
(db-close *db*)))
(use-fixtures :each fixture-db-path fixture-db-env fixture-db)
;;; ----------------------------------------------------------------------------
;;; tests
;;; ----------------------------------------------------------------------------
(deftest basic-db-open-close
(let [path (make-temp-dir)]
(try
(let [e (db-env-open path :allow-create true :transactional true)
db (db-open e "db" :allow-create true)
idx1 (db-sec-open e db "idx1" :allow-create true :key-creator-fn :idx1)
idx2 (db-sec-open e db "idx2" :allow-create true :key-creator-fn :idx2)
txn1 (db-txn-begin e)
txn2 (db-txn-begin e)
cur1 (db-cursor-open idx1)
cur2 (db-cursor-open idx2)
jcur1 (db-join-cursor-open [cur1 cur2])]
(is (not (nil? @(jcur1 :join-cursor-handle))))
(db-join-cursor-close jcur1)
(is (nil? @(jcur1 :join-cursor-handle)))
(is (not (nil? @(cur2 :cursor-handle))))
(db-cursor-close cur2)
(is (nil? @(cur2 :cursor-handle)))
(is (not (nil? @(cur1 :cursor-handle))))
(db-cursor-close cur1)
(is (nil? @(cur1 :cursor-handle)))
(is (not (nil? @(txn2 :txn-handle))))
(db-txn-commit txn2)
(is (nil? @(txn2 :txn-handle)))
(is (not (nil? @(txn1 :txn-handle))))
(db-txn-abort txn1)
(is (nil? @(txn1 :txn-handle)))
(is (not (nil? @(idx2 :db-sec-handle))))
(db-sec-close idx2)
(is (nil? @(idx2 :db-sec-handle)))
(is (not (nil? @(idx1 :db-sec-handle))))
(db-sec-close idx1)
(is (nil? @(idx1 :db-sec-handle)))
(is (not (nil? @(db :db-handle))))
(db-close db)
(is (nil? @(db :db-handle)))
(is (not (nil? @(e :env-handle))))
(db-env-close e)
(is (nil? @(e :env-handle))))
(finally
(rmdir-recursive path)))))
(deftest db-operations
(is (thrown? DatabaseException (db-open *db-env* "not here" :allow-create false)))
(with-db [db *db-env* "newly created" :allow-create true])
(with-db [db *db-env* "newly created" :allow-create false]
(is (zero? (db-count db))))
(db-env-rename-db *db-env* "newly created" "my-db")
(with-db [db *db-env* "my-db" :allow-create false]
(is (zero? (db-count db)))
(db-put db "one" 1)
(db-put db "two" 2)
(is (= (db-count db) 2)))
(is (= (db-env-truncate-db *db-env* "my-db" :count true) 2))
(db-env-remove-db *db-env* "my-db")
(is (thrown? DatabaseException (db-open *db-env* "my-db" :allow-create false)))
;; test statistics (doesn't check for validity, just makes sure the code runs)
(let [stats (db-env-stats *db-env*
:n-cache-bytes true
:n-cache-misses true
:n-fsyncs true
:n-random-reads true
:n-random-writes true
:n-seq-reads true
:n-seq-writes true
:n-total-log-bytes true
:n-txn-active true
:n-txn-begins true
:n-txn-aborts true
:n-txn-commits true
:n-lock-owners true
:n-read-locks true
:n-total-locks true
:n-lock-waiting-txns true
:n-write-locks true
:n-lock-requests true
:n-lock-waits true)]
(is (every? identity (map #(contains? stats %)
[:n-cache-bytes :n-cache-misses :n-fsyncs
:n-random-reads :n-random-writes :n-seq-reads
:n-seq-writes :n-total-log-bytes :n-txn-active
:n-txn-begins :n-txn-aborts :n-txn-commits
:n-lock-owners :n-read-locks :n-total-locks
:n-lock-waiting-txns :n-write-locks :n-lock-requests
:n-lock-waits])))))
(deftest basics
(db-put *db* "one" 1)
(is (= (db-get *db* "one") ["one" 1]))
(dotimes [i 100] (db-put *db* (str i) i))
(is (= (db-get *db* "50") ["50" 50]))
(is (empty? (db-get *db* "not there")))
(db-delete *db* "one")
(is (empty? (db-get *db* "one"))))
(deftest types
(let [now (java.util.Date.)
uuid (java.util.UUID/randomUUID)]
(db-put *db* "nil" nil)
(db-put *db* "boolean" true)
(db-put *db* "char" \c)
(db-put *db* "byte" (byte 1))
(db-put *db* "short" (short 1))
(db-put *db* "int" (int 1))
(db-put *db* "long" (long 1))
(db-put *db* "bigint" (bigint 1))
(db-put *db* "ratio" (/ 1 2))
(db-put *db* "double" 1.0)
(db-put *db* "string" "hello world")
(db-put *db* "date" now)
(db-put *db* "uuid" uuid)
(db-put *db* "keyword" :one)
(db-put *db* "symbol" 'one)
(db-put *db* "list" (list 1 2 3))
(db-put *db* "vector" [1 2 3])
(db-put *db* "map" {:one 1 :two 2 :three 3})
(db-put *db* "set" #{:one 2 'three})
(is (= (db-get *db* "nil") ["nil" nil]))
(is (= (db-get *db* "boolean") ["boolean" true]))
(is (= (db-get *db* "char") ["char" \c]))
(is (= (db-get *db* "byte") ["byte" (byte 1)]))
(is (= (db-get *db* "short") ["short" (short 1)]))
(is (= (db-get *db* "int") ["int" (int 1)]))
(is (= (db-get *db* "long") ["long" (long 1)]))
(is (= (db-get *db* "bigint") ["bigint" (bigint 1)]))
(is (= (db-get *db* "ratio") ["ratio" (/ 1 2)]))
(is (= (db-get *db* "double") ["double" 1.0]))
(is (= (db-get *db* "string") ["string" "hello world"]))
(is (= (db-get *db* "date") ["date" now]))
(is (= (db-get *db* "uuid") ["uuid" uuid]))
(is (= (db-get *db* "keyword") ["keyword" :one]))
(is (= (db-get *db* "symbol") ["symbol" 'one]))
(is (= (db-get *db* "list") ["list" (list 1 2 3)]))
(is (= (db-get *db* "vector") ["vector" [1 2 3]]))
(is (= (db-get *db* "map") ["map" {:one 1 :two 2 :three 3}]))
(is (= (db-get *db* "set") ["set" #{:one 2 'three}]))))
(deftest duplicates
(is (= (db-put *db* "a" 1) OperationStatus/SUCCESS))
(is (= (db-put *db* "a" 1 :no-overwrite true) OperationStatus/KEYEXIST))
(with-db [db *db-env* "db2" :allow-create true :sorted-duplicates true]
(is (= (db-put db "a" 1) OperationStatus/SUCCESS))
(is (= (db-put db "b" 2) OperationStatus/SUCCESS))
(is (= (db-put db "a" 3) OperationStatus/SUCCESS))
(is (= (db-put db "b" 2 :no-dup-data true) OperationStatus/KEYEXIST))
(is (= (db-put db "b" 4 :no-overwrite true) OperationStatus/KEYEXIST))
(with-db-cursor [cur1 db]
(is (= (db-cursor-search cur1 "a" :data 3 :search-both true) ["a" 3]))
(is (= (db-cursor-search cur1 "a") ["a" 1]))))
(db-env-remove-db *db-env* "db2"))
(deftest cursors
(let [data1 #{:one 1 :two 2 :three "three" :four "five six seven eight"}
data2 "hello world"
data3 3.3
data4 [4]
data5 {:one 1 :two 2}]
(db-put *db* "a" data1)
(db-put *db* "b" data2)
(db-put *db* "c" data3)
(db-put *db* "d" data4)
(with-db-cursor [cur1 *db*]
(is (= (db-cursor-search cur1 "a") ["a" data1]))
(is (= (db-cursor-next cur1) ["b" data2]))
(is (= (db-cursor-next cur1) ["c" data3]))
(is (= (db-cursor-next cur1 :direction :back) ["b" data2]))
(db-cursor-put cur1 "e" data5)
(is (= (db-cursor-next cur1 :direction :back) ["d" data4]))
(is (= (db-cursor-next cur1 :direction :forward) ["e" data5]))
(db-cursor-delete cur1)
(is (= (db-cursor-next cur1 :direction :back) ["d" data4]))
(is (empty? (db-cursor-next cur1 :direction :forward)))
(db-cursor-put cur1 "e" data5)
(db-cursor-replace cur1 data1)
(db-cursor-next cur1 :direction :back)
(is (= (db-cursor-next cur1 :direction :forward) ["e" data1]))
(is (= (db-cursor-current cur1) ["e" data1]))
(is (= (db-cursor-first cur1) ["a" data1]))
(is (= (db-cursor-last cur1) ["e" data1]))
(is (= (db-cursor-search cur1 "a" :data data1 :search-both true) ["a" data1])))))
(deftest indices
(let [data1 {:id 1 :first-name "Aardvark" :last-name "Aardvarkov"}
data2 {:id 2 :first-name "Baran" :last-name "Baranovich"}
data3 {:id 3 :first-name "Beleg" :last-name "Cuthalion"}]
(with-db-sec [idx1 *db-env* *db* "idx1" :allow-create true :key-creator-fn :last-name]
(db-put *db* 1 data1)
(db-put *db* 2 data2)
(db-put *db* 3 data3)
(is (= (db-get *db* 1) [1 data1]))
(is (= (db-sec-get idx1 "Cuthalion") [3 data3]))
(is (empty? (db-sec-get idx1 "Balkonsky")))
(db-sec-delete idx1 "Baranovich")
(is (empty? (db-get *db* 2)))
(is (empty? (db-sec-get idx1 "Baranovich"))))))
(deftest index-cursors
(let [data1 {:id 1 :first-name "Aardvark" :last-name "Aardvarkov"}
data2 {:id 2 :first-name "Baran" :last-name "Baranovich"}
data3 {:id 3 :first-name "Beleg" :last-name "Cuthalion"}]
(with-db-sec [idx1 *db-env* *db* "idx1" :allow-create true :key-creator-fn :last-name]
(db-put *db* 1 data1)
(db-put *db* 2 data2)
(db-put *db* 3 data3)
(with-db-cursor [cur1 idx1]
(is (= (db-cursor-search cur1 "Baran") [2 data2]))
(is (= (db-cursor-next cur1) [3 data3]))))))
(deftest joins
(let [car-1 {:marque "BMW" :model "X3" :year 2006 :color "blue" :awd true}
car-2 {:marque "Audi" :model "TT" :year 2002 :color "blue" :awd true}
car-3 {:marque "Audi" :model "allroad" :year 2002 :color "grey" :awd true}
car-4 {:marque "Audi" :model "A6 Avant" :year 2006 :color "white" :awd true}
car-5 {:marque "Audi" :model "Q5" :year 2010 :color "white" :awd true}
car-6 {:marque "Ford" :model "Taurus" :year 1996 :color "beige" :awd false}
car-7 {:marque "BMW" :model "330i" :year 2003 :color "blue" :awd false}
car-8 {:marque "Eagle" :model "Summit" :year 1994 :color "blue" :awd false}
car-9 {:marque "Audi" :model "A4" :year 2003 :color "blue" :awd false}]
(with-db-sec [idx-color *db-env* *db* "idx-color"
:allow-create true :sorted-duplicates true
:key-creator-fn :color]
(with-db-sec [idx-year *db-env* *db* "idx-year"
:allow-create true :sorted-duplicates true
:key-creator-fn :year]
(with-db-sec [idx-awd *db-env* *db* "idx-awd"
:allow-create true :sorted-duplicates true
:key-creator-fn :awd]
(db-put *db* 1 car-1)
(db-put *db* 2 car-2)
(db-put *db* 3 car-3)
(db-put *db* 4 car-4)
(db-put *db* 5 car-5)
(db-put *db* 6 car-6)
(db-put *db* 7 car-7)
(db-put *db* 8 car-8)
(db-put *db* 9 car-9)
(with-db-cursor [c1 idx-year]
(with-db-cursor [c2 idx-color]
(is (= (db-cursor-search c1 2003) [7 car-7]))
(is (= (db-cursor-search c2 "blue") [1 car-1]))
(with-db-join-cursor [j [c1 c2]]
(is (= (db-join-cursor-next j) [7 car-7]))
(is (= (db-join-cursor-next j) [9 car-9]))
(is (empty? (db-join-cursor-next j)))))))))))
(deftest cursor-scans-1
(with-db-sec [idx1 *db-env* *db* "idx1"
:allow-create true
:key-creator-fn :a
:sorted-duplicates true]
;; (1 2 3 3 3 5 5 7 nil 11 12)
(db-put *db* 1 {:a 1})
(db-put *db* 2 {:a 2})
(db-put *db* 3 {:a 3})
(db-put *db* 4 {:a 3})
(db-put *db* 5 {:a 3})
(db-put *db* 6 {:a 5})
(db-put *db* 7 {:a 5})
(db-put *db* 8 {:a 7})
(db-put *db* 11 {:a 11})
(db-put *db* 12 {:a 12})
(with-db-cursor [cur1 idx1]
(is (= (db-cursor-scan cur1 1)
[ [1 {:a 1}] ]))
(is (= (db-cursor-scan cur1 3)
[ [3 {:a 3}] [4 {:a 3}] [5 {:a 3}] ]))
(is (empty? (db-cursor-scan cur1 6)))
(is (= (db-cursor-scan cur1 4 :comparison-fn <)
[ [5 {:a 3}] [4 {:a 3}] [3 {:a 3}] [2 {:a 2}] [1 {:a 1}] ]))
(is (= (db-cursor-scan cur1 5 :comparison-fn <=)
[ [6 {:a 5}] [5 {:a 3}] [4 {:a 3}] [3 {:a 3}] [2 {:a 2}] [1 {:a 1}] ]))
(is (= (db-cursor-scan cur1 4 :comparison-fn >)
[ [6 {:a 5}] [7 {:a 5}] [8 {:a 7}] [11 {:a 11}] [12 {:a 12}] ]))
(is (= (db-cursor-scan cur1 2 :comparison-fn >)
[ [3 {:a 3}] [4 {:a 3}] [5 {:a 3}] [6 {:a 5}] [7 {:a 5}]
[8 {:a 7}] [11 {:a 11}] [12 {:a 12}] ]))
(is (= (take 2 (db-cursor-scan cur1 2 :comparison-fn >=))
[ [2 {:a 2}] [3 {:a 3}] ])))
(with-db-cursor [cur2 *db*]
(is (= (db-cursor-scan cur2 4) [ [4 {:a 3}] ]))
(is (empty? (db-cursor-scan cur2 10)))
(is (= (db-cursor-scan cur2 10 :comparison-fn < :direction :back)
[ [8 {:a 7}] [7 {:a 5}] [6 {:a 5}] [5 {:a 3}] [4 {:a 3}]
[3 {:a 3}] [2 {:a 2}] [1 {:a 1}] ]))
(is (= (db-cursor-scan cur2 10 :comparison-fn >)
[ [11 {:a 11}] [12 {:a 12}] ]))
(is (= (db-cursor-scan cur2 11 :comparison-fn >=)
[ [11 {:a 11}] [12 {:a 12}] ]))
(is (= (db-cursor-scan cur2 11 :comparison-fn >)
[ [12 {:a 12}] ])))))
(deftest cursor-scans-2
(with-db-sec [idx1 *db-env* *db* "idx1"
:allow-create true
:key-creator-fn :a
:sorted-duplicates true]
(db-put *db* 1 {:a "abc123"})
(db-put *db* 2 {:a "def456"})
(db-put *db* 3 {:a "def789"})
(db-put *db* 4 {:a "ghi789"})
(with-db-cursor [cur1 idx1]
(is (= (db-cursor-scan cur1 "def" :comparison-fn starts-with)
[ [2 {:a "def456"}] [3 {:a "def789"}] ])))))
(deftest transactions
(let [path (make-temp-dir)]
(with-db-env [e path :allow-create true :transactional true]
(with-db [db e "db" :allow-create true]
(with-db-sec [idx1 e db "idx1" :key-creator-fn :login :allow-create true]
;; basic transactionality tests
(db-put db "one" 1)
(with-db-txn [txn1 e]
(db-put db "two" 2 :txn txn1)
(db-put db "three" 3 :txn txn1))
(is (= (db-get db "one") ["one" 1]))
(is (= (db-get db "two") ["two" 2]))
(is (= (db-get db "three") ["three" 3]))
(with-db-txn [txn2 e]
(db-put db "four" 4 :txn txn2)
(db-put db "five" 5 :txn txn2)
(db-txn-abort txn2))
(is (empty? (db-get db "four")))
(is (empty? (db-get db "five")))
(with-db-txn [txn3 e]
(db-put db "six" 6)
(db-put db "seven" 7 :txn txn3)
(db-txn-abort txn3))
(is (= (db-get db "six") ["six" 6]))
(is (empty? (db-get db "seven")))
;; tests for secondary database transactionality
(db-put db 1 {:login "gw" :name "George Washington"})
(db-put db 2 {:login "ja" :name "John Adams"})
(db-put db 3 {:login "tj" :name "Thomas Jefferson"})
(db-put db 4 {:login "jm" :name "James Madison"})
(with-db-txn [txn4 e]
(with-db-cursor [cur1 idx1 :txn txn4]
(db-cursor-search cur1 "j")
(db-cursor-delete cur1)
(db-cursor-next cur1)
(db-cursor-delete cur1))
(db-txn-abort txn4))
(is (= (db-get db 2) [2 {:login "ja" :name "John Adams"}]))
(is (= (db-get db 4) [4 {:login "jm" :name "James Madison"}]))
(with-db-txn [txn5 e]
(with-db-cursor [cur2 idx1 :txn txn5]
(db-cursor-search cur2 "j")
(db-cursor-delete cur2)
(db-cursor-next cur2)
(db-cursor-delete cur2)))
(is (empty? (db-get db 2)))
(is (empty? (db-get db 4))))))
(rmdir-recursive path)))
| 75239 | (ns test.cupboard.bdb.je
(:use [clojure test])
(:use cupboard.utils cupboard.bdb.je)
(:import [com.sleepycat.je OperationStatus DatabaseException]))
;;; ----------------------------------------------------------------------------
;;; fixtures
;;; ----------------------------------------------------------------------------
(declare ^:dynamic *db-path* ^:dynamic *db-env* ^:dynamic *db*)
(defn fixture-db-path [f]
(binding [*db-path* (.getAbsolutePath (make-temp-dir))]
(f)
(rmdir-recursive *db-path*)))
(defn fixture-db-env [f]
(binding [*db-env* (db-env-open *db-path* :allow-create true)]
(f)
(db-env-close *db-env*)))
(defn fixture-db [f]
(binding [*db* (db-open *db-env* "db" :allow-create true)]
(f)
(db-close *db*)))
(use-fixtures :each fixture-db-path fixture-db-env fixture-db)
;;; ----------------------------------------------------------------------------
;;; tests
;;; ----------------------------------------------------------------------------
(deftest basic-db-open-close
(let [path (make-temp-dir)]
(try
(let [e (db-env-open path :allow-create true :transactional true)
db (db-open e "db" :allow-create true)
idx1 (db-sec-open e db "idx1" :allow-create true :key-creator-fn :idx1)
idx2 (db-sec-open e db "idx2" :allow-create true :key-creator-fn :idx2)
txn1 (db-txn-begin e)
txn2 (db-txn-begin e)
cur1 (db-cursor-open idx1)
cur2 (db-cursor-open idx2)
jcur1 (db-join-cursor-open [cur1 cur2])]
(is (not (nil? @(jcur1 :join-cursor-handle))))
(db-join-cursor-close jcur1)
(is (nil? @(jcur1 :join-cursor-handle)))
(is (not (nil? @(cur2 :cursor-handle))))
(db-cursor-close cur2)
(is (nil? @(cur2 :cursor-handle)))
(is (not (nil? @(cur1 :cursor-handle))))
(db-cursor-close cur1)
(is (nil? @(cur1 :cursor-handle)))
(is (not (nil? @(txn2 :txn-handle))))
(db-txn-commit txn2)
(is (nil? @(txn2 :txn-handle)))
(is (not (nil? @(txn1 :txn-handle))))
(db-txn-abort txn1)
(is (nil? @(txn1 :txn-handle)))
(is (not (nil? @(idx2 :db-sec-handle))))
(db-sec-close idx2)
(is (nil? @(idx2 :db-sec-handle)))
(is (not (nil? @(idx1 :db-sec-handle))))
(db-sec-close idx1)
(is (nil? @(idx1 :db-sec-handle)))
(is (not (nil? @(db :db-handle))))
(db-close db)
(is (nil? @(db :db-handle)))
(is (not (nil? @(e :env-handle))))
(db-env-close e)
(is (nil? @(e :env-handle))))
(finally
(rmdir-recursive path)))))
(deftest db-operations
(is (thrown? DatabaseException (db-open *db-env* "not here" :allow-create false)))
(with-db [db *db-env* "newly created" :allow-create true])
(with-db [db *db-env* "newly created" :allow-create false]
(is (zero? (db-count db))))
(db-env-rename-db *db-env* "newly created" "my-db")
(with-db [db *db-env* "my-db" :allow-create false]
(is (zero? (db-count db)))
(db-put db "one" 1)
(db-put db "two" 2)
(is (= (db-count db) 2)))
(is (= (db-env-truncate-db *db-env* "my-db" :count true) 2))
(db-env-remove-db *db-env* "my-db")
(is (thrown? DatabaseException (db-open *db-env* "my-db" :allow-create false)))
;; test statistics (doesn't check for validity, just makes sure the code runs)
(let [stats (db-env-stats *db-env*
:n-cache-bytes true
:n-cache-misses true
:n-fsyncs true
:n-random-reads true
:n-random-writes true
:n-seq-reads true
:n-seq-writes true
:n-total-log-bytes true
:n-txn-active true
:n-txn-begins true
:n-txn-aborts true
:n-txn-commits true
:n-lock-owners true
:n-read-locks true
:n-total-locks true
:n-lock-waiting-txns true
:n-write-locks true
:n-lock-requests true
:n-lock-waits true)]
(is (every? identity (map #(contains? stats %)
[:n-cache-bytes :n-cache-misses :n-fsyncs
:n-random-reads :n-random-writes :n-seq-reads
:n-seq-writes :n-total-log-bytes :n-txn-active
:n-txn-begins :n-txn-aborts :n-txn-commits
:n-lock-owners :n-read-locks :n-total-locks
:n-lock-waiting-txns :n-write-locks :n-lock-requests
:n-lock-waits])))))
(deftest basics
(db-put *db* "one" 1)
(is (= (db-get *db* "one") ["one" 1]))
(dotimes [i 100] (db-put *db* (str i) i))
(is (= (db-get *db* "50") ["50" 50]))
(is (empty? (db-get *db* "not there")))
(db-delete *db* "one")
(is (empty? (db-get *db* "one"))))
(deftest types
(let [now (java.util.Date.)
uuid (java.util.UUID/randomUUID)]
(db-put *db* "nil" nil)
(db-put *db* "boolean" true)
(db-put *db* "char" \c)
(db-put *db* "byte" (byte 1))
(db-put *db* "short" (short 1))
(db-put *db* "int" (int 1))
(db-put *db* "long" (long 1))
(db-put *db* "bigint" (bigint 1))
(db-put *db* "ratio" (/ 1 2))
(db-put *db* "double" 1.0)
(db-put *db* "string" "hello world")
(db-put *db* "date" now)
(db-put *db* "uuid" uuid)
(db-put *db* "keyword" :one)
(db-put *db* "symbol" 'one)
(db-put *db* "list" (list 1 2 3))
(db-put *db* "vector" [1 2 3])
(db-put *db* "map" {:one 1 :two 2 :three 3})
(db-put *db* "set" #{:one 2 'three})
(is (= (db-get *db* "nil") ["nil" nil]))
(is (= (db-get *db* "boolean") ["boolean" true]))
(is (= (db-get *db* "char") ["char" \c]))
(is (= (db-get *db* "byte") ["byte" (byte 1)]))
(is (= (db-get *db* "short") ["short" (short 1)]))
(is (= (db-get *db* "int") ["int" (int 1)]))
(is (= (db-get *db* "long") ["long" (long 1)]))
(is (= (db-get *db* "bigint") ["bigint" (bigint 1)]))
(is (= (db-get *db* "ratio") ["ratio" (/ 1 2)]))
(is (= (db-get *db* "double") ["double" 1.0]))
(is (= (db-get *db* "string") ["string" "hello world"]))
(is (= (db-get *db* "date") ["date" now]))
(is (= (db-get *db* "uuid") ["uuid" uuid]))
(is (= (db-get *db* "keyword") ["keyword" :one]))
(is (= (db-get *db* "symbol") ["symbol" 'one]))
(is (= (db-get *db* "list") ["list" (list 1 2 3)]))
(is (= (db-get *db* "vector") ["vector" [1 2 3]]))
(is (= (db-get *db* "map") ["map" {:one 1 :two 2 :three 3}]))
(is (= (db-get *db* "set") ["set" #{:one 2 'three}]))))
(deftest duplicates
(is (= (db-put *db* "a" 1) OperationStatus/SUCCESS))
(is (= (db-put *db* "a" 1 :no-overwrite true) OperationStatus/KEYEXIST))
(with-db [db *db-env* "db2" :allow-create true :sorted-duplicates true]
(is (= (db-put db "a" 1) OperationStatus/SUCCESS))
(is (= (db-put db "b" 2) OperationStatus/SUCCESS))
(is (= (db-put db "a" 3) OperationStatus/SUCCESS))
(is (= (db-put db "b" 2 :no-dup-data true) OperationStatus/KEYEXIST))
(is (= (db-put db "b" 4 :no-overwrite true) OperationStatus/KEYEXIST))
(with-db-cursor [cur1 db]
(is (= (db-cursor-search cur1 "a" :data 3 :search-both true) ["a" 3]))
(is (= (db-cursor-search cur1 "a") ["a" 1]))))
(db-env-remove-db *db-env* "db2"))
(deftest cursors
(let [data1 #{:one 1 :two 2 :three "three" :four "five six seven eight"}
data2 "hello world"
data3 3.3
data4 [4]
data5 {:one 1 :two 2}]
(db-put *db* "a" data1)
(db-put *db* "b" data2)
(db-put *db* "c" data3)
(db-put *db* "d" data4)
(with-db-cursor [cur1 *db*]
(is (= (db-cursor-search cur1 "a") ["a" data1]))
(is (= (db-cursor-next cur1) ["b" data2]))
(is (= (db-cursor-next cur1) ["c" data3]))
(is (= (db-cursor-next cur1 :direction :back) ["b" data2]))
(db-cursor-put cur1 "e" data5)
(is (= (db-cursor-next cur1 :direction :back) ["d" data4]))
(is (= (db-cursor-next cur1 :direction :forward) ["e" data5]))
(db-cursor-delete cur1)
(is (= (db-cursor-next cur1 :direction :back) ["d" data4]))
(is (empty? (db-cursor-next cur1 :direction :forward)))
(db-cursor-put cur1 "e" data5)
(db-cursor-replace cur1 data1)
(db-cursor-next cur1 :direction :back)
(is (= (db-cursor-next cur1 :direction :forward) ["e" data1]))
(is (= (db-cursor-current cur1) ["e" data1]))
(is (= (db-cursor-first cur1) ["a" data1]))
(is (= (db-cursor-last cur1) ["e" data1]))
(is (= (db-cursor-search cur1 "a" :data data1 :search-both true) ["a" data1])))))
(deftest indices
(let [data1 {:id 1 :first-name "<NAME>" :last-name "<NAME>"}
data2 {:id 2 :first-name "<NAME>" :last-name "<NAME>"}
data3 {:id 3 :first-name "<NAME>" :last-name "<NAME>"}]
(with-db-sec [idx1 *db-env* *db* "idx1" :allow-create true :key-creator-fn :last-name]
(db-put *db* 1 data1)
(db-put *db* 2 data2)
(db-put *db* 3 data3)
(is (= (db-get *db* 1) [1 data1]))
(is (= (db-sec-get idx1 "Cuthalion") [3 data3]))
(is (empty? (db-sec-get idx1 "Balkonsky")))
(db-sec-delete idx1 "Baranovich")
(is (empty? (db-get *db* 2)))
(is (empty? (db-sec-get idx1 "Baranovich"))))))
(deftest index-cursors
(let [data1 {:id 1 :first-name "<NAME>" :last-name "<NAME>"}
data2 {:id 2 :first-name "<NAME>" :last-name "<NAME>"}
data3 {:id 3 :first-name "<NAME>" :last-name "<NAME>"}]
(with-db-sec [idx1 *db-env* *db* "idx1" :allow-create true :key-creator-fn :last-name]
(db-put *db* 1 data1)
(db-put *db* 2 data2)
(db-put *db* 3 data3)
(with-db-cursor [cur1 idx1]
(is (= (db-cursor-search cur1 "Baran") [2 data2]))
(is (= (db-cursor-next cur1) [3 data3]))))))
(deftest joins
(let [car-1 {:marque "BMW" :model "X3" :year 2006 :color "blue" :awd true}
car-2 {:marque "Audi" :model "TT" :year 2002 :color "blue" :awd true}
car-3 {:marque "Audi" :model "allroad" :year 2002 :color "grey" :awd true}
car-4 {:marque "Audi" :model "A6 Avant" :year 2006 :color "white" :awd true}
car-5 {:marque "Audi" :model "Q5" :year 2010 :color "white" :awd true}
car-6 {:marque "Ford" :model "Taurus" :year 1996 :color "beige" :awd false}
car-7 {:marque "BMW" :model "330i" :year 2003 :color "blue" :awd false}
car-8 {:marque "Eagle" :model "Summit" :year 1994 :color "blue" :awd false}
car-9 {:marque "Audi" :model "A4" :year 2003 :color "blue" :awd false}]
(with-db-sec [idx-color *db-env* *db* "idx-color"
:allow-create true :sorted-duplicates true
:key-creator-fn :color]
(with-db-sec [idx-year *db-env* *db* "idx-year"
:allow-create true :sorted-duplicates true
:key-creator-fn :year]
(with-db-sec [idx-awd *db-env* *db* "idx-awd"
:allow-create true :sorted-duplicates true
:key-creator-fn :awd]
(db-put *db* 1 car-1)
(db-put *db* 2 car-2)
(db-put *db* 3 car-3)
(db-put *db* 4 car-4)
(db-put *db* 5 car-5)
(db-put *db* 6 car-6)
(db-put *db* 7 car-7)
(db-put *db* 8 car-8)
(db-put *db* 9 car-9)
(with-db-cursor [c1 idx-year]
(with-db-cursor [c2 idx-color]
(is (= (db-cursor-search c1 2003) [7 car-7]))
(is (= (db-cursor-search c2 "blue") [1 car-1]))
(with-db-join-cursor [j [c1 c2]]
(is (= (db-join-cursor-next j) [7 car-7]))
(is (= (db-join-cursor-next j) [9 car-9]))
(is (empty? (db-join-cursor-next j)))))))))))
(deftest cursor-scans-1
(with-db-sec [idx1 *db-env* *db* "idx1"
:allow-create true
:key-creator-fn :a
:sorted-duplicates true]
;; (1 2 3 3 3 5 5 7 nil 11 12)
(db-put *db* 1 {:a 1})
(db-put *db* 2 {:a 2})
(db-put *db* 3 {:a 3})
(db-put *db* 4 {:a 3})
(db-put *db* 5 {:a 3})
(db-put *db* 6 {:a 5})
(db-put *db* 7 {:a 5})
(db-put *db* 8 {:a 7})
(db-put *db* 11 {:a 11})
(db-put *db* 12 {:a 12})
(with-db-cursor [cur1 idx1]
(is (= (db-cursor-scan cur1 1)
[ [1 {:a 1}] ]))
(is (= (db-cursor-scan cur1 3)
[ [3 {:a 3}] [4 {:a 3}] [5 {:a 3}] ]))
(is (empty? (db-cursor-scan cur1 6)))
(is (= (db-cursor-scan cur1 4 :comparison-fn <)
[ [5 {:a 3}] [4 {:a 3}] [3 {:a 3}] [2 {:a 2}] [1 {:a 1}] ]))
(is (= (db-cursor-scan cur1 5 :comparison-fn <=)
[ [6 {:a 5}] [5 {:a 3}] [4 {:a 3}] [3 {:a 3}] [2 {:a 2}] [1 {:a 1}] ]))
(is (= (db-cursor-scan cur1 4 :comparison-fn >)
[ [6 {:a 5}] [7 {:a 5}] [8 {:a 7}] [11 {:a 11}] [12 {:a 12}] ]))
(is (= (db-cursor-scan cur1 2 :comparison-fn >)
[ [3 {:a 3}] [4 {:a 3}] [5 {:a 3}] [6 {:a 5}] [7 {:a 5}]
[8 {:a 7}] [11 {:a 11}] [12 {:a 12}] ]))
(is (= (take 2 (db-cursor-scan cur1 2 :comparison-fn >=))
[ [2 {:a 2}] [3 {:a 3}] ])))
(with-db-cursor [cur2 *db*]
(is (= (db-cursor-scan cur2 4) [ [4 {:a 3}] ]))
(is (empty? (db-cursor-scan cur2 10)))
(is (= (db-cursor-scan cur2 10 :comparison-fn < :direction :back)
[ [8 {:a 7}] [7 {:a 5}] [6 {:a 5}] [5 {:a 3}] [4 {:a 3}]
[3 {:a 3}] [2 {:a 2}] [1 {:a 1}] ]))
(is (= (db-cursor-scan cur2 10 :comparison-fn >)
[ [11 {:a 11}] [12 {:a 12}] ]))
(is (= (db-cursor-scan cur2 11 :comparison-fn >=)
[ [11 {:a 11}] [12 {:a 12}] ]))
(is (= (db-cursor-scan cur2 11 :comparison-fn >)
[ [12 {:a 12}] ])))))
(deftest cursor-scans-2
(with-db-sec [idx1 *db-env* *db* "idx1"
:allow-create true
:key-creator-fn :a
:sorted-duplicates true]
(db-put *db* 1 {:a "abc123"})
(db-put *db* 2 {:a "def456"})
(db-put *db* 3 {:a "def789"})
(db-put *db* 4 {:a "ghi789"})
(with-db-cursor [cur1 idx1]
(is (= (db-cursor-scan cur1 "def" :comparison-fn starts-with)
[ [2 {:a "def456"}] [3 {:a "def789"}] ])))))
(deftest transactions
(let [path (make-temp-dir)]
(with-db-env [e path :allow-create true :transactional true]
(with-db [db e "db" :allow-create true]
(with-db-sec [idx1 e db "idx1" :key-creator-fn :login :allow-create true]
;; basic transactionality tests
(db-put db "one" 1)
(with-db-txn [txn1 e]
(db-put db "two" 2 :txn txn1)
(db-put db "three" 3 :txn txn1))
(is (= (db-get db "one") ["one" 1]))
(is (= (db-get db "two") ["two" 2]))
(is (= (db-get db "three") ["three" 3]))
(with-db-txn [txn2 e]
(db-put db "four" 4 :txn txn2)
(db-put db "five" 5 :txn txn2)
(db-txn-abort txn2))
(is (empty? (db-get db "four")))
(is (empty? (db-get db "five")))
(with-db-txn [txn3 e]
(db-put db "six" 6)
(db-put db "seven" 7 :txn txn3)
(db-txn-abort txn3))
(is (= (db-get db "six") ["six" 6]))
(is (empty? (db-get db "seven")))
;; tests for secondary database transactionality
(db-put db 1 {:login "gw" :name "<NAME>"})
(db-put db 2 {:login "ja" :name "<NAME>"})
(db-put db 3 {:login "tj" :name "<NAME>"})
(db-put db 4 {:login "jm" :name "<NAME>"})
(with-db-txn [txn4 e]
(with-db-cursor [cur1 idx1 :txn txn4]
(db-cursor-search cur1 "j")
(db-cursor-delete cur1)
(db-cursor-next cur1)
(db-cursor-delete cur1))
(db-txn-abort txn4))
(is (= (db-get db 2) [2 {:login "ja" :name "<NAME>"}]))
(is (= (db-get db 4) [4 {:login "jm" :name "<NAME>"}]))
(with-db-txn [txn5 e]
(with-db-cursor [cur2 idx1 :txn txn5]
(db-cursor-search cur2 "j")
(db-cursor-delete cur2)
(db-cursor-next cur2)
(db-cursor-delete cur2)))
(is (empty? (db-get db 2)))
(is (empty? (db-get db 4))))))
(rmdir-recursive path)))
| true | (ns test.cupboard.bdb.je
(:use [clojure test])
(:use cupboard.utils cupboard.bdb.je)
(:import [com.sleepycat.je OperationStatus DatabaseException]))
;;; ----------------------------------------------------------------------------
;;; fixtures
;;; ----------------------------------------------------------------------------
(declare ^:dynamic *db-path* ^:dynamic *db-env* ^:dynamic *db*)
(defn fixture-db-path [f]
(binding [*db-path* (.getAbsolutePath (make-temp-dir))]
(f)
(rmdir-recursive *db-path*)))
(defn fixture-db-env [f]
(binding [*db-env* (db-env-open *db-path* :allow-create true)]
(f)
(db-env-close *db-env*)))
(defn fixture-db [f]
(binding [*db* (db-open *db-env* "db" :allow-create true)]
(f)
(db-close *db*)))
(use-fixtures :each fixture-db-path fixture-db-env fixture-db)
;;; ----------------------------------------------------------------------------
;;; tests
;;; ----------------------------------------------------------------------------
(deftest basic-db-open-close
(let [path (make-temp-dir)]
(try
(let [e (db-env-open path :allow-create true :transactional true)
db (db-open e "db" :allow-create true)
idx1 (db-sec-open e db "idx1" :allow-create true :key-creator-fn :idx1)
idx2 (db-sec-open e db "idx2" :allow-create true :key-creator-fn :idx2)
txn1 (db-txn-begin e)
txn2 (db-txn-begin e)
cur1 (db-cursor-open idx1)
cur2 (db-cursor-open idx2)
jcur1 (db-join-cursor-open [cur1 cur2])]
(is (not (nil? @(jcur1 :join-cursor-handle))))
(db-join-cursor-close jcur1)
(is (nil? @(jcur1 :join-cursor-handle)))
(is (not (nil? @(cur2 :cursor-handle))))
(db-cursor-close cur2)
(is (nil? @(cur2 :cursor-handle)))
(is (not (nil? @(cur1 :cursor-handle))))
(db-cursor-close cur1)
(is (nil? @(cur1 :cursor-handle)))
(is (not (nil? @(txn2 :txn-handle))))
(db-txn-commit txn2)
(is (nil? @(txn2 :txn-handle)))
(is (not (nil? @(txn1 :txn-handle))))
(db-txn-abort txn1)
(is (nil? @(txn1 :txn-handle)))
(is (not (nil? @(idx2 :db-sec-handle))))
(db-sec-close idx2)
(is (nil? @(idx2 :db-sec-handle)))
(is (not (nil? @(idx1 :db-sec-handle))))
(db-sec-close idx1)
(is (nil? @(idx1 :db-sec-handle)))
(is (not (nil? @(db :db-handle))))
(db-close db)
(is (nil? @(db :db-handle)))
(is (not (nil? @(e :env-handle))))
(db-env-close e)
(is (nil? @(e :env-handle))))
(finally
(rmdir-recursive path)))))
(deftest db-operations
(is (thrown? DatabaseException (db-open *db-env* "not here" :allow-create false)))
(with-db [db *db-env* "newly created" :allow-create true])
(with-db [db *db-env* "newly created" :allow-create false]
(is (zero? (db-count db))))
(db-env-rename-db *db-env* "newly created" "my-db")
(with-db [db *db-env* "my-db" :allow-create false]
(is (zero? (db-count db)))
(db-put db "one" 1)
(db-put db "two" 2)
(is (= (db-count db) 2)))
(is (= (db-env-truncate-db *db-env* "my-db" :count true) 2))
(db-env-remove-db *db-env* "my-db")
(is (thrown? DatabaseException (db-open *db-env* "my-db" :allow-create false)))
;; test statistics (doesn't check for validity, just makes sure the code runs)
(let [stats (db-env-stats *db-env*
:n-cache-bytes true
:n-cache-misses true
:n-fsyncs true
:n-random-reads true
:n-random-writes true
:n-seq-reads true
:n-seq-writes true
:n-total-log-bytes true
:n-txn-active true
:n-txn-begins true
:n-txn-aborts true
:n-txn-commits true
:n-lock-owners true
:n-read-locks true
:n-total-locks true
:n-lock-waiting-txns true
:n-write-locks true
:n-lock-requests true
:n-lock-waits true)]
(is (every? identity (map #(contains? stats %)
[:n-cache-bytes :n-cache-misses :n-fsyncs
:n-random-reads :n-random-writes :n-seq-reads
:n-seq-writes :n-total-log-bytes :n-txn-active
:n-txn-begins :n-txn-aborts :n-txn-commits
:n-lock-owners :n-read-locks :n-total-locks
:n-lock-waiting-txns :n-write-locks :n-lock-requests
:n-lock-waits])))))
(deftest basics
(db-put *db* "one" 1)
(is (= (db-get *db* "one") ["one" 1]))
(dotimes [i 100] (db-put *db* (str i) i))
(is (= (db-get *db* "50") ["50" 50]))
(is (empty? (db-get *db* "not there")))
(db-delete *db* "one")
(is (empty? (db-get *db* "one"))))
(deftest types
(let [now (java.util.Date.)
uuid (java.util.UUID/randomUUID)]
(db-put *db* "nil" nil)
(db-put *db* "boolean" true)
(db-put *db* "char" \c)
(db-put *db* "byte" (byte 1))
(db-put *db* "short" (short 1))
(db-put *db* "int" (int 1))
(db-put *db* "long" (long 1))
(db-put *db* "bigint" (bigint 1))
(db-put *db* "ratio" (/ 1 2))
(db-put *db* "double" 1.0)
(db-put *db* "string" "hello world")
(db-put *db* "date" now)
(db-put *db* "uuid" uuid)
(db-put *db* "keyword" :one)
(db-put *db* "symbol" 'one)
(db-put *db* "list" (list 1 2 3))
(db-put *db* "vector" [1 2 3])
(db-put *db* "map" {:one 1 :two 2 :three 3})
(db-put *db* "set" #{:one 2 'three})
(is (= (db-get *db* "nil") ["nil" nil]))
(is (= (db-get *db* "boolean") ["boolean" true]))
(is (= (db-get *db* "char") ["char" \c]))
(is (= (db-get *db* "byte") ["byte" (byte 1)]))
(is (= (db-get *db* "short") ["short" (short 1)]))
(is (= (db-get *db* "int") ["int" (int 1)]))
(is (= (db-get *db* "long") ["long" (long 1)]))
(is (= (db-get *db* "bigint") ["bigint" (bigint 1)]))
(is (= (db-get *db* "ratio") ["ratio" (/ 1 2)]))
(is (= (db-get *db* "double") ["double" 1.0]))
(is (= (db-get *db* "string") ["string" "hello world"]))
(is (= (db-get *db* "date") ["date" now]))
(is (= (db-get *db* "uuid") ["uuid" uuid]))
(is (= (db-get *db* "keyword") ["keyword" :one]))
(is (= (db-get *db* "symbol") ["symbol" 'one]))
(is (= (db-get *db* "list") ["list" (list 1 2 3)]))
(is (= (db-get *db* "vector") ["vector" [1 2 3]]))
(is (= (db-get *db* "map") ["map" {:one 1 :two 2 :three 3}]))
(is (= (db-get *db* "set") ["set" #{:one 2 'three}]))))
(deftest duplicates
(is (= (db-put *db* "a" 1) OperationStatus/SUCCESS))
(is (= (db-put *db* "a" 1 :no-overwrite true) OperationStatus/KEYEXIST))
(with-db [db *db-env* "db2" :allow-create true :sorted-duplicates true]
(is (= (db-put db "a" 1) OperationStatus/SUCCESS))
(is (= (db-put db "b" 2) OperationStatus/SUCCESS))
(is (= (db-put db "a" 3) OperationStatus/SUCCESS))
(is (= (db-put db "b" 2 :no-dup-data true) OperationStatus/KEYEXIST))
(is (= (db-put db "b" 4 :no-overwrite true) OperationStatus/KEYEXIST))
(with-db-cursor [cur1 db]
(is (= (db-cursor-search cur1 "a" :data 3 :search-both true) ["a" 3]))
(is (= (db-cursor-search cur1 "a") ["a" 1]))))
(db-env-remove-db *db-env* "db2"))
(deftest cursors
(let [data1 #{:one 1 :two 2 :three "three" :four "five six seven eight"}
data2 "hello world"
data3 3.3
data4 [4]
data5 {:one 1 :two 2}]
(db-put *db* "a" data1)
(db-put *db* "b" data2)
(db-put *db* "c" data3)
(db-put *db* "d" data4)
(with-db-cursor [cur1 *db*]
(is (= (db-cursor-search cur1 "a") ["a" data1]))
(is (= (db-cursor-next cur1) ["b" data2]))
(is (= (db-cursor-next cur1) ["c" data3]))
(is (= (db-cursor-next cur1 :direction :back) ["b" data2]))
(db-cursor-put cur1 "e" data5)
(is (= (db-cursor-next cur1 :direction :back) ["d" data4]))
(is (= (db-cursor-next cur1 :direction :forward) ["e" data5]))
(db-cursor-delete cur1)
(is (= (db-cursor-next cur1 :direction :back) ["d" data4]))
(is (empty? (db-cursor-next cur1 :direction :forward)))
(db-cursor-put cur1 "e" data5)
(db-cursor-replace cur1 data1)
(db-cursor-next cur1 :direction :back)
(is (= (db-cursor-next cur1 :direction :forward) ["e" data1]))
(is (= (db-cursor-current cur1) ["e" data1]))
(is (= (db-cursor-first cur1) ["a" data1]))
(is (= (db-cursor-last cur1) ["e" data1]))
(is (= (db-cursor-search cur1 "a" :data data1 :search-both true) ["a" data1])))))
(deftest indices
(let [data1 {:id 1 :first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
data2 {:id 2 :first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
data3 {:id 3 :first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}]
(with-db-sec [idx1 *db-env* *db* "idx1" :allow-create true :key-creator-fn :last-name]
(db-put *db* 1 data1)
(db-put *db* 2 data2)
(db-put *db* 3 data3)
(is (= (db-get *db* 1) [1 data1]))
(is (= (db-sec-get idx1 "Cuthalion") [3 data3]))
(is (empty? (db-sec-get idx1 "Balkonsky")))
(db-sec-delete idx1 "Baranovich")
(is (empty? (db-get *db* 2)))
(is (empty? (db-sec-get idx1 "Baranovich"))))))
(deftest index-cursors
(let [data1 {:id 1 :first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
data2 {:id 2 :first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}
data3 {:id 3 :first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}]
(with-db-sec [idx1 *db-env* *db* "idx1" :allow-create true :key-creator-fn :last-name]
(db-put *db* 1 data1)
(db-put *db* 2 data2)
(db-put *db* 3 data3)
(with-db-cursor [cur1 idx1]
(is (= (db-cursor-search cur1 "Baran") [2 data2]))
(is (= (db-cursor-next cur1) [3 data3]))))))
(deftest joins
(let [car-1 {:marque "BMW" :model "X3" :year 2006 :color "blue" :awd true}
car-2 {:marque "Audi" :model "TT" :year 2002 :color "blue" :awd true}
car-3 {:marque "Audi" :model "allroad" :year 2002 :color "grey" :awd true}
car-4 {:marque "Audi" :model "A6 Avant" :year 2006 :color "white" :awd true}
car-5 {:marque "Audi" :model "Q5" :year 2010 :color "white" :awd true}
car-6 {:marque "Ford" :model "Taurus" :year 1996 :color "beige" :awd false}
car-7 {:marque "BMW" :model "330i" :year 2003 :color "blue" :awd false}
car-8 {:marque "Eagle" :model "Summit" :year 1994 :color "blue" :awd false}
car-9 {:marque "Audi" :model "A4" :year 2003 :color "blue" :awd false}]
(with-db-sec [idx-color *db-env* *db* "idx-color"
:allow-create true :sorted-duplicates true
:key-creator-fn :color]
(with-db-sec [idx-year *db-env* *db* "idx-year"
:allow-create true :sorted-duplicates true
:key-creator-fn :year]
(with-db-sec [idx-awd *db-env* *db* "idx-awd"
:allow-create true :sorted-duplicates true
:key-creator-fn :awd]
(db-put *db* 1 car-1)
(db-put *db* 2 car-2)
(db-put *db* 3 car-3)
(db-put *db* 4 car-4)
(db-put *db* 5 car-5)
(db-put *db* 6 car-6)
(db-put *db* 7 car-7)
(db-put *db* 8 car-8)
(db-put *db* 9 car-9)
(with-db-cursor [c1 idx-year]
(with-db-cursor [c2 idx-color]
(is (= (db-cursor-search c1 2003) [7 car-7]))
(is (= (db-cursor-search c2 "blue") [1 car-1]))
(with-db-join-cursor [j [c1 c2]]
(is (= (db-join-cursor-next j) [7 car-7]))
(is (= (db-join-cursor-next j) [9 car-9]))
(is (empty? (db-join-cursor-next j)))))))))))
(deftest cursor-scans-1
(with-db-sec [idx1 *db-env* *db* "idx1"
:allow-create true
:key-creator-fn :a
:sorted-duplicates true]
;; (1 2 3 3 3 5 5 7 nil 11 12)
(db-put *db* 1 {:a 1})
(db-put *db* 2 {:a 2})
(db-put *db* 3 {:a 3})
(db-put *db* 4 {:a 3})
(db-put *db* 5 {:a 3})
(db-put *db* 6 {:a 5})
(db-put *db* 7 {:a 5})
(db-put *db* 8 {:a 7})
(db-put *db* 11 {:a 11})
(db-put *db* 12 {:a 12})
(with-db-cursor [cur1 idx1]
(is (= (db-cursor-scan cur1 1)
[ [1 {:a 1}] ]))
(is (= (db-cursor-scan cur1 3)
[ [3 {:a 3}] [4 {:a 3}] [5 {:a 3}] ]))
(is (empty? (db-cursor-scan cur1 6)))
(is (= (db-cursor-scan cur1 4 :comparison-fn <)
[ [5 {:a 3}] [4 {:a 3}] [3 {:a 3}] [2 {:a 2}] [1 {:a 1}] ]))
(is (= (db-cursor-scan cur1 5 :comparison-fn <=)
[ [6 {:a 5}] [5 {:a 3}] [4 {:a 3}] [3 {:a 3}] [2 {:a 2}] [1 {:a 1}] ]))
(is (= (db-cursor-scan cur1 4 :comparison-fn >)
[ [6 {:a 5}] [7 {:a 5}] [8 {:a 7}] [11 {:a 11}] [12 {:a 12}] ]))
(is (= (db-cursor-scan cur1 2 :comparison-fn >)
[ [3 {:a 3}] [4 {:a 3}] [5 {:a 3}] [6 {:a 5}] [7 {:a 5}]
[8 {:a 7}] [11 {:a 11}] [12 {:a 12}] ]))
(is (= (take 2 (db-cursor-scan cur1 2 :comparison-fn >=))
[ [2 {:a 2}] [3 {:a 3}] ])))
(with-db-cursor [cur2 *db*]
(is (= (db-cursor-scan cur2 4) [ [4 {:a 3}] ]))
(is (empty? (db-cursor-scan cur2 10)))
(is (= (db-cursor-scan cur2 10 :comparison-fn < :direction :back)
[ [8 {:a 7}] [7 {:a 5}] [6 {:a 5}] [5 {:a 3}] [4 {:a 3}]
[3 {:a 3}] [2 {:a 2}] [1 {:a 1}] ]))
(is (= (db-cursor-scan cur2 10 :comparison-fn >)
[ [11 {:a 11}] [12 {:a 12}] ]))
(is (= (db-cursor-scan cur2 11 :comparison-fn >=)
[ [11 {:a 11}] [12 {:a 12}] ]))
(is (= (db-cursor-scan cur2 11 :comparison-fn >)
[ [12 {:a 12}] ])))))
(deftest cursor-scans-2
(with-db-sec [idx1 *db-env* *db* "idx1"
:allow-create true
:key-creator-fn :a
:sorted-duplicates true]
(db-put *db* 1 {:a "abc123"})
(db-put *db* 2 {:a "def456"})
(db-put *db* 3 {:a "def789"})
(db-put *db* 4 {:a "ghi789"})
(with-db-cursor [cur1 idx1]
(is (= (db-cursor-scan cur1 "def" :comparison-fn starts-with)
[ [2 {:a "def456"}] [3 {:a "def789"}] ])))))
(deftest transactions
(let [path (make-temp-dir)]
(with-db-env [e path :allow-create true :transactional true]
(with-db [db e "db" :allow-create true]
(with-db-sec [idx1 e db "idx1" :key-creator-fn :login :allow-create true]
;; basic transactionality tests
(db-put db "one" 1)
(with-db-txn [txn1 e]
(db-put db "two" 2 :txn txn1)
(db-put db "three" 3 :txn txn1))
(is (= (db-get db "one") ["one" 1]))
(is (= (db-get db "two") ["two" 2]))
(is (= (db-get db "three") ["three" 3]))
(with-db-txn [txn2 e]
(db-put db "four" 4 :txn txn2)
(db-put db "five" 5 :txn txn2)
(db-txn-abort txn2))
(is (empty? (db-get db "four")))
(is (empty? (db-get db "five")))
(with-db-txn [txn3 e]
(db-put db "six" 6)
(db-put db "seven" 7 :txn txn3)
(db-txn-abort txn3))
(is (= (db-get db "six") ["six" 6]))
(is (empty? (db-get db "seven")))
;; tests for secondary database transactionality
(db-put db 1 {:login "gw" :name "PI:NAME:<NAME>END_PI"})
(db-put db 2 {:login "ja" :name "PI:NAME:<NAME>END_PI"})
(db-put db 3 {:login "tj" :name "PI:NAME:<NAME>END_PI"})
(db-put db 4 {:login "jm" :name "PI:NAME:<NAME>END_PI"})
(with-db-txn [txn4 e]
(with-db-cursor [cur1 idx1 :txn txn4]
(db-cursor-search cur1 "j")
(db-cursor-delete cur1)
(db-cursor-next cur1)
(db-cursor-delete cur1))
(db-txn-abort txn4))
(is (= (db-get db 2) [2 {:login "ja" :name "PI:NAME:<NAME>END_PI"}]))
(is (= (db-get db 4) [4 {:login "jm" :name "PI:NAME:<NAME>END_PI"}]))
(with-db-txn [txn5 e]
(with-db-cursor [cur2 idx1 :txn txn5]
(db-cursor-search cur2 "j")
(db-cursor-delete cur2)
(db-cursor-next cur2)
(db-cursor-delete cur2)))
(is (empty? (db-get db 2)))
(is (empty? (db-get db 4))))))
(rmdir-recursive path)))
|
[
{
"context": "; Copyright 2010 Mark Allerton. All rights reserved.\n;\n; Redistribution and u",
"end": 33,
"score": 0.9998698234558105,
"start": 20,
"tag": "NAME",
"value": "Mark Allerton"
},
{
"context": " distribution.\n;\n; THIS SOFTWARE IS PROVIDED BY MARK ALLERTON ``AS IS'' AND ANY EXPRESS OR IMPLIED\n; ",
"end": 638,
"score": 0.620776891708374,
"start": 634,
"tag": "NAME",
"value": "MARK"
}
] | BridgeSupport/src/clojure/couverjure/tools/bstool.clj | allertonm/Couverjure | 3 | ; Copyright 2010 Mark Allerton. All rights reserved.
;
; Redistribution and use in source and binary forms, with or without modification, are
; permitted provided that the following conditions are met:
;
; 1. Redistributions of source code must retain the above copyright notice, this list of
; conditions and the following disclaimer.
;
; 2. Redistributions in binary form must reproduce the above copyright notice, this list
; of conditions and the following disclaimer in the documentation and/or other materials
; provided with the distribution.
;
; THIS SOFTWARE IS PROVIDED BY MARK ALLERTON ``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 <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.
;
; The views and conclusions contained in the software and documentation are those of the
; authors and should not be interpreted as representing official policies, either expressed
; or implied, of Mark Allerton.
(ns couverjure.tools.bsgen
(:use
clojure.xml
clojure.contrib.seq-utils
couverjure.types
couverjure.parser
couverjure.type-encoding
couverjure.tools.java-model
couverjure.tools.clojure-model)
(:import (java.io File FileWriter PrintWriter)))
;
; Some helpers for working with bridgesupport XML elements
;
(defn tag= [t e] (= t (tag e)))
(defn type64-or-type [struct]
(or (:type64 (:attrs struct)) (:type (:attrs struct))))
;
; ______________________________________________________ output file creation
;
(defn output-file [name pkg-name dir extn]
(let [parts (seq (.split pkg-name "\\."))
dirname (apply str (interpose \/ parts))
rootdir (File. dir)
pkgdir (File. rootdir dirname)]
(.mkdirs pkgdir)
(let [file (File. pkgdir (str name "." extn))]
(println "output-file: " (.getAbsolutePath file))
(if (.exists file) (.delete file))
file)))
(defn java-output-file [name pkg-name dir]
(output-file name pkg-name (str dir "/java") "java"))
(defn clojure-output-file [name pkg-name dir]
(output-file name pkg-name (str dir "/clojure") "clj"))
;
; ______________________________________________________ Generating java class files
;
; define a java tab (4 spaces)
(def jtab " ")
; ______________________________________________________ java type references
; the to-type-spec multimethod generates a type-spec, dispatching on the :kind member
(defmulti to-type-spec :kind)
(defmethod to-type-spec :structure [s]
(type-spec (if (= :no-name (:name s)) "Object" (str (:name s) ".ByVal"))))
(defmethod to-type-spec :array [a]
(array-type-spec (:name (to-type-spec (:type a)))))
(defmethod to-type-spec :bitfield [b]
(type-spec "long"))
(defmethod to-type-spec :pointer [p]
; have to peek inside the type to do this right
(let [type (:type p)]
(cond
; primitive case - get correct pointer type
(= :primitive (:kind type))
(type-spec (.getSimpleName (or (:java-type (to-pointer-octype (:type type))) com.sun.jna.Pointer)))
; pointer to pointer, use PointerByReference
(= :pointer (:kind type))
(type-spec "PointerByReference")
; opaque structure - generate ref to opaque PointerType
(and (= :structure (:kind type)) (not (option? (:fields type))))
(type-spec (str (:name type) "Pointer"))
; default case, use the structure's ByRef type
true
(type-spec (str (:name (to-type-spec type)) ".ByRef")))))
(defmethod to-type-spec :primitive [p]
(type-spec (.getSimpleName (:java-type (:type p)))))
; ______________________________________________________ java class generation
(defn constructor [modifiers name params body] (method-decl modifiers nil name params body))
(defn call-super-ctor [params] (call-method nil "super" params))
(defn structure-modifier-class [name type var-decls]
(let [interface ({:value "Structure.ByValue" :reference "Structure.ByReference"} type)
inner-name ({:value "ByVal" :reference "ByRef"} type)]
(class-decl [public static] inner-name interface name [
(constructor [public] inner-name nil [
(statement (call-super-ctor nil))
])
(constructor [public] inner-name var-decls [
(statement
(call-super-ctor
(for [v var-decls] (var-ref nil (:name v)))))
])
(constructor [public] inner-name [(var-decl (type-spec name) "from")] [
(statement
(call-super-ctor [(var-ref nil "from")])
)
])
])))
(defn structure-class-decl [s]
(let [name (:name s)
var-decls (for [f (:fields s)] (var-decl (to-type-spec (:type f)) (:name f)))]
(class-decl [public] name nil "Structure" [
(line-comment "Structure fields")
(for [v var-decls] (field-decl [public] v))
(break)
(line-comment "Constructors")
(constructor [public] name nil [
(statement (call-super-ctor nil))
])
(constructor [public] name var-decls [
(for [v var-decls]
(statement (assignment (var-ref "this" (:name v)) (var-ref nil (:name v)))))
])
(constructor [public] name [(var-decl (type-spec name) "from")] [
(for [v var-decls]
(statement (assignment (var-ref "this" (:name v)) (var-ref "from" (:name v)))))
])
(break)
(line-comment "By-value override class")
(structure-modifier-class name :value var-decls)
(break)
(line-comment "By-reference override class")
(structure-modifier-class name :reference var-decls)
])))
(defn opaque-class-decl [s]
(let [type (:type s)
name (str (:name type) "Pointer")]
(class-decl [public] name nil "PointerType" [
(constructor [public] name nil [
(statement (call-super-ctor nil))
])
(constructor [public] name [ (var-decl (type-spec "Pointer") "p") ] [
(statement (call-super-ctor [ (var-ref nil "p") ]))
])
])))
(defn library-interface-decl [name libfns]
(interface-decl [public] name "Library" [
(for [f libfns]
(let [content
(content f)
return-type
(first
(for [e content :when (tag= :retval e)]
(first (type-encoding (type64-or-type e)))))
;_ (println "return-decoded: " (:name (attrs f)) " " return-decoded)
return-type-spec
(if return-type (to-type-spec return-type) (type-spec "void"))
args
(for [e content :when (tag= :arg e)] e)
arg-decls
(for [a args]
(var-decl (to-type-spec (first (type-encoding (type64-or-type a)))) (:name (:attrs a))))
all-arg-decls
(if (:variadic (attrs f))
(concat arg-decls [(var-decl (variadic-type-spec "Object") "rest")])
arg-decls)]
(method-decl [public] return-type-spec (:name (:attrs f)) all-arg-decls nil)))
]))
; ______________________________________________________ java file output
; execute the block with an output stream on a clojure output file
(defn with-java-file [name dir pkg-name block]
(with-open [raw-out (FileWriter. (java-output-file name pkg-name dir))
out (PrintWriter. raw-out)]
(block out)))
; standard import preamble for all java files
(defn java-file-preamble [pkg-name]
[ (multiline-comment [ "Generated by bstool" ])
(package-decl pkg-name)
(break)
(import-decl "com.sun.jna" "*")
(import-decl "com.sun.jna.ptr" "*")
(import-decl "org.couverjure.core" "*")
(break) ])
(defn gen-java-file-preamble [out pkg-name]
(doto out
(.println (str
"/*\n"
" * Generated by bstool\n"
" */\n"))
(.println (str "package " pkg-name ";"))
(.println "")
(.println "import com.sun.jna.*;")
(.println "import com.sun.jna.ptr.*;")
(.println "import org.couverjure.core.*;")
(.println "")))
; generate a class for a structure
(defn gen-java-struct-file [dir pkg-name struct]
(let [objc-type (:objc-type struct)]
(with-java-file (:name objc-type) dir pkg-name
#(doto %
;(gen-java-file-preamble pkg-name)
;(format-java-source (emit-java (to-class-decl objc-type)))
(format-java-source
(emit-java [
(java-file-preamble pkg-name)
(structure-class-decl objc-type)
])))
)))
; generate a class for an opaque pointer type
(defn gen-java-opaque-file [dir pkg-name struct]
(let [objc-type (:objc-type struct)] ; for an opaque, this is assumed to be a pointer
(with-java-file (str (:name (:type objc-type)) "Pointer") dir pkg-name ; use name of the referenced struct
#(doto %
(format-java-source
(emit-java [
(java-file-preamble pkg-name)
(opaque-class-decl objc-type)
])))
)))
(defn java-library-name [name function-type]
(str name ({ :inline "Inline" :variadic "Variadic" } function-type)))
(defn function-type-pred [function-type]
(condp = function-type
:inline #(:inline (attrs %))
:variadic #(:variadic (attrs %))
#(not (or (:inline (attrs %)) (:variadic (attrs %))))))
; generate a class defining external functions
(defn gen-java-functions-file [name dir pkg-name functions function-type]
(let [classname
(java-library-name name function-type)
filtered
(filter (function-type-pred function-type) functions)]
(with-java-file classname dir pkg-name
(fn [out]
(format-java-source
out
(emit-java [
(java-file-preamble pkg-name)
(library-interface-decl classname filtered)
])))
)))
; generate all java files for a framework
(defn gen-java-framework [name output-dir java-namespace components]
(doall (for [struct (:structs components)]
(gen-java-struct-file output-dir java-namespace struct)
))
(doall (for [op (:opaques components)]
(gen-java-opaque-file output-dir java-namespace op)
))
(gen-java-functions-file name output-dir java-namespace (:functions components) nil)
; inline functions must be written to a separate class since we have to load the bridgesupport dylib
; with the compiled versions
(gen-java-functions-file name output-dir java-namespace (:functions components) :inline)
; write variadic functions to a separate class since they cannot be used with JNA direct mapping
(gen-java-functions-file name output-dir java-namespace (:functions components) :variadic))
; ______________________________________________________ generating clojure source files
; execute the block with an output stream on a clojure output file
(defn with-clojure-file [name dir pkg-name block]
(with-open [raw-out (FileWriter. (clojure-output-file name pkg-name dir))
out (PrintWriter. raw-out)]
(block out)))
; section separator for clojure code
(def separator "______________________________________________________ ")
(defn clojure-framework-struct [struct struct-type]
(let [cname
(:name (:attrs struct))
jname
(:name (:objc-type struct))
members
(for [f (:fields (:objc-type struct))] (symbol (:name f)))
struct-classname
(str jname ({:value "$ByVal" :reference "$ByRef"} struct-type))
type-prefix
(if (= :reference struct-type) "^")
suffix
(if (= :reference struct-type) "*")
escape
(fn [s] (.replace s "\"" "\\\""))]
(list :no-brackets
(list (symbol "defoctype") (symbol (str cname suffix)) :break :indent
(str type-prefix (escape (encode (:objc-type struct))))
(symbol struct-classname))
:break :break :unindent
(list (symbol "defn") (symbol (str (.toLowerCase cname) suffix "?")) :break :indent
[(symbol "x")] :break
(list (symbol "instance?") (symbol struct-classname) (symbol "x")))
:break :break :unindent
(list (symbol "defn") (symbol (str (.toLowerCase cname) suffix)) :break :indent
(list (apply vector members) :break :indent
(list (symbol (str struct-classname ".")) (no-brackets members)))
(if (< 1 (count members))
(list :no-brackets :break :unindent
(list [(symbol "from")] :break :indent
(list (symbol (str struct-classname ".")) (symbol "from"))))
(list :no-brackets)))
:break :break :unindent :unindent
)))
(defn clojure-framework-structs [structs]
(no-brackets
(for [struct structs]
(let [cname (:name (:attrs struct))]
(list :no-brackets
(list :comment (str separator cname))
:break
(clojure-framework-struct struct :value)
(clojure-framework-struct struct :reference)
)))))
(defn clojure-framework-enums [enums dup-names]
(no-brackets
(for [enum enums :when (not (dup-names (:name (attrs enum))))]
(list :no-brackets
(list (symbol "def") (symbol (:name (:attrs enum))) (list :source (:value (:attrs enum))))
:break))))
; must go after functions (non-inline) since it uses the library def
(defn clojure-framework-constants [framework-name constants]
(let [filtered (filter #(= "@" (:type (attrs %))) constants)
constants-lib-name (str (.toLowerCase framework-name) "-constants")]
(list :no-brackets
(list (symbol "def") (symbol constants-lib-name) (list (symbol "load-framework-constants") framework-name))
:break :break
(no-brackets
(for [c filtered]
(let [const-name (:name (attrs c))]
(list :no-brackets
(list (symbol "def") (symbol const-name) :break :indent
(list (symbol "framework-constant") (symbol constants-lib-name) const-name))
:unindent :break :break
))
)))))
(defn clojure-framework-functions [name functions function-type]
(let [library-class
(java-library-name name function-type)
native-library-name
(if (= function-type :inline) (str name "Inline") name)
filtered
(filter (function-type-pred function-type) functions)
lib-sym (symbol (str (.toLowerCase library-class) "-lib"))]
(if (seq filtered)
(list :no-brackets
(list (symbol "def") lib-sym :break :indent
(list (symbol "load-framework-library") (symbol library-class) (str native-library-name)))
:break :break :unindent
(no-brackets
(for [f filtered]
(let [fn-name
(:name (attrs f))
arg-syms
(for [e (content f) :when (tag= :arg e)]
(symbol (:name (:attrs e))))
all-arg-syms
(if (= :variadic function-type)
(concat arg-syms [(symbol "rest")])
arg-syms)]
(list :no-brackets
(list (symbol "defn") (symbol fn-name) :break :indent
(apply vector all-arg-syms) :break
(list (symbol (str "." fn-name)) lib-sym (no-brackets all-arg-syms)))
:break :break :unindent)
)))
))))
(defn clojure-framework-classes [name classes dup-classnames]
(list :no-brackets
(no-brackets
(for [c classes :when (not (dup-classnames (:name (attrs c))))]
(list :no-brackets
(list (symbol "def") (symbol (:name (attrs c))) (list (symbol "objc-class") (:name (attrs c))))
:break)
))
:break :break))
(defn gen-clojure-framework [name dir clj-namespace java-namespace components]
(with-clojure-file (.toLowerCase name) dir clj-namespace
(fn [out]
(format-clojure-source out (emit-clojure
(list :no-brackets
(list :comment "" "Generated by bstool" "")
(list (symbol "ns") (symbol (str clj-namespace "." (.toLowerCase name))) :break :indent
;(list (symbol "ns") (symbol clj-namespace) :break :indent
(list :use (symbol "couverjure.core") (symbol "couverjure.types") (symbol "couverjure.frameworks")) :break
(list :import
(list (symbol java-namespace) :break :indent
(list :no-brackets
(symbol name) :break
(symbol (str name "Inline")) :break
(symbol (str name "Variadic")) :break
(no-brackets
(for [s (:structs components)]
(let [sname (:name (:objc-type s))]
(list :no-brackets
(symbol (str sname "$ByRef"))
:break
(symbol (str sname "$ByVal"))
:break)))))
)))
:break :unindent :unindent
(list :comment (str separator "structs")) :break
(clojure-framework-structs (:structs components))
(list :comment (str separator "functions (non-inline)")) :break
(clojure-framework-functions name (:functions components) nil)
(list :comment (str separator "functions (variadic)")) :break
(clojure-framework-functions name (:functions components) :variadic)
(list :comment (str separator "functions (inline)")) :break
(clojure-framework-functions name (:functions components) :inline)
(list :comment (str separator "enums")) :break
(clojure-framework-enums (:enums components) (:dup-names components)) :break
(list :comment (str separator "constants")) :break
(clojure-framework-constants name (:constants components)) :break
(list :comment (str separator "classes")) :break
(clojure-framework-classes name (:classes components) (:dup-names components))
))))))
(defn dup-names [dup-files]
"Obtains all of the class & enum names declared in the given set of bridgesupport files, which can be used
to eliminate duplicate class & enum declarations."
(set
(flatten
(for [filename dup-files :when (seq filename)]
(let [file (File. filename)
xml (xml-seq (parse file))]
(for [elem xml :when (#{:class :enum} (tag elem))] (:name (attrs elem)))
)))))
; ______________________________________________________ tool main
(defn generate-framework-classes
"Generates JNA-based java source files from the .bridgesupport XML file, using the supplied output directory and namespace"
[name bsfilename output-dir java-namespace clj-namespace & dup-files]
(let [file (File. bsfilename)
xml (xml-seq (parse file))
components {
:structs
(for [elem xml :when (tag= :struct elem)]
(assoc elem
:objc-type (first (type-encoding (type64-or-type elem)))))
:opaques
(for [elem xml :when (tag= :opaque elem)]
(assoc elem
:objc-type (first (type-encoding (type64-or-type elem)))))
:enums
(for [elem xml :when (tag= :enum elem)] elem)
:functions
(for [elem xml :when (tag= :function elem)] elem)
:constants
(for [elem xml :when (tag= :constant elem)] elem)
:classes
(for [elem xml :when (tag= :class elem)] elem)
:dup-names
(dup-names dup-files)
}]
(gen-java-framework name output-dir java-namespace components)
; one clojure module will reference all three classes, clojure code shouldn't need to know these details
(gen-clojure-framework name output-dir clj-namespace java-namespace components)))
(if (< 4 (count *command-line-args*))
(apply generate-framework-classes *command-line-args*)
(println "Usage: bsgen <name> <bridgesupport file> <output-dir> <java-namespace> <clj-namespace> [<bridgesupport duplicate class file>*]"))
| 79297 | ; Copyright 2010 <NAME>. All rights reserved.
;
; Redistribution and use in source and binary forms, with or without modification, are
; permitted provided that the following conditions are met:
;
; 1. Redistributions of source code must retain the above copyright notice, this list of
; conditions and the following disclaimer.
;
; 2. Redistributions in binary form must reproduce the above copyright notice, this list
; of conditions and the following disclaimer in the documentation and/or other materials
; provided with the distribution.
;
; THIS SOFTWARE IS PROVIDED BY <NAME> ALLERTON ``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 <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.
;
; The views and conclusions contained in the software and documentation are those of the
; authors and should not be interpreted as representing official policies, either expressed
; or implied, of Mark Allerton.
(ns couverjure.tools.bsgen
(:use
clojure.xml
clojure.contrib.seq-utils
couverjure.types
couverjure.parser
couverjure.type-encoding
couverjure.tools.java-model
couverjure.tools.clojure-model)
(:import (java.io File FileWriter PrintWriter)))
;
; Some helpers for working with bridgesupport XML elements
;
(defn tag= [t e] (= t (tag e)))
(defn type64-or-type [struct]
(or (:type64 (:attrs struct)) (:type (:attrs struct))))
;
; ______________________________________________________ output file creation
;
(defn output-file [name pkg-name dir extn]
(let [parts (seq (.split pkg-name "\\."))
dirname (apply str (interpose \/ parts))
rootdir (File. dir)
pkgdir (File. rootdir dirname)]
(.mkdirs pkgdir)
(let [file (File. pkgdir (str name "." extn))]
(println "output-file: " (.getAbsolutePath file))
(if (.exists file) (.delete file))
file)))
(defn java-output-file [name pkg-name dir]
(output-file name pkg-name (str dir "/java") "java"))
(defn clojure-output-file [name pkg-name dir]
(output-file name pkg-name (str dir "/clojure") "clj"))
;
; ______________________________________________________ Generating java class files
;
; define a java tab (4 spaces)
(def jtab " ")
; ______________________________________________________ java type references
; the to-type-spec multimethod generates a type-spec, dispatching on the :kind member
(defmulti to-type-spec :kind)
(defmethod to-type-spec :structure [s]
(type-spec (if (= :no-name (:name s)) "Object" (str (:name s) ".ByVal"))))
(defmethod to-type-spec :array [a]
(array-type-spec (:name (to-type-spec (:type a)))))
(defmethod to-type-spec :bitfield [b]
(type-spec "long"))
(defmethod to-type-spec :pointer [p]
; have to peek inside the type to do this right
(let [type (:type p)]
(cond
; primitive case - get correct pointer type
(= :primitive (:kind type))
(type-spec (.getSimpleName (or (:java-type (to-pointer-octype (:type type))) com.sun.jna.Pointer)))
; pointer to pointer, use PointerByReference
(= :pointer (:kind type))
(type-spec "PointerByReference")
; opaque structure - generate ref to opaque PointerType
(and (= :structure (:kind type)) (not (option? (:fields type))))
(type-spec (str (:name type) "Pointer"))
; default case, use the structure's ByRef type
true
(type-spec (str (:name (to-type-spec type)) ".ByRef")))))
(defmethod to-type-spec :primitive [p]
(type-spec (.getSimpleName (:java-type (:type p)))))
; ______________________________________________________ java class generation
(defn constructor [modifiers name params body] (method-decl modifiers nil name params body))
(defn call-super-ctor [params] (call-method nil "super" params))
(defn structure-modifier-class [name type var-decls]
(let [interface ({:value "Structure.ByValue" :reference "Structure.ByReference"} type)
inner-name ({:value "ByVal" :reference "ByRef"} type)]
(class-decl [public static] inner-name interface name [
(constructor [public] inner-name nil [
(statement (call-super-ctor nil))
])
(constructor [public] inner-name var-decls [
(statement
(call-super-ctor
(for [v var-decls] (var-ref nil (:name v)))))
])
(constructor [public] inner-name [(var-decl (type-spec name) "from")] [
(statement
(call-super-ctor [(var-ref nil "from")])
)
])
])))
(defn structure-class-decl [s]
(let [name (:name s)
var-decls (for [f (:fields s)] (var-decl (to-type-spec (:type f)) (:name f)))]
(class-decl [public] name nil "Structure" [
(line-comment "Structure fields")
(for [v var-decls] (field-decl [public] v))
(break)
(line-comment "Constructors")
(constructor [public] name nil [
(statement (call-super-ctor nil))
])
(constructor [public] name var-decls [
(for [v var-decls]
(statement (assignment (var-ref "this" (:name v)) (var-ref nil (:name v)))))
])
(constructor [public] name [(var-decl (type-spec name) "from")] [
(for [v var-decls]
(statement (assignment (var-ref "this" (:name v)) (var-ref "from" (:name v)))))
])
(break)
(line-comment "By-value override class")
(structure-modifier-class name :value var-decls)
(break)
(line-comment "By-reference override class")
(structure-modifier-class name :reference var-decls)
])))
(defn opaque-class-decl [s]
(let [type (:type s)
name (str (:name type) "Pointer")]
(class-decl [public] name nil "PointerType" [
(constructor [public] name nil [
(statement (call-super-ctor nil))
])
(constructor [public] name [ (var-decl (type-spec "Pointer") "p") ] [
(statement (call-super-ctor [ (var-ref nil "p") ]))
])
])))
(defn library-interface-decl [name libfns]
(interface-decl [public] name "Library" [
(for [f libfns]
(let [content
(content f)
return-type
(first
(for [e content :when (tag= :retval e)]
(first (type-encoding (type64-or-type e)))))
;_ (println "return-decoded: " (:name (attrs f)) " " return-decoded)
return-type-spec
(if return-type (to-type-spec return-type) (type-spec "void"))
args
(for [e content :when (tag= :arg e)] e)
arg-decls
(for [a args]
(var-decl (to-type-spec (first (type-encoding (type64-or-type a)))) (:name (:attrs a))))
all-arg-decls
(if (:variadic (attrs f))
(concat arg-decls [(var-decl (variadic-type-spec "Object") "rest")])
arg-decls)]
(method-decl [public] return-type-spec (:name (:attrs f)) all-arg-decls nil)))
]))
; ______________________________________________________ java file output
; execute the block with an output stream on a clojure output file
(defn with-java-file [name dir pkg-name block]
(with-open [raw-out (FileWriter. (java-output-file name pkg-name dir))
out (PrintWriter. raw-out)]
(block out)))
; standard import preamble for all java files
(defn java-file-preamble [pkg-name]
[ (multiline-comment [ "Generated by bstool" ])
(package-decl pkg-name)
(break)
(import-decl "com.sun.jna" "*")
(import-decl "com.sun.jna.ptr" "*")
(import-decl "org.couverjure.core" "*")
(break) ])
(defn gen-java-file-preamble [out pkg-name]
(doto out
(.println (str
"/*\n"
" * Generated by bstool\n"
" */\n"))
(.println (str "package " pkg-name ";"))
(.println "")
(.println "import com.sun.jna.*;")
(.println "import com.sun.jna.ptr.*;")
(.println "import org.couverjure.core.*;")
(.println "")))
; generate a class for a structure
(defn gen-java-struct-file [dir pkg-name struct]
(let [objc-type (:objc-type struct)]
(with-java-file (:name objc-type) dir pkg-name
#(doto %
;(gen-java-file-preamble pkg-name)
;(format-java-source (emit-java (to-class-decl objc-type)))
(format-java-source
(emit-java [
(java-file-preamble pkg-name)
(structure-class-decl objc-type)
])))
)))
; generate a class for an opaque pointer type
(defn gen-java-opaque-file [dir pkg-name struct]
(let [objc-type (:objc-type struct)] ; for an opaque, this is assumed to be a pointer
(with-java-file (str (:name (:type objc-type)) "Pointer") dir pkg-name ; use name of the referenced struct
#(doto %
(format-java-source
(emit-java [
(java-file-preamble pkg-name)
(opaque-class-decl objc-type)
])))
)))
(defn java-library-name [name function-type]
(str name ({ :inline "Inline" :variadic "Variadic" } function-type)))
(defn function-type-pred [function-type]
(condp = function-type
:inline #(:inline (attrs %))
:variadic #(:variadic (attrs %))
#(not (or (:inline (attrs %)) (:variadic (attrs %))))))
; generate a class defining external functions
(defn gen-java-functions-file [name dir pkg-name functions function-type]
(let [classname
(java-library-name name function-type)
filtered
(filter (function-type-pred function-type) functions)]
(with-java-file classname dir pkg-name
(fn [out]
(format-java-source
out
(emit-java [
(java-file-preamble pkg-name)
(library-interface-decl classname filtered)
])))
)))
; generate all java files for a framework
(defn gen-java-framework [name output-dir java-namespace components]
(doall (for [struct (:structs components)]
(gen-java-struct-file output-dir java-namespace struct)
))
(doall (for [op (:opaques components)]
(gen-java-opaque-file output-dir java-namespace op)
))
(gen-java-functions-file name output-dir java-namespace (:functions components) nil)
; inline functions must be written to a separate class since we have to load the bridgesupport dylib
; with the compiled versions
(gen-java-functions-file name output-dir java-namespace (:functions components) :inline)
; write variadic functions to a separate class since they cannot be used with JNA direct mapping
(gen-java-functions-file name output-dir java-namespace (:functions components) :variadic))
; ______________________________________________________ generating clojure source files
; execute the block with an output stream on a clojure output file
(defn with-clojure-file [name dir pkg-name block]
(with-open [raw-out (FileWriter. (clojure-output-file name pkg-name dir))
out (PrintWriter. raw-out)]
(block out)))
; section separator for clojure code
(def separator "______________________________________________________ ")
(defn clojure-framework-struct [struct struct-type]
(let [cname
(:name (:attrs struct))
jname
(:name (:objc-type struct))
members
(for [f (:fields (:objc-type struct))] (symbol (:name f)))
struct-classname
(str jname ({:value "$ByVal" :reference "$ByRef"} struct-type))
type-prefix
(if (= :reference struct-type) "^")
suffix
(if (= :reference struct-type) "*")
escape
(fn [s] (.replace s "\"" "\\\""))]
(list :no-brackets
(list (symbol "defoctype") (symbol (str cname suffix)) :break :indent
(str type-prefix (escape (encode (:objc-type struct))))
(symbol struct-classname))
:break :break :unindent
(list (symbol "defn") (symbol (str (.toLowerCase cname) suffix "?")) :break :indent
[(symbol "x")] :break
(list (symbol "instance?") (symbol struct-classname) (symbol "x")))
:break :break :unindent
(list (symbol "defn") (symbol (str (.toLowerCase cname) suffix)) :break :indent
(list (apply vector members) :break :indent
(list (symbol (str struct-classname ".")) (no-brackets members)))
(if (< 1 (count members))
(list :no-brackets :break :unindent
(list [(symbol "from")] :break :indent
(list (symbol (str struct-classname ".")) (symbol "from"))))
(list :no-brackets)))
:break :break :unindent :unindent
)))
(defn clojure-framework-structs [structs]
(no-brackets
(for [struct structs]
(let [cname (:name (:attrs struct))]
(list :no-brackets
(list :comment (str separator cname))
:break
(clojure-framework-struct struct :value)
(clojure-framework-struct struct :reference)
)))))
(defn clojure-framework-enums [enums dup-names]
(no-brackets
(for [enum enums :when (not (dup-names (:name (attrs enum))))]
(list :no-brackets
(list (symbol "def") (symbol (:name (:attrs enum))) (list :source (:value (:attrs enum))))
:break))))
; must go after functions (non-inline) since it uses the library def
(defn clojure-framework-constants [framework-name constants]
(let [filtered (filter #(= "@" (:type (attrs %))) constants)
constants-lib-name (str (.toLowerCase framework-name) "-constants")]
(list :no-brackets
(list (symbol "def") (symbol constants-lib-name) (list (symbol "load-framework-constants") framework-name))
:break :break
(no-brackets
(for [c filtered]
(let [const-name (:name (attrs c))]
(list :no-brackets
(list (symbol "def") (symbol const-name) :break :indent
(list (symbol "framework-constant") (symbol constants-lib-name) const-name))
:unindent :break :break
))
)))))
(defn clojure-framework-functions [name functions function-type]
(let [library-class
(java-library-name name function-type)
native-library-name
(if (= function-type :inline) (str name "Inline") name)
filtered
(filter (function-type-pred function-type) functions)
lib-sym (symbol (str (.toLowerCase library-class) "-lib"))]
(if (seq filtered)
(list :no-brackets
(list (symbol "def") lib-sym :break :indent
(list (symbol "load-framework-library") (symbol library-class) (str native-library-name)))
:break :break :unindent
(no-brackets
(for [f filtered]
(let [fn-name
(:name (attrs f))
arg-syms
(for [e (content f) :when (tag= :arg e)]
(symbol (:name (:attrs e))))
all-arg-syms
(if (= :variadic function-type)
(concat arg-syms [(symbol "rest")])
arg-syms)]
(list :no-brackets
(list (symbol "defn") (symbol fn-name) :break :indent
(apply vector all-arg-syms) :break
(list (symbol (str "." fn-name)) lib-sym (no-brackets all-arg-syms)))
:break :break :unindent)
)))
))))
(defn clojure-framework-classes [name classes dup-classnames]
(list :no-brackets
(no-brackets
(for [c classes :when (not (dup-classnames (:name (attrs c))))]
(list :no-brackets
(list (symbol "def") (symbol (:name (attrs c))) (list (symbol "objc-class") (:name (attrs c))))
:break)
))
:break :break))
(defn gen-clojure-framework [name dir clj-namespace java-namespace components]
(with-clojure-file (.toLowerCase name) dir clj-namespace
(fn [out]
(format-clojure-source out (emit-clojure
(list :no-brackets
(list :comment "" "Generated by bstool" "")
(list (symbol "ns") (symbol (str clj-namespace "." (.toLowerCase name))) :break :indent
;(list (symbol "ns") (symbol clj-namespace) :break :indent
(list :use (symbol "couverjure.core") (symbol "couverjure.types") (symbol "couverjure.frameworks")) :break
(list :import
(list (symbol java-namespace) :break :indent
(list :no-brackets
(symbol name) :break
(symbol (str name "Inline")) :break
(symbol (str name "Variadic")) :break
(no-brackets
(for [s (:structs components)]
(let [sname (:name (:objc-type s))]
(list :no-brackets
(symbol (str sname "$ByRef"))
:break
(symbol (str sname "$ByVal"))
:break)))))
)))
:break :unindent :unindent
(list :comment (str separator "structs")) :break
(clojure-framework-structs (:structs components))
(list :comment (str separator "functions (non-inline)")) :break
(clojure-framework-functions name (:functions components) nil)
(list :comment (str separator "functions (variadic)")) :break
(clojure-framework-functions name (:functions components) :variadic)
(list :comment (str separator "functions (inline)")) :break
(clojure-framework-functions name (:functions components) :inline)
(list :comment (str separator "enums")) :break
(clojure-framework-enums (:enums components) (:dup-names components)) :break
(list :comment (str separator "constants")) :break
(clojure-framework-constants name (:constants components)) :break
(list :comment (str separator "classes")) :break
(clojure-framework-classes name (:classes components) (:dup-names components))
))))))
(defn dup-names [dup-files]
"Obtains all of the class & enum names declared in the given set of bridgesupport files, which can be used
to eliminate duplicate class & enum declarations."
(set
(flatten
(for [filename dup-files :when (seq filename)]
(let [file (File. filename)
xml (xml-seq (parse file))]
(for [elem xml :when (#{:class :enum} (tag elem))] (:name (attrs elem)))
)))))
; ______________________________________________________ tool main
(defn generate-framework-classes
"Generates JNA-based java source files from the .bridgesupport XML file, using the supplied output directory and namespace"
[name bsfilename output-dir java-namespace clj-namespace & dup-files]
(let [file (File. bsfilename)
xml (xml-seq (parse file))
components {
:structs
(for [elem xml :when (tag= :struct elem)]
(assoc elem
:objc-type (first (type-encoding (type64-or-type elem)))))
:opaques
(for [elem xml :when (tag= :opaque elem)]
(assoc elem
:objc-type (first (type-encoding (type64-or-type elem)))))
:enums
(for [elem xml :when (tag= :enum elem)] elem)
:functions
(for [elem xml :when (tag= :function elem)] elem)
:constants
(for [elem xml :when (tag= :constant elem)] elem)
:classes
(for [elem xml :when (tag= :class elem)] elem)
:dup-names
(dup-names dup-files)
}]
(gen-java-framework name output-dir java-namespace components)
; one clojure module will reference all three classes, clojure code shouldn't need to know these details
(gen-clojure-framework name output-dir clj-namespace java-namespace components)))
(if (< 4 (count *command-line-args*))
(apply generate-framework-classes *command-line-args*)
(println "Usage: bsgen <name> <bridgesupport file> <output-dir> <java-namespace> <clj-namespace> [<bridgesupport duplicate class file>*]"))
| true | ; Copyright 2010 PI:NAME:<NAME>END_PI. All rights reserved.
;
; Redistribution and use in source and binary forms, with or without modification, are
; permitted provided that the following conditions are met:
;
; 1. Redistributions of source code must retain the above copyright notice, this list of
; conditions and the following disclaimer.
;
; 2. Redistributions in binary form must reproduce the above copyright notice, this list
; of conditions and the following disclaimer in the documentation and/or other materials
; provided with the distribution.
;
; THIS SOFTWARE IS PROVIDED BY PI:NAME:<NAME>END_PI ALLERTON ``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 <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.
;
; The views and conclusions contained in the software and documentation are those of the
; authors and should not be interpreted as representing official policies, either expressed
; or implied, of Mark Allerton.
(ns couverjure.tools.bsgen
(:use
clojure.xml
clojure.contrib.seq-utils
couverjure.types
couverjure.parser
couverjure.type-encoding
couverjure.tools.java-model
couverjure.tools.clojure-model)
(:import (java.io File FileWriter PrintWriter)))
;
; Some helpers for working with bridgesupport XML elements
;
(defn tag= [t e] (= t (tag e)))
(defn type64-or-type [struct]
(or (:type64 (:attrs struct)) (:type (:attrs struct))))
;
; ______________________________________________________ output file creation
;
(defn output-file [name pkg-name dir extn]
(let [parts (seq (.split pkg-name "\\."))
dirname (apply str (interpose \/ parts))
rootdir (File. dir)
pkgdir (File. rootdir dirname)]
(.mkdirs pkgdir)
(let [file (File. pkgdir (str name "." extn))]
(println "output-file: " (.getAbsolutePath file))
(if (.exists file) (.delete file))
file)))
(defn java-output-file [name pkg-name dir]
(output-file name pkg-name (str dir "/java") "java"))
(defn clojure-output-file [name pkg-name dir]
(output-file name pkg-name (str dir "/clojure") "clj"))
;
; ______________________________________________________ Generating java class files
;
; define a java tab (4 spaces)
(def jtab " ")
; ______________________________________________________ java type references
; the to-type-spec multimethod generates a type-spec, dispatching on the :kind member
(defmulti to-type-spec :kind)
(defmethod to-type-spec :structure [s]
(type-spec (if (= :no-name (:name s)) "Object" (str (:name s) ".ByVal"))))
(defmethod to-type-spec :array [a]
(array-type-spec (:name (to-type-spec (:type a)))))
(defmethod to-type-spec :bitfield [b]
(type-spec "long"))
(defmethod to-type-spec :pointer [p]
; have to peek inside the type to do this right
(let [type (:type p)]
(cond
; primitive case - get correct pointer type
(= :primitive (:kind type))
(type-spec (.getSimpleName (or (:java-type (to-pointer-octype (:type type))) com.sun.jna.Pointer)))
; pointer to pointer, use PointerByReference
(= :pointer (:kind type))
(type-spec "PointerByReference")
; opaque structure - generate ref to opaque PointerType
(and (= :structure (:kind type)) (not (option? (:fields type))))
(type-spec (str (:name type) "Pointer"))
; default case, use the structure's ByRef type
true
(type-spec (str (:name (to-type-spec type)) ".ByRef")))))
(defmethod to-type-spec :primitive [p]
(type-spec (.getSimpleName (:java-type (:type p)))))
; ______________________________________________________ java class generation
(defn constructor [modifiers name params body] (method-decl modifiers nil name params body))
(defn call-super-ctor [params] (call-method nil "super" params))
(defn structure-modifier-class [name type var-decls]
(let [interface ({:value "Structure.ByValue" :reference "Structure.ByReference"} type)
inner-name ({:value "ByVal" :reference "ByRef"} type)]
(class-decl [public static] inner-name interface name [
(constructor [public] inner-name nil [
(statement (call-super-ctor nil))
])
(constructor [public] inner-name var-decls [
(statement
(call-super-ctor
(for [v var-decls] (var-ref nil (:name v)))))
])
(constructor [public] inner-name [(var-decl (type-spec name) "from")] [
(statement
(call-super-ctor [(var-ref nil "from")])
)
])
])))
(defn structure-class-decl [s]
(let [name (:name s)
var-decls (for [f (:fields s)] (var-decl (to-type-spec (:type f)) (:name f)))]
(class-decl [public] name nil "Structure" [
(line-comment "Structure fields")
(for [v var-decls] (field-decl [public] v))
(break)
(line-comment "Constructors")
(constructor [public] name nil [
(statement (call-super-ctor nil))
])
(constructor [public] name var-decls [
(for [v var-decls]
(statement (assignment (var-ref "this" (:name v)) (var-ref nil (:name v)))))
])
(constructor [public] name [(var-decl (type-spec name) "from")] [
(for [v var-decls]
(statement (assignment (var-ref "this" (:name v)) (var-ref "from" (:name v)))))
])
(break)
(line-comment "By-value override class")
(structure-modifier-class name :value var-decls)
(break)
(line-comment "By-reference override class")
(structure-modifier-class name :reference var-decls)
])))
(defn opaque-class-decl [s]
(let [type (:type s)
name (str (:name type) "Pointer")]
(class-decl [public] name nil "PointerType" [
(constructor [public] name nil [
(statement (call-super-ctor nil))
])
(constructor [public] name [ (var-decl (type-spec "Pointer") "p") ] [
(statement (call-super-ctor [ (var-ref nil "p") ]))
])
])))
(defn library-interface-decl [name libfns]
(interface-decl [public] name "Library" [
(for [f libfns]
(let [content
(content f)
return-type
(first
(for [e content :when (tag= :retval e)]
(first (type-encoding (type64-or-type e)))))
;_ (println "return-decoded: " (:name (attrs f)) " " return-decoded)
return-type-spec
(if return-type (to-type-spec return-type) (type-spec "void"))
args
(for [e content :when (tag= :arg e)] e)
arg-decls
(for [a args]
(var-decl (to-type-spec (first (type-encoding (type64-or-type a)))) (:name (:attrs a))))
all-arg-decls
(if (:variadic (attrs f))
(concat arg-decls [(var-decl (variadic-type-spec "Object") "rest")])
arg-decls)]
(method-decl [public] return-type-spec (:name (:attrs f)) all-arg-decls nil)))
]))
; ______________________________________________________ java file output
; execute the block with an output stream on a clojure output file
(defn with-java-file [name dir pkg-name block]
(with-open [raw-out (FileWriter. (java-output-file name pkg-name dir))
out (PrintWriter. raw-out)]
(block out)))
; standard import preamble for all java files
(defn java-file-preamble [pkg-name]
[ (multiline-comment [ "Generated by bstool" ])
(package-decl pkg-name)
(break)
(import-decl "com.sun.jna" "*")
(import-decl "com.sun.jna.ptr" "*")
(import-decl "org.couverjure.core" "*")
(break) ])
(defn gen-java-file-preamble [out pkg-name]
(doto out
(.println (str
"/*\n"
" * Generated by bstool\n"
" */\n"))
(.println (str "package " pkg-name ";"))
(.println "")
(.println "import com.sun.jna.*;")
(.println "import com.sun.jna.ptr.*;")
(.println "import org.couverjure.core.*;")
(.println "")))
; generate a class for a structure
(defn gen-java-struct-file [dir pkg-name struct]
(let [objc-type (:objc-type struct)]
(with-java-file (:name objc-type) dir pkg-name
#(doto %
;(gen-java-file-preamble pkg-name)
;(format-java-source (emit-java (to-class-decl objc-type)))
(format-java-source
(emit-java [
(java-file-preamble pkg-name)
(structure-class-decl objc-type)
])))
)))
; generate a class for an opaque pointer type
(defn gen-java-opaque-file [dir pkg-name struct]
(let [objc-type (:objc-type struct)] ; for an opaque, this is assumed to be a pointer
(with-java-file (str (:name (:type objc-type)) "Pointer") dir pkg-name ; use name of the referenced struct
#(doto %
(format-java-source
(emit-java [
(java-file-preamble pkg-name)
(opaque-class-decl objc-type)
])))
)))
(defn java-library-name [name function-type]
(str name ({ :inline "Inline" :variadic "Variadic" } function-type)))
(defn function-type-pred [function-type]
(condp = function-type
:inline #(:inline (attrs %))
:variadic #(:variadic (attrs %))
#(not (or (:inline (attrs %)) (:variadic (attrs %))))))
; generate a class defining external functions
(defn gen-java-functions-file [name dir pkg-name functions function-type]
(let [classname
(java-library-name name function-type)
filtered
(filter (function-type-pred function-type) functions)]
(with-java-file classname dir pkg-name
(fn [out]
(format-java-source
out
(emit-java [
(java-file-preamble pkg-name)
(library-interface-decl classname filtered)
])))
)))
; generate all java files for a framework
(defn gen-java-framework [name output-dir java-namespace components]
(doall (for [struct (:structs components)]
(gen-java-struct-file output-dir java-namespace struct)
))
(doall (for [op (:opaques components)]
(gen-java-opaque-file output-dir java-namespace op)
))
(gen-java-functions-file name output-dir java-namespace (:functions components) nil)
; inline functions must be written to a separate class since we have to load the bridgesupport dylib
; with the compiled versions
(gen-java-functions-file name output-dir java-namespace (:functions components) :inline)
; write variadic functions to a separate class since they cannot be used with JNA direct mapping
(gen-java-functions-file name output-dir java-namespace (:functions components) :variadic))
; ______________________________________________________ generating clojure source files
; execute the block with an output stream on a clojure output file
(defn with-clojure-file [name dir pkg-name block]
(with-open [raw-out (FileWriter. (clojure-output-file name pkg-name dir))
out (PrintWriter. raw-out)]
(block out)))
; section separator for clojure code
(def separator "______________________________________________________ ")
(defn clojure-framework-struct [struct struct-type]
(let [cname
(:name (:attrs struct))
jname
(:name (:objc-type struct))
members
(for [f (:fields (:objc-type struct))] (symbol (:name f)))
struct-classname
(str jname ({:value "$ByVal" :reference "$ByRef"} struct-type))
type-prefix
(if (= :reference struct-type) "^")
suffix
(if (= :reference struct-type) "*")
escape
(fn [s] (.replace s "\"" "\\\""))]
(list :no-brackets
(list (symbol "defoctype") (symbol (str cname suffix)) :break :indent
(str type-prefix (escape (encode (:objc-type struct))))
(symbol struct-classname))
:break :break :unindent
(list (symbol "defn") (symbol (str (.toLowerCase cname) suffix "?")) :break :indent
[(symbol "x")] :break
(list (symbol "instance?") (symbol struct-classname) (symbol "x")))
:break :break :unindent
(list (symbol "defn") (symbol (str (.toLowerCase cname) suffix)) :break :indent
(list (apply vector members) :break :indent
(list (symbol (str struct-classname ".")) (no-brackets members)))
(if (< 1 (count members))
(list :no-brackets :break :unindent
(list [(symbol "from")] :break :indent
(list (symbol (str struct-classname ".")) (symbol "from"))))
(list :no-brackets)))
:break :break :unindent :unindent
)))
(defn clojure-framework-structs [structs]
(no-brackets
(for [struct structs]
(let [cname (:name (:attrs struct))]
(list :no-brackets
(list :comment (str separator cname))
:break
(clojure-framework-struct struct :value)
(clojure-framework-struct struct :reference)
)))))
(defn clojure-framework-enums [enums dup-names]
(no-brackets
(for [enum enums :when (not (dup-names (:name (attrs enum))))]
(list :no-brackets
(list (symbol "def") (symbol (:name (:attrs enum))) (list :source (:value (:attrs enum))))
:break))))
; must go after functions (non-inline) since it uses the library def
(defn clojure-framework-constants [framework-name constants]
(let [filtered (filter #(= "@" (:type (attrs %))) constants)
constants-lib-name (str (.toLowerCase framework-name) "-constants")]
(list :no-brackets
(list (symbol "def") (symbol constants-lib-name) (list (symbol "load-framework-constants") framework-name))
:break :break
(no-brackets
(for [c filtered]
(let [const-name (:name (attrs c))]
(list :no-brackets
(list (symbol "def") (symbol const-name) :break :indent
(list (symbol "framework-constant") (symbol constants-lib-name) const-name))
:unindent :break :break
))
)))))
(defn clojure-framework-functions [name functions function-type]
(let [library-class
(java-library-name name function-type)
native-library-name
(if (= function-type :inline) (str name "Inline") name)
filtered
(filter (function-type-pred function-type) functions)
lib-sym (symbol (str (.toLowerCase library-class) "-lib"))]
(if (seq filtered)
(list :no-brackets
(list (symbol "def") lib-sym :break :indent
(list (symbol "load-framework-library") (symbol library-class) (str native-library-name)))
:break :break :unindent
(no-brackets
(for [f filtered]
(let [fn-name
(:name (attrs f))
arg-syms
(for [e (content f) :when (tag= :arg e)]
(symbol (:name (:attrs e))))
all-arg-syms
(if (= :variadic function-type)
(concat arg-syms [(symbol "rest")])
arg-syms)]
(list :no-brackets
(list (symbol "defn") (symbol fn-name) :break :indent
(apply vector all-arg-syms) :break
(list (symbol (str "." fn-name)) lib-sym (no-brackets all-arg-syms)))
:break :break :unindent)
)))
))))
(defn clojure-framework-classes [name classes dup-classnames]
(list :no-brackets
(no-brackets
(for [c classes :when (not (dup-classnames (:name (attrs c))))]
(list :no-brackets
(list (symbol "def") (symbol (:name (attrs c))) (list (symbol "objc-class") (:name (attrs c))))
:break)
))
:break :break))
(defn gen-clojure-framework [name dir clj-namespace java-namespace components]
(with-clojure-file (.toLowerCase name) dir clj-namespace
(fn [out]
(format-clojure-source out (emit-clojure
(list :no-brackets
(list :comment "" "Generated by bstool" "")
(list (symbol "ns") (symbol (str clj-namespace "." (.toLowerCase name))) :break :indent
;(list (symbol "ns") (symbol clj-namespace) :break :indent
(list :use (symbol "couverjure.core") (symbol "couverjure.types") (symbol "couverjure.frameworks")) :break
(list :import
(list (symbol java-namespace) :break :indent
(list :no-brackets
(symbol name) :break
(symbol (str name "Inline")) :break
(symbol (str name "Variadic")) :break
(no-brackets
(for [s (:structs components)]
(let [sname (:name (:objc-type s))]
(list :no-brackets
(symbol (str sname "$ByRef"))
:break
(symbol (str sname "$ByVal"))
:break)))))
)))
:break :unindent :unindent
(list :comment (str separator "structs")) :break
(clojure-framework-structs (:structs components))
(list :comment (str separator "functions (non-inline)")) :break
(clojure-framework-functions name (:functions components) nil)
(list :comment (str separator "functions (variadic)")) :break
(clojure-framework-functions name (:functions components) :variadic)
(list :comment (str separator "functions (inline)")) :break
(clojure-framework-functions name (:functions components) :inline)
(list :comment (str separator "enums")) :break
(clojure-framework-enums (:enums components) (:dup-names components)) :break
(list :comment (str separator "constants")) :break
(clojure-framework-constants name (:constants components)) :break
(list :comment (str separator "classes")) :break
(clojure-framework-classes name (:classes components) (:dup-names components))
))))))
(defn dup-names [dup-files]
"Obtains all of the class & enum names declared in the given set of bridgesupport files, which can be used
to eliminate duplicate class & enum declarations."
(set
(flatten
(for [filename dup-files :when (seq filename)]
(let [file (File. filename)
xml (xml-seq (parse file))]
(for [elem xml :when (#{:class :enum} (tag elem))] (:name (attrs elem)))
)))))
; ______________________________________________________ tool main
(defn generate-framework-classes
"Generates JNA-based java source files from the .bridgesupport XML file, using the supplied output directory and namespace"
[name bsfilename output-dir java-namespace clj-namespace & dup-files]
(let [file (File. bsfilename)
xml (xml-seq (parse file))
components {
:structs
(for [elem xml :when (tag= :struct elem)]
(assoc elem
:objc-type (first (type-encoding (type64-or-type elem)))))
:opaques
(for [elem xml :when (tag= :opaque elem)]
(assoc elem
:objc-type (first (type-encoding (type64-or-type elem)))))
:enums
(for [elem xml :when (tag= :enum elem)] elem)
:functions
(for [elem xml :when (tag= :function elem)] elem)
:constants
(for [elem xml :when (tag= :constant elem)] elem)
:classes
(for [elem xml :when (tag= :class elem)] elem)
:dup-names
(dup-names dup-files)
}]
(gen-java-framework name output-dir java-namespace components)
; one clojure module will reference all three classes, clojure code shouldn't need to know these details
(gen-clojure-framework name output-dir clj-namespace java-namespace components)))
(if (< 4 (count *command-line-args*))
(apply generate-framework-classes *command-line-args*)
(println "Usage: bsgen <name> <bridgesupport file> <output-dir> <java-namespace> <clj-namespace> [<bridgesupport duplicate class file>*]"))
|
[
{
"context": ";; Copyright (c) 2015-2016 Andrey Antukh <niwi@niwi.nz>\n;; All rights reserved.\n;;\n;; Redi",
"end": 40,
"score": 0.999882698059082,
"start": 27,
"tag": "NAME",
"value": "Andrey Antukh"
},
{
"context": ";; Copyright (c) 2015-2016 Andrey Antukh <niwi@niwi.nz>\n;; All rights reserved.\n;;\n;; Redistribution and",
"end": 54,
"score": 0.9999328255653381,
"start": 42,
"tag": "EMAIL",
"value": "niwi@niwi.nz"
}
] | src/clojure/catacumba/impl/atomic.clj | source-c/catacumba | 212 | ;; Copyright (c) 2015-2016 Andrey Antukh <niwi@niwi.nz>
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; 1. Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; 2. Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(ns catacumba.impl.atomic
"A clojure idiomatic wrapper for JDK atomic types."
(:refer-clojure :exclude [set! get long ref boolean compare-and-set!]))
(defprotocol IAtomic
"A common abstraction for atomic types."
(compare-and-set! [_ v v'] "Perform the CAS operation.")
(get-and-set! [_ v] "Set a new value and return the previous one.")
(eventually-set! [_ v] "Eventually set a new value.")
(get [_] "Get the current value.")
(set! [_ v] "Set a new value."))
(defprotocol IAtomicNumber
"A common abstraction for number atomic types."
(get-and-add! [_ v] "Adds a delta and return the previous value.")
(get-and-dec! [_] "Decrements the value and return the previous one.")
(get-and-inc! [_] "Increments the value and returns the previous one.")
(dec-and-get! [_] "Decrements the value and return it.")
(inc-and-get! [_] "Increments the value and return it."))
(deftype AtomicLong [^java.util.concurrent.atomic.AtomicLong av]
IAtomicNumber
(get-and-add! [_ v]
(.getAndAdd av v))
(get-and-dec! [_]
(.getAndDecrement av))
(get-and-inc! [_]
(.getAndIncrement av))
(dec-and-get! [_]
(.decrementAndGet av))
(inc-and-get! [_]
(.incrementAndGet av))
IAtomic
(compare-and-set! [_ expected update]
(.compareAndSet av expected update))
(get-and-set! [_ v]
(.getAndSet av v))
(eventually-set! [_ v]
(.lazySet av v))
(get [_]
(.get av))
(set! [_ v]
(.set av v))
clojure.lang.IDeref
(deref [_]
(.get av)))
(deftype AtomicRef [^java.util.concurrent.atomic.AtomicReference av]
IAtomic
( compare-and-set! [_ expected update]
(.compareAndSet av expected update))
(get-and-set! [_ v]
(.getAndSet av v))
( eventually-set! [_ v]
(.lazySet av v))
(get [_]
(.get av))
(set! [_ v]
(.set av v))
clojure.lang.IDeref
(deref [_]
(.get av)))
(deftype AtomicBoolean [^java.util.concurrent.atomic.AtomicBoolean av]
IAtomic
(compare-and-set! [_ expected update]
(.compareAndSet av expected update))
(get-and-set! [_ v]
(.getAndSet av v))
(eventually-set! [_ v]
(.lazySet av v))
(get [_]
(.get av))
(set! [_ v]
(.set av v))
clojure.lang.IDeref
(deref [_]
(.get av)))
(alter-meta! #'->AtomicRef assoc :private true)
(alter-meta! #'->AtomicLong assoc :private true)
(alter-meta! #'->AtomicBoolean assoc :private true)
(defn long
"Create an instance of atomic long with optional
initial value. If it is not provided, `0` will be
the initial value."
([] (long 0))
([n]
(let [al (java.util.concurrent.atomic.AtomicLong. n)]
(AtomicLong. al))))
(defn ref
"Create an instance of atomic reference."
[v]
(let [ar (java.util.concurrent.atomic.AtomicReference. v)]
(AtomicRef. ar)))
(defn boolean
"Create an instance of atomic boolean."
[v]
(let [ar (java.util.concurrent.atomic.AtomicBoolean. v)]
(AtomicBoolean. ar)))
| 88902 | ;; Copyright (c) 2015-2016 <NAME> <<EMAIL>>
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; 1. Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; 2. Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(ns catacumba.impl.atomic
"A clojure idiomatic wrapper for JDK atomic types."
(:refer-clojure :exclude [set! get long ref boolean compare-and-set!]))
(defprotocol IAtomic
"A common abstraction for atomic types."
(compare-and-set! [_ v v'] "Perform the CAS operation.")
(get-and-set! [_ v] "Set a new value and return the previous one.")
(eventually-set! [_ v] "Eventually set a new value.")
(get [_] "Get the current value.")
(set! [_ v] "Set a new value."))
(defprotocol IAtomicNumber
"A common abstraction for number atomic types."
(get-and-add! [_ v] "Adds a delta and return the previous value.")
(get-and-dec! [_] "Decrements the value and return the previous one.")
(get-and-inc! [_] "Increments the value and returns the previous one.")
(dec-and-get! [_] "Decrements the value and return it.")
(inc-and-get! [_] "Increments the value and return it."))
(deftype AtomicLong [^java.util.concurrent.atomic.AtomicLong av]
IAtomicNumber
(get-and-add! [_ v]
(.getAndAdd av v))
(get-and-dec! [_]
(.getAndDecrement av))
(get-and-inc! [_]
(.getAndIncrement av))
(dec-and-get! [_]
(.decrementAndGet av))
(inc-and-get! [_]
(.incrementAndGet av))
IAtomic
(compare-and-set! [_ expected update]
(.compareAndSet av expected update))
(get-and-set! [_ v]
(.getAndSet av v))
(eventually-set! [_ v]
(.lazySet av v))
(get [_]
(.get av))
(set! [_ v]
(.set av v))
clojure.lang.IDeref
(deref [_]
(.get av)))
(deftype AtomicRef [^java.util.concurrent.atomic.AtomicReference av]
IAtomic
( compare-and-set! [_ expected update]
(.compareAndSet av expected update))
(get-and-set! [_ v]
(.getAndSet av v))
( eventually-set! [_ v]
(.lazySet av v))
(get [_]
(.get av))
(set! [_ v]
(.set av v))
clojure.lang.IDeref
(deref [_]
(.get av)))
(deftype AtomicBoolean [^java.util.concurrent.atomic.AtomicBoolean av]
IAtomic
(compare-and-set! [_ expected update]
(.compareAndSet av expected update))
(get-and-set! [_ v]
(.getAndSet av v))
(eventually-set! [_ v]
(.lazySet av v))
(get [_]
(.get av))
(set! [_ v]
(.set av v))
clojure.lang.IDeref
(deref [_]
(.get av)))
(alter-meta! #'->AtomicRef assoc :private true)
(alter-meta! #'->AtomicLong assoc :private true)
(alter-meta! #'->AtomicBoolean assoc :private true)
(defn long
"Create an instance of atomic long with optional
initial value. If it is not provided, `0` will be
the initial value."
([] (long 0))
([n]
(let [al (java.util.concurrent.atomic.AtomicLong. n)]
(AtomicLong. al))))
(defn ref
"Create an instance of atomic reference."
[v]
(let [ar (java.util.concurrent.atomic.AtomicReference. v)]
(AtomicRef. ar)))
(defn boolean
"Create an instance of atomic boolean."
[v]
(let [ar (java.util.concurrent.atomic.AtomicBoolean. v)]
(AtomicBoolean. ar)))
| true | ;; Copyright (c) 2015-2016 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions
;; are met:
;;
;; 1. Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; 2. Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
;; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
;; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
;; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
;; INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
;; NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
;; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
;; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(ns catacumba.impl.atomic
"A clojure idiomatic wrapper for JDK atomic types."
(:refer-clojure :exclude [set! get long ref boolean compare-and-set!]))
(defprotocol IAtomic
"A common abstraction for atomic types."
(compare-and-set! [_ v v'] "Perform the CAS operation.")
(get-and-set! [_ v] "Set a new value and return the previous one.")
(eventually-set! [_ v] "Eventually set a new value.")
(get [_] "Get the current value.")
(set! [_ v] "Set a new value."))
(defprotocol IAtomicNumber
"A common abstraction for number atomic types."
(get-and-add! [_ v] "Adds a delta and return the previous value.")
(get-and-dec! [_] "Decrements the value and return the previous one.")
(get-and-inc! [_] "Increments the value and returns the previous one.")
(dec-and-get! [_] "Decrements the value and return it.")
(inc-and-get! [_] "Increments the value and return it."))
(deftype AtomicLong [^java.util.concurrent.atomic.AtomicLong av]
IAtomicNumber
(get-and-add! [_ v]
(.getAndAdd av v))
(get-and-dec! [_]
(.getAndDecrement av))
(get-and-inc! [_]
(.getAndIncrement av))
(dec-and-get! [_]
(.decrementAndGet av))
(inc-and-get! [_]
(.incrementAndGet av))
IAtomic
(compare-and-set! [_ expected update]
(.compareAndSet av expected update))
(get-and-set! [_ v]
(.getAndSet av v))
(eventually-set! [_ v]
(.lazySet av v))
(get [_]
(.get av))
(set! [_ v]
(.set av v))
clojure.lang.IDeref
(deref [_]
(.get av)))
(deftype AtomicRef [^java.util.concurrent.atomic.AtomicReference av]
IAtomic
( compare-and-set! [_ expected update]
(.compareAndSet av expected update))
(get-and-set! [_ v]
(.getAndSet av v))
( eventually-set! [_ v]
(.lazySet av v))
(get [_]
(.get av))
(set! [_ v]
(.set av v))
clojure.lang.IDeref
(deref [_]
(.get av)))
(deftype AtomicBoolean [^java.util.concurrent.atomic.AtomicBoolean av]
IAtomic
(compare-and-set! [_ expected update]
(.compareAndSet av expected update))
(get-and-set! [_ v]
(.getAndSet av v))
(eventually-set! [_ v]
(.lazySet av v))
(get [_]
(.get av))
(set! [_ v]
(.set av v))
clojure.lang.IDeref
(deref [_]
(.get av)))
(alter-meta! #'->AtomicRef assoc :private true)
(alter-meta! #'->AtomicLong assoc :private true)
(alter-meta! #'->AtomicBoolean assoc :private true)
(defn long
"Create an instance of atomic long with optional
initial value. If it is not provided, `0` will be
the initial value."
([] (long 0))
([n]
(let [al (java.util.concurrent.atomic.AtomicLong. n)]
(AtomicLong. al))))
(defn ref
"Create an instance of atomic reference."
[v]
(let [ar (java.util.concurrent.atomic.AtomicReference. v)]
(AtomicRef. ar)))
(defn boolean
"Create an instance of atomic boolean."
[v]
(let [ar (java.util.concurrent.atomic.AtomicBoolean. v)]
(AtomicBoolean. ar)))
|
[
{
"context": " byte-spec defined in synthdef.clj.\"\n :author \"Jeff Rose\"}\n overtone.sc.synth\n (:use [overtone.util lib ",
"end": 327,
"score": 0.9998903870582581,
"start": 318,
"tag": "NAME",
"value": "Jeff Rose"
}
] | src/overtone/sc/synth.clj | rosejn/overtone | 4 | (ns
^{:doc "The ugen functions create a data structure representing a synthesizer
graph that can be executed on the synthesis server. This is the logic
to \"compile\" these clojure data structures into a form that can be
serialized by the byte-spec defined in synthdef.clj."
:author "Jeff Rose"}
overtone.sc.synth
(:use [overtone.util lib old-contrib]
[overtone.libs event counters]
[overtone.music time]
[overtone.sc.machinery.ugen fn-gen defaults common specs sc-ugen]
[overtone.sc.machinery synthdef]
[overtone.sc bindings ugens server node]
[overtone.helpers seq])
(:require [overtone.util.log :as log]
[clojure.set :as set]))
;; ### Synth
;;
;; A Synth is a collection of unit generators that run together. They can be
;; addressed and controlled by commands to the synthesis engine. They read
;; input and write output to global audio and control buses. Synths can have
;; their own local controls that are set via commands to the server.
(defn- ugen-index [ugens ugen]
(ffirst (filter (fn [[i v]]
(= (:id v) (:id ugen)))
(indexed ugens))))
; Gets the group number (source) and param index within the group (index)
; from the params that are grouped by rate like this:
;
;[[{:name :freq :default 440.0 :rate 1} {:name :amp :default 0.4 :rate 1}]
; [{:name :adfs :default 20.23 :rate 2} {:name :bar :default 8.6 :rate 2}]]
(defn- param-input-spec [grouped-params param-proxy]
(let [param-name (:name param-proxy)
ctl-filter (fn [[idx ctl]] (= param-name (:name ctl)))
[[src group] foo] (take 1 (filter
(fn [[src grp]]
(not (empty?
(filter ctl-filter (indexed grp)))))
(indexed grouped-params)))
[[idx param] bar] (take 1 (filter ctl-filter (indexed group)))]
(if (or (nil? src) (nil? idx))
(throw (IllegalArgumentException. (str "Invalid parameter name: " param-name ". Please make sure you have named all parameters in the param map in order to use them inside the synth definition."))))
{:src src :index idx}))
(defn- inputs-from-outputs [src src-ugen]
(for [i (range (count (:outputs src-ugen)))]
{:src src :index i}))
; NOTES:
; * *All* inputs must refer to either a constant or the output of another
; UGen that is higher up in the list.
(defn- with-inputs
"Returns ugen object with its input ports connected to constants and upstream
ugens according to the arguments in the initial definition."
[ugen ugens constants grouped-params]
(when-not (contains? ugen :args)
(throw (IllegalArgumentException.
(format "The %s ugen does not have any arguments."
(:name ugen)))))
(when-not (every? #(or (sc-ugen? %) (number? %) (string? %)) (:args ugen))
(throw (IllegalArgumentException.
(format "The %s ugen has an invalid argument: %s"
(:name ugen)
(first (filter
#(not (or (sc-ugen? %) (number? %)))
(:args ugen)))))))
; (println "with-inputs: " ugen)
(let [inputs (flatten
(map (fn [arg]
(cond
; constant
(number? arg)
{:src -1 :index (index-of constants (float arg))}
; control
(control-proxy? arg)
(param-input-spec grouped-params arg)
; output proxy
(output-proxy? arg)
(let [src (ugen-index ugens (:ugen arg))]
{:src src :index (:index arg)})
; child ugen
(sc-ugen? arg)
(let [src (ugen-index ugens arg)
updated-ugen (nth ugens src)]
;(println "child ugen: " arg)
;(println "src: " src)
(inputs-from-outputs src updated-ugen))))
(:args ugen)))
; _ (println "inputs: " inputs)
ugen (assoc ugen :inputs inputs)]
(when-not (every? (fn [{:keys [src index]}]
(and (not (nil? src))
(not (nil? index))))
(:inputs ugen))
(throw (Exception.
(format "Cannot connect ugen arguments for %s ugen with args: %s" (:name ugen) (str (seq (:args ugen)))))))
ugen))
; TODO: Currently the output rate is hard coded to be the same as the
; computation rate of the ugen. We probably need to have some meta-data
; capabilities for supporting varying output rates...
(defn- with-outputs
"Returns a ugen with its output port connections setup according to the spec."
[ugen]
{:post [(every? (fn [val] (not (nil? val))) (:outputs %))]}
(if (contains? ugen :outputs)
ugen
(let [spec (get-ugen (:name ugen))
num-outs (or (:n-outputs ugen) 1)
outputs (take num-outs (repeat {:rate (:rate ugen)}))]
(assoc ugen :outputs outputs))))
; IMPORTANT NOTE: We need to add outputs before inputs, so that multi-channel
; outputs can be correctly connected.
(defn- detail-ugens
"Fill in all the input and output specs for each ugen."
[ugens constants grouped-params]
(let [constants (map float constants)
outs (map with-outputs ugens)
ins (map #(with-inputs %1 outs constants grouped-params) outs)
final (map #(assoc %1 :args nil) ins)]
(doall final)))
(defn- make-control-ugens
"Controls are grouped by rate, so that a single Control ugen represents
each rate present in the params. The Control ugens are always the top nodes
in the graph, so they can be prepended to the topologically sorted tree.
Specifically handles control proxies at :tr, :ar, :kr and :ir"
[grouped-params]
(loop [done {}
todo grouped-params
offset 0]
(if (empty? todo)
(filter #(not (nil? %))
[(:ir done) (:tr done) (:ar done) (:kr done)])
(let [group (first todo)
group-rate (:rate (first group))
group-size (count group)
ctl-proxy (case group-rate
:tr (trig-control-ugen group-size offset)
:ar (audio-control-ugen group-size offset)
:kr (control-ugen group-size offset)
:ir (inst-control-ugen group-size offset))]
(recur (assoc done group-rate ctl-proxy) (rest todo) (+ offset group-size))))))
(defn- group-params
"Groups params by rate. Groups a list of parameters into a
list of lists, one per rate."
[params]
(let [by-rate (reduce (fn [mem param]
(let [rate (:rate param)
rate-group (get mem rate [])]
(assoc mem rate (conj rate-group param))))
{} params)]
(filter #(not (nil? %1))
[(:ir by-rate) (:tr by-rate) (:ar by-rate) (:kr by-rate)])))
(def DEFAULT-RATE :kr)
(defn- ensure-param-keys!
"throws an error if map m doesn't contain the correct keys: :name, :default and :rate"
[m]
(when-not (and
(contains? m :name)
(contains? m :default)
(contains? m :rate))
(throw (IllegalArgumentException. (str "Invalid synth param map. Expected to find the keys :name, :default, :rate, got: " m)))))
(defn- ensure-paired-params!
"throws an error if list l does not contain an even number of elements"
[l]
(when-not (even? (count l))
(throw (IllegalArgumentException. (str "A synth requires either an even number of arguments in the form [control default]* i.e. [freq 440 vol 0.5] or a list of maps. You passed " (count l) " args: " l)))))
(defn- ensure-vec!
"throws an error if list l is not a vector"
[l]
(when-not (vector? l)
(throw (IllegalArgumentException. (str "Your synth argument list is not a vector. Instead I found " (type l) ": " l)))))
(defn- mapify-params
"converts a list of param name val pairs to a param map. If the val of a param
is a vector, it assumes it's a pair of [val rate] and sets the rate of the
param accordingly. If the val is a plain number, it sets the rate to
DEFAULT-RATE. All names are converted to strings"
[params]
(for [[p-name p-val] (partition 2 params)]
(let [param-map
(if (associative? p-val)
(merge
{:name (str p-name)
:rate DEFAULT-RATE} p-val)
{:name (str p-name)
:default `(float ~p-val)
:rate DEFAULT-RATE})]
(ensure-param-keys! param-map)
param-map)))
(defn- stringify-names
"takes a map and converts the val of key :name to a string"
[m]
(into {} (for [[k v] m] (if (= :name k) [k (str v)] [k v]))))
;; TODO: Figure out a better way to specify rates for synth parameters
;; perhaps using name post-fixes such as [freq:kr 440]
(defn- parse-params
"Used by defsynth to parse the param list. Accepts either a vector of
name default pairs, name [default rate] pairs or a vector of maps:
(defsynth foo [freq 440] ...)
(defsynth foo [freq {:default 440 :rate :ar}] ...)
Returns a vec of param maps"
[params]
(ensure-vec! params)
(ensure-paired-params! params)
(vec (mapify-params params)))
(defn- make-params
"Create the param value vector and parameter name vector."
[grouped-params]
(let [param-list (flatten grouped-params)
pvals (map #(:default %1) param-list)
pnames (map (fn [[idx param]]
{:name (to-str (:name param))
:index idx})
(indexed param-list))]
[pvals pnames]))
(defn- ugen-form? [form]
(and (seq? form)
(= 'ugen (first form))))
(defn- fastest-rate [rates]
(REVERSE-RATES (first (reverse (sort (map RATES rates))))))
(defn- special-op-args? [args]
(some #(or (sc-ugen? %1) (keyword? %1)) args))
(defn- find-rate [args]
(fastest-rate (map #(cond
(sc-ugen? %1) (REVERSE-RATES (:rate %1))
(keyword? %1) :kr)
args)))
;; For greatest efficiency:
;;
;; * Unit generators should be listed in an order that permits efficient reuse
;; of connection buffers, so use a depth first topological sort of the graph.
; NOTES:
; * The ugen tree is turned into a ugen list that is sorted by the order in
; which nodes should be processed. (Depth first, starting at outermost leaf
; of the first branch.
;
; * params are sorted by rate, and then a Control ugen per rate is created
; and prepended to the ugen list
;
; * finally, ugen inputs are specified using their index
; in the sorted ugen list.
;
; * No feedback loops are allowed. Feedback must be accomplished via delay lines
; or through buses.
;
(defn synthdef
"Transforms a synth definition (ugen-graph) into a form that's ready to save
to disk or send to the server.
(synthdef \"pad-z\" [
"
[sname params ugens constants]
(let [grouped-params (group-params params)
[params pnames] (make-params grouped-params)
with-ctl-ugens (concat (make-control-ugens grouped-params) ugens)
detailed (detail-ugens with-ctl-ugens constants grouped-params)]
(with-meta {:name (str sname)
:constants constants
:params params
:pnames pnames
:ugens detailed}
{:type :overtone.sc.machinery.synthdef/synthdef})))
(defn- control-proxies
"Returns a list of param name symbols and control proxies"
[params]
(mapcat (fn [param] [(symbol (:name param))
`(control-proxy ~(:name param) ~(:default param) ~(:rate param))])
params))
(defn- gen-synth-name
"Auto generate an anonymous synth name. Intended for use in synths that have not
been defined with an explicit name. Has the form \"anon-id\" where id is a unique
integer across all anonymous synths."
[]
(str "anon-" (next-id ::anonymous-synth)))
(defn- id-able-type?
[o]
(or (isa? (type o) :overtone.sc.buffer/buffer)
(isa? (type o) :overtone.sc.sample/sample)
(isa? (type o) :overtone.sc.bus/audio-bus)
(isa? (type o) :overtone.sc.bus/control-bus)))
(defn normalize-synth-args
"Pull out and normalize the synth name, parameters, control proxies and the ugen form
from the supplied arglist resorting to defaults if necessary."
[args]
(let [[sname args] (cond
(or (string? (first args))
(symbol? (first args))) [(str (first args)) (rest args)]
:default [(gen-synth-name) args])
[params ugen-form] (if (vector? (first args))
[(first args) (rest args)]
[[] args])
param-proxies (control-proxies params)]
[sname params param-proxies ugen-form]))
(defn gather-ugens-and-constants
"Traverses a ugen tree and returns a vector of two sets [#{ugens} #{constants}]."
[root]
(if (seq? root)
(reduce
(fn [[ugens constants] ugen]
(let [[us cs] (gather-ugens-and-constants ugen)]
[(set/union ugens us)
(set/union constants cs)]))
[#{} #{}]
root)
(let [args (:args root)
cur-ugens (filter sc-ugen? args)
cur-ugens (filter (comp not control-proxy?) cur-ugens)
cur-ugens (map #(if (output-proxy? %)
(:ugen %)
%) cur-ugens)
cur-consts (filter number? args)
[child-ugens child-consts] (gather-ugens-and-constants cur-ugens)
ugens (conj (set child-ugens) root)
constants (set/union (set cur-consts) child-consts)]
[ugens (vec constants)])))
(defn- ugen-children
"Returns the children (arguments) of this ugen that are themselves upstream ugens."
[ug]
(mapcat
#(cond
(seq? %) %
(output-proxy? %) [(:ugen %)]
:default [%])
(filter
(fn [arg]
(and (not (control-proxy? arg))
(or (sc-ugen? arg)
(and (seq? arg)
(every? sc-ugen? arg)))))
(:args ug))))
(defn topological-sort-ugens
"Sort into a vector where each node in the directed graph of ugens will always
be preceded by its upstream dependencies."
[ugens]
(loop [ugens ugens
; start with leaf nodes that don't have any dependencies
leaves (set (filter (fn [ugen]
(every?
#(or (not (sc-ugen? %))
(control-proxy? %))
(:args ugen)))
ugens))
sorted-ugens []
rec-count 0]
;(println "\n------------\nugens: " ugens)
;(println "leaves: " leaves)
;(println "sorted-ugens: " sorted-ugens)
; bail out after 1000 iterations, either a bug in this code, or a bad synth graph
(when (= 1000 rec-count)
(throw (Exception. "Invalid ugen tree passed to topological-sort-ugens, maybe you have cycles in the synthdef...")))
(if (empty? leaves)
sorted-ugens
(let [last-ugen (last sorted-ugens)
; try to always place the downstream ugen from the last-ugen if all other
; deps are satisfied, which keeps internal buffers in cache as long as possible
next-ugen (first (filter #((set (ugen-children %)) last-ugen) leaves))
[next-ugen leaves] (if next-ugen
[next-ugen (disj leaves next-ugen)]
[(first leaves) (next leaves)])
;_ (println "next-ugen: " next-ugen)
sorted-ugens (conj sorted-ugens next-ugen)
sorted-ugen-set (set sorted-ugens)
ugens (set/difference ugens sorted-ugen-set leaves)
leaves (set
(reduce
(fn [rleaves ug]
(let [children (ugen-children ug)]
;(println ug ": " children)
(if (set/subset? children sorted-ugen-set)
(conj rleaves ug)
rleaves)))
leaves
ugens))]
(recur ugens leaves sorted-ugens (inc rec-count))))))
(comment
; Some test synths, while shaking out the bugs...
(defsynth foo [] (out 0 (rlpf (saw [220 663]) (x-line:kr 20000 2 1 FREE))))
(defsynth bar [freq 220] (out 0 (rlpf (saw [freq (* 3.013 freq)]) (x-line:kr 20000 2 1 FREE))))
(definst faz [] (rlpf (saw [220 663]) (x-line:kr 20000 2 1 FREE)))
(definst baz [freq 220] (rlpf (saw [freq (* 3.013 freq)]) (x-line:kr 20000 2 1 FREE)))
(run 1 (out 184 (saw (x-line:kr 10000 10 1 FREE))))
)
(defmacro pre-synth
"Resolve a synth def to a list of its name, params, ugens (nested if
necessary) and constants. Sets the lexical bindings of the param
names to control proxies within the synth definition"
[& args]
(let [[sname params param-proxies ugen-form] (normalize-synth-args args)]
`(let [~@param-proxies]
(binding [*ugens* []
*constants* #{}]
(let [[ugens# constants#] (gather-ugens-and-constants
(with-overloaded-ugens ~@ugen-form))
ugens# (topological-sort-ugens ugens#)
;; _# (println "main-tree[" (count ugens#) "]: " ugens#)
;; _# (println (str "*ugens*: [" (count *ugens*) "] " *ugens*))
main-tree# (set ugens#)
side-tree# (filter #(not (main-tree# %)) *ugens*)
;; _# (println "side-tree[" (count side-tree#) "]: " side-tree#)
ugens# (concat ugens# side-tree#)
constants# (into [] (set (concat constants# *constants*)))]
;; (println "all ugens[" (count ugens#) "]: " ugens#)
[~sname ~params ugens# constants#])))))
(defn synth-player
[name params this & args]
"Returns a player function for a named synth. Used by (synth ...)
internally, but can be used to generate a player for a pre-compiled
synth. The function generated will accept two optional arguments that
must come first, the :position and :target (see the node function docs).
(foo)
(foo :position :tail :target 0)
or if foo has two arguments:
(foo 440 0.3)
(foo :position :tail :target 0 440 0.3)
at the head of group 2:
(foo :position :head :target 2 440 0.3)
These can also be abbreviated:
(foo :tgt 2 :pos :head)
"
(let [arg-names (map keyword (map :name params))
args (if (and (= 1 (count args))
(map? (first args))
(not (id-able-type? (first args))))
(flatten (seq (first args)))
args)
[args sgroup] (if (or (= :target (first args))
(= :tgt (first args)))
[(drop 2 args) (second args)]
[args @synth-group*])
[args pos] (if (or (= :position (first args))
(= :pos (first args)))
[(drop 2 args) (second args)]
[args :tail])
[args sgroup] (if (or (= :target (first args))
(= :tgt (first args)))
[(drop 2 args) (second args)]
[args sgroup])
args (map #(if (id-able-type? %)
(:id %) %) args)
defaults (into {} (map (fn [{:keys [name value]}]
[(keyword name) @value])
params))
arg-map (arg-mapper args arg-names defaults)
synth-node (node name arg-map {:position pos :target sgroup })
synth-node (if (:instance-fn this)
((:instance-fn this) synth-node)
synth-node)]
(when (:instance-fn this)
(swap! active-synth-nodes* assoc (:id synth-node) synth-node))
synth-node))
(defrecord-ifn Synth [name ugens sdef args params instance-fn]
(partial synth-player name params))
(defn update-tap-data
[msg]
(let [[node-id label-id val] (:args msg)
node (get @active-synth-nodes* node-id)
label (get (:tap-labels node) label-id)
tap-atom (get (:taps node) label)]
(reset! tap-atom val)))
(on-event "/overtone/tap" #'update-tap-data ::handle-incoming-tap-data)
(defmacro synth
"Define a SuperCollider synthesizer using the library of ugen
functions provided by overtone.sc.ugen. This will return callable
record which can be used to trigger the synthesizer.
"
[& args]
`(let [[sname# params# ugens# constants#] (pre-synth ~@args)
sdef# (synthdef sname# params# ugens# constants#)
arg-names# (map :name params#)
params-with-vals# (map #(assoc % :value (atom (:default %))) params#)
instance-fn# (apply comp (map :instance-fn (filter :instance-fn (map meta ugens#))))
smap# (with-meta
(map->Synth
{:name sname#
:ugens ugens#
:sdef sdef#
:args arg-names#
:params params-with-vals#
:instance-fn instance-fn#})
{:overtone.util.live/to-string #(str (name (:type %)) ":" (:name %))})]
(load-synthdef sdef#)
(event :new-synth :synth smap#)
smap#))
(defn synth-form
"Internal function used to prepare synth meta-data."
[s-name s-form]
(let [[s-name s-form] (name-with-attributes s-name s-form)
_ (when (not (symbol? s-name))
(throw (IllegalArgumentException. (str "You need to specify a name for your synth using a symbol"))))
params (first s-form)
params (parse-params params)
ugen-form (concat '(do) (next s-form))
param-names (list (vec (map #(symbol (:name %)) params)))
md (assoc (meta s-name)
:name s-name
:type ::synth
:arglists (list 'quote param-names))]
[(with-meta s-name md) params ugen-form]))
(defmacro defsynth
"Define a synthesizer and return a player function. The synth definition
will be loaded immediately, and a :new-synth event will be emitted.
(defsynth foo [freq 440]
(sin-osc freq))
is equivalent to:
(def foo
(synth [freq 440] (sin-osc freq)))
A doc string can also be included:
(defsynth bar
\"The phatest space pad ever!\"
[] (...))
"
[s-name & s-form]
(let [[s-name params ugen-form] (synth-form s-name s-form)]
`(def ~s-name (synth ~s-name ~params ~ugen-form))))
(defn synth?
"Returns true if s is a synth, false otherwise."
[s]
(= overtone.sc.synth.Synth (type s)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Synthdef de-compilation
;; The eventual goal is to be able to take any SuperCollider scsyndef
;; file, and produce equivalent clojure code that can be re-edited.
(defn- param-vector [params pnames]
"Create a synthdef parameter vector."
(vec (flatten
(map #(list (symbol (:name %1))
(nth params (:index %1)))
pnames))))
(defn- ugen-form
"Create a ugen form."
[ug]
(let [uname (real-ugen-name ug)
ugen (get-ugen uname)
uname (if (and
(zero? (:special ug))
(not= (:rate-name ug) (:default-rate ugen)))
(str uname (:rate-name ug))
uname)
uname (symbol uname)]
(apply list uname (:inputs ug))))
(defn- ugen-constant-inputs
"Replace constant ugen inputs with the constant values."
[constants ug]
(assoc ug :inputs
(map
(fn [{:keys [src index] :as input}]
(if (= src -1)
(nth constants index)
input))
(:inputs ug))))
(defn- reverse-ugen-inputs
"Replace ugen inputs that are other ugens with their generated symbolic name."
[pnames ugens ug]
(assoc ug :inputs
(map
(fn [{:keys [src index] :as input}]
(if src
(let [u-in (nth ugens src)]
(if (= "Control" (:name u-in))
(nth pnames index)
(:sname (nth ugens src))))
input))
(:inputs ug))))
; In order to do this correctly is a big project because you also have to
; reverse the process of the various ugen modes. For example, you need
; to recognize the ugens that have array arguments which will be
; appended, and then you need to gather up the inputs and place them into
; an array at the correct argument location.
(defn synthdef-decompile
"Decompile a parsed SuperCollider synth definition back into clojure code
that could be used to generate an identical synth.
While this probably won't create a synth definition that can directly compile,
it can still be helpful when trying to reverse engineer a synth."
[{:keys [name constants params pnames ugens] :as sdef}]
(let [sname (symbol name)
param-vec (param-vector params pnames)
ugens (map #(assoc % :sname %2)
ugens
(map (comp symbol #(str "ug-" %) char) (range 97 200)))
ugens (map (partial ugen-constant-inputs constants) ugens)
pnames (map (comp symbol :name) pnames)
ugens (map (partial reverse-ugen-inputs pnames ugens) ugens)
ugens (filter #(not= "Control" (:name %)) ugens)
ugen-forms (map vector
(map :sname ugens)
(map ugen-form ugens))]
(print (format "(defsynth %s %s\n (let [" sname param-vec))
(println (ffirst ugen-forms) (second (first ugen-forms)))
(doseq [[uname uform] (drop 1 ugen-forms)]
(println " " uname uform))
(println (str " ]\n " (first (last ugen-forms)) ")"))))
(def ^{:dynamic true} *demo-time* 2000)
(defmacro run
"Run an anonymous synth definition for a fixed period of time. Useful for
experimentation. Does NOT add an out ugen - see #'demo for that. You can
specify a timeout in seconds as the first argument otherwise it defaults to
*demo-time* ms.
(run (send-reply (impulse 1) \"/foo\" [1] 43)) ;=> send OSC messages out"
[& body]
(let [[demo-time body] (if (number? (first body))
[(* 1000 (first body)) (second body)]
[*demo-time* (first body)])]
`(let [s# (synth "audition-synth" ~body)
note# (s#)]
(after-delay ~demo-time #(node-free note#))
note#)))
(defmacro demo
"Listen to an anonymous synth definition for a fixed period of time. Useful
for experimentation. If the root node is not an out ugen, then it will add
one automatically. You can specify a timeout in seconds as the first argument
otherwise it defaults to *demo-time* ms.
(demo (sin-osc 440)) ;=> plays a sine wave for *demo-time* ms
(demo 0.5 (sin-osc 440)) ;=> plays a sine wave for half a second"
[& body]
(let [[demo-time body] (if (number? (first body))
[(first body) (second body)]
[(* 0.001 *demo-time*) (first body)])
[out-bus body] (if (= 'out (first body))
[(second body) (nth body 2)]
[0 body])
body (list 'out out-bus (list 'hold body demo-time :done 'FREE))]
`((synth "audition-synth" ~body))))
(defn active-synths
"Return a seq of the actively running synth nodes. If a synth or inst are passed as the filter it will only return nodes of that type.
(active-synths) ; => [{:type synth :name \"mixer\" :id 12}
{:type synth :name \"my-synth\" :id 24}]
(active-synths my-synth) ; => [{:type synth :name \"my-synth\" :id 24}]
"
[& [synth-filter]]
(let [active-nodes (filter #(= overtone.sc.node.SynthNode (type %))
(vals @active-synth-nodes*))]
(if synth-filter
(filter #(= (:name synth-filter) (:name %)) active-nodes)
active-nodes)))
(defmethod print-method ::synth [syn w]
(let [info (meta syn)]
(.write w (format "#<synth: %s>" (:name info)))))
; TODO: pull out the default param atom stuff into a separate mechanism
(defn modify-synth-params
"Update synth parameter value atoms storing the current default settings."
[s & params-vals]
(let [params (:params s)]
(for [[param value] (partition 2 params-vals)]
(let [val-atom (:value (first (filter #(= (:name %) (name param)) params)))]
(if val-atom
(reset! val-atom value)
(throw (IllegalArgumentException. (str "Invalid control parameter: " param))))))))
(defn reset-synth-defaults
"Reset a synth to it's default settings defined at definition time."
[synth]
(doseq [param (:params synth)]
(reset! (:value param) (:default param))))
| 49940 | (ns
^{:doc "The ugen functions create a data structure representing a synthesizer
graph that can be executed on the synthesis server. This is the logic
to \"compile\" these clojure data structures into a form that can be
serialized by the byte-spec defined in synthdef.clj."
:author "<NAME>"}
overtone.sc.synth
(:use [overtone.util lib old-contrib]
[overtone.libs event counters]
[overtone.music time]
[overtone.sc.machinery.ugen fn-gen defaults common specs sc-ugen]
[overtone.sc.machinery synthdef]
[overtone.sc bindings ugens server node]
[overtone.helpers seq])
(:require [overtone.util.log :as log]
[clojure.set :as set]))
;; ### Synth
;;
;; A Synth is a collection of unit generators that run together. They can be
;; addressed and controlled by commands to the synthesis engine. They read
;; input and write output to global audio and control buses. Synths can have
;; their own local controls that are set via commands to the server.
(defn- ugen-index [ugens ugen]
(ffirst (filter (fn [[i v]]
(= (:id v) (:id ugen)))
(indexed ugens))))
; Gets the group number (source) and param index within the group (index)
; from the params that are grouped by rate like this:
;
;[[{:name :freq :default 440.0 :rate 1} {:name :amp :default 0.4 :rate 1}]
; [{:name :adfs :default 20.23 :rate 2} {:name :bar :default 8.6 :rate 2}]]
(defn- param-input-spec [grouped-params param-proxy]
(let [param-name (:name param-proxy)
ctl-filter (fn [[idx ctl]] (= param-name (:name ctl)))
[[src group] foo] (take 1 (filter
(fn [[src grp]]
(not (empty?
(filter ctl-filter (indexed grp)))))
(indexed grouped-params)))
[[idx param] bar] (take 1 (filter ctl-filter (indexed group)))]
(if (or (nil? src) (nil? idx))
(throw (IllegalArgumentException. (str "Invalid parameter name: " param-name ". Please make sure you have named all parameters in the param map in order to use them inside the synth definition."))))
{:src src :index idx}))
(defn- inputs-from-outputs [src src-ugen]
(for [i (range (count (:outputs src-ugen)))]
{:src src :index i}))
; NOTES:
; * *All* inputs must refer to either a constant or the output of another
; UGen that is higher up in the list.
(defn- with-inputs
"Returns ugen object with its input ports connected to constants and upstream
ugens according to the arguments in the initial definition."
[ugen ugens constants grouped-params]
(when-not (contains? ugen :args)
(throw (IllegalArgumentException.
(format "The %s ugen does not have any arguments."
(:name ugen)))))
(when-not (every? #(or (sc-ugen? %) (number? %) (string? %)) (:args ugen))
(throw (IllegalArgumentException.
(format "The %s ugen has an invalid argument: %s"
(:name ugen)
(first (filter
#(not (or (sc-ugen? %) (number? %)))
(:args ugen)))))))
; (println "with-inputs: " ugen)
(let [inputs (flatten
(map (fn [arg]
(cond
; constant
(number? arg)
{:src -1 :index (index-of constants (float arg))}
; control
(control-proxy? arg)
(param-input-spec grouped-params arg)
; output proxy
(output-proxy? arg)
(let [src (ugen-index ugens (:ugen arg))]
{:src src :index (:index arg)})
; child ugen
(sc-ugen? arg)
(let [src (ugen-index ugens arg)
updated-ugen (nth ugens src)]
;(println "child ugen: " arg)
;(println "src: " src)
(inputs-from-outputs src updated-ugen))))
(:args ugen)))
; _ (println "inputs: " inputs)
ugen (assoc ugen :inputs inputs)]
(when-not (every? (fn [{:keys [src index]}]
(and (not (nil? src))
(not (nil? index))))
(:inputs ugen))
(throw (Exception.
(format "Cannot connect ugen arguments for %s ugen with args: %s" (:name ugen) (str (seq (:args ugen)))))))
ugen))
; TODO: Currently the output rate is hard coded to be the same as the
; computation rate of the ugen. We probably need to have some meta-data
; capabilities for supporting varying output rates...
(defn- with-outputs
"Returns a ugen with its output port connections setup according to the spec."
[ugen]
{:post [(every? (fn [val] (not (nil? val))) (:outputs %))]}
(if (contains? ugen :outputs)
ugen
(let [spec (get-ugen (:name ugen))
num-outs (or (:n-outputs ugen) 1)
outputs (take num-outs (repeat {:rate (:rate ugen)}))]
(assoc ugen :outputs outputs))))
; IMPORTANT NOTE: We need to add outputs before inputs, so that multi-channel
; outputs can be correctly connected.
(defn- detail-ugens
"Fill in all the input and output specs for each ugen."
[ugens constants grouped-params]
(let [constants (map float constants)
outs (map with-outputs ugens)
ins (map #(with-inputs %1 outs constants grouped-params) outs)
final (map #(assoc %1 :args nil) ins)]
(doall final)))
(defn- make-control-ugens
"Controls are grouped by rate, so that a single Control ugen represents
each rate present in the params. The Control ugens are always the top nodes
in the graph, so they can be prepended to the topologically sorted tree.
Specifically handles control proxies at :tr, :ar, :kr and :ir"
[grouped-params]
(loop [done {}
todo grouped-params
offset 0]
(if (empty? todo)
(filter #(not (nil? %))
[(:ir done) (:tr done) (:ar done) (:kr done)])
(let [group (first todo)
group-rate (:rate (first group))
group-size (count group)
ctl-proxy (case group-rate
:tr (trig-control-ugen group-size offset)
:ar (audio-control-ugen group-size offset)
:kr (control-ugen group-size offset)
:ir (inst-control-ugen group-size offset))]
(recur (assoc done group-rate ctl-proxy) (rest todo) (+ offset group-size))))))
(defn- group-params
"Groups params by rate. Groups a list of parameters into a
list of lists, one per rate."
[params]
(let [by-rate (reduce (fn [mem param]
(let [rate (:rate param)
rate-group (get mem rate [])]
(assoc mem rate (conj rate-group param))))
{} params)]
(filter #(not (nil? %1))
[(:ir by-rate) (:tr by-rate) (:ar by-rate) (:kr by-rate)])))
(def DEFAULT-RATE :kr)
(defn- ensure-param-keys!
"throws an error if map m doesn't contain the correct keys: :name, :default and :rate"
[m]
(when-not (and
(contains? m :name)
(contains? m :default)
(contains? m :rate))
(throw (IllegalArgumentException. (str "Invalid synth param map. Expected to find the keys :name, :default, :rate, got: " m)))))
(defn- ensure-paired-params!
"throws an error if list l does not contain an even number of elements"
[l]
(when-not (even? (count l))
(throw (IllegalArgumentException. (str "A synth requires either an even number of arguments in the form [control default]* i.e. [freq 440 vol 0.5] or a list of maps. You passed " (count l) " args: " l)))))
(defn- ensure-vec!
"throws an error if list l is not a vector"
[l]
(when-not (vector? l)
(throw (IllegalArgumentException. (str "Your synth argument list is not a vector. Instead I found " (type l) ": " l)))))
(defn- mapify-params
"converts a list of param name val pairs to a param map. If the val of a param
is a vector, it assumes it's a pair of [val rate] and sets the rate of the
param accordingly. If the val is a plain number, it sets the rate to
DEFAULT-RATE. All names are converted to strings"
[params]
(for [[p-name p-val] (partition 2 params)]
(let [param-map
(if (associative? p-val)
(merge
{:name (str p-name)
:rate DEFAULT-RATE} p-val)
{:name (str p-name)
:default `(float ~p-val)
:rate DEFAULT-RATE})]
(ensure-param-keys! param-map)
param-map)))
(defn- stringify-names
"takes a map and converts the val of key :name to a string"
[m]
(into {} (for [[k v] m] (if (= :name k) [k (str v)] [k v]))))
;; TODO: Figure out a better way to specify rates for synth parameters
;; perhaps using name post-fixes such as [freq:kr 440]
(defn- parse-params
"Used by defsynth to parse the param list. Accepts either a vector of
name default pairs, name [default rate] pairs or a vector of maps:
(defsynth foo [freq 440] ...)
(defsynth foo [freq {:default 440 :rate :ar}] ...)
Returns a vec of param maps"
[params]
(ensure-vec! params)
(ensure-paired-params! params)
(vec (mapify-params params)))
(defn- make-params
"Create the param value vector and parameter name vector."
[grouped-params]
(let [param-list (flatten grouped-params)
pvals (map #(:default %1) param-list)
pnames (map (fn [[idx param]]
{:name (to-str (:name param))
:index idx})
(indexed param-list))]
[pvals pnames]))
(defn- ugen-form? [form]
(and (seq? form)
(= 'ugen (first form))))
(defn- fastest-rate [rates]
(REVERSE-RATES (first (reverse (sort (map RATES rates))))))
(defn- special-op-args? [args]
(some #(or (sc-ugen? %1) (keyword? %1)) args))
(defn- find-rate [args]
(fastest-rate (map #(cond
(sc-ugen? %1) (REVERSE-RATES (:rate %1))
(keyword? %1) :kr)
args)))
;; For greatest efficiency:
;;
;; * Unit generators should be listed in an order that permits efficient reuse
;; of connection buffers, so use a depth first topological sort of the graph.
; NOTES:
; * The ugen tree is turned into a ugen list that is sorted by the order in
; which nodes should be processed. (Depth first, starting at outermost leaf
; of the first branch.
;
; * params are sorted by rate, and then a Control ugen per rate is created
; and prepended to the ugen list
;
; * finally, ugen inputs are specified using their index
; in the sorted ugen list.
;
; * No feedback loops are allowed. Feedback must be accomplished via delay lines
; or through buses.
;
(defn synthdef
"Transforms a synth definition (ugen-graph) into a form that's ready to save
to disk or send to the server.
(synthdef \"pad-z\" [
"
[sname params ugens constants]
(let [grouped-params (group-params params)
[params pnames] (make-params grouped-params)
with-ctl-ugens (concat (make-control-ugens grouped-params) ugens)
detailed (detail-ugens with-ctl-ugens constants grouped-params)]
(with-meta {:name (str sname)
:constants constants
:params params
:pnames pnames
:ugens detailed}
{:type :overtone.sc.machinery.synthdef/synthdef})))
(defn- control-proxies
"Returns a list of param name symbols and control proxies"
[params]
(mapcat (fn [param] [(symbol (:name param))
`(control-proxy ~(:name param) ~(:default param) ~(:rate param))])
params))
(defn- gen-synth-name
"Auto generate an anonymous synth name. Intended for use in synths that have not
been defined with an explicit name. Has the form \"anon-id\" where id is a unique
integer across all anonymous synths."
[]
(str "anon-" (next-id ::anonymous-synth)))
(defn- id-able-type?
[o]
(or (isa? (type o) :overtone.sc.buffer/buffer)
(isa? (type o) :overtone.sc.sample/sample)
(isa? (type o) :overtone.sc.bus/audio-bus)
(isa? (type o) :overtone.sc.bus/control-bus)))
(defn normalize-synth-args
"Pull out and normalize the synth name, parameters, control proxies and the ugen form
from the supplied arglist resorting to defaults if necessary."
[args]
(let [[sname args] (cond
(or (string? (first args))
(symbol? (first args))) [(str (first args)) (rest args)]
:default [(gen-synth-name) args])
[params ugen-form] (if (vector? (first args))
[(first args) (rest args)]
[[] args])
param-proxies (control-proxies params)]
[sname params param-proxies ugen-form]))
(defn gather-ugens-and-constants
"Traverses a ugen tree and returns a vector of two sets [#{ugens} #{constants}]."
[root]
(if (seq? root)
(reduce
(fn [[ugens constants] ugen]
(let [[us cs] (gather-ugens-and-constants ugen)]
[(set/union ugens us)
(set/union constants cs)]))
[#{} #{}]
root)
(let [args (:args root)
cur-ugens (filter sc-ugen? args)
cur-ugens (filter (comp not control-proxy?) cur-ugens)
cur-ugens (map #(if (output-proxy? %)
(:ugen %)
%) cur-ugens)
cur-consts (filter number? args)
[child-ugens child-consts] (gather-ugens-and-constants cur-ugens)
ugens (conj (set child-ugens) root)
constants (set/union (set cur-consts) child-consts)]
[ugens (vec constants)])))
(defn- ugen-children
"Returns the children (arguments) of this ugen that are themselves upstream ugens."
[ug]
(mapcat
#(cond
(seq? %) %
(output-proxy? %) [(:ugen %)]
:default [%])
(filter
(fn [arg]
(and (not (control-proxy? arg))
(or (sc-ugen? arg)
(and (seq? arg)
(every? sc-ugen? arg)))))
(:args ug))))
(defn topological-sort-ugens
"Sort into a vector where each node in the directed graph of ugens will always
be preceded by its upstream dependencies."
[ugens]
(loop [ugens ugens
; start with leaf nodes that don't have any dependencies
leaves (set (filter (fn [ugen]
(every?
#(or (not (sc-ugen? %))
(control-proxy? %))
(:args ugen)))
ugens))
sorted-ugens []
rec-count 0]
;(println "\n------------\nugens: " ugens)
;(println "leaves: " leaves)
;(println "sorted-ugens: " sorted-ugens)
; bail out after 1000 iterations, either a bug in this code, or a bad synth graph
(when (= 1000 rec-count)
(throw (Exception. "Invalid ugen tree passed to topological-sort-ugens, maybe you have cycles in the synthdef...")))
(if (empty? leaves)
sorted-ugens
(let [last-ugen (last sorted-ugens)
; try to always place the downstream ugen from the last-ugen if all other
; deps are satisfied, which keeps internal buffers in cache as long as possible
next-ugen (first (filter #((set (ugen-children %)) last-ugen) leaves))
[next-ugen leaves] (if next-ugen
[next-ugen (disj leaves next-ugen)]
[(first leaves) (next leaves)])
;_ (println "next-ugen: " next-ugen)
sorted-ugens (conj sorted-ugens next-ugen)
sorted-ugen-set (set sorted-ugens)
ugens (set/difference ugens sorted-ugen-set leaves)
leaves (set
(reduce
(fn [rleaves ug]
(let [children (ugen-children ug)]
;(println ug ": " children)
(if (set/subset? children sorted-ugen-set)
(conj rleaves ug)
rleaves)))
leaves
ugens))]
(recur ugens leaves sorted-ugens (inc rec-count))))))
(comment
; Some test synths, while shaking out the bugs...
(defsynth foo [] (out 0 (rlpf (saw [220 663]) (x-line:kr 20000 2 1 FREE))))
(defsynth bar [freq 220] (out 0 (rlpf (saw [freq (* 3.013 freq)]) (x-line:kr 20000 2 1 FREE))))
(definst faz [] (rlpf (saw [220 663]) (x-line:kr 20000 2 1 FREE)))
(definst baz [freq 220] (rlpf (saw [freq (* 3.013 freq)]) (x-line:kr 20000 2 1 FREE)))
(run 1 (out 184 (saw (x-line:kr 10000 10 1 FREE))))
)
(defmacro pre-synth
"Resolve a synth def to a list of its name, params, ugens (nested if
necessary) and constants. Sets the lexical bindings of the param
names to control proxies within the synth definition"
[& args]
(let [[sname params param-proxies ugen-form] (normalize-synth-args args)]
`(let [~@param-proxies]
(binding [*ugens* []
*constants* #{}]
(let [[ugens# constants#] (gather-ugens-and-constants
(with-overloaded-ugens ~@ugen-form))
ugens# (topological-sort-ugens ugens#)
;; _# (println "main-tree[" (count ugens#) "]: " ugens#)
;; _# (println (str "*ugens*: [" (count *ugens*) "] " *ugens*))
main-tree# (set ugens#)
side-tree# (filter #(not (main-tree# %)) *ugens*)
;; _# (println "side-tree[" (count side-tree#) "]: " side-tree#)
ugens# (concat ugens# side-tree#)
constants# (into [] (set (concat constants# *constants*)))]
;; (println "all ugens[" (count ugens#) "]: " ugens#)
[~sname ~params ugens# constants#])))))
(defn synth-player
[name params this & args]
"Returns a player function for a named synth. Used by (synth ...)
internally, but can be used to generate a player for a pre-compiled
synth. The function generated will accept two optional arguments that
must come first, the :position and :target (see the node function docs).
(foo)
(foo :position :tail :target 0)
or if foo has two arguments:
(foo 440 0.3)
(foo :position :tail :target 0 440 0.3)
at the head of group 2:
(foo :position :head :target 2 440 0.3)
These can also be abbreviated:
(foo :tgt 2 :pos :head)
"
(let [arg-names (map keyword (map :name params))
args (if (and (= 1 (count args))
(map? (first args))
(not (id-able-type? (first args))))
(flatten (seq (first args)))
args)
[args sgroup] (if (or (= :target (first args))
(= :tgt (first args)))
[(drop 2 args) (second args)]
[args @synth-group*])
[args pos] (if (or (= :position (first args))
(= :pos (first args)))
[(drop 2 args) (second args)]
[args :tail])
[args sgroup] (if (or (= :target (first args))
(= :tgt (first args)))
[(drop 2 args) (second args)]
[args sgroup])
args (map #(if (id-able-type? %)
(:id %) %) args)
defaults (into {} (map (fn [{:keys [name value]}]
[(keyword name) @value])
params))
arg-map (arg-mapper args arg-names defaults)
synth-node (node name arg-map {:position pos :target sgroup })
synth-node (if (:instance-fn this)
((:instance-fn this) synth-node)
synth-node)]
(when (:instance-fn this)
(swap! active-synth-nodes* assoc (:id synth-node) synth-node))
synth-node))
(defrecord-ifn Synth [name ugens sdef args params instance-fn]
(partial synth-player name params))
(defn update-tap-data
[msg]
(let [[node-id label-id val] (:args msg)
node (get @active-synth-nodes* node-id)
label (get (:tap-labels node) label-id)
tap-atom (get (:taps node) label)]
(reset! tap-atom val)))
(on-event "/overtone/tap" #'update-tap-data ::handle-incoming-tap-data)
(defmacro synth
"Define a SuperCollider synthesizer using the library of ugen
functions provided by overtone.sc.ugen. This will return callable
record which can be used to trigger the synthesizer.
"
[& args]
`(let [[sname# params# ugens# constants#] (pre-synth ~@args)
sdef# (synthdef sname# params# ugens# constants#)
arg-names# (map :name params#)
params-with-vals# (map #(assoc % :value (atom (:default %))) params#)
instance-fn# (apply comp (map :instance-fn (filter :instance-fn (map meta ugens#))))
smap# (with-meta
(map->Synth
{:name sname#
:ugens ugens#
:sdef sdef#
:args arg-names#
:params params-with-vals#
:instance-fn instance-fn#})
{:overtone.util.live/to-string #(str (name (:type %)) ":" (:name %))})]
(load-synthdef sdef#)
(event :new-synth :synth smap#)
smap#))
(defn synth-form
"Internal function used to prepare synth meta-data."
[s-name s-form]
(let [[s-name s-form] (name-with-attributes s-name s-form)
_ (when (not (symbol? s-name))
(throw (IllegalArgumentException. (str "You need to specify a name for your synth using a symbol"))))
params (first s-form)
params (parse-params params)
ugen-form (concat '(do) (next s-form))
param-names (list (vec (map #(symbol (:name %)) params)))
md (assoc (meta s-name)
:name s-name
:type ::synth
:arglists (list 'quote param-names))]
[(with-meta s-name md) params ugen-form]))
(defmacro defsynth
"Define a synthesizer and return a player function. The synth definition
will be loaded immediately, and a :new-synth event will be emitted.
(defsynth foo [freq 440]
(sin-osc freq))
is equivalent to:
(def foo
(synth [freq 440] (sin-osc freq)))
A doc string can also be included:
(defsynth bar
\"The phatest space pad ever!\"
[] (...))
"
[s-name & s-form]
(let [[s-name params ugen-form] (synth-form s-name s-form)]
`(def ~s-name (synth ~s-name ~params ~ugen-form))))
(defn synth?
"Returns true if s is a synth, false otherwise."
[s]
(= overtone.sc.synth.Synth (type s)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Synthdef de-compilation
;; The eventual goal is to be able to take any SuperCollider scsyndef
;; file, and produce equivalent clojure code that can be re-edited.
(defn- param-vector [params pnames]
"Create a synthdef parameter vector."
(vec (flatten
(map #(list (symbol (:name %1))
(nth params (:index %1)))
pnames))))
(defn- ugen-form
"Create a ugen form."
[ug]
(let [uname (real-ugen-name ug)
ugen (get-ugen uname)
uname (if (and
(zero? (:special ug))
(not= (:rate-name ug) (:default-rate ugen)))
(str uname (:rate-name ug))
uname)
uname (symbol uname)]
(apply list uname (:inputs ug))))
(defn- ugen-constant-inputs
"Replace constant ugen inputs with the constant values."
[constants ug]
(assoc ug :inputs
(map
(fn [{:keys [src index] :as input}]
(if (= src -1)
(nth constants index)
input))
(:inputs ug))))
(defn- reverse-ugen-inputs
"Replace ugen inputs that are other ugens with their generated symbolic name."
[pnames ugens ug]
(assoc ug :inputs
(map
(fn [{:keys [src index] :as input}]
(if src
(let [u-in (nth ugens src)]
(if (= "Control" (:name u-in))
(nth pnames index)
(:sname (nth ugens src))))
input))
(:inputs ug))))
; In order to do this correctly is a big project because you also have to
; reverse the process of the various ugen modes. For example, you need
; to recognize the ugens that have array arguments which will be
; appended, and then you need to gather up the inputs and place them into
; an array at the correct argument location.
(defn synthdef-decompile
"Decompile a parsed SuperCollider synth definition back into clojure code
that could be used to generate an identical synth.
While this probably won't create a synth definition that can directly compile,
it can still be helpful when trying to reverse engineer a synth."
[{:keys [name constants params pnames ugens] :as sdef}]
(let [sname (symbol name)
param-vec (param-vector params pnames)
ugens (map #(assoc % :sname %2)
ugens
(map (comp symbol #(str "ug-" %) char) (range 97 200)))
ugens (map (partial ugen-constant-inputs constants) ugens)
pnames (map (comp symbol :name) pnames)
ugens (map (partial reverse-ugen-inputs pnames ugens) ugens)
ugens (filter #(not= "Control" (:name %)) ugens)
ugen-forms (map vector
(map :sname ugens)
(map ugen-form ugens))]
(print (format "(defsynth %s %s\n (let [" sname param-vec))
(println (ffirst ugen-forms) (second (first ugen-forms)))
(doseq [[uname uform] (drop 1 ugen-forms)]
(println " " uname uform))
(println (str " ]\n " (first (last ugen-forms)) ")"))))
(def ^{:dynamic true} *demo-time* 2000)
(defmacro run
"Run an anonymous synth definition for a fixed period of time. Useful for
experimentation. Does NOT add an out ugen - see #'demo for that. You can
specify a timeout in seconds as the first argument otherwise it defaults to
*demo-time* ms.
(run (send-reply (impulse 1) \"/foo\" [1] 43)) ;=> send OSC messages out"
[& body]
(let [[demo-time body] (if (number? (first body))
[(* 1000 (first body)) (second body)]
[*demo-time* (first body)])]
`(let [s# (synth "audition-synth" ~body)
note# (s#)]
(after-delay ~demo-time #(node-free note#))
note#)))
(defmacro demo
"Listen to an anonymous synth definition for a fixed period of time. Useful
for experimentation. If the root node is not an out ugen, then it will add
one automatically. You can specify a timeout in seconds as the first argument
otherwise it defaults to *demo-time* ms.
(demo (sin-osc 440)) ;=> plays a sine wave for *demo-time* ms
(demo 0.5 (sin-osc 440)) ;=> plays a sine wave for half a second"
[& body]
(let [[demo-time body] (if (number? (first body))
[(first body) (second body)]
[(* 0.001 *demo-time*) (first body)])
[out-bus body] (if (= 'out (first body))
[(second body) (nth body 2)]
[0 body])
body (list 'out out-bus (list 'hold body demo-time :done 'FREE))]
`((synth "audition-synth" ~body))))
(defn active-synths
"Return a seq of the actively running synth nodes. If a synth or inst are passed as the filter it will only return nodes of that type.
(active-synths) ; => [{:type synth :name \"mixer\" :id 12}
{:type synth :name \"my-synth\" :id 24}]
(active-synths my-synth) ; => [{:type synth :name \"my-synth\" :id 24}]
"
[& [synth-filter]]
(let [active-nodes (filter #(= overtone.sc.node.SynthNode (type %))
(vals @active-synth-nodes*))]
(if synth-filter
(filter #(= (:name synth-filter) (:name %)) active-nodes)
active-nodes)))
(defmethod print-method ::synth [syn w]
(let [info (meta syn)]
(.write w (format "#<synth: %s>" (:name info)))))
; TODO: pull out the default param atom stuff into a separate mechanism
(defn modify-synth-params
"Update synth parameter value atoms storing the current default settings."
[s & params-vals]
(let [params (:params s)]
(for [[param value] (partition 2 params-vals)]
(let [val-atom (:value (first (filter #(= (:name %) (name param)) params)))]
(if val-atom
(reset! val-atom value)
(throw (IllegalArgumentException. (str "Invalid control parameter: " param))))))))
(defn reset-synth-defaults
"Reset a synth to it's default settings defined at definition time."
[synth]
(doseq [param (:params synth)]
(reset! (:value param) (:default param))))
| true | (ns
^{:doc "The ugen functions create a data structure representing a synthesizer
graph that can be executed on the synthesis server. This is the logic
to \"compile\" these clojure data structures into a form that can be
serialized by the byte-spec defined in synthdef.clj."
:author "PI:NAME:<NAME>END_PI"}
overtone.sc.synth
(:use [overtone.util lib old-contrib]
[overtone.libs event counters]
[overtone.music time]
[overtone.sc.machinery.ugen fn-gen defaults common specs sc-ugen]
[overtone.sc.machinery synthdef]
[overtone.sc bindings ugens server node]
[overtone.helpers seq])
(:require [overtone.util.log :as log]
[clojure.set :as set]))
;; ### Synth
;;
;; A Synth is a collection of unit generators that run together. They can be
;; addressed and controlled by commands to the synthesis engine. They read
;; input and write output to global audio and control buses. Synths can have
;; their own local controls that are set via commands to the server.
(defn- ugen-index [ugens ugen]
(ffirst (filter (fn [[i v]]
(= (:id v) (:id ugen)))
(indexed ugens))))
; Gets the group number (source) and param index within the group (index)
; from the params that are grouped by rate like this:
;
;[[{:name :freq :default 440.0 :rate 1} {:name :amp :default 0.4 :rate 1}]
; [{:name :adfs :default 20.23 :rate 2} {:name :bar :default 8.6 :rate 2}]]
(defn- param-input-spec [grouped-params param-proxy]
(let [param-name (:name param-proxy)
ctl-filter (fn [[idx ctl]] (= param-name (:name ctl)))
[[src group] foo] (take 1 (filter
(fn [[src grp]]
(not (empty?
(filter ctl-filter (indexed grp)))))
(indexed grouped-params)))
[[idx param] bar] (take 1 (filter ctl-filter (indexed group)))]
(if (or (nil? src) (nil? idx))
(throw (IllegalArgumentException. (str "Invalid parameter name: " param-name ". Please make sure you have named all parameters in the param map in order to use them inside the synth definition."))))
{:src src :index idx}))
(defn- inputs-from-outputs [src src-ugen]
(for [i (range (count (:outputs src-ugen)))]
{:src src :index i}))
; NOTES:
; * *All* inputs must refer to either a constant or the output of another
; UGen that is higher up in the list.
(defn- with-inputs
"Returns ugen object with its input ports connected to constants and upstream
ugens according to the arguments in the initial definition."
[ugen ugens constants grouped-params]
(when-not (contains? ugen :args)
(throw (IllegalArgumentException.
(format "The %s ugen does not have any arguments."
(:name ugen)))))
(when-not (every? #(or (sc-ugen? %) (number? %) (string? %)) (:args ugen))
(throw (IllegalArgumentException.
(format "The %s ugen has an invalid argument: %s"
(:name ugen)
(first (filter
#(not (or (sc-ugen? %) (number? %)))
(:args ugen)))))))
; (println "with-inputs: " ugen)
(let [inputs (flatten
(map (fn [arg]
(cond
; constant
(number? arg)
{:src -1 :index (index-of constants (float arg))}
; control
(control-proxy? arg)
(param-input-spec grouped-params arg)
; output proxy
(output-proxy? arg)
(let [src (ugen-index ugens (:ugen arg))]
{:src src :index (:index arg)})
; child ugen
(sc-ugen? arg)
(let [src (ugen-index ugens arg)
updated-ugen (nth ugens src)]
;(println "child ugen: " arg)
;(println "src: " src)
(inputs-from-outputs src updated-ugen))))
(:args ugen)))
; _ (println "inputs: " inputs)
ugen (assoc ugen :inputs inputs)]
(when-not (every? (fn [{:keys [src index]}]
(and (not (nil? src))
(not (nil? index))))
(:inputs ugen))
(throw (Exception.
(format "Cannot connect ugen arguments for %s ugen with args: %s" (:name ugen) (str (seq (:args ugen)))))))
ugen))
; TODO: Currently the output rate is hard coded to be the same as the
; computation rate of the ugen. We probably need to have some meta-data
; capabilities for supporting varying output rates...
(defn- with-outputs
"Returns a ugen with its output port connections setup according to the spec."
[ugen]
{:post [(every? (fn [val] (not (nil? val))) (:outputs %))]}
(if (contains? ugen :outputs)
ugen
(let [spec (get-ugen (:name ugen))
num-outs (or (:n-outputs ugen) 1)
outputs (take num-outs (repeat {:rate (:rate ugen)}))]
(assoc ugen :outputs outputs))))
; IMPORTANT NOTE: We need to add outputs before inputs, so that multi-channel
; outputs can be correctly connected.
(defn- detail-ugens
"Fill in all the input and output specs for each ugen."
[ugens constants grouped-params]
(let [constants (map float constants)
outs (map with-outputs ugens)
ins (map #(with-inputs %1 outs constants grouped-params) outs)
final (map #(assoc %1 :args nil) ins)]
(doall final)))
(defn- make-control-ugens
"Controls are grouped by rate, so that a single Control ugen represents
each rate present in the params. The Control ugens are always the top nodes
in the graph, so they can be prepended to the topologically sorted tree.
Specifically handles control proxies at :tr, :ar, :kr and :ir"
[grouped-params]
(loop [done {}
todo grouped-params
offset 0]
(if (empty? todo)
(filter #(not (nil? %))
[(:ir done) (:tr done) (:ar done) (:kr done)])
(let [group (first todo)
group-rate (:rate (first group))
group-size (count group)
ctl-proxy (case group-rate
:tr (trig-control-ugen group-size offset)
:ar (audio-control-ugen group-size offset)
:kr (control-ugen group-size offset)
:ir (inst-control-ugen group-size offset))]
(recur (assoc done group-rate ctl-proxy) (rest todo) (+ offset group-size))))))
(defn- group-params
"Groups params by rate. Groups a list of parameters into a
list of lists, one per rate."
[params]
(let [by-rate (reduce (fn [mem param]
(let [rate (:rate param)
rate-group (get mem rate [])]
(assoc mem rate (conj rate-group param))))
{} params)]
(filter #(not (nil? %1))
[(:ir by-rate) (:tr by-rate) (:ar by-rate) (:kr by-rate)])))
(def DEFAULT-RATE :kr)
(defn- ensure-param-keys!
"throws an error if map m doesn't contain the correct keys: :name, :default and :rate"
[m]
(when-not (and
(contains? m :name)
(contains? m :default)
(contains? m :rate))
(throw (IllegalArgumentException. (str "Invalid synth param map. Expected to find the keys :name, :default, :rate, got: " m)))))
(defn- ensure-paired-params!
"throws an error if list l does not contain an even number of elements"
[l]
(when-not (even? (count l))
(throw (IllegalArgumentException. (str "A synth requires either an even number of arguments in the form [control default]* i.e. [freq 440 vol 0.5] or a list of maps. You passed " (count l) " args: " l)))))
(defn- ensure-vec!
"throws an error if list l is not a vector"
[l]
(when-not (vector? l)
(throw (IllegalArgumentException. (str "Your synth argument list is not a vector. Instead I found " (type l) ": " l)))))
(defn- mapify-params
"converts a list of param name val pairs to a param map. If the val of a param
is a vector, it assumes it's a pair of [val rate] and sets the rate of the
param accordingly. If the val is a plain number, it sets the rate to
DEFAULT-RATE. All names are converted to strings"
[params]
(for [[p-name p-val] (partition 2 params)]
(let [param-map
(if (associative? p-val)
(merge
{:name (str p-name)
:rate DEFAULT-RATE} p-val)
{:name (str p-name)
:default `(float ~p-val)
:rate DEFAULT-RATE})]
(ensure-param-keys! param-map)
param-map)))
(defn- stringify-names
"takes a map and converts the val of key :name to a string"
[m]
(into {} (for [[k v] m] (if (= :name k) [k (str v)] [k v]))))
;; TODO: Figure out a better way to specify rates for synth parameters
;; perhaps using name post-fixes such as [freq:kr 440]
(defn- parse-params
"Used by defsynth to parse the param list. Accepts either a vector of
name default pairs, name [default rate] pairs or a vector of maps:
(defsynth foo [freq 440] ...)
(defsynth foo [freq {:default 440 :rate :ar}] ...)
Returns a vec of param maps"
[params]
(ensure-vec! params)
(ensure-paired-params! params)
(vec (mapify-params params)))
(defn- make-params
"Create the param value vector and parameter name vector."
[grouped-params]
(let [param-list (flatten grouped-params)
pvals (map #(:default %1) param-list)
pnames (map (fn [[idx param]]
{:name (to-str (:name param))
:index idx})
(indexed param-list))]
[pvals pnames]))
(defn- ugen-form? [form]
(and (seq? form)
(= 'ugen (first form))))
(defn- fastest-rate [rates]
(REVERSE-RATES (first (reverse (sort (map RATES rates))))))
(defn- special-op-args? [args]
(some #(or (sc-ugen? %1) (keyword? %1)) args))
(defn- find-rate [args]
(fastest-rate (map #(cond
(sc-ugen? %1) (REVERSE-RATES (:rate %1))
(keyword? %1) :kr)
args)))
;; For greatest efficiency:
;;
;; * Unit generators should be listed in an order that permits efficient reuse
;; of connection buffers, so use a depth first topological sort of the graph.
; NOTES:
; * The ugen tree is turned into a ugen list that is sorted by the order in
; which nodes should be processed. (Depth first, starting at outermost leaf
; of the first branch.
;
; * params are sorted by rate, and then a Control ugen per rate is created
; and prepended to the ugen list
;
; * finally, ugen inputs are specified using their index
; in the sorted ugen list.
;
; * No feedback loops are allowed. Feedback must be accomplished via delay lines
; or through buses.
;
(defn synthdef
"Transforms a synth definition (ugen-graph) into a form that's ready to save
to disk or send to the server.
(synthdef \"pad-z\" [
"
[sname params ugens constants]
(let [grouped-params (group-params params)
[params pnames] (make-params grouped-params)
with-ctl-ugens (concat (make-control-ugens grouped-params) ugens)
detailed (detail-ugens with-ctl-ugens constants grouped-params)]
(with-meta {:name (str sname)
:constants constants
:params params
:pnames pnames
:ugens detailed}
{:type :overtone.sc.machinery.synthdef/synthdef})))
(defn- control-proxies
"Returns a list of param name symbols and control proxies"
[params]
(mapcat (fn [param] [(symbol (:name param))
`(control-proxy ~(:name param) ~(:default param) ~(:rate param))])
params))
(defn- gen-synth-name
"Auto generate an anonymous synth name. Intended for use in synths that have not
been defined with an explicit name. Has the form \"anon-id\" where id is a unique
integer across all anonymous synths."
[]
(str "anon-" (next-id ::anonymous-synth)))
(defn- id-able-type?
[o]
(or (isa? (type o) :overtone.sc.buffer/buffer)
(isa? (type o) :overtone.sc.sample/sample)
(isa? (type o) :overtone.sc.bus/audio-bus)
(isa? (type o) :overtone.sc.bus/control-bus)))
(defn normalize-synth-args
"Pull out and normalize the synth name, parameters, control proxies and the ugen form
from the supplied arglist resorting to defaults if necessary."
[args]
(let [[sname args] (cond
(or (string? (first args))
(symbol? (first args))) [(str (first args)) (rest args)]
:default [(gen-synth-name) args])
[params ugen-form] (if (vector? (first args))
[(first args) (rest args)]
[[] args])
param-proxies (control-proxies params)]
[sname params param-proxies ugen-form]))
(defn gather-ugens-and-constants
"Traverses a ugen tree and returns a vector of two sets [#{ugens} #{constants}]."
[root]
(if (seq? root)
(reduce
(fn [[ugens constants] ugen]
(let [[us cs] (gather-ugens-and-constants ugen)]
[(set/union ugens us)
(set/union constants cs)]))
[#{} #{}]
root)
(let [args (:args root)
cur-ugens (filter sc-ugen? args)
cur-ugens (filter (comp not control-proxy?) cur-ugens)
cur-ugens (map #(if (output-proxy? %)
(:ugen %)
%) cur-ugens)
cur-consts (filter number? args)
[child-ugens child-consts] (gather-ugens-and-constants cur-ugens)
ugens (conj (set child-ugens) root)
constants (set/union (set cur-consts) child-consts)]
[ugens (vec constants)])))
(defn- ugen-children
"Returns the children (arguments) of this ugen that are themselves upstream ugens."
[ug]
(mapcat
#(cond
(seq? %) %
(output-proxy? %) [(:ugen %)]
:default [%])
(filter
(fn [arg]
(and (not (control-proxy? arg))
(or (sc-ugen? arg)
(and (seq? arg)
(every? sc-ugen? arg)))))
(:args ug))))
(defn topological-sort-ugens
"Sort into a vector where each node in the directed graph of ugens will always
be preceded by its upstream dependencies."
[ugens]
(loop [ugens ugens
; start with leaf nodes that don't have any dependencies
leaves (set (filter (fn [ugen]
(every?
#(or (not (sc-ugen? %))
(control-proxy? %))
(:args ugen)))
ugens))
sorted-ugens []
rec-count 0]
;(println "\n------------\nugens: " ugens)
;(println "leaves: " leaves)
;(println "sorted-ugens: " sorted-ugens)
; bail out after 1000 iterations, either a bug in this code, or a bad synth graph
(when (= 1000 rec-count)
(throw (Exception. "Invalid ugen tree passed to topological-sort-ugens, maybe you have cycles in the synthdef...")))
(if (empty? leaves)
sorted-ugens
(let [last-ugen (last sorted-ugens)
; try to always place the downstream ugen from the last-ugen if all other
; deps are satisfied, which keeps internal buffers in cache as long as possible
next-ugen (first (filter #((set (ugen-children %)) last-ugen) leaves))
[next-ugen leaves] (if next-ugen
[next-ugen (disj leaves next-ugen)]
[(first leaves) (next leaves)])
;_ (println "next-ugen: " next-ugen)
sorted-ugens (conj sorted-ugens next-ugen)
sorted-ugen-set (set sorted-ugens)
ugens (set/difference ugens sorted-ugen-set leaves)
leaves (set
(reduce
(fn [rleaves ug]
(let [children (ugen-children ug)]
;(println ug ": " children)
(if (set/subset? children sorted-ugen-set)
(conj rleaves ug)
rleaves)))
leaves
ugens))]
(recur ugens leaves sorted-ugens (inc rec-count))))))
(comment
; Some test synths, while shaking out the bugs...
(defsynth foo [] (out 0 (rlpf (saw [220 663]) (x-line:kr 20000 2 1 FREE))))
(defsynth bar [freq 220] (out 0 (rlpf (saw [freq (* 3.013 freq)]) (x-line:kr 20000 2 1 FREE))))
(definst faz [] (rlpf (saw [220 663]) (x-line:kr 20000 2 1 FREE)))
(definst baz [freq 220] (rlpf (saw [freq (* 3.013 freq)]) (x-line:kr 20000 2 1 FREE)))
(run 1 (out 184 (saw (x-line:kr 10000 10 1 FREE))))
)
(defmacro pre-synth
"Resolve a synth def to a list of its name, params, ugens (nested if
necessary) and constants. Sets the lexical bindings of the param
names to control proxies within the synth definition"
[& args]
(let [[sname params param-proxies ugen-form] (normalize-synth-args args)]
`(let [~@param-proxies]
(binding [*ugens* []
*constants* #{}]
(let [[ugens# constants#] (gather-ugens-and-constants
(with-overloaded-ugens ~@ugen-form))
ugens# (topological-sort-ugens ugens#)
;; _# (println "main-tree[" (count ugens#) "]: " ugens#)
;; _# (println (str "*ugens*: [" (count *ugens*) "] " *ugens*))
main-tree# (set ugens#)
side-tree# (filter #(not (main-tree# %)) *ugens*)
;; _# (println "side-tree[" (count side-tree#) "]: " side-tree#)
ugens# (concat ugens# side-tree#)
constants# (into [] (set (concat constants# *constants*)))]
;; (println "all ugens[" (count ugens#) "]: " ugens#)
[~sname ~params ugens# constants#])))))
(defn synth-player
[name params this & args]
"Returns a player function for a named synth. Used by (synth ...)
internally, but can be used to generate a player for a pre-compiled
synth. The function generated will accept two optional arguments that
must come first, the :position and :target (see the node function docs).
(foo)
(foo :position :tail :target 0)
or if foo has two arguments:
(foo 440 0.3)
(foo :position :tail :target 0 440 0.3)
at the head of group 2:
(foo :position :head :target 2 440 0.3)
These can also be abbreviated:
(foo :tgt 2 :pos :head)
"
(let [arg-names (map keyword (map :name params))
args (if (and (= 1 (count args))
(map? (first args))
(not (id-able-type? (first args))))
(flatten (seq (first args)))
args)
[args sgroup] (if (or (= :target (first args))
(= :tgt (first args)))
[(drop 2 args) (second args)]
[args @synth-group*])
[args pos] (if (or (= :position (first args))
(= :pos (first args)))
[(drop 2 args) (second args)]
[args :tail])
[args sgroup] (if (or (= :target (first args))
(= :tgt (first args)))
[(drop 2 args) (second args)]
[args sgroup])
args (map #(if (id-able-type? %)
(:id %) %) args)
defaults (into {} (map (fn [{:keys [name value]}]
[(keyword name) @value])
params))
arg-map (arg-mapper args arg-names defaults)
synth-node (node name arg-map {:position pos :target sgroup })
synth-node (if (:instance-fn this)
((:instance-fn this) synth-node)
synth-node)]
(when (:instance-fn this)
(swap! active-synth-nodes* assoc (:id synth-node) synth-node))
synth-node))
(defrecord-ifn Synth [name ugens sdef args params instance-fn]
(partial synth-player name params))
(defn update-tap-data
[msg]
(let [[node-id label-id val] (:args msg)
node (get @active-synth-nodes* node-id)
label (get (:tap-labels node) label-id)
tap-atom (get (:taps node) label)]
(reset! tap-atom val)))
(on-event "/overtone/tap" #'update-tap-data ::handle-incoming-tap-data)
(defmacro synth
"Define a SuperCollider synthesizer using the library of ugen
functions provided by overtone.sc.ugen. This will return callable
record which can be used to trigger the synthesizer.
"
[& args]
`(let [[sname# params# ugens# constants#] (pre-synth ~@args)
sdef# (synthdef sname# params# ugens# constants#)
arg-names# (map :name params#)
params-with-vals# (map #(assoc % :value (atom (:default %))) params#)
instance-fn# (apply comp (map :instance-fn (filter :instance-fn (map meta ugens#))))
smap# (with-meta
(map->Synth
{:name sname#
:ugens ugens#
:sdef sdef#
:args arg-names#
:params params-with-vals#
:instance-fn instance-fn#})
{:overtone.util.live/to-string #(str (name (:type %)) ":" (:name %))})]
(load-synthdef sdef#)
(event :new-synth :synth smap#)
smap#))
(defn synth-form
"Internal function used to prepare synth meta-data."
[s-name s-form]
(let [[s-name s-form] (name-with-attributes s-name s-form)
_ (when (not (symbol? s-name))
(throw (IllegalArgumentException. (str "You need to specify a name for your synth using a symbol"))))
params (first s-form)
params (parse-params params)
ugen-form (concat '(do) (next s-form))
param-names (list (vec (map #(symbol (:name %)) params)))
md (assoc (meta s-name)
:name s-name
:type ::synth
:arglists (list 'quote param-names))]
[(with-meta s-name md) params ugen-form]))
(defmacro defsynth
"Define a synthesizer and return a player function. The synth definition
will be loaded immediately, and a :new-synth event will be emitted.
(defsynth foo [freq 440]
(sin-osc freq))
is equivalent to:
(def foo
(synth [freq 440] (sin-osc freq)))
A doc string can also be included:
(defsynth bar
\"The phatest space pad ever!\"
[] (...))
"
[s-name & s-form]
(let [[s-name params ugen-form] (synth-form s-name s-form)]
`(def ~s-name (synth ~s-name ~params ~ugen-form))))
(defn synth?
"Returns true if s is a synth, false otherwise."
[s]
(= overtone.sc.synth.Synth (type s)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Synthdef de-compilation
;; The eventual goal is to be able to take any SuperCollider scsyndef
;; file, and produce equivalent clojure code that can be re-edited.
(defn- param-vector [params pnames]
"Create a synthdef parameter vector."
(vec (flatten
(map #(list (symbol (:name %1))
(nth params (:index %1)))
pnames))))
(defn- ugen-form
"Create a ugen form."
[ug]
(let [uname (real-ugen-name ug)
ugen (get-ugen uname)
uname (if (and
(zero? (:special ug))
(not= (:rate-name ug) (:default-rate ugen)))
(str uname (:rate-name ug))
uname)
uname (symbol uname)]
(apply list uname (:inputs ug))))
(defn- ugen-constant-inputs
"Replace constant ugen inputs with the constant values."
[constants ug]
(assoc ug :inputs
(map
(fn [{:keys [src index] :as input}]
(if (= src -1)
(nth constants index)
input))
(:inputs ug))))
(defn- reverse-ugen-inputs
"Replace ugen inputs that are other ugens with their generated symbolic name."
[pnames ugens ug]
(assoc ug :inputs
(map
(fn [{:keys [src index] :as input}]
(if src
(let [u-in (nth ugens src)]
(if (= "Control" (:name u-in))
(nth pnames index)
(:sname (nth ugens src))))
input))
(:inputs ug))))
; In order to do this correctly is a big project because you also have to
; reverse the process of the various ugen modes. For example, you need
; to recognize the ugens that have array arguments which will be
; appended, and then you need to gather up the inputs and place them into
; an array at the correct argument location.
(defn synthdef-decompile
"Decompile a parsed SuperCollider synth definition back into clojure code
that could be used to generate an identical synth.
While this probably won't create a synth definition that can directly compile,
it can still be helpful when trying to reverse engineer a synth."
[{:keys [name constants params pnames ugens] :as sdef}]
(let [sname (symbol name)
param-vec (param-vector params pnames)
ugens (map #(assoc % :sname %2)
ugens
(map (comp symbol #(str "ug-" %) char) (range 97 200)))
ugens (map (partial ugen-constant-inputs constants) ugens)
pnames (map (comp symbol :name) pnames)
ugens (map (partial reverse-ugen-inputs pnames ugens) ugens)
ugens (filter #(not= "Control" (:name %)) ugens)
ugen-forms (map vector
(map :sname ugens)
(map ugen-form ugens))]
(print (format "(defsynth %s %s\n (let [" sname param-vec))
(println (ffirst ugen-forms) (second (first ugen-forms)))
(doseq [[uname uform] (drop 1 ugen-forms)]
(println " " uname uform))
(println (str " ]\n " (first (last ugen-forms)) ")"))))
(def ^{:dynamic true} *demo-time* 2000)
(defmacro run
"Run an anonymous synth definition for a fixed period of time. Useful for
experimentation. Does NOT add an out ugen - see #'demo for that. You can
specify a timeout in seconds as the first argument otherwise it defaults to
*demo-time* ms.
(run (send-reply (impulse 1) \"/foo\" [1] 43)) ;=> send OSC messages out"
[& body]
(let [[demo-time body] (if (number? (first body))
[(* 1000 (first body)) (second body)]
[*demo-time* (first body)])]
`(let [s# (synth "audition-synth" ~body)
note# (s#)]
(after-delay ~demo-time #(node-free note#))
note#)))
(defmacro demo
"Listen to an anonymous synth definition for a fixed period of time. Useful
for experimentation. If the root node is not an out ugen, then it will add
one automatically. You can specify a timeout in seconds as the first argument
otherwise it defaults to *demo-time* ms.
(demo (sin-osc 440)) ;=> plays a sine wave for *demo-time* ms
(demo 0.5 (sin-osc 440)) ;=> plays a sine wave for half a second"
[& body]
(let [[demo-time body] (if (number? (first body))
[(first body) (second body)]
[(* 0.001 *demo-time*) (first body)])
[out-bus body] (if (= 'out (first body))
[(second body) (nth body 2)]
[0 body])
body (list 'out out-bus (list 'hold body demo-time :done 'FREE))]
`((synth "audition-synth" ~body))))
(defn active-synths
"Return a seq of the actively running synth nodes. If a synth or inst are passed as the filter it will only return nodes of that type.
(active-synths) ; => [{:type synth :name \"mixer\" :id 12}
{:type synth :name \"my-synth\" :id 24}]
(active-synths my-synth) ; => [{:type synth :name \"my-synth\" :id 24}]
"
[& [synth-filter]]
(let [active-nodes (filter #(= overtone.sc.node.SynthNode (type %))
(vals @active-synth-nodes*))]
(if synth-filter
(filter #(= (:name synth-filter) (:name %)) active-nodes)
active-nodes)))
(defmethod print-method ::synth [syn w]
(let [info (meta syn)]
(.write w (format "#<synth: %s>" (:name info)))))
; TODO: pull out the default param atom stuff into a separate mechanism
(defn modify-synth-params
"Update synth parameter value atoms storing the current default settings."
[s & params-vals]
(let [params (:params s)]
(for [[param value] (partition 2 params-vals)]
(let [val-atom (:value (first (filter #(= (:name %) (name param)) params)))]
(if val-atom
(reset! val-atom value)
(throw (IllegalArgumentException. (str "Invalid control parameter: " param))))))))
(defn reset-synth-defaults
"Reset a synth to it's default settings defined at definition time."
[synth]
(doseq [param (:params synth)]
(reset! (:value param) (:default param))))
|
[
{
"context": "\n :email \"yap@yap.org\"\n :user \"",
"end": 2028,
"score": 0.9999130368232727,
"start": 2017,
"tag": "EMAIL",
"value": "yap@yap.org"
},
{
"context": "\"\n :user \"yapper\"\n :role \"",
"end": 2084,
"score": 0.9995853304862976,
"start": 2078,
"tag": "USERNAME",
"value": "yapper"
},
{
"context": "\n :email \"medina@med.com\"\n :user \"",
"end": 2288,
"score": 0.9999263286590576,
"start": 2274,
"tag": "EMAIL",
"value": "medina@med.com"
},
{
"context": "\"\n :user \"medina\"\n :role \"",
"end": 2344,
"score": 0.9996008276939392,
"start": 2338,
"tag": "USERNAME",
"value": "medina"
},
{
"context": "\n :email \"addie@adder.org\"\n :user \"",
"end": 2550,
"score": 0.9999262690544128,
"start": 2535,
"tag": "EMAIL",
"value": "addie@adder.org"
},
{
"context": "\"\n :user \"addie\"\n :role \"",
"end": 2605,
"score": 0.9995788335800171,
"start": 2600,
"tag": "USERNAME",
"value": "addie"
},
{
"context": "td>yapper</td>\"\n \"<td>yap@yap.org</td>\"\n \"<td>user</td>",
"end": 3276,
"score": 0.999323844909668,
"start": 3265,
"tag": "EMAIL",
"value": "yap@yap.org"
},
{
"context": "td>medina</td>\"\n \"<td>medina@med.com</td>\"\n \"<td>media</td",
"end": 3513,
"score": 0.9998875260353088,
"start": 3499,
"tag": "EMAIL",
"value": "medina@med.com"
},
{
"context": "<td>addie</td>\"\n \"<td>addie@adder.org</td>\"\n \"<td>admin</td",
"end": 3751,
"score": 0.9998865723609924,
"start": 3736,
"tag": "EMAIL",
"value": "addie@adder.org"
}
] | frontend/test/frontend/admin_test.clj | raymondpoling/rerun-tv | 0 | (ns frontend.admin-test
(:require
[clojure.test :refer [deftest is]]
[ring.mock.request :as mock]
[frontend.handler :refer [app]]
[frontend.util :refer [make-cookie
make-response
testing-with-log-markers
basic-matcher]]
[clj-http.fake :refer [with-fake-routes-in-isolation]]))
(deftest test-admin-routes
(let [admin-cookie (make-cookie "admin")
media-cookie (make-cookie "media")]
(testing-with-log-markers
"user has no access to user-management"
(with-fake-routes-in-isolation
{}
(let [response (app (-> (mock/request :get "/user-management.html")
media-cookie))]
(is (= (:status response) 302))
(is (get (:headers response) "Location")
"http://localhost:4008/login.html"))))
(testing-with-log-markers
"user has no access to user"
(with-fake-routes-in-isolation
{}
(let [response (app (-> (mock/request :post "/user")
media-cookie))]
(is (= (:status response) 302))
(is (get (:headers response) "Location")
"http://localhost:4008/login.html"))))
(testing-with-log-markers
"user has no access to role"
(with-fake-routes-in-isolation
{}
(let [response (app (-> (mock/request :post "/role")
media-cookie))]
(is (= (:status response) 302))
(is (get (:headers response) "Location")
"http://localhost:4008/login.html"))))
(testing-with-log-markers
"admin user has access"
(with-fake-routes-in-isolation
{
"http://identity:4012/role"
(fn [_] (make-response {:status "ok"
:roles ["user","admin","media"]}))
"http://identity:4012/user"
(fn [_] (make-response {:status "ok"
:users [{
:email "yap@yap.org"
:user "yapper"
:role "user"
}
{
:email "medina@med.com"
:user "medina"
:role "media"
}
{
:email "addie@adder.org"
:user "addie"
:role "admin"
}]}))
}
(let [response (app (-> (mock/request :get "/user-management.html")
admin-cookie))]
(is (= (:status response) 200))
(is (basic-matcher "<option selected=\"selected\">user</option>"
(:body response)))
(is (basic-matcher "<option>admin</option>" (:body response)))
(is (basic-matcher "<option>media</option>" (:body response)))
(is (basic-matcher (str
"<tr><td>yapper</td>"
"<td>yap@yap.org</td>"
"<td>user</td></tr>")
(:body response)))
(is (basic-matcher (str
"<tr><td>medina</td>"
"<td>medina@med.com</td>"
"<td>media</td></tr>")
(:body response)))
(is (basic-matcher (str
"<tr><td>addie</td>"
"<td>addie@adder.org</td>"
"<td>admin</td></tr>")
(:body response))))))
(testing-with-log-markers
"admin adds user"
(with-fake-routes-in-isolation
{}
(let [response (app (-> (mock/request :post "/user")
admin-cookie))]
(is (= (:status response) 302))
(is (get (:headers response) "Location")
"http://localhost:4008/user-management.html"))))
(testing-with-log-markers
"user has no access to role"
(with-fake-routes-in-isolation
{}
(let [response (app (-> (mock/request :post "/role")
admin-cookie))]
(is (= (:status response) 302))
(is (get (:headers response) "Location")
"http://localhost:4008/user-management.html"))))))
| 3758 | (ns frontend.admin-test
(:require
[clojure.test :refer [deftest is]]
[ring.mock.request :as mock]
[frontend.handler :refer [app]]
[frontend.util :refer [make-cookie
make-response
testing-with-log-markers
basic-matcher]]
[clj-http.fake :refer [with-fake-routes-in-isolation]]))
(deftest test-admin-routes
(let [admin-cookie (make-cookie "admin")
media-cookie (make-cookie "media")]
(testing-with-log-markers
"user has no access to user-management"
(with-fake-routes-in-isolation
{}
(let [response (app (-> (mock/request :get "/user-management.html")
media-cookie))]
(is (= (:status response) 302))
(is (get (:headers response) "Location")
"http://localhost:4008/login.html"))))
(testing-with-log-markers
"user has no access to user"
(with-fake-routes-in-isolation
{}
(let [response (app (-> (mock/request :post "/user")
media-cookie))]
(is (= (:status response) 302))
(is (get (:headers response) "Location")
"http://localhost:4008/login.html"))))
(testing-with-log-markers
"user has no access to role"
(with-fake-routes-in-isolation
{}
(let [response (app (-> (mock/request :post "/role")
media-cookie))]
(is (= (:status response) 302))
(is (get (:headers response) "Location")
"http://localhost:4008/login.html"))))
(testing-with-log-markers
"admin user has access"
(with-fake-routes-in-isolation
{
"http://identity:4012/role"
(fn [_] (make-response {:status "ok"
:roles ["user","admin","media"]}))
"http://identity:4012/user"
(fn [_] (make-response {:status "ok"
:users [{
:email "<EMAIL>"
:user "yapper"
:role "user"
}
{
:email "<EMAIL>"
:user "medina"
:role "media"
}
{
:email "<EMAIL>"
:user "addie"
:role "admin"
}]}))
}
(let [response (app (-> (mock/request :get "/user-management.html")
admin-cookie))]
(is (= (:status response) 200))
(is (basic-matcher "<option selected=\"selected\">user</option>"
(:body response)))
(is (basic-matcher "<option>admin</option>" (:body response)))
(is (basic-matcher "<option>media</option>" (:body response)))
(is (basic-matcher (str
"<tr><td>yapper</td>"
"<td><EMAIL></td>"
"<td>user</td></tr>")
(:body response)))
(is (basic-matcher (str
"<tr><td>medina</td>"
"<td><EMAIL></td>"
"<td>media</td></tr>")
(:body response)))
(is (basic-matcher (str
"<tr><td>addie</td>"
"<td><EMAIL></td>"
"<td>admin</td></tr>")
(:body response))))))
(testing-with-log-markers
"admin adds user"
(with-fake-routes-in-isolation
{}
(let [response (app (-> (mock/request :post "/user")
admin-cookie))]
(is (= (:status response) 302))
(is (get (:headers response) "Location")
"http://localhost:4008/user-management.html"))))
(testing-with-log-markers
"user has no access to role"
(with-fake-routes-in-isolation
{}
(let [response (app (-> (mock/request :post "/role")
admin-cookie))]
(is (= (:status response) 302))
(is (get (:headers response) "Location")
"http://localhost:4008/user-management.html"))))))
| true | (ns frontend.admin-test
(:require
[clojure.test :refer [deftest is]]
[ring.mock.request :as mock]
[frontend.handler :refer [app]]
[frontend.util :refer [make-cookie
make-response
testing-with-log-markers
basic-matcher]]
[clj-http.fake :refer [with-fake-routes-in-isolation]]))
(deftest test-admin-routes
(let [admin-cookie (make-cookie "admin")
media-cookie (make-cookie "media")]
(testing-with-log-markers
"user has no access to user-management"
(with-fake-routes-in-isolation
{}
(let [response (app (-> (mock/request :get "/user-management.html")
media-cookie))]
(is (= (:status response) 302))
(is (get (:headers response) "Location")
"http://localhost:4008/login.html"))))
(testing-with-log-markers
"user has no access to user"
(with-fake-routes-in-isolation
{}
(let [response (app (-> (mock/request :post "/user")
media-cookie))]
(is (= (:status response) 302))
(is (get (:headers response) "Location")
"http://localhost:4008/login.html"))))
(testing-with-log-markers
"user has no access to role"
(with-fake-routes-in-isolation
{}
(let [response (app (-> (mock/request :post "/role")
media-cookie))]
(is (= (:status response) 302))
(is (get (:headers response) "Location")
"http://localhost:4008/login.html"))))
(testing-with-log-markers
"admin user has access"
(with-fake-routes-in-isolation
{
"http://identity:4012/role"
(fn [_] (make-response {:status "ok"
:roles ["user","admin","media"]}))
"http://identity:4012/user"
(fn [_] (make-response {:status "ok"
:users [{
:email "PI:EMAIL:<EMAIL>END_PI"
:user "yapper"
:role "user"
}
{
:email "PI:EMAIL:<EMAIL>END_PI"
:user "medina"
:role "media"
}
{
:email "PI:EMAIL:<EMAIL>END_PI"
:user "addie"
:role "admin"
}]}))
}
(let [response (app (-> (mock/request :get "/user-management.html")
admin-cookie))]
(is (= (:status response) 200))
(is (basic-matcher "<option selected=\"selected\">user</option>"
(:body response)))
(is (basic-matcher "<option>admin</option>" (:body response)))
(is (basic-matcher "<option>media</option>" (:body response)))
(is (basic-matcher (str
"<tr><td>yapper</td>"
"<td>PI:EMAIL:<EMAIL>END_PI</td>"
"<td>user</td></tr>")
(:body response)))
(is (basic-matcher (str
"<tr><td>medina</td>"
"<td>PI:EMAIL:<EMAIL>END_PI</td>"
"<td>media</td></tr>")
(:body response)))
(is (basic-matcher (str
"<tr><td>addie</td>"
"<td>PI:EMAIL:<EMAIL>END_PI</td>"
"<td>admin</td></tr>")
(:body response))))))
(testing-with-log-markers
"admin adds user"
(with-fake-routes-in-isolation
{}
(let [response (app (-> (mock/request :post "/user")
admin-cookie))]
(is (= (:status response) 302))
(is (get (:headers response) "Location")
"http://localhost:4008/user-management.html"))))
(testing-with-log-markers
"user has no access to role"
(with-fake-routes-in-isolation
{}
(let [response (app (-> (mock/request :post "/role")
admin-cookie))]
(is (= (:status response) 302))
(is (get (:headers response) "Location")
"http://localhost:4008/user-management.html"))))))
|
[
{
"context": "; Copyright (c) 2012 Jochen Rau\n; \n; Permission is hereby granted, free of charge",
"end": 31,
"score": 0.9998762607574463,
"start": 21,
"tag": "NAME",
"value": "Jochen Rau"
},
{
"context": "f the know:ledge management system.\"\n :author \"Jochen Rau\"} \n knowl.edge.transformation\n (:refer-clojure",
"end": 1282,
"score": 0.9998777508735657,
"start": 1272,
"tag": "NAME",
"value": "Jochen Rau"
}
] | src/knowl/edge/transformation.clj | cldwalker/knowl-edge | 1 | ; Copyright (c) 2012 Jochen Rau
;
; 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
^{:doc "This namespace provides functionailty to transform a given resource recursively into a representation. It is part of the know:ledge management system."
:author "Jochen Rau"}
knowl.edge.transformation
(:refer-clojure :exclude [namespace])
(:use
[clojure.contrib.core :only (-?>)]
knowl.edge.store
knowl.edge.model)
(:require
[clojure.contrib.str-utils2 :as string]
[clj-time.format :as time]
[net.cgrand.enlive-html :as template]))
(def ^:dynamic *template* (template/html-resource (java.io.File. "resources/private/templates/page.html")))
(def ^:dynamic *store* default-store)
;; Predicates
(defn- type= [resource]
#{(template/attr-has :typeof (identifier resource)) (template/attr-has :about (identifier resource))})
(defn- property= [resource]
(template/attr-has :property (identifier resource)))
(defn- relation= [resource]
(template/attr-has :rel (identifier resource)))
(defn- property? []
#{(template/attr? :property)
(template/attr-has :rel)})
(defn- set-datatype [datatype]
(template/set-attr :datatype (value datatype)))
(defn- set-language [language]
(comp (template/set-attr :lang (value language)) (template/set-attr :xml:lang (value language))))
(defn- set-content [resource]
(template/set-attr :content (value resource)))
(defn- set-resource [resource]
(template/set-attr :about (identifier resource)))
(defn- set-property [resource]
(template/set-attr :property (identifier resource)))
(defn- set-relation [resource]
(template/set-attr :rel (identifier resource)))
(defn- set-reference [resource]
(template/set-attr :href (identifier resource)))
(defn- set-types [types]
(template/set-attr :typeof (string/join " " (map str types))))
;; Helper functions
(defn- extract-predicates [snippet]
(filter #(string/contains? % ":")
(map #(or (-> % :attrs :property)
(-> % :attrs :rel))
(template/select snippet [(property?)]))))
;; Context
(defprotocol ContextHandling
"Functions for dealing with a transformations context (like render depth, the web request, or the current selector chain)."
(conj-selector [this selector] "Appends a selector to the selector-chain"))
(defrecord Context [depth rootline]
ContextHandling
(conj-selector
[this selector]
(update-in this [:rootline] #(into % selector))))
;; Transformations
(defprotocol Transformer
"Provides functions to transform the given subject into a different representation."
(transform [this context] "Transforms the subject."))
(extend-protocol Transformer
java.lang.String
(transform [this context] this)
nil
(transform [this context] nil))
(defmulti transform-literal (fn [literal context] (-> literal datatype value)))
(defmethod transform-literal :default [literal context] (value literal))
(defmethod transform-literal "http://www.w3.org/2001/XMLSchema#dateTime" [literal context]
(time/unparse (time/formatter "EEEE dd MMMM, yyyy") (time/parse (time/formatters :date-time-no-ms) (value literal))))
(defn transform-statement [statement context]
(let [predicate (predicate statement)
object (object statement)]
(if (= (identifier predicate) "http://dbpedia.org/ontology/wikiPageExternalLink")
(template/do->
(set-reference object)
(template/content (value object)))
(template/do->
(template/content (transform object context))
(if (satisfies? knowl.edge.model/Literal object)
(template/do->
(if-let [datatype (datatype object)]
(template/do->
(set-datatype datatype)
(set-content (value object)))
identity)
(if-let [language ( language object)]
(set-language language)
identity))
identity)))))
(defn transform-statements [statements resource types context]
(let [context (conj-selector context [(into #{} (map #(type= %) types))])
snippet (template/select *template* (:rootline context))
snippet-predicates (extract-predicates snippet)
grouped-statements (group-by #(predicate %) statements)
query-predicates (keys grouped-statements)]
(loop [snippet (template/transform snippet [template/root]
(template/do->
(set-types types)
(set-resource resource)))
grouped-statements grouped-statements]
(if-not (seq grouped-statements)
snippet
(recur
(let [predicate (ffirst grouped-statements)]
(template/at
snippet
[(property= predicate)] (template/do->
(set-property predicate)
(template/clone-for
[statement (second (first grouped-statements))]
(transform-statement statement context)))
[(relation= predicate)] (template/do->
(set-relation predicate)
(template/clone-for
[statement (second (first grouped-statements))]
(transform-statement statement context)))))
(rest grouped-statements))))))
(defn transform-query [query store context]
(when-let [statements (find-by-query store query)]
(do (when (not= default-store store) (add default-store statements))
(let [grouped-statements (group-by #(subject %) statements)]
(loop [grouped-statements grouped-statements
result []]
(if-not (seq grouped-statements)
result
(recur
(rest grouped-statements)
(into
result
(let [statement-group (first grouped-statements)
resource (key statement-group)
types (find-types-of store resource)
statements (val statement-group)]
(transform-statements statements resource types context))))))))))
(defn transform-resource [resource context]
(if (< (count (:rootline context)) 6)
(loop [stores (stores-for resource)
representation nil]
(if (or (not (seq stores)) representation)
representation
(recur
(rest stores)
(let [store (first stores)]
(if-let [statements (find-matching store resource)]
(let [types (find-types-of store resource)]
(if (some #(= (identifier %) "http://spinrdf.org/sp#Construct") types)
(when-let [query (-> (filter #(= (-> % predicate identifier) "http://knowl-edge.org/ontology/core#query") statements) first object value)]
(when-let [service-statements (filter #(= (-> % predicate identifier) "http://knowl-edge.org/ontology/core#sparqlEndpoint") statements)]
(let [store (knowl.edge.store.Endpoint. (-> service-statements first object value) {})]
(transform-query query store context))))
(do
(when (not= default-store store) (add default-store statements))
(transform-statements statements resource types context)))))))))))
;; Entry Point
(defn dereference [resource]
(let [representation (or
(-?> (find-matching *store* nil (create-resource ["http://knowl-edge.org/ontology/core#" "represents"]) resource) first subject)
resource)]
(when-let [document (transform representation (Context. 0 []))]
(template/emit* document))))
(use 'knowl.edge.implementation.jena.transformation)
| 112665 | ; Copyright (c) 2012 <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
^{:doc "This namespace provides functionailty to transform a given resource recursively into a representation. It is part of the know:ledge management system."
:author "<NAME>"}
knowl.edge.transformation
(:refer-clojure :exclude [namespace])
(:use
[clojure.contrib.core :only (-?>)]
knowl.edge.store
knowl.edge.model)
(:require
[clojure.contrib.str-utils2 :as string]
[clj-time.format :as time]
[net.cgrand.enlive-html :as template]))
(def ^:dynamic *template* (template/html-resource (java.io.File. "resources/private/templates/page.html")))
(def ^:dynamic *store* default-store)
;; Predicates
(defn- type= [resource]
#{(template/attr-has :typeof (identifier resource)) (template/attr-has :about (identifier resource))})
(defn- property= [resource]
(template/attr-has :property (identifier resource)))
(defn- relation= [resource]
(template/attr-has :rel (identifier resource)))
(defn- property? []
#{(template/attr? :property)
(template/attr-has :rel)})
(defn- set-datatype [datatype]
(template/set-attr :datatype (value datatype)))
(defn- set-language [language]
(comp (template/set-attr :lang (value language)) (template/set-attr :xml:lang (value language))))
(defn- set-content [resource]
(template/set-attr :content (value resource)))
(defn- set-resource [resource]
(template/set-attr :about (identifier resource)))
(defn- set-property [resource]
(template/set-attr :property (identifier resource)))
(defn- set-relation [resource]
(template/set-attr :rel (identifier resource)))
(defn- set-reference [resource]
(template/set-attr :href (identifier resource)))
(defn- set-types [types]
(template/set-attr :typeof (string/join " " (map str types))))
;; Helper functions
(defn- extract-predicates [snippet]
(filter #(string/contains? % ":")
(map #(or (-> % :attrs :property)
(-> % :attrs :rel))
(template/select snippet [(property?)]))))
;; Context
(defprotocol ContextHandling
"Functions for dealing with a transformations context (like render depth, the web request, or the current selector chain)."
(conj-selector [this selector] "Appends a selector to the selector-chain"))
(defrecord Context [depth rootline]
ContextHandling
(conj-selector
[this selector]
(update-in this [:rootline] #(into % selector))))
;; Transformations
(defprotocol Transformer
"Provides functions to transform the given subject into a different representation."
(transform [this context] "Transforms the subject."))
(extend-protocol Transformer
java.lang.String
(transform [this context] this)
nil
(transform [this context] nil))
(defmulti transform-literal (fn [literal context] (-> literal datatype value)))
(defmethod transform-literal :default [literal context] (value literal))
(defmethod transform-literal "http://www.w3.org/2001/XMLSchema#dateTime" [literal context]
(time/unparse (time/formatter "EEEE dd MMMM, yyyy") (time/parse (time/formatters :date-time-no-ms) (value literal))))
(defn transform-statement [statement context]
(let [predicate (predicate statement)
object (object statement)]
(if (= (identifier predicate) "http://dbpedia.org/ontology/wikiPageExternalLink")
(template/do->
(set-reference object)
(template/content (value object)))
(template/do->
(template/content (transform object context))
(if (satisfies? knowl.edge.model/Literal object)
(template/do->
(if-let [datatype (datatype object)]
(template/do->
(set-datatype datatype)
(set-content (value object)))
identity)
(if-let [language ( language object)]
(set-language language)
identity))
identity)))))
(defn transform-statements [statements resource types context]
(let [context (conj-selector context [(into #{} (map #(type= %) types))])
snippet (template/select *template* (:rootline context))
snippet-predicates (extract-predicates snippet)
grouped-statements (group-by #(predicate %) statements)
query-predicates (keys grouped-statements)]
(loop [snippet (template/transform snippet [template/root]
(template/do->
(set-types types)
(set-resource resource)))
grouped-statements grouped-statements]
(if-not (seq grouped-statements)
snippet
(recur
(let [predicate (ffirst grouped-statements)]
(template/at
snippet
[(property= predicate)] (template/do->
(set-property predicate)
(template/clone-for
[statement (second (first grouped-statements))]
(transform-statement statement context)))
[(relation= predicate)] (template/do->
(set-relation predicate)
(template/clone-for
[statement (second (first grouped-statements))]
(transform-statement statement context)))))
(rest grouped-statements))))))
(defn transform-query [query store context]
(when-let [statements (find-by-query store query)]
(do (when (not= default-store store) (add default-store statements))
(let [grouped-statements (group-by #(subject %) statements)]
(loop [grouped-statements grouped-statements
result []]
(if-not (seq grouped-statements)
result
(recur
(rest grouped-statements)
(into
result
(let [statement-group (first grouped-statements)
resource (key statement-group)
types (find-types-of store resource)
statements (val statement-group)]
(transform-statements statements resource types context))))))))))
(defn transform-resource [resource context]
(if (< (count (:rootline context)) 6)
(loop [stores (stores-for resource)
representation nil]
(if (or (not (seq stores)) representation)
representation
(recur
(rest stores)
(let [store (first stores)]
(if-let [statements (find-matching store resource)]
(let [types (find-types-of store resource)]
(if (some #(= (identifier %) "http://spinrdf.org/sp#Construct") types)
(when-let [query (-> (filter #(= (-> % predicate identifier) "http://knowl-edge.org/ontology/core#query") statements) first object value)]
(when-let [service-statements (filter #(= (-> % predicate identifier) "http://knowl-edge.org/ontology/core#sparqlEndpoint") statements)]
(let [store (knowl.edge.store.Endpoint. (-> service-statements first object value) {})]
(transform-query query store context))))
(do
(when (not= default-store store) (add default-store statements))
(transform-statements statements resource types context)))))))))))
;; Entry Point
(defn dereference [resource]
(let [representation (or
(-?> (find-matching *store* nil (create-resource ["http://knowl-edge.org/ontology/core#" "represents"]) resource) first subject)
resource)]
(when-let [document (transform representation (Context. 0 []))]
(template/emit* document))))
(use 'knowl.edge.implementation.jena.transformation)
| true | ; Copyright (c) 2012 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
^{:doc "This namespace provides functionailty to transform a given resource recursively into a representation. It is part of the know:ledge management system."
:author "PI:NAME:<NAME>END_PI"}
knowl.edge.transformation
(:refer-clojure :exclude [namespace])
(:use
[clojure.contrib.core :only (-?>)]
knowl.edge.store
knowl.edge.model)
(:require
[clojure.contrib.str-utils2 :as string]
[clj-time.format :as time]
[net.cgrand.enlive-html :as template]))
(def ^:dynamic *template* (template/html-resource (java.io.File. "resources/private/templates/page.html")))
(def ^:dynamic *store* default-store)
;; Predicates
(defn- type= [resource]
#{(template/attr-has :typeof (identifier resource)) (template/attr-has :about (identifier resource))})
(defn- property= [resource]
(template/attr-has :property (identifier resource)))
(defn- relation= [resource]
(template/attr-has :rel (identifier resource)))
(defn- property? []
#{(template/attr? :property)
(template/attr-has :rel)})
(defn- set-datatype [datatype]
(template/set-attr :datatype (value datatype)))
(defn- set-language [language]
(comp (template/set-attr :lang (value language)) (template/set-attr :xml:lang (value language))))
(defn- set-content [resource]
(template/set-attr :content (value resource)))
(defn- set-resource [resource]
(template/set-attr :about (identifier resource)))
(defn- set-property [resource]
(template/set-attr :property (identifier resource)))
(defn- set-relation [resource]
(template/set-attr :rel (identifier resource)))
(defn- set-reference [resource]
(template/set-attr :href (identifier resource)))
(defn- set-types [types]
(template/set-attr :typeof (string/join " " (map str types))))
;; Helper functions
(defn- extract-predicates [snippet]
(filter #(string/contains? % ":")
(map #(or (-> % :attrs :property)
(-> % :attrs :rel))
(template/select snippet [(property?)]))))
;; Context
(defprotocol ContextHandling
"Functions for dealing with a transformations context (like render depth, the web request, or the current selector chain)."
(conj-selector [this selector] "Appends a selector to the selector-chain"))
(defrecord Context [depth rootline]
ContextHandling
(conj-selector
[this selector]
(update-in this [:rootline] #(into % selector))))
;; Transformations
(defprotocol Transformer
"Provides functions to transform the given subject into a different representation."
(transform [this context] "Transforms the subject."))
(extend-protocol Transformer
java.lang.String
(transform [this context] this)
nil
(transform [this context] nil))
(defmulti transform-literal (fn [literal context] (-> literal datatype value)))
(defmethod transform-literal :default [literal context] (value literal))
(defmethod transform-literal "http://www.w3.org/2001/XMLSchema#dateTime" [literal context]
(time/unparse (time/formatter "EEEE dd MMMM, yyyy") (time/parse (time/formatters :date-time-no-ms) (value literal))))
(defn transform-statement [statement context]
(let [predicate (predicate statement)
object (object statement)]
(if (= (identifier predicate) "http://dbpedia.org/ontology/wikiPageExternalLink")
(template/do->
(set-reference object)
(template/content (value object)))
(template/do->
(template/content (transform object context))
(if (satisfies? knowl.edge.model/Literal object)
(template/do->
(if-let [datatype (datatype object)]
(template/do->
(set-datatype datatype)
(set-content (value object)))
identity)
(if-let [language ( language object)]
(set-language language)
identity))
identity)))))
(defn transform-statements [statements resource types context]
(let [context (conj-selector context [(into #{} (map #(type= %) types))])
snippet (template/select *template* (:rootline context))
snippet-predicates (extract-predicates snippet)
grouped-statements (group-by #(predicate %) statements)
query-predicates (keys grouped-statements)]
(loop [snippet (template/transform snippet [template/root]
(template/do->
(set-types types)
(set-resource resource)))
grouped-statements grouped-statements]
(if-not (seq grouped-statements)
snippet
(recur
(let [predicate (ffirst grouped-statements)]
(template/at
snippet
[(property= predicate)] (template/do->
(set-property predicate)
(template/clone-for
[statement (second (first grouped-statements))]
(transform-statement statement context)))
[(relation= predicate)] (template/do->
(set-relation predicate)
(template/clone-for
[statement (second (first grouped-statements))]
(transform-statement statement context)))))
(rest grouped-statements))))))
(defn transform-query [query store context]
(when-let [statements (find-by-query store query)]
(do (when (not= default-store store) (add default-store statements))
(let [grouped-statements (group-by #(subject %) statements)]
(loop [grouped-statements grouped-statements
result []]
(if-not (seq grouped-statements)
result
(recur
(rest grouped-statements)
(into
result
(let [statement-group (first grouped-statements)
resource (key statement-group)
types (find-types-of store resource)
statements (val statement-group)]
(transform-statements statements resource types context))))))))))
(defn transform-resource [resource context]
(if (< (count (:rootline context)) 6)
(loop [stores (stores-for resource)
representation nil]
(if (or (not (seq stores)) representation)
representation
(recur
(rest stores)
(let [store (first stores)]
(if-let [statements (find-matching store resource)]
(let [types (find-types-of store resource)]
(if (some #(= (identifier %) "http://spinrdf.org/sp#Construct") types)
(when-let [query (-> (filter #(= (-> % predicate identifier) "http://knowl-edge.org/ontology/core#query") statements) first object value)]
(when-let [service-statements (filter #(= (-> % predicate identifier) "http://knowl-edge.org/ontology/core#sparqlEndpoint") statements)]
(let [store (knowl.edge.store.Endpoint. (-> service-statements first object value) {})]
(transform-query query store context))))
(do
(when (not= default-store store) (add default-store statements))
(transform-statements statements resource types context)))))))))))
;; Entry Point
(defn dereference [resource]
(let [representation (or
(-?> (find-matching *store* nil (create-resource ["http://knowl-edge.org/ontology/core#" "represents"]) resource) first subject)
resource)]
(when-let [document (transform representation (Context. 0 []))]
(template/emit* document))))
(use 'knowl.edge.implementation.jena.transformation)
|
[
{
"context": "ern :southern])\n\n(defn greet []\n (println \"Hello, Eric!\"))\n\n(def hello-world #'greet)\n\n(defn plus2 [x]\n ",
"end": 3562,
"score": 0.9985326528549194,
"start": 3558,
"tag": "NAME",
"value": "Eric"
}
] | src/volcanoes/core.clj | lispcast/volcanoes | 0 | (ns volcanoes.core
(:require [clojure.data.csv :as csv]
[clojure.java.io :as io]
[clojure.string :as str]
[volcanoes.protocol :as p]))
;; Main ways to execute code in your files
;; 1. Whole file
;; 2. Top-level form (expression)
;; 3. Single expression
;; 4. REPL Prompt
;; Ergonomics
;; 1. Autocomplete
;; unintrusive <-> intrusive
;; 2. Brace matching
;; 2.1 rainbow parens
;; 2.2 highlight matching
;; 3. Visual prompts
;; args
;; Structural Editing
;; 1. Nothing
;; 2. Simple
;; 3. Parinfer
;; 4. Paredit
;; Know your printers
;; 1. println
;; 2. prn
;; 3. pprint
;; def trick for storing values for use at the repl
(defn p [v & more]
(apply prn v more)
v)
;; Tricks
;; 1. doto
;; 2. define new print function
;; 3. _ (in a let)
;; Scientific Debugging
;; 1. Testing individual expressions to locate the problem
;; 2. Set up env using def
;; 3. Inside->out, outside->in
;; 5 ways to print
;; 1. println
;; 2. prn
;; 3. clojure.pprint/pprint
;; 4. clojure.pprint/print-table
;; 5. doseq print
;; Controlling printing
;; 1. *print-length*
;; 2. *print-level*
;; Playing with values
;; 1. Result history
;; *1, *2, *3, *e
;; 2. def values you want to save
;; 3. Ask for what you need
;; a. omit
;; b. summarize
;; c. metadata
(defonce csv-lines
(with-open [csv (io/reader (io/resource "GVP_Volcano_List_Holocene.csv"))]
(doall
(csv/read-csv csv))))
(defonce state (atom nil))
(defn reset-state []
(reset! state nil))
(comment (reset-state))
(defn setup []
)
(defn teardown []
)
(defn reset []
(teardown)
(setup))
(defn transform-header [header]
(if (= "Elevation (m)" header)
:elevation-meters
(-> header
(clojure.string/replace #"L" "l")
clojure.string/lower-case
(clojure.string/replace #" " "-")
keyword)))
(defn transform-header-row [header-line]
(map transform-header header-line))
(def volcano-records
(let [data-csv-lines (rest csv-lines)
header-line (transform-header-row (first data-csv-lines))
volcano-lines (rest data-csv-lines)]
(map (fn [volcano-line]
(zipmap header-line volcano-line))
volcano-lines)))
(defn parse-eruption-date [date]
(if (= "Unknown" date)
nil
(let [[_ y e] (re-matches #"(\d+)[\s]+(.+)" date)]
(cond
(= e "BCE")
(- (Integer/parseInt y))
(= e "CE")
(Integer/parseInt y)
:else
(throw (ex-info "Could not parse year." {:year date}))))))
(defn slash->set [s]
(set (map str/trim (str/split s #"/"))))
(defn parse-volcano-numbers [volcano]
(-> volcano
(update :elevation-meters #(Integer/parseInt %))
(update :longitude #(Double/parseDouble %))
(update :latitude #(Double/parseDouble %))
(assoc :last-eruption-parsed (parse-eruption-date (:last-known-eruption volcano)))
(update :tectonic-setting slash->set)
(update :dominant-rock-type slash->set)))
(def volcanoes-parsed
(mapv parse-volcano-numbers volcano-records))
(def types (set (map :primary-volcano-type volcano-records)))
;; Demonstrations of problems reloading
(defrecord Mountain [name]
p/Volcano
(erupt [m]
(println name "is erupting!")))
(defmulti hemisphere (fn [volcano]
[(pos? (:longitude volcano))
(pos? (:latitude volcano))]))
(defmethod hemisphere [true true]
[v]
[:eastern :northern])
(defmethod hemisphere [false false]
[v]
[:western :southern])
(defn greet []
(println "Hello, Eric!"))
(def hello-world #'greet)
(defn plus2 [x]
(+ x 2))
(defn times3 [x]
(* x 3))
(def x+2*3 (comp #'times3 #'plus2))
(fn [] (greet))
#'greet
(var greet)
#_ (println "All done!")
(comment
;; REPL-driven code
(let [volcano (nth volcanoes-parsed 100)]
(clojure.pprint/pprint volcano))
(let [volcano (first (filter #(= "221291" (:volcano-number %)) volcanoes-parsed))]
(clojure.pprint/pprint volcano)))
(comment
(parse-eruption-date "2014 CE")
(parse-eruption-date "187 BCE"))
(reset)
| 120019 | (ns volcanoes.core
(:require [clojure.data.csv :as csv]
[clojure.java.io :as io]
[clojure.string :as str]
[volcanoes.protocol :as p]))
;; Main ways to execute code in your files
;; 1. Whole file
;; 2. Top-level form (expression)
;; 3. Single expression
;; 4. REPL Prompt
;; Ergonomics
;; 1. Autocomplete
;; unintrusive <-> intrusive
;; 2. Brace matching
;; 2.1 rainbow parens
;; 2.2 highlight matching
;; 3. Visual prompts
;; args
;; Structural Editing
;; 1. Nothing
;; 2. Simple
;; 3. Parinfer
;; 4. Paredit
;; Know your printers
;; 1. println
;; 2. prn
;; 3. pprint
;; def trick for storing values for use at the repl
(defn p [v & more]
(apply prn v more)
v)
;; Tricks
;; 1. doto
;; 2. define new print function
;; 3. _ (in a let)
;; Scientific Debugging
;; 1. Testing individual expressions to locate the problem
;; 2. Set up env using def
;; 3. Inside->out, outside->in
;; 5 ways to print
;; 1. println
;; 2. prn
;; 3. clojure.pprint/pprint
;; 4. clojure.pprint/print-table
;; 5. doseq print
;; Controlling printing
;; 1. *print-length*
;; 2. *print-level*
;; Playing with values
;; 1. Result history
;; *1, *2, *3, *e
;; 2. def values you want to save
;; 3. Ask for what you need
;; a. omit
;; b. summarize
;; c. metadata
(defonce csv-lines
(with-open [csv (io/reader (io/resource "GVP_Volcano_List_Holocene.csv"))]
(doall
(csv/read-csv csv))))
(defonce state (atom nil))
(defn reset-state []
(reset! state nil))
(comment (reset-state))
(defn setup []
)
(defn teardown []
)
(defn reset []
(teardown)
(setup))
(defn transform-header [header]
(if (= "Elevation (m)" header)
:elevation-meters
(-> header
(clojure.string/replace #"L" "l")
clojure.string/lower-case
(clojure.string/replace #" " "-")
keyword)))
(defn transform-header-row [header-line]
(map transform-header header-line))
(def volcano-records
(let [data-csv-lines (rest csv-lines)
header-line (transform-header-row (first data-csv-lines))
volcano-lines (rest data-csv-lines)]
(map (fn [volcano-line]
(zipmap header-line volcano-line))
volcano-lines)))
(defn parse-eruption-date [date]
(if (= "Unknown" date)
nil
(let [[_ y e] (re-matches #"(\d+)[\s]+(.+)" date)]
(cond
(= e "BCE")
(- (Integer/parseInt y))
(= e "CE")
(Integer/parseInt y)
:else
(throw (ex-info "Could not parse year." {:year date}))))))
(defn slash->set [s]
(set (map str/trim (str/split s #"/"))))
(defn parse-volcano-numbers [volcano]
(-> volcano
(update :elevation-meters #(Integer/parseInt %))
(update :longitude #(Double/parseDouble %))
(update :latitude #(Double/parseDouble %))
(assoc :last-eruption-parsed (parse-eruption-date (:last-known-eruption volcano)))
(update :tectonic-setting slash->set)
(update :dominant-rock-type slash->set)))
(def volcanoes-parsed
(mapv parse-volcano-numbers volcano-records))
(def types (set (map :primary-volcano-type volcano-records)))
;; Demonstrations of problems reloading
(defrecord Mountain [name]
p/Volcano
(erupt [m]
(println name "is erupting!")))
(defmulti hemisphere (fn [volcano]
[(pos? (:longitude volcano))
(pos? (:latitude volcano))]))
(defmethod hemisphere [true true]
[v]
[:eastern :northern])
(defmethod hemisphere [false false]
[v]
[:western :southern])
(defn greet []
(println "Hello, <NAME>!"))
(def hello-world #'greet)
(defn plus2 [x]
(+ x 2))
(defn times3 [x]
(* x 3))
(def x+2*3 (comp #'times3 #'plus2))
(fn [] (greet))
#'greet
(var greet)
#_ (println "All done!")
(comment
;; REPL-driven code
(let [volcano (nth volcanoes-parsed 100)]
(clojure.pprint/pprint volcano))
(let [volcano (first (filter #(= "221291" (:volcano-number %)) volcanoes-parsed))]
(clojure.pprint/pprint volcano)))
(comment
(parse-eruption-date "2014 CE")
(parse-eruption-date "187 BCE"))
(reset)
| true | (ns volcanoes.core
(:require [clojure.data.csv :as csv]
[clojure.java.io :as io]
[clojure.string :as str]
[volcanoes.protocol :as p]))
;; Main ways to execute code in your files
;; 1. Whole file
;; 2. Top-level form (expression)
;; 3. Single expression
;; 4. REPL Prompt
;; Ergonomics
;; 1. Autocomplete
;; unintrusive <-> intrusive
;; 2. Brace matching
;; 2.1 rainbow parens
;; 2.2 highlight matching
;; 3. Visual prompts
;; args
;; Structural Editing
;; 1. Nothing
;; 2. Simple
;; 3. Parinfer
;; 4. Paredit
;; Know your printers
;; 1. println
;; 2. prn
;; 3. pprint
;; def trick for storing values for use at the repl
(defn p [v & more]
(apply prn v more)
v)
;; Tricks
;; 1. doto
;; 2. define new print function
;; 3. _ (in a let)
;; Scientific Debugging
;; 1. Testing individual expressions to locate the problem
;; 2. Set up env using def
;; 3. Inside->out, outside->in
;; 5 ways to print
;; 1. println
;; 2. prn
;; 3. clojure.pprint/pprint
;; 4. clojure.pprint/print-table
;; 5. doseq print
;; Controlling printing
;; 1. *print-length*
;; 2. *print-level*
;; Playing with values
;; 1. Result history
;; *1, *2, *3, *e
;; 2. def values you want to save
;; 3. Ask for what you need
;; a. omit
;; b. summarize
;; c. metadata
(defonce csv-lines
(with-open [csv (io/reader (io/resource "GVP_Volcano_List_Holocene.csv"))]
(doall
(csv/read-csv csv))))
(defonce state (atom nil))
(defn reset-state []
(reset! state nil))
(comment (reset-state))
(defn setup []
)
(defn teardown []
)
(defn reset []
(teardown)
(setup))
(defn transform-header [header]
(if (= "Elevation (m)" header)
:elevation-meters
(-> header
(clojure.string/replace #"L" "l")
clojure.string/lower-case
(clojure.string/replace #" " "-")
keyword)))
(defn transform-header-row [header-line]
(map transform-header header-line))
(def volcano-records
(let [data-csv-lines (rest csv-lines)
header-line (transform-header-row (first data-csv-lines))
volcano-lines (rest data-csv-lines)]
(map (fn [volcano-line]
(zipmap header-line volcano-line))
volcano-lines)))
(defn parse-eruption-date [date]
(if (= "Unknown" date)
nil
(let [[_ y e] (re-matches #"(\d+)[\s]+(.+)" date)]
(cond
(= e "BCE")
(- (Integer/parseInt y))
(= e "CE")
(Integer/parseInt y)
:else
(throw (ex-info "Could not parse year." {:year date}))))))
(defn slash->set [s]
(set (map str/trim (str/split s #"/"))))
(defn parse-volcano-numbers [volcano]
(-> volcano
(update :elevation-meters #(Integer/parseInt %))
(update :longitude #(Double/parseDouble %))
(update :latitude #(Double/parseDouble %))
(assoc :last-eruption-parsed (parse-eruption-date (:last-known-eruption volcano)))
(update :tectonic-setting slash->set)
(update :dominant-rock-type slash->set)))
(def volcanoes-parsed
(mapv parse-volcano-numbers volcano-records))
(def types (set (map :primary-volcano-type volcano-records)))
;; Demonstrations of problems reloading
(defrecord Mountain [name]
p/Volcano
(erupt [m]
(println name "is erupting!")))
(defmulti hemisphere (fn [volcano]
[(pos? (:longitude volcano))
(pos? (:latitude volcano))]))
(defmethod hemisphere [true true]
[v]
[:eastern :northern])
(defmethod hemisphere [false false]
[v]
[:western :southern])
(defn greet []
(println "Hello, PI:NAME:<NAME>END_PI!"))
(def hello-world #'greet)
(defn plus2 [x]
(+ x 2))
(defn times3 [x]
(* x 3))
(def x+2*3 (comp #'times3 #'plus2))
(fn [] (greet))
#'greet
(var greet)
#_ (println "All done!")
(comment
;; REPL-driven code
(let [volcano (nth volcanoes-parsed 100)]
(clojure.pprint/pprint volcano))
(let [volcano (first (filter #(= "221291" (:volcano-number %)) volcanoes-parsed))]
(clojure.pprint/pprint volcano)))
(comment
(parse-eruption-date "2014 CE")
(parse-eruption-date "187 BCE"))
(reset)
|
[
{
"context": " [hara.common.watch :as watch]\n [robert.hooke]))\n\n;;; (use '[clojure.tools.nrepl.server :on",
"end": 399,
"score": 0.6826303601264954,
"start": 391,
"tag": "USERNAME",
"value": "robert.h"
},
{
"context": "hara.common.watch :as watch]\n [robert.hooke]))\n\n;;; (use '[clojure.tools.nrepl.server :only",
"end": 401,
"score": 0.49334752559661865,
"start": 399,
"tag": "NAME",
"value": "oo"
},
{
"context": "ra.common.watch :as watch]\n [robert.hooke]))\n\n;;; (use '[clojure.tools.nrepl.server :only (",
"end": 403,
"score": 0.5771174430847168,
"start": 401,
"tag": "USERNAME",
"value": "ke"
}
] | src/leiningen/aar_tool.clj | R1ck77/aar-tool | 1 | (ns leiningen.aar-tool
(:use [leiningen.core.main :only [info abort debug warn]]
[clojure.java.shell :only [sh]]
[clojure.xml :as xml]
[clojure.java.io :as io]
[couchgames.utils.zip :as czip])
(:import [java.io File ByteArrayInputStream]
[java.nio.file Paths])
(:require [hara.io.watch]
[hara.common.watch :as watch]
[robert.hooke]))
;;; (use '[clojure.tools.nrepl.server :only (start-server stop-server)])
;;; (defonce server (start-server :port 7888))
(def android-home-env-var "ANDROID_HOME")
(def aar-build-dir "aar")
(def android-manifest-name "AndroidManifest.xml")
(def expected-jar-name "classes.jar")
(def r-txt "R.txt")
(def non-res-files [#".*[.]swp$" #".*~"])
(defn get-package-from-manifest [slurpable-content]
(try
(or (:package (:attrs (xml/parse (io/input-stream slurpable-content))))
(throw (RuntimeException. "package attribute not found")))
(catch Exception e (abort (str "Unable to read the package from the manifest (" (.getMessage e) ")")))))
(defn get-project-package [{manifest :android-manifest}]
(get-package-from-manifest manifest))
(defn output-directory-from-package [package]
(let [components (clojure.string/split package #"[.]")]
(case (count components)
0 (throw (RuntimeException. "Unexpected number of package components (0)"))
1 (first components)
(.toString (java.nio.file.Paths/get (first components) (into-array (rest components)))))))
(defn R-class-file? [file]
{:pre [(instance? File file)]}
(and (not (.isDirectory file))
(re-find #"^R([$].+)?[.]class" (.getName file))))
(defn get-R-directory [{target :target-path :as project} package-path]
(.toString (Paths/get target (into-array ["classes" package-path]))))
(defn list-dir [path]
(->> path io/file .list (map io/file)))
(defn R-files-in-directory
[path]
{:pre [(instance? String path)]}
(map #(io/file path (.toString %)) (filter R-class-file? (list-dir path))))
(defn R-class-files [project]
(R-files-in-directory (get-R-directory project (output-directory-from-package (get-project-package project)))))
(defn- get-api-level
"Return the value of maxSdkVersion or targetSdkVersion or minSdkVersion or 1"
[manifest-path]
(let [attrs (:attrs (first (filter #(= (:tag %) :uses-sdk) (:content (xml/parse manifest-path)))))]
(Integer/valueOf (or (:android:maxSdkVersion attrs)
(:android:targetSdkVersion attrs)
(:android:minSdkVersion attrs)
"1"))))
(defn readable-file? [file]
(and (.exists file)
(.canRead file)))
(defn android-jar-file [sdk version]
(io/file (apply str (interpose File/separator
[sdk "platforms" (str "android-" version) "android.jar"]))))
(defn check-jar-file [file]
(if (readable-file? file)
file
(abort (str "\"" (.getAbsolutePath file) "\" doesn't exist, or is not readable"))))
(defn get-android-jar-location
[sdk version]
(check-jar-file (android-jar-file sdk version)))
(defn- get-all-build-tools
"Return a sequence of all build-tools versions available"
[sdk]
(seq (.list (io/file sdk "build-tools"))))
(defn is-directory? [file]
(.isDirectory file))
(defn composite-path-is-dir? [base-path child-path]
(is-directory? (io/file (str base-path File/separator child-path))))
(defn all-directories?
"Returns true if and only if both base and all its childs are directories"
[base-path & child-paths]
(and
(is-directory? base-path)
(reduce (fn [acc child] (and acc (composite-path-is-dir? base-path child)))
true child-paths)))
(defn- android-home-is-valid? [android-home]
"Check if the ANDROID_HOME variable points to a valid android-sdk directory
The check assumes that ANDROID_HOME contains a number of directories"
(apply all-directories? (map io/file [android-home "build-tools" "platforms" "tools"])))
(defn get-env [var]
(System/getenv var))
(defn get-android-home []
(if-let [android-home (get-env android-home-env-var)]
android-home
(abort (str "The variable \"" android-home-env-var "\" not set"))))
(defn get-most-recent-aapt-location [sdk version]
"Validate the sdk and return the highest versioned aapt"
(if (not (android-home-is-valid? sdk))
(throw (RuntimeException. "sdk not recognized: is the content of ANDROID_HOME valid?"))
(let [aapt (io/file (apply str (interpose File/separator [sdk "build-tools" version "aapt"])))]
(if (and (.exists aapt) (.canExecute aapt))
(.getAbsolutePath aapt)
(throw (RuntimeException. (str "\"" (.getAbsolutePath aapt) "\" doesn't exist, or is not an executable")))))))
(defn- get-aapt-location
"Return the path of aapt for a specific version of the build tools in the sdk using the sdk found with 'get-android-home' and the
highest versioned build tool found with 'get-all-build-tools'.
Throw a runtime exception if not found or not executable"
([sdk]
(get-most-recent-aapt-location sdk (last (sort (get-all-build-tools sdk))))))
(defn- android-jar-from-manifest
"Return the path of android.jar from the android manifest and the environment"
[manifest-path]
(.getAbsolutePath (get-android-jar-location (get-android-home) (get-api-level manifest-path))))
(defn- get-arguments
"Read the arguments from the project, fail if any is missing"
[project xs]
(debug "Ensuring that the project arguments are there")
(reduce (fn [m v]
(if (contains? project v)
(assoc m v (get project v))
(abort (str "Unable to find " v " in project.clj!"))))
{}
xs))
(defn- check-is-directory!
"Check whether the specified path is a directory
If create-if-missing is set to true, the function will try to fix that, no solution if the file exists and is not a directory"
([path] (check-is-directory! path false))
([path create-if-missing]
(debug (str "Checking for \"" path "\" existance"))
(let [fpath (File. path)]
(if (not (.isDirectory fpath))
(if (and create-if-missing (not (.exists fpath)))
(do
(debug (str "The path \"" path "\" is not present: creating…"))
(.mkdirs fpath)
(check-is-directory! path false))
(abort (str "The path \"" path "\" doesn't exist, or is not a directory")))))))
(defn- path-from-dirs
"creating a Path in java 7 from clojure is messy"
[base & elements]
(Paths/get base (into-array String elements)))
(defn- copy-file
"Kudos to this guy: https://clojuredocs.org/clojure.java.io/copy"
[source-path dest-path]
(io/copy (io/file source-path) (io/file dest-path)))
;;;; TODO/FIXME: The "src" string is completely bogus and will break
;;;; watch-res if we specify a different source dir in leinigen
(defn- run-aapt
"Run the aapt command with the parameters required to generate a R.txt file
This will also generate a R.java file in destpath/src"
[aapt destpath sympath manifest android-jar res]
(let [src-path (if (nil? destpath)
(do (warn "Using hard-coded src-java as R.java path") "src-java")
destpath)]
(check-is-directory! src-path true)
(let [sh-arguments (if (nil? sympath)
(list aapt
"packange"
"-f"
"-m"
"-M" manifest
"-I" android-jar
"-S" res
"-J" src-path)
(list aapt
"package"
"--output-text-symbols" sympath
"-f"
"-m"
"-M" manifest
"-I" android-jar
"-S" res
"-J" src-path))
res (do
(debug "About to run aapt with arguments: " sh-arguments)
(apply sh sh-arguments))]
res)))
(defn- filter-temp
"Remove from the list of paths/pairs the files ending with ~"
[xs]
(filter
(fn [v]
(not (re-matches #".*~$" (if (string? v)
v
(first v))))) xs))
(defn- zip-contents
"Create a .aar library in a temporary location. Returns the path"
[work-path manifest res-dir jar]
(let [
full-r-path (.toString (path-from-dirs work-path r-txt))
aar-file (.toString (path-from-dirs work-path "library.aar"))
res-files (filter-temp (files-in-dir res-dir (.getParent (File. res-dir))))
zip-arguments (vec (concat [aar-file [jar expected-jar-name] [full-r-path r-txt] [manifest android-manifest-name]]
res-files))]
(debug "invoking the zip command with arguments:" zip-arguments)
(if (nil? (apply czip/zip-files zip-arguments))
(abort "Unable to compress" jar full-r-path "and" manifest "into" aar-file)
aar-file)))
(defn convert-path-to-absolute [path]
(-> (File. path)
.toPath .toAbsolutePath .normalize .toString))
(defn absolutize-paths-selectively [m-options s-keys]
(into m-options
(map (fn [[key value]]
(vector key (convert-path-to-absolute value)))
(filter #(-> % first s-keys) m-options))))
(defn- move [source destination]
(debug "Moving" source "to" destination)
(try
(.delete (File. destination))
(catch Exception e (abort "Unable to remove the destination file" destination "to make space for the resulting aar")))
(.renameTo (File. source) (File. destination)))
(defn- check-arguments [params]
(let [manifest (:android-manifest params)]
(if (not= "res" (.getName (File. (:res params)))) (abort "The :res option must point to a directory named \"res\""))
(if (not= android-manifest-name (.getName (File. manifest))) (abort "The :res option must point to a directory named \"" android-manifest-name "\""))
(if (not (.exists (File. manifest))) (abort (str "The file \"" manifest "\" does not exist")))
(if (not= (:aot params) [:all]) (abort (str ":aot :all must be specified in project.clj!")))))
(defn- run-aapt-noisy [& args]
(let [res (apply run-aapt args)]
(if (not= 0 (:exit res))
(abort (str "Invocation of aapt failed with error: \"" (:err res) "\"")))))
(defn wipe-extra-classes [project]
(dorun
(map (fn [file]
(info (str "Removing " (.getName file) "…"))
(.delete file)) (R-class-files project))))
(defn leiningen-task-hook [function task project args]
(debug "About to execute the task" task)
;;; Apply the task
(let [result (function task project args)]
(debug "Task" task "executed")
;;; if the task is javac, remove the R*.class after compilation
(if (= task "compile")
(wipe-extra-classes project))
result))
(defn activate-compile-hook []
(robert.hooke/add-hook #'leiningen.core.main/apply-task #'leiningen-task-hook))
(def create-R)
(defn create-aar
"Create a AAR library suitable for Android integration"
[project arguments]
(create-R project arguments)
(activate-compile-hook)
(let [my-args (absolutize-paths-selectively
(get-arguments project [:aar-name :aot :res :source-paths :target-path :android-manifest])
#{:aar-name :res :target-path :android-manifest})]
(check-arguments my-args)
;;; TODO/FIXME: get the jar name in a more robust way (use the jar task function directly?)
(let [jar-path (second (first (leiningen.core.main/apply-task "jar" project [])))
tmp-path (.toString (path-from-dirs (:target-path my-args) aar-build-dir))
dest-path (.toString (path-from-dirs tmp-path "src"))]
(debug "The jar is: " jar-path)
(debug "The aar compilation will be made in " tmp-path)
(check-is-directory! (:res my-args))
(check-is-directory! tmp-path true)
(run-aapt-noisy (get-aapt-location (get-android-home))
dest-path
tmp-path
(:android-manifest my-args)
(android-jar-from-manifest (:android-manifest my-args))
(:res my-args))
(let [aar-location (zip-contents tmp-path
(:android-manifest my-args)
(:res my-args)
jar-path)]
(move aar-location (:aar-name my-args))
(shutdown-agents)
(info "Created" (:aar-name my-args))))))
(defn- clear-trailing [char string]
(apply str (reverse (drop-while (hash-set char) (reverse string)))))
(defn- generate-R-java [aapt manifest android-jar res src]
(let [result (run-aapt aapt src nil manifest android-jar res)]
(info
(case (:exit result)
0 "✓ R.java updated"
(clear-trailing \newline (str "❌ error with R.java generation: " ( :err result)))))
(flush)
result))
(defn- watch-res-directory
"Update the contents of the R.java file when a :res file changes"
[my-args]
(let [aapt (get-aapt-location (get-android-home))
manifest (:android-manifest my-args)
android-jar (android-jar-from-manifest (:android-manifest my-args))
res (:res my-args)
dir (:res my-args)
java-src (first (:java-src-paths my-args))
to-be-excluded? (fn [path]
(reduce (fn [acc value] (or acc (re-matches value path)))
false
non-res-files))]
(generate-R-java aapt manifest android-jar res java-src)
(watch/add (clojure.java.io/file dir)
:my-watch
(fn [obj key prev next]
(let [path (.toString (second next))]
(if (not (to-be-excluded? path))
(generate-R-java aapt manifest android-jar res java-src))))
{
:types #{:create :modify :delete}})))
(defn- watches-for-file?
"Returns true if the watch listener disappeared
This can actually happen only if the watch sort of stops itself"
[file]
(> (count (watch/list file)) 0))
(defn- blocking-watch
"Starts a watch on the specific directory, and blocks"
[project]
(let [args (absolutize-paths-selectively
(get-arguments project
[:res :source-paths :target-path :android-manifest])
#{:res :target-path :android-manifest})]
(watch-res-directory args)
(loop [f (clojure.java.io/file (:res project))]
(if (watches-for-file? f)
(do
(Thread/sleep 100)
(recur f))))))
(defn watch-res
"Watch the res directory and update the R.java if any file changes
The updates are applied directly into the src directory"
[project & args]
(info "Starting a watch on the res directory…")
(blocking-watch project))
(defn create-R
"Create a R.java file with the information in the res directory
The file is created in the src directory"
[project & args]
(let [args (absolutize-paths-selectively
(get-arguments project
[:java-source-paths :res :source-paths :target-path :android-manifest])
#{:res :target-path :android-manifest})
aapt (get-aapt-location (get-android-home))
manifest (:android-manifest args)
android-jar (android-jar-from-manifest manifest)
res (:res args)
dir (:res args)
java-src (first (:java-source-paths args))]
(if (nil? java-src)
(abort "no :java-src-paths specified (at least one is needed)")
(do
(info "Using '" java-src "' for the R.java output…")
(generate-R-java aapt manifest android-jar res java-src)))))
(defn leiningen-test [project & args]
(activate-compile-hook)
(leiningen.core.main/apply-task "jar" project [])
(shutdown-agents))
(defn aar-tool
"Functions for android development"
{:subtasks [#'create-aar #'watch-res #'create-R]}
[project & args]
(case (first args)
nil (info "An action must be provided")
"create-aar" (create-aar project (rest args))
"watch-res" (watch-res project (rest args))
"create-R" (create-R project (rest args))
(abort "Unknown option")))
| 9531 | (ns leiningen.aar-tool
(:use [leiningen.core.main :only [info abort debug warn]]
[clojure.java.shell :only [sh]]
[clojure.xml :as xml]
[clojure.java.io :as io]
[couchgames.utils.zip :as czip])
(:import [java.io File ByteArrayInputStream]
[java.nio.file Paths])
(:require [hara.io.watch]
[hara.common.watch :as watch]
[robert.h<NAME>ke]))
;;; (use '[clojure.tools.nrepl.server :only (start-server stop-server)])
;;; (defonce server (start-server :port 7888))
(def android-home-env-var "ANDROID_HOME")
(def aar-build-dir "aar")
(def android-manifest-name "AndroidManifest.xml")
(def expected-jar-name "classes.jar")
(def r-txt "R.txt")
(def non-res-files [#".*[.]swp$" #".*~"])
(defn get-package-from-manifest [slurpable-content]
(try
(or (:package (:attrs (xml/parse (io/input-stream slurpable-content))))
(throw (RuntimeException. "package attribute not found")))
(catch Exception e (abort (str "Unable to read the package from the manifest (" (.getMessage e) ")")))))
(defn get-project-package [{manifest :android-manifest}]
(get-package-from-manifest manifest))
(defn output-directory-from-package [package]
(let [components (clojure.string/split package #"[.]")]
(case (count components)
0 (throw (RuntimeException. "Unexpected number of package components (0)"))
1 (first components)
(.toString (java.nio.file.Paths/get (first components) (into-array (rest components)))))))
(defn R-class-file? [file]
{:pre [(instance? File file)]}
(and (not (.isDirectory file))
(re-find #"^R([$].+)?[.]class" (.getName file))))
(defn get-R-directory [{target :target-path :as project} package-path]
(.toString (Paths/get target (into-array ["classes" package-path]))))
(defn list-dir [path]
(->> path io/file .list (map io/file)))
(defn R-files-in-directory
[path]
{:pre [(instance? String path)]}
(map #(io/file path (.toString %)) (filter R-class-file? (list-dir path))))
(defn R-class-files [project]
(R-files-in-directory (get-R-directory project (output-directory-from-package (get-project-package project)))))
(defn- get-api-level
"Return the value of maxSdkVersion or targetSdkVersion or minSdkVersion or 1"
[manifest-path]
(let [attrs (:attrs (first (filter #(= (:tag %) :uses-sdk) (:content (xml/parse manifest-path)))))]
(Integer/valueOf (or (:android:maxSdkVersion attrs)
(:android:targetSdkVersion attrs)
(:android:minSdkVersion attrs)
"1"))))
(defn readable-file? [file]
(and (.exists file)
(.canRead file)))
(defn android-jar-file [sdk version]
(io/file (apply str (interpose File/separator
[sdk "platforms" (str "android-" version) "android.jar"]))))
(defn check-jar-file [file]
(if (readable-file? file)
file
(abort (str "\"" (.getAbsolutePath file) "\" doesn't exist, or is not readable"))))
(defn get-android-jar-location
[sdk version]
(check-jar-file (android-jar-file sdk version)))
(defn- get-all-build-tools
"Return a sequence of all build-tools versions available"
[sdk]
(seq (.list (io/file sdk "build-tools"))))
(defn is-directory? [file]
(.isDirectory file))
(defn composite-path-is-dir? [base-path child-path]
(is-directory? (io/file (str base-path File/separator child-path))))
(defn all-directories?
"Returns true if and only if both base and all its childs are directories"
[base-path & child-paths]
(and
(is-directory? base-path)
(reduce (fn [acc child] (and acc (composite-path-is-dir? base-path child)))
true child-paths)))
(defn- android-home-is-valid? [android-home]
"Check if the ANDROID_HOME variable points to a valid android-sdk directory
The check assumes that ANDROID_HOME contains a number of directories"
(apply all-directories? (map io/file [android-home "build-tools" "platforms" "tools"])))
(defn get-env [var]
(System/getenv var))
(defn get-android-home []
(if-let [android-home (get-env android-home-env-var)]
android-home
(abort (str "The variable \"" android-home-env-var "\" not set"))))
(defn get-most-recent-aapt-location [sdk version]
"Validate the sdk and return the highest versioned aapt"
(if (not (android-home-is-valid? sdk))
(throw (RuntimeException. "sdk not recognized: is the content of ANDROID_HOME valid?"))
(let [aapt (io/file (apply str (interpose File/separator [sdk "build-tools" version "aapt"])))]
(if (and (.exists aapt) (.canExecute aapt))
(.getAbsolutePath aapt)
(throw (RuntimeException. (str "\"" (.getAbsolutePath aapt) "\" doesn't exist, or is not an executable")))))))
(defn- get-aapt-location
"Return the path of aapt for a specific version of the build tools in the sdk using the sdk found with 'get-android-home' and the
highest versioned build tool found with 'get-all-build-tools'.
Throw a runtime exception if not found or not executable"
([sdk]
(get-most-recent-aapt-location sdk (last (sort (get-all-build-tools sdk))))))
(defn- android-jar-from-manifest
"Return the path of android.jar from the android manifest and the environment"
[manifest-path]
(.getAbsolutePath (get-android-jar-location (get-android-home) (get-api-level manifest-path))))
(defn- get-arguments
"Read the arguments from the project, fail if any is missing"
[project xs]
(debug "Ensuring that the project arguments are there")
(reduce (fn [m v]
(if (contains? project v)
(assoc m v (get project v))
(abort (str "Unable to find " v " in project.clj!"))))
{}
xs))
(defn- check-is-directory!
"Check whether the specified path is a directory
If create-if-missing is set to true, the function will try to fix that, no solution if the file exists and is not a directory"
([path] (check-is-directory! path false))
([path create-if-missing]
(debug (str "Checking for \"" path "\" existance"))
(let [fpath (File. path)]
(if (not (.isDirectory fpath))
(if (and create-if-missing (not (.exists fpath)))
(do
(debug (str "The path \"" path "\" is not present: creating…"))
(.mkdirs fpath)
(check-is-directory! path false))
(abort (str "The path \"" path "\" doesn't exist, or is not a directory")))))))
(defn- path-from-dirs
"creating a Path in java 7 from clojure is messy"
[base & elements]
(Paths/get base (into-array String elements)))
(defn- copy-file
"Kudos to this guy: https://clojuredocs.org/clojure.java.io/copy"
[source-path dest-path]
(io/copy (io/file source-path) (io/file dest-path)))
;;;; TODO/FIXME: The "src" string is completely bogus and will break
;;;; watch-res if we specify a different source dir in leinigen
(defn- run-aapt
"Run the aapt command with the parameters required to generate a R.txt file
This will also generate a R.java file in destpath/src"
[aapt destpath sympath manifest android-jar res]
(let [src-path (if (nil? destpath)
(do (warn "Using hard-coded src-java as R.java path") "src-java")
destpath)]
(check-is-directory! src-path true)
(let [sh-arguments (if (nil? sympath)
(list aapt
"packange"
"-f"
"-m"
"-M" manifest
"-I" android-jar
"-S" res
"-J" src-path)
(list aapt
"package"
"--output-text-symbols" sympath
"-f"
"-m"
"-M" manifest
"-I" android-jar
"-S" res
"-J" src-path))
res (do
(debug "About to run aapt with arguments: " sh-arguments)
(apply sh sh-arguments))]
res)))
(defn- filter-temp
"Remove from the list of paths/pairs the files ending with ~"
[xs]
(filter
(fn [v]
(not (re-matches #".*~$" (if (string? v)
v
(first v))))) xs))
(defn- zip-contents
"Create a .aar library in a temporary location. Returns the path"
[work-path manifest res-dir jar]
(let [
full-r-path (.toString (path-from-dirs work-path r-txt))
aar-file (.toString (path-from-dirs work-path "library.aar"))
res-files (filter-temp (files-in-dir res-dir (.getParent (File. res-dir))))
zip-arguments (vec (concat [aar-file [jar expected-jar-name] [full-r-path r-txt] [manifest android-manifest-name]]
res-files))]
(debug "invoking the zip command with arguments:" zip-arguments)
(if (nil? (apply czip/zip-files zip-arguments))
(abort "Unable to compress" jar full-r-path "and" manifest "into" aar-file)
aar-file)))
(defn convert-path-to-absolute [path]
(-> (File. path)
.toPath .toAbsolutePath .normalize .toString))
(defn absolutize-paths-selectively [m-options s-keys]
(into m-options
(map (fn [[key value]]
(vector key (convert-path-to-absolute value)))
(filter #(-> % first s-keys) m-options))))
(defn- move [source destination]
(debug "Moving" source "to" destination)
(try
(.delete (File. destination))
(catch Exception e (abort "Unable to remove the destination file" destination "to make space for the resulting aar")))
(.renameTo (File. source) (File. destination)))
(defn- check-arguments [params]
(let [manifest (:android-manifest params)]
(if (not= "res" (.getName (File. (:res params)))) (abort "The :res option must point to a directory named \"res\""))
(if (not= android-manifest-name (.getName (File. manifest))) (abort "The :res option must point to a directory named \"" android-manifest-name "\""))
(if (not (.exists (File. manifest))) (abort (str "The file \"" manifest "\" does not exist")))
(if (not= (:aot params) [:all]) (abort (str ":aot :all must be specified in project.clj!")))))
(defn- run-aapt-noisy [& args]
(let [res (apply run-aapt args)]
(if (not= 0 (:exit res))
(abort (str "Invocation of aapt failed with error: \"" (:err res) "\"")))))
(defn wipe-extra-classes [project]
(dorun
(map (fn [file]
(info (str "Removing " (.getName file) "…"))
(.delete file)) (R-class-files project))))
(defn leiningen-task-hook [function task project args]
(debug "About to execute the task" task)
;;; Apply the task
(let [result (function task project args)]
(debug "Task" task "executed")
;;; if the task is javac, remove the R*.class after compilation
(if (= task "compile")
(wipe-extra-classes project))
result))
(defn activate-compile-hook []
(robert.hooke/add-hook #'leiningen.core.main/apply-task #'leiningen-task-hook))
(def create-R)
(defn create-aar
"Create a AAR library suitable for Android integration"
[project arguments]
(create-R project arguments)
(activate-compile-hook)
(let [my-args (absolutize-paths-selectively
(get-arguments project [:aar-name :aot :res :source-paths :target-path :android-manifest])
#{:aar-name :res :target-path :android-manifest})]
(check-arguments my-args)
;;; TODO/FIXME: get the jar name in a more robust way (use the jar task function directly?)
(let [jar-path (second (first (leiningen.core.main/apply-task "jar" project [])))
tmp-path (.toString (path-from-dirs (:target-path my-args) aar-build-dir))
dest-path (.toString (path-from-dirs tmp-path "src"))]
(debug "The jar is: " jar-path)
(debug "The aar compilation will be made in " tmp-path)
(check-is-directory! (:res my-args))
(check-is-directory! tmp-path true)
(run-aapt-noisy (get-aapt-location (get-android-home))
dest-path
tmp-path
(:android-manifest my-args)
(android-jar-from-manifest (:android-manifest my-args))
(:res my-args))
(let [aar-location (zip-contents tmp-path
(:android-manifest my-args)
(:res my-args)
jar-path)]
(move aar-location (:aar-name my-args))
(shutdown-agents)
(info "Created" (:aar-name my-args))))))
(defn- clear-trailing [char string]
(apply str (reverse (drop-while (hash-set char) (reverse string)))))
(defn- generate-R-java [aapt manifest android-jar res src]
(let [result (run-aapt aapt src nil manifest android-jar res)]
(info
(case (:exit result)
0 "✓ R.java updated"
(clear-trailing \newline (str "❌ error with R.java generation: " ( :err result)))))
(flush)
result))
(defn- watch-res-directory
"Update the contents of the R.java file when a :res file changes"
[my-args]
(let [aapt (get-aapt-location (get-android-home))
manifest (:android-manifest my-args)
android-jar (android-jar-from-manifest (:android-manifest my-args))
res (:res my-args)
dir (:res my-args)
java-src (first (:java-src-paths my-args))
to-be-excluded? (fn [path]
(reduce (fn [acc value] (or acc (re-matches value path)))
false
non-res-files))]
(generate-R-java aapt manifest android-jar res java-src)
(watch/add (clojure.java.io/file dir)
:my-watch
(fn [obj key prev next]
(let [path (.toString (second next))]
(if (not (to-be-excluded? path))
(generate-R-java aapt manifest android-jar res java-src))))
{
:types #{:create :modify :delete}})))
(defn- watches-for-file?
"Returns true if the watch listener disappeared
This can actually happen only if the watch sort of stops itself"
[file]
(> (count (watch/list file)) 0))
(defn- blocking-watch
"Starts a watch on the specific directory, and blocks"
[project]
(let [args (absolutize-paths-selectively
(get-arguments project
[:res :source-paths :target-path :android-manifest])
#{:res :target-path :android-manifest})]
(watch-res-directory args)
(loop [f (clojure.java.io/file (:res project))]
(if (watches-for-file? f)
(do
(Thread/sleep 100)
(recur f))))))
(defn watch-res
"Watch the res directory and update the R.java if any file changes
The updates are applied directly into the src directory"
[project & args]
(info "Starting a watch on the res directory…")
(blocking-watch project))
(defn create-R
"Create a R.java file with the information in the res directory
The file is created in the src directory"
[project & args]
(let [args (absolutize-paths-selectively
(get-arguments project
[:java-source-paths :res :source-paths :target-path :android-manifest])
#{:res :target-path :android-manifest})
aapt (get-aapt-location (get-android-home))
manifest (:android-manifest args)
android-jar (android-jar-from-manifest manifest)
res (:res args)
dir (:res args)
java-src (first (:java-source-paths args))]
(if (nil? java-src)
(abort "no :java-src-paths specified (at least one is needed)")
(do
(info "Using '" java-src "' for the R.java output…")
(generate-R-java aapt manifest android-jar res java-src)))))
(defn leiningen-test [project & args]
(activate-compile-hook)
(leiningen.core.main/apply-task "jar" project [])
(shutdown-agents))
(defn aar-tool
"Functions for android development"
{:subtasks [#'create-aar #'watch-res #'create-R]}
[project & args]
(case (first args)
nil (info "An action must be provided")
"create-aar" (create-aar project (rest args))
"watch-res" (watch-res project (rest args))
"create-R" (create-R project (rest args))
(abort "Unknown option")))
| true | (ns leiningen.aar-tool
(:use [leiningen.core.main :only [info abort debug warn]]
[clojure.java.shell :only [sh]]
[clojure.xml :as xml]
[clojure.java.io :as io]
[couchgames.utils.zip :as czip])
(:import [java.io File ByteArrayInputStream]
[java.nio.file Paths])
(:require [hara.io.watch]
[hara.common.watch :as watch]
[robert.hPI:NAME:<NAME>END_PIke]))
;;; (use '[clojure.tools.nrepl.server :only (start-server stop-server)])
;;; (defonce server (start-server :port 7888))
(def android-home-env-var "ANDROID_HOME")
(def aar-build-dir "aar")
(def android-manifest-name "AndroidManifest.xml")
(def expected-jar-name "classes.jar")
(def r-txt "R.txt")
(def non-res-files [#".*[.]swp$" #".*~"])
(defn get-package-from-manifest [slurpable-content]
(try
(or (:package (:attrs (xml/parse (io/input-stream slurpable-content))))
(throw (RuntimeException. "package attribute not found")))
(catch Exception e (abort (str "Unable to read the package from the manifest (" (.getMessage e) ")")))))
(defn get-project-package [{manifest :android-manifest}]
(get-package-from-manifest manifest))
(defn output-directory-from-package [package]
(let [components (clojure.string/split package #"[.]")]
(case (count components)
0 (throw (RuntimeException. "Unexpected number of package components (0)"))
1 (first components)
(.toString (java.nio.file.Paths/get (first components) (into-array (rest components)))))))
(defn R-class-file? [file]
{:pre [(instance? File file)]}
(and (not (.isDirectory file))
(re-find #"^R([$].+)?[.]class" (.getName file))))
(defn get-R-directory [{target :target-path :as project} package-path]
(.toString (Paths/get target (into-array ["classes" package-path]))))
(defn list-dir [path]
(->> path io/file .list (map io/file)))
(defn R-files-in-directory
[path]
{:pre [(instance? String path)]}
(map #(io/file path (.toString %)) (filter R-class-file? (list-dir path))))
(defn R-class-files [project]
(R-files-in-directory (get-R-directory project (output-directory-from-package (get-project-package project)))))
(defn- get-api-level
"Return the value of maxSdkVersion or targetSdkVersion or minSdkVersion or 1"
[manifest-path]
(let [attrs (:attrs (first (filter #(= (:tag %) :uses-sdk) (:content (xml/parse manifest-path)))))]
(Integer/valueOf (or (:android:maxSdkVersion attrs)
(:android:targetSdkVersion attrs)
(:android:minSdkVersion attrs)
"1"))))
(defn readable-file? [file]
(and (.exists file)
(.canRead file)))
(defn android-jar-file [sdk version]
(io/file (apply str (interpose File/separator
[sdk "platforms" (str "android-" version) "android.jar"]))))
(defn check-jar-file [file]
(if (readable-file? file)
file
(abort (str "\"" (.getAbsolutePath file) "\" doesn't exist, or is not readable"))))
(defn get-android-jar-location
[sdk version]
(check-jar-file (android-jar-file sdk version)))
(defn- get-all-build-tools
"Return a sequence of all build-tools versions available"
[sdk]
(seq (.list (io/file sdk "build-tools"))))
(defn is-directory? [file]
(.isDirectory file))
(defn composite-path-is-dir? [base-path child-path]
(is-directory? (io/file (str base-path File/separator child-path))))
(defn all-directories?
"Returns true if and only if both base and all its childs are directories"
[base-path & child-paths]
(and
(is-directory? base-path)
(reduce (fn [acc child] (and acc (composite-path-is-dir? base-path child)))
true child-paths)))
(defn- android-home-is-valid? [android-home]
"Check if the ANDROID_HOME variable points to a valid android-sdk directory
The check assumes that ANDROID_HOME contains a number of directories"
(apply all-directories? (map io/file [android-home "build-tools" "platforms" "tools"])))
(defn get-env [var]
(System/getenv var))
(defn get-android-home []
(if-let [android-home (get-env android-home-env-var)]
android-home
(abort (str "The variable \"" android-home-env-var "\" not set"))))
(defn get-most-recent-aapt-location [sdk version]
"Validate the sdk and return the highest versioned aapt"
(if (not (android-home-is-valid? sdk))
(throw (RuntimeException. "sdk not recognized: is the content of ANDROID_HOME valid?"))
(let [aapt (io/file (apply str (interpose File/separator [sdk "build-tools" version "aapt"])))]
(if (and (.exists aapt) (.canExecute aapt))
(.getAbsolutePath aapt)
(throw (RuntimeException. (str "\"" (.getAbsolutePath aapt) "\" doesn't exist, or is not an executable")))))))
(defn- get-aapt-location
"Return the path of aapt for a specific version of the build tools in the sdk using the sdk found with 'get-android-home' and the
highest versioned build tool found with 'get-all-build-tools'.
Throw a runtime exception if not found or not executable"
([sdk]
(get-most-recent-aapt-location sdk (last (sort (get-all-build-tools sdk))))))
(defn- android-jar-from-manifest
"Return the path of android.jar from the android manifest and the environment"
[manifest-path]
(.getAbsolutePath (get-android-jar-location (get-android-home) (get-api-level manifest-path))))
(defn- get-arguments
"Read the arguments from the project, fail if any is missing"
[project xs]
(debug "Ensuring that the project arguments are there")
(reduce (fn [m v]
(if (contains? project v)
(assoc m v (get project v))
(abort (str "Unable to find " v " in project.clj!"))))
{}
xs))
(defn- check-is-directory!
"Check whether the specified path is a directory
If create-if-missing is set to true, the function will try to fix that, no solution if the file exists and is not a directory"
([path] (check-is-directory! path false))
([path create-if-missing]
(debug (str "Checking for \"" path "\" existance"))
(let [fpath (File. path)]
(if (not (.isDirectory fpath))
(if (and create-if-missing (not (.exists fpath)))
(do
(debug (str "The path \"" path "\" is not present: creating…"))
(.mkdirs fpath)
(check-is-directory! path false))
(abort (str "The path \"" path "\" doesn't exist, or is not a directory")))))))
(defn- path-from-dirs
"creating a Path in java 7 from clojure is messy"
[base & elements]
(Paths/get base (into-array String elements)))
(defn- copy-file
"Kudos to this guy: https://clojuredocs.org/clojure.java.io/copy"
[source-path dest-path]
(io/copy (io/file source-path) (io/file dest-path)))
;;;; TODO/FIXME: The "src" string is completely bogus and will break
;;;; watch-res if we specify a different source dir in leinigen
(defn- run-aapt
"Run the aapt command with the parameters required to generate a R.txt file
This will also generate a R.java file in destpath/src"
[aapt destpath sympath manifest android-jar res]
(let [src-path (if (nil? destpath)
(do (warn "Using hard-coded src-java as R.java path") "src-java")
destpath)]
(check-is-directory! src-path true)
(let [sh-arguments (if (nil? sympath)
(list aapt
"packange"
"-f"
"-m"
"-M" manifest
"-I" android-jar
"-S" res
"-J" src-path)
(list aapt
"package"
"--output-text-symbols" sympath
"-f"
"-m"
"-M" manifest
"-I" android-jar
"-S" res
"-J" src-path))
res (do
(debug "About to run aapt with arguments: " sh-arguments)
(apply sh sh-arguments))]
res)))
(defn- filter-temp
"Remove from the list of paths/pairs the files ending with ~"
[xs]
(filter
(fn [v]
(not (re-matches #".*~$" (if (string? v)
v
(first v))))) xs))
(defn- zip-contents
"Create a .aar library in a temporary location. Returns the path"
[work-path manifest res-dir jar]
(let [
full-r-path (.toString (path-from-dirs work-path r-txt))
aar-file (.toString (path-from-dirs work-path "library.aar"))
res-files (filter-temp (files-in-dir res-dir (.getParent (File. res-dir))))
zip-arguments (vec (concat [aar-file [jar expected-jar-name] [full-r-path r-txt] [manifest android-manifest-name]]
res-files))]
(debug "invoking the zip command with arguments:" zip-arguments)
(if (nil? (apply czip/zip-files zip-arguments))
(abort "Unable to compress" jar full-r-path "and" manifest "into" aar-file)
aar-file)))
(defn convert-path-to-absolute [path]
(-> (File. path)
.toPath .toAbsolutePath .normalize .toString))
(defn absolutize-paths-selectively [m-options s-keys]
(into m-options
(map (fn [[key value]]
(vector key (convert-path-to-absolute value)))
(filter #(-> % first s-keys) m-options))))
(defn- move [source destination]
(debug "Moving" source "to" destination)
(try
(.delete (File. destination))
(catch Exception e (abort "Unable to remove the destination file" destination "to make space for the resulting aar")))
(.renameTo (File. source) (File. destination)))
(defn- check-arguments [params]
(let [manifest (:android-manifest params)]
(if (not= "res" (.getName (File. (:res params)))) (abort "The :res option must point to a directory named \"res\""))
(if (not= android-manifest-name (.getName (File. manifest))) (abort "The :res option must point to a directory named \"" android-manifest-name "\""))
(if (not (.exists (File. manifest))) (abort (str "The file \"" manifest "\" does not exist")))
(if (not= (:aot params) [:all]) (abort (str ":aot :all must be specified in project.clj!")))))
(defn- run-aapt-noisy [& args]
(let [res (apply run-aapt args)]
(if (not= 0 (:exit res))
(abort (str "Invocation of aapt failed with error: \"" (:err res) "\"")))))
(defn wipe-extra-classes [project]
(dorun
(map (fn [file]
(info (str "Removing " (.getName file) "…"))
(.delete file)) (R-class-files project))))
(defn leiningen-task-hook [function task project args]
(debug "About to execute the task" task)
;;; Apply the task
(let [result (function task project args)]
(debug "Task" task "executed")
;;; if the task is javac, remove the R*.class after compilation
(if (= task "compile")
(wipe-extra-classes project))
result))
(defn activate-compile-hook []
(robert.hooke/add-hook #'leiningen.core.main/apply-task #'leiningen-task-hook))
(def create-R)
(defn create-aar
"Create a AAR library suitable for Android integration"
[project arguments]
(create-R project arguments)
(activate-compile-hook)
(let [my-args (absolutize-paths-selectively
(get-arguments project [:aar-name :aot :res :source-paths :target-path :android-manifest])
#{:aar-name :res :target-path :android-manifest})]
(check-arguments my-args)
;;; TODO/FIXME: get the jar name in a more robust way (use the jar task function directly?)
(let [jar-path (second (first (leiningen.core.main/apply-task "jar" project [])))
tmp-path (.toString (path-from-dirs (:target-path my-args) aar-build-dir))
dest-path (.toString (path-from-dirs tmp-path "src"))]
(debug "The jar is: " jar-path)
(debug "The aar compilation will be made in " tmp-path)
(check-is-directory! (:res my-args))
(check-is-directory! tmp-path true)
(run-aapt-noisy (get-aapt-location (get-android-home))
dest-path
tmp-path
(:android-manifest my-args)
(android-jar-from-manifest (:android-manifest my-args))
(:res my-args))
(let [aar-location (zip-contents tmp-path
(:android-manifest my-args)
(:res my-args)
jar-path)]
(move aar-location (:aar-name my-args))
(shutdown-agents)
(info "Created" (:aar-name my-args))))))
(defn- clear-trailing [char string]
(apply str (reverse (drop-while (hash-set char) (reverse string)))))
(defn- generate-R-java [aapt manifest android-jar res src]
(let [result (run-aapt aapt src nil manifest android-jar res)]
(info
(case (:exit result)
0 "✓ R.java updated"
(clear-trailing \newline (str "❌ error with R.java generation: " ( :err result)))))
(flush)
result))
(defn- watch-res-directory
"Update the contents of the R.java file when a :res file changes"
[my-args]
(let [aapt (get-aapt-location (get-android-home))
manifest (:android-manifest my-args)
android-jar (android-jar-from-manifest (:android-manifest my-args))
res (:res my-args)
dir (:res my-args)
java-src (first (:java-src-paths my-args))
to-be-excluded? (fn [path]
(reduce (fn [acc value] (or acc (re-matches value path)))
false
non-res-files))]
(generate-R-java aapt manifest android-jar res java-src)
(watch/add (clojure.java.io/file dir)
:my-watch
(fn [obj key prev next]
(let [path (.toString (second next))]
(if (not (to-be-excluded? path))
(generate-R-java aapt manifest android-jar res java-src))))
{
:types #{:create :modify :delete}})))
(defn- watches-for-file?
"Returns true if the watch listener disappeared
This can actually happen only if the watch sort of stops itself"
[file]
(> (count (watch/list file)) 0))
(defn- blocking-watch
"Starts a watch on the specific directory, and blocks"
[project]
(let [args (absolutize-paths-selectively
(get-arguments project
[:res :source-paths :target-path :android-manifest])
#{:res :target-path :android-manifest})]
(watch-res-directory args)
(loop [f (clojure.java.io/file (:res project))]
(if (watches-for-file? f)
(do
(Thread/sleep 100)
(recur f))))))
(defn watch-res
"Watch the res directory and update the R.java if any file changes
The updates are applied directly into the src directory"
[project & args]
(info "Starting a watch on the res directory…")
(blocking-watch project))
(defn create-R
"Create a R.java file with the information in the res directory
The file is created in the src directory"
[project & args]
(let [args (absolutize-paths-selectively
(get-arguments project
[:java-source-paths :res :source-paths :target-path :android-manifest])
#{:res :target-path :android-manifest})
aapt (get-aapt-location (get-android-home))
manifest (:android-manifest args)
android-jar (android-jar-from-manifest manifest)
res (:res args)
dir (:res args)
java-src (first (:java-source-paths args))]
(if (nil? java-src)
(abort "no :java-src-paths specified (at least one is needed)")
(do
(info "Using '" java-src "' for the R.java output…")
(generate-R-java aapt manifest android-jar res java-src)))))
(defn leiningen-test [project & args]
(activate-compile-hook)
(leiningen.core.main/apply-task "jar" project [])
(shutdown-agents))
(defn aar-tool
"Functions for android development"
{:subtasks [#'create-aar #'watch-res #'create-R]}
[project & args]
(case (first args)
nil (info "An action must be provided")
"create-aar" (create-aar project (rest args))
"watch-res" (watch-res project (rest args))
"create-R" (create-R project (rest args))
(abort "Unknown option")))
|
[
{
"context": " (let [user (get-in config [:basic-auth-user] \"admin\")\n pwd (creds/hash-bcrypt (get-in conf",
"end": 2648,
"score": 0.7868552803993225,
"start": 2643,
"tag": "USERNAME",
"value": "admin"
},
{
"context": "eds/hash-bcrypt (get-in config [:basic-auth-pwd] \"admin\"))\n users {\"admin\" {:username user :pa",
"end": 2725,
"score": 0.746894121170044,
"start": 2720,
"tag": "PASSWORD",
"value": "admin"
},
{
"context": "d] \"admin\"))\n users {\"admin\" {:username user :password pwd :roles (lookup-roles db \"admin\")}}\n",
"end": 2771,
"score": 0.9019939303398132,
"start": 2767,
"tag": "USERNAME",
"value": "user"
},
{
"context": " users {\"admin\" {:username user :password pwd :roles (lookup-roles db \"admin\")}}\n bc",
"end": 2785,
"score": 0.9630551338195801,
"start": 2782,
"tag": "PASSWORD",
"value": "pwd"
}
] | src/main/clj/planted/auth.clj | jandorfer/planted | 2 | (ns planted.auth
(:require [cemerick.friend :as friend]
[cemerick.friend.credentials :as creds]
[cemerick.friend.workflows :as workflows]
[clojure.tools.logging :as log]
[com.stuartsierra.component :as component]
[friend-oauth2.workflow :as oauth2]
[friend-oauth2.util :refer [format-config-uri]]))
(defn- lookup-roles
[db token]
;; TODO lookup roles from DB or some other appropriate source
(if (.equals "admin" token)
{:identity token :roles #{::user ::admin}}
{:identity token :roles #{::user}}))
(defn- check-missing-google-config
[variable name example]
(if (nil? variable)
(throw (Exception. (str "For google auth, must set '" name "' config value (" example ")")))))
(defn- build-client-config
[config]
(let [domain (:domain config)
callback (get-in config [:oauth-callback] "/oauth2callback")
{:keys [client-id client-secret] :as client-config} config]
(check-missing-google-config domain "domain" "like https://mysite.com")
(check-missing-google-config client-id "client-id" "get from google dev console")
(check-missing-google-config client-secret "client-secret" "get from google dev console")
(cons client-config {:callback {:domain domain :path callback}})))
(defn- build-uri-config
[client-config]
{:authentication-uri {:url "https://accounts.google.com/o/oauth2/auth"
:query {:client_id (:client-id client-config)
:response_type "code"
:redirect_uri (format-config-uri client-config)
:scope "email"}}
:access-token-uri {:url "https://accounts.google.com/o/oauth2/token"
:query {:client_id (:client-id client-config)
:client_secret (:client-secret client-config)
:grant_type "authorization_code"
:redirect_uri (format-config-uri client-config)}}})
(defn- get-google-workflow
[config db]
(if (:use-google-auth config)
(let [client-config (build-client-config config)]
[(oauth2/workflow
{:client-config client-config
:uri-config (build-uri-config client-config)
:credential-fn (partial lookup-roles db)})])))
(defn- login-failure [_]
{:status 403 :headers {} :body "User or password incorrect."})
(defn- get-basic-workflow
[config db]
(if (:use-basic-auth config)
(do
(log/warn "Basic authentication enabled! This should ONLY be for dev/test.")
(let [user (get-in config [:basic-auth-user] "admin")
pwd (creds/hash-bcrypt (get-in config [:basic-auth-pwd] "admin"))
users {"admin" {:username user :password pwd :roles (lookup-roles db "admin")}}
bcrypt (partial creds/bcrypt-credential-fn users)]
[(workflows/interactive-form
:credential-fn bcrypt
:login-failure-handler login-failure
:realm "/"
:redirect-on-auth? false)]))))
(defn- get-workflows
[config db]
(let [workflows (concat (get-google-workflow config db) (get-basic-workflow config db))]
(if (= 0 (count workflows))
(throw (Exception. "No authenication mode enabled"))
workflows)))
(defn get-handler
[config db]
(let [workflows (get-workflows config db)]
(fn [ring-handler]
(log/info "Loading workflows" (count workflows))
(friend/authenticate ring-handler
{:allow-anon? true
:workflows workflows}))))
(defrecord AuthProvider [config db handler]
component/Lifecycle
(start [this]
(log/info "Setting up authentication component")
(if (not db) (throw (Exception. "Authentication component requires missing 'db' dependency.")))
(if handler
this
(assoc this :handler (get-handler config db))))
(stop [this]
(log/info "Cleaning up authentication component")
(if (not handler)
this
(assoc this :handler nil))))
(defn new-authprovider
"This class implements the Lifecycle interface providing start/stop methods
for the authentication component for this system."
[config]
(map->AuthProvider {:config config})) | 42262 | (ns planted.auth
(:require [cemerick.friend :as friend]
[cemerick.friend.credentials :as creds]
[cemerick.friend.workflows :as workflows]
[clojure.tools.logging :as log]
[com.stuartsierra.component :as component]
[friend-oauth2.workflow :as oauth2]
[friend-oauth2.util :refer [format-config-uri]]))
(defn- lookup-roles
[db token]
;; TODO lookup roles from DB or some other appropriate source
(if (.equals "admin" token)
{:identity token :roles #{::user ::admin}}
{:identity token :roles #{::user}}))
(defn- check-missing-google-config
[variable name example]
(if (nil? variable)
(throw (Exception. (str "For google auth, must set '" name "' config value (" example ")")))))
(defn- build-client-config
[config]
(let [domain (:domain config)
callback (get-in config [:oauth-callback] "/oauth2callback")
{:keys [client-id client-secret] :as client-config} config]
(check-missing-google-config domain "domain" "like https://mysite.com")
(check-missing-google-config client-id "client-id" "get from google dev console")
(check-missing-google-config client-secret "client-secret" "get from google dev console")
(cons client-config {:callback {:domain domain :path callback}})))
(defn- build-uri-config
[client-config]
{:authentication-uri {:url "https://accounts.google.com/o/oauth2/auth"
:query {:client_id (:client-id client-config)
:response_type "code"
:redirect_uri (format-config-uri client-config)
:scope "email"}}
:access-token-uri {:url "https://accounts.google.com/o/oauth2/token"
:query {:client_id (:client-id client-config)
:client_secret (:client-secret client-config)
:grant_type "authorization_code"
:redirect_uri (format-config-uri client-config)}}})
(defn- get-google-workflow
[config db]
(if (:use-google-auth config)
(let [client-config (build-client-config config)]
[(oauth2/workflow
{:client-config client-config
:uri-config (build-uri-config client-config)
:credential-fn (partial lookup-roles db)})])))
(defn- login-failure [_]
{:status 403 :headers {} :body "User or password incorrect."})
(defn- get-basic-workflow
[config db]
(if (:use-basic-auth config)
(do
(log/warn "Basic authentication enabled! This should ONLY be for dev/test.")
(let [user (get-in config [:basic-auth-user] "admin")
pwd (creds/hash-bcrypt (get-in config [:basic-auth-pwd] "<PASSWORD>"))
users {"admin" {:username user :password <PASSWORD> :roles (lookup-roles db "admin")}}
bcrypt (partial creds/bcrypt-credential-fn users)]
[(workflows/interactive-form
:credential-fn bcrypt
:login-failure-handler login-failure
:realm "/"
:redirect-on-auth? false)]))))
(defn- get-workflows
[config db]
(let [workflows (concat (get-google-workflow config db) (get-basic-workflow config db))]
(if (= 0 (count workflows))
(throw (Exception. "No authenication mode enabled"))
workflows)))
(defn get-handler
[config db]
(let [workflows (get-workflows config db)]
(fn [ring-handler]
(log/info "Loading workflows" (count workflows))
(friend/authenticate ring-handler
{:allow-anon? true
:workflows workflows}))))
(defrecord AuthProvider [config db handler]
component/Lifecycle
(start [this]
(log/info "Setting up authentication component")
(if (not db) (throw (Exception. "Authentication component requires missing 'db' dependency.")))
(if handler
this
(assoc this :handler (get-handler config db))))
(stop [this]
(log/info "Cleaning up authentication component")
(if (not handler)
this
(assoc this :handler nil))))
(defn new-authprovider
"This class implements the Lifecycle interface providing start/stop methods
for the authentication component for this system."
[config]
(map->AuthProvider {:config config})) | true | (ns planted.auth
(:require [cemerick.friend :as friend]
[cemerick.friend.credentials :as creds]
[cemerick.friend.workflows :as workflows]
[clojure.tools.logging :as log]
[com.stuartsierra.component :as component]
[friend-oauth2.workflow :as oauth2]
[friend-oauth2.util :refer [format-config-uri]]))
(defn- lookup-roles
[db token]
;; TODO lookup roles from DB or some other appropriate source
(if (.equals "admin" token)
{:identity token :roles #{::user ::admin}}
{:identity token :roles #{::user}}))
(defn- check-missing-google-config
[variable name example]
(if (nil? variable)
(throw (Exception. (str "For google auth, must set '" name "' config value (" example ")")))))
(defn- build-client-config
[config]
(let [domain (:domain config)
callback (get-in config [:oauth-callback] "/oauth2callback")
{:keys [client-id client-secret] :as client-config} config]
(check-missing-google-config domain "domain" "like https://mysite.com")
(check-missing-google-config client-id "client-id" "get from google dev console")
(check-missing-google-config client-secret "client-secret" "get from google dev console")
(cons client-config {:callback {:domain domain :path callback}})))
(defn- build-uri-config
[client-config]
{:authentication-uri {:url "https://accounts.google.com/o/oauth2/auth"
:query {:client_id (:client-id client-config)
:response_type "code"
:redirect_uri (format-config-uri client-config)
:scope "email"}}
:access-token-uri {:url "https://accounts.google.com/o/oauth2/token"
:query {:client_id (:client-id client-config)
:client_secret (:client-secret client-config)
:grant_type "authorization_code"
:redirect_uri (format-config-uri client-config)}}})
(defn- get-google-workflow
[config db]
(if (:use-google-auth config)
(let [client-config (build-client-config config)]
[(oauth2/workflow
{:client-config client-config
:uri-config (build-uri-config client-config)
:credential-fn (partial lookup-roles db)})])))
(defn- login-failure [_]
{:status 403 :headers {} :body "User or password incorrect."})
(defn- get-basic-workflow
[config db]
(if (:use-basic-auth config)
(do
(log/warn "Basic authentication enabled! This should ONLY be for dev/test.")
(let [user (get-in config [:basic-auth-user] "admin")
pwd (creds/hash-bcrypt (get-in config [:basic-auth-pwd] "PI:PASSWORD:<PASSWORD>END_PI"))
users {"admin" {:username user :password PI:PASSWORD:<PASSWORD>END_PI :roles (lookup-roles db "admin")}}
bcrypt (partial creds/bcrypt-credential-fn users)]
[(workflows/interactive-form
:credential-fn bcrypt
:login-failure-handler login-failure
:realm "/"
:redirect-on-auth? false)]))))
(defn- get-workflows
[config db]
(let [workflows (concat (get-google-workflow config db) (get-basic-workflow config db))]
(if (= 0 (count workflows))
(throw (Exception. "No authenication mode enabled"))
workflows)))
(defn get-handler
[config db]
(let [workflows (get-workflows config db)]
(fn [ring-handler]
(log/info "Loading workflows" (count workflows))
(friend/authenticate ring-handler
{:allow-anon? true
:workflows workflows}))))
(defrecord AuthProvider [config db handler]
component/Lifecycle
(start [this]
(log/info "Setting up authentication component")
(if (not db) (throw (Exception. "Authentication component requires missing 'db' dependency.")))
(if handler
this
(assoc this :handler (get-handler config db))))
(stop [this]
(log/info "Cleaning up authentication component")
(if (not handler)
this
(assoc this :handler nil))))
(defn new-authprovider
"This class implements the Lifecycle interface providing start/stop methods
for the authentication component for this system."
[config]
(map->AuthProvider {:config config})) |
[
{
"context": "operty\"} {:id 2, :name \"property\"} {:id 1, :name \"first_name\"})\n ({:id 1, :name \"property\"} {:id 2, :name \"p",
"end": 623,
"score": 0.9586957097053528,
"start": 613,
"tag": "NAME",
"value": "first_name"
},
{
"context": "operty\"} {:id 2, :name \"property\"} {:id 2, :name \"last_name\"})\n ({:id 1, :name \"property\"} {:id 2, :name \"p",
"end": 707,
"score": 0.9326097369194031,
"start": 698,
"tag": "NAME",
"value": "last_name"
},
{
"context": "ipedge\"} {:id 1, :name \"id1\"})\n ({:id 2, :name \"friendshipedge\"} {:id 2, :name \"id2\"})])\n\n\n(defn nullpathgenerat",
"end": 1518,
"score": 0.6527500152587891,
"start": 1504,
"tag": "USERNAME",
"value": "friendshipedge"
}
] | src/clj/dfs_clj/tapmapper.clj | EricGebhart/dfs-clj | 1 | (ns dfs-clj.tapmapper
"Defines Null Pail Tap mappers and property path generators for vertically partitioned Pails.")
;------ Path generator ---------
; given a thrift data type or other schema object
; return a list of vectors representing the paths to each property in the tree.
; The thrift example in pail-graph generates a property path list like this.
; Although this is very specific to graph schema, where field-ids and names are given.
(comment
(type/property-paths DataUnit)
=>[({:id 1, :name "property"} {:id 1, :name "id"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 1, :name "first_name"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 2, :name "last_name"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 4, :name "location"} {:id 1, :name "address"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 4, :name "location"} {:id 2, :name "city"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 4, :name "location"} {:id 3, :name "county"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 4, :name "location"} {:id 4, :name "state"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 4, :name "location"} {:id 5, :name "country"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 4, :name "location"} {:id 6, :name "zip"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 5, :name "age"})
({:id 2, :name "friendshipedge"} {:id 1, :name "id1"})
({:id 2, :name "friendshipedge"} {:id 2, :name "id2"})])
(defn nullpathgenerator [path]
"A null pathgenerator returns no paths"
{})
(defn null-path-generator
"return a null pathgenerator"
[]
nullpathgenerator)
;---- Tap Mappers ------
;Takes a thrift property_path vector and creates a valid partition path for that property.
; [ :location ["property" "location"]]
;Specify the tapmapper with :tapmapper in the PailStructure.
;
(defn nulltapmapper [path]
"A null tapmapper returns no taps"
{})
(defn null-tapmapper
"return a null tapmapper"
[]
nulltapmapper)
| 86827 | (ns dfs-clj.tapmapper
"Defines Null Pail Tap mappers and property path generators for vertically partitioned Pails.")
;------ Path generator ---------
; given a thrift data type or other schema object
; return a list of vectors representing the paths to each property in the tree.
; The thrift example in pail-graph generates a property path list like this.
; Although this is very specific to graph schema, where field-ids and names are given.
(comment
(type/property-paths DataUnit)
=>[({:id 1, :name "property"} {:id 1, :name "id"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 1, :name "<NAME>"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 2, :name "<NAME>"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 4, :name "location"} {:id 1, :name "address"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 4, :name "location"} {:id 2, :name "city"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 4, :name "location"} {:id 3, :name "county"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 4, :name "location"} {:id 4, :name "state"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 4, :name "location"} {:id 5, :name "country"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 4, :name "location"} {:id 6, :name "zip"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 5, :name "age"})
({:id 2, :name "friendshipedge"} {:id 1, :name "id1"})
({:id 2, :name "friendshipedge"} {:id 2, :name "id2"})])
(defn nullpathgenerator [path]
"A null pathgenerator returns no paths"
{})
(defn null-path-generator
"return a null pathgenerator"
[]
nullpathgenerator)
;---- Tap Mappers ------
;Takes a thrift property_path vector and creates a valid partition path for that property.
; [ :location ["property" "location"]]
;Specify the tapmapper with :tapmapper in the PailStructure.
;
(defn nulltapmapper [path]
"A null tapmapper returns no taps"
{})
(defn null-tapmapper
"return a null tapmapper"
[]
nulltapmapper)
| true | (ns dfs-clj.tapmapper
"Defines Null Pail Tap mappers and property path generators for vertically partitioned Pails.")
;------ Path generator ---------
; given a thrift data type or other schema object
; return a list of vectors representing the paths to each property in the tree.
; The thrift example in pail-graph generates a property path list like this.
; Although this is very specific to graph schema, where field-ids and names are given.
(comment
(type/property-paths DataUnit)
=>[({:id 1, :name "property"} {:id 1, :name "id"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 1, :name "PI:NAME:<NAME>END_PI"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 2, :name "PI:NAME:<NAME>END_PI"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 4, :name "location"} {:id 1, :name "address"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 4, :name "location"} {:id 2, :name "city"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 4, :name "location"} {:id 3, :name "county"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 4, :name "location"} {:id 4, :name "state"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 4, :name "location"} {:id 5, :name "country"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 4, :name "location"} {:id 6, :name "zip"})
({:id 1, :name "property"} {:id 2, :name "property"} {:id 5, :name "age"})
({:id 2, :name "friendshipedge"} {:id 1, :name "id1"})
({:id 2, :name "friendshipedge"} {:id 2, :name "id2"})])
(defn nullpathgenerator [path]
"A null pathgenerator returns no paths"
{})
(defn null-path-generator
"return a null pathgenerator"
[]
nullpathgenerator)
;---- Tap Mappers ------
;Takes a thrift property_path vector and creates a valid partition path for that property.
; [ :location ["property" "location"]]
;Specify the tapmapper with :tapmapper in the PailStructure.
;
(defn nulltapmapper [path]
"A null tapmapper returns no taps"
{})
(defn null-tapmapper
"return a null tapmapper"
[]
nulltapmapper)
|
[
{
"context": ";; Copyright (c) Rich Hickey and contributors. All rights reserved.\n;; The u",
"end": 30,
"score": 0.9998458623886108,
"start": 19,
"tag": "NAME",
"value": "Rich Hickey"
}
] | docs/js/compiled/out/cljs/core/async/impl/dispatch.cljs | pvik/who-assist | 0 | ;; Copyright (c) Rich Hickey and contributors. 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.async.impl.dispatch
(:require [cljs.core.async.impl.buffers :as buffers]
[goog.async.nextTick]))
(def tasks (buffers/ring-buffer 32))
(def running? false)
(def queued? false)
(def TASK_BATCH_SIZE 1024)
(declare queue-dispatcher)
(defn process-messages []
(set! running? true)
(set! queued? false)
(loop [count 0]
(let [m (.pop tasks)]
(when-not (nil? m)
(m)
(when (< count TASK_BATCH_SIZE)
(recur (inc count))))))
(set! running? false)
(when (> (.-length tasks) 0)
(queue-dispatcher)))
(defn queue-dispatcher []
(when-not (and queued? running?)
(set! queued? true)
(goog.async.nextTick process-messages)))
(defn run [f]
(.unbounded-unshift tasks f)
(queue-dispatcher))
(defn queue-delay [f delay]
(js/setTimeout f delay))
| 109614 | ;; Copyright (c) <NAME> and contributors. 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.async.impl.dispatch
(:require [cljs.core.async.impl.buffers :as buffers]
[goog.async.nextTick]))
(def tasks (buffers/ring-buffer 32))
(def running? false)
(def queued? false)
(def TASK_BATCH_SIZE 1024)
(declare queue-dispatcher)
(defn process-messages []
(set! running? true)
(set! queued? false)
(loop [count 0]
(let [m (.pop tasks)]
(when-not (nil? m)
(m)
(when (< count TASK_BATCH_SIZE)
(recur (inc count))))))
(set! running? false)
(when (> (.-length tasks) 0)
(queue-dispatcher)))
(defn queue-dispatcher []
(when-not (and queued? running?)
(set! queued? true)
(goog.async.nextTick process-messages)))
(defn run [f]
(.unbounded-unshift tasks f)
(queue-dispatcher))
(defn queue-delay [f delay]
(js/setTimeout f delay))
| true | ;; Copyright (c) PI:NAME:<NAME>END_PI and contributors. 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.async.impl.dispatch
(:require [cljs.core.async.impl.buffers :as buffers]
[goog.async.nextTick]))
(def tasks (buffers/ring-buffer 32))
(def running? false)
(def queued? false)
(def TASK_BATCH_SIZE 1024)
(declare queue-dispatcher)
(defn process-messages []
(set! running? true)
(set! queued? false)
(loop [count 0]
(let [m (.pop tasks)]
(when-not (nil? m)
(m)
(when (< count TASK_BATCH_SIZE)
(recur (inc count))))))
(set! running? false)
(when (> (.-length tasks) 0)
(queue-dispatcher)))
(defn queue-dispatcher []
(when-not (and queued? running?)
(set! queued? true)
(goog.async.nextTick process-messages)))
(defn run [f]
(.unbounded-unshift tasks f)
(queue-dispatcher))
(defn queue-delay [f delay]
(js/setTimeout f delay))
|
[
{
"context": "chatops-skill\"}\n :command/token \"bccf5898b3eaf2f54b71f1538444f92da97737e9\"\n :label/number 15\n ",
"end": 4451,
"score": 0.999188244342804,
"start": 4411,
"tag": "KEY",
"value": "bccf5898b3eaf2f54b71f1538444f92da97737e9"
}
] | src/atomist/commands/label.cljs | atomist-skills/github-slash-commands-skill | 0 | ;; Copyright © 2020 Atomist, Inc.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns atomist.commands.label
(:require [atomist.shell :as shell]
[clojure.string :as string]
[cljs.core.async :refer [<!] :as async]
[atomist.commands :refer [run]]
[atomist.cljs-log :as log]
[goog.string :as gstring]
[goog.string.format]
[atomist.github :as github])
(:require-macros [cljs.core.async.macros :refer [go]]))
(defn ensure-label [request label default-color]
(go
(let [response (<! (github/get-label request label))]
(log/info "get-label: " response)
(if (= "Not Found" (:message response))
(<! (github/add-label request {:name label
:color default-color
:description (gstring/format "added by %s/%s"
(-> request :skill :namespace)
(-> request :skill :name))}))
response))))
;; /label --rm label1,label2
;; /label labe1,label2
;; these only make sense from Issue/PR comments
(defmethod run "label" [{{:command/keys [args token repo]
:label/keys [number default-color] :or {default-color "f29513"}} :command}]
(go
(if (not number)
{:errors ["/label command only works from a PR/Issue Comment"]}
(let [{{:keys [rm]} :options just-args :arguments}
(shell/raw-message->options {:raw_message args}
[[nil "--rm"]])
request {:ref {:owner (:owner repo) :repo (:name repo)}
:number number
:token token}
labels (->> just-args
(mapcat #(string/split % #","))
(map string/trim)
(map (fn [label] (if (or (< (count label) 3)
(re-find #"[\.\#]" label))
:error
label)))
(into []))]
(log/info "labels to create: " (pr-str labels))
(if (some #(= :error %) labels)
{:errors [(gstring/format "invalid label names %s" labels)]}
(if rm
(let [response (<! (->> (for [label labels]
(github/rm-label request label))
(async/merge)
(async/reduce conj [])))
status (->> response
(map :status)
(interpose ",")
(apply str))]
(log/debugf "rm-labels: %s" status)
{:status status})
(do
(let [response (<! (->> (for [label labels] (ensure-label request label default-color))
(async/merge)
(async/reduce conj [])))
ensure-status (->> response
(map :status)
(interpose ",")
(apply str))]
(log/debugf "ensure-labels: %s" ensure-status))
(let [status (:status (<! (github/put-label
(assoc request
:labels labels))))]
(log/debugf "put-labels: %s" status)
{:status status}))))))))
(comment
(run {:command {:command/command "label"
:command/args "hey1,hey2"
:command/repo {:owner "atomist-skills"
:name "git-chatops-skill"}
:command/token "bccf5898b3eaf2f54b71f1538444f92da97737e9"
:label/number 15
:label/default-color "f29513"}})) | 115421 | ;; Copyright © 2020 Atomist, Inc.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns atomist.commands.label
(:require [atomist.shell :as shell]
[clojure.string :as string]
[cljs.core.async :refer [<!] :as async]
[atomist.commands :refer [run]]
[atomist.cljs-log :as log]
[goog.string :as gstring]
[goog.string.format]
[atomist.github :as github])
(:require-macros [cljs.core.async.macros :refer [go]]))
(defn ensure-label [request label default-color]
(go
(let [response (<! (github/get-label request label))]
(log/info "get-label: " response)
(if (= "Not Found" (:message response))
(<! (github/add-label request {:name label
:color default-color
:description (gstring/format "added by %s/%s"
(-> request :skill :namespace)
(-> request :skill :name))}))
response))))
;; /label --rm label1,label2
;; /label labe1,label2
;; these only make sense from Issue/PR comments
(defmethod run "label" [{{:command/keys [args token repo]
:label/keys [number default-color] :or {default-color "f29513"}} :command}]
(go
(if (not number)
{:errors ["/label command only works from a PR/Issue Comment"]}
(let [{{:keys [rm]} :options just-args :arguments}
(shell/raw-message->options {:raw_message args}
[[nil "--rm"]])
request {:ref {:owner (:owner repo) :repo (:name repo)}
:number number
:token token}
labels (->> just-args
(mapcat #(string/split % #","))
(map string/trim)
(map (fn [label] (if (or (< (count label) 3)
(re-find #"[\.\#]" label))
:error
label)))
(into []))]
(log/info "labels to create: " (pr-str labels))
(if (some #(= :error %) labels)
{:errors [(gstring/format "invalid label names %s" labels)]}
(if rm
(let [response (<! (->> (for [label labels]
(github/rm-label request label))
(async/merge)
(async/reduce conj [])))
status (->> response
(map :status)
(interpose ",")
(apply str))]
(log/debugf "rm-labels: %s" status)
{:status status})
(do
(let [response (<! (->> (for [label labels] (ensure-label request label default-color))
(async/merge)
(async/reduce conj [])))
ensure-status (->> response
(map :status)
(interpose ",")
(apply str))]
(log/debugf "ensure-labels: %s" ensure-status))
(let [status (:status (<! (github/put-label
(assoc request
:labels labels))))]
(log/debugf "put-labels: %s" status)
{:status status}))))))))
(comment
(run {:command {:command/command "label"
:command/args "hey1,hey2"
:command/repo {:owner "atomist-skills"
:name "git-chatops-skill"}
:command/token "<KEY>"
:label/number 15
:label/default-color "f29513"}})) | true | ;; Copyright © 2020 Atomist, Inc.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns atomist.commands.label
(:require [atomist.shell :as shell]
[clojure.string :as string]
[cljs.core.async :refer [<!] :as async]
[atomist.commands :refer [run]]
[atomist.cljs-log :as log]
[goog.string :as gstring]
[goog.string.format]
[atomist.github :as github])
(:require-macros [cljs.core.async.macros :refer [go]]))
(defn ensure-label [request label default-color]
(go
(let [response (<! (github/get-label request label))]
(log/info "get-label: " response)
(if (= "Not Found" (:message response))
(<! (github/add-label request {:name label
:color default-color
:description (gstring/format "added by %s/%s"
(-> request :skill :namespace)
(-> request :skill :name))}))
response))))
;; /label --rm label1,label2
;; /label labe1,label2
;; these only make sense from Issue/PR comments
(defmethod run "label" [{{:command/keys [args token repo]
:label/keys [number default-color] :or {default-color "f29513"}} :command}]
(go
(if (not number)
{:errors ["/label command only works from a PR/Issue Comment"]}
(let [{{:keys [rm]} :options just-args :arguments}
(shell/raw-message->options {:raw_message args}
[[nil "--rm"]])
request {:ref {:owner (:owner repo) :repo (:name repo)}
:number number
:token token}
labels (->> just-args
(mapcat #(string/split % #","))
(map string/trim)
(map (fn [label] (if (or (< (count label) 3)
(re-find #"[\.\#]" label))
:error
label)))
(into []))]
(log/info "labels to create: " (pr-str labels))
(if (some #(= :error %) labels)
{:errors [(gstring/format "invalid label names %s" labels)]}
(if rm
(let [response (<! (->> (for [label labels]
(github/rm-label request label))
(async/merge)
(async/reduce conj [])))
status (->> response
(map :status)
(interpose ",")
(apply str))]
(log/debugf "rm-labels: %s" status)
{:status status})
(do
(let [response (<! (->> (for [label labels] (ensure-label request label default-color))
(async/merge)
(async/reduce conj [])))
ensure-status (->> response
(map :status)
(interpose ",")
(apply str))]
(log/debugf "ensure-labels: %s" ensure-status))
(let [status (:status (<! (github/put-label
(assoc request
:labels labels))))]
(log/debugf "put-labels: %s" status)
{:status status}))))))))
(comment
(run {:command {:command/command "label"
:command/args "hey1,hey2"
:command/repo {:owner "atomist-skills"
:name "git-chatops-skill"}
:command/token "PI:KEY:<KEY>END_PI"
:label/number 15
:label/default-color "f29513"}})) |
[
{
"context": "ef master-pubkey (keyring/get-public-key pubring \"923b1c1c4392318a\"))\n\n(def pubkey (encrypted-credentials/get-secre",
"end": 1739,
"score": 0.9917477965354919,
"start": 1723,
"tag": "KEY",
"value": "923b1c1c4392318a"
},
{
"context": "gp/test/keys/secring.gpg\"\n :key-id \"3f40edec41c6cb7d\"}))\n(def seckey (encrypted-credentials/get-secre",
"end": 1937,
"score": 0.9996888041496277,
"start": 1921,
"tag": "KEY",
"value": "3f40edec41c6cb7d"
},
{
"context": "gp/test/keys/secring.gpg\"\n :key-id \"3f40edec41c6cb7d\"}))\n(def privkey (pgp/unlock-key seckey \"test pas",
"end": 2135,
"score": 0.999667227268219,
"start": 2119,
"tag": "KEY",
"value": "3f40edec41c6cb7d"
}
] | test/src/clj_pgp/test/encryption_test_scenario.clj | DomainDrivenArchitecture/dda-pallet-commons | 2 | ; 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 clj-pgp.test.encryption-test-scenario
(:require
[clojure.java.io :as io]
[clojure.test :refer :all]
[clojure.test.check.generators :as gen]
[schema.core :as s]
[byte-streams :refer [bytes=]]
[clj-pgp.core :as pgp]
[clj-pgp.generate :as pgp-gen]
[clj-pgp.keyring :as keyring]
[clj-pgp.tags :as tags]
[clj-pgp.message :as pgp-msg]
[dda.pallet.commons.encrypted-credentials :as encrypted-credentials]))
(def pubring
(-> "clj_pgp/test/keys/pubring.gpg"
io/resource
io/file
keyring/load-public-keyring))
(def secring
(encrypted-credentials/load-secret-keyring
(merge (encrypted-credentials/default-encryption-configuration)
{:secring-path "clj_pgp/test/keys/secring.gpg"})))
(defn get-privkey
[id]
(some-> secring
(keyring/get-secret-key id)
(pgp/unlock-key "test password")))
(def master-pubkey (keyring/get-public-key pubring "923b1c1c4392318a"))
(def pubkey (encrypted-credentials/get-secret-key
{:user-home "/home/user/"
:secring-path "clj_pgp/test/keys/secring.gpg"
:key-id "3f40edec41c6cb7d"}))
(def seckey (encrypted-credentials/get-secret-key
{:user-home "/home/user/"
:secring-path "clj_pgp/test/keys/secring.gpg"
:key-id "3f40edec41c6cb7d"}))
(def privkey (pgp/unlock-key seckey "test password"))
;; ## Generative Utilities
(defn gen-rsa-keyspec
"Returns a generator for RSA keys with the given strengths."
[strengths]
(gen/fmap
(partial vector :rsa :rsa-general)
(gen/elements strengths)))
(defn gen-ec-keyspec
"Returns a generator for EC keys with the given algorithm and named curves."
[algorithm curves]
(gen/fmap
(partial vector :ec algorithm)
(gen/elements curves)))
(defn spec->keypair
"Generates a keypair from a keyspec."
[[key-type & opts]]
(case key-type
:rsa (let [[algo strength] opts
rsa (pgp-gen/rsa-keypair-generator strength)]
(pgp-gen/generate-keypair rsa algo))
:ec (let [[algo curve] opts
ec (pgp-gen/ec-keypair-generator curve)]
(pgp-gen/generate-keypair ec algo))))
(def key-cache
"Stores generated keys by their key-specs to memoize key generation calls."
(atom {}))
(defn memospec->keypair
"Returns a keypair for a keyspec. Uses the key-cache var to memoize the
generated keys."
[spec]
(or (when (string? spec) spec)
(get @key-cache spec)
(let [k (spec->keypair spec)]
(swap! key-cache assoc spec k)
k)))
(defn generate-rsa-keypair []
(let [rsa (pgp-gen/rsa-keypair-generator 1024)]
(pgp-gen/generate-keypair rsa :rsa-general)))
(defn test-encryption-scenario
"Tests that encrypting and decrypting data with the given keypairs/passphrases
returns the original data."
[keyspecs data compress cipher armor]
(testing (str "Encrypting " (count data) " bytes with " cipher
" for keys " (pr-str keyspecs)
(when compress (str " compressed with " compress))
" encoded in " (if armor "ascii" "binary"))
(let [encryptors (map memospec->keypair keyspecs)
ciphertext (pgp-msg/encrypt
data encryptors
:compress compress
:cipher cipher
:armor armor)]
(is (not (bytes= data ciphertext))
"ciphertext bytes differ from data")
(doseq [decryptor encryptors]
(is (bytes= data (pgp-msg/decrypt ciphertext decryptor))
"decrypting the ciphertext returns plaintext"))
[encryptors ciphertext])))
| 69437 | ; 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 clj-pgp.test.encryption-test-scenario
(:require
[clojure.java.io :as io]
[clojure.test :refer :all]
[clojure.test.check.generators :as gen]
[schema.core :as s]
[byte-streams :refer [bytes=]]
[clj-pgp.core :as pgp]
[clj-pgp.generate :as pgp-gen]
[clj-pgp.keyring :as keyring]
[clj-pgp.tags :as tags]
[clj-pgp.message :as pgp-msg]
[dda.pallet.commons.encrypted-credentials :as encrypted-credentials]))
(def pubring
(-> "clj_pgp/test/keys/pubring.gpg"
io/resource
io/file
keyring/load-public-keyring))
(def secring
(encrypted-credentials/load-secret-keyring
(merge (encrypted-credentials/default-encryption-configuration)
{:secring-path "clj_pgp/test/keys/secring.gpg"})))
(defn get-privkey
[id]
(some-> secring
(keyring/get-secret-key id)
(pgp/unlock-key "test password")))
(def master-pubkey (keyring/get-public-key pubring "<KEY>"))
(def pubkey (encrypted-credentials/get-secret-key
{:user-home "/home/user/"
:secring-path "clj_pgp/test/keys/secring.gpg"
:key-id "<KEY>"}))
(def seckey (encrypted-credentials/get-secret-key
{:user-home "/home/user/"
:secring-path "clj_pgp/test/keys/secring.gpg"
:key-id "<KEY>"}))
(def privkey (pgp/unlock-key seckey "test password"))
;; ## Generative Utilities
(defn gen-rsa-keyspec
"Returns a generator for RSA keys with the given strengths."
[strengths]
(gen/fmap
(partial vector :rsa :rsa-general)
(gen/elements strengths)))
(defn gen-ec-keyspec
"Returns a generator for EC keys with the given algorithm and named curves."
[algorithm curves]
(gen/fmap
(partial vector :ec algorithm)
(gen/elements curves)))
(defn spec->keypair
"Generates a keypair from a keyspec."
[[key-type & opts]]
(case key-type
:rsa (let [[algo strength] opts
rsa (pgp-gen/rsa-keypair-generator strength)]
(pgp-gen/generate-keypair rsa algo))
:ec (let [[algo curve] opts
ec (pgp-gen/ec-keypair-generator curve)]
(pgp-gen/generate-keypair ec algo))))
(def key-cache
"Stores generated keys by their key-specs to memoize key generation calls."
(atom {}))
(defn memospec->keypair
"Returns a keypair for a keyspec. Uses the key-cache var to memoize the
generated keys."
[spec]
(or (when (string? spec) spec)
(get @key-cache spec)
(let [k (spec->keypair spec)]
(swap! key-cache assoc spec k)
k)))
(defn generate-rsa-keypair []
(let [rsa (pgp-gen/rsa-keypair-generator 1024)]
(pgp-gen/generate-keypair rsa :rsa-general)))
(defn test-encryption-scenario
"Tests that encrypting and decrypting data with the given keypairs/passphrases
returns the original data."
[keyspecs data compress cipher armor]
(testing (str "Encrypting " (count data) " bytes with " cipher
" for keys " (pr-str keyspecs)
(when compress (str " compressed with " compress))
" encoded in " (if armor "ascii" "binary"))
(let [encryptors (map memospec->keypair keyspecs)
ciphertext (pgp-msg/encrypt
data encryptors
:compress compress
:cipher cipher
:armor armor)]
(is (not (bytes= data ciphertext))
"ciphertext bytes differ from data")
(doseq [decryptor encryptors]
(is (bytes= data (pgp-msg/decrypt ciphertext decryptor))
"decrypting the ciphertext returns plaintext"))
[encryptors ciphertext])))
| 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 clj-pgp.test.encryption-test-scenario
(:require
[clojure.java.io :as io]
[clojure.test :refer :all]
[clojure.test.check.generators :as gen]
[schema.core :as s]
[byte-streams :refer [bytes=]]
[clj-pgp.core :as pgp]
[clj-pgp.generate :as pgp-gen]
[clj-pgp.keyring :as keyring]
[clj-pgp.tags :as tags]
[clj-pgp.message :as pgp-msg]
[dda.pallet.commons.encrypted-credentials :as encrypted-credentials]))
(def pubring
(-> "clj_pgp/test/keys/pubring.gpg"
io/resource
io/file
keyring/load-public-keyring))
(def secring
(encrypted-credentials/load-secret-keyring
(merge (encrypted-credentials/default-encryption-configuration)
{:secring-path "clj_pgp/test/keys/secring.gpg"})))
(defn get-privkey
[id]
(some-> secring
(keyring/get-secret-key id)
(pgp/unlock-key "test password")))
(def master-pubkey (keyring/get-public-key pubring "PI:KEY:<KEY>END_PI"))
(def pubkey (encrypted-credentials/get-secret-key
{:user-home "/home/user/"
:secring-path "clj_pgp/test/keys/secring.gpg"
:key-id "PI:KEY:<KEY>END_PI"}))
(def seckey (encrypted-credentials/get-secret-key
{:user-home "/home/user/"
:secring-path "clj_pgp/test/keys/secring.gpg"
:key-id "PI:KEY:<KEY>END_PI"}))
(def privkey (pgp/unlock-key seckey "test password"))
;; ## Generative Utilities
(defn gen-rsa-keyspec
"Returns a generator for RSA keys with the given strengths."
[strengths]
(gen/fmap
(partial vector :rsa :rsa-general)
(gen/elements strengths)))
(defn gen-ec-keyspec
"Returns a generator for EC keys with the given algorithm and named curves."
[algorithm curves]
(gen/fmap
(partial vector :ec algorithm)
(gen/elements curves)))
(defn spec->keypair
"Generates a keypair from a keyspec."
[[key-type & opts]]
(case key-type
:rsa (let [[algo strength] opts
rsa (pgp-gen/rsa-keypair-generator strength)]
(pgp-gen/generate-keypair rsa algo))
:ec (let [[algo curve] opts
ec (pgp-gen/ec-keypair-generator curve)]
(pgp-gen/generate-keypair ec algo))))
(def key-cache
"Stores generated keys by their key-specs to memoize key generation calls."
(atom {}))
(defn memospec->keypair
"Returns a keypair for a keyspec. Uses the key-cache var to memoize the
generated keys."
[spec]
(or (when (string? spec) spec)
(get @key-cache spec)
(let [k (spec->keypair spec)]
(swap! key-cache assoc spec k)
k)))
(defn generate-rsa-keypair []
(let [rsa (pgp-gen/rsa-keypair-generator 1024)]
(pgp-gen/generate-keypair rsa :rsa-general)))
(defn test-encryption-scenario
"Tests that encrypting and decrypting data with the given keypairs/passphrases
returns the original data."
[keyspecs data compress cipher armor]
(testing (str "Encrypting " (count data) " bytes with " cipher
" for keys " (pr-str keyspecs)
(when compress (str " compressed with " compress))
" encoded in " (if armor "ascii" "binary"))
(let [encryptors (map memospec->keypair keyspecs)
ciphertext (pgp-msg/encrypt
data encryptors
:compress compress
:cipher cipher
:armor armor)]
(is (not (bytes= data ciphertext))
"ciphertext bytes differ from data")
(doseq [decryptor encryptors]
(is (bytes= data (pgp-msg/decrypt ciphertext decryptor))
"decrypting the ciphertext returns plaintext"))
[encryptors ciphertext])))
|
[
{
"context": "--------------------------------\n;; Copyright 2017 Greg Haskins\n;;\n;; SPDX-License-Identifier: Apache-2.0\n;;-----",
"end": 110,
"score": 0.9998035430908203,
"start": 98,
"tag": "NAME",
"value": "Greg Haskins"
}
] | examples/example02/client/cljs/src/fabric_sdk/channel.cljs | simonmulser/fabric-chaintool | 138 | ;;-----------------------------------------------------------------------------
;; Copyright 2017 Greg Haskins
;;
;; SPDX-License-Identifier: Apache-2.0
;;-----------------------------------------------------------------------------
(ns fabric-sdk.channel
(:require-macros [fabric-sdk.macros :as m])
(:require [promesa.core :as p :include-macros true]))
(defn new [client name]
(.newChannel client name))
(defn initialize [channel]
(m/pwrap (.initialize channel)))
(defn add-peer [channel instance]
(.addPeer channel instance))
(defn add-orderer [channel instance]
(.addOrderer channel instance))
(defn set-dev-mode [channel enabled]
(.setDevMode channel enabled))
(defn send-instantiate-proposal [channel request]
(m/pwrap (.sendInstantiateProposal channel request)))
(defn send-transaction-proposal [channel request]
(m/pwrap (.sendTransactionProposal channel request)))
(defn send-transaction [channel request]
(m/pwrap (.sendTransaction channel request)))
(defn query-by-chaincode [channel request]
(m/pwrap (.queryByChaincode channel request)))
| 3676 | ;;-----------------------------------------------------------------------------
;; Copyright 2017 <NAME>
;;
;; SPDX-License-Identifier: Apache-2.0
;;-----------------------------------------------------------------------------
(ns fabric-sdk.channel
(:require-macros [fabric-sdk.macros :as m])
(:require [promesa.core :as p :include-macros true]))
(defn new [client name]
(.newChannel client name))
(defn initialize [channel]
(m/pwrap (.initialize channel)))
(defn add-peer [channel instance]
(.addPeer channel instance))
(defn add-orderer [channel instance]
(.addOrderer channel instance))
(defn set-dev-mode [channel enabled]
(.setDevMode channel enabled))
(defn send-instantiate-proposal [channel request]
(m/pwrap (.sendInstantiateProposal channel request)))
(defn send-transaction-proposal [channel request]
(m/pwrap (.sendTransactionProposal channel request)))
(defn send-transaction [channel request]
(m/pwrap (.sendTransaction channel request)))
(defn query-by-chaincode [channel request]
(m/pwrap (.queryByChaincode channel request)))
| true | ;;-----------------------------------------------------------------------------
;; Copyright 2017 PI:NAME:<NAME>END_PI
;;
;; SPDX-License-Identifier: Apache-2.0
;;-----------------------------------------------------------------------------
(ns fabric-sdk.channel
(:require-macros [fabric-sdk.macros :as m])
(:require [promesa.core :as p :include-macros true]))
(defn new [client name]
(.newChannel client name))
(defn initialize [channel]
(m/pwrap (.initialize channel)))
(defn add-peer [channel instance]
(.addPeer channel instance))
(defn add-orderer [channel instance]
(.addOrderer channel instance))
(defn set-dev-mode [channel enabled]
(.setDevMode channel enabled))
(defn send-instantiate-proposal [channel request]
(m/pwrap (.sendInstantiateProposal channel request)))
(defn send-transaction-proposal [channel request]
(m/pwrap (.sendTransactionProposal channel request)))
(defn send-transaction [channel request]
(m/pwrap (.sendTransaction channel request)))
(defn query-by-chaincode [channel request]
(m/pwrap (.queryByChaincode channel request)))
|
[
{
"context": "(comment\n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License",
"end": 48,
"score": 0.9998792409896851,
"start": 36,
"tag": "NAME",
"value": "Ronen Narkis"
},
{
"context": "comment\n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License,\n Version ",
"end": 61,
"score": 0.8580243587493896,
"start": 51,
"tag": "EMAIL",
"value": "arkisr.com"
}
] | src/es/node.clj | celestial-ops/core | 1 | (comment
re-core, Copyright 2012 Ronen Narkis, narkisr.com
Licensed under the Apache License,
Version 2.0 (the "License") you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.)
(ns es.node
"An embedded ES node instance"
(:import
[org.elasticsearch.node NodeBuilder])
(:require
[safely.core :refer [safely]]
[re-core.common :refer (get! import-logging)]
[clojurewerkz.elastisch.native.conversion :as cnv]
[clojurewerkz.elastisch.native :as es]))
(import-logging)
(def ES (atom nil))
(defn connect-
"Connecting to Elasticsearch"
[]
(let [{:keys [host port cluster]} (get! :elasticsearch)]
(info "Connecting to elasticsearch")
(reset! ES (es/connect [[host port]] {"cluster.name" cluster}))))
(defn connect
"Connecting to Elasticsearch with retry support"
[]
(let [{:keys [host port cluster]} (get! :elasticsearch)]
(safely (connect-)
:on-error
:max-retry 5
:message "Error while trying to connect to Elasticsearch"
:log-errors true
:retry-delay [:random-range :min 2000 :max 5000])))
(defn stop
"stops embedded ES node"
[]
(info "Stoping local elasticsearch node")
(.close @ES)
(reset! ES nil))
(defn health [indices]
(.name (.getStatus @ES)))
| 114195 | (comment
re-core, Copyright 2012 <NAME>, n<EMAIL>
Licensed under the Apache License,
Version 2.0 (the "License") you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.)
(ns es.node
"An embedded ES node instance"
(:import
[org.elasticsearch.node NodeBuilder])
(:require
[safely.core :refer [safely]]
[re-core.common :refer (get! import-logging)]
[clojurewerkz.elastisch.native.conversion :as cnv]
[clojurewerkz.elastisch.native :as es]))
(import-logging)
(def ES (atom nil))
(defn connect-
"Connecting to Elasticsearch"
[]
(let [{:keys [host port cluster]} (get! :elasticsearch)]
(info "Connecting to elasticsearch")
(reset! ES (es/connect [[host port]] {"cluster.name" cluster}))))
(defn connect
"Connecting to Elasticsearch with retry support"
[]
(let [{:keys [host port cluster]} (get! :elasticsearch)]
(safely (connect-)
:on-error
:max-retry 5
:message "Error while trying to connect to Elasticsearch"
:log-errors true
:retry-delay [:random-range :min 2000 :max 5000])))
(defn stop
"stops embedded ES node"
[]
(info "Stoping local elasticsearch node")
(.close @ES)
(reset! ES nil))
(defn health [indices]
(.name (.getStatus @ES)))
| true | (comment
re-core, Copyright 2012 PI:NAME:<NAME>END_PI, nPI:EMAIL:<EMAIL>END_PI
Licensed under the Apache License,
Version 2.0 (the "License") you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.)
(ns es.node
"An embedded ES node instance"
(:import
[org.elasticsearch.node NodeBuilder])
(:require
[safely.core :refer [safely]]
[re-core.common :refer (get! import-logging)]
[clojurewerkz.elastisch.native.conversion :as cnv]
[clojurewerkz.elastisch.native :as es]))
(import-logging)
(def ES (atom nil))
(defn connect-
"Connecting to Elasticsearch"
[]
(let [{:keys [host port cluster]} (get! :elasticsearch)]
(info "Connecting to elasticsearch")
(reset! ES (es/connect [[host port]] {"cluster.name" cluster}))))
(defn connect
"Connecting to Elasticsearch with retry support"
[]
(let [{:keys [host port cluster]} (get! :elasticsearch)]
(safely (connect-)
:on-error
:max-retry 5
:message "Error while trying to connect to Elasticsearch"
:log-errors true
:retry-delay [:random-range :min 2000 :max 5000])))
(defn stop
"stops embedded ES node"
[]
(info "Stoping local elasticsearch node")
(.close @ES)
(reset! ES nil))
(defn health [indices]
(.name (.getStatus @ES)))
|
[
{
"context": ";\n; Copyright © 2013 Sebastian Hoß <mail@shoss.de>\n; This work is free. You can redi",
"end": 34,
"score": 0.9998664259910583,
"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.999927818775177,
"start": 36,
"tag": "EMAIL",
"value": "mail@shoss.de"
}
] | src/main/clojure/finj/investment.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.investment
"In finance, investment is putting money into something with the expectation of gain, usually over a longer term.
This may or may not be backed by research and analysis. Most or all forms of investment involve some form of risk,
such as investment in equities, property, and even fixed interest securities which are subject, inter alia, to
inflation risk. or you can express it in short form The act or action of using (money) to make more money out of
something that will increase in value.
References:
* http://en.wikipedia.org/wiki/Investment"
(:require [com.github.sebhoss.def :refer :all]
[com.github.sebhoss.math :refer :all]
[finj.annuity :refer :all]))
(defnk net-present-value
"Calculates the net present value (NPV) of a time series of cash flows.
Parameters:
* rate - The discount rate.
* cashflows - A sequence of cashflows, ordered by their period. This includes the initial investment.
Examples:
* (net-present-value :rate 0.05 :cashflows [-1000 500 600 800])
=> 711.4782420904868
* (net-present-value :rate 0.1 :cashflows [-1250 560 630 840])
=> 410.85649887302736
* (net-present-value :rate 0.15 :cashflows [-2000 800 750 1200])
=> 51.7794033040193
References:
* http://en.wikipedia.org/wiki/Net_present_value"
[:rate :cashflows]
(reduce + (map #(/ %1 (pow (inc rate) %2)) cashflows (range))))
(defnk adjusted-present-value
"Calculates the adjusted present value (ADV) of a business.
Parameters:
* value-without-liabilities - The value of the business without any liabilities
* borrowed-capital - The amount of borrowed money as a sequence.
* rate - The business 'tax rate' for the borrowed money.
* risk-free-rate - The risk free rate.
Examples:
* (adjusted-present-value
:value-without-liabilities 250
:borrowed-capital [200 300 400 350]
:rate 0.1
:risk-free-rate 0.08)
=> 258.7884367220444
* (adjusted-present-value
:value-without-liabilities 300
:borrowed-capital [200 150 120 80]
:rate 0.05
:risk-free-rate 0.08)
=> 302.02110450642687
* (adjusted-present-value
:value-without-liabilities 500
:borrowed-capital [100 200 300 350]
:rate 0.15
:risk-free-rate 0.08)
=> 509.84273738759333
References:
- http://en.wikipedia.org/wiki/Adjusted_present_value"
[:value-without-liabilities :borrowed-capital :rate :risk-free-rate]
(+ value-without-liabilities
(reduce + (map #(/ (* %1 rate risk-free-rate) (pow (inc risk-free-rate) %2))
borrowed-capital (range)))))
(defnk equivalent-annual-cost
"In finance the equivalent annual cost (EAC) is the cost per year of owning and operating an asset over its entire
lifespan.
Parameters:
* investment - Total invesment cost
* period - Expected lifetime of the investment
* maintenance - Annual maintenance costs
* rate - Cost of invested capital
Examples:
* (equivalent-annual-cost :investment 50000 :period 3 :maintenance 13000 :rate 0.05)
=> 31360.42823156223
* (equivalent-annual-cost :investment 150000 :period 8 :maintenance 7500 :rate 0.05)
=> 30708.27204415216
* (equivalent-annual-cost :investment 75000 :period 5 :maintenance 11000 :rate 0.15)
=> 33373.66643461463
References:
* http://en.wikipedia.org/wiki/Equivalent_annual_cost"
[:investment :period :maintenance :rate]
{:pre [(number? investment)
(number? period)
(number? maintenance)
(number? rate)]}
(let [present-immediate-factor (present-immediate-factor :rate rate :period period)]
(+ maintenance (/ investment present-immediate-factor))))
| 104521 | ;
; 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.investment
"In finance, investment is putting money into something with the expectation of gain, usually over a longer term.
This may or may not be backed by research and analysis. Most or all forms of investment involve some form of risk,
such as investment in equities, property, and even fixed interest securities which are subject, inter alia, to
inflation risk. or you can express it in short form The act or action of using (money) to make more money out of
something that will increase in value.
References:
* http://en.wikipedia.org/wiki/Investment"
(:require [com.github.sebhoss.def :refer :all]
[com.github.sebhoss.math :refer :all]
[finj.annuity :refer :all]))
(defnk net-present-value
"Calculates the net present value (NPV) of a time series of cash flows.
Parameters:
* rate - The discount rate.
* cashflows - A sequence of cashflows, ordered by their period. This includes the initial investment.
Examples:
* (net-present-value :rate 0.05 :cashflows [-1000 500 600 800])
=> 711.4782420904868
* (net-present-value :rate 0.1 :cashflows [-1250 560 630 840])
=> 410.85649887302736
* (net-present-value :rate 0.15 :cashflows [-2000 800 750 1200])
=> 51.7794033040193
References:
* http://en.wikipedia.org/wiki/Net_present_value"
[:rate :cashflows]
(reduce + (map #(/ %1 (pow (inc rate) %2)) cashflows (range))))
(defnk adjusted-present-value
"Calculates the adjusted present value (ADV) of a business.
Parameters:
* value-without-liabilities - The value of the business without any liabilities
* borrowed-capital - The amount of borrowed money as a sequence.
* rate - The business 'tax rate' for the borrowed money.
* risk-free-rate - The risk free rate.
Examples:
* (adjusted-present-value
:value-without-liabilities 250
:borrowed-capital [200 300 400 350]
:rate 0.1
:risk-free-rate 0.08)
=> 258.7884367220444
* (adjusted-present-value
:value-without-liabilities 300
:borrowed-capital [200 150 120 80]
:rate 0.05
:risk-free-rate 0.08)
=> 302.02110450642687
* (adjusted-present-value
:value-without-liabilities 500
:borrowed-capital [100 200 300 350]
:rate 0.15
:risk-free-rate 0.08)
=> 509.84273738759333
References:
- http://en.wikipedia.org/wiki/Adjusted_present_value"
[:value-without-liabilities :borrowed-capital :rate :risk-free-rate]
(+ value-without-liabilities
(reduce + (map #(/ (* %1 rate risk-free-rate) (pow (inc risk-free-rate) %2))
borrowed-capital (range)))))
(defnk equivalent-annual-cost
"In finance the equivalent annual cost (EAC) is the cost per year of owning and operating an asset over its entire
lifespan.
Parameters:
* investment - Total invesment cost
* period - Expected lifetime of the investment
* maintenance - Annual maintenance costs
* rate - Cost of invested capital
Examples:
* (equivalent-annual-cost :investment 50000 :period 3 :maintenance 13000 :rate 0.05)
=> 31360.42823156223
* (equivalent-annual-cost :investment 150000 :period 8 :maintenance 7500 :rate 0.05)
=> 30708.27204415216
* (equivalent-annual-cost :investment 75000 :period 5 :maintenance 11000 :rate 0.15)
=> 33373.66643461463
References:
* http://en.wikipedia.org/wiki/Equivalent_annual_cost"
[:investment :period :maintenance :rate]
{:pre [(number? investment)
(number? period)
(number? maintenance)
(number? rate)]}
(let [present-immediate-factor (present-immediate-factor :rate rate :period period)]
(+ maintenance (/ investment present-immediate-factor))))
| 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.investment
"In finance, investment is putting money into something with the expectation of gain, usually over a longer term.
This may or may not be backed by research and analysis. Most or all forms of investment involve some form of risk,
such as investment in equities, property, and even fixed interest securities which are subject, inter alia, to
inflation risk. or you can express it in short form The act or action of using (money) to make more money out of
something that will increase in value.
References:
* http://en.wikipedia.org/wiki/Investment"
(:require [com.github.sebhoss.def :refer :all]
[com.github.sebhoss.math :refer :all]
[finj.annuity :refer :all]))
(defnk net-present-value
"Calculates the net present value (NPV) of a time series of cash flows.
Parameters:
* rate - The discount rate.
* cashflows - A sequence of cashflows, ordered by their period. This includes the initial investment.
Examples:
* (net-present-value :rate 0.05 :cashflows [-1000 500 600 800])
=> 711.4782420904868
* (net-present-value :rate 0.1 :cashflows [-1250 560 630 840])
=> 410.85649887302736
* (net-present-value :rate 0.15 :cashflows [-2000 800 750 1200])
=> 51.7794033040193
References:
* http://en.wikipedia.org/wiki/Net_present_value"
[:rate :cashflows]
(reduce + (map #(/ %1 (pow (inc rate) %2)) cashflows (range))))
(defnk adjusted-present-value
"Calculates the adjusted present value (ADV) of a business.
Parameters:
* value-without-liabilities - The value of the business without any liabilities
* borrowed-capital - The amount of borrowed money as a sequence.
* rate - The business 'tax rate' for the borrowed money.
* risk-free-rate - The risk free rate.
Examples:
* (adjusted-present-value
:value-without-liabilities 250
:borrowed-capital [200 300 400 350]
:rate 0.1
:risk-free-rate 0.08)
=> 258.7884367220444
* (adjusted-present-value
:value-without-liabilities 300
:borrowed-capital [200 150 120 80]
:rate 0.05
:risk-free-rate 0.08)
=> 302.02110450642687
* (adjusted-present-value
:value-without-liabilities 500
:borrowed-capital [100 200 300 350]
:rate 0.15
:risk-free-rate 0.08)
=> 509.84273738759333
References:
- http://en.wikipedia.org/wiki/Adjusted_present_value"
[:value-without-liabilities :borrowed-capital :rate :risk-free-rate]
(+ value-without-liabilities
(reduce + (map #(/ (* %1 rate risk-free-rate) (pow (inc risk-free-rate) %2))
borrowed-capital (range)))))
(defnk equivalent-annual-cost
"In finance the equivalent annual cost (EAC) is the cost per year of owning and operating an asset over its entire
lifespan.
Parameters:
* investment - Total invesment cost
* period - Expected lifetime of the investment
* maintenance - Annual maintenance costs
* rate - Cost of invested capital
Examples:
* (equivalent-annual-cost :investment 50000 :period 3 :maintenance 13000 :rate 0.05)
=> 31360.42823156223
* (equivalent-annual-cost :investment 150000 :period 8 :maintenance 7500 :rate 0.05)
=> 30708.27204415216
* (equivalent-annual-cost :investment 75000 :period 5 :maintenance 11000 :rate 0.15)
=> 33373.66643461463
References:
* http://en.wikipedia.org/wiki/Equivalent_annual_cost"
[:investment :period :maintenance :rate]
{:pre [(number? investment)
(number? period)
(number? maintenance)
(number? rate)]}
(let [present-immediate-factor (present-immediate-factor :rate rate :period period)]
(+ maintenance (/ investment present-immediate-factor))))
|
[
{
"context": "t-type bytes size]} upload-info\n blob-key (make-clean-uuid)\n blob-info (BlobInfo. blob-key content-ty",
"end": 2278,
"score": 0.971603512763977,
"start": 2263,
"tag": "KEY",
"value": "make-clean-uuid"
}
] | src/appengine_magic/blobstore_upload.clj | zenlambda/appengine-magic | 41 | (ns appengine-magic.blobstore-upload
(:use [appengine-magic.multipart-params :only [wrap-multipart-params]])
(:require [appengine-magic.services.datastore :as ds]
[clojure.java.io :as io])
(:import [java.io File OutputStreamWriter]
[java.net URL HttpURLConnection]
com.google.appengine.api.datastore.KeyFactory
com.google.appengine.api.blobstore.BlobKey))
(ds/defentity BlobInfo [^:key blob-key, content_type, creation, filename, size]
:kind "__BlobInfo__")
(ds/defentity BlobUploadSession [success_path] ; XXX: underscore (_), not hyphen (-)
:kind "__BlobUploadSession__")
(defn- make-clean-uuid []
(.replaceAll (str (java.util.UUID/randomUUID)) "-" ""))
(defn- hit-callback [req uploads success-path]
(let [url (URL. "http" (:server-name req) (:server-port req) success-path)
cxn (cast HttpURLConnection (.openConnection url))]
(doto cxn
(.setDoOutput true)
(.setRequestMethod "POST")
(.setUseCaches false)
(.setInstanceFollowRedirects false)
(.setRequestProperty "Content-Type" "text/plain")
(.setRequestProperty "X-AppEngine-BlobUpload" "true"))
(doseq [header ["User-Agent" "Cookie" "Origin" "Referer"]]
(let [lc-header (.toLowerCase header)]
(.setRequestProperty cxn header (get (:headers req) lc-header))))
(with-open [cxn-writer (-> cxn .getOutputStream OutputStreamWriter.)]
(.write cxn-writer (prn-str uploads)))
(.connect cxn)
(let [resp-code (.getResponseCode cxn)
headers (reduce (fn [acc [header-key header-value]]
(let [hv (into [] header-value)
hv (if (= 1 (count hv)) (first hv) hv)]
(when-not (nil? header-key)
(assoc acc header-key hv))))
{}
(.getHeaderFields cxn))]
(when-not (= 302 resp-code)
(throw (RuntimeException. "An upload callback must return a redirect.")))
(.sendRedirect (:response req) (headers "Location"))
{:commit? false})))
(defn- save-upload! [upload-name upload-info target-dir]
(let [{:keys [filename content-type bytes size]} upload-info
blob-key (make-clean-uuid)
blob-info (BlobInfo. blob-key content-type (java.util.Date.) filename size)
blob-file (File. target-dir blob-key)]
(io/copy bytes blob-file)
(ds/save! blob-info)
;; Return the blob-key for later use.
blob-key))
(defn make-blob-upload-handler [war-root]
(let [web-inf-dir (File. war-root "WEB-INF")
appengine-generated-dir (File. web-inf-dir "appengine-generated")]
(wrap-multipart-params
(fn [req]
(let [uri (:uri req)
key-string (.substring uri (inc (.lastIndexOf uri "/")))
key-object (KeyFactory/stringToKey key-string)
upload-session (ds/retrieve BlobUploadSession key-object
:kind "__BlobUploadSession__")
raw-uploads (:multipart-params req)
uploads (reduce (fn [acc [upload-name upload-info]]
(if (map? upload-info)
(assoc acc upload-name
(save-upload! upload-name
upload-info appengine-generated-dir))
acc))
{}
raw-uploads)]
(ds/delete! upload-session)
(let [resp (hit-callback req uploads (:success_path upload-session))]
;; just return it to the user's browser
resp))))))
| 64181 | (ns appengine-magic.blobstore-upload
(:use [appengine-magic.multipart-params :only [wrap-multipart-params]])
(:require [appengine-magic.services.datastore :as ds]
[clojure.java.io :as io])
(:import [java.io File OutputStreamWriter]
[java.net URL HttpURLConnection]
com.google.appengine.api.datastore.KeyFactory
com.google.appengine.api.blobstore.BlobKey))
(ds/defentity BlobInfo [^:key blob-key, content_type, creation, filename, size]
:kind "__BlobInfo__")
(ds/defentity BlobUploadSession [success_path] ; XXX: underscore (_), not hyphen (-)
:kind "__BlobUploadSession__")
(defn- make-clean-uuid []
(.replaceAll (str (java.util.UUID/randomUUID)) "-" ""))
(defn- hit-callback [req uploads success-path]
(let [url (URL. "http" (:server-name req) (:server-port req) success-path)
cxn (cast HttpURLConnection (.openConnection url))]
(doto cxn
(.setDoOutput true)
(.setRequestMethod "POST")
(.setUseCaches false)
(.setInstanceFollowRedirects false)
(.setRequestProperty "Content-Type" "text/plain")
(.setRequestProperty "X-AppEngine-BlobUpload" "true"))
(doseq [header ["User-Agent" "Cookie" "Origin" "Referer"]]
(let [lc-header (.toLowerCase header)]
(.setRequestProperty cxn header (get (:headers req) lc-header))))
(with-open [cxn-writer (-> cxn .getOutputStream OutputStreamWriter.)]
(.write cxn-writer (prn-str uploads)))
(.connect cxn)
(let [resp-code (.getResponseCode cxn)
headers (reduce (fn [acc [header-key header-value]]
(let [hv (into [] header-value)
hv (if (= 1 (count hv)) (first hv) hv)]
(when-not (nil? header-key)
(assoc acc header-key hv))))
{}
(.getHeaderFields cxn))]
(when-not (= 302 resp-code)
(throw (RuntimeException. "An upload callback must return a redirect.")))
(.sendRedirect (:response req) (headers "Location"))
{:commit? false})))
(defn- save-upload! [upload-name upload-info target-dir]
(let [{:keys [filename content-type bytes size]} upload-info
blob-key (<KEY>)
blob-info (BlobInfo. blob-key content-type (java.util.Date.) filename size)
blob-file (File. target-dir blob-key)]
(io/copy bytes blob-file)
(ds/save! blob-info)
;; Return the blob-key for later use.
blob-key))
(defn make-blob-upload-handler [war-root]
(let [web-inf-dir (File. war-root "WEB-INF")
appengine-generated-dir (File. web-inf-dir "appengine-generated")]
(wrap-multipart-params
(fn [req]
(let [uri (:uri req)
key-string (.substring uri (inc (.lastIndexOf uri "/")))
key-object (KeyFactory/stringToKey key-string)
upload-session (ds/retrieve BlobUploadSession key-object
:kind "__BlobUploadSession__")
raw-uploads (:multipart-params req)
uploads (reduce (fn [acc [upload-name upload-info]]
(if (map? upload-info)
(assoc acc upload-name
(save-upload! upload-name
upload-info appengine-generated-dir))
acc))
{}
raw-uploads)]
(ds/delete! upload-session)
(let [resp (hit-callback req uploads (:success_path upload-session))]
;; just return it to the user's browser
resp))))))
| true | (ns appengine-magic.blobstore-upload
(:use [appengine-magic.multipart-params :only [wrap-multipart-params]])
(:require [appengine-magic.services.datastore :as ds]
[clojure.java.io :as io])
(:import [java.io File OutputStreamWriter]
[java.net URL HttpURLConnection]
com.google.appengine.api.datastore.KeyFactory
com.google.appengine.api.blobstore.BlobKey))
(ds/defentity BlobInfo [^:key blob-key, content_type, creation, filename, size]
:kind "__BlobInfo__")
(ds/defentity BlobUploadSession [success_path] ; XXX: underscore (_), not hyphen (-)
:kind "__BlobUploadSession__")
(defn- make-clean-uuid []
(.replaceAll (str (java.util.UUID/randomUUID)) "-" ""))
(defn- hit-callback [req uploads success-path]
(let [url (URL. "http" (:server-name req) (:server-port req) success-path)
cxn (cast HttpURLConnection (.openConnection url))]
(doto cxn
(.setDoOutput true)
(.setRequestMethod "POST")
(.setUseCaches false)
(.setInstanceFollowRedirects false)
(.setRequestProperty "Content-Type" "text/plain")
(.setRequestProperty "X-AppEngine-BlobUpload" "true"))
(doseq [header ["User-Agent" "Cookie" "Origin" "Referer"]]
(let [lc-header (.toLowerCase header)]
(.setRequestProperty cxn header (get (:headers req) lc-header))))
(with-open [cxn-writer (-> cxn .getOutputStream OutputStreamWriter.)]
(.write cxn-writer (prn-str uploads)))
(.connect cxn)
(let [resp-code (.getResponseCode cxn)
headers (reduce (fn [acc [header-key header-value]]
(let [hv (into [] header-value)
hv (if (= 1 (count hv)) (first hv) hv)]
(when-not (nil? header-key)
(assoc acc header-key hv))))
{}
(.getHeaderFields cxn))]
(when-not (= 302 resp-code)
(throw (RuntimeException. "An upload callback must return a redirect.")))
(.sendRedirect (:response req) (headers "Location"))
{:commit? false})))
(defn- save-upload! [upload-name upload-info target-dir]
(let [{:keys [filename content-type bytes size]} upload-info
blob-key (PI:KEY:<KEY>END_PI)
blob-info (BlobInfo. blob-key content-type (java.util.Date.) filename size)
blob-file (File. target-dir blob-key)]
(io/copy bytes blob-file)
(ds/save! blob-info)
;; Return the blob-key for later use.
blob-key))
(defn make-blob-upload-handler [war-root]
(let [web-inf-dir (File. war-root "WEB-INF")
appengine-generated-dir (File. web-inf-dir "appengine-generated")]
(wrap-multipart-params
(fn [req]
(let [uri (:uri req)
key-string (.substring uri (inc (.lastIndexOf uri "/")))
key-object (KeyFactory/stringToKey key-string)
upload-session (ds/retrieve BlobUploadSession key-object
:kind "__BlobUploadSession__")
raw-uploads (:multipart-params req)
uploads (reduce (fn [acc [upload-name upload-info]]
(if (map? upload-info)
(assoc acc upload-name
(save-upload! upload-name
upload-info appengine-generated-dir))
acc))
{}
raw-uploads)]
(ds/delete! upload-session)
(let [resp (hit-callback req uploads (:success_path upload-session))]
;; just return it to the user's browser
resp))))))
|
[
{
"context": "n\"\n ::danger/token \"SEVMTE8.nppGBrCjzE0Ipz1pzm6gRLwi_rc\"})\n (itsdangerous/unsign \"SEVMTE8.nppGBrC",
"end": 2296,
"score": 0.6746527552604675,
"start": 2261,
"tag": "KEY",
"value": "SEVMTE8.nppGBrCjzE0Ipz1pzm6gRLwi_rc"
}
] | test/exoscale/itsdangerous_test.clj | exoscale/clj-itsdangerous | 0 | (ns exoscale.itsdangerous-test
(:require [clojure.test :refer :all]
[itsdangerous]
[exoscale.itsdangerous :as danger]))
(deftest readme-test
;; Replicate usage shown in the README
(let [payload "{\"user-id\": 1234}"
private-key "A-SECRET-KEY"
salt "session"
algorithm ::danger/hmac-sha1
token (danger/sign {:exoscale.itsdangerous/algorithm algorithm
:exoscale.itsdangerous/private-key private-key
:exoscale.itsdangerous/salt salt
:exoscale.itsdangerous/payload payload})]
(testing "Verifying yields the initial payload"
(is (= (danger/verify {:exoscale.itsdangerous/algorithm algorithm
:exoscale.itsdangerous/private-key private-key
:exoscale.itsdangerous/salt salt
:exoscale.itsdangerous/token token})
payload)))))
(deftest multiple-key-test
;; Replicate usage shown in the README
(let [payload "{\"user-id\": 1234}"
old-key "A-SECRET-KEY"
private-keys ["ANOTHER-KEY" old-key]
salt "session"
algorithm ::danger/hmac-sha1
token (danger/sign {:exoscale.itsdangerous/algorithm algorithm
:exoscale.itsdangerous/private-key old-key
:exoscale.itsdangerous/salt salt
:exoscale.itsdangerous/payload payload})]
(testing "Verifying yields the initial payload"
(is (= (danger/verify {:exoscale.itsdangerous/algorithm algorithm
:exoscale.itsdangerous/private-keys private-keys
:exoscale.itsdangerous/salt salt
:exoscale.itsdangerous/token token})
payload)))))
(deftest compatibility-test
(is (= (danger/verify {::danger/algorithm ::danger/hmac-sha1
::danger/private-key "A-SECRET-KEY"
::danger/salt "session"
::danger/token "SEVMTE8.nppGBrCjzE0Ipz1pzm6gRLwi_rc"})
(itsdangerous/unsign "SEVMTE8.nppGBrCjzE0Ipz1pzm6gRLwi_rc"
"A-SECRET-KEY"
{:alg :hs1
:salt "session"})
"HELLO")))
| 65322 | (ns exoscale.itsdangerous-test
(:require [clojure.test :refer :all]
[itsdangerous]
[exoscale.itsdangerous :as danger]))
(deftest readme-test
;; Replicate usage shown in the README
(let [payload "{\"user-id\": 1234}"
private-key "A-SECRET-KEY"
salt "session"
algorithm ::danger/hmac-sha1
token (danger/sign {:exoscale.itsdangerous/algorithm algorithm
:exoscale.itsdangerous/private-key private-key
:exoscale.itsdangerous/salt salt
:exoscale.itsdangerous/payload payload})]
(testing "Verifying yields the initial payload"
(is (= (danger/verify {:exoscale.itsdangerous/algorithm algorithm
:exoscale.itsdangerous/private-key private-key
:exoscale.itsdangerous/salt salt
:exoscale.itsdangerous/token token})
payload)))))
(deftest multiple-key-test
;; Replicate usage shown in the README
(let [payload "{\"user-id\": 1234}"
old-key "A-SECRET-KEY"
private-keys ["ANOTHER-KEY" old-key]
salt "session"
algorithm ::danger/hmac-sha1
token (danger/sign {:exoscale.itsdangerous/algorithm algorithm
:exoscale.itsdangerous/private-key old-key
:exoscale.itsdangerous/salt salt
:exoscale.itsdangerous/payload payload})]
(testing "Verifying yields the initial payload"
(is (= (danger/verify {:exoscale.itsdangerous/algorithm algorithm
:exoscale.itsdangerous/private-keys private-keys
:exoscale.itsdangerous/salt salt
:exoscale.itsdangerous/token token})
payload)))))
(deftest compatibility-test
(is (= (danger/verify {::danger/algorithm ::danger/hmac-sha1
::danger/private-key "A-SECRET-KEY"
::danger/salt "session"
::danger/token "<KEY>"})
(itsdangerous/unsign "SEVMTE8.nppGBrCjzE0Ipz1pzm6gRLwi_rc"
"A-SECRET-KEY"
{:alg :hs1
:salt "session"})
"HELLO")))
| true | (ns exoscale.itsdangerous-test
(:require [clojure.test :refer :all]
[itsdangerous]
[exoscale.itsdangerous :as danger]))
(deftest readme-test
;; Replicate usage shown in the README
(let [payload "{\"user-id\": 1234}"
private-key "A-SECRET-KEY"
salt "session"
algorithm ::danger/hmac-sha1
token (danger/sign {:exoscale.itsdangerous/algorithm algorithm
:exoscale.itsdangerous/private-key private-key
:exoscale.itsdangerous/salt salt
:exoscale.itsdangerous/payload payload})]
(testing "Verifying yields the initial payload"
(is (= (danger/verify {:exoscale.itsdangerous/algorithm algorithm
:exoscale.itsdangerous/private-key private-key
:exoscale.itsdangerous/salt salt
:exoscale.itsdangerous/token token})
payload)))))
(deftest multiple-key-test
;; Replicate usage shown in the README
(let [payload "{\"user-id\": 1234}"
old-key "A-SECRET-KEY"
private-keys ["ANOTHER-KEY" old-key]
salt "session"
algorithm ::danger/hmac-sha1
token (danger/sign {:exoscale.itsdangerous/algorithm algorithm
:exoscale.itsdangerous/private-key old-key
:exoscale.itsdangerous/salt salt
:exoscale.itsdangerous/payload payload})]
(testing "Verifying yields the initial payload"
(is (= (danger/verify {:exoscale.itsdangerous/algorithm algorithm
:exoscale.itsdangerous/private-keys private-keys
:exoscale.itsdangerous/salt salt
:exoscale.itsdangerous/token token})
payload)))))
(deftest compatibility-test
(is (= (danger/verify {::danger/algorithm ::danger/hmac-sha1
::danger/private-key "A-SECRET-KEY"
::danger/salt "session"
::danger/token "PI:KEY:<KEY>END_PI"})
(itsdangerous/unsign "SEVMTE8.nppGBrCjzE0Ipz1pzm6gRLwi_rc"
"A-SECRET-KEY"
{:alg :hs1
:salt "session"})
"HELLO")))
|
[
{
"context": "er])]\n\n (let [james (UUID/randomUUID)\n mary (UUID/randomUUID)]\n\n (chimera/ensure-migrati",
"end": 1422,
"score": 0.7245378494262695,
"start": 1418,
"tag": "NAME",
"value": "mary"
},
{
"context": " :test.person/name \"James\"})\n (chimera/operate adapter :chimera.oper",
"end": 1708,
"score": 0.9984225630760193,
"start": 1703,
"tag": "NAME",
"value": "James"
},
{
"context": "te adapter :chimera.operation/put {:test.person/id mary\n ",
"end": 1789,
"score": 0.959693968296051,
"start": 1785,
"tag": "NAME",
"value": "mary"
},
{
"context": " :test.person/name \"Mary\"})\n (is (= {:test.person/id james, :test.p",
"end": 1870,
"score": 0.9994443655014038,
"start": 1866,
"tag": "NAME",
"value": "Mary"
},
{
"context": "rson/name \"Mary\"})\n (is (= {:test.person/id james, :test.person/name \"James\"}\n (chime",
"end": 1911,
"score": 0.6999456882476807,
"start": 1906,
"tag": "NAME",
"value": "james"
},
{
"context": "(is (= {:test.person/id james, :test.person/name \"James\"}\n (chimera/operate adapter :chimer",
"end": 1937,
"score": 0.9993950128555298,
"start": 1932,
"tag": "NAME",
"value": "James"
},
{
"context": "mera.operation/get (chimera/lookup :test.person/id james))))\n (is (= {:test.person/id mary, :test.p",
"end": 2040,
"score": 0.7049645185470581,
"start": 2035,
"tag": "NAME",
"value": "james"
},
{
"context": "erson/id james))))\n (is (= {:test.person/id mary, :test.person/name \"Mary\"}\n (chimer",
"end": 2081,
"score": 0.8284233212471008,
"start": 2077,
"tag": "NAME",
"value": "mary"
},
{
"context": " (is (= {:test.person/id mary, :test.person/name \"Mary\"}\n (chimera/operate adapter :chimer",
"end": 2106,
"score": 0.9994308948516846,
"start": 2102,
"tag": "NAME",
"value": "Mary"
},
{
"context": "mera.operation/get (chimera/lookup :test.person/id mary))))\n (is (nil? (chimera/operate adapter",
"end": 2205,
"score": 0.8888146281242371,
"start": 2204,
"tag": "NAME",
"value": "m"
},
{
"context": "ra.operation/get (chimera/lookup :test.person/id mary))))\n (is (nil? (chimera/operate adapter :c",
"end": 2208,
"score": 0.5514602661132812,
"start": 2205,
"tag": "NAME",
"value": "ary"
},
{
"context": "dapter :chimera.operation/put {:test.person/name \"Elizabeth\"}))))\n\n (testing \"testing updates\"\n (",
"end": 2505,
"score": 0.9889643788337708,
"start": 2496,
"tag": "NAME",
"value": "Elizabeth"
},
{
"context": "te adapter :chimera.operation/put {:test.person/id james\n ",
"end": 2694,
"score": 0.6499119400978088,
"start": 2693,
"tag": "NAME",
"value": "j"
},
{
"context": " adapter :chimera.operation/put {:test.person/id james\n ",
"end": 2698,
"score": 0.6248201727867126,
"start": 2694,
"tag": "NAME",
"value": "ames"
},
{
"context": "person/dob t1})\n\n (is (= {:test.person/id james,\n :test.person/name \"James\"\n",
"end": 2819,
"score": 0.6136941313743591,
"start": 2818,
"tag": "NAME",
"value": "j"
},
{
"context": "rson/dob t1})\n\n (is (= {:test.person/id james,\n :test.person/name \"James\"\n ",
"end": 2823,
"score": 0.565459132194519,
"start": 2819,
"tag": "NAME",
"value": "ames"
},
{
"context": "on/id james,\n :test.person/name \"James\"\n :test.person/dob t1}\n ",
"end": 2867,
"score": 0.9996668100357056,
"start": 2862,
"tag": "NAME",
"value": "James"
},
{
"context": "ra.operation/get (chimera/lookup :test.person/id james))))\n\n (is (thrown-with-msg? ArachneExcep",
"end": 3010,
"score": 0.4533329904079437,
"start": 3006,
"tag": "NAME",
"value": "ames"
},
{
"context": " adapter :chimera.operation/put {:test.person/id james\n ",
"end": 3269,
"score": 0.39021775126457214,
"start": 3265,
"tag": "NAME",
"value": "ames"
},
{
"context": " :test.person/name \"Jimmy\"\n ",
"end": 3356,
"score": 0.9950723648071289,
"start": 3351,
"tag": "NAME",
"value": "Jimmy"
},
{
"context": "rson/dob t2})\n\n (is (= {:test.person/id james,\n :test.person/name \"Jimmy\"\n ",
"end": 3482,
"score": 0.5142452716827393,
"start": 3478,
"tag": "NAME",
"value": "ames"
},
{
"context": "on/id james,\n :test.person/name \"Jimmy\"\n :test.person/dob t2}\n ",
"end": 3526,
"score": 0.9990302324295044,
"start": 3521,
"tag": "NAME",
"value": "Jimmy"
},
{
"context": "tion/delete-entity (chimera/lookup :test.person/id james))\n\n (is (nil? (chimera/operate adapter",
"end": 3808,
"score": 0.816024661064148,
"start": 3807,
"tag": "NAME",
"value": "j"
},
{
"context": "on/delete-entity (chimera/lookup :test.person/id james))\n\n (is (nil? (chimera/operate adapter :ch",
"end": 3812,
"score": 0.8219655156135559,
"start": 3808,
"tag": "NAME",
"value": "ames"
},
{
"context": "mera.operation/get (chimera/lookup :test.person/id james)))))\n\n\n (testing \"can't set cardinality-",
"end": 3915,
"score": 0.8249974250793457,
"start": 3914,
"tag": "NAME",
"value": "j"
},
{
"context": "ra.operation/get (chimera/lookup :test.person/id james)))))\n\n\n (testing \"can't set cardinality-many",
"end": 3919,
"score": 0.7664437890052795,
"start": 3915,
"tag": "NAME",
"value": "ames"
},
{
"context": "era.operation/put\n {:test.person/id mary\n :test.person/nicknames \"M-dog\"})",
"end": 4154,
"score": 0.9826980233192444,
"start": 4150,
"tag": "NAME",
"value": "mary"
},
{
"context": "era.operation/put\n {:test.person/id mary\n :test.person/name #{\"Mary\"}}))))",
"end": 4437,
"score": 0.9255656003952026,
"start": 4433,
"tag": "NAME",
"value": "mary"
},
{
"context": "son/id mary\n :test.person/name #{\"Mary\"}}))))\n\n\n\n )))\n\n(defn delete-attributes\n [a",
"end": 4480,
"score": 0.999563992023468,
"start": 4476,
"tag": "NAME",
"value": "Mary"
},
{
"context": "andomUUID)\n original-map {:test.person/id james\n :test.person/name \"Ja",
"end": 4908,
"score": 0.5836672186851501,
"start": 4907,
"tag": "NAME",
"value": "j"
},
{
"context": " james\n :test.person/name \"James\"\n :test.person/dob (Date.)",
"end": 4961,
"score": 0.9978441596031189,
"start": 4956,
"tag": "NAME",
"value": "James"
},
{
"context": ".operation/delete [(chimera/lookup :test.person/id james)\n ",
"end": 5216,
"score": 0.8295601606369019,
"start": 5215,
"tag": "NAME",
"value": "j"
},
{
"context": "peration/delete [(chimera/lookup :test.person/id james)\n ",
"end": 5220,
"score": 0.5985090136528015,
"start": 5216,
"tag": "NAME",
"value": "ames"
},
{
"context": " :test.person/name \"Jimmy-jim\"])\n\n (is (= original-map (chimera/operate ",
"end": 5310,
"score": 0.9966524839401245,
"start": 5301,
"tag": "NAME",
"value": "Jimmy-jim"
},
{
"context": ".operation/delete [(chimera/lookup :test.person/id james)\n ",
"end": 5527,
"score": 0.5301856994628906,
"start": 5526,
"tag": "NAME",
"value": "j"
},
{
"context": "peration/delete [(chimera/lookup :test.person/id james)\n ",
"end": 5531,
"score": 0.5298119783401489,
"start": 5527,
"tag": "NAME",
"value": "ames"
},
{
"context": " :test.person/name \"James\"])\n\n (is (= (dissoc original-map :test.per",
"end": 5617,
"score": 0.9826077222824097,
"start": 5612,
"tag": "NAME",
"value": "James"
},
{
"context": "mera.operation/get (chimera/lookup :test.person/id james))))\n\n (chimera/operate adapter :chimer",
"end": 5773,
"score": 0.6495644450187683,
"start": 5772,
"tag": "NAME",
"value": "j"
},
{
"context": "ra.operation/get (chimera/lookup :test.person/id james))))\n\n (chimera/operate adapter :chimera.op",
"end": 5777,
"score": 0.44761261343955994,
"start": 5773,
"tag": "NAME",
"value": "ames"
},
{
"context": ".operation/delete [(chimera/lookup :test.person/id james)\n ",
"end": 5876,
"score": 0.6976955533027649,
"start": 5875,
"tag": "NAME",
"value": "j"
},
{
"context": "peration/delete [(chimera/lookup :test.person/id james)\n ",
"end": 5880,
"score": 0.502987265586853,
"start": 5876,
"tag": "NAME",
"value": "ames"
},
{
"context": "test.person/dob])\n\n (is (= {:test.person/id james}\n (chimera/operate adapter :chi",
"end": 5995,
"score": 0.6707322001457214,
"start": 5994,
"tag": "NAME",
"value": "j"
},
{
"context": "st.person/dob])\n\n (is (= {:test.person/id james}\n (chimera/operate adapter :chimera",
"end": 5999,
"score": 0.5630182027816772,
"start": 5995,
"tag": "NAME",
"value": "ames"
},
{
"context": "ra.operation/get (chimera/lookup :test.person/id james)))))\n\n (testing \"delete attr cannot delete k",
"end": 6101,
"score": 0.4462404251098633,
"start": 6097,
"tag": "NAME",
"value": "ames"
},
{
"context": ".operation/delete [(chimera/lookup :test.person/id james)\n ",
"end": 6344,
"score": 0.7041252255439758,
"start": 6343,
"tag": "NAME",
"value": "j"
},
{
"context": "peration/delete [(chimera/lookup :test.person/id james)\n ",
"end": 6348,
"score": 0.5272682905197144,
"start": 6344,
"tag": "NAME",
"value": "ames"
}
] | src/arachne/chimera/test_harness/basics.clj | arachne-framework/arachne-chimera | 2 | (ns arachne.chimera.test-harness.basics
(:require [arachne.chimera :as chimera]
[arachne.core :as core]
[arachne.core.runtime :as rt]
[arachne.chimera.test-harness.common :as common]
[com.stuartsierra.component :as component]
[clojure.test :as test :refer [testing is]])
(:import [java.util UUID Date]
[arachne ArachneException]))
(defn bad-operations
[adapter-dsl-fn modules]
(let [cfg (core/build-config modules `(common/config 0 ~adapter-dsl-fn))
rt (rt/init cfg [:arachne/id :test/rt])
rt (component/start rt)
adapter (rt/lookup rt [:arachne/id :test/adapter])]
(is (thrown-with-msg? ArachneException #"not supported"
(chimera/operate adapter :no.such/operation [])))
(is (thrown-with-msg? ArachneException #"Unknown dispatch"
(chimera/operate adapter :test.operation/foo [])))
(is (thrown-with-msg? ArachneException #"did not conform "
(chimera/operate adapter :chimera.operation/initialize-migrations false)))))
(defn simple-crud
[adapter-dsl-fn modules]
(let [cfg (core/build-config modules `(common/config 0 ~adapter-dsl-fn))
rt (rt/init cfg [:arachne/id :test/rt])
rt (component/start rt)
adapter (rt/lookup rt [:arachne/id :test/adapter])]
(let [james (UUID/randomUUID)
mary (UUID/randomUUID)]
(chimera/ensure-migrations rt [:arachne/id :test/adapter])
(testing "testing basic put/get"
(chimera/operate adapter :chimera.operation/put {:test.person/id james
:test.person/name "James"})
(chimera/operate adapter :chimera.operation/put {:test.person/id mary
:test.person/name "Mary"})
(is (= {:test.person/id james, :test.person/name "James"}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id james))))
(is (= {:test.person/id mary, :test.person/name "Mary"}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id mary))))
(is (nil? (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id (UUID/randomUUID)))))
(is (thrown-with-msg? ArachneException #"requires a key"
(chimera/operate adapter :chimera.operation/put {:test.person/name "Elizabeth"}))))
(testing "testing updates"
(let [t1 (java.util.Date.)
t2 (java.util.Date.)]
(chimera/operate adapter :chimera.operation/put {:test.person/id james
:test.person/dob t1})
(is (= {:test.person/id james,
:test.person/name "James"
:test.person/dob t1}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id james))))
(is (thrown-with-msg? ArachneException #"requires a key"
(chimera/operate adapter :chimera.operation/put {:test.person/dob t1})))
(chimera/operate adapter :chimera.operation/put {:test.person/id james
:test.person/name "Jimmy"
:test.person/dob t2})
(is (= {:test.person/id james,
:test.person/name "Jimmy"
:test.person/dob t2}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id james))))))
(testing "delete entity"
(chimera/operate adapter :chimera.operation/delete-entity (chimera/lookup :test.person/id james))
(is (nil? (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id james)))))
(testing "can't set cardinality-many attrs using single value"
(is (thrown-with-msg? ArachneException #"be a set"
(chimera/operate adapter :chimera.operation/put
{:test.person/id mary
:test.person/nicknames "M-dog"}))))
(testing "can't set cardinality-one attrs using a set"
(is (thrown-with-msg? ArachneException #"be a single value"
(chimera/operate adapter :chimera.operation/put
{:test.person/id mary
:test.person/name #{"Mary"}}))))
)))
(defn delete-attributes
[adapter-dsl-fn modules]
(let [cfg (core/build-config modules `(common/config 0 ~adapter-dsl-fn))
rt (rt/init cfg [:arachne/id :test/rt])
rt (component/start rt)
adapter (rt/lookup rt [:arachne/id :test/adapter])]
(chimera/ensure-migrations rt [:arachne/id :test/adapter])
(let [james (UUID/randomUUID)
original-map {:test.person/id james
:test.person/name "James"
:test.person/dob (Date.)}]
(testing "Testing delete attr"
(chimera/operate adapter :chimera.operation/put original-map)
(chimera/operate adapter :chimera.operation/delete [(chimera/lookup :test.person/id james)
:test.person/name "Jimmy-jim"])
(is (= original-map (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id james))))
(chimera/operate adapter :chimera.operation/delete [(chimera/lookup :test.person/id james)
:test.person/name "James"])
(is (= (dissoc original-map :test.person/name)
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id james))))
(chimera/operate adapter :chimera.operation/delete [(chimera/lookup :test.person/id james)
:test.person/dob])
(is (= {:test.person/id james}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id james)))))
(testing "delete attr cannot delete key attributes"
(is (thrown-with-msg? ArachneException #"Cannot delete key attribute"
(chimera/operate adapter :chimera.operation/delete [(chimera/lookup :test.person/id james)
:test.person/id])
))
))))
(defn exercise-all
[adapter-dsl-fn modules]
(bad-operations adapter-dsl-fn modules)
(simple-crud adapter-dsl-fn modules)
(delete-attributes adapter-dsl-fn modules))
| 7610 | (ns arachne.chimera.test-harness.basics
(:require [arachne.chimera :as chimera]
[arachne.core :as core]
[arachne.core.runtime :as rt]
[arachne.chimera.test-harness.common :as common]
[com.stuartsierra.component :as component]
[clojure.test :as test :refer [testing is]])
(:import [java.util UUID Date]
[arachne ArachneException]))
(defn bad-operations
[adapter-dsl-fn modules]
(let [cfg (core/build-config modules `(common/config 0 ~adapter-dsl-fn))
rt (rt/init cfg [:arachne/id :test/rt])
rt (component/start rt)
adapter (rt/lookup rt [:arachne/id :test/adapter])]
(is (thrown-with-msg? ArachneException #"not supported"
(chimera/operate adapter :no.such/operation [])))
(is (thrown-with-msg? ArachneException #"Unknown dispatch"
(chimera/operate adapter :test.operation/foo [])))
(is (thrown-with-msg? ArachneException #"did not conform "
(chimera/operate adapter :chimera.operation/initialize-migrations false)))))
(defn simple-crud
[adapter-dsl-fn modules]
(let [cfg (core/build-config modules `(common/config 0 ~adapter-dsl-fn))
rt (rt/init cfg [:arachne/id :test/rt])
rt (component/start rt)
adapter (rt/lookup rt [:arachne/id :test/adapter])]
(let [james (UUID/randomUUID)
<NAME> (UUID/randomUUID)]
(chimera/ensure-migrations rt [:arachne/id :test/adapter])
(testing "testing basic put/get"
(chimera/operate adapter :chimera.operation/put {:test.person/id james
:test.person/name "<NAME>"})
(chimera/operate adapter :chimera.operation/put {:test.person/id <NAME>
:test.person/name "<NAME>"})
(is (= {:test.person/id <NAME>, :test.person/name "<NAME>"}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id <NAME>))))
(is (= {:test.person/id <NAME>, :test.person/name "<NAME>"}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id <NAME> <NAME>))))
(is (nil? (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id (UUID/randomUUID)))))
(is (thrown-with-msg? ArachneException #"requires a key"
(chimera/operate adapter :chimera.operation/put {:test.person/name "<NAME>"}))))
(testing "testing updates"
(let [t1 (java.util.Date.)
t2 (java.util.Date.)]
(chimera/operate adapter :chimera.operation/put {:test.person/id <NAME> <NAME>
:test.person/dob t1})
(is (= {:test.person/id <NAME> <NAME>,
:test.person/name "<NAME>"
:test.person/dob t1}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id j<NAME>))))
(is (thrown-with-msg? ArachneException #"requires a key"
(chimera/operate adapter :chimera.operation/put {:test.person/dob t1})))
(chimera/operate adapter :chimera.operation/put {:test.person/id j<NAME>
:test.person/name "<NAME>"
:test.person/dob t2})
(is (= {:test.person/id j<NAME>,
:test.person/name "<NAME>"
:test.person/dob t2}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id james))))))
(testing "delete entity"
(chimera/operate adapter :chimera.operation/delete-entity (chimera/lookup :test.person/id <NAME> <NAME>))
(is (nil? (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id <NAME> <NAME>)))))
(testing "can't set cardinality-many attrs using single value"
(is (thrown-with-msg? ArachneException #"be a set"
(chimera/operate adapter :chimera.operation/put
{:test.person/id <NAME>
:test.person/nicknames "M-dog"}))))
(testing "can't set cardinality-one attrs using a set"
(is (thrown-with-msg? ArachneException #"be a single value"
(chimera/operate adapter :chimera.operation/put
{:test.person/id <NAME>
:test.person/name #{"<NAME>"}}))))
)))
(defn delete-attributes
[adapter-dsl-fn modules]
(let [cfg (core/build-config modules `(common/config 0 ~adapter-dsl-fn))
rt (rt/init cfg [:arachne/id :test/rt])
rt (component/start rt)
adapter (rt/lookup rt [:arachne/id :test/adapter])]
(chimera/ensure-migrations rt [:arachne/id :test/adapter])
(let [james (UUID/randomUUID)
original-map {:test.person/id <NAME>ames
:test.person/name "<NAME>"
:test.person/dob (Date.)}]
(testing "Testing delete attr"
(chimera/operate adapter :chimera.operation/put original-map)
(chimera/operate adapter :chimera.operation/delete [(chimera/lookup :test.person/id <NAME> <NAME>)
:test.person/name "<NAME>"])
(is (= original-map (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id james))))
(chimera/operate adapter :chimera.operation/delete [(chimera/lookup :test.person/id <NAME> <NAME>)
:test.person/name "<NAME>"])
(is (= (dissoc original-map :test.person/name)
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id <NAME> <NAME>))))
(chimera/operate adapter :chimera.operation/delete [(chimera/lookup :test.person/id <NAME> <NAME>)
:test.person/dob])
(is (= {:test.person/id <NAME> <NAME>}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id j<NAME>)))))
(testing "delete attr cannot delete key attributes"
(is (thrown-with-msg? ArachneException #"Cannot delete key attribute"
(chimera/operate adapter :chimera.operation/delete [(chimera/lookup :test.person/id <NAME> <NAME>)
:test.person/id])
))
))))
(defn exercise-all
[adapter-dsl-fn modules]
(bad-operations adapter-dsl-fn modules)
(simple-crud adapter-dsl-fn modules)
(delete-attributes adapter-dsl-fn modules))
| true | (ns arachne.chimera.test-harness.basics
(:require [arachne.chimera :as chimera]
[arachne.core :as core]
[arachne.core.runtime :as rt]
[arachne.chimera.test-harness.common :as common]
[com.stuartsierra.component :as component]
[clojure.test :as test :refer [testing is]])
(:import [java.util UUID Date]
[arachne ArachneException]))
(defn bad-operations
[adapter-dsl-fn modules]
(let [cfg (core/build-config modules `(common/config 0 ~adapter-dsl-fn))
rt (rt/init cfg [:arachne/id :test/rt])
rt (component/start rt)
adapter (rt/lookup rt [:arachne/id :test/adapter])]
(is (thrown-with-msg? ArachneException #"not supported"
(chimera/operate adapter :no.such/operation [])))
(is (thrown-with-msg? ArachneException #"Unknown dispatch"
(chimera/operate adapter :test.operation/foo [])))
(is (thrown-with-msg? ArachneException #"did not conform "
(chimera/operate adapter :chimera.operation/initialize-migrations false)))))
(defn simple-crud
[adapter-dsl-fn modules]
(let [cfg (core/build-config modules `(common/config 0 ~adapter-dsl-fn))
rt (rt/init cfg [:arachne/id :test/rt])
rt (component/start rt)
adapter (rt/lookup rt [:arachne/id :test/adapter])]
(let [james (UUID/randomUUID)
PI:NAME:<NAME>END_PI (UUID/randomUUID)]
(chimera/ensure-migrations rt [:arachne/id :test/adapter])
(testing "testing basic put/get"
(chimera/operate adapter :chimera.operation/put {:test.person/id james
:test.person/name "PI:NAME:<NAME>END_PI"})
(chimera/operate adapter :chimera.operation/put {:test.person/id PI:NAME:<NAME>END_PI
:test.person/name "PI:NAME:<NAME>END_PI"})
(is (= {:test.person/id PI:NAME:<NAME>END_PI, :test.person/name "PI:NAME:<NAME>END_PI"}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id PI:NAME:<NAME>END_PI))))
(is (= {:test.person/id PI:NAME:<NAME>END_PI, :test.person/name "PI:NAME:<NAME>END_PI"}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI))))
(is (nil? (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id (UUID/randomUUID)))))
(is (thrown-with-msg? ArachneException #"requires a key"
(chimera/operate adapter :chimera.operation/put {:test.person/name "PI:NAME:<NAME>END_PI"}))))
(testing "testing updates"
(let [t1 (java.util.Date.)
t2 (java.util.Date.)]
(chimera/operate adapter :chimera.operation/put {:test.person/id PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI
:test.person/dob t1})
(is (= {:test.person/id PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI,
:test.person/name "PI:NAME:<NAME>END_PI"
:test.person/dob t1}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id jPI:NAME:<NAME>END_PI))))
(is (thrown-with-msg? ArachneException #"requires a key"
(chimera/operate adapter :chimera.operation/put {:test.person/dob t1})))
(chimera/operate adapter :chimera.operation/put {:test.person/id jPI:NAME:<NAME>END_PI
:test.person/name "PI:NAME:<NAME>END_PI"
:test.person/dob t2})
(is (= {:test.person/id jPI:NAME:<NAME>END_PI,
:test.person/name "PI:NAME:<NAME>END_PI"
:test.person/dob t2}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id james))))))
(testing "delete entity"
(chimera/operate adapter :chimera.operation/delete-entity (chimera/lookup :test.person/id PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI))
(is (nil? (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI)))))
(testing "can't set cardinality-many attrs using single value"
(is (thrown-with-msg? ArachneException #"be a set"
(chimera/operate adapter :chimera.operation/put
{:test.person/id PI:NAME:<NAME>END_PI
:test.person/nicknames "M-dog"}))))
(testing "can't set cardinality-one attrs using a set"
(is (thrown-with-msg? ArachneException #"be a single value"
(chimera/operate adapter :chimera.operation/put
{:test.person/id PI:NAME:<NAME>END_PI
:test.person/name #{"PI:NAME:<NAME>END_PI"}}))))
)))
(defn delete-attributes
[adapter-dsl-fn modules]
(let [cfg (core/build-config modules `(common/config 0 ~adapter-dsl-fn))
rt (rt/init cfg [:arachne/id :test/rt])
rt (component/start rt)
adapter (rt/lookup rt [:arachne/id :test/adapter])]
(chimera/ensure-migrations rt [:arachne/id :test/adapter])
(let [james (UUID/randomUUID)
original-map {:test.person/id PI:NAME:<NAME>END_PIames
:test.person/name "PI:NAME:<NAME>END_PI"
:test.person/dob (Date.)}]
(testing "Testing delete attr"
(chimera/operate adapter :chimera.operation/put original-map)
(chimera/operate adapter :chimera.operation/delete [(chimera/lookup :test.person/id PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI)
:test.person/name "PI:NAME:<NAME>END_PI"])
(is (= original-map (chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id james))))
(chimera/operate adapter :chimera.operation/delete [(chimera/lookup :test.person/id PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI)
:test.person/name "PI:NAME:<NAME>END_PI"])
(is (= (dissoc original-map :test.person/name)
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI))))
(chimera/operate adapter :chimera.operation/delete [(chimera/lookup :test.person/id PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI)
:test.person/dob])
(is (= {:test.person/id PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI}
(chimera/operate adapter :chimera.operation/get (chimera/lookup :test.person/id jPI:NAME:<NAME>END_PI)))))
(testing "delete attr cannot delete key attributes"
(is (thrown-with-msg? ArachneException #"Cannot delete key attribute"
(chimera/operate adapter :chimera.operation/delete [(chimera/lookup :test.person/id PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI)
:test.person/id])
))
))))
(defn exercise-all
[adapter-dsl-fn modules]
(bad-operations adapter-dsl-fn modules)
(simple-crud adapter-dsl-fn modules)
(delete-attributes adapter-dsl-fn modules))
|
[
{
"context": "tests for scraping functions\n;;\n;; Copyright 2012, F.M. de Waard & Vixu.com <fmw@vixu.com>.\n;;\n;; Licensed under t",
"end": 95,
"score": 0.9998595714569092,
"start": 82,
"tag": "NAME",
"value": "F.M. de Waard"
},
{
"context": "s\n;;\n;; Copyright 2012, F.M. de Waard & Vixu.com <fmw@vixu.com>.\n;;\n;; Licensed under the Apache License, Versio",
"end": 120,
"score": 0.9999327659606934,
"start": 108,
"tag": "EMAIL",
"value": "fmw@vixu.com"
},
{
"context": " [\"Heirloom Collection: Westminster\"\n \"G. L. Pease\"\n \"Gregory L. Pease\"\n \"Virg",
"end": 7064,
"score": 0.8620285987854004,
"start": 7053,
"tag": "NAME",
"value": "G. L. Pease"
},
{
"context": "stminster\"\n \"G. L. Pease\"\n \"Gregory L. Pease\"\n \"Virginia, Latakia and Oriental\"\n ",
"end": 7095,
"score": 0.9782269597053528,
"start": 7079,
"tag": "NAME",
"value": "Gregory L. Pease"
}
] | test/alida/test/scrape.clj | fmw/alida | 6 | ;; test/alida/test/scrape.clj: tests for scraping 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.test.scrape
(:use [clojure.test]
[clj-http.fake]
[alida.test.helpers :only [with-test-db +test-db+ dummy-routes]]
[alida.scrape] :reload)
(:require [net.cgrand.enlive-html :as enlive]
[alida.crawl :as crawl]
[alida.util :as util]
[alida.db :as db]
[clojure.pprint])
(:import [java.io StringReader]))
(deftest test-content-type-is-html?
(is (content-type-is-html?
{:headers {"content-type" "text/html;charset=UTF-8"}}))
(is (false? (content-type-is-html?
{:headers {"content-type" "text/plain;charset=UTF-8"}}))))
(deftest test-get-links-enlive
(let [html (slurp "resources/test-data/dummy-shop/whisky.html")]
(is (= (get-links-enlive "http://www.dummyhealthfoodstore.com/index.html"
html
[:a])
#{"http://www.dummyhealthfoodstore.com/clynelish.html"
"http://www.dummyhealthfoodstore.com/en/About.html"
"http://www.dummyhealthfoodstore.com/products/pipe-tobacco.html"
"http://www.dummyhealthfoodstore.com/ardbeg.html"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com/nl"
"http://www.dummyhealthfoodstore.com/"
"http://www.dummyhealthfoodstore.com/en/Contact.html"
"http://www.dummyhealthfoodstore.com/products/whisky.html"
"http://www.dummyhealthfoodstore.com/port-ellen.html"
"http://www.dummyhealthfoodstore.com/macallan.html"}))))
(deftest test-get-links-jsoup
(let [html (slurp "resources/test-data/dummy-shop/whisky.html")]
(is (= (get-links-jsoup "http://www.dummyhealthfoodstore.com/index.html"
html)
#{"http://www.dummyhealthfoodstore.com/clynelish.html"
"http://www.dummyhealthfoodstore.com/en/About.html"
"http://www.dummyhealthfoodstore.com/products/pipe-tobacco.html"
"http://www.dummyhealthfoodstore.com/ardbeg.html"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com/nl"
"http://www.dummyhealthfoodstore.com/"
"http://www.dummyhealthfoodstore.com/en/Contact.html"
"http://www.dummyhealthfoodstore.com/products/whisky.html"
"http://www.dummyhealthfoodstore.com/port-ellen.html"
"http://www.dummyhealthfoodstore.com/macallan.html"}))))
(deftest test-get-links
(let [html (slurp "resources/test-data/dummy-shop/whisky.html")
index-html (slurp "resources/test-data/dummy-shop/index.html")]
(is (= (get-links "http://www.dummyhealthfoodstore.com/" html [:a])
(get-links "http://www.dummyhealthfoodstore.com/" html [:a] nil)
#{"http://www.dummyhealthfoodstore.com/clynelish.html"
"http://www.dummyhealthfoodstore.com/en/About.html"
"http://www.dummyhealthfoodstore.com/products/pipe-tobacco.html"
"http://www.dummyhealthfoodstore.com/ardbeg.html"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com/nl"
"http://www.dummyhealthfoodstore.com/"
"http://www.dummyhealthfoodstore.com/en/Contact.html"
"http://www.dummyhealthfoodstore.com/products/whisky.html"
"http://www.dummyhealthfoodstore.com/port-ellen.html"
"http://www.dummyhealthfoodstore.com/macallan.html"}))
(is (= (get-links "http://www.dummyhealthfoodstore.com/"
html
[:a]
{:path-filter #"^/products.+"})
["http://www.dummyhealthfoodstore.com/products/pipe-tobacco.html"
"http://www.dummyhealthfoodstore.com/products/whisky.html"]))
(is (= (get-links "http://www.dummyhealthfoodstore.com/"
index-html
[:a])
#{"http://www.vixu.com/"
"http://www.dummyhealthfoodstore.com/en/Contact.html"
"http://www.dummyhealthfoodstore.com/products/pipe-tobacco.html"
"http://www.dummyhealthfoodstore.com/nl"
"http://www.dummyhealthfoodstore.com/"
"http://www.dummyhealthfoodstore.com/products/whisky.html"
"http://www.dummyhealthfoodstore.com/en/About.html"}))
(is (= (get-links "http://www.dummyhealthfoodstore.com/"
index-html
[:a]
{:filter #"http://www.vixu.com.*"})
(get-links "http://www.dummyhealthfoodstore.com/"
index-html
[:a]
{:filter #"http://www.vixu.com.*"
:path-filter #"/"})
["http://www.vixu.com/"]))
(is (= (get-links "http://www.dummyhealthfoodstore.com/"
index-html
[:a]
{:path-filter #"/"})
["http://www.vixu.com/"
"http://www.dummyhealthfoodstore.com/"]))))
(deftest test-html-to-plaintext
(is (= (html-to-plaintext
(slurp "resources/test-data/dummy-shop/index.html"))
(str "Dummy Shop Dummy Shop Search Nederlands "
"Home Whisky Pipe Tobacco About Contact "
"Welcome to the Dummy Health Food Store! "
"This health food dummy store only sells whisky "
"and pipe tobacco! "
"Powered by Vixu.com "
"© 2012, Dummy Store Incorporated. All rights reserved."))))
(deftest test-get-trimmed-content
(let [html (slurp "resources/test-data/dummy-shop/glp-westminster.html")
resource (enlive/html-resource (StringReader. html))]
(is (= (get-trimmed-content html [:#description])
(get-trimmed-content resource [:#description])
"Flavorful English mixture with a healthy dose of Latakia."))
(is (= (get-trimmed-content html [[:#content]
[:div]
[:span (enlive/nth-of-type 2)]])
(get-trimmed-content resource [[:#content]
[:div]
[:span (enlive/nth-of-type 2)]])
["Heirloom Collection: Westminster"
"G. L. Pease"
"Gregory L. Pease"
"Virginia, Latakia and Oriental"
"Ribbon"]))))
(deftest test-extract-and-store-data
(with-test-db
(with-redefs [util/make-timestamp #(str "2012-05-19T22:08:56.250Z")]
(do
(db/create-views +test-db+)
(with-fake-routes dummy-routes
(db/add-batched-documents
+test-db+
@(crawl/directed-crawl
"extract-and-store-data-test"
"2012-05-19T22:08:56.250Z"
0
"http://www.dummyhealthfoodstore.com/index.html"
[{:selector [:ul#menu :a]
:path-filter #"^/products.+"
:next [{:selector [[:div#content] [:a]]}]}]))))
(is (nil? (extract-and-store-data
+test-db+
"extract-and-store-data-test"
"2012-05-19T22:08:56.250Z"
(fn [raw-page]
{:page-title
(first
(:content
(first (enlive/select
(enlive/html-resource
(StringReader. (:body raw-page)))
[:title]))))
:fulltext
(html-to-plaintext (:body raw-page))})
3)))
(is (= (map #(dissoc % :fulltext :_id :_rev)
(:documents
(db/get-scrape-results +test-db+
"extract-and-store-data-test"
"2012-05-19T22:08:56.250Z"
1000)))
[{:crawled-at "2012-05-19T22:08:56.250Z",
:uri (str "http://www.dummyhealthfoodstore.com/"
"products/whisky.html"),
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: whisky overview"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri (str "http://www.dummyhealthfoodstore.com/"
"products/pipe-tobacco.html"),
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: pipe tobacco overview"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri "http://www.dummyhealthfoodstore.com/port-ellen.html",
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: Port Ellen 30yo"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri "http://www.dummyhealthfoodstore.com/navy-rolls.html",
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: Dunhill De Luxe Navy Rolls"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri "http://www.dummyhealthfoodstore.com/macallan.html",
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: Macallan 30yo"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri (str "http://www.dummyhealthfoodstore.com"
"/london-mixture.html"),
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: Dunhill London Mixture"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri "http://www.dummyhealthfoodstore.com/index.html",
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri (str "http://www.dummyhealthfoodstore.com"
"/glp-westminster.html"),
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: GLP Westminster"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri "http://www.dummyhealthfoodstore.com/glp-meridian.html",
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: GLP Meridian"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri "http://www.dummyhealthfoodstore.com/clynelish.html",
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: Clynelish 30yo"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri "http://www.dummyhealthfoodstore.com/brora.html",
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: Brora 30yo"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri (str "http://www.dummyhealthfoodstore.com"
"/blackwoods-flake.html"),
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: McClelland Blackwoods Flake"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri "http://www.dummyhealthfoodstore.com/ardbeg.html",
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: Ardbeg 10yo"}]))))) | 53775 | ;; test/alida/test/scrape.clj: tests for scraping 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.test.scrape
(:use [clojure.test]
[clj-http.fake]
[alida.test.helpers :only [with-test-db +test-db+ dummy-routes]]
[alida.scrape] :reload)
(:require [net.cgrand.enlive-html :as enlive]
[alida.crawl :as crawl]
[alida.util :as util]
[alida.db :as db]
[clojure.pprint])
(:import [java.io StringReader]))
(deftest test-content-type-is-html?
(is (content-type-is-html?
{:headers {"content-type" "text/html;charset=UTF-8"}}))
(is (false? (content-type-is-html?
{:headers {"content-type" "text/plain;charset=UTF-8"}}))))
(deftest test-get-links-enlive
(let [html (slurp "resources/test-data/dummy-shop/whisky.html")]
(is (= (get-links-enlive "http://www.dummyhealthfoodstore.com/index.html"
html
[:a])
#{"http://www.dummyhealthfoodstore.com/clynelish.html"
"http://www.dummyhealthfoodstore.com/en/About.html"
"http://www.dummyhealthfoodstore.com/products/pipe-tobacco.html"
"http://www.dummyhealthfoodstore.com/ardbeg.html"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com/nl"
"http://www.dummyhealthfoodstore.com/"
"http://www.dummyhealthfoodstore.com/en/Contact.html"
"http://www.dummyhealthfoodstore.com/products/whisky.html"
"http://www.dummyhealthfoodstore.com/port-ellen.html"
"http://www.dummyhealthfoodstore.com/macallan.html"}))))
(deftest test-get-links-jsoup
(let [html (slurp "resources/test-data/dummy-shop/whisky.html")]
(is (= (get-links-jsoup "http://www.dummyhealthfoodstore.com/index.html"
html)
#{"http://www.dummyhealthfoodstore.com/clynelish.html"
"http://www.dummyhealthfoodstore.com/en/About.html"
"http://www.dummyhealthfoodstore.com/products/pipe-tobacco.html"
"http://www.dummyhealthfoodstore.com/ardbeg.html"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com/nl"
"http://www.dummyhealthfoodstore.com/"
"http://www.dummyhealthfoodstore.com/en/Contact.html"
"http://www.dummyhealthfoodstore.com/products/whisky.html"
"http://www.dummyhealthfoodstore.com/port-ellen.html"
"http://www.dummyhealthfoodstore.com/macallan.html"}))))
(deftest test-get-links
(let [html (slurp "resources/test-data/dummy-shop/whisky.html")
index-html (slurp "resources/test-data/dummy-shop/index.html")]
(is (= (get-links "http://www.dummyhealthfoodstore.com/" html [:a])
(get-links "http://www.dummyhealthfoodstore.com/" html [:a] nil)
#{"http://www.dummyhealthfoodstore.com/clynelish.html"
"http://www.dummyhealthfoodstore.com/en/About.html"
"http://www.dummyhealthfoodstore.com/products/pipe-tobacco.html"
"http://www.dummyhealthfoodstore.com/ardbeg.html"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com/nl"
"http://www.dummyhealthfoodstore.com/"
"http://www.dummyhealthfoodstore.com/en/Contact.html"
"http://www.dummyhealthfoodstore.com/products/whisky.html"
"http://www.dummyhealthfoodstore.com/port-ellen.html"
"http://www.dummyhealthfoodstore.com/macallan.html"}))
(is (= (get-links "http://www.dummyhealthfoodstore.com/"
html
[:a]
{:path-filter #"^/products.+"})
["http://www.dummyhealthfoodstore.com/products/pipe-tobacco.html"
"http://www.dummyhealthfoodstore.com/products/whisky.html"]))
(is (= (get-links "http://www.dummyhealthfoodstore.com/"
index-html
[:a])
#{"http://www.vixu.com/"
"http://www.dummyhealthfoodstore.com/en/Contact.html"
"http://www.dummyhealthfoodstore.com/products/pipe-tobacco.html"
"http://www.dummyhealthfoodstore.com/nl"
"http://www.dummyhealthfoodstore.com/"
"http://www.dummyhealthfoodstore.com/products/whisky.html"
"http://www.dummyhealthfoodstore.com/en/About.html"}))
(is (= (get-links "http://www.dummyhealthfoodstore.com/"
index-html
[:a]
{:filter #"http://www.vixu.com.*"})
(get-links "http://www.dummyhealthfoodstore.com/"
index-html
[:a]
{:filter #"http://www.vixu.com.*"
:path-filter #"/"})
["http://www.vixu.com/"]))
(is (= (get-links "http://www.dummyhealthfoodstore.com/"
index-html
[:a]
{:path-filter #"/"})
["http://www.vixu.com/"
"http://www.dummyhealthfoodstore.com/"]))))
(deftest test-html-to-plaintext
(is (= (html-to-plaintext
(slurp "resources/test-data/dummy-shop/index.html"))
(str "Dummy Shop Dummy Shop Search Nederlands "
"Home Whisky Pipe Tobacco About Contact "
"Welcome to the Dummy Health Food Store! "
"This health food dummy store only sells whisky "
"and pipe tobacco! "
"Powered by Vixu.com "
"© 2012, Dummy Store Incorporated. All rights reserved."))))
(deftest test-get-trimmed-content
(let [html (slurp "resources/test-data/dummy-shop/glp-westminster.html")
resource (enlive/html-resource (StringReader. html))]
(is (= (get-trimmed-content html [:#description])
(get-trimmed-content resource [:#description])
"Flavorful English mixture with a healthy dose of Latakia."))
(is (= (get-trimmed-content html [[:#content]
[:div]
[:span (enlive/nth-of-type 2)]])
(get-trimmed-content resource [[:#content]
[:div]
[:span (enlive/nth-of-type 2)]])
["Heirloom Collection: Westminster"
"<NAME>"
"<NAME>"
"Virginia, Latakia and Oriental"
"Ribbon"]))))
(deftest test-extract-and-store-data
(with-test-db
(with-redefs [util/make-timestamp #(str "2012-05-19T22:08:56.250Z")]
(do
(db/create-views +test-db+)
(with-fake-routes dummy-routes
(db/add-batched-documents
+test-db+
@(crawl/directed-crawl
"extract-and-store-data-test"
"2012-05-19T22:08:56.250Z"
0
"http://www.dummyhealthfoodstore.com/index.html"
[{:selector [:ul#menu :a]
:path-filter #"^/products.+"
:next [{:selector [[:div#content] [:a]]}]}]))))
(is (nil? (extract-and-store-data
+test-db+
"extract-and-store-data-test"
"2012-05-19T22:08:56.250Z"
(fn [raw-page]
{:page-title
(first
(:content
(first (enlive/select
(enlive/html-resource
(StringReader. (:body raw-page)))
[:title]))))
:fulltext
(html-to-plaintext (:body raw-page))})
3)))
(is (= (map #(dissoc % :fulltext :_id :_rev)
(:documents
(db/get-scrape-results +test-db+
"extract-and-store-data-test"
"2012-05-19T22:08:56.250Z"
1000)))
[{:crawled-at "2012-05-19T22:08:56.250Z",
:uri (str "http://www.dummyhealthfoodstore.com/"
"products/whisky.html"),
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: whisky overview"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri (str "http://www.dummyhealthfoodstore.com/"
"products/pipe-tobacco.html"),
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: pipe tobacco overview"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri "http://www.dummyhealthfoodstore.com/port-ellen.html",
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: Port Ellen 30yo"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri "http://www.dummyhealthfoodstore.com/navy-rolls.html",
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: Dunhill De Luxe Navy Rolls"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri "http://www.dummyhealthfoodstore.com/macallan.html",
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: Macallan 30yo"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri (str "http://www.dummyhealthfoodstore.com"
"/london-mixture.html"),
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: Dunhill London Mixture"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri "http://www.dummyhealthfoodstore.com/index.html",
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri (str "http://www.dummyhealthfoodstore.com"
"/glp-westminster.html"),
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: GLP Westminster"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri "http://www.dummyhealthfoodstore.com/glp-meridian.html",
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: GLP Meridian"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri "http://www.dummyhealthfoodstore.com/clynelish.html",
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: Clynelish 30yo"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri "http://www.dummyhealthfoodstore.com/brora.html",
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: Brora 30yo"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri (str "http://www.dummyhealthfoodstore.com"
"/blackwoods-flake.html"),
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: McClelland Blackwoods Flake"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri "http://www.dummyhealthfoodstore.com/ardbeg.html",
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: Ardbeg 10yo"}]))))) | true | ;; test/alida/test/scrape.clj: tests for scraping 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.test.scrape
(:use [clojure.test]
[clj-http.fake]
[alida.test.helpers :only [with-test-db +test-db+ dummy-routes]]
[alida.scrape] :reload)
(:require [net.cgrand.enlive-html :as enlive]
[alida.crawl :as crawl]
[alida.util :as util]
[alida.db :as db]
[clojure.pprint])
(:import [java.io StringReader]))
(deftest test-content-type-is-html?
(is (content-type-is-html?
{:headers {"content-type" "text/html;charset=UTF-8"}}))
(is (false? (content-type-is-html?
{:headers {"content-type" "text/plain;charset=UTF-8"}}))))
(deftest test-get-links-enlive
(let [html (slurp "resources/test-data/dummy-shop/whisky.html")]
(is (= (get-links-enlive "http://www.dummyhealthfoodstore.com/index.html"
html
[:a])
#{"http://www.dummyhealthfoodstore.com/clynelish.html"
"http://www.dummyhealthfoodstore.com/en/About.html"
"http://www.dummyhealthfoodstore.com/products/pipe-tobacco.html"
"http://www.dummyhealthfoodstore.com/ardbeg.html"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com/nl"
"http://www.dummyhealthfoodstore.com/"
"http://www.dummyhealthfoodstore.com/en/Contact.html"
"http://www.dummyhealthfoodstore.com/products/whisky.html"
"http://www.dummyhealthfoodstore.com/port-ellen.html"
"http://www.dummyhealthfoodstore.com/macallan.html"}))))
(deftest test-get-links-jsoup
(let [html (slurp "resources/test-data/dummy-shop/whisky.html")]
(is (= (get-links-jsoup "http://www.dummyhealthfoodstore.com/index.html"
html)
#{"http://www.dummyhealthfoodstore.com/clynelish.html"
"http://www.dummyhealthfoodstore.com/en/About.html"
"http://www.dummyhealthfoodstore.com/products/pipe-tobacco.html"
"http://www.dummyhealthfoodstore.com/ardbeg.html"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com/nl"
"http://www.dummyhealthfoodstore.com/"
"http://www.dummyhealthfoodstore.com/en/Contact.html"
"http://www.dummyhealthfoodstore.com/products/whisky.html"
"http://www.dummyhealthfoodstore.com/port-ellen.html"
"http://www.dummyhealthfoodstore.com/macallan.html"}))))
(deftest test-get-links
(let [html (slurp "resources/test-data/dummy-shop/whisky.html")
index-html (slurp "resources/test-data/dummy-shop/index.html")]
(is (= (get-links "http://www.dummyhealthfoodstore.com/" html [:a])
(get-links "http://www.dummyhealthfoodstore.com/" html [:a] nil)
#{"http://www.dummyhealthfoodstore.com/clynelish.html"
"http://www.dummyhealthfoodstore.com/en/About.html"
"http://www.dummyhealthfoodstore.com/products/pipe-tobacco.html"
"http://www.dummyhealthfoodstore.com/ardbeg.html"
"http://www.dummyhealthfoodstore.com/brora.html"
"http://www.dummyhealthfoodstore.com/nl"
"http://www.dummyhealthfoodstore.com/"
"http://www.dummyhealthfoodstore.com/en/Contact.html"
"http://www.dummyhealthfoodstore.com/products/whisky.html"
"http://www.dummyhealthfoodstore.com/port-ellen.html"
"http://www.dummyhealthfoodstore.com/macallan.html"}))
(is (= (get-links "http://www.dummyhealthfoodstore.com/"
html
[:a]
{:path-filter #"^/products.+"})
["http://www.dummyhealthfoodstore.com/products/pipe-tobacco.html"
"http://www.dummyhealthfoodstore.com/products/whisky.html"]))
(is (= (get-links "http://www.dummyhealthfoodstore.com/"
index-html
[:a])
#{"http://www.vixu.com/"
"http://www.dummyhealthfoodstore.com/en/Contact.html"
"http://www.dummyhealthfoodstore.com/products/pipe-tobacco.html"
"http://www.dummyhealthfoodstore.com/nl"
"http://www.dummyhealthfoodstore.com/"
"http://www.dummyhealthfoodstore.com/products/whisky.html"
"http://www.dummyhealthfoodstore.com/en/About.html"}))
(is (= (get-links "http://www.dummyhealthfoodstore.com/"
index-html
[:a]
{:filter #"http://www.vixu.com.*"})
(get-links "http://www.dummyhealthfoodstore.com/"
index-html
[:a]
{:filter #"http://www.vixu.com.*"
:path-filter #"/"})
["http://www.vixu.com/"]))
(is (= (get-links "http://www.dummyhealthfoodstore.com/"
index-html
[:a]
{:path-filter #"/"})
["http://www.vixu.com/"
"http://www.dummyhealthfoodstore.com/"]))))
(deftest test-html-to-plaintext
(is (= (html-to-plaintext
(slurp "resources/test-data/dummy-shop/index.html"))
(str "Dummy Shop Dummy Shop Search Nederlands "
"Home Whisky Pipe Tobacco About Contact "
"Welcome to the Dummy Health Food Store! "
"This health food dummy store only sells whisky "
"and pipe tobacco! "
"Powered by Vixu.com "
"© 2012, Dummy Store Incorporated. All rights reserved."))))
(deftest test-get-trimmed-content
(let [html (slurp "resources/test-data/dummy-shop/glp-westminster.html")
resource (enlive/html-resource (StringReader. html))]
(is (= (get-trimmed-content html [:#description])
(get-trimmed-content resource [:#description])
"Flavorful English mixture with a healthy dose of Latakia."))
(is (= (get-trimmed-content html [[:#content]
[:div]
[:span (enlive/nth-of-type 2)]])
(get-trimmed-content resource [[:#content]
[:div]
[:span (enlive/nth-of-type 2)]])
["Heirloom Collection: Westminster"
"PI:NAME:<NAME>END_PI"
"PI:NAME:<NAME>END_PI"
"Virginia, Latakia and Oriental"
"Ribbon"]))))
(deftest test-extract-and-store-data
(with-test-db
(with-redefs [util/make-timestamp #(str "2012-05-19T22:08:56.250Z")]
(do
(db/create-views +test-db+)
(with-fake-routes dummy-routes
(db/add-batched-documents
+test-db+
@(crawl/directed-crawl
"extract-and-store-data-test"
"2012-05-19T22:08:56.250Z"
0
"http://www.dummyhealthfoodstore.com/index.html"
[{:selector [:ul#menu :a]
:path-filter #"^/products.+"
:next [{:selector [[:div#content] [:a]]}]}]))))
(is (nil? (extract-and-store-data
+test-db+
"extract-and-store-data-test"
"2012-05-19T22:08:56.250Z"
(fn [raw-page]
{:page-title
(first
(:content
(first (enlive/select
(enlive/html-resource
(StringReader. (:body raw-page)))
[:title]))))
:fulltext
(html-to-plaintext (:body raw-page))})
3)))
(is (= (map #(dissoc % :fulltext :_id :_rev)
(:documents
(db/get-scrape-results +test-db+
"extract-and-store-data-test"
"2012-05-19T22:08:56.250Z"
1000)))
[{:crawled-at "2012-05-19T22:08:56.250Z",
:uri (str "http://www.dummyhealthfoodstore.com/"
"products/whisky.html"),
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: whisky overview"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri (str "http://www.dummyhealthfoodstore.com/"
"products/pipe-tobacco.html"),
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: pipe tobacco overview"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri "http://www.dummyhealthfoodstore.com/port-ellen.html",
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: Port Ellen 30yo"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri "http://www.dummyhealthfoodstore.com/navy-rolls.html",
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: Dunhill De Luxe Navy Rolls"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri "http://www.dummyhealthfoodstore.com/macallan.html",
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: Macallan 30yo"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri (str "http://www.dummyhealthfoodstore.com"
"/london-mixture.html"),
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: Dunhill London Mixture"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri "http://www.dummyhealthfoodstore.com/index.html",
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri (str "http://www.dummyhealthfoodstore.com"
"/glp-westminster.html"),
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: GLP Westminster"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri "http://www.dummyhealthfoodstore.com/glp-meridian.html",
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: GLP Meridian"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri "http://www.dummyhealthfoodstore.com/clynelish.html",
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: Clynelish 30yo"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri "http://www.dummyhealthfoodstore.com/brora.html",
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: Brora 30yo"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri (str "http://www.dummyhealthfoodstore.com"
"/blackwoods-flake.html"),
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: McClelland Blackwoods Flake"}
{:crawled-at "2012-05-19T22:08:56.250Z",
:uri "http://www.dummyhealthfoodstore.com/ardbeg.html",
:type "scrape-result",
:crawl-tag "extract-and-store-data-test",
:crawl-timestamp "2012-05-19T22:08:56.250Z",
:page-title "Dummy Shop: Ardbeg 10yo"}]))))) |
[
{
"context": " :person.firstName\n [[1 \"Eleni\"]\n [2 \"Kostas\"]]\n\n ",
"end": 153,
"score": 0.9998473525047302,
"start": 148,
"tag": "NAME",
"value": "Eleni"
},
{
"context": " [[1 \"Eleni\"]\n [2 \"Kostas\"]]\n\n :person.lastName\n ",
"end": 183,
"score": 0.9998164176940918,
"start": 177,
"tag": "NAME",
"value": "Kostas"
},
{
"context": " :person.lastName\n [[1 \"Papadopoulou\"]\n [2 \"Georgiou\"]]\n\n ",
"end": 254,
"score": 0.9996039271354675,
"start": 242,
"tag": "NAME",
"value": "Papadopoulou"
},
{
"context": " [[1 \"Papadopoulou\"]\n [2 \"Georgiou\"]]\n\n :person.address\n ",
"end": 286,
"score": 0.9988608360290527,
"start": 278,
"tag": "NAME",
"value": "Georgiou"
},
{
"context": " ?lastName))\n\n;;[person firstName lastName]\n;;1 \"Eleni\" \"Papadopoulou\"\n;;2 \"Kostas\" \"Georgiou\"\n\n;;But ad",
"end": 846,
"score": 0.9997944235801697,
"start": 841,
"tag": "NAME",
"value": "Eleni"
},
{
"context": "ame))\n\n;;[person firstName lastName]\n;;1 \"Eleni\" \"Papadopoulou\"\n;;2 \"Kostas\" \"Georgiou\"\n\n;;But address has only ",
"end": 861,
"score": 0.9990549683570862,
"start": 849,
"tag": "NAME",
"value": "Papadopoulou"
},
{
"context": "rstName lastName]\n;;1 \"Eleni\" \"Papadopoulou\"\n;;2 \"Kostas\" \"Georgiou\"\n\n;;But address has only eleni\n#_(q {:",
"end": 874,
"score": 0.9991011619567871,
"start": 868,
"tag": "NAME",
"value": "Kostas"
},
{
"context": "astName]\n;;1 \"Eleni\" \"Papadopoulou\"\n;;2 \"Kostas\" \"Georgiou\"\n\n;;But address has only eleni\n#_(q {:q-in [relat",
"end": 885,
"score": 0.9928833842277527,
"start": 877,
"tag": "NAME",
"value": "Georgiou"
},
{
"context": "s))\n\n;;[person address firstName lastName]\n;;1 1 \"Eleni\" \"Papadopoulou\"\n\n;;Lets see the complete data\n#_(",
"end": 1144,
"score": 0.9997594356536865,
"start": 1139,
"tag": "NAME",
"value": "Eleni"
},
{
"context": "person address firstName lastName]\n;;1 1 \"Eleni\" \"Papadopoulou\"\n\n;;Lets see the complete data\n#_(q {:q-in [relat",
"end": 1159,
"score": 0.9967570900917053,
"start": 1147,
"tag": "NAME",
"value": "Papadopoulou"
},
{
"context": "lastName postalCode city streetAddress region]\n;;\"Eleni\" \"Papadopoulou\" \"17562\" \"ATHENS\" \"Ahilleos\" \"Atti",
"end": 1680,
"score": 0.9997761249542236,
"start": 1675,
"tag": "NAME",
"value": "Eleni"
},
{
"context": " postalCode city streetAddress region]\n;;\"Eleni\" \"Papadopoulou\" \"17562\" \"ATHENS\" \"Ahilleos\" \"Attika\"\n\n\n;;Summary",
"end": 1695,
"score": 0.9828792214393616,
"start": 1683,
"tag": "NAME",
"value": "Papadopoulou"
},
{
"context": "leni\" \"Papadopoulou\" \"17562\" \"ATHENS\" \"Ahilleos\" \"Attika\"\n\n\n;;Summary\n;;Here the joins are made in a ch",
"end": 1729,
"score": 0.6131255626678467,
"start": 1726,
"tag": "NAME",
"value": "Att"
}
] | test/documentation/address.clj | tkaryadis/louna-local | 0 | (ns documentation.address
(:use louna.louna
louna.louna-util))
#_(def relations {
:person.firstName
[[1 "Eleni"]
[2 "Kostas"]]
:person.lastName
[[1 "Papadopoulou"]
[2 "Georgiou"]]
:person.address
[[1 1]]
:address.postalCode
[[1 "17562"]]
:address.city
[[1 "ATHENS"]]
:address.streetAddress
[[1 "Ahilleos"]]
:address.region
[[1 "Attika"]]
})
;;Both of them have firstname+lastname
#_(q {:q-in [relations] :q-out ["print"]}
(:person.firstName ?person ?firstName)
(:person.lastName ?lastName))
;;[person firstName lastName]
;;1 "Eleni" "Papadopoulou"
;;2 "Kostas" "Georgiou"
;;But address has only eleni
#_(q {:q-in [relations] :q-out ["print"]}
(:person.firstName ?person ?firstName)
(:person.lastName ?lastName)
(:person.address ?address))
;;[person address firstName lastName]
;;1 1 "Eleni" "Papadopoulou"
;;Lets see the complete data
#_(q {:q-in [relations] :q-out ["print"]}
[?firstName ?lastName ?postalCode ?city ?streetAddress ?region]
(:person.firstName ?person ?firstName)
(:person.lastName ?lastName)
(:person.address ?address)
(:address.postalCode ?address ?postalCode)
(:address.city ?city)
(:address.streetAddress ?streetAddress)
(:address.region ?region))
;;[firstName lastName postalCode city streetAddress region]
;;"Eleni" "Papadopoulou" "17562" "ATHENS" "Ahilleos" "Attika"
;;Summary
;;Here the joins are made in a chain also(addrees is object)
;;The s-expressions make it easier to read and see the join variables
;;because you ignore the relation,and you read key-value pairs
| 91463 | (ns documentation.address
(:use louna.louna
louna.louna-util))
#_(def relations {
:person.firstName
[[1 "<NAME>"]
[2 "<NAME>"]]
:person.lastName
[[1 "<NAME>"]
[2 "<NAME>"]]
:person.address
[[1 1]]
:address.postalCode
[[1 "17562"]]
:address.city
[[1 "ATHENS"]]
:address.streetAddress
[[1 "Ahilleos"]]
:address.region
[[1 "Attika"]]
})
;;Both of them have firstname+lastname
#_(q {:q-in [relations] :q-out ["print"]}
(:person.firstName ?person ?firstName)
(:person.lastName ?lastName))
;;[person firstName lastName]
;;1 "<NAME>" "<NAME>"
;;2 "<NAME>" "<NAME>"
;;But address has only eleni
#_(q {:q-in [relations] :q-out ["print"]}
(:person.firstName ?person ?firstName)
(:person.lastName ?lastName)
(:person.address ?address))
;;[person address firstName lastName]
;;1 1 "<NAME>" "<NAME>"
;;Lets see the complete data
#_(q {:q-in [relations] :q-out ["print"]}
[?firstName ?lastName ?postalCode ?city ?streetAddress ?region]
(:person.firstName ?person ?firstName)
(:person.lastName ?lastName)
(:person.address ?address)
(:address.postalCode ?address ?postalCode)
(:address.city ?city)
(:address.streetAddress ?streetAddress)
(:address.region ?region))
;;[firstName lastName postalCode city streetAddress region]
;;"<NAME>" "<NAME>" "17562" "ATHENS" "Ahilleos" "<NAME>ika"
;;Summary
;;Here the joins are made in a chain also(addrees is object)
;;The s-expressions make it easier to read and see the join variables
;;because you ignore the relation,and you read key-value pairs
| true | (ns documentation.address
(:use louna.louna
louna.louna-util))
#_(def relations {
:person.firstName
[[1 "PI:NAME:<NAME>END_PI"]
[2 "PI:NAME:<NAME>END_PI"]]
:person.lastName
[[1 "PI:NAME:<NAME>END_PI"]
[2 "PI:NAME:<NAME>END_PI"]]
:person.address
[[1 1]]
:address.postalCode
[[1 "17562"]]
:address.city
[[1 "ATHENS"]]
:address.streetAddress
[[1 "Ahilleos"]]
:address.region
[[1 "Attika"]]
})
;;Both of them have firstname+lastname
#_(q {:q-in [relations] :q-out ["print"]}
(:person.firstName ?person ?firstName)
(:person.lastName ?lastName))
;;[person firstName lastName]
;;1 "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"
;;2 "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"
;;But address has only eleni
#_(q {:q-in [relations] :q-out ["print"]}
(:person.firstName ?person ?firstName)
(:person.lastName ?lastName)
(:person.address ?address))
;;[person address firstName lastName]
;;1 1 "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"
;;Lets see the complete data
#_(q {:q-in [relations] :q-out ["print"]}
[?firstName ?lastName ?postalCode ?city ?streetAddress ?region]
(:person.firstName ?person ?firstName)
(:person.lastName ?lastName)
(:person.address ?address)
(:address.postalCode ?address ?postalCode)
(:address.city ?city)
(:address.streetAddress ?streetAddress)
(:address.region ?region))
;;[firstName lastName postalCode city streetAddress region]
;;"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "17562" "ATHENS" "Ahilleos" "PI:NAME:<NAME>END_PIika"
;;Summary
;;Here the joins are made in a chain also(addrees is object)
;;The s-expressions make it easier to read and see the join variables
;;because you ignore the relation,and you read key-value pairs
|
[
{
"context": "\n(ns ^{:author \"Chas Emerick\"}\n clojure.tools.nrepl.middleware.pr-values\n ",
"end": 28,
"score": 0.9998884201049805,
"start": 16,
"tag": "NAME",
"value": "Chas Emerick"
}
] | clojure/tools/nrepl/middleware/pr_values.clj | prapisarda/Scripts | 0 |
(ns ^{:author "Chas Emerick"}
clojure.tools.nrepl.middleware.pr-values
(:require [clojure.tools.nrepl.transport :as t])
(:use [clojure.tools.nrepl.middleware :only (set-descriptor!)])
(:import clojure.tools.nrepl.transport.Transport))
(defn pr-values
"Middleware that returns a handler which transforms any :value slots
in messages sent via the request's Transport to strings via `pr`,
delegating all actual message handling to the provided handler.
Requires that results of eval operations are sent in messages in a
:value slot.
If :value is already a string, and a sent message's :printed-value
slot contains any truthy value, then :value will not be re-printed.
This allows evaluation contexts to produce printed results in :value
if they so choose, and opt out of the printing here."
[h]
(fn [{:keys [op ^Transport transport] :as msg}]
(h (assoc msg
:transport (reify Transport
(recv [this] (.recv transport))
(recv [this timeout] (.recv transport timeout))
(send [this {:keys [printed-value value] :as resp}]
(.send transport
(if (and printed-value (string? value))
(dissoc resp :printed-value)
(if-let [[_ v] (find resp :value)]
(assoc resp
:value (let [repr (java.io.StringWriter.)]
(if *print-dup*
(print-dup v repr)
(print-method v repr))
(str repr)))
resp)))
this))))))
(set-descriptor! #'pr-values
{:requires #{}
:expects #{}
:handles {}})
| 69975 |
(ns ^{:author "<NAME>"}
clojure.tools.nrepl.middleware.pr-values
(:require [clojure.tools.nrepl.transport :as t])
(:use [clojure.tools.nrepl.middleware :only (set-descriptor!)])
(:import clojure.tools.nrepl.transport.Transport))
(defn pr-values
"Middleware that returns a handler which transforms any :value slots
in messages sent via the request's Transport to strings via `pr`,
delegating all actual message handling to the provided handler.
Requires that results of eval operations are sent in messages in a
:value slot.
If :value is already a string, and a sent message's :printed-value
slot contains any truthy value, then :value will not be re-printed.
This allows evaluation contexts to produce printed results in :value
if they so choose, and opt out of the printing here."
[h]
(fn [{:keys [op ^Transport transport] :as msg}]
(h (assoc msg
:transport (reify Transport
(recv [this] (.recv transport))
(recv [this timeout] (.recv transport timeout))
(send [this {:keys [printed-value value] :as resp}]
(.send transport
(if (and printed-value (string? value))
(dissoc resp :printed-value)
(if-let [[_ v] (find resp :value)]
(assoc resp
:value (let [repr (java.io.StringWriter.)]
(if *print-dup*
(print-dup v repr)
(print-method v repr))
(str repr)))
resp)))
this))))))
(set-descriptor! #'pr-values
{:requires #{}
:expects #{}
:handles {}})
| true |
(ns ^{:author "PI:NAME:<NAME>END_PI"}
clojure.tools.nrepl.middleware.pr-values
(:require [clojure.tools.nrepl.transport :as t])
(:use [clojure.tools.nrepl.middleware :only (set-descriptor!)])
(:import clojure.tools.nrepl.transport.Transport))
(defn pr-values
"Middleware that returns a handler which transforms any :value slots
in messages sent via the request's Transport to strings via `pr`,
delegating all actual message handling to the provided handler.
Requires that results of eval operations are sent in messages in a
:value slot.
If :value is already a string, and a sent message's :printed-value
slot contains any truthy value, then :value will not be re-printed.
This allows evaluation contexts to produce printed results in :value
if they so choose, and opt out of the printing here."
[h]
(fn [{:keys [op ^Transport transport] :as msg}]
(h (assoc msg
:transport (reify Transport
(recv [this] (.recv transport))
(recv [this timeout] (.recv transport timeout))
(send [this {:keys [printed-value value] :as resp}]
(.send transport
(if (and printed-value (string? value))
(dissoc resp :printed-value)
(if-let [[_ v] (find resp :value)]
(assoc resp
:value (let [repr (java.io.StringWriter.)]
(if *print-dup*
(print-dup v repr)
(print-method v repr))
(str repr)))
resp)))
this))))))
(set-descriptor! #'pr-values
{:requires #{}
:expects #{}
:handles {}})
|
[
{
"context": " :password password}}}))\n\n(def mappings\n {:sports-sites\n {:setting",
"end": 388,
"score": 0.9690462946891785,
"start": 380,
"tag": "PASSWORD",
"value": "password"
}
] | webapp/src/clj/lipas/backend/search.clj | lipas-liikuntapaikat/lipas | 49 | (ns lipas.backend.search
(:require
[qbits.spandex :as es]
[qbits.spandex.utils :as es-utils]
[clojure.core.async :as async]))
(def es-type "_doc") ; See https://bit.ly/2wslBqY
(defn create-cli
[{:keys [hosts user password]}]
(es/client {:hosts hosts
:http-client {:basic-auth {:user user
:password password}}}))
(def mappings
{:sports-sites
{:settings
{:max_result_window 50000}
:mappings
{:properties
{:search-meta.location.wgs84-point
{:type "geo_point"}
:search-meta.location.wgs84-center
{:type "geo_point"}
:search-meta.location.wgs84-end
{:type "geo_point"}
:search-meta.location.geometries
{:type "geo_shape"}}}}})
(defn gen-idx-name
"Returns index name generated from current timestamp that is
a valid ElasticSearch alias. Example: \"2017-08-13t14-44-42-761\""
[]
(-> (java.time.LocalDateTime/now)
str
(clojure.string/lower-case)
(clojure.string/replace #"[:|.]" "-")))
(defn create-index!
[client index mappings]
(es/request client {:method :put
:url (es-utils/url [index])
:body mappings}))
(defn delete-index!
[client index]
(es/request client {:method :delete
:url (es-utils/url [index])}))
(defn index!
([client idx-name id-fn data]
(index! client idx-name id-fn data false))
([client idx-name id-fn data sync?]
(es/request client {:method :put
:url (es-utils/url [idx-name es-type (id-fn data)])
:body data
:query-string (when sync? {:refresh "wait_for"})})))
(defn delete!
[client idx-name id]
(es/request client {:method :delete
:url (es-utils/url [idx-name es-type id])}))
(defn bulk-index!
([client data]
(let [{:keys [input-ch output-ch]}
(es/bulk-chan client {:flush-threshold 100
:flush-interval 5000
:max-concurrent-requests 3})]
(async/put! input-ch data)
(future (loop [] (async/<!! output-ch))))))
(defn current-idxs
"Returns a coll containing current index(es) pointing to alias."
[client {:keys [alias]}]
(let [res (es/request client {:method :get
:url (es-utils/url ["*" "_alias" alias])
:exception-handler (constantly nil)})]
(not-empty (keys (:body res)))))
(defn swap-alias!
"Swaps alias to point to new-idx. Possible existing aliases will be removed."
[client {:keys [new-idx alias] :or {alias "sports_sites"}}]
(let [old-idxs (current-idxs client {:alias alias})
actions (-> (map #(hash-map :remove {:index % :alias alias}) old-idxs)
(conj {:add {:index new-idx :alias alias}}))]
(es/request client {:method :post
:url (es-utils/url [:_aliases])
:body {:actions actions}})
old-idxs))
(defn search
[client idx-name params]
(es/request client {:method :get
:url (es-utils/url [idx-name :_search])
:body params}))
(defn scroll
[client idx-name params]
(es/scroll-chan client {:method :get
:url (es-utils/url [idx-name :_search])
:body params}))
(defn more?
"Returns true if result set was limited considering
page-size and requested page, otherwise false."
[results page-size page]
(let [total (-> results :hits :total)
n (count (-> results :hits :hits))]
(< (+ (* page page-size) n) total)))
(def partial? "Alias for `more?`" more?)
(defn wrap-es-bulk
[es-index es-type id-fn entry]
[{:index {:_index es-index
;;:_type es-type
:_id (id-fn entry)}}
entry])
(defn ->bulk [es-index id-fn data]
(reduce into (map (partial wrap-es-bulk es-index es-type id-fn) data)))
| 96365 | (ns lipas.backend.search
(:require
[qbits.spandex :as es]
[qbits.spandex.utils :as es-utils]
[clojure.core.async :as async]))
(def es-type "_doc") ; See https://bit.ly/2wslBqY
(defn create-cli
[{:keys [hosts user password]}]
(es/client {:hosts hosts
:http-client {:basic-auth {:user user
:password <PASSWORD>}}}))
(def mappings
{:sports-sites
{:settings
{:max_result_window 50000}
:mappings
{:properties
{:search-meta.location.wgs84-point
{:type "geo_point"}
:search-meta.location.wgs84-center
{:type "geo_point"}
:search-meta.location.wgs84-end
{:type "geo_point"}
:search-meta.location.geometries
{:type "geo_shape"}}}}})
(defn gen-idx-name
"Returns index name generated from current timestamp that is
a valid ElasticSearch alias. Example: \"2017-08-13t14-44-42-761\""
[]
(-> (java.time.LocalDateTime/now)
str
(clojure.string/lower-case)
(clojure.string/replace #"[:|.]" "-")))
(defn create-index!
[client index mappings]
(es/request client {:method :put
:url (es-utils/url [index])
:body mappings}))
(defn delete-index!
[client index]
(es/request client {:method :delete
:url (es-utils/url [index])}))
(defn index!
([client idx-name id-fn data]
(index! client idx-name id-fn data false))
([client idx-name id-fn data sync?]
(es/request client {:method :put
:url (es-utils/url [idx-name es-type (id-fn data)])
:body data
:query-string (when sync? {:refresh "wait_for"})})))
(defn delete!
[client idx-name id]
(es/request client {:method :delete
:url (es-utils/url [idx-name es-type id])}))
(defn bulk-index!
([client data]
(let [{:keys [input-ch output-ch]}
(es/bulk-chan client {:flush-threshold 100
:flush-interval 5000
:max-concurrent-requests 3})]
(async/put! input-ch data)
(future (loop [] (async/<!! output-ch))))))
(defn current-idxs
"Returns a coll containing current index(es) pointing to alias."
[client {:keys [alias]}]
(let [res (es/request client {:method :get
:url (es-utils/url ["*" "_alias" alias])
:exception-handler (constantly nil)})]
(not-empty (keys (:body res)))))
(defn swap-alias!
"Swaps alias to point to new-idx. Possible existing aliases will be removed."
[client {:keys [new-idx alias] :or {alias "sports_sites"}}]
(let [old-idxs (current-idxs client {:alias alias})
actions (-> (map #(hash-map :remove {:index % :alias alias}) old-idxs)
(conj {:add {:index new-idx :alias alias}}))]
(es/request client {:method :post
:url (es-utils/url [:_aliases])
:body {:actions actions}})
old-idxs))
(defn search
[client idx-name params]
(es/request client {:method :get
:url (es-utils/url [idx-name :_search])
:body params}))
(defn scroll
[client idx-name params]
(es/scroll-chan client {:method :get
:url (es-utils/url [idx-name :_search])
:body params}))
(defn more?
"Returns true if result set was limited considering
page-size and requested page, otherwise false."
[results page-size page]
(let [total (-> results :hits :total)
n (count (-> results :hits :hits))]
(< (+ (* page page-size) n) total)))
(def partial? "Alias for `more?`" more?)
(defn wrap-es-bulk
[es-index es-type id-fn entry]
[{:index {:_index es-index
;;:_type es-type
:_id (id-fn entry)}}
entry])
(defn ->bulk [es-index id-fn data]
(reduce into (map (partial wrap-es-bulk es-index es-type id-fn) data)))
| true | (ns lipas.backend.search
(:require
[qbits.spandex :as es]
[qbits.spandex.utils :as es-utils]
[clojure.core.async :as async]))
(def es-type "_doc") ; See https://bit.ly/2wslBqY
(defn create-cli
[{:keys [hosts user password]}]
(es/client {:hosts hosts
:http-client {:basic-auth {:user user
:password PI:PASSWORD:<PASSWORD>END_PI}}}))
(def mappings
{:sports-sites
{:settings
{:max_result_window 50000}
:mappings
{:properties
{:search-meta.location.wgs84-point
{:type "geo_point"}
:search-meta.location.wgs84-center
{:type "geo_point"}
:search-meta.location.wgs84-end
{:type "geo_point"}
:search-meta.location.geometries
{:type "geo_shape"}}}}})
(defn gen-idx-name
"Returns index name generated from current timestamp that is
a valid ElasticSearch alias. Example: \"2017-08-13t14-44-42-761\""
[]
(-> (java.time.LocalDateTime/now)
str
(clojure.string/lower-case)
(clojure.string/replace #"[:|.]" "-")))
(defn create-index!
[client index mappings]
(es/request client {:method :put
:url (es-utils/url [index])
:body mappings}))
(defn delete-index!
[client index]
(es/request client {:method :delete
:url (es-utils/url [index])}))
(defn index!
([client idx-name id-fn data]
(index! client idx-name id-fn data false))
([client idx-name id-fn data sync?]
(es/request client {:method :put
:url (es-utils/url [idx-name es-type (id-fn data)])
:body data
:query-string (when sync? {:refresh "wait_for"})})))
(defn delete!
[client idx-name id]
(es/request client {:method :delete
:url (es-utils/url [idx-name es-type id])}))
(defn bulk-index!
([client data]
(let [{:keys [input-ch output-ch]}
(es/bulk-chan client {:flush-threshold 100
:flush-interval 5000
:max-concurrent-requests 3})]
(async/put! input-ch data)
(future (loop [] (async/<!! output-ch))))))
(defn current-idxs
"Returns a coll containing current index(es) pointing to alias."
[client {:keys [alias]}]
(let [res (es/request client {:method :get
:url (es-utils/url ["*" "_alias" alias])
:exception-handler (constantly nil)})]
(not-empty (keys (:body res)))))
(defn swap-alias!
"Swaps alias to point to new-idx. Possible existing aliases will be removed."
[client {:keys [new-idx alias] :or {alias "sports_sites"}}]
(let [old-idxs (current-idxs client {:alias alias})
actions (-> (map #(hash-map :remove {:index % :alias alias}) old-idxs)
(conj {:add {:index new-idx :alias alias}}))]
(es/request client {:method :post
:url (es-utils/url [:_aliases])
:body {:actions actions}})
old-idxs))
(defn search
[client idx-name params]
(es/request client {:method :get
:url (es-utils/url [idx-name :_search])
:body params}))
(defn scroll
[client idx-name params]
(es/scroll-chan client {:method :get
:url (es-utils/url [idx-name :_search])
:body params}))
(defn more?
"Returns true if result set was limited considering
page-size and requested page, otherwise false."
[results page-size page]
(let [total (-> results :hits :total)
n (count (-> results :hits :hits))]
(< (+ (* page page-size) n) total)))
(def partial? "Alias for `more?`" more?)
(defn wrap-es-bulk
[es-index es-type id-fn entry]
[{:index {:_index es-index
;;:_type es-type
:_id (id-fn entry)}}
entry])
(defn ->bulk [es-index id-fn data]
(reduce into (map (partial wrap-es-bulk es-index es-type id-fn) data)))
|
[
{
"context": "dbtype \"postgresql\", :user \"vladkotu\", :password \"pwd123\", :dbname \"blog_db\", :port 54320, :host \"localhos",
"end": 360,
"score": 0.9993752241134644,
"start": 354,
"tag": "PASSWORD",
"value": "pwd123"
},
{
"context": ":host \"localhost\"})))\n(comment (let [body {:name \"Li\", :email \"li@bisss.com\", :nickname \"L\", :biograph",
"end": 447,
"score": 0.997627317905426,
"start": 445,
"tag": "NAME",
"value": "Li"
},
{
"context": "ost\"})))\n(comment (let [body {:name \"Li\", :email \"li@bisss.com\", :nickname \"L\", :biography nil}]\n (ins",
"end": 470,
"score": 0.9999250769615173,
"start": 458,
"tag": "EMAIL",
"value": "li@bisss.com"
},
{
"context": " (map vals\n [{:name \"Ivan\"\n :email \"ivan@ttt.com\"\n ",
"end": 675,
"score": 0.9997087717056274,
"start": 671,
"tag": "NAME",
"value": "Ivan"
},
{
"context": "[{:name \"Ivan\"\n :email \"ivan@ttt.com\"\n :nickname \"ivanko\"\n ",
"end": 719,
"score": 0.9999278783798218,
"start": 707,
"tag": "EMAIL",
"value": "ivan@ttt.com"
},
{
"context": " :biography nil}\n {:name \"Sven\"\n :email \"svet@ttt.com\"\n ",
"end": 827,
"score": 0.9996975064277649,
"start": 823,
"tag": "NAME",
"value": "Sven"
},
{
"context": " {:name \"Sven\"\n :email \"svet@ttt.com\"\n :nickname \"svenlo\"\n ",
"end": 871,
"score": 0.9999184608459473,
"start": 859,
"tag": "EMAIL",
"value": "svet@ttt.com"
},
{
"context": "mment\n (authors/get-author-by-email @db {:email \"svet@ttt.com\"})\n (let [{:keys [id]} (authors/get-author-by-em",
"end": 1016,
"score": 0.9999271035194397,
"start": 1004,
"tag": "EMAIL",
"value": "svet@ttt.com"
},
{
"context": "s [id]} (authors/get-author-by-email @db {:email \"svet@ttt.com\"})]\n (authors/generic-update @db {:id id :upda",
"end": 1095,
"score": 0.9999242424964905,
"start": 1083,
"tag": "EMAIL",
"value": "svet@ttt.com"
},
{
"context": "thors/generic-update @db {:id id :updates {:name \"Svetlana\"}})))\n\n(comment\n (authors/clj-expr-single-sqlvec",
"end": 1165,
"score": 0.9472245573997498,
"start": 1157,
"tag": "NAME",
"value": "Svetlana"
},
{
"context": "ame\"] :id 1})\n (get-author-by-email @db {:email \"svet@ttt.com\"}))\n\n(comment\n (authors/get-all-authors @db))\n\n",
"end": 1353,
"score": 0.9999254941940308,
"start": 1341,
"tag": "EMAIL",
"value": "svet@ttt.com"
}
] | wiz.blog.api/src/wiz/blog/api/db/authors.clj | vladkotu/edge-clj-rest-api-example | 0 | (ns wiz.blog.api.db.authors
(:require
[hugsql.core :as hugsql]))
(hugsql/def-db-fns "wiz/blog/api/db/sql/authors.sql")
;; this should be removed in prod mode
(hugsql/def-sqlvec-fns "wiz/blog/api/db/sql/authors.sql")
;; primers mostly expired as of names have been changed
(comment (def db (atom {:dbtype "postgresql", :user "vladkotu", :password "pwd123", :dbname "blog_db", :port 54320, :host "localhost"})))
(comment (let [body {:name "Li", :email "li@bisss.com", :nickname "L", :biography nil}]
(insert-distinct-entity @db body)))
(comment (authors/insert-authors
@db
{:authors
(map vals
[{:name "Ivan"
:email "ivan@ttt.com"
:nickname "ivanko"
:biography nil}
{:name "Sven"
:email "svet@ttt.com"
:nickname "svenlo"
:biography nil}])}))
(comment
(authors/get-author-by-email @db {:email "svet@ttt.com"})
(let [{:keys [id]} (authors/get-author-by-email @db {:email "svet@ttt.com"})]
(authors/generic-update @db {:id id :updates {:name "Svetlana"}})))
(comment
(authors/clj-expr-single-sqlvec {:cols ["email" "name"]})
(authors/clj-expr-single @db {:cols ["email" "name"] :id 1})
(get-author-by-email @db {:email "svet@ttt.com"}))
(comment
(authors/get-all-authors @db))
| 48187 | (ns wiz.blog.api.db.authors
(:require
[hugsql.core :as hugsql]))
(hugsql/def-db-fns "wiz/blog/api/db/sql/authors.sql")
;; this should be removed in prod mode
(hugsql/def-sqlvec-fns "wiz/blog/api/db/sql/authors.sql")
;; primers mostly expired as of names have been changed
(comment (def db (atom {:dbtype "postgresql", :user "vladkotu", :password "<PASSWORD>", :dbname "blog_db", :port 54320, :host "localhost"})))
(comment (let [body {:name "<NAME>", :email "<EMAIL>", :nickname "L", :biography nil}]
(insert-distinct-entity @db body)))
(comment (authors/insert-authors
@db
{:authors
(map vals
[{:name "<NAME>"
:email "<EMAIL>"
:nickname "ivanko"
:biography nil}
{:name "<NAME>"
:email "<EMAIL>"
:nickname "svenlo"
:biography nil}])}))
(comment
(authors/get-author-by-email @db {:email "<EMAIL>"})
(let [{:keys [id]} (authors/get-author-by-email @db {:email "<EMAIL>"})]
(authors/generic-update @db {:id id :updates {:name "<NAME>"}})))
(comment
(authors/clj-expr-single-sqlvec {:cols ["email" "name"]})
(authors/clj-expr-single @db {:cols ["email" "name"] :id 1})
(get-author-by-email @db {:email "<EMAIL>"}))
(comment
(authors/get-all-authors @db))
| true | (ns wiz.blog.api.db.authors
(:require
[hugsql.core :as hugsql]))
(hugsql/def-db-fns "wiz/blog/api/db/sql/authors.sql")
;; this should be removed in prod mode
(hugsql/def-sqlvec-fns "wiz/blog/api/db/sql/authors.sql")
;; primers mostly expired as of names have been changed
(comment (def db (atom {:dbtype "postgresql", :user "vladkotu", :password "PI:PASSWORD:<PASSWORD>END_PI", :dbname "blog_db", :port 54320, :host "localhost"})))
(comment (let [body {:name "PI:NAME:<NAME>END_PI", :email "PI:EMAIL:<EMAIL>END_PI", :nickname "L", :biography nil}]
(insert-distinct-entity @db body)))
(comment (authors/insert-authors
@db
{:authors
(map vals
[{:name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:nickname "ivanko"
:biography nil}
{:name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:nickname "svenlo"
:biography nil}])}))
(comment
(authors/get-author-by-email @db {:email "PI:EMAIL:<EMAIL>END_PI"})
(let [{:keys [id]} (authors/get-author-by-email @db {:email "PI:EMAIL:<EMAIL>END_PI"})]
(authors/generic-update @db {:id id :updates {:name "PI:NAME:<NAME>END_PI"}})))
(comment
(authors/clj-expr-single-sqlvec {:cols ["email" "name"]})
(authors/clj-expr-single @db {:cols ["email" "name"] :id 1})
(get-author-by-email @db {:email "PI:EMAIL:<EMAIL>END_PI"}))
(comment
(authors/get-all-authors @db))
|
[
{
"context": "{:crux.db/id :id/jeff\n :person/name \"Jeff\"}]\n [:crux.tx/put\n {:crux.",
"end": 812,
"score": 0.999210000038147,
"start": 808,
"tag": "NAME",
"value": "Jeff"
},
{
"context": " {:crux.db/id :id/lia\n :person/name \"Lia\"}]])\n\n (api/transaction-time\n (api/db syst #i",
"end": 907,
"score": 0.9989198446273804,
"start": 904,
"tag": "NAME",
"value": "Lia"
}
] | docs/example/backup-restore/src/example_backup_restore/main.clj | neuromantik33/crux | 0 | (ns example-backup-restore.main
(:require [crux.api :as api]
[crux.backup :as backup]))
(def crux-options
{:crux.node/topology 'crux.standalone/topology
:crux.node/kv-store 'crux.kv.rocksdb/kv
:crux.standalone/event-log-dir "data/eventlog-1"
:crux.kv/db-dir "data/db-dir-1"
:backup-dir "checkpoint"})
(def syst (api/start-node crux-options))
(comment
(backup/restore crux-options)
(backup/backup crux-options syst)
(backup/check-and-restore crux-options)
(api/valid-time (api/db syst #inst "2019-02-02"))
(api/history syst :id/jeff)
(api/entity (api/db syst) :id/jeff)
(api/document syst "48ea7b320721dbdbd09c5e6be1486b0e76369b6a")
(api/submit-tx
syst
[[:crux.tx/put
{:crux.db/id :id/jeff
:person/name "Jeff"}]
[:crux.tx/put
{:crux.db/id :id/lia
:person/name "Lia"}]])
(api/transaction-time
(api/db syst #inst "2019-02-02"
#inst "2019-04-16T12:35:05.042-00:00"))
(api/document
(api/db syst #inst "2019-02-02"
#inst "2019-04-16T12:35:05.042-00:00")))
| 92433 | (ns example-backup-restore.main
(:require [crux.api :as api]
[crux.backup :as backup]))
(def crux-options
{:crux.node/topology 'crux.standalone/topology
:crux.node/kv-store 'crux.kv.rocksdb/kv
:crux.standalone/event-log-dir "data/eventlog-1"
:crux.kv/db-dir "data/db-dir-1"
:backup-dir "checkpoint"})
(def syst (api/start-node crux-options))
(comment
(backup/restore crux-options)
(backup/backup crux-options syst)
(backup/check-and-restore crux-options)
(api/valid-time (api/db syst #inst "2019-02-02"))
(api/history syst :id/jeff)
(api/entity (api/db syst) :id/jeff)
(api/document syst "48ea7b320721dbdbd09c5e6be1486b0e76369b6a")
(api/submit-tx
syst
[[:crux.tx/put
{:crux.db/id :id/jeff
:person/name "<NAME>"}]
[:crux.tx/put
{:crux.db/id :id/lia
:person/name "<NAME>"}]])
(api/transaction-time
(api/db syst #inst "2019-02-02"
#inst "2019-04-16T12:35:05.042-00:00"))
(api/document
(api/db syst #inst "2019-02-02"
#inst "2019-04-16T12:35:05.042-00:00")))
| true | (ns example-backup-restore.main
(:require [crux.api :as api]
[crux.backup :as backup]))
(def crux-options
{:crux.node/topology 'crux.standalone/topology
:crux.node/kv-store 'crux.kv.rocksdb/kv
:crux.standalone/event-log-dir "data/eventlog-1"
:crux.kv/db-dir "data/db-dir-1"
:backup-dir "checkpoint"})
(def syst (api/start-node crux-options))
(comment
(backup/restore crux-options)
(backup/backup crux-options syst)
(backup/check-and-restore crux-options)
(api/valid-time (api/db syst #inst "2019-02-02"))
(api/history syst :id/jeff)
(api/entity (api/db syst) :id/jeff)
(api/document syst "48ea7b320721dbdbd09c5e6be1486b0e76369b6a")
(api/submit-tx
syst
[[:crux.tx/put
{:crux.db/id :id/jeff
:person/name "PI:NAME:<NAME>END_PI"}]
[:crux.tx/put
{:crux.db/id :id/lia
:person/name "PI:NAME:<NAME>END_PI"}]])
(api/transaction-time
(api/db syst #inst "2019-02-02"
#inst "2019-04-16T12:35:05.042-00:00"))
(api/document
(api/db syst #inst "2019-02-02"
#inst "2019-04-16T12:35:05.042-00:00")))
|
[
{
"context": "rOrLogin []\n (let [userName (hutil/getValueById \"userName\")\n password (hutil/getValueById \"password\"",
"end": 1704,
"score": 0.9939795732498169,
"start": 1696,
"tag": "USERNAME",
"value": "userName"
},
{
"context": "eg\")\n (send {:method \"registration\" :userName userName :password password})\n (send {:method \"login\"",
"end": 1956,
"score": 0.9973269701004028,
"start": 1948,
"tag": "USERNAME",
"value": "userName"
},
{
"context": " password})\n (send {:method \"login\" :userName userName :password password}))))\n\n(defn sendNewMessage []\n",
"end": 2025,
"score": 0.9961177706718445,
"start": 2017,
"tag": "USERNAME",
"value": "userName"
},
{
"context": "send {:method \"login\" :userName userName :password password}))))\n\n(defn sendNewMessage []\n (let [text (hutil",
"end": 2044,
"score": 0.9356458783149719,
"start": 2036,
"tag": "PASSWORD",
"value": "password"
}
] | Labs/FP/src/cljs/chat/uiHandlers.cljs | VerkhovtsovPavel/BSUIR_Labs | 1 | (ns cljs.chat.client.uiHandlers
(:require [cljs.chat.client.utils.htmlUtils :as hutil]
[cljs.chat.client.utils.cssUtils :as cutil]
[cljs.chat.client.model.state :as state]
[cljs.chat.client.core])
(:use [cljs.chat.client.websocket :only [send]]))
(defn showAddRoom []
(let [addRoomDiv (hutil/getById "addRoom")
searchDiv (hutil/getById "search")
subscription (hutil/getById "subscription")
setStyleDiv (hutil/getById "setStyle")]
(hutil/setVisibility {searchDiv "hidden" setStyleDiv "hidden" addRoomDiv "visible" subscription "hidden"})))
(defn showSearch []
(let [addRoomDiv (hutil/getById "addRoom")
searchDiv (hutil/getById "search")
subscription (hutil/getById "subscription")
setStyleDiv (hutil/getById "setStyle")]
(hutil/setVisibility {searchDiv "visible" setStyleDiv "hidden" addRoomDiv "hidden" subscription "hidden"})))
(defn showCustomizeRoom []
(let [addRoomDiv (hutil/getById "addRoom")
searchDiv (hutil/getById "search")
subscription (hutil/getById "subscription")
setStyleDiv (hutil/getById "setStyle")]
(hutil/setVisibility {searchDiv "hidden" setStyleDiv "visible" addRoomDiv "hidden" subscription "hidden"})))
(defn showSubscription []
(let [addRoomDiv (hutil/getById "addRoom")
searchDiv (hutil/getById "search")
subscription (hutil/getById "subscription")
setStyleDiv (hutil/getById "setStyle")]
(hutil/setVisibility {searchDiv "hidden" setStyleDiv "hidden" addRoomDiv "hidden" subscription "visible"}))
(send {:method "roomListToSubscibe"})
)
(defn registerOrLogin []
(let [userName (hutil/getValueById "userName")
password (hutil/getValueById "password")
userChoice (first (filter (fn [i] (.-checked i)) (.getElementsByName js/document "logRegRadio")))]
(if (= (.-value userChoice) "reg")
(send {:method "registration" :userName userName :password password})
(send {:method "login" :userName userName :password password}))))
(defn sendNewMessage []
(let [text (hutil/getValueById "text")
room (state/currentRoom)]
(if (= text "")
(js/alert "Message is empty")
(send {:method "message", :text text, :room room}))))
(defn nextPage []
(let [room (state/currentRoom)]
(send {:method "nextPage", :page @state/page, :messages @state/newMessages :room room}))
(swap! state/page (fn [current_state] (+ current_state 1))))
(defn saveStyle []
(let [bgrColor (hutil/getSelectedValue (hutil/getById "bgrColor"))
bgrImage (hutil/getValueById "bgrImage")
msgFont (hutil/getSelectedValue (hutil/getById "msgFont"))
msgFontSize (hutil/getValueById "msgFontSize")
msgFontColor (hutil/getSelectedValue (hutil/getById "msgFontColor"))
controlsColor (hutil/getSelectedValue (hutil/getById "controlsColor"))
room (state/currentRoom)
roomStyle (cutil/build-css bgrColor bgrImage msgFont msgFontSize msgFontColor controlsColor)]
(send {:method "saveStyle", :roomStyle roomStyle, :room room})))
(defn createRoom []
(let [roomName (hutil/getValueById "roomName")
roomPart (hutil/getValueById "roomPart")
type (.-checked (hutil/getById "roomType"))]
(if (or (= roomName "") (= roomPart ""))
(js/alert "Please feel all fields")
(send {:method "newRoom", :roomName roomName, :part (clojure.string/split roomPart ";") :isOpened type}))))
(defn searchQuery []
(let [query (hutil/getValueById "searchQuery")
room (state/currentRoom)]
(send {:method "search", :query query, :room room})))
(defn subscribe []
(let [room (hutil/getSelectedValue (hutil/getById "roomToSubscribe"))]
(send {:method "subscribe" :room room})))
(defn unsubscribe []
(let [room (state/currentRoom)]
(send {:method "unsubscribe", :room room}))) | 58335 | (ns cljs.chat.client.uiHandlers
(:require [cljs.chat.client.utils.htmlUtils :as hutil]
[cljs.chat.client.utils.cssUtils :as cutil]
[cljs.chat.client.model.state :as state]
[cljs.chat.client.core])
(:use [cljs.chat.client.websocket :only [send]]))
(defn showAddRoom []
(let [addRoomDiv (hutil/getById "addRoom")
searchDiv (hutil/getById "search")
subscription (hutil/getById "subscription")
setStyleDiv (hutil/getById "setStyle")]
(hutil/setVisibility {searchDiv "hidden" setStyleDiv "hidden" addRoomDiv "visible" subscription "hidden"})))
(defn showSearch []
(let [addRoomDiv (hutil/getById "addRoom")
searchDiv (hutil/getById "search")
subscription (hutil/getById "subscription")
setStyleDiv (hutil/getById "setStyle")]
(hutil/setVisibility {searchDiv "visible" setStyleDiv "hidden" addRoomDiv "hidden" subscription "hidden"})))
(defn showCustomizeRoom []
(let [addRoomDiv (hutil/getById "addRoom")
searchDiv (hutil/getById "search")
subscription (hutil/getById "subscription")
setStyleDiv (hutil/getById "setStyle")]
(hutil/setVisibility {searchDiv "hidden" setStyleDiv "visible" addRoomDiv "hidden" subscription "hidden"})))
(defn showSubscription []
(let [addRoomDiv (hutil/getById "addRoom")
searchDiv (hutil/getById "search")
subscription (hutil/getById "subscription")
setStyleDiv (hutil/getById "setStyle")]
(hutil/setVisibility {searchDiv "hidden" setStyleDiv "hidden" addRoomDiv "hidden" subscription "visible"}))
(send {:method "roomListToSubscibe"})
)
(defn registerOrLogin []
(let [userName (hutil/getValueById "userName")
password (hutil/getValueById "password")
userChoice (first (filter (fn [i] (.-checked i)) (.getElementsByName js/document "logRegRadio")))]
(if (= (.-value userChoice) "reg")
(send {:method "registration" :userName userName :password password})
(send {:method "login" :userName userName :password <PASSWORD>}))))
(defn sendNewMessage []
(let [text (hutil/getValueById "text")
room (state/currentRoom)]
(if (= text "")
(js/alert "Message is empty")
(send {:method "message", :text text, :room room}))))
(defn nextPage []
(let [room (state/currentRoom)]
(send {:method "nextPage", :page @state/page, :messages @state/newMessages :room room}))
(swap! state/page (fn [current_state] (+ current_state 1))))
(defn saveStyle []
(let [bgrColor (hutil/getSelectedValue (hutil/getById "bgrColor"))
bgrImage (hutil/getValueById "bgrImage")
msgFont (hutil/getSelectedValue (hutil/getById "msgFont"))
msgFontSize (hutil/getValueById "msgFontSize")
msgFontColor (hutil/getSelectedValue (hutil/getById "msgFontColor"))
controlsColor (hutil/getSelectedValue (hutil/getById "controlsColor"))
room (state/currentRoom)
roomStyle (cutil/build-css bgrColor bgrImage msgFont msgFontSize msgFontColor controlsColor)]
(send {:method "saveStyle", :roomStyle roomStyle, :room room})))
(defn createRoom []
(let [roomName (hutil/getValueById "roomName")
roomPart (hutil/getValueById "roomPart")
type (.-checked (hutil/getById "roomType"))]
(if (or (= roomName "") (= roomPart ""))
(js/alert "Please feel all fields")
(send {:method "newRoom", :roomName roomName, :part (clojure.string/split roomPart ";") :isOpened type}))))
(defn searchQuery []
(let [query (hutil/getValueById "searchQuery")
room (state/currentRoom)]
(send {:method "search", :query query, :room room})))
(defn subscribe []
(let [room (hutil/getSelectedValue (hutil/getById "roomToSubscribe"))]
(send {:method "subscribe" :room room})))
(defn unsubscribe []
(let [room (state/currentRoom)]
(send {:method "unsubscribe", :room room}))) | true | (ns cljs.chat.client.uiHandlers
(:require [cljs.chat.client.utils.htmlUtils :as hutil]
[cljs.chat.client.utils.cssUtils :as cutil]
[cljs.chat.client.model.state :as state]
[cljs.chat.client.core])
(:use [cljs.chat.client.websocket :only [send]]))
(defn showAddRoom []
(let [addRoomDiv (hutil/getById "addRoom")
searchDiv (hutil/getById "search")
subscription (hutil/getById "subscription")
setStyleDiv (hutil/getById "setStyle")]
(hutil/setVisibility {searchDiv "hidden" setStyleDiv "hidden" addRoomDiv "visible" subscription "hidden"})))
(defn showSearch []
(let [addRoomDiv (hutil/getById "addRoom")
searchDiv (hutil/getById "search")
subscription (hutil/getById "subscription")
setStyleDiv (hutil/getById "setStyle")]
(hutil/setVisibility {searchDiv "visible" setStyleDiv "hidden" addRoomDiv "hidden" subscription "hidden"})))
(defn showCustomizeRoom []
(let [addRoomDiv (hutil/getById "addRoom")
searchDiv (hutil/getById "search")
subscription (hutil/getById "subscription")
setStyleDiv (hutil/getById "setStyle")]
(hutil/setVisibility {searchDiv "hidden" setStyleDiv "visible" addRoomDiv "hidden" subscription "hidden"})))
(defn showSubscription []
(let [addRoomDiv (hutil/getById "addRoom")
searchDiv (hutil/getById "search")
subscription (hutil/getById "subscription")
setStyleDiv (hutil/getById "setStyle")]
(hutil/setVisibility {searchDiv "hidden" setStyleDiv "hidden" addRoomDiv "hidden" subscription "visible"}))
(send {:method "roomListToSubscibe"})
)
(defn registerOrLogin []
(let [userName (hutil/getValueById "userName")
password (hutil/getValueById "password")
userChoice (first (filter (fn [i] (.-checked i)) (.getElementsByName js/document "logRegRadio")))]
(if (= (.-value userChoice) "reg")
(send {:method "registration" :userName userName :password password})
(send {:method "login" :userName userName :password PI:PASSWORD:<PASSWORD>END_PI}))))
(defn sendNewMessage []
(let [text (hutil/getValueById "text")
room (state/currentRoom)]
(if (= text "")
(js/alert "Message is empty")
(send {:method "message", :text text, :room room}))))
(defn nextPage []
(let [room (state/currentRoom)]
(send {:method "nextPage", :page @state/page, :messages @state/newMessages :room room}))
(swap! state/page (fn [current_state] (+ current_state 1))))
(defn saveStyle []
(let [bgrColor (hutil/getSelectedValue (hutil/getById "bgrColor"))
bgrImage (hutil/getValueById "bgrImage")
msgFont (hutil/getSelectedValue (hutil/getById "msgFont"))
msgFontSize (hutil/getValueById "msgFontSize")
msgFontColor (hutil/getSelectedValue (hutil/getById "msgFontColor"))
controlsColor (hutil/getSelectedValue (hutil/getById "controlsColor"))
room (state/currentRoom)
roomStyle (cutil/build-css bgrColor bgrImage msgFont msgFontSize msgFontColor controlsColor)]
(send {:method "saveStyle", :roomStyle roomStyle, :room room})))
(defn createRoom []
(let [roomName (hutil/getValueById "roomName")
roomPart (hutil/getValueById "roomPart")
type (.-checked (hutil/getById "roomType"))]
(if (or (= roomName "") (= roomPart ""))
(js/alert "Please feel all fields")
(send {:method "newRoom", :roomName roomName, :part (clojure.string/split roomPart ";") :isOpened type}))))
(defn searchQuery []
(let [query (hutil/getValueById "searchQuery")
room (state/currentRoom)]
(send {:method "search", :query query, :room room})))
(defn subscribe []
(let [room (hutil/getSelectedValue (hutil/getById "roomToSubscribe"))]
(send {:method "subscribe" :room room})))
(defn unsubscribe []
(let [room (state/currentRoom)]
(send {:method "unsubscribe", :room room}))) |
[
{
"context": "]))\n\n(def dbname \"drift_db_test\")\n\n(def username \"drift-db\")\n(def password \"drift-db-pass\")\n\n(deftest test-o",
"end": 237,
"score": 0.9982720017433167,
"start": 229,
"tag": "USERNAME",
"value": "drift-db"
},
{
"context": "_test\")\n\n(def username \"drift-db\")\n(def password \"drift-db-pass\")\n\n(deftest test-order-clause\r\n (is (= (order-cl",
"end": 268,
"score": 0.9994170069694519,
"start": 255,
"tag": "PASSWORD",
"value": "drift-db-pass"
}
] | drift-db-mysql/test/drift_db_mysql/test/flavor.clj | macourtney/drift-db | 3 | (ns drift-db-mysql.test.flavor
(:use drift-db-mysql.flavor
clojure.test)
(:require [drift-db.core :as drift-db]
[drift-db-mysql.test.column :as column-test]))
(def dbname "drift_db_test")
(def username "drift-db")
(def password "drift-db-pass")
(deftest test-order-clause
(is (= (order-clause { :order-by :test}) " ORDER BY `test`"))
(is (= (order-clause { :order-by { :expression :test }}) " ORDER BY `test`"))
(is (= (order-clause { :order-by { :expression :test :direction :aSc }}) " ORDER BY `test` ASC"))
(is (= (order-clause { :order-by [:test :test2]}) " ORDER BY `test`, `test2`"))
(is (= (order-clause { :order-by [{ :expression :test :direction :aSc }
{ :expression :test2 :direction :desc }]})
" ORDER BY `test` ASC, `test2` DESC")))
(deftest create-flavor
(let [flavor (mysql-flavor username password dbname)]
(try
(is flavor)
(drift-db/init-flavor flavor)
(drift-db/create-table :test
(drift-db/integer :id { :auto-increment true :primary-key true })
(drift-db/string :name { :length 20 :not-null true })
(drift-db/date :created-at)
(drift-db/date-time :edited-at)
(drift-db/decimal :bar)
(drift-db/text :description)
(drift-db/time-type :deleted-at)
(drift-db/boolean :foo))
(is (drift-db/table-exists? :test))
(let [table-description (drift-db/describe-table :test)
expected-columns [{ :length 11 :not-null true :primary-key true :name :id :type :integer :auto-increment true }
{ :default "" :length 20 :not-null true :name :name :type :string }
{ :name :created-at :type :date }
{ :name :edited-at :type :date-time }
{ :scale 6 :precision 20 :name :bar :type :decimal }
{ :name :description :type :text }
{ :name :deleted-at :type :time }
{ :name :foo :type :integer :length 1 }]]
(is (= (get table-description :name) :test))
(is (get table-description :columns))
(is (= (count (get table-description :columns)) (count expected-columns)))
(doseq [column-pair (map #(list %1 %2) (get table-description :columns) expected-columns)]
(column-test/assert-column-map (first column-pair) (second column-pair))))
(is (drift-db/column-exists? :test :id))
(is (drift-db/column-exists? :test "bar"))
(drift-db/add-column :test
(drift-db/string :added))
(column-test/assert-column-map
(drift-db/find-column :test :added)
{ :length 255, :name :added, :type :string })
(drift-db/update-column :test
:added (drift-db/string :altered-test))
(column-test/assert-column-map
(drift-db/find-column :test :altered-test)
{ :length 255, :name :altered-test, :type :string })
(drift-db/update-column :test
:altered-test (drift-db/string :altered { :length 100 :not-null true }))
(column-test/assert-column-map
(drift-db/find-column (drift-db/describe-table :test) :altered)
{ :type :string, :name :altered, :length 100, :not-null true })
(drift-db/drop-column :test :altered)
(is (not (drift-db/column-exists? :test :altered)))
(drift-db/drop-column-if-exists :test :altered)
(drift-db/drop-column-if-exists :test :bar)
(is (not (drift-db/column-exists? :test :bar)))
(drift-db/create-index :test :name-index { :columns [:name] :unique? true :method :hash :direction :descending })
(drift-db/drop-index :test :name-index)
(finally
(drift-db/drop-table-if-exists :test)
(is (not (drift-db/table-exists? :test)))))))
(deftest test-rows
(let [flavor (mysql-flavor username password dbname)]
(try
(is flavor)
(drift-db/init-flavor flavor)
(drift-db/create-table :test
(drift-db/string :name { :length 20 :not-null true :primary-key true }))
(is (drift-db/table-exists? :test))
(let [test-row-name "blah"
test-row-name2 "blah2"
test-row { :name test-row-name }
test-row2 { :name test-row-name2 }]
(drift-db/insert-into :test test-row)
(is (= (first (drift-db/sql-find { :table :test :where [(str "NAME = '" test-row-name "'")] :limit 1 :order-by :name }))
test-row))
(drift-db/update :test ["NAME = ?" test-row-name] { :name test-row-name2 })
(is (= (first (drift-db/sql-find { :table :test :where ["NAME = ?" test-row-name2] })) test-row2))
(drift-db/update :test { :name test-row-name2 } { :name test-row-name })
(is (= (first (drift-db/sql-find { :table :test :where ["NAME = ?" test-row-name] })) test-row))
(drift-db/delete :test ["NAME = ?" test-row-name])
(is (nil? (first (drift-db/sql-find { :table :test :where { :name test-row-name } })))))
(finally
(drift-db/drop-table :test)
(is (not (drift-db/table-exists? :test)))))))
| 103446 | (ns drift-db-mysql.test.flavor
(:use drift-db-mysql.flavor
clojure.test)
(:require [drift-db.core :as drift-db]
[drift-db-mysql.test.column :as column-test]))
(def dbname "drift_db_test")
(def username "drift-db")
(def password "<PASSWORD>")
(deftest test-order-clause
(is (= (order-clause { :order-by :test}) " ORDER BY `test`"))
(is (= (order-clause { :order-by { :expression :test }}) " ORDER BY `test`"))
(is (= (order-clause { :order-by { :expression :test :direction :aSc }}) " ORDER BY `test` ASC"))
(is (= (order-clause { :order-by [:test :test2]}) " ORDER BY `test`, `test2`"))
(is (= (order-clause { :order-by [{ :expression :test :direction :aSc }
{ :expression :test2 :direction :desc }]})
" ORDER BY `test` ASC, `test2` DESC")))
(deftest create-flavor
(let [flavor (mysql-flavor username password dbname)]
(try
(is flavor)
(drift-db/init-flavor flavor)
(drift-db/create-table :test
(drift-db/integer :id { :auto-increment true :primary-key true })
(drift-db/string :name { :length 20 :not-null true })
(drift-db/date :created-at)
(drift-db/date-time :edited-at)
(drift-db/decimal :bar)
(drift-db/text :description)
(drift-db/time-type :deleted-at)
(drift-db/boolean :foo))
(is (drift-db/table-exists? :test))
(let [table-description (drift-db/describe-table :test)
expected-columns [{ :length 11 :not-null true :primary-key true :name :id :type :integer :auto-increment true }
{ :default "" :length 20 :not-null true :name :name :type :string }
{ :name :created-at :type :date }
{ :name :edited-at :type :date-time }
{ :scale 6 :precision 20 :name :bar :type :decimal }
{ :name :description :type :text }
{ :name :deleted-at :type :time }
{ :name :foo :type :integer :length 1 }]]
(is (= (get table-description :name) :test))
(is (get table-description :columns))
(is (= (count (get table-description :columns)) (count expected-columns)))
(doseq [column-pair (map #(list %1 %2) (get table-description :columns) expected-columns)]
(column-test/assert-column-map (first column-pair) (second column-pair))))
(is (drift-db/column-exists? :test :id))
(is (drift-db/column-exists? :test "bar"))
(drift-db/add-column :test
(drift-db/string :added))
(column-test/assert-column-map
(drift-db/find-column :test :added)
{ :length 255, :name :added, :type :string })
(drift-db/update-column :test
:added (drift-db/string :altered-test))
(column-test/assert-column-map
(drift-db/find-column :test :altered-test)
{ :length 255, :name :altered-test, :type :string })
(drift-db/update-column :test
:altered-test (drift-db/string :altered { :length 100 :not-null true }))
(column-test/assert-column-map
(drift-db/find-column (drift-db/describe-table :test) :altered)
{ :type :string, :name :altered, :length 100, :not-null true })
(drift-db/drop-column :test :altered)
(is (not (drift-db/column-exists? :test :altered)))
(drift-db/drop-column-if-exists :test :altered)
(drift-db/drop-column-if-exists :test :bar)
(is (not (drift-db/column-exists? :test :bar)))
(drift-db/create-index :test :name-index { :columns [:name] :unique? true :method :hash :direction :descending })
(drift-db/drop-index :test :name-index)
(finally
(drift-db/drop-table-if-exists :test)
(is (not (drift-db/table-exists? :test)))))))
(deftest test-rows
(let [flavor (mysql-flavor username password dbname)]
(try
(is flavor)
(drift-db/init-flavor flavor)
(drift-db/create-table :test
(drift-db/string :name { :length 20 :not-null true :primary-key true }))
(is (drift-db/table-exists? :test))
(let [test-row-name "blah"
test-row-name2 "blah2"
test-row { :name test-row-name }
test-row2 { :name test-row-name2 }]
(drift-db/insert-into :test test-row)
(is (= (first (drift-db/sql-find { :table :test :where [(str "NAME = '" test-row-name "'")] :limit 1 :order-by :name }))
test-row))
(drift-db/update :test ["NAME = ?" test-row-name] { :name test-row-name2 })
(is (= (first (drift-db/sql-find { :table :test :where ["NAME = ?" test-row-name2] })) test-row2))
(drift-db/update :test { :name test-row-name2 } { :name test-row-name })
(is (= (first (drift-db/sql-find { :table :test :where ["NAME = ?" test-row-name] })) test-row))
(drift-db/delete :test ["NAME = ?" test-row-name])
(is (nil? (first (drift-db/sql-find { :table :test :where { :name test-row-name } })))))
(finally
(drift-db/drop-table :test)
(is (not (drift-db/table-exists? :test)))))))
| true | (ns drift-db-mysql.test.flavor
(:use drift-db-mysql.flavor
clojure.test)
(:require [drift-db.core :as drift-db]
[drift-db-mysql.test.column :as column-test]))
(def dbname "drift_db_test")
(def username "drift-db")
(def password "PI:PASSWORD:<PASSWORD>END_PI")
(deftest test-order-clause
(is (= (order-clause { :order-by :test}) " ORDER BY `test`"))
(is (= (order-clause { :order-by { :expression :test }}) " ORDER BY `test`"))
(is (= (order-clause { :order-by { :expression :test :direction :aSc }}) " ORDER BY `test` ASC"))
(is (= (order-clause { :order-by [:test :test2]}) " ORDER BY `test`, `test2`"))
(is (= (order-clause { :order-by [{ :expression :test :direction :aSc }
{ :expression :test2 :direction :desc }]})
" ORDER BY `test` ASC, `test2` DESC")))
(deftest create-flavor
(let [flavor (mysql-flavor username password dbname)]
(try
(is flavor)
(drift-db/init-flavor flavor)
(drift-db/create-table :test
(drift-db/integer :id { :auto-increment true :primary-key true })
(drift-db/string :name { :length 20 :not-null true })
(drift-db/date :created-at)
(drift-db/date-time :edited-at)
(drift-db/decimal :bar)
(drift-db/text :description)
(drift-db/time-type :deleted-at)
(drift-db/boolean :foo))
(is (drift-db/table-exists? :test))
(let [table-description (drift-db/describe-table :test)
expected-columns [{ :length 11 :not-null true :primary-key true :name :id :type :integer :auto-increment true }
{ :default "" :length 20 :not-null true :name :name :type :string }
{ :name :created-at :type :date }
{ :name :edited-at :type :date-time }
{ :scale 6 :precision 20 :name :bar :type :decimal }
{ :name :description :type :text }
{ :name :deleted-at :type :time }
{ :name :foo :type :integer :length 1 }]]
(is (= (get table-description :name) :test))
(is (get table-description :columns))
(is (= (count (get table-description :columns)) (count expected-columns)))
(doseq [column-pair (map #(list %1 %2) (get table-description :columns) expected-columns)]
(column-test/assert-column-map (first column-pair) (second column-pair))))
(is (drift-db/column-exists? :test :id))
(is (drift-db/column-exists? :test "bar"))
(drift-db/add-column :test
(drift-db/string :added))
(column-test/assert-column-map
(drift-db/find-column :test :added)
{ :length 255, :name :added, :type :string })
(drift-db/update-column :test
:added (drift-db/string :altered-test))
(column-test/assert-column-map
(drift-db/find-column :test :altered-test)
{ :length 255, :name :altered-test, :type :string })
(drift-db/update-column :test
:altered-test (drift-db/string :altered { :length 100 :not-null true }))
(column-test/assert-column-map
(drift-db/find-column (drift-db/describe-table :test) :altered)
{ :type :string, :name :altered, :length 100, :not-null true })
(drift-db/drop-column :test :altered)
(is (not (drift-db/column-exists? :test :altered)))
(drift-db/drop-column-if-exists :test :altered)
(drift-db/drop-column-if-exists :test :bar)
(is (not (drift-db/column-exists? :test :bar)))
(drift-db/create-index :test :name-index { :columns [:name] :unique? true :method :hash :direction :descending })
(drift-db/drop-index :test :name-index)
(finally
(drift-db/drop-table-if-exists :test)
(is (not (drift-db/table-exists? :test)))))))
(deftest test-rows
(let [flavor (mysql-flavor username password dbname)]
(try
(is flavor)
(drift-db/init-flavor flavor)
(drift-db/create-table :test
(drift-db/string :name { :length 20 :not-null true :primary-key true }))
(is (drift-db/table-exists? :test))
(let [test-row-name "blah"
test-row-name2 "blah2"
test-row { :name test-row-name }
test-row2 { :name test-row-name2 }]
(drift-db/insert-into :test test-row)
(is (= (first (drift-db/sql-find { :table :test :where [(str "NAME = '" test-row-name "'")] :limit 1 :order-by :name }))
test-row))
(drift-db/update :test ["NAME = ?" test-row-name] { :name test-row-name2 })
(is (= (first (drift-db/sql-find { :table :test :where ["NAME = ?" test-row-name2] })) test-row2))
(drift-db/update :test { :name test-row-name2 } { :name test-row-name })
(is (= (first (drift-db/sql-find { :table :test :where ["NAME = ?" test-row-name] })) test-row))
(drift-db/delete :test ["NAME = ?" test-row-name])
(is (nil? (first (drift-db/sql-find { :table :test :where { :name test-row-name } })))))
(finally
(drift-db/drop-table :test)
(is (not (drift-db/table-exists? :test)))))))
|
[
{
"context": "tities [{:name \"Personal\"}]\n :accounts [{:name \"Credit card\"\n :type :liability}\n {",
"end": 1429,
"score": 0.6826643347740173,
"start": 1418,
"tag": "NAME",
"value": "Credit card"
},
{
"context": " {:name \"Business\"}]\n :accounts [{:name \"Credit card\"\n :type :liability\n :",
"end": 5353,
"score": 0.983784556388855,
"start": 5342,
"tag": "NAME",
"value": "Credit card"
},
{
"context": " :entity-id \"Personal\"}\n {:name \"Auto\"\n :type :expense\n :en",
"end": 5451,
"score": 0.7296575903892517,
"start": 5447,
"tag": "NAME",
"value": "Auto"
},
{
"context": " :entity-id \"Personal\"}\n {:name \"Repair\"\n :type :expense\n :en",
"end": 5549,
"score": 0.9739661812782288,
"start": 5543,
"tag": "NAME",
"value": "Repair"
},
{
"context": " :parent-id \"Auto\"}\n {:name \"Household\"\n :type :expense\n :en",
"end": 5683,
"score": 0.8877261877059937,
"start": 5674,
"tag": "NAME",
"value": "Household"
},
{
"context": " :entity-id \"Personal\"}\n {:name \"Investment\"\n :type :income\n :ent",
"end": 5785,
"score": 0.9305967092514038,
"start": 5775,
"tag": "NAME",
"value": "Investment"
},
{
"context": "ontext)))\n result (accounts/create {:name \"Credit card\"\n :type :liabilit",
"end": 6078,
"score": 0.9827353954315186,
"start": 6067,
"tag": "NAME",
"value": "Credit card"
},
{
"context": "usehold\")\n result (accounts/create {:name \"Repair\"\n :type :expense\n",
"end": 6445,
"score": 0.9843412637710571,
"start": 6439,
"tag": "NAME",
"value": "Repair"
},
{
"context": "ersonal\")\n result (accounts/create {:name \"Repair\"\n :type :expense\n",
"end": 6820,
"score": 0.9878562092781067,
"start": 6814,
"tag": "NAME",
"value": "Repair"
},
{
"context": "ersonal\")\n result (accounts/create {:name \"Investment\"\n :type :expense\n",
"end": 7148,
"score": 0.9686588048934937,
"start": 7138,
"tag": "NAME",
"value": "Investment"
},
{
"context": "tities [{:name \"Personal\"}]\n :accounts [{:name \"Savings\"\n :type :asset}]})\n\n(deftest create",
"end": 7517,
"score": 0.7670825123786926,
"start": 7510,
"tag": "NAME",
"value": "Savings"
},
{
"context": "ities first)\n car (accounts/create {:name \"Car\"\n :type :asset\n ",
"end": 7760,
"score": 0.9484221339225769,
"start": 7757,
"tag": "NAME",
"value": "Car"
},
{
"context": "es first)\n result (accounts/create {:name \"Federal income tax\"\n :type :expense\n",
"end": 8181,
"score": 0.9764065742492676,
"start": 8163,
"tag": "NAME",
"value": "Federal income tax"
},
{
"context": " result (accounts/update (assoc account :name \"New name\"))\n retrieved (accounts/find account)]\n ",
"end": 9974,
"score": 0.6526095867156982,
"start": 9966,
"tag": "NAME",
"value": "New name"
}
] | test/clj_money/models/accounts_test.clj | dgknght/clj-money | 5 | (ns clj-money.models.accounts-test
(:require [clojure.test :refer [deftest use-fixtures is]]
[clj-factory.core :refer [factory]]
[dgknght.app-lib.test]
[clj-money.factories.user-factory]
[clj-money.factories.entity-factory]
[clj-money.factories.account-factory]
[clj-money.test-context :refer [realize
find-entity
find-commodity
find-account]]
[clj-money.models.accounts :as accounts]
[clj-money.accounts :refer [polarize-quantity
derive-action]]
[clj-money.test-helpers :refer [reset-db]]))
(use-fixtures :each reset-db)
(def ^:private account-context
{:users [(factory :user)]
:commodities [{:symbol "USD"
:type :currency
:name "US Dollar"}]
:entities [{:name "Personal"}]})
(defn- attributes
[context]
{:name "Checking"
:type :asset
:entity-id (-> context :entities first :id)
:system-tags #{:something-special}})
(def ^:private select-context
{:users [(factory :user)]
:commodities [{:symbol "USD"
:type :currency
:name "US Dollar"
:entity-id "Personal"}]
:entities [{:name "Personal"}]
:accounts [{:name "Credit card"
:type :liability}
{:name "Checking"
:type :asset}]})
(deftest select-accounts
(let [context (realize select-context)
entity-id (-> context :entities first :id)
actual (->> (accounts/search {:entity-id entity-id})
(map #(select-keys % [:name
:type
:system-tags
:quantity
:value
:entity-id
:commodity])))
expected [{:name "Checking"
:type :asset
:system-tags #{}
:quantity 0M
:value 0M
:entity-id entity-id}
{:name "Credit card"
:type :liability
:system-tags #{}
:quantity 0M
:value 0M
:entity-id entity-id}]]
(is (= expected actual) "It returns the correct accounts")))
(def ^:private nested-context
{:users [(factory :user)]
:commodities [{:symbol "USD"
:type :currency
:name "US Dollar"
:entity-id "Personal"}]
:entities [{:name "Personal"}]
:accounts [{:name "Savings"
:type :asset}
{:name "Reserve"
:type :asset
:parent-id "Savings"}
{:name "Car"
:type :asset
:parent-id "Savings"}
{:name "Doug"
:type :asset
:parent-id "Car"}
{:name "Eli"
:type :asset
:parent-id "Car"}
{:name "Checking"
:type :asset}
{:name "Taxes"
:type :expense}
{:name "Federal Income Tax"
:type :expense
:parent-id "Taxes"}
{:name "Social Security"
:type :expense
:parent-id "Taxes"}]})
(deftest select-account-with-children
(let [ctx (realize nested-context)
account (find-account ctx "Savings")
result (accounts/search {:id (:id account)}
{:include-children? true})]
(is (= #{"Savings" "Reserve" "Car" "Doug" "Eli"}
(set (map :name result))))))
(deftest create-an-account
(let [context (realize account-context)
result (accounts/create (attributes context))
entity (find-entity context "Personal")
usd (find-commodity context "USD")
accounts (->> (accounts/search {:entity-id (:id entity)})
(map #(select-keys % [:name
:type
:entity-id
:system-tags
:commodity-id
:quantity
:value])))
expected [{:name "Checking"
:type :asset
:entity-id (:id entity)
:system-tags #{:something-special}
:commodity-id (:id usd)
:quantity 0M
:value 0M}]]
(is (valid? result))
(is (= expected accounts) "The account can be retrieved")))
(def ^:private duplicate-name-context
{:users [(factory :user)]
:commodities [{:symbol "USD"
:name "US Dollar"
:type :currency
:entity-id "Personal"}
{:symbol "USD"
:name "US Dollar"
:entity-id "Business"
:type :currency}]
:entities [{:name "Personal"}
{:name "Business"}]
:accounts [{:name "Credit card"
:type :liability
:entity-id "Personal"}
{:name "Auto"
:type :expense
:entity-id "Personal"}
{:name "Repair"
:type :expense
:entity-id "Personal"
:parent-id "Auto"}
{:name "Household"
:type :expense
:entity-id "Personal"}
{:name "Investment"
:type :income
:entity-id "Personal"}]})
(deftest duplicate-name-across-entities
(let [context (realize duplicate-name-context)
business (first (filter #(= "Business" (:name %)) (:entities context)))
result (accounts/create {:name "Credit card"
:type :liability
:entity-id (:id business)})]
(is (valid? result))))
(deftest duplicate-name-across-parents
(let [ctx (realize duplicate-name-context)
business (find-entity ctx "Personal")
household (find-account ctx "Household")
result (accounts/create {:name "Repair"
:type :expense
:parent-id (:id household)
:entity-id (:id business)})]
(is (valid? result))))
(deftest duplicate-name-with-nil-parent
(let [ctx (realize duplicate-name-context)
entity (find-entity ctx "Personal")
result (accounts/create {:name "Repair"
:type :expense
:entity-id (:id entity)})]
(is (valid? result))))
(deftest duplicate-name-across-asset-types
(let [context (realize duplicate-name-context)
entity (find-entity context "Personal")
result (accounts/create {:name "Investment"
:type :expense
:entity-id (:id entity)})]
(is (valid? result))))
(def ^:private create-child-context
{:users [(factory :user)]
:commodities [{:symbol "USD"
:type :currency
:name "US Dollar"}]
:entities [{:name "Personal"}]
:accounts [{:name "Savings"
:type :asset}]})
(deftest create-a-child-account
(let [context (realize create-child-context)
savings (-> context :accounts first)
entity (-> context :entities first)
car (accounts/create {:name "Car"
:type :asset
:parent-id (:id savings)
:entity-id (:id entity)})]
(is (valid? car))))
(deftest child-must-have-same-type-as-parent
(let [context (realize create-child-context)
savings (-> context :accounts first)
entity (-> context :entities first)
result (accounts/create {:name "Federal income tax"
:type :expense
:parent-id (:id savings)
:entity-id (:id entity)})]
(is (invalid? result [:type] "Type must match the parent type"))))
(deftest name-is-required
(let [context (realize account-context)
attr (-> context
attributes
(dissoc :name))
result (accounts/create attr)]
(is (invalid? result [:name] "Name is required"))))
(deftest name-is-unique-within-a-parent
(let [context (realize duplicate-name-context)
entity (-> context :entities first)
auto (first (filter #(= "Auto" (:name %)) (:accounts context)))
attributes {:name "Repair"
:parent-id (:id auto)
:entity-id (:id entity)
:type :expense}]
(is (invalid? (accounts/create attributes) [:name] "Name is already in use"))))
(deftest correct-account-type
(let [context (realize account-context)
attr (assoc (attributes context) :type :invalidtype)]
(is (invalid? (accounts/create attr)
[:type]
"Type must be expense, equity, liability, income, or asset"))))
(deftest commodity-id-defaults-to-entity-default
(let [context (realize account-context)
commodity (-> context :commodities first)
account (-> context
attributes
(dissoc :commodity-id))
result (accounts/create account)]
(is (= (:id commodity) (:commodity-id result))
"The specified default commodity is used")))
(deftest update-an-account
(let [context (realize select-context)
account (find-account context "Checking")
result (accounts/update (assoc account :name "New name"))
retrieved (accounts/find account)]
(is (valid? result))
(is (= "New name" (:name result)) "The updated account is returned")
(is (= "New name" (:name retrieved)) "The updated account is retreived")))
(def same-parent-context
{:users [(factory :user)]
:entities [{:name "Personal"}]
:commodities [{:name "US Dollar"
:symbol "USD"
:type :currency}]
:accounts [{:name "Current assets"
:type :asset}
{:name "Fixed assets"
:type :asset}
{:name "House"
:type :asset
:parent-id "Current assets"}]})
(deftest change-an-account-parent
(let [context (realize same-parent-context)
[_ fixed house] (:accounts context)
updated (assoc house :parent-id (:id fixed))
result (accounts/update updated)
retrieved (accounts/reload updated)]
(is (valid? result))
(is (= (:id fixed)
(:parent-id result))
"The returned account has the correct parent-id value")
(is (= (:id fixed)
(:parent-id retrieved))
"The retrieved account has the correct parent-id value")))
(deftest delete-an-account
(let [context (realize select-context)
account (-> context :accounts first)
_ (accounts/delete account)
retrieved (accounts/find (:id account))]
(is (nil? retrieved) "The account cannot be retrieved after delete.")))
(defmacro test-polarization
[context account-type action quantity expected message]
`(let [account# (accounts/create (assoc (attributes ~context)
:type ~account-type))
item# {:account-id (:id account#)
:action ~action
:quantity ~quantity}
polarized# (polarize-quantity item# account#)]
(is (= ~expected polarized#) ~message)))
(deftest polarize-a-quantity
(let [context (realize account-context)]
; Debits
(test-polarization context :asset :debit 100M 100M "A debit in an asset account increases the balance")
(test-polarization context :expense :debit 100M 100M "A debit in an expense account increases the balance")
(test-polarization context :liability :debit 100M -100M "A debit in an liability account decreases the balance")
(test-polarization context :equity :debit 100M -100M "A debit in an equity account decreases the balance")
(test-polarization context :income :debit 100M -100M "A debit in an income account decreases the balance")
;; Credits
(test-polarization context :asset :credit 100M -100M "A credit in an asset account decreases the balance")
(test-polarization context :expense :credit 100M -100M "A credit in an expense account dereases the balance")
(test-polarization context :liability :credit 100M 100M "A credit in an liability account increases the balance")
(test-polarization context :equity :credit 100M 100M "A credit in an equity account increases the balance")
(test-polarization context :income :credit 100M 100M "A credit in an income account increases the balance")))
(deftest derive-action-from-quantity-and-account
(is (= :debit (derive-action 1 {:type :asset})))
(is (= :credit (derive-action -1 {:type :asset})))
(is (= :debit (derive-action 1 {:type :expense})))
(is (= :credit (derive-action -1 {:type :expense})))
(is (= :credit (derive-action 1 {:type :income})))
(is (= :debit (derive-action -1 {:type :income})))
(is (= :credit (derive-action 1 {:type :equity})))
(is (= :debit (derive-action -1 {:type :equity})))
(is (= :credit (derive-action 1 {:type :liability})))
(is (= :debit (derive-action -1 {:type :liability}))))
| 58972 | (ns clj-money.models.accounts-test
(:require [clojure.test :refer [deftest use-fixtures is]]
[clj-factory.core :refer [factory]]
[dgknght.app-lib.test]
[clj-money.factories.user-factory]
[clj-money.factories.entity-factory]
[clj-money.factories.account-factory]
[clj-money.test-context :refer [realize
find-entity
find-commodity
find-account]]
[clj-money.models.accounts :as accounts]
[clj-money.accounts :refer [polarize-quantity
derive-action]]
[clj-money.test-helpers :refer [reset-db]]))
(use-fixtures :each reset-db)
(def ^:private account-context
{:users [(factory :user)]
:commodities [{:symbol "USD"
:type :currency
:name "US Dollar"}]
:entities [{:name "Personal"}]})
(defn- attributes
[context]
{:name "Checking"
:type :asset
:entity-id (-> context :entities first :id)
:system-tags #{:something-special}})
(def ^:private select-context
{:users [(factory :user)]
:commodities [{:symbol "USD"
:type :currency
:name "US Dollar"
:entity-id "Personal"}]
:entities [{:name "Personal"}]
:accounts [{:name "<NAME>"
:type :liability}
{:name "Checking"
:type :asset}]})
(deftest select-accounts
(let [context (realize select-context)
entity-id (-> context :entities first :id)
actual (->> (accounts/search {:entity-id entity-id})
(map #(select-keys % [:name
:type
:system-tags
:quantity
:value
:entity-id
:commodity])))
expected [{:name "Checking"
:type :asset
:system-tags #{}
:quantity 0M
:value 0M
:entity-id entity-id}
{:name "Credit card"
:type :liability
:system-tags #{}
:quantity 0M
:value 0M
:entity-id entity-id}]]
(is (= expected actual) "It returns the correct accounts")))
(def ^:private nested-context
{:users [(factory :user)]
:commodities [{:symbol "USD"
:type :currency
:name "US Dollar"
:entity-id "Personal"}]
:entities [{:name "Personal"}]
:accounts [{:name "Savings"
:type :asset}
{:name "Reserve"
:type :asset
:parent-id "Savings"}
{:name "Car"
:type :asset
:parent-id "Savings"}
{:name "Doug"
:type :asset
:parent-id "Car"}
{:name "Eli"
:type :asset
:parent-id "Car"}
{:name "Checking"
:type :asset}
{:name "Taxes"
:type :expense}
{:name "Federal Income Tax"
:type :expense
:parent-id "Taxes"}
{:name "Social Security"
:type :expense
:parent-id "Taxes"}]})
(deftest select-account-with-children
(let [ctx (realize nested-context)
account (find-account ctx "Savings")
result (accounts/search {:id (:id account)}
{:include-children? true})]
(is (= #{"Savings" "Reserve" "Car" "Doug" "Eli"}
(set (map :name result))))))
(deftest create-an-account
(let [context (realize account-context)
result (accounts/create (attributes context))
entity (find-entity context "Personal")
usd (find-commodity context "USD")
accounts (->> (accounts/search {:entity-id (:id entity)})
(map #(select-keys % [:name
:type
:entity-id
:system-tags
:commodity-id
:quantity
:value])))
expected [{:name "Checking"
:type :asset
:entity-id (:id entity)
:system-tags #{:something-special}
:commodity-id (:id usd)
:quantity 0M
:value 0M}]]
(is (valid? result))
(is (= expected accounts) "The account can be retrieved")))
(def ^:private duplicate-name-context
{:users [(factory :user)]
:commodities [{:symbol "USD"
:name "US Dollar"
:type :currency
:entity-id "Personal"}
{:symbol "USD"
:name "US Dollar"
:entity-id "Business"
:type :currency}]
:entities [{:name "Personal"}
{:name "Business"}]
:accounts [{:name "<NAME>"
:type :liability
:entity-id "Personal"}
{:name "<NAME>"
:type :expense
:entity-id "Personal"}
{:name "<NAME>"
:type :expense
:entity-id "Personal"
:parent-id "Auto"}
{:name "<NAME>"
:type :expense
:entity-id "Personal"}
{:name "<NAME>"
:type :income
:entity-id "Personal"}]})
(deftest duplicate-name-across-entities
(let [context (realize duplicate-name-context)
business (first (filter #(= "Business" (:name %)) (:entities context)))
result (accounts/create {:name "<NAME>"
:type :liability
:entity-id (:id business)})]
(is (valid? result))))
(deftest duplicate-name-across-parents
(let [ctx (realize duplicate-name-context)
business (find-entity ctx "Personal")
household (find-account ctx "Household")
result (accounts/create {:name "<NAME>"
:type :expense
:parent-id (:id household)
:entity-id (:id business)})]
(is (valid? result))))
(deftest duplicate-name-with-nil-parent
(let [ctx (realize duplicate-name-context)
entity (find-entity ctx "Personal")
result (accounts/create {:name "<NAME>"
:type :expense
:entity-id (:id entity)})]
(is (valid? result))))
(deftest duplicate-name-across-asset-types
(let [context (realize duplicate-name-context)
entity (find-entity context "Personal")
result (accounts/create {:name "<NAME>"
:type :expense
:entity-id (:id entity)})]
(is (valid? result))))
(def ^:private create-child-context
{:users [(factory :user)]
:commodities [{:symbol "USD"
:type :currency
:name "US Dollar"}]
:entities [{:name "Personal"}]
:accounts [{:name "<NAME>"
:type :asset}]})
(deftest create-a-child-account
(let [context (realize create-child-context)
savings (-> context :accounts first)
entity (-> context :entities first)
car (accounts/create {:name "<NAME>"
:type :asset
:parent-id (:id savings)
:entity-id (:id entity)})]
(is (valid? car))))
(deftest child-must-have-same-type-as-parent
(let [context (realize create-child-context)
savings (-> context :accounts first)
entity (-> context :entities first)
result (accounts/create {:name "<NAME>"
:type :expense
:parent-id (:id savings)
:entity-id (:id entity)})]
(is (invalid? result [:type] "Type must match the parent type"))))
(deftest name-is-required
(let [context (realize account-context)
attr (-> context
attributes
(dissoc :name))
result (accounts/create attr)]
(is (invalid? result [:name] "Name is required"))))
(deftest name-is-unique-within-a-parent
(let [context (realize duplicate-name-context)
entity (-> context :entities first)
auto (first (filter #(= "Auto" (:name %)) (:accounts context)))
attributes {:name "Repair"
:parent-id (:id auto)
:entity-id (:id entity)
:type :expense}]
(is (invalid? (accounts/create attributes) [:name] "Name is already in use"))))
(deftest correct-account-type
(let [context (realize account-context)
attr (assoc (attributes context) :type :invalidtype)]
(is (invalid? (accounts/create attr)
[:type]
"Type must be expense, equity, liability, income, or asset"))))
(deftest commodity-id-defaults-to-entity-default
(let [context (realize account-context)
commodity (-> context :commodities first)
account (-> context
attributes
(dissoc :commodity-id))
result (accounts/create account)]
(is (= (:id commodity) (:commodity-id result))
"The specified default commodity is used")))
(deftest update-an-account
(let [context (realize select-context)
account (find-account context "Checking")
result (accounts/update (assoc account :name "<NAME>"))
retrieved (accounts/find account)]
(is (valid? result))
(is (= "New name" (:name result)) "The updated account is returned")
(is (= "New name" (:name retrieved)) "The updated account is retreived")))
(def same-parent-context
{:users [(factory :user)]
:entities [{:name "Personal"}]
:commodities [{:name "US Dollar"
:symbol "USD"
:type :currency}]
:accounts [{:name "Current assets"
:type :asset}
{:name "Fixed assets"
:type :asset}
{:name "House"
:type :asset
:parent-id "Current assets"}]})
(deftest change-an-account-parent
(let [context (realize same-parent-context)
[_ fixed house] (:accounts context)
updated (assoc house :parent-id (:id fixed))
result (accounts/update updated)
retrieved (accounts/reload updated)]
(is (valid? result))
(is (= (:id fixed)
(:parent-id result))
"The returned account has the correct parent-id value")
(is (= (:id fixed)
(:parent-id retrieved))
"The retrieved account has the correct parent-id value")))
(deftest delete-an-account
(let [context (realize select-context)
account (-> context :accounts first)
_ (accounts/delete account)
retrieved (accounts/find (:id account))]
(is (nil? retrieved) "The account cannot be retrieved after delete.")))
(defmacro test-polarization
[context account-type action quantity expected message]
`(let [account# (accounts/create (assoc (attributes ~context)
:type ~account-type))
item# {:account-id (:id account#)
:action ~action
:quantity ~quantity}
polarized# (polarize-quantity item# account#)]
(is (= ~expected polarized#) ~message)))
(deftest polarize-a-quantity
(let [context (realize account-context)]
; Debits
(test-polarization context :asset :debit 100M 100M "A debit in an asset account increases the balance")
(test-polarization context :expense :debit 100M 100M "A debit in an expense account increases the balance")
(test-polarization context :liability :debit 100M -100M "A debit in an liability account decreases the balance")
(test-polarization context :equity :debit 100M -100M "A debit in an equity account decreases the balance")
(test-polarization context :income :debit 100M -100M "A debit in an income account decreases the balance")
;; Credits
(test-polarization context :asset :credit 100M -100M "A credit in an asset account decreases the balance")
(test-polarization context :expense :credit 100M -100M "A credit in an expense account dereases the balance")
(test-polarization context :liability :credit 100M 100M "A credit in an liability account increases the balance")
(test-polarization context :equity :credit 100M 100M "A credit in an equity account increases the balance")
(test-polarization context :income :credit 100M 100M "A credit in an income account increases the balance")))
(deftest derive-action-from-quantity-and-account
(is (= :debit (derive-action 1 {:type :asset})))
(is (= :credit (derive-action -1 {:type :asset})))
(is (= :debit (derive-action 1 {:type :expense})))
(is (= :credit (derive-action -1 {:type :expense})))
(is (= :credit (derive-action 1 {:type :income})))
(is (= :debit (derive-action -1 {:type :income})))
(is (= :credit (derive-action 1 {:type :equity})))
(is (= :debit (derive-action -1 {:type :equity})))
(is (= :credit (derive-action 1 {:type :liability})))
(is (= :debit (derive-action -1 {:type :liability}))))
| true | (ns clj-money.models.accounts-test
(:require [clojure.test :refer [deftest use-fixtures is]]
[clj-factory.core :refer [factory]]
[dgknght.app-lib.test]
[clj-money.factories.user-factory]
[clj-money.factories.entity-factory]
[clj-money.factories.account-factory]
[clj-money.test-context :refer [realize
find-entity
find-commodity
find-account]]
[clj-money.models.accounts :as accounts]
[clj-money.accounts :refer [polarize-quantity
derive-action]]
[clj-money.test-helpers :refer [reset-db]]))
(use-fixtures :each reset-db)
(def ^:private account-context
{:users [(factory :user)]
:commodities [{:symbol "USD"
:type :currency
:name "US Dollar"}]
:entities [{:name "Personal"}]})
(defn- attributes
[context]
{:name "Checking"
:type :asset
:entity-id (-> context :entities first :id)
:system-tags #{:something-special}})
(def ^:private select-context
{:users [(factory :user)]
:commodities [{:symbol "USD"
:type :currency
:name "US Dollar"
:entity-id "Personal"}]
:entities [{:name "Personal"}]
:accounts [{:name "PI:NAME:<NAME>END_PI"
:type :liability}
{:name "Checking"
:type :asset}]})
(deftest select-accounts
(let [context (realize select-context)
entity-id (-> context :entities first :id)
actual (->> (accounts/search {:entity-id entity-id})
(map #(select-keys % [:name
:type
:system-tags
:quantity
:value
:entity-id
:commodity])))
expected [{:name "Checking"
:type :asset
:system-tags #{}
:quantity 0M
:value 0M
:entity-id entity-id}
{:name "Credit card"
:type :liability
:system-tags #{}
:quantity 0M
:value 0M
:entity-id entity-id}]]
(is (= expected actual) "It returns the correct accounts")))
(def ^:private nested-context
{:users [(factory :user)]
:commodities [{:symbol "USD"
:type :currency
:name "US Dollar"
:entity-id "Personal"}]
:entities [{:name "Personal"}]
:accounts [{:name "Savings"
:type :asset}
{:name "Reserve"
:type :asset
:parent-id "Savings"}
{:name "Car"
:type :asset
:parent-id "Savings"}
{:name "Doug"
:type :asset
:parent-id "Car"}
{:name "Eli"
:type :asset
:parent-id "Car"}
{:name "Checking"
:type :asset}
{:name "Taxes"
:type :expense}
{:name "Federal Income Tax"
:type :expense
:parent-id "Taxes"}
{:name "Social Security"
:type :expense
:parent-id "Taxes"}]})
(deftest select-account-with-children
(let [ctx (realize nested-context)
account (find-account ctx "Savings")
result (accounts/search {:id (:id account)}
{:include-children? true})]
(is (= #{"Savings" "Reserve" "Car" "Doug" "Eli"}
(set (map :name result))))))
(deftest create-an-account
(let [context (realize account-context)
result (accounts/create (attributes context))
entity (find-entity context "Personal")
usd (find-commodity context "USD")
accounts (->> (accounts/search {:entity-id (:id entity)})
(map #(select-keys % [:name
:type
:entity-id
:system-tags
:commodity-id
:quantity
:value])))
expected [{:name "Checking"
:type :asset
:entity-id (:id entity)
:system-tags #{:something-special}
:commodity-id (:id usd)
:quantity 0M
:value 0M}]]
(is (valid? result))
(is (= expected accounts) "The account can be retrieved")))
(def ^:private duplicate-name-context
{:users [(factory :user)]
:commodities [{:symbol "USD"
:name "US Dollar"
:type :currency
:entity-id "Personal"}
{:symbol "USD"
:name "US Dollar"
:entity-id "Business"
:type :currency}]
:entities [{:name "Personal"}
{:name "Business"}]
:accounts [{:name "PI:NAME:<NAME>END_PI"
:type :liability
:entity-id "Personal"}
{:name "PI:NAME:<NAME>END_PI"
:type :expense
:entity-id "Personal"}
{:name "PI:NAME:<NAME>END_PI"
:type :expense
:entity-id "Personal"
:parent-id "Auto"}
{:name "PI:NAME:<NAME>END_PI"
:type :expense
:entity-id "Personal"}
{:name "PI:NAME:<NAME>END_PI"
:type :income
:entity-id "Personal"}]})
(deftest duplicate-name-across-entities
(let [context (realize duplicate-name-context)
business (first (filter #(= "Business" (:name %)) (:entities context)))
result (accounts/create {:name "PI:NAME:<NAME>END_PI"
:type :liability
:entity-id (:id business)})]
(is (valid? result))))
(deftest duplicate-name-across-parents
(let [ctx (realize duplicate-name-context)
business (find-entity ctx "Personal")
household (find-account ctx "Household")
result (accounts/create {:name "PI:NAME:<NAME>END_PI"
:type :expense
:parent-id (:id household)
:entity-id (:id business)})]
(is (valid? result))))
(deftest duplicate-name-with-nil-parent
(let [ctx (realize duplicate-name-context)
entity (find-entity ctx "Personal")
result (accounts/create {:name "PI:NAME:<NAME>END_PI"
:type :expense
:entity-id (:id entity)})]
(is (valid? result))))
(deftest duplicate-name-across-asset-types
(let [context (realize duplicate-name-context)
entity (find-entity context "Personal")
result (accounts/create {:name "PI:NAME:<NAME>END_PI"
:type :expense
:entity-id (:id entity)})]
(is (valid? result))))
(def ^:private create-child-context
{:users [(factory :user)]
:commodities [{:symbol "USD"
:type :currency
:name "US Dollar"}]
:entities [{:name "Personal"}]
:accounts [{:name "PI:NAME:<NAME>END_PI"
:type :asset}]})
(deftest create-a-child-account
(let [context (realize create-child-context)
savings (-> context :accounts first)
entity (-> context :entities first)
car (accounts/create {:name "PI:NAME:<NAME>END_PI"
:type :asset
:parent-id (:id savings)
:entity-id (:id entity)})]
(is (valid? car))))
(deftest child-must-have-same-type-as-parent
(let [context (realize create-child-context)
savings (-> context :accounts first)
entity (-> context :entities first)
result (accounts/create {:name "PI:NAME:<NAME>END_PI"
:type :expense
:parent-id (:id savings)
:entity-id (:id entity)})]
(is (invalid? result [:type] "Type must match the parent type"))))
(deftest name-is-required
(let [context (realize account-context)
attr (-> context
attributes
(dissoc :name))
result (accounts/create attr)]
(is (invalid? result [:name] "Name is required"))))
(deftest name-is-unique-within-a-parent
(let [context (realize duplicate-name-context)
entity (-> context :entities first)
auto (first (filter #(= "Auto" (:name %)) (:accounts context)))
attributes {:name "Repair"
:parent-id (:id auto)
:entity-id (:id entity)
:type :expense}]
(is (invalid? (accounts/create attributes) [:name] "Name is already in use"))))
(deftest correct-account-type
(let [context (realize account-context)
attr (assoc (attributes context) :type :invalidtype)]
(is (invalid? (accounts/create attr)
[:type]
"Type must be expense, equity, liability, income, or asset"))))
(deftest commodity-id-defaults-to-entity-default
(let [context (realize account-context)
commodity (-> context :commodities first)
account (-> context
attributes
(dissoc :commodity-id))
result (accounts/create account)]
(is (= (:id commodity) (:commodity-id result))
"The specified default commodity is used")))
(deftest update-an-account
(let [context (realize select-context)
account (find-account context "Checking")
result (accounts/update (assoc account :name "PI:NAME:<NAME>END_PI"))
retrieved (accounts/find account)]
(is (valid? result))
(is (= "New name" (:name result)) "The updated account is returned")
(is (= "New name" (:name retrieved)) "The updated account is retreived")))
(def same-parent-context
{:users [(factory :user)]
:entities [{:name "Personal"}]
:commodities [{:name "US Dollar"
:symbol "USD"
:type :currency}]
:accounts [{:name "Current assets"
:type :asset}
{:name "Fixed assets"
:type :asset}
{:name "House"
:type :asset
:parent-id "Current assets"}]})
(deftest change-an-account-parent
(let [context (realize same-parent-context)
[_ fixed house] (:accounts context)
updated (assoc house :parent-id (:id fixed))
result (accounts/update updated)
retrieved (accounts/reload updated)]
(is (valid? result))
(is (= (:id fixed)
(:parent-id result))
"The returned account has the correct parent-id value")
(is (= (:id fixed)
(:parent-id retrieved))
"The retrieved account has the correct parent-id value")))
(deftest delete-an-account
(let [context (realize select-context)
account (-> context :accounts first)
_ (accounts/delete account)
retrieved (accounts/find (:id account))]
(is (nil? retrieved) "The account cannot be retrieved after delete.")))
(defmacro test-polarization
[context account-type action quantity expected message]
`(let [account# (accounts/create (assoc (attributes ~context)
:type ~account-type))
item# {:account-id (:id account#)
:action ~action
:quantity ~quantity}
polarized# (polarize-quantity item# account#)]
(is (= ~expected polarized#) ~message)))
(deftest polarize-a-quantity
(let [context (realize account-context)]
; Debits
(test-polarization context :asset :debit 100M 100M "A debit in an asset account increases the balance")
(test-polarization context :expense :debit 100M 100M "A debit in an expense account increases the balance")
(test-polarization context :liability :debit 100M -100M "A debit in an liability account decreases the balance")
(test-polarization context :equity :debit 100M -100M "A debit in an equity account decreases the balance")
(test-polarization context :income :debit 100M -100M "A debit in an income account decreases the balance")
;; Credits
(test-polarization context :asset :credit 100M -100M "A credit in an asset account decreases the balance")
(test-polarization context :expense :credit 100M -100M "A credit in an expense account dereases the balance")
(test-polarization context :liability :credit 100M 100M "A credit in an liability account increases the balance")
(test-polarization context :equity :credit 100M 100M "A credit in an equity account increases the balance")
(test-polarization context :income :credit 100M 100M "A credit in an income account increases the balance")))
(deftest derive-action-from-quantity-and-account
(is (= :debit (derive-action 1 {:type :asset})))
(is (= :credit (derive-action -1 {:type :asset})))
(is (= :debit (derive-action 1 {:type :expense})))
(is (= :credit (derive-action -1 {:type :expense})))
(is (= :credit (derive-action 1 {:type :income})))
(is (= :debit (derive-action -1 {:type :income})))
(is (= :credit (derive-action 1 {:type :equity})))
(is (= :debit (derive-action -1 {:type :equity})))
(is (= :credit (derive-action 1 {:type :liability})))
(is (= :debit (derive-action -1 {:type :liability}))))
|
[
{
"context": "ef ^:private user->info\n {:rasta {:email \"rasta@metabase.com\"\n :first \"Rasta\"\n ",
"end": 1227,
"score": 0.9999285936355591,
"start": 1209,
"tag": "EMAIL",
"value": "rasta@metabase.com"
},
{
"context": " :last \"Toucan\"\n :password \"blueberries\"}\n :crowberto {:email \"crowberto@metabase.c",
"end": 1333,
"score": 0.9994361996650696,
"start": 1322,
"tag": "PASSWORD",
"value": "blueberries"
},
{
"context": "assword \"blueberries\"}\n :crowberto {:email \"crowberto@metabase.com\"\n :first \"Crowberto\"\n ",
"end": 1385,
"score": 0.9999258518218994,
"start": 1363,
"tag": "EMAIL",
"value": "crowberto@metabase.com"
},
{
"context": "owberto@metabase.com\"\n :first \"Crowberto\"\n :last \"Corv\"\n ",
"end": 1423,
"score": 0.5342711210250854,
"start": 1415,
"tag": "NAME",
"value": "rowberto"
},
{
"context": " :last \"Corv\"\n :password \"blackjet\"\n :superuser true}\n :lucky {:",
"end": 1493,
"score": 0.9994977712631226,
"start": 1485,
"tag": "PASSWORD",
"value": "blackjet"
},
{
"context": " :superuser true}\n :lucky {:email \"lucky@metabase.com\"\n :first \"Lucky\"\n ",
"end": 1571,
"score": 0.9999269247055054,
"start": 1553,
"tag": "EMAIL",
"value": "lucky@metabase.com"
},
{
"context": " :last \"Pigeon\"\n :password \"almonds\"}\n :trashbird {:email \"trashbird@metabase.co",
"end": 1673,
"score": 0.9994730353355408,
"start": 1666,
"tag": "PASSWORD",
"value": "almonds"
},
{
"context": " :password \"almonds\"}\n :trashbird {:email \"trashbird@metabase.com\"\n :first \"Trash\"\n ",
"end": 1724,
"score": 0.9999262690544128,
"start": 1702,
"tag": "EMAIL",
"value": "trashbird@metabase.com"
},
{
"context": " :last \"Bird\"\n :password \"birdseed\"\n :active false}})\n\n(def username",
"end": 1825,
"score": 0.999518871307373,
"start": 1817,
"tag": "PASSWORD",
"value": "birdseed"
},
{
"context": " :last_name last\n :password password\n :is_superuser superuser\n ",
"end": 2750,
"score": 0.9990664124488831,
"start": 2742,
"tag": "PASSWORD",
"value": "password"
},
{
"context": ":id 100 :first_name \\\"Rasta\\\" ...}\"\n [username :- TestUserName]\n (m/mapply fetch-or-create-user! (user->info us",
"end": 3067,
"score": 0.9554396271705627,
"start": 3055,
"tag": "USERNAME",
"value": "TestUserName"
},
{
"context": ".\n\n (user->credentials :rasta) -> {:username \\\"rasta@metabase.com\\\", :password \\\"blueberries\\\"}\"\n [username :- Tes",
"end": 3804,
"score": 0.9999097585678101,
"start": 3786,
"tag": "EMAIL",
"value": "rasta@metabase.com"
},
{
"context": "-> {:username \\\"rasta@metabase.com\\\", :password \\\"blueberries\\\"}\"\n [username :- TestUserName]\n {:pre [(contai",
"end": 3831,
"score": 0.999424934387207,
"start": 3820,
"tag": "PASSWORD",
"value": "blueberries"
},
{
"context": ".com\\\", :password \\\"blueberries\\\"}\"\n [username :- TestUserName]\n {:pre [(contains? usernames username)]}\n (let",
"end": 3863,
"score": 0.9752687215805054,
"start": 3851,
"tag": "USERNAME",
"value": "TestUserName"
},
{
"context": "nfo username)]\n {:username email\n :password password}))\n\n(def ^{:arglists '([id])} id->user\n \"Reverse",
"end": 4007,
"score": 0.9968997836112976,
"start": 3999,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " User, logging in first if needed.\"\n [username :- TestUserName]\n (or (@tokens username)\n (locking tokens\n ",
"end": 4378,
"score": 0.9894907474517822,
"start": 4366,
"tag": "USERNAME",
"value": "TestUserName"
},
{
"context": "easier to\n use when writing code.\"\n [username :- TestUserName]\n (fetch-user username) ; force creation of the ",
"end": 5830,
"score": 0.9969679117202759,
"start": 5818,
"tag": "USERNAME",
"value": "TestUserName"
},
{
"context": "ay be either a\n redefined test User name, e.g. `:rasta`, or any User or User ID. (Because we don't have ",
"end": 6122,
"score": 0.9204851984977722,
"start": 6117,
"tag": "USERNAME",
"value": "rasta"
}
] | c#-metabase/test/metabase/test/data/users.clj | hanakhry/Crime_Admin | 0 | (ns metabase.test.data.users
"Code related to creating / managing fake `Users` for testing purposes."
(:require [cemerick.friend.credentials :as creds]
[clojure.test :as t]
[medley.core :as m]
[metabase.http-client :as http]
[metabase.models.permissions-group :refer [PermissionsGroup]]
[metabase.models.permissions-group-membership :refer [PermissionsGroupMembership]]
[metabase.models.user :refer [User]]
[metabase.server.middleware.session :as mw.session]
[metabase.test.initialize :as initialize]
[metabase.util :as u]
[schema.core :as s]
[toucan.db :as db]
[toucan.util.test :as tt])
(:import clojure.lang.ExceptionInfo
metabase.models.user.UserInstance))
;;; ------------------------------------------------ User Definitions ------------------------------------------------
;; ## Test Users
;;
;; These users have permissions for the Test. They are lazily created as needed.
;; Three test users are defined:
;; * rasta
;; * crowberto - superuser
;; * lucky
;; * trashbird - inactive
(def ^:private user->info
{:rasta {:email "rasta@metabase.com"
:first "Rasta"
:last "Toucan"
:password "blueberries"}
:crowberto {:email "crowberto@metabase.com"
:first "Crowberto"
:last "Corv"
:password "blackjet"
:superuser true}
:lucky {:email "lucky@metabase.com"
:first "Lucky"
:last "Pigeon"
:password "almonds"}
:trashbird {:email "trashbird@metabase.com"
:first "Trash"
:last "Bird"
:password "birdseed"
:active false}})
(def usernames
(set (keys user->info)))
(def ^:private TestUserName
(apply s/enum usernames))
;;; ------------------------------------------------- Test User Fns --------------------------------------------------
(def ^:private create-user-lock (Object.))
(defn- fetch-or-create-user!
"Create User if they don't already exist and return User."
[& {:keys [email first last password superuser active]
:or {superuser false
active true}}]
{:pre [(string? email) (string? first) (string? last) (string? password) (m/boolean? superuser) (m/boolean? active)]}
(initialize/initialize-if-needed! :db)
(or (User :email email)
(locking create-user-lock
(or (User :email email)
(db/insert! User
:email email
:first_name first
:last_name last
:password password
:is_superuser superuser
:is_qbnewb true
:is_active active)))))
(s/defn fetch-user :- UserInstance
"Fetch the User object associated with `username`. Creates user if needed.
(fetch-user :rasta) -> {:id 100 :first_name \"Rasta\" ...}"
[username :- TestUserName]
(m/mapply fetch-or-create-user! (user->info username)))
(def ^{:arglists '([] [user-name])} user->id
"Creates user if needed. With zero args, returns map of user name to ID. With 1 arg, returns ID of that User. Creates
User(s) if needed. Memoized.
(user->id) ; -> {:rasta 4, ...}
(user->id :rasta) ; -> 4"
(memoize
(fn
([]
(zipmap usernames (map user->id usernames)))
([user-name]
{:pre [(contains? usernames user-name)]}
(u/the-id (fetch-user user-name))))))
(s/defn user->credentials :- {:username (s/pred u/email?), :password s/Str}
"Return a map with `:username` and `:password` for User with `username`.
(user->credentials :rasta) -> {:username \"rasta@metabase.com\", :password \"blueberries\"}"
[username :- TestUserName]
{:pre [(contains? usernames username)]}
(let [{:keys [email password]} (user->info username)]
{:username email
:password password}))
(def ^{:arglists '([id])} id->user
"Reverse of `user->id`.
(id->user 4) -> :rasta"
(let [m (delay (zipmap (map user->id usernames) usernames))]
(fn [id]
(@m id))))
(defonce ^:private tokens (atom {}))
(s/defn username->token :- u/uuid-regex
"Return cached session token for a test User, logging in first if needed."
[username :- TestUserName]
(or (@tokens username)
(locking tokens
(or (@tokens username)
(u/prog1 (http/authenticate (user->credentials username))
(swap! tokens assoc username <>))))
(throw (Exception. (format "Authentication failed for %s with credentials %s"
username (user->credentials username))))))
(defn clear-cached-session-tokens!
"Clear any cached session tokens, which may have expired or been removed. You should do this in the even you get a
`401` unauthenticated response, and then retry the request."
[]
(locking tokens
(reset! tokens {})))
(defn- client-fn [username & args]
(try
(apply http/client (username->token username) args)
(catch ExceptionInfo e
(let [{:keys [status-code]} (ex-data e)]
(when-not (= status-code 401)
(throw e))
;; If we got a 401 unauthenticated clear the tokens cache + recur
(clear-cached-session-tokens!)
(apply client-fn username args)))))
(s/defn ^:deprecated user->client :- (s/pred fn?)
"Returns a `metabase.http-client/client` partially bound with the credentials for User with `username`.
In addition, it forces lazy creation of the User if needed.
((user->client) :get 200 \"meta/table\")
DEPRECATED -- use `user-http-request` instead, which has proper `:arglists` metadata which makes it a bit easier to
use when writing code."
[username :- TestUserName]
(fetch-user username) ; force creation of the user if not already created
(partial client-fn username))
(defn user-http-request
"A version of our test HTTP client that issues the request with credentials for a given User. User may be either a
redefined test User name, e.g. `:rasta`, or any User or User ID. (Because we don't have the User's original
password, this function temporarily overrides the password for that User.)"
{:arglists '([test-user-name-or-user-or-id method expected-status-code? endpoint
request-options? http-body-map? & {:as query-params}])}
[user & args]
(if (keyword? user)
(do
(fetch-user user)
(apply client-fn user args))
(let [user-id (u/the-id user)
user-email (db/select-one-field :email User :id user-id)
[old-password-info] (db/simple-select User {:select [:password :password_salt]
:where [:= :id user-id]})]
(when-not user-email
(throw (ex-info "User does not exist" {:user user})))
(try
(db/execute! {:update User
:set {:password (creds/hash-bcrypt user-email)
:password_salt ""}
:where [:= :id user-id]})
(apply http/client {:username user-email, :password user-email} args)
(finally
(db/execute! {:update User
:set old-password-info
:where [:= :id user-id]}))))))
(defn do-with-test-user [user-kwd thunk]
(t/testing (format "with test user %s\n" user-kwd)
(mw.session/with-current-user (some-> user-kwd user->id)
(thunk))))
(defmacro with-test-user
"Call `body` with various `metabase.api.common` dynamic vars like `*current-user*` bound to the predefined test User
named by `user-kwd`. If you want to bind a non-predefined-test User, use `mt/with-current-user` instead."
{:style/indent 1}
[user-kwd & body]
`(do-with-test-user ~user-kwd (fn [] ~@body)))
(defn test-user?
"Does this User or User ID belong to one of the predefined test birds?"
[user-or-id]
(contains? (set (vals (user->id))) (u/the-id user-or-id)))
(defn test-user-name-or-user-id->user-id [test-user-name-or-user-id]
(if (keyword? test-user-name-or-user-id)
(user->id test-user-name-or-user-id)
(u/the-id test-user-name-or-user-id)))
(defn do-with-group-for-user [group test-user-name-or-user-id f]
(tt/with-temp* [PermissionsGroup [group group]
PermissionsGroupMembership [_ {:group_id (u/the-id group)
:user_id (test-user-name-or-user-id->user-id test-user-name-or-user-id)}]]
(f group)))
(defmacro with-group
"Create a new PermissionsGroup, bound to `group-binding`; add test user Rasta Toucan [RIP] to the
group, then execute `body`."
[[group-binding group] & body]
`(do-with-group-for-user ~group :rasta (fn [~group-binding] ~@body)))
(defmacro with-group-for-user
"Like `with-group`, but for any test user (by passing in a test username keyword e.g. `:rasta`) or User ID."
[[group-binding test-user-name-or-user-id group] & body]
`(do-with-group-for-user ~group ~test-user-name-or-user-id (fn [~group-binding] ~@body)))
| 3742 | (ns metabase.test.data.users
"Code related to creating / managing fake `Users` for testing purposes."
(:require [cemerick.friend.credentials :as creds]
[clojure.test :as t]
[medley.core :as m]
[metabase.http-client :as http]
[metabase.models.permissions-group :refer [PermissionsGroup]]
[metabase.models.permissions-group-membership :refer [PermissionsGroupMembership]]
[metabase.models.user :refer [User]]
[metabase.server.middleware.session :as mw.session]
[metabase.test.initialize :as initialize]
[metabase.util :as u]
[schema.core :as s]
[toucan.db :as db]
[toucan.util.test :as tt])
(:import clojure.lang.ExceptionInfo
metabase.models.user.UserInstance))
;;; ------------------------------------------------ User Definitions ------------------------------------------------
;; ## Test Users
;;
;; These users have permissions for the Test. They are lazily created as needed.
;; Three test users are defined:
;; * rasta
;; * crowberto - superuser
;; * lucky
;; * trashbird - inactive
(def ^:private user->info
{:rasta {:email "<EMAIL>"
:first "Rasta"
:last "Toucan"
:password "<PASSWORD>"}
:crowberto {:email "<EMAIL>"
:first "C<NAME>"
:last "Corv"
:password "<PASSWORD>"
:superuser true}
:lucky {:email "<EMAIL>"
:first "Lucky"
:last "Pigeon"
:password "<PASSWORD>"}
:trashbird {:email "<EMAIL>"
:first "Trash"
:last "Bird"
:password "<PASSWORD>"
:active false}})
(def usernames
(set (keys user->info)))
(def ^:private TestUserName
(apply s/enum usernames))
;;; ------------------------------------------------- Test User Fns --------------------------------------------------
(def ^:private create-user-lock (Object.))
(defn- fetch-or-create-user!
"Create User if they don't already exist and return User."
[& {:keys [email first last password superuser active]
:or {superuser false
active true}}]
{:pre [(string? email) (string? first) (string? last) (string? password) (m/boolean? superuser) (m/boolean? active)]}
(initialize/initialize-if-needed! :db)
(or (User :email email)
(locking create-user-lock
(or (User :email email)
(db/insert! User
:email email
:first_name first
:last_name last
:password <PASSWORD>
:is_superuser superuser
:is_qbnewb true
:is_active active)))))
(s/defn fetch-user :- UserInstance
"Fetch the User object associated with `username`. Creates user if needed.
(fetch-user :rasta) -> {:id 100 :first_name \"Rasta\" ...}"
[username :- TestUserName]
(m/mapply fetch-or-create-user! (user->info username)))
(def ^{:arglists '([] [user-name])} user->id
"Creates user if needed. With zero args, returns map of user name to ID. With 1 arg, returns ID of that User. Creates
User(s) if needed. Memoized.
(user->id) ; -> {:rasta 4, ...}
(user->id :rasta) ; -> 4"
(memoize
(fn
([]
(zipmap usernames (map user->id usernames)))
([user-name]
{:pre [(contains? usernames user-name)]}
(u/the-id (fetch-user user-name))))))
(s/defn user->credentials :- {:username (s/pred u/email?), :password s/Str}
"Return a map with `:username` and `:password` for User with `username`.
(user->credentials :rasta) -> {:username \"<EMAIL>\", :password \"<PASSWORD>\"}"
[username :- TestUserName]
{:pre [(contains? usernames username)]}
(let [{:keys [email password]} (user->info username)]
{:username email
:password <PASSWORD>}))
(def ^{:arglists '([id])} id->user
"Reverse of `user->id`.
(id->user 4) -> :rasta"
(let [m (delay (zipmap (map user->id usernames) usernames))]
(fn [id]
(@m id))))
(defonce ^:private tokens (atom {}))
(s/defn username->token :- u/uuid-regex
"Return cached session token for a test User, logging in first if needed."
[username :- TestUserName]
(or (@tokens username)
(locking tokens
(or (@tokens username)
(u/prog1 (http/authenticate (user->credentials username))
(swap! tokens assoc username <>))))
(throw (Exception. (format "Authentication failed for %s with credentials %s"
username (user->credentials username))))))
(defn clear-cached-session-tokens!
"Clear any cached session tokens, which may have expired or been removed. You should do this in the even you get a
`401` unauthenticated response, and then retry the request."
[]
(locking tokens
(reset! tokens {})))
(defn- client-fn [username & args]
(try
(apply http/client (username->token username) args)
(catch ExceptionInfo e
(let [{:keys [status-code]} (ex-data e)]
(when-not (= status-code 401)
(throw e))
;; If we got a 401 unauthenticated clear the tokens cache + recur
(clear-cached-session-tokens!)
(apply client-fn username args)))))
(s/defn ^:deprecated user->client :- (s/pred fn?)
"Returns a `metabase.http-client/client` partially bound with the credentials for User with `username`.
In addition, it forces lazy creation of the User if needed.
((user->client) :get 200 \"meta/table\")
DEPRECATED -- use `user-http-request` instead, which has proper `:arglists` metadata which makes it a bit easier to
use when writing code."
[username :- TestUserName]
(fetch-user username) ; force creation of the user if not already created
(partial client-fn username))
(defn user-http-request
"A version of our test HTTP client that issues the request with credentials for a given User. User may be either a
redefined test User name, e.g. `:rasta`, or any User or User ID. (Because we don't have the User's original
password, this function temporarily overrides the password for that User.)"
{:arglists '([test-user-name-or-user-or-id method expected-status-code? endpoint
request-options? http-body-map? & {:as query-params}])}
[user & args]
(if (keyword? user)
(do
(fetch-user user)
(apply client-fn user args))
(let [user-id (u/the-id user)
user-email (db/select-one-field :email User :id user-id)
[old-password-info] (db/simple-select User {:select [:password :password_salt]
:where [:= :id user-id]})]
(when-not user-email
(throw (ex-info "User does not exist" {:user user})))
(try
(db/execute! {:update User
:set {:password (creds/hash-bcrypt user-email)
:password_salt ""}
:where [:= :id user-id]})
(apply http/client {:username user-email, :password user-email} args)
(finally
(db/execute! {:update User
:set old-password-info
:where [:= :id user-id]}))))))
(defn do-with-test-user [user-kwd thunk]
(t/testing (format "with test user %s\n" user-kwd)
(mw.session/with-current-user (some-> user-kwd user->id)
(thunk))))
(defmacro with-test-user
"Call `body` with various `metabase.api.common` dynamic vars like `*current-user*` bound to the predefined test User
named by `user-kwd`. If you want to bind a non-predefined-test User, use `mt/with-current-user` instead."
{:style/indent 1}
[user-kwd & body]
`(do-with-test-user ~user-kwd (fn [] ~@body)))
(defn test-user?
"Does this User or User ID belong to one of the predefined test birds?"
[user-or-id]
(contains? (set (vals (user->id))) (u/the-id user-or-id)))
(defn test-user-name-or-user-id->user-id [test-user-name-or-user-id]
(if (keyword? test-user-name-or-user-id)
(user->id test-user-name-or-user-id)
(u/the-id test-user-name-or-user-id)))
(defn do-with-group-for-user [group test-user-name-or-user-id f]
(tt/with-temp* [PermissionsGroup [group group]
PermissionsGroupMembership [_ {:group_id (u/the-id group)
:user_id (test-user-name-or-user-id->user-id test-user-name-or-user-id)}]]
(f group)))
(defmacro with-group
"Create a new PermissionsGroup, bound to `group-binding`; add test user Rasta Toucan [RIP] to the
group, then execute `body`."
[[group-binding group] & body]
`(do-with-group-for-user ~group :rasta (fn [~group-binding] ~@body)))
(defmacro with-group-for-user
"Like `with-group`, but for any test user (by passing in a test username keyword e.g. `:rasta`) or User ID."
[[group-binding test-user-name-or-user-id group] & body]
`(do-with-group-for-user ~group ~test-user-name-or-user-id (fn [~group-binding] ~@body)))
| true | (ns metabase.test.data.users
"Code related to creating / managing fake `Users` for testing purposes."
(:require [cemerick.friend.credentials :as creds]
[clojure.test :as t]
[medley.core :as m]
[metabase.http-client :as http]
[metabase.models.permissions-group :refer [PermissionsGroup]]
[metabase.models.permissions-group-membership :refer [PermissionsGroupMembership]]
[metabase.models.user :refer [User]]
[metabase.server.middleware.session :as mw.session]
[metabase.test.initialize :as initialize]
[metabase.util :as u]
[schema.core :as s]
[toucan.db :as db]
[toucan.util.test :as tt])
(:import clojure.lang.ExceptionInfo
metabase.models.user.UserInstance))
;;; ------------------------------------------------ User Definitions ------------------------------------------------
;; ## Test Users
;;
;; These users have permissions for the Test. They are lazily created as needed.
;; Three test users are defined:
;; * rasta
;; * crowberto - superuser
;; * lucky
;; * trashbird - inactive
(def ^:private user->info
{:rasta {:email "PI:EMAIL:<EMAIL>END_PI"
:first "Rasta"
:last "Toucan"
:password "PI:PASSWORD:<PASSWORD>END_PI"}
:crowberto {:email "PI:EMAIL:<EMAIL>END_PI"
:first "CPI:NAME:<NAME>END_PI"
:last "Corv"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:superuser true}
:lucky {:email "PI:EMAIL:<EMAIL>END_PI"
:first "Lucky"
:last "Pigeon"
:password "PI:PASSWORD:<PASSWORD>END_PI"}
:trashbird {:email "PI:EMAIL:<EMAIL>END_PI"
:first "Trash"
:last "Bird"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:active false}})
(def usernames
(set (keys user->info)))
(def ^:private TestUserName
(apply s/enum usernames))
;;; ------------------------------------------------- Test User Fns --------------------------------------------------
(def ^:private create-user-lock (Object.))
(defn- fetch-or-create-user!
"Create User if they don't already exist and return User."
[& {:keys [email first last password superuser active]
:or {superuser false
active true}}]
{:pre [(string? email) (string? first) (string? last) (string? password) (m/boolean? superuser) (m/boolean? active)]}
(initialize/initialize-if-needed! :db)
(or (User :email email)
(locking create-user-lock
(or (User :email email)
(db/insert! User
:email email
:first_name first
:last_name last
:password PI:PASSWORD:<PASSWORD>END_PI
:is_superuser superuser
:is_qbnewb true
:is_active active)))))
(s/defn fetch-user :- UserInstance
"Fetch the User object associated with `username`. Creates user if needed.
(fetch-user :rasta) -> {:id 100 :first_name \"Rasta\" ...}"
[username :- TestUserName]
(m/mapply fetch-or-create-user! (user->info username)))
(def ^{:arglists '([] [user-name])} user->id
"Creates user if needed. With zero args, returns map of user name to ID. With 1 arg, returns ID of that User. Creates
User(s) if needed. Memoized.
(user->id) ; -> {:rasta 4, ...}
(user->id :rasta) ; -> 4"
(memoize
(fn
([]
(zipmap usernames (map user->id usernames)))
([user-name]
{:pre [(contains? usernames user-name)]}
(u/the-id (fetch-user user-name))))))
(s/defn user->credentials :- {:username (s/pred u/email?), :password s/Str}
"Return a map with `:username` and `:password` for User with `username`.
(user->credentials :rasta) -> {:username \"PI:EMAIL:<EMAIL>END_PI\", :password \"PI:PASSWORD:<PASSWORD>END_PI\"}"
[username :- TestUserName]
{:pre [(contains? usernames username)]}
(let [{:keys [email password]} (user->info username)]
{:username email
:password PI:PASSWORD:<PASSWORD>END_PI}))
(def ^{:arglists '([id])} id->user
"Reverse of `user->id`.
(id->user 4) -> :rasta"
(let [m (delay (zipmap (map user->id usernames) usernames))]
(fn [id]
(@m id))))
(defonce ^:private tokens (atom {}))
(s/defn username->token :- u/uuid-regex
"Return cached session token for a test User, logging in first if needed."
[username :- TestUserName]
(or (@tokens username)
(locking tokens
(or (@tokens username)
(u/prog1 (http/authenticate (user->credentials username))
(swap! tokens assoc username <>))))
(throw (Exception. (format "Authentication failed for %s with credentials %s"
username (user->credentials username))))))
(defn clear-cached-session-tokens!
"Clear any cached session tokens, which may have expired or been removed. You should do this in the even you get a
`401` unauthenticated response, and then retry the request."
[]
(locking tokens
(reset! tokens {})))
(defn- client-fn [username & args]
(try
(apply http/client (username->token username) args)
(catch ExceptionInfo e
(let [{:keys [status-code]} (ex-data e)]
(when-not (= status-code 401)
(throw e))
;; If we got a 401 unauthenticated clear the tokens cache + recur
(clear-cached-session-tokens!)
(apply client-fn username args)))))
(s/defn ^:deprecated user->client :- (s/pred fn?)
"Returns a `metabase.http-client/client` partially bound with the credentials for User with `username`.
In addition, it forces lazy creation of the User if needed.
((user->client) :get 200 \"meta/table\")
DEPRECATED -- use `user-http-request` instead, which has proper `:arglists` metadata which makes it a bit easier to
use when writing code."
[username :- TestUserName]
(fetch-user username) ; force creation of the user if not already created
(partial client-fn username))
(defn user-http-request
"A version of our test HTTP client that issues the request with credentials for a given User. User may be either a
redefined test User name, e.g. `:rasta`, or any User or User ID. (Because we don't have the User's original
password, this function temporarily overrides the password for that User.)"
{:arglists '([test-user-name-or-user-or-id method expected-status-code? endpoint
request-options? http-body-map? & {:as query-params}])}
[user & args]
(if (keyword? user)
(do
(fetch-user user)
(apply client-fn user args))
(let [user-id (u/the-id user)
user-email (db/select-one-field :email User :id user-id)
[old-password-info] (db/simple-select User {:select [:password :password_salt]
:where [:= :id user-id]})]
(when-not user-email
(throw (ex-info "User does not exist" {:user user})))
(try
(db/execute! {:update User
:set {:password (creds/hash-bcrypt user-email)
:password_salt ""}
:where [:= :id user-id]})
(apply http/client {:username user-email, :password user-email} args)
(finally
(db/execute! {:update User
:set old-password-info
:where [:= :id user-id]}))))))
(defn do-with-test-user [user-kwd thunk]
(t/testing (format "with test user %s\n" user-kwd)
(mw.session/with-current-user (some-> user-kwd user->id)
(thunk))))
(defmacro with-test-user
"Call `body` with various `metabase.api.common` dynamic vars like `*current-user*` bound to the predefined test User
named by `user-kwd`. If you want to bind a non-predefined-test User, use `mt/with-current-user` instead."
{:style/indent 1}
[user-kwd & body]
`(do-with-test-user ~user-kwd (fn [] ~@body)))
(defn test-user?
"Does this User or User ID belong to one of the predefined test birds?"
[user-or-id]
(contains? (set (vals (user->id))) (u/the-id user-or-id)))
(defn test-user-name-or-user-id->user-id [test-user-name-or-user-id]
(if (keyword? test-user-name-or-user-id)
(user->id test-user-name-or-user-id)
(u/the-id test-user-name-or-user-id)))
(defn do-with-group-for-user [group test-user-name-or-user-id f]
(tt/with-temp* [PermissionsGroup [group group]
PermissionsGroupMembership [_ {:group_id (u/the-id group)
:user_id (test-user-name-or-user-id->user-id test-user-name-or-user-id)}]]
(f group)))
(defmacro with-group
"Create a new PermissionsGroup, bound to `group-binding`; add test user Rasta Toucan [RIP] to the
group, then execute `body`."
[[group-binding group] & body]
`(do-with-group-for-user ~group :rasta (fn [~group-binding] ~@body)))
(defmacro with-group-for-user
"Like `with-group`, but for any test user (by passing in a test username keyword e.g. `:rasta`) or User ID."
[[group-binding test-user-name-or-user-id group] & body]
`(do-with-group-for-user ~group ~test-user-name-or-user-id (fn [~group-binding] ~@body)))
|
[
{
"context": ";;;;;;;;;;;;;;;;;;;;;;;;;;;\n;; Copyright (c) 2008, J. Bester\n;; All rights reserved.\n;;\n;; Redistribution and ",
"end": 433,
"score": 0.9998849630355835,
"start": 424,
"tag": "NAME",
"value": "J. Bester"
}
] | src/cljext/system.clj | jbester/cljext | 9 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; File : system.clj
;; Function : system library
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Send comments or questions to code at freshlime dot org
;; $Id: 086eaf6714e69dfe92bb730bf283beb4f23459fa $
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Copyright (c) 2008, J. Bester
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;; * Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; * Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ``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 BE LIABLE FOR ANY
;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
;; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
;; ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns cljext.system
(:refer-clojure)
(:import [java.io BufferedReader InputStreamReader]))
(defn system
"(system cmd)
cmd - string to execute
Returns:
output of command as list of strings"
([cmd]
;; spawn process and capture output
(let [proc (.exec (Runtime/getRuntime) #^String cmd)
stdout (java.io.BufferedReader. (java.io.InputStreamReader. (.getInputStream #^Process proc)))]
;; wait for completion
(.waitFor proc)
;; collect output
(loop [result []]
(let [line (.readLine stdout)]
(if (nil? line)
result
(recur (conj result line))))))))
(defn exit
([status]
(System/exit status)))
(defn getenv
([]
(System/getenv))
([str]
(System/getenv #^String str)))
(defn gc
([]
(System/gc)))
(defn sleep
([ms]
(Thread/sleep ms)))
| 103464 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; File : system.clj
;; Function : system library
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Send comments or questions to code at freshlime dot org
;; $Id: 086eaf6714e69dfe92bb730bf283beb4f23459fa $
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Copyright (c) 2008, <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:
;; * Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; * Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ``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 BE LIABLE FOR ANY
;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
;; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
;; ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns cljext.system
(:refer-clojure)
(:import [java.io BufferedReader InputStreamReader]))
(defn system
"(system cmd)
cmd - string to execute
Returns:
output of command as list of strings"
([cmd]
;; spawn process and capture output
(let [proc (.exec (Runtime/getRuntime) #^String cmd)
stdout (java.io.BufferedReader. (java.io.InputStreamReader. (.getInputStream #^Process proc)))]
;; wait for completion
(.waitFor proc)
;; collect output
(loop [result []]
(let [line (.readLine stdout)]
(if (nil? line)
result
(recur (conj result line))))))))
(defn exit
([status]
(System/exit status)))
(defn getenv
([]
(System/getenv))
([str]
(System/getenv #^String str)))
(defn gc
([]
(System/gc)))
(defn sleep
([ms]
(Thread/sleep ms)))
| true | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; File : system.clj
;; Function : system library
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Send comments or questions to code at freshlime dot org
;; $Id: 086eaf6714e69dfe92bb730bf283beb4f23459fa $
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Copyright (c) 2008, 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:
;; * Redistributions of source code must retain the above copyright
;; notice, this list of conditions and the following disclaimer.
;; * Redistributions in binary form must reproduce the above copyright
;; notice, this list of conditions and the following disclaimer in the
;; documentation and/or other materials provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER ``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 BE LIABLE FOR ANY
;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
;; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
;; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
;; ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns cljext.system
(:refer-clojure)
(:import [java.io BufferedReader InputStreamReader]))
(defn system
"(system cmd)
cmd - string to execute
Returns:
output of command as list of strings"
([cmd]
;; spawn process and capture output
(let [proc (.exec (Runtime/getRuntime) #^String cmd)
stdout (java.io.BufferedReader. (java.io.InputStreamReader. (.getInputStream #^Process proc)))]
;; wait for completion
(.waitFor proc)
;; collect output
(loop [result []]
(let [line (.readLine stdout)]
(if (nil? line)
result
(recur (conj result line))))))))
(defn exit
([status]
(System/exit status)))
(defn getenv
([]
(System/getenv))
([str]
(System/getenv #^String str)))
(defn gc
([]
(System/gc)))
(defn sleep
([ms]
(Thread/sleep ms)))
|
[
{
"context": " is created.\n\n ```javascript\n data.set('name', 'Red Gem Stone');\n ```\n\n You can also pass in an object of key",
"end": 6058,
"score": 0.926160991191864,
"start": 6045,
"tag": "NAME",
"value": "Red Gem Stone"
},
{
"context": "st argument:\n\n ```javascript\n data.set({ name: 'Red Gem Stone', level: 2, owner: 'Link', gold: 50 });\n ```\n\n ",
"end": 6194,
"score": 0.9802788496017456,
"start": 6181,
"tag": "NAME",
"value": "Red Gem Stone"
},
{
"context": "r example, if you updated an existing key called `PlayerLives` then it would emit the event `changedata-PlayerL",
"end": 6723,
"score": 0.956805408000946,
"start": 6712,
"tag": "KEY",
"value": "PlayerLives"
}
] | src/phzr/data/data_manager.cljs | sjcasey21/phzr | 1 | (ns phzr.data.data-manager
(:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]]
[phzr.impl.extend :as ex]
[cljsjs.phaser])
(:refer-clojure :exclude [get set merge remove pop]))
(defn ->DataManager
" Parameters:
* parent (object) - The object that this DataManager belongs to.
* event-emitter (Phaser.Events.EventEmitter) - The DataManager's event emitter."
([parent event-emitter]
(js/Phaser.Data.DataManager. (clj->phaser parent)
(clj->phaser event-emitter))))
(defn destroy
"Destroy this data manager."
([data-manager]
(phaser->clj
(.destroy data-manager))))
(defn each
"Passes all data entries to the given callback.
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* callback (DataEachCallback) - The function to call.
* context (*) {optional} - Value to use as `this` when executing callback.
* args (*) {optional} - Additional arguments that will be passed to the callback, after the game object, key, and data.
Returns: Phaser.Data.DataManager - This DataManager object."
([data-manager callback]
(phaser->clj
(.each data-manager
(clj->phaser callback))))
([data-manager callback context]
(phaser->clj
(.each data-manager
(clj->phaser callback)
(clj->phaser context))))
([data-manager callback context args]
(phaser->clj
(.each data-manager
(clj->phaser callback)
(clj->phaser context)
(clj->phaser args)))))
(defn get
"Retrieves the value for the given key, or undefined if it doesn't exist.
You can also access values via the `values` object. For example, if you had a key called `gold` you can do either:
```javascript
this.data.get('gold');
```
Or access the value directly:
```javascript
this.data.values.gold;
```
You can also pass in an array of keys, in which case an array of values will be returned:
```javascript
this.data.get([ 'gold', 'armor', 'health' ]);
```
This approach is useful for destructuring arrays in ES6.
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* key (string | Array.<string>) - The key of the value to retrieve, or an array of keys.
Returns: * - The value belonging to the given key, or an array of values, the order of which will match the input array."
([data-manager key]
(phaser->clj
(.get data-manager
(clj->phaser key)))))
(defn get-all
"Retrieves all data values in a new object.
Returns: Object.<string, *> - All data values."
([data-manager]
(phaser->clj
(.getAll data-manager))))
(defn has
"Determines whether the given key is set in this Data Manager.
Please note that the keys are case-sensitive and must be valid JavaScript Object property strings.
This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager.
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* key (string) - The key to check.
Returns: boolean - Returns `true` if the key exists, otherwise `false`."
([data-manager key]
(phaser->clj
(.has data-manager
(clj->phaser key)))))
(defn merge
"Merge the given object of key value pairs into this DataManager.
Any newly created values will emit a `setdata` event. Any updated values (see the `overwrite` argument)
will emit a `changedata` event.
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* data (Object.<string, *>) - The data to merge.
* overwrite (boolean) {optional} - Whether to overwrite existing data. Defaults to true.
Returns: Phaser.Data.DataManager - This DataManager object."
([data-manager data]
(phaser->clj
(.merge data-manager
(clj->phaser data))))
([data-manager data overwrite]
(phaser->clj
(.merge data-manager
(clj->phaser data)
(clj->phaser overwrite)))))
(defn pop
"Retrieves the data associated with the given 'key', deletes it from this Data Manager, then returns it.
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* key (string) - The key of the value to retrieve and delete.
Returns: * - The value of the given key."
([data-manager key]
(phaser->clj
(.pop data-manager
(clj->phaser key)))))
(defn query
"Queries the DataManager for the values of keys matching the given regular expression.
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* search (RegExp) - A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj).
Returns: Object.<string, *> - The values of the keys matching the search string."
([data-manager search]
(phaser->clj
(.query data-manager
(clj->phaser search)))))
(defn remove
"Remove the value for the given key.
If the key is found in this Data Manager it is removed from the internal lists and a
`removedata` event is emitted.
You can also pass in an array of keys, in which case all keys in the array will be removed:
```javascript
this.data.remove([ 'gold', 'armor', 'health' ]);
```
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* key (string | Array.<string>) - The key to remove, or an array of keys to remove.
Returns: Phaser.Data.DataManager - This DataManager object."
([data-manager key]
(phaser->clj
(.remove data-manager
(clj->phaser key)))))
(defn reset
"Delete all data in this Data Manager and unfreeze it.
Returns: Phaser.Data.DataManager - This DataManager object."
([data-manager]
(phaser->clj
(.reset data-manager))))
(defn set
"Sets a value for the given key. If the key doesn't already exist in the Data Manager then it is created.
```javascript
data.set('name', 'Red Gem Stone');
```
You can also pass in an object of key value pairs as the first argument:
```javascript
data.set({ name: 'Red Gem Stone', level: 2, owner: 'Link', gold: 50 });
```
To get a value back again you can call `get`:
```javascript
data.get('gold');
```
Or you can access the value directly via the `values` property, where it works like any other variable:
```javascript
data.values.gold += 50;
```
When the value is first set, a `setdata` event is emitted.
If the key already exists, a `changedata` event is emitted instead, along an event named after the key.
For example, if you updated an existing key called `PlayerLives` then it would emit the event `changedata-PlayerLives`.
These events will be emitted regardless if you use this method to set the value, or the direct `values` setter.
Please note that the data keys are case-sensitive and must be valid JavaScript Object property strings.
This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager.
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* key (string | object) - The key to set the value for. Or an object or key value pairs. If an object the `data` argument is ignored.
* data (*) - The value to set for the given key. If an object is provided as the key this argument is ignored.
Returns: Phaser.Data.DataManager - This DataManager object."
([data-manager key data]
(phaser->clj
(.set data-manager
(clj->phaser key)
(clj->phaser data)))))
(defn set-freeze
"Freeze or unfreeze this Data Manager. A frozen Data Manager will block all attempts
to create new values or update existing ones.
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* value (boolean) - Whether to freeze or unfreeze the Data Manager.
Returns: Phaser.Data.DataManager - This DataManager object."
([data-manager value]
(phaser->clj
(.setFreeze data-manager
(clj->phaser value))))) | 104420 | (ns phzr.data.data-manager
(:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]]
[phzr.impl.extend :as ex]
[cljsjs.phaser])
(:refer-clojure :exclude [get set merge remove pop]))
(defn ->DataManager
" Parameters:
* parent (object) - The object that this DataManager belongs to.
* event-emitter (Phaser.Events.EventEmitter) - The DataManager's event emitter."
([parent event-emitter]
(js/Phaser.Data.DataManager. (clj->phaser parent)
(clj->phaser event-emitter))))
(defn destroy
"Destroy this data manager."
([data-manager]
(phaser->clj
(.destroy data-manager))))
(defn each
"Passes all data entries to the given callback.
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* callback (DataEachCallback) - The function to call.
* context (*) {optional} - Value to use as `this` when executing callback.
* args (*) {optional} - Additional arguments that will be passed to the callback, after the game object, key, and data.
Returns: Phaser.Data.DataManager - This DataManager object."
([data-manager callback]
(phaser->clj
(.each data-manager
(clj->phaser callback))))
([data-manager callback context]
(phaser->clj
(.each data-manager
(clj->phaser callback)
(clj->phaser context))))
([data-manager callback context args]
(phaser->clj
(.each data-manager
(clj->phaser callback)
(clj->phaser context)
(clj->phaser args)))))
(defn get
"Retrieves the value for the given key, or undefined if it doesn't exist.
You can also access values via the `values` object. For example, if you had a key called `gold` you can do either:
```javascript
this.data.get('gold');
```
Or access the value directly:
```javascript
this.data.values.gold;
```
You can also pass in an array of keys, in which case an array of values will be returned:
```javascript
this.data.get([ 'gold', 'armor', 'health' ]);
```
This approach is useful for destructuring arrays in ES6.
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* key (string | Array.<string>) - The key of the value to retrieve, or an array of keys.
Returns: * - The value belonging to the given key, or an array of values, the order of which will match the input array."
([data-manager key]
(phaser->clj
(.get data-manager
(clj->phaser key)))))
(defn get-all
"Retrieves all data values in a new object.
Returns: Object.<string, *> - All data values."
([data-manager]
(phaser->clj
(.getAll data-manager))))
(defn has
"Determines whether the given key is set in this Data Manager.
Please note that the keys are case-sensitive and must be valid JavaScript Object property strings.
This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager.
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* key (string) - The key to check.
Returns: boolean - Returns `true` if the key exists, otherwise `false`."
([data-manager key]
(phaser->clj
(.has data-manager
(clj->phaser key)))))
(defn merge
"Merge the given object of key value pairs into this DataManager.
Any newly created values will emit a `setdata` event. Any updated values (see the `overwrite` argument)
will emit a `changedata` event.
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* data (Object.<string, *>) - The data to merge.
* overwrite (boolean) {optional} - Whether to overwrite existing data. Defaults to true.
Returns: Phaser.Data.DataManager - This DataManager object."
([data-manager data]
(phaser->clj
(.merge data-manager
(clj->phaser data))))
([data-manager data overwrite]
(phaser->clj
(.merge data-manager
(clj->phaser data)
(clj->phaser overwrite)))))
(defn pop
"Retrieves the data associated with the given 'key', deletes it from this Data Manager, then returns it.
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* key (string) - The key of the value to retrieve and delete.
Returns: * - The value of the given key."
([data-manager key]
(phaser->clj
(.pop data-manager
(clj->phaser key)))))
(defn query
"Queries the DataManager for the values of keys matching the given regular expression.
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* search (RegExp) - A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj).
Returns: Object.<string, *> - The values of the keys matching the search string."
([data-manager search]
(phaser->clj
(.query data-manager
(clj->phaser search)))))
(defn remove
"Remove the value for the given key.
If the key is found in this Data Manager it is removed from the internal lists and a
`removedata` event is emitted.
You can also pass in an array of keys, in which case all keys in the array will be removed:
```javascript
this.data.remove([ 'gold', 'armor', 'health' ]);
```
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* key (string | Array.<string>) - The key to remove, or an array of keys to remove.
Returns: Phaser.Data.DataManager - This DataManager object."
([data-manager key]
(phaser->clj
(.remove data-manager
(clj->phaser key)))))
(defn reset
"Delete all data in this Data Manager and unfreeze it.
Returns: Phaser.Data.DataManager - This DataManager object."
([data-manager]
(phaser->clj
(.reset data-manager))))
(defn set
"Sets a value for the given key. If the key doesn't already exist in the Data Manager then it is created.
```javascript
data.set('name', '<NAME>');
```
You can also pass in an object of key value pairs as the first argument:
```javascript
data.set({ name: '<NAME>', level: 2, owner: 'Link', gold: 50 });
```
To get a value back again you can call `get`:
```javascript
data.get('gold');
```
Or you can access the value directly via the `values` property, where it works like any other variable:
```javascript
data.values.gold += 50;
```
When the value is first set, a `setdata` event is emitted.
If the key already exists, a `changedata` event is emitted instead, along an event named after the key.
For example, if you updated an existing key called `<KEY>` then it would emit the event `changedata-PlayerLives`.
These events will be emitted regardless if you use this method to set the value, or the direct `values` setter.
Please note that the data keys are case-sensitive and must be valid JavaScript Object property strings.
This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager.
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* key (string | object) - The key to set the value for. Or an object or key value pairs. If an object the `data` argument is ignored.
* data (*) - The value to set for the given key. If an object is provided as the key this argument is ignored.
Returns: Phaser.Data.DataManager - This DataManager object."
([data-manager key data]
(phaser->clj
(.set data-manager
(clj->phaser key)
(clj->phaser data)))))
(defn set-freeze
"Freeze or unfreeze this Data Manager. A frozen Data Manager will block all attempts
to create new values or update existing ones.
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* value (boolean) - Whether to freeze or unfreeze the Data Manager.
Returns: Phaser.Data.DataManager - This DataManager object."
([data-manager value]
(phaser->clj
(.setFreeze data-manager
(clj->phaser value))))) | true | (ns phzr.data.data-manager
(:require [phzr.impl.utils.core :refer [clj->phaser phaser->clj]]
[phzr.impl.extend :as ex]
[cljsjs.phaser])
(:refer-clojure :exclude [get set merge remove pop]))
(defn ->DataManager
" Parameters:
* parent (object) - The object that this DataManager belongs to.
* event-emitter (Phaser.Events.EventEmitter) - The DataManager's event emitter."
([parent event-emitter]
(js/Phaser.Data.DataManager. (clj->phaser parent)
(clj->phaser event-emitter))))
(defn destroy
"Destroy this data manager."
([data-manager]
(phaser->clj
(.destroy data-manager))))
(defn each
"Passes all data entries to the given callback.
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* callback (DataEachCallback) - The function to call.
* context (*) {optional} - Value to use as `this` when executing callback.
* args (*) {optional} - Additional arguments that will be passed to the callback, after the game object, key, and data.
Returns: Phaser.Data.DataManager - This DataManager object."
([data-manager callback]
(phaser->clj
(.each data-manager
(clj->phaser callback))))
([data-manager callback context]
(phaser->clj
(.each data-manager
(clj->phaser callback)
(clj->phaser context))))
([data-manager callback context args]
(phaser->clj
(.each data-manager
(clj->phaser callback)
(clj->phaser context)
(clj->phaser args)))))
(defn get
"Retrieves the value for the given key, or undefined if it doesn't exist.
You can also access values via the `values` object. For example, if you had a key called `gold` you can do either:
```javascript
this.data.get('gold');
```
Or access the value directly:
```javascript
this.data.values.gold;
```
You can also pass in an array of keys, in which case an array of values will be returned:
```javascript
this.data.get([ 'gold', 'armor', 'health' ]);
```
This approach is useful for destructuring arrays in ES6.
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* key (string | Array.<string>) - The key of the value to retrieve, or an array of keys.
Returns: * - The value belonging to the given key, or an array of values, the order of which will match the input array."
([data-manager key]
(phaser->clj
(.get data-manager
(clj->phaser key)))))
(defn get-all
"Retrieves all data values in a new object.
Returns: Object.<string, *> - All data values."
([data-manager]
(phaser->clj
(.getAll data-manager))))
(defn has
"Determines whether the given key is set in this Data Manager.
Please note that the keys are case-sensitive and must be valid JavaScript Object property strings.
This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager.
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* key (string) - The key to check.
Returns: boolean - Returns `true` if the key exists, otherwise `false`."
([data-manager key]
(phaser->clj
(.has data-manager
(clj->phaser key)))))
(defn merge
"Merge the given object of key value pairs into this DataManager.
Any newly created values will emit a `setdata` event. Any updated values (see the `overwrite` argument)
will emit a `changedata` event.
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* data (Object.<string, *>) - The data to merge.
* overwrite (boolean) {optional} - Whether to overwrite existing data. Defaults to true.
Returns: Phaser.Data.DataManager - This DataManager object."
([data-manager data]
(phaser->clj
(.merge data-manager
(clj->phaser data))))
([data-manager data overwrite]
(phaser->clj
(.merge data-manager
(clj->phaser data)
(clj->phaser overwrite)))))
(defn pop
"Retrieves the data associated with the given 'key', deletes it from this Data Manager, then returns it.
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* key (string) - The key of the value to retrieve and delete.
Returns: * - The value of the given key."
([data-manager key]
(phaser->clj
(.pop data-manager
(clj->phaser key)))))
(defn query
"Queries the DataManager for the values of keys matching the given regular expression.
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* search (RegExp) - A regular expression object. If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj).
Returns: Object.<string, *> - The values of the keys matching the search string."
([data-manager search]
(phaser->clj
(.query data-manager
(clj->phaser search)))))
(defn remove
"Remove the value for the given key.
If the key is found in this Data Manager it is removed from the internal lists and a
`removedata` event is emitted.
You can also pass in an array of keys, in which case all keys in the array will be removed:
```javascript
this.data.remove([ 'gold', 'armor', 'health' ]);
```
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* key (string | Array.<string>) - The key to remove, or an array of keys to remove.
Returns: Phaser.Data.DataManager - This DataManager object."
([data-manager key]
(phaser->clj
(.remove data-manager
(clj->phaser key)))))
(defn reset
"Delete all data in this Data Manager and unfreeze it.
Returns: Phaser.Data.DataManager - This DataManager object."
([data-manager]
(phaser->clj
(.reset data-manager))))
(defn set
"Sets a value for the given key. If the key doesn't already exist in the Data Manager then it is created.
```javascript
data.set('name', 'PI:NAME:<NAME>END_PI');
```
You can also pass in an object of key value pairs as the first argument:
```javascript
data.set({ name: 'PI:NAME:<NAME>END_PI', level: 2, owner: 'Link', gold: 50 });
```
To get a value back again you can call `get`:
```javascript
data.get('gold');
```
Or you can access the value directly via the `values` property, where it works like any other variable:
```javascript
data.values.gold += 50;
```
When the value is first set, a `setdata` event is emitted.
If the key already exists, a `changedata` event is emitted instead, along an event named after the key.
For example, if you updated an existing key called `PI:KEY:<KEY>END_PI` then it would emit the event `changedata-PlayerLives`.
These events will be emitted regardless if you use this method to set the value, or the direct `values` setter.
Please note that the data keys are case-sensitive and must be valid JavaScript Object property strings.
This means the keys `gold` and `Gold` are treated as two unique values within the Data Manager.
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* key (string | object) - The key to set the value for. Or an object or key value pairs. If an object the `data` argument is ignored.
* data (*) - The value to set for the given key. If an object is provided as the key this argument is ignored.
Returns: Phaser.Data.DataManager - This DataManager object."
([data-manager key data]
(phaser->clj
(.set data-manager
(clj->phaser key)
(clj->phaser data)))))
(defn set-freeze
"Freeze or unfreeze this Data Manager. A frozen Data Manager will block all attempts
to create new values or update existing ones.
Parameters:
* data-manager (Phaser.Data.DataManager) - Targeted instance for method
* value (boolean) - Whether to freeze or unfreeze the Data Manager.
Returns: Phaser.Data.DataManager - This DataManager object."
([data-manager value]
(phaser->clj
(.setFreeze data-manager
(clj->phaser value))))) |
[
{
"context": "ps\n [Root {:my-list '(\"a string\" [1 2 3] {:name \"Jim\" :age 10} {:name \"Jane\" :age 7})}\n \"root\"\n (r",
"end": 1859,
"score": 0.999853253364563,
"start": 1856,
"tag": "NAME",
"value": "Jim"
},
{
"context": "(\"a string\" [1 2 3] {:name \"Jim\" :age 10} {:name \"Jane\" :age 7})}\n \"root\"\n (r/atom {:data-frisk {\"ro",
"end": 1882,
"score": 0.9996699094772339,
"start": 1878,
"tag": "NAME",
"value": "Jane"
}
] | devcards/datafrisk/ui_card.cljs | Odinodin/data-drill-reagent | 113 | (ns datafrisk.ui-card
(:require [devcards.core]
[reagent.core :as r]
[datafrisk.view :refer [Root]])
(:require-macros [devcards.core :as dc :refer [defcard-rg]]))
(defcard-rg modifiable-data
"When the data you are watching is swappable, you can edit it."
[Root
(r/atom 3)
"root"
(r/atom {})])
(defcard-rg modifiable-nested-data
"When the data you are watching is nested in a swappable, you can edit the values."
[Root
(r/atom {:foo 2
3 "bar"})
"root"
(r/atom {})])
(defcard-rg data-types
[Root
{:a "I'm a string"
:b :imakeyword
:c [1 2 3]
:d '(1 2 3)
:e #{1 2 3}
:f (clj->js {:i-am "an-object"})
"g" "String key"
0 nil
"not a number" js/NaN
}
"root"
(r/atom {})])
(defcard-rg first-level-expanded
[Root
{:a "a"
:b [1 2 3]
:c :d}
"root"
(r/atom {:data-frisk {"root" {:metadata-paths {[] {:expanded? true}}}}})])
(defcard-rg second-level-expanded
[Root {:a "a"
:b [1 2 3]
:c :d}
"root"
(r/atom {:data-frisk {"root" {:metadata-paths {[] {:expanded? true}
[:b] {:expanded? true}}}}})])
(defcard-rg empty-collections
[Root {:set #{}
:vec []
:list '()}
"root"
(r/atom {:data-frisk {"root" {:metadata-paths {[] {:expanded? true}}}}})])
(defcard-rg nil-in-collections
[Root {:set #{nil}
:vec [nil]
:list '(nil nil)}
"root"
(r/atom {:data-frisk {"root" {:metadata-paths {[] {:expanded? true}
[:set] {:expanded? true}
[:vec] {:expanded? true}
[:list] {:expanded? true}}}}})])
(defcard-rg list-of-maps
[Root {:my-list '("a string" [1 2 3] {:name "Jim" :age 10} {:name "Jane" :age 7})}
"root"
(r/atom {:data-frisk {"root" {:metadata-paths {[] {:expanded? true}
[:my-list] {:expanded? true}}}}})])
(defcard-rg list-of-lists
[Root '(1 (1 2 3))
"root"
(r/atom {:data-frisk {"root" {:metadata-paths {[] {:expanded? true}
[:my-list] (:expanded? true)}}}})])
(defcard-rg set-with-list
[Root #{1 '(1 2 3) [4 5 6]}
"root"
(r/atom {:data-frisk {"root" {:metadata-paths {[] {:expanded? true}
[:my-list] (:expanded? true)}}}})])
(defcard-rg meta-data
[Root {:a 1 :b 2}
"root"
(r/atom {:data-frisk {"root" {:metadata-paths {[] {:error "bad stuff"
:expanded? true}
[:a] {:error "very bad stuff"}}}}})]) | 17431 | (ns datafrisk.ui-card
(:require [devcards.core]
[reagent.core :as r]
[datafrisk.view :refer [Root]])
(:require-macros [devcards.core :as dc :refer [defcard-rg]]))
(defcard-rg modifiable-data
"When the data you are watching is swappable, you can edit it."
[Root
(r/atom 3)
"root"
(r/atom {})])
(defcard-rg modifiable-nested-data
"When the data you are watching is nested in a swappable, you can edit the values."
[Root
(r/atom {:foo 2
3 "bar"})
"root"
(r/atom {})])
(defcard-rg data-types
[Root
{:a "I'm a string"
:b :imakeyword
:c [1 2 3]
:d '(1 2 3)
:e #{1 2 3}
:f (clj->js {:i-am "an-object"})
"g" "String key"
0 nil
"not a number" js/NaN
}
"root"
(r/atom {})])
(defcard-rg first-level-expanded
[Root
{:a "a"
:b [1 2 3]
:c :d}
"root"
(r/atom {:data-frisk {"root" {:metadata-paths {[] {:expanded? true}}}}})])
(defcard-rg second-level-expanded
[Root {:a "a"
:b [1 2 3]
:c :d}
"root"
(r/atom {:data-frisk {"root" {:metadata-paths {[] {:expanded? true}
[:b] {:expanded? true}}}}})])
(defcard-rg empty-collections
[Root {:set #{}
:vec []
:list '()}
"root"
(r/atom {:data-frisk {"root" {:metadata-paths {[] {:expanded? true}}}}})])
(defcard-rg nil-in-collections
[Root {:set #{nil}
:vec [nil]
:list '(nil nil)}
"root"
(r/atom {:data-frisk {"root" {:metadata-paths {[] {:expanded? true}
[:set] {:expanded? true}
[:vec] {:expanded? true}
[:list] {:expanded? true}}}}})])
(defcard-rg list-of-maps
[Root {:my-list '("a string" [1 2 3] {:name "<NAME>" :age 10} {:name "<NAME>" :age 7})}
"root"
(r/atom {:data-frisk {"root" {:metadata-paths {[] {:expanded? true}
[:my-list] {:expanded? true}}}}})])
(defcard-rg list-of-lists
[Root '(1 (1 2 3))
"root"
(r/atom {:data-frisk {"root" {:metadata-paths {[] {:expanded? true}
[:my-list] (:expanded? true)}}}})])
(defcard-rg set-with-list
[Root #{1 '(1 2 3) [4 5 6]}
"root"
(r/atom {:data-frisk {"root" {:metadata-paths {[] {:expanded? true}
[:my-list] (:expanded? true)}}}})])
(defcard-rg meta-data
[Root {:a 1 :b 2}
"root"
(r/atom {:data-frisk {"root" {:metadata-paths {[] {:error "bad stuff"
:expanded? true}
[:a] {:error "very bad stuff"}}}}})]) | true | (ns datafrisk.ui-card
(:require [devcards.core]
[reagent.core :as r]
[datafrisk.view :refer [Root]])
(:require-macros [devcards.core :as dc :refer [defcard-rg]]))
(defcard-rg modifiable-data
"When the data you are watching is swappable, you can edit it."
[Root
(r/atom 3)
"root"
(r/atom {})])
(defcard-rg modifiable-nested-data
"When the data you are watching is nested in a swappable, you can edit the values."
[Root
(r/atom {:foo 2
3 "bar"})
"root"
(r/atom {})])
(defcard-rg data-types
[Root
{:a "I'm a string"
:b :imakeyword
:c [1 2 3]
:d '(1 2 3)
:e #{1 2 3}
:f (clj->js {:i-am "an-object"})
"g" "String key"
0 nil
"not a number" js/NaN
}
"root"
(r/atom {})])
(defcard-rg first-level-expanded
[Root
{:a "a"
:b [1 2 3]
:c :d}
"root"
(r/atom {:data-frisk {"root" {:metadata-paths {[] {:expanded? true}}}}})])
(defcard-rg second-level-expanded
[Root {:a "a"
:b [1 2 3]
:c :d}
"root"
(r/atom {:data-frisk {"root" {:metadata-paths {[] {:expanded? true}
[:b] {:expanded? true}}}}})])
(defcard-rg empty-collections
[Root {:set #{}
:vec []
:list '()}
"root"
(r/atom {:data-frisk {"root" {:metadata-paths {[] {:expanded? true}}}}})])
(defcard-rg nil-in-collections
[Root {:set #{nil}
:vec [nil]
:list '(nil nil)}
"root"
(r/atom {:data-frisk {"root" {:metadata-paths {[] {:expanded? true}
[:set] {:expanded? true}
[:vec] {:expanded? true}
[:list] {:expanded? true}}}}})])
(defcard-rg list-of-maps
[Root {:my-list '("a string" [1 2 3] {:name "PI:NAME:<NAME>END_PI" :age 10} {:name "PI:NAME:<NAME>END_PI" :age 7})}
"root"
(r/atom {:data-frisk {"root" {:metadata-paths {[] {:expanded? true}
[:my-list] {:expanded? true}}}}})])
(defcard-rg list-of-lists
[Root '(1 (1 2 3))
"root"
(r/atom {:data-frisk {"root" {:metadata-paths {[] {:expanded? true}
[:my-list] (:expanded? true)}}}})])
(defcard-rg set-with-list
[Root #{1 '(1 2 3) [4 5 6]}
"root"
(r/atom {:data-frisk {"root" {:metadata-paths {[] {:expanded? true}
[:my-list] (:expanded? true)}}}})])
(defcard-rg meta-data
[Root {:a 1 :b 2}
"root"
(r/atom {:data-frisk {"root" {:metadata-paths {[] {:error "bad stuff"
:expanded? true}
[:a] {:error "very bad stuff"}}}}})]) |
[
{
"context": "(ns ^{:author \"Leeor Engel\"}\n chapter-2.chapter-2-q6)\n\n(defn palindrome? [l",
"end": 26,
"score": 0.9998971819877625,
"start": 15,
"tag": "NAME",
"value": "Leeor Engel"
}
] | Clojure/src/chapter_2/chapter_2_q6.clj | Kiandr/crackingcodinginterview | 0 | (ns ^{:author "Leeor Engel"}
chapter-2.chapter-2-q6)
(defn palindrome? [l]
(= l (reverse l))) | 121728 | (ns ^{:author "<NAME>"}
chapter-2.chapter-2-q6)
(defn palindrome? [l]
(= l (reverse l))) | true | (ns ^{:author "PI:NAME:<NAME>END_PI"}
chapter-2.chapter-2-q6)
(defn palindrome? [l]
(= l (reverse l))) |
[
{
"context": "(def booking\n {\n :id 8773\n :customer-name \"Alice Smith\"\n :catering-notes \"Vegetarian on Sundays\"\n ",
"end": 131,
"score": 0.9990062713623047,
"start": 120,
"tag": "NAME",
"value": "Alice Smith"
}
] | Chapter03/tests/Exercise3.02/repl.clj | transducer/The-Clojure-Workshop | 55 | (require '[clojure.test :as test :refer [is are deftest run-tests]])
(def booking
{
:id 8773
:customer-name "Alice Smith"
:catering-notes "Vegetarian on Sundays"
:flights [
{
:from {:lat 48.9615 :lon 2.4372 :name "Paris Le Bourget Airport"},
:to {:lat 37.742 :lon -25.6976 :name "Ponta Delgada Airport"}},
{
:from {:lat 37.742 :lon -25.6976 :name "Ponta Delgada Airport"},
:to {:lat 48.9615 :lon 2.4372 :name "Paris Le Bourget Airport"}}
]
})
; (deftest exercise302-test
;
| 104295 | (require '[clojure.test :as test :refer [is are deftest run-tests]])
(def booking
{
:id 8773
:customer-name "<NAME>"
:catering-notes "Vegetarian on Sundays"
:flights [
{
:from {:lat 48.9615 :lon 2.4372 :name "Paris Le Bourget Airport"},
:to {:lat 37.742 :lon -25.6976 :name "Ponta Delgada Airport"}},
{
:from {:lat 37.742 :lon -25.6976 :name "Ponta Delgada Airport"},
:to {:lat 48.9615 :lon 2.4372 :name "Paris Le Bourget Airport"}}
]
})
; (deftest exercise302-test
;
| true | (require '[clojure.test :as test :refer [is are deftest run-tests]])
(def booking
{
:id 8773
:customer-name "PI:NAME:<NAME>END_PI"
:catering-notes "Vegetarian on Sundays"
:flights [
{
:from {:lat 48.9615 :lon 2.4372 :name "Paris Le Bourget Airport"},
:to {:lat 37.742 :lon -25.6976 :name "Ponta Delgada Airport"}},
{
:from {:lat 37.742 :lon -25.6976 :name "Ponta Delgada Airport"},
:to {:lat 48.9615 :lon 2.4372 :name "Paris Le Bourget Airport"}}
]
})
; (deftest exercise302-test
;
|
[
{
"context": "; Written by Raju\n; Run using following command\n; clojure streamSeq",
"end": 17,
"score": 0.9998493194580078,
"start": 13,
"tag": "NAME",
"value": "Raju"
}
] | Chapter09/streamSequence.clj | PacktPublishing/Learning-Functional-Data-Structures-and-Algorithms | 31 | ; Written by Raju
; Run using following command
; clojure streamSequence.clj
;Streams (lazy sequence) in Clojure
(defn strFun [n]
( lazy-seq (println "Evaluating next element of Stream") (cons n (strFun (inc n)))))
(println (take 3 (strFun 1)))
;Creating a memoized function of lazy sequences in Clojure
(defn strFun [n]
( lazy-seq (println "Evaluating next element of Stream") (cons n (strFun (inc n)))))
(def memzstrFun (memoize strFun))
(println (take 3 (memzstrFun 1)))
(println (take 3 (memzstrFun 1)))
| 62929 | ; Written by <NAME>
; Run using following command
; clojure streamSequence.clj
;Streams (lazy sequence) in Clojure
(defn strFun [n]
( lazy-seq (println "Evaluating next element of Stream") (cons n (strFun (inc n)))))
(println (take 3 (strFun 1)))
;Creating a memoized function of lazy sequences in Clojure
(defn strFun [n]
( lazy-seq (println "Evaluating next element of Stream") (cons n (strFun (inc n)))))
(def memzstrFun (memoize strFun))
(println (take 3 (memzstrFun 1)))
(println (take 3 (memzstrFun 1)))
| true | ; Written by PI:NAME:<NAME>END_PI
; Run using following command
; clojure streamSequence.clj
;Streams (lazy sequence) in Clojure
(defn strFun [n]
( lazy-seq (println "Evaluating next element of Stream") (cons n (strFun (inc n)))))
(println (take 3 (strFun 1)))
;Creating a memoized function of lazy sequences in Clojure
(defn strFun [n]
( lazy-seq (println "Evaluating next element of Stream") (cons n (strFun (inc n)))))
(def memzstrFun (memoize strFun))
(println (take 3 (memzstrFun 1)))
(println (take 3 (memzstrFun 1)))
|
[
{
"context": "ts? \"input#username\"))\n (input-text \"#username\" \"admin\")\n (-> \"#password\" (input-text \"changeme\") submi",
"end": 489,
"score": 0.9954477548599243,
"start": 484,
"tag": "USERNAME",
"value": "admin"
},
{
"context": "username\" \"admin\")\n (-> \"#password\" (input-text \"changeme\") submit)\n (wait-until #(exists? \"a.SystemsMenu\"",
"end": 531,
"score": 0.9350394010543823,
"start": 523,
"tag": "PASSWORD",
"value": "changeme"
}
] | data/test/clojure/64d27bd2962c7f175182c2a07b7e989d2a32df68common.clj | harshp8l/deep-learning-lang-detection | 84 | (ns elm.ui.common
(:import
org.openqa.selenium.Dimension
org.openqa.selenium.remote.DesiredCapabilities
org.openqa.selenium.phantomjs.PhantomJSDriver
org.openqa.selenium.OutputType)
(:use
clj-webdriver.taxi
clj-webdriver.driver))
(defn take-snapshot []
(.getScreenshotAs (:webdriver clj-webdriver.taxi/*driver*) OutputType/FILE))
(defn login []
(to "https://localhost:8443/")
(wait-until #(exists? "input#username"))
(input-text "#username" "admin")
(-> "#password" (input-text "changeme") submit)
(wait-until #(exists? "a.SystemsMenu")))
(System/setProperty "webdriver.chrome.driver" "/usr/bin/chromedriver")
(System/setProperty "phantomjs.binary.path" "/usr/bin/phantomjs")
(defn phantom-driver []
(let [args (into-array String ["--ignore-ssl-errors=true" "--webdriver-loglevel=ERROR"])]
(PhantomJSDriver.
(doto (DesiredCapabilities.)
(.setCapability "phantomjs.page.settings.userAgent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0")
(.setCapability "phantomjs.page.customHeaders.Accept-Language" "en-US")
(.setCapability "phantomjs.page.customHeaders.Connection" "keep-alive")
(.setCapability "phantomjs.cli.args" args)))))
(defn set-view-size [driver]
(.setSize (.window (.manage driver)) (Dimension. 1920 1080)) driver)
(defn create-phantom []
(init-driver {:webdriver (set-view-size (phantom-driver))}))
(def browser {:browser :phantomjs})
(defmacro with-driver-
[driver & body]
`(binding [clj-webdriver.taxi/*driver* ~driver]
(try ~@body
(catch Exception e#
(timbre/error e#)
(take-snapshot))
(finally (quit)))))
(defn uuid [] (first (.split (str (java.util.UUID/randomUUID)) "-")))
(defn click-next [] (click "button#Next"))
| 12384 | (ns elm.ui.common
(:import
org.openqa.selenium.Dimension
org.openqa.selenium.remote.DesiredCapabilities
org.openqa.selenium.phantomjs.PhantomJSDriver
org.openqa.selenium.OutputType)
(:use
clj-webdriver.taxi
clj-webdriver.driver))
(defn take-snapshot []
(.getScreenshotAs (:webdriver clj-webdriver.taxi/*driver*) OutputType/FILE))
(defn login []
(to "https://localhost:8443/")
(wait-until #(exists? "input#username"))
(input-text "#username" "admin")
(-> "#password" (input-text "<PASSWORD>") submit)
(wait-until #(exists? "a.SystemsMenu")))
(System/setProperty "webdriver.chrome.driver" "/usr/bin/chromedriver")
(System/setProperty "phantomjs.binary.path" "/usr/bin/phantomjs")
(defn phantom-driver []
(let [args (into-array String ["--ignore-ssl-errors=true" "--webdriver-loglevel=ERROR"])]
(PhantomJSDriver.
(doto (DesiredCapabilities.)
(.setCapability "phantomjs.page.settings.userAgent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0")
(.setCapability "phantomjs.page.customHeaders.Accept-Language" "en-US")
(.setCapability "phantomjs.page.customHeaders.Connection" "keep-alive")
(.setCapability "phantomjs.cli.args" args)))))
(defn set-view-size [driver]
(.setSize (.window (.manage driver)) (Dimension. 1920 1080)) driver)
(defn create-phantom []
(init-driver {:webdriver (set-view-size (phantom-driver))}))
(def browser {:browser :phantomjs})
(defmacro with-driver-
[driver & body]
`(binding [clj-webdriver.taxi/*driver* ~driver]
(try ~@body
(catch Exception e#
(timbre/error e#)
(take-snapshot))
(finally (quit)))))
(defn uuid [] (first (.split (str (java.util.UUID/randomUUID)) "-")))
(defn click-next [] (click "button#Next"))
| true | (ns elm.ui.common
(:import
org.openqa.selenium.Dimension
org.openqa.selenium.remote.DesiredCapabilities
org.openqa.selenium.phantomjs.PhantomJSDriver
org.openqa.selenium.OutputType)
(:use
clj-webdriver.taxi
clj-webdriver.driver))
(defn take-snapshot []
(.getScreenshotAs (:webdriver clj-webdriver.taxi/*driver*) OutputType/FILE))
(defn login []
(to "https://localhost:8443/")
(wait-until #(exists? "input#username"))
(input-text "#username" "admin")
(-> "#password" (input-text "PI:PASSWORD:<PASSWORD>END_PI") submit)
(wait-until #(exists? "a.SystemsMenu")))
(System/setProperty "webdriver.chrome.driver" "/usr/bin/chromedriver")
(System/setProperty "phantomjs.binary.path" "/usr/bin/phantomjs")
(defn phantom-driver []
(let [args (into-array String ["--ignore-ssl-errors=true" "--webdriver-loglevel=ERROR"])]
(PhantomJSDriver.
(doto (DesiredCapabilities.)
(.setCapability "phantomjs.page.settings.userAgent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0")
(.setCapability "phantomjs.page.customHeaders.Accept-Language" "en-US")
(.setCapability "phantomjs.page.customHeaders.Connection" "keep-alive")
(.setCapability "phantomjs.cli.args" args)))))
(defn set-view-size [driver]
(.setSize (.window (.manage driver)) (Dimension. 1920 1080)) driver)
(defn create-phantom []
(init-driver {:webdriver (set-view-size (phantom-driver))}))
(def browser {:browser :phantomjs})
(defmacro with-driver-
[driver & body]
`(binding [clj-webdriver.taxi/*driver* ~driver]
(try ~@body
(catch Exception e#
(timbre/error e#)
(take-snapshot))
(finally (quit)))))
(defn uuid [] (first (.split (str (java.util.UUID/randomUUID)) "-")))
(defn click-next [] (click "button#Next"))
|
[
{
"context": "tion `%s'.\" verb-fn-sym)\n (let [handler-key (gensym \"handler-key__\")\n routes' (assoc route",
"end": 8542,
"score": 0.5827172994613647,
"start": 8536,
"tag": "KEY",
"value": "gensym"
}
] | src/io/aviso/rook/dispatcher.clj | curious-attempt-bunny/rook | 0 | (ns io.aviso.rook.dispatcher
"This namespace deals with dispatch tables mapping route specs of
the form
[method [path-segment ...]]
to resource handler functions. The recognized format is described at
length in the docstrings of the [[unnest-dispatch-table]] and
[[request-route-spec]] functions exported by this namespace.
User code interested in setting up a handler for a RESTful API will
typically not interact with this namespace directly; rather, it will
use [[io.aviso.rook/namespace-handler]]. Functions exported by this
namespace can be useful, however, to code that wishes to use the
dispatcher in a more flexible way (perhaps avoiding the namespace to
resource correspondence) and utility add-ons that wish to deal with
dispatch tables directly.
The expected way to use this namespace is as follows:
- namespaces correspond to resources;
- [[namespace-dispatch-table]] produces a dispatch table for a single
namespace
- any number of such dispatch tables can be concatenated to form a
dispatch table for a collection of resources
- such compound dispatch tables can be compiled using
[[compile-dispatch-table]].
The individual resource handler functions are expected to support a
single arity only. The arglist for that arity and the metadata on
the resource handler function will be examined to determine the
correct argument resolution strategy at dispatch table compilation
time."
{:added "0.1.10"}
(:require [clojure.core.async :as async]
[clojure.string :as string]
[clojure.set :as set]
[io.aviso.tracker :as t]
[io.aviso.rook.internals :as internals]
[clojure.string :as str]
[clojure.tools.logging :as l]
[io.aviso.rook.utils :as utils]))
(def ^:private default-mappings
"Default function -> route spec mappings.
Namespace dispatch tables will by default include entries for public
Vars named by the keys in this map, with methods and pathvecs
provided by the values."
{
'new [:get ["new"]]
'edit [:get [:id "edit"]]
'show [:get [:id]]
'update [:put [:id]]
'patch [:patch [:id]]
'destroy [:delete [:id]]
'index [:get []]
'create [:post []]
}
)
(defn default-namespace-middleware
"Default namespace middleware that ignores the metadata and returns the handler unchanged.
Namespace middleware is slightly different than Ring middleware, as the metadata from
the function is available. Namespace middleware may also return nil."
[handler metadata]
handler)
(defn- request-route-spec
"Takes a Ring request map and returns `[method pathvec]`, where method
is a request method keyword and pathvec is a vector of path
segments.
For example,
GET /foo/bar HTTP/1.1
become:
[:get [\"foo\" \"bar\"]]
The individual path segments are URL decoded; UTF-8 encoding is
assumed."
[request]
[(:request-method request)
(mapv #(java.net.URLDecoder/decode ^String % "UTF-8")
(next (string/split (:uri request) #"/" 0)))])
(defn path-spec->route-spec
"Takes a path-spec in the format `[:method \"/path/:param\"]` and
returns the equivalent route-spec in the format `[:method
[\"path\" :param]]`. If passed nil as input, returns nil."
[path-spec]
(if-not (nil? path-spec)
(let [[method path] path-spec
_ (assert (instance? String path))
paramify (fn [seg]
(if (.startsWith ^String seg ":")
(keyword (subs seg 1))
seg))]
[method (mapv paramify (next (string/split path #"/" 0)))])))
(defn pathvec->path [pathvec]
(if (seq pathvec)
(string/join "/" (cons nil pathvec))
"/"))
(defn route-spec->path-spec
"Takes a route-spec in the format `[:method [\"path\" :param ...]]`
and returns the equivalent path-spec in the format `[:method
\"/path/:param\"]`. If passed nil as input, returns nil."
[route-spec]
(if-not (nil? route-spec)
(let [[method pathvec] route-spec]
[method (pathvec->path pathvec)])))
(defn unnest-dispatch-table
"Given a nested dispatch table:
[[method pathvec verb-fn middleware
[method' pathvec' verb-fn' middleware' ...]
...]
...]
produces a dispatch table with no nesting:
[[method pathvec verb-fn middleware]
[method' (into pathvec pathvec') verb-fn' middleware']
...]
Entries may also take the alternative form of
[pathvec middleware? & entries],
in which case pathvec and middleware? (if present) will provide a
context pathvec and default middleware for the nested entries
without introducing a separate route."
[dispatch-table]
(letfn [(unnest-entry [default-middleware [x :as entry]]
(cond
(keyword? x)
(let [[method pathvec verb-fn middleware & nested-table] entry]
(if nested-table
(let [mw (or middleware default-middleware)]
(into [[method pathvec verb-fn mw]]
(unnest-table pathvec mw nested-table)))
(cond-> [entry]
(nil? middleware) (assoc-in [0 3] default-middleware))))
(vector? x)
(let [[context-pathvec & maybe-middleware+entries] entry
middleware (if-not (vector?
(first maybe-middleware+entries))
(first maybe-middleware+entries))
entries (if middleware
(next maybe-middleware+entries)
maybe-middleware+entries)]
(unnest-table context-pathvec middleware entries))))
(unnest-table [context-pathvec default-middleware entries]
(mapv (fn [[_ pathvec :as unnested-entry]]
(assoc unnested-entry 1
(with-meta (into context-pathvec pathvec)
{:context (into context-pathvec
(:context (meta pathvec)))})))
(mapcat (partial unnest-entry default-middleware) entries)))]
(unnest-table [] nil dispatch-table)))
(defn- keywords->symbols
"Converts keywords in xs to symbols, leaving other items unchanged."
[xs]
(mapv #(if (keyword? %)
(symbol (name %))
%)
xs))
(defn- variable? [x]
(or (keyword? x) (symbol? x)))
(defn compare-pathvecs
"Uses lexicographic order. Variables come before literal strings (so
that /foo/:id sorts before /foo/bar)."
[pathvec1 pathvec2]
(loop [pv1 (seq pathvec1)
pv2 (seq pathvec2)]
(cond
(nil? pv1) (if (nil? pv2) 0 -1)
(nil? pv2) 1
:else
(let [seg1 (first pv1)
seg2 (first pv2)]
(cond
(variable? seg1) (if (variable? seg2)
(let [res (compare (name seg1) (name seg2))]
(if (zero? res)
(recur (next pv1) (next pv2))
res))
-1)
(variable? seg2) 1
:else (let [res (compare seg1 seg2)]
(if (zero? res)
(recur (next pv1) (next pv2))
res)))))))
(defn compare-route-specs
"Uses compare-pathvecs first, breaking ties by comparing methods."
[[method1 pathvec1] [method2 pathvec2]]
(let [res (compare-pathvecs pathvec1 pathvec2)]
(if (zero? res)
(compare method1 method2)
res)))
(defn sort-dispatch-table
[dispatch-table]
(vec (sort compare-route-specs dispatch-table)))
(defn- sorted-routes
"Converts the given map of route specs -> * to a sorted map."
[routes]
(into (sorted-map-by compare-route-specs) routes))
(defn- caching-get
[m k f]
(if (contains? m k)
[m (get m k)]
(let [new-value (f)
new-map (assoc m k new-value)]
[new-map new-value])))
(def ^:private suppress-metadata-keys
"Keys to suppress when producing debugging output about function metadata; the goal is to present
just the non-standard metadata."
(cons :function (-> #'map meta keys)))
(defn- analyze*
[[routes handlers middleware namespaces-metadata] arg-resolvers dispatch-table-entry]
(if-let [[method pathvec verb-fn-sym mw-spec] dispatch-table-entry]
(t/track
(format "Analyzing resource handler function `%s'." verb-fn-sym)
(let [handler-key (gensym "handler-key__")
routes' (assoc routes
[method (keywords->symbols pathvec)] handler-key)
[middleware' middleware-key] (caching-get middleware mw-spec #(gensym "middleware-key__"))
ns-symbol (-> verb-fn-sym namespace symbol)
[namespaces-metadata' ns-metadata] (caching-get namespaces-metadata ns-symbol
#(binding [*ns* (the-ns ns-symbol)]
(-> *ns* meta eval (dissoc :doc))))
metadata (merge ns-metadata
{:function (str verb-fn-sym)}
(meta (resolve verb-fn-sym)))
_ (l/tracef "Analyzing function `%s' w/ metadata: %s"
(:function metadata)
(utils/pretty-print (apply dissoc metadata suppress-metadata-keys)))
route-params (mapv (comp symbol name)
(filter keyword? pathvec))
context (:context (meta pathvec))
;; Should it be an error if there is more than one airty on the function? We ignore
;; all but the first.
arglist (first (:arglists metadata))
;; :arg-resolvers is an option passed to compile-dispatch-table,
;; and metadata is merged onto that.
arg-resolvers (merge arg-resolvers (:arg-resolvers metadata))
handler (cond->
{:middleware-key middleware-key
:route-params route-params
:verb-fn-sym verb-fn-sym
:arglist arglist
:arg-resolvers arg-resolvers
:metadata metadata}
context
(assoc :context (string/join "/" (cons "" context))))
handlers' (assoc handlers handler-key handler)]
[routes' handlers' middleware' namespaces-metadata']))))
(declare default-arg-resolver-factories default-arg-resolvers)
(defn analyse-dispatch-table
"Returns a map holding a map of route-spec* -> handler-sym at
key :routes, a map of route-spec -> handler-map at key :handlers and
a map of middleware-symbol -> middleware-spec at key :middleware.
The structure of handler-maps is as required by handler-form;
middleware-spec is the literal form specifying the middleware in the
dispatch table; a route-spec* is a route-spec with keywords replaced
by symbols in the pathvec.
options should be a map of options or nil. Currently only one
option is supported:
:arg-resolvers
: _Default: nil_
: Map of symbol to argument resolver (keyword or function) that
serves as a default that can be extended with function or
namespace :arg-resolvers metadata. Metadata attached to this map
will be examined; if it contains a truthy value at the key
of :replace, default arg resolvers will be excluded."
[dispatch-table options]
(let [extra-arg-resolvers (:arg-resolvers options)
arg-resolvers (if (:replace (meta extra-arg-resolvers))
extra-arg-resolvers
(if (:replace-factories (meta extra-arg-resolvers))
(if (:replace-resolvers (meta extra-arg-resolvers))
extra-arg-resolvers
(merge default-arg-resolvers extra-arg-resolvers))
(if (:replace-resolvers (meta extra-arg-resolvers))
(merge default-arg-resolver-factories extra-arg-resolvers)
(merge
default-arg-resolver-factories
default-arg-resolvers
extra-arg-resolvers))))]
(loop [analyze-state nil
entries (seq (unnest-dispatch-table dispatch-table))]
(if-let [analyze-state' (analyze* analyze-state arg-resolvers (first entries))]
(recur analyze-state' (next entries))
(let [[routes handlers middleware] analyze-state]
{:routes (sorted-routes routes)
:handlers handlers
:middleware (set/map-invert middleware)})))))
(defn- map-traversal-dispatcher
"Returns a Ring handler using the given dispatch-map to guide
dispatch. Used by build-map-traversal-handler. The optional
not-found-response argument defaults to nil; pass in a closed
channel for async operation."
([dispatch-map]
(map-traversal-dispatcher dispatch-map nil))
([dispatch-map not-found-response]
(fn rook-map-traversal-dispatcher [request]
(loop [pathvec (second (request-route-spec request))
dispatch dispatch-map
route-param-vals []]
(if-let [seg (first pathvec)]
(if (contains? dispatch seg)
(recur (next pathvec) (get dispatch seg) route-param-vals)
(if-let [dispatch' (::param dispatch)]
(recur (next pathvec) dispatch' (conj route-param-vals seg))
;; no match on path
not-found-response))
(if-let [{:keys [handler route-param-keys]}
(or (get dispatch (:request-method request))
(get dispatch :all))]
(let [route-params (zipmap route-param-keys route-param-vals)]
(handler (assoc request :route-params route-params)))
;; unsupported method for path
not-found-response))))))
(defn make-header-arg-resolver [sym]
(fn [request]
(-> request :headers (get (name sym)))))
(defn make-param-arg-resolver [sym]
(let [kw (keyword sym)]
(fn [request]
(-> request :params kw))))
(defn make-request-key-resolver [sym]
(let [kw (keyword sym)]
(fn [request]
(kw request))))
(defn make-route-param-resolver [sym]
(let [kw (keyword sym)]
(fn [request]
(-> request :route-params kw))))
(defn make-resource-uri-arg-resolver [sym]
(fn [request]
(internals/resource-uri-for request)))
(defn make-injection-resolver [sym]
(let [kw (keyword sym)]
(fn [request]
(internals/get-injection request kw))))
;;; these two maps will typically be merged, but the user can ask for
;;; either to be left out
(def default-arg-resolver-factories
"A map of keyword -> (function of symbol returning a function of
request). The functions stored in this map will be used as
\"resolver factories\" (they will be passed arg symbols and expected
to produce resolvers in return). A keyword in the value position
would cause a repeated lookup."
{:request (constantly identity)
:request-key make-request-key-resolver
:header make-header-arg-resolver
:param make-param-arg-resolver
:injection make-injection-resolver
:resource-uri make-resource-uri-arg-resolver})
(def default-arg-resolvers
"A map of symbol -> (function of request). The functions will be
used as argument resolvers."
{'request identity
'params (make-request-key-resolver :params)
'params* internals/clojurized-params-arg-resolver
'resource-uri (make-resource-uri-arg-resolver 'resource-uri)})
(def ^:private default-factory-keys
(set (filter keyword? (keys default-arg-resolvers))))
(defn- symbol-for-argument [arg]
"Returns the argument symbol for an argument; this is either the argument itself or
(if a map, for destructuring) the :as key of the map."
(if (map? arg)
(if-let [as (:as arg)]
as
(throw (ex-info "map argument has no :as key"
{:arg arg})))
arg))
(defn- find-factory [arg-resolvers tag]
(loop [tag tag]
(if (keyword? tag)
(recur (get arg-resolvers tag))
tag)))
(defn- find-resolver
[arg-resolvers arg hint]
(cond
(fn? hint)
hint
(keyword? hint)
(if-let [f (find-factory arg-resolvers hint)]
(f arg)
(throw (ex-info (format "Keyword %s does not identify a known argument resolver." hint)
{:arg arg :resolver hint :arg-resolvers arg-resolvers})))
:else
(throw (ex-info (format "Argument resolver value `%s' is neither a keyword not a function." hint)
{:arg arg :resolver hint}))))
(defn- find-argument-resolver-tag
[arg-resolvers arg arg-meta]
(let [resolver-ks (filterv #(contains? arg-resolvers %)
(filter keyword? (keys arg-meta)))]
(case (count resolver-ks)
0 nil
1 (first resolver-ks)
(throw (ex-info (format "Parameter `%s' has conflicting keywords identifying its argument resolution strategy: %s."
arg
(str/join ", " resolver-ks))
{:arg arg :resolver-tags resolver-ks})))))
(defn identify-argument-resolver
"Identifies the specific argument resolver function for an argument, which can come from many sources based on
configuration in general, metadata on the argument symbol and on the function's metadata (merged with
the containing namespace's metadata).
arg-resolvers
: See the docstring on
[[io.aviso.rook.dispatcher/default-arg-resolvers]]. The map passed
to this function will have been extended with user-supplied
resolvers and/or resolver factories.
route-params
: set of keywords
arg
: Argument, a symbol or a map (for destructuring)."
[arg-resolvers route-params arg]
(let [arg-symbol (symbol-for-argument arg)
arg-meta (meta arg-symbol)]
(t/track #(format "Identifying argument resolver for `%s'." arg-symbol)
(cond
;; route param resolution takes precedence
(contains? route-params arg)
(make-route-param-resolver arg-symbol)
;; explicit ::rook/resolver metadata takes precedence for non-route params
(contains? arg-meta :io.aviso.rook/resolver)
(find-resolver arg-resolvers arg-symbol (:io.aviso.rook/resolver arg-meta))
:else
(if-let [resolver-tag (find-argument-resolver-tag
arg-resolvers arg-symbol arg-meta)]
;; explicit tags attached to the arg symbol itself come next
(find-resolver arg-resolvers arg-symbol resolver-tag)
;; non-route-param name-based resolution is implicit and
;; should not override explicit tags, so this check comes
;; last; NB. the value at arg-symbol might be a keyword
;; identifying a resolver factory, so we still need to call
;; find-resolver
(if (contains? arg-resolvers arg-symbol)
(find-resolver arg-resolvers arg-symbol (get arg-resolvers arg-symbol))
;; only static resolution is supported
(throw (ex-info
(format "Unable to identify argument resolver for symbol `%s'." arg-symbol)
{:symbol arg-symbol
:symbol-meta arg-meta
:route-params route-params
:arg-resolvers arg-resolvers}))))))))
(defn- create-arglist-resolver
"Returns a function that is passed the Ring request and returns an array of argument values which
the resource handler function can be applied to."
[arg-resolvers route-params arglist]
(if (seq arglist)
(->>
arglist
(map (partial identify-argument-resolver arg-resolvers (set route-params)))
(apply juxt))
(constantly ())))
(defn- add-dispatch-entries
[dispatch-map method pathvec handler]
(let [pathvec' (mapv #(if (variable? %) ::param %) pathvec)
dispatch-path (conj pathvec' method)
route-params (filterv variable? pathvec)]
(assoc-in dispatch-map dispatch-path
{:handler handler
:route-param-keys (mapv keyword route-params)})))
(defn- build-dispatch-map
"Returns a dispatch-map for use with map-traversal-dispatcher."
[{:keys [routes handlers middleware]}
{:keys [async? arg-resolvers]}]
(reduce (fn [dispatch-map [[method pathvec] handler-key]]
(t/track #(format "Compiling handler for `%s'."
(get-in handlers [handler-key :verb-fn-sym]))
(let [{:keys [middleware-key route-params
verb-fn-sym arglist
metadata context]
extra-resolvers :arg-resolvers}
(get handlers handler-key)
arglist-resolver (create-arglist-resolver
(if (:replace (meta extra-resolvers))
extra-resolvers
(merge
arg-resolvers
extra-resolvers))
(set route-params)
arglist)
middleware (get middleware middleware-key)
resource-handler-fn (eval verb-fn-sym)
request-handler (fn [request]
(apply resource-handler-fn (arglist-resolver request)))
request-handler (if (and async? (:sync metadata))
(internals/ring-handler->async-handler request-handler)
request-handler)
middleware-applied (or (middleware request-handler metadata) request-handler)
context-maintaining-handler (if context
(fn [request]
(-> request
(update-in [:context] str context)
middleware-applied))
middleware-applied)
logging-handler (fn [request]
(l/debugf "Matched %s to %s"
(utils/summarize-request request)
verb-fn-sym)
(context-maintaining-handler request))]
(add-dispatch-entries dispatch-map method pathvec logging-handler))))
{}
routes))
(defn build-map-traversal-handler
"Returns a form evaluating to a Ring handler that handles dispatch
by using the pathvec and method of the incoming request to look up
an endpoint function in a nested map.
Can be passed to compile-dispatch-table using the :build-handler-fn
option."
[analysed-dispatch-table opts]
(let [dispatch-map (build-dispatch-map analysed-dispatch-table opts)]
(if (:async? opts)
(map-traversal-dispatcher dispatch-map
(doto (async/chan) (async/close!)))
(map-traversal-dispatcher dispatch-map))))
(def ^:private dispatch-table-compilation-defaults
{:async? false
:arg-resolvers default-arg-resolvers
:build-handler-fn build-map-traversal-handler})
(defn compile-dispatch-table
"Compiles the dispatch table into a Ring handler.
See the docstring of unnest-dispatch-table for a description of
dispatch table format.
Supported options and their default values:
:async?
: _Default: false_
: Determines the way in which middleware is applied to the terminal
handler. Pass in true when compiling async handlers.
: Note that when async is enabled, you must be careful to only apply middleware that
is appropriately async aware.
:build-handler-fn
: _Default: [[build-map-traversal-handler]]_
: Will be called with routes, handlers, middleware and should
produce a Ring handler.
:arg-resolvers
: _Default: [[io.aviso.rook.dispatcher/default-arg-resolvers]]_
: Map of symbol to (keyword or function of request) or keyword
to (function of symbol returning function of request). Entries of
the former provide argument resolvers to be used when resolving
arguments named by the given symbol; in the keyword case, a known
resolver factory will be used. Entries of the latter type
introduce custom resolver factories. Tag with {:replace true} to
exclude default resolvers and resolver factories; tag with
{:replace-resolvers true} or {:replace-factories true} to leave
out default resolvers or resolver factories, respectively."
([dispatch-table]
(compile-dispatch-table
dispatch-table-compilation-defaults
dispatch-table))
([options dispatch-table]
(let [options (merge dispatch-table-compilation-defaults options)
build-handler (:build-handler-fn options)
analysed-dispatch-table (analyse-dispatch-table
dispatch-table options)]
(build-handler analysed-dispatch-table options))))
(defn- simple-namespace-dispatch-table
"Examines the given namespace and produces a dispatch table in a
format intelligible to compile-dispatch-table."
([ns-sym]
(simple-namespace-dispatch-table [] ns-sym))
([context-pathvec ns-sym]
(simple-namespace-dispatch-table context-pathvec ns-sym default-namespace-middleware))
([context-pathvec ns-sym middleware]
(t/track
#(format "Identifying resource handler functions in `%s'." ns-sym)
(try
(if-not (find-ns ns-sym)
(require ns-sym))
(catch Exception e
(throw (ex-info "failed to require ns in namespace-dispatch-table"
{:context-pathvec context-pathvec
:ns ns-sym
:middleware middleware}
e))))
[(->> ns-sym
ns-publics
(keep (fn [[k v]]
(if (ifn? @v)
(t/track #(format "Building route mapping for `%s/%s'." ns-sym k)
(if-let [route-spec (or (:route-spec (meta v))
(path-spec->route-spec
(:path-spec (meta v)))
(get default-mappings k))]
(conj route-spec (symbol (name ns-sym) (name k))))))))
(list* context-pathvec middleware)
vec)])))
(defn canonicalize-ns-specs
"Handles unnesting of ns-specs."
[outer-context-pathvec outer-middleware ns-specs]
(mapcat (fn [[context-pathvec? ns-sym middleware? :as ns-spec]]
(t/track (format "Parsing namespace specification `%s'." (pr-str ns-spec))
(let [context-pathvec (if (or (nil? context-pathvec?)
(vector? context-pathvec?))
(or context-pathvec? []))
middleware (let [mw? (if context-pathvec
middleware?
ns-sym)]
(if-not (vector? mw?)
mw?))
ns-sym (if context-pathvec
ns-sym
context-pathvec?)
skip (reduce + 1
(map #(if % 1 0)
[context-pathvec middleware]))
nested (drop skip ns-spec)]
(assert (symbol? ns-sym)
(str "Malformed ns-spec: " (pr-str ns-sym)))
(concat
[[(into outer-context-pathvec context-pathvec)
ns-sym
(or middleware outer-middleware)]]
(canonicalize-ns-specs
(into outer-context-pathvec context-pathvec)
(or middleware outer-middleware)
nested)))))
ns-specs))
(def ^:private default-opts
{:context-pathvec []
:default-middleware default-namespace-middleware})
(defn namespace-dispatch-table
"Similar to [[io.aviso.rook/namespace-handler]], but stops short of
producing a handler, returning a dispatch table instead. See the
docstring of [[io.aviso.rook/namespace-handler]] for a description
of ns-spec syntax and a list of supported options (NB. `async?` is
irrelevant to the shape of the dispatch table).
The resulting dispatch table in its unnested form will include
entries such as
[:get [\"api\" \"foo\"] 'example.foo/index ns-middleware]."
[options? & ns-specs]
(let [opts (merge default-opts (if (map? options?) options?))
{outer-context-pathvec :context-pathvec
default-middleware :default-middleware} opts
ns-specs (canonicalize-ns-specs
[]
default-middleware
(if (map? options?)
ns-specs
(cons options? ns-specs)))]
[(reduce into [outer-context-pathvec default-middleware]
(map (fn [[context-pathvec ns-sym middleware]]
(simple-namespace-dispatch-table
context-pathvec ns-sym middleware))
ns-specs))]))
| 15622 | (ns io.aviso.rook.dispatcher
"This namespace deals with dispatch tables mapping route specs of
the form
[method [path-segment ...]]
to resource handler functions. The recognized format is described at
length in the docstrings of the [[unnest-dispatch-table]] and
[[request-route-spec]] functions exported by this namespace.
User code interested in setting up a handler for a RESTful API will
typically not interact with this namespace directly; rather, it will
use [[io.aviso.rook/namespace-handler]]. Functions exported by this
namespace can be useful, however, to code that wishes to use the
dispatcher in a more flexible way (perhaps avoiding the namespace to
resource correspondence) and utility add-ons that wish to deal with
dispatch tables directly.
The expected way to use this namespace is as follows:
- namespaces correspond to resources;
- [[namespace-dispatch-table]] produces a dispatch table for a single
namespace
- any number of such dispatch tables can be concatenated to form a
dispatch table for a collection of resources
- such compound dispatch tables can be compiled using
[[compile-dispatch-table]].
The individual resource handler functions are expected to support a
single arity only. The arglist for that arity and the metadata on
the resource handler function will be examined to determine the
correct argument resolution strategy at dispatch table compilation
time."
{:added "0.1.10"}
(:require [clojure.core.async :as async]
[clojure.string :as string]
[clojure.set :as set]
[io.aviso.tracker :as t]
[io.aviso.rook.internals :as internals]
[clojure.string :as str]
[clojure.tools.logging :as l]
[io.aviso.rook.utils :as utils]))
(def ^:private default-mappings
"Default function -> route spec mappings.
Namespace dispatch tables will by default include entries for public
Vars named by the keys in this map, with methods and pathvecs
provided by the values."
{
'new [:get ["new"]]
'edit [:get [:id "edit"]]
'show [:get [:id]]
'update [:put [:id]]
'patch [:patch [:id]]
'destroy [:delete [:id]]
'index [:get []]
'create [:post []]
}
)
(defn default-namespace-middleware
"Default namespace middleware that ignores the metadata and returns the handler unchanged.
Namespace middleware is slightly different than Ring middleware, as the metadata from
the function is available. Namespace middleware may also return nil."
[handler metadata]
handler)
(defn- request-route-spec
"Takes a Ring request map and returns `[method pathvec]`, where method
is a request method keyword and pathvec is a vector of path
segments.
For example,
GET /foo/bar HTTP/1.1
become:
[:get [\"foo\" \"bar\"]]
The individual path segments are URL decoded; UTF-8 encoding is
assumed."
[request]
[(:request-method request)
(mapv #(java.net.URLDecoder/decode ^String % "UTF-8")
(next (string/split (:uri request) #"/" 0)))])
(defn path-spec->route-spec
"Takes a path-spec in the format `[:method \"/path/:param\"]` and
returns the equivalent route-spec in the format `[:method
[\"path\" :param]]`. If passed nil as input, returns nil."
[path-spec]
(if-not (nil? path-spec)
(let [[method path] path-spec
_ (assert (instance? String path))
paramify (fn [seg]
(if (.startsWith ^String seg ":")
(keyword (subs seg 1))
seg))]
[method (mapv paramify (next (string/split path #"/" 0)))])))
(defn pathvec->path [pathvec]
(if (seq pathvec)
(string/join "/" (cons nil pathvec))
"/"))
(defn route-spec->path-spec
"Takes a route-spec in the format `[:method [\"path\" :param ...]]`
and returns the equivalent path-spec in the format `[:method
\"/path/:param\"]`. If passed nil as input, returns nil."
[route-spec]
(if-not (nil? route-spec)
(let [[method pathvec] route-spec]
[method (pathvec->path pathvec)])))
(defn unnest-dispatch-table
"Given a nested dispatch table:
[[method pathvec verb-fn middleware
[method' pathvec' verb-fn' middleware' ...]
...]
...]
produces a dispatch table with no nesting:
[[method pathvec verb-fn middleware]
[method' (into pathvec pathvec') verb-fn' middleware']
...]
Entries may also take the alternative form of
[pathvec middleware? & entries],
in which case pathvec and middleware? (if present) will provide a
context pathvec and default middleware for the nested entries
without introducing a separate route."
[dispatch-table]
(letfn [(unnest-entry [default-middleware [x :as entry]]
(cond
(keyword? x)
(let [[method pathvec verb-fn middleware & nested-table] entry]
(if nested-table
(let [mw (or middleware default-middleware)]
(into [[method pathvec verb-fn mw]]
(unnest-table pathvec mw nested-table)))
(cond-> [entry]
(nil? middleware) (assoc-in [0 3] default-middleware))))
(vector? x)
(let [[context-pathvec & maybe-middleware+entries] entry
middleware (if-not (vector?
(first maybe-middleware+entries))
(first maybe-middleware+entries))
entries (if middleware
(next maybe-middleware+entries)
maybe-middleware+entries)]
(unnest-table context-pathvec middleware entries))))
(unnest-table [context-pathvec default-middleware entries]
(mapv (fn [[_ pathvec :as unnested-entry]]
(assoc unnested-entry 1
(with-meta (into context-pathvec pathvec)
{:context (into context-pathvec
(:context (meta pathvec)))})))
(mapcat (partial unnest-entry default-middleware) entries)))]
(unnest-table [] nil dispatch-table)))
(defn- keywords->symbols
"Converts keywords in xs to symbols, leaving other items unchanged."
[xs]
(mapv #(if (keyword? %)
(symbol (name %))
%)
xs))
(defn- variable? [x]
(or (keyword? x) (symbol? x)))
(defn compare-pathvecs
"Uses lexicographic order. Variables come before literal strings (so
that /foo/:id sorts before /foo/bar)."
[pathvec1 pathvec2]
(loop [pv1 (seq pathvec1)
pv2 (seq pathvec2)]
(cond
(nil? pv1) (if (nil? pv2) 0 -1)
(nil? pv2) 1
:else
(let [seg1 (first pv1)
seg2 (first pv2)]
(cond
(variable? seg1) (if (variable? seg2)
(let [res (compare (name seg1) (name seg2))]
(if (zero? res)
(recur (next pv1) (next pv2))
res))
-1)
(variable? seg2) 1
:else (let [res (compare seg1 seg2)]
(if (zero? res)
(recur (next pv1) (next pv2))
res)))))))
(defn compare-route-specs
"Uses compare-pathvecs first, breaking ties by comparing methods."
[[method1 pathvec1] [method2 pathvec2]]
(let [res (compare-pathvecs pathvec1 pathvec2)]
(if (zero? res)
(compare method1 method2)
res)))
(defn sort-dispatch-table
[dispatch-table]
(vec (sort compare-route-specs dispatch-table)))
(defn- sorted-routes
"Converts the given map of route specs -> * to a sorted map."
[routes]
(into (sorted-map-by compare-route-specs) routes))
(defn- caching-get
[m k f]
(if (contains? m k)
[m (get m k)]
(let [new-value (f)
new-map (assoc m k new-value)]
[new-map new-value])))
(def ^:private suppress-metadata-keys
"Keys to suppress when producing debugging output about function metadata; the goal is to present
just the non-standard metadata."
(cons :function (-> #'map meta keys)))
(defn- analyze*
[[routes handlers middleware namespaces-metadata] arg-resolvers dispatch-table-entry]
(if-let [[method pathvec verb-fn-sym mw-spec] dispatch-table-entry]
(t/track
(format "Analyzing resource handler function `%s'." verb-fn-sym)
(let [handler-key (<KEY> "handler-key__")
routes' (assoc routes
[method (keywords->symbols pathvec)] handler-key)
[middleware' middleware-key] (caching-get middleware mw-spec #(gensym "middleware-key__"))
ns-symbol (-> verb-fn-sym namespace symbol)
[namespaces-metadata' ns-metadata] (caching-get namespaces-metadata ns-symbol
#(binding [*ns* (the-ns ns-symbol)]
(-> *ns* meta eval (dissoc :doc))))
metadata (merge ns-metadata
{:function (str verb-fn-sym)}
(meta (resolve verb-fn-sym)))
_ (l/tracef "Analyzing function `%s' w/ metadata: %s"
(:function metadata)
(utils/pretty-print (apply dissoc metadata suppress-metadata-keys)))
route-params (mapv (comp symbol name)
(filter keyword? pathvec))
context (:context (meta pathvec))
;; Should it be an error if there is more than one airty on the function? We ignore
;; all but the first.
arglist (first (:arglists metadata))
;; :arg-resolvers is an option passed to compile-dispatch-table,
;; and metadata is merged onto that.
arg-resolvers (merge arg-resolvers (:arg-resolvers metadata))
handler (cond->
{:middleware-key middleware-key
:route-params route-params
:verb-fn-sym verb-fn-sym
:arglist arglist
:arg-resolvers arg-resolvers
:metadata metadata}
context
(assoc :context (string/join "/" (cons "" context))))
handlers' (assoc handlers handler-key handler)]
[routes' handlers' middleware' namespaces-metadata']))))
(declare default-arg-resolver-factories default-arg-resolvers)
(defn analyse-dispatch-table
"Returns a map holding a map of route-spec* -> handler-sym at
key :routes, a map of route-spec -> handler-map at key :handlers and
a map of middleware-symbol -> middleware-spec at key :middleware.
The structure of handler-maps is as required by handler-form;
middleware-spec is the literal form specifying the middleware in the
dispatch table; a route-spec* is a route-spec with keywords replaced
by symbols in the pathvec.
options should be a map of options or nil. Currently only one
option is supported:
:arg-resolvers
: _Default: nil_
: Map of symbol to argument resolver (keyword or function) that
serves as a default that can be extended with function or
namespace :arg-resolvers metadata. Metadata attached to this map
will be examined; if it contains a truthy value at the key
of :replace, default arg resolvers will be excluded."
[dispatch-table options]
(let [extra-arg-resolvers (:arg-resolvers options)
arg-resolvers (if (:replace (meta extra-arg-resolvers))
extra-arg-resolvers
(if (:replace-factories (meta extra-arg-resolvers))
(if (:replace-resolvers (meta extra-arg-resolvers))
extra-arg-resolvers
(merge default-arg-resolvers extra-arg-resolvers))
(if (:replace-resolvers (meta extra-arg-resolvers))
(merge default-arg-resolver-factories extra-arg-resolvers)
(merge
default-arg-resolver-factories
default-arg-resolvers
extra-arg-resolvers))))]
(loop [analyze-state nil
entries (seq (unnest-dispatch-table dispatch-table))]
(if-let [analyze-state' (analyze* analyze-state arg-resolvers (first entries))]
(recur analyze-state' (next entries))
(let [[routes handlers middleware] analyze-state]
{:routes (sorted-routes routes)
:handlers handlers
:middleware (set/map-invert middleware)})))))
(defn- map-traversal-dispatcher
"Returns a Ring handler using the given dispatch-map to guide
dispatch. Used by build-map-traversal-handler. The optional
not-found-response argument defaults to nil; pass in a closed
channel for async operation."
([dispatch-map]
(map-traversal-dispatcher dispatch-map nil))
([dispatch-map not-found-response]
(fn rook-map-traversal-dispatcher [request]
(loop [pathvec (second (request-route-spec request))
dispatch dispatch-map
route-param-vals []]
(if-let [seg (first pathvec)]
(if (contains? dispatch seg)
(recur (next pathvec) (get dispatch seg) route-param-vals)
(if-let [dispatch' (::param dispatch)]
(recur (next pathvec) dispatch' (conj route-param-vals seg))
;; no match on path
not-found-response))
(if-let [{:keys [handler route-param-keys]}
(or (get dispatch (:request-method request))
(get dispatch :all))]
(let [route-params (zipmap route-param-keys route-param-vals)]
(handler (assoc request :route-params route-params)))
;; unsupported method for path
not-found-response))))))
(defn make-header-arg-resolver [sym]
(fn [request]
(-> request :headers (get (name sym)))))
(defn make-param-arg-resolver [sym]
(let [kw (keyword sym)]
(fn [request]
(-> request :params kw))))
(defn make-request-key-resolver [sym]
(let [kw (keyword sym)]
(fn [request]
(kw request))))
(defn make-route-param-resolver [sym]
(let [kw (keyword sym)]
(fn [request]
(-> request :route-params kw))))
(defn make-resource-uri-arg-resolver [sym]
(fn [request]
(internals/resource-uri-for request)))
(defn make-injection-resolver [sym]
(let [kw (keyword sym)]
(fn [request]
(internals/get-injection request kw))))
;;; these two maps will typically be merged, but the user can ask for
;;; either to be left out
(def default-arg-resolver-factories
"A map of keyword -> (function of symbol returning a function of
request). The functions stored in this map will be used as
\"resolver factories\" (they will be passed arg symbols and expected
to produce resolvers in return). A keyword in the value position
would cause a repeated lookup."
{:request (constantly identity)
:request-key make-request-key-resolver
:header make-header-arg-resolver
:param make-param-arg-resolver
:injection make-injection-resolver
:resource-uri make-resource-uri-arg-resolver})
(def default-arg-resolvers
"A map of symbol -> (function of request). The functions will be
used as argument resolvers."
{'request identity
'params (make-request-key-resolver :params)
'params* internals/clojurized-params-arg-resolver
'resource-uri (make-resource-uri-arg-resolver 'resource-uri)})
(def ^:private default-factory-keys
(set (filter keyword? (keys default-arg-resolvers))))
(defn- symbol-for-argument [arg]
"Returns the argument symbol for an argument; this is either the argument itself or
(if a map, for destructuring) the :as key of the map."
(if (map? arg)
(if-let [as (:as arg)]
as
(throw (ex-info "map argument has no :as key"
{:arg arg})))
arg))
(defn- find-factory [arg-resolvers tag]
(loop [tag tag]
(if (keyword? tag)
(recur (get arg-resolvers tag))
tag)))
(defn- find-resolver
[arg-resolvers arg hint]
(cond
(fn? hint)
hint
(keyword? hint)
(if-let [f (find-factory arg-resolvers hint)]
(f arg)
(throw (ex-info (format "Keyword %s does not identify a known argument resolver." hint)
{:arg arg :resolver hint :arg-resolvers arg-resolvers})))
:else
(throw (ex-info (format "Argument resolver value `%s' is neither a keyword not a function." hint)
{:arg arg :resolver hint}))))
(defn- find-argument-resolver-tag
[arg-resolvers arg arg-meta]
(let [resolver-ks (filterv #(contains? arg-resolvers %)
(filter keyword? (keys arg-meta)))]
(case (count resolver-ks)
0 nil
1 (first resolver-ks)
(throw (ex-info (format "Parameter `%s' has conflicting keywords identifying its argument resolution strategy: %s."
arg
(str/join ", " resolver-ks))
{:arg arg :resolver-tags resolver-ks})))))
(defn identify-argument-resolver
"Identifies the specific argument resolver function for an argument, which can come from many sources based on
configuration in general, metadata on the argument symbol and on the function's metadata (merged with
the containing namespace's metadata).
arg-resolvers
: See the docstring on
[[io.aviso.rook.dispatcher/default-arg-resolvers]]. The map passed
to this function will have been extended with user-supplied
resolvers and/or resolver factories.
route-params
: set of keywords
arg
: Argument, a symbol or a map (for destructuring)."
[arg-resolvers route-params arg]
(let [arg-symbol (symbol-for-argument arg)
arg-meta (meta arg-symbol)]
(t/track #(format "Identifying argument resolver for `%s'." arg-symbol)
(cond
;; route param resolution takes precedence
(contains? route-params arg)
(make-route-param-resolver arg-symbol)
;; explicit ::rook/resolver metadata takes precedence for non-route params
(contains? arg-meta :io.aviso.rook/resolver)
(find-resolver arg-resolvers arg-symbol (:io.aviso.rook/resolver arg-meta))
:else
(if-let [resolver-tag (find-argument-resolver-tag
arg-resolvers arg-symbol arg-meta)]
;; explicit tags attached to the arg symbol itself come next
(find-resolver arg-resolvers arg-symbol resolver-tag)
;; non-route-param name-based resolution is implicit and
;; should not override explicit tags, so this check comes
;; last; NB. the value at arg-symbol might be a keyword
;; identifying a resolver factory, so we still need to call
;; find-resolver
(if (contains? arg-resolvers arg-symbol)
(find-resolver arg-resolvers arg-symbol (get arg-resolvers arg-symbol))
;; only static resolution is supported
(throw (ex-info
(format "Unable to identify argument resolver for symbol `%s'." arg-symbol)
{:symbol arg-symbol
:symbol-meta arg-meta
:route-params route-params
:arg-resolvers arg-resolvers}))))))))
(defn- create-arglist-resolver
"Returns a function that is passed the Ring request and returns an array of argument values which
the resource handler function can be applied to."
[arg-resolvers route-params arglist]
(if (seq arglist)
(->>
arglist
(map (partial identify-argument-resolver arg-resolvers (set route-params)))
(apply juxt))
(constantly ())))
(defn- add-dispatch-entries
[dispatch-map method pathvec handler]
(let [pathvec' (mapv #(if (variable? %) ::param %) pathvec)
dispatch-path (conj pathvec' method)
route-params (filterv variable? pathvec)]
(assoc-in dispatch-map dispatch-path
{:handler handler
:route-param-keys (mapv keyword route-params)})))
(defn- build-dispatch-map
"Returns a dispatch-map for use with map-traversal-dispatcher."
[{:keys [routes handlers middleware]}
{:keys [async? arg-resolvers]}]
(reduce (fn [dispatch-map [[method pathvec] handler-key]]
(t/track #(format "Compiling handler for `%s'."
(get-in handlers [handler-key :verb-fn-sym]))
(let [{:keys [middleware-key route-params
verb-fn-sym arglist
metadata context]
extra-resolvers :arg-resolvers}
(get handlers handler-key)
arglist-resolver (create-arglist-resolver
(if (:replace (meta extra-resolvers))
extra-resolvers
(merge
arg-resolvers
extra-resolvers))
(set route-params)
arglist)
middleware (get middleware middleware-key)
resource-handler-fn (eval verb-fn-sym)
request-handler (fn [request]
(apply resource-handler-fn (arglist-resolver request)))
request-handler (if (and async? (:sync metadata))
(internals/ring-handler->async-handler request-handler)
request-handler)
middleware-applied (or (middleware request-handler metadata) request-handler)
context-maintaining-handler (if context
(fn [request]
(-> request
(update-in [:context] str context)
middleware-applied))
middleware-applied)
logging-handler (fn [request]
(l/debugf "Matched %s to %s"
(utils/summarize-request request)
verb-fn-sym)
(context-maintaining-handler request))]
(add-dispatch-entries dispatch-map method pathvec logging-handler))))
{}
routes))
(defn build-map-traversal-handler
"Returns a form evaluating to a Ring handler that handles dispatch
by using the pathvec and method of the incoming request to look up
an endpoint function in a nested map.
Can be passed to compile-dispatch-table using the :build-handler-fn
option."
[analysed-dispatch-table opts]
(let [dispatch-map (build-dispatch-map analysed-dispatch-table opts)]
(if (:async? opts)
(map-traversal-dispatcher dispatch-map
(doto (async/chan) (async/close!)))
(map-traversal-dispatcher dispatch-map))))
(def ^:private dispatch-table-compilation-defaults
{:async? false
:arg-resolvers default-arg-resolvers
:build-handler-fn build-map-traversal-handler})
(defn compile-dispatch-table
"Compiles the dispatch table into a Ring handler.
See the docstring of unnest-dispatch-table for a description of
dispatch table format.
Supported options and their default values:
:async?
: _Default: false_
: Determines the way in which middleware is applied to the terminal
handler. Pass in true when compiling async handlers.
: Note that when async is enabled, you must be careful to only apply middleware that
is appropriately async aware.
:build-handler-fn
: _Default: [[build-map-traversal-handler]]_
: Will be called with routes, handlers, middleware and should
produce a Ring handler.
:arg-resolvers
: _Default: [[io.aviso.rook.dispatcher/default-arg-resolvers]]_
: Map of symbol to (keyword or function of request) or keyword
to (function of symbol returning function of request). Entries of
the former provide argument resolvers to be used when resolving
arguments named by the given symbol; in the keyword case, a known
resolver factory will be used. Entries of the latter type
introduce custom resolver factories. Tag with {:replace true} to
exclude default resolvers and resolver factories; tag with
{:replace-resolvers true} or {:replace-factories true} to leave
out default resolvers or resolver factories, respectively."
([dispatch-table]
(compile-dispatch-table
dispatch-table-compilation-defaults
dispatch-table))
([options dispatch-table]
(let [options (merge dispatch-table-compilation-defaults options)
build-handler (:build-handler-fn options)
analysed-dispatch-table (analyse-dispatch-table
dispatch-table options)]
(build-handler analysed-dispatch-table options))))
(defn- simple-namespace-dispatch-table
"Examines the given namespace and produces a dispatch table in a
format intelligible to compile-dispatch-table."
([ns-sym]
(simple-namespace-dispatch-table [] ns-sym))
([context-pathvec ns-sym]
(simple-namespace-dispatch-table context-pathvec ns-sym default-namespace-middleware))
([context-pathvec ns-sym middleware]
(t/track
#(format "Identifying resource handler functions in `%s'." ns-sym)
(try
(if-not (find-ns ns-sym)
(require ns-sym))
(catch Exception e
(throw (ex-info "failed to require ns in namespace-dispatch-table"
{:context-pathvec context-pathvec
:ns ns-sym
:middleware middleware}
e))))
[(->> ns-sym
ns-publics
(keep (fn [[k v]]
(if (ifn? @v)
(t/track #(format "Building route mapping for `%s/%s'." ns-sym k)
(if-let [route-spec (or (:route-spec (meta v))
(path-spec->route-spec
(:path-spec (meta v)))
(get default-mappings k))]
(conj route-spec (symbol (name ns-sym) (name k))))))))
(list* context-pathvec middleware)
vec)])))
(defn canonicalize-ns-specs
"Handles unnesting of ns-specs."
[outer-context-pathvec outer-middleware ns-specs]
(mapcat (fn [[context-pathvec? ns-sym middleware? :as ns-spec]]
(t/track (format "Parsing namespace specification `%s'." (pr-str ns-spec))
(let [context-pathvec (if (or (nil? context-pathvec?)
(vector? context-pathvec?))
(or context-pathvec? []))
middleware (let [mw? (if context-pathvec
middleware?
ns-sym)]
(if-not (vector? mw?)
mw?))
ns-sym (if context-pathvec
ns-sym
context-pathvec?)
skip (reduce + 1
(map #(if % 1 0)
[context-pathvec middleware]))
nested (drop skip ns-spec)]
(assert (symbol? ns-sym)
(str "Malformed ns-spec: " (pr-str ns-sym)))
(concat
[[(into outer-context-pathvec context-pathvec)
ns-sym
(or middleware outer-middleware)]]
(canonicalize-ns-specs
(into outer-context-pathvec context-pathvec)
(or middleware outer-middleware)
nested)))))
ns-specs))
(def ^:private default-opts
{:context-pathvec []
:default-middleware default-namespace-middleware})
(defn namespace-dispatch-table
"Similar to [[io.aviso.rook/namespace-handler]], but stops short of
producing a handler, returning a dispatch table instead. See the
docstring of [[io.aviso.rook/namespace-handler]] for a description
of ns-spec syntax and a list of supported options (NB. `async?` is
irrelevant to the shape of the dispatch table).
The resulting dispatch table in its unnested form will include
entries such as
[:get [\"api\" \"foo\"] 'example.foo/index ns-middleware]."
[options? & ns-specs]
(let [opts (merge default-opts (if (map? options?) options?))
{outer-context-pathvec :context-pathvec
default-middleware :default-middleware} opts
ns-specs (canonicalize-ns-specs
[]
default-middleware
(if (map? options?)
ns-specs
(cons options? ns-specs)))]
[(reduce into [outer-context-pathvec default-middleware]
(map (fn [[context-pathvec ns-sym middleware]]
(simple-namespace-dispatch-table
context-pathvec ns-sym middleware))
ns-specs))]))
| true | (ns io.aviso.rook.dispatcher
"This namespace deals with dispatch tables mapping route specs of
the form
[method [path-segment ...]]
to resource handler functions. The recognized format is described at
length in the docstrings of the [[unnest-dispatch-table]] and
[[request-route-spec]] functions exported by this namespace.
User code interested in setting up a handler for a RESTful API will
typically not interact with this namespace directly; rather, it will
use [[io.aviso.rook/namespace-handler]]. Functions exported by this
namespace can be useful, however, to code that wishes to use the
dispatcher in a more flexible way (perhaps avoiding the namespace to
resource correspondence) and utility add-ons that wish to deal with
dispatch tables directly.
The expected way to use this namespace is as follows:
- namespaces correspond to resources;
- [[namespace-dispatch-table]] produces a dispatch table for a single
namespace
- any number of such dispatch tables can be concatenated to form a
dispatch table for a collection of resources
- such compound dispatch tables can be compiled using
[[compile-dispatch-table]].
The individual resource handler functions are expected to support a
single arity only. The arglist for that arity and the metadata on
the resource handler function will be examined to determine the
correct argument resolution strategy at dispatch table compilation
time."
{:added "0.1.10"}
(:require [clojure.core.async :as async]
[clojure.string :as string]
[clojure.set :as set]
[io.aviso.tracker :as t]
[io.aviso.rook.internals :as internals]
[clojure.string :as str]
[clojure.tools.logging :as l]
[io.aviso.rook.utils :as utils]))
(def ^:private default-mappings
"Default function -> route spec mappings.
Namespace dispatch tables will by default include entries for public
Vars named by the keys in this map, with methods and pathvecs
provided by the values."
{
'new [:get ["new"]]
'edit [:get [:id "edit"]]
'show [:get [:id]]
'update [:put [:id]]
'patch [:patch [:id]]
'destroy [:delete [:id]]
'index [:get []]
'create [:post []]
}
)
(defn default-namespace-middleware
"Default namespace middleware that ignores the metadata and returns the handler unchanged.
Namespace middleware is slightly different than Ring middleware, as the metadata from
the function is available. Namespace middleware may also return nil."
[handler metadata]
handler)
(defn- request-route-spec
"Takes a Ring request map and returns `[method pathvec]`, where method
is a request method keyword and pathvec is a vector of path
segments.
For example,
GET /foo/bar HTTP/1.1
become:
[:get [\"foo\" \"bar\"]]
The individual path segments are URL decoded; UTF-8 encoding is
assumed."
[request]
[(:request-method request)
(mapv #(java.net.URLDecoder/decode ^String % "UTF-8")
(next (string/split (:uri request) #"/" 0)))])
(defn path-spec->route-spec
"Takes a path-spec in the format `[:method \"/path/:param\"]` and
returns the equivalent route-spec in the format `[:method
[\"path\" :param]]`. If passed nil as input, returns nil."
[path-spec]
(if-not (nil? path-spec)
(let [[method path] path-spec
_ (assert (instance? String path))
paramify (fn [seg]
(if (.startsWith ^String seg ":")
(keyword (subs seg 1))
seg))]
[method (mapv paramify (next (string/split path #"/" 0)))])))
(defn pathvec->path [pathvec]
(if (seq pathvec)
(string/join "/" (cons nil pathvec))
"/"))
(defn route-spec->path-spec
"Takes a route-spec in the format `[:method [\"path\" :param ...]]`
and returns the equivalent path-spec in the format `[:method
\"/path/:param\"]`. If passed nil as input, returns nil."
[route-spec]
(if-not (nil? route-spec)
(let [[method pathvec] route-spec]
[method (pathvec->path pathvec)])))
(defn unnest-dispatch-table
"Given a nested dispatch table:
[[method pathvec verb-fn middleware
[method' pathvec' verb-fn' middleware' ...]
...]
...]
produces a dispatch table with no nesting:
[[method pathvec verb-fn middleware]
[method' (into pathvec pathvec') verb-fn' middleware']
...]
Entries may also take the alternative form of
[pathvec middleware? & entries],
in which case pathvec and middleware? (if present) will provide a
context pathvec and default middleware for the nested entries
without introducing a separate route."
[dispatch-table]
(letfn [(unnest-entry [default-middleware [x :as entry]]
(cond
(keyword? x)
(let [[method pathvec verb-fn middleware & nested-table] entry]
(if nested-table
(let [mw (or middleware default-middleware)]
(into [[method pathvec verb-fn mw]]
(unnest-table pathvec mw nested-table)))
(cond-> [entry]
(nil? middleware) (assoc-in [0 3] default-middleware))))
(vector? x)
(let [[context-pathvec & maybe-middleware+entries] entry
middleware (if-not (vector?
(first maybe-middleware+entries))
(first maybe-middleware+entries))
entries (if middleware
(next maybe-middleware+entries)
maybe-middleware+entries)]
(unnest-table context-pathvec middleware entries))))
(unnest-table [context-pathvec default-middleware entries]
(mapv (fn [[_ pathvec :as unnested-entry]]
(assoc unnested-entry 1
(with-meta (into context-pathvec pathvec)
{:context (into context-pathvec
(:context (meta pathvec)))})))
(mapcat (partial unnest-entry default-middleware) entries)))]
(unnest-table [] nil dispatch-table)))
(defn- keywords->symbols
"Converts keywords in xs to symbols, leaving other items unchanged."
[xs]
(mapv #(if (keyword? %)
(symbol (name %))
%)
xs))
(defn- variable? [x]
(or (keyword? x) (symbol? x)))
(defn compare-pathvecs
"Uses lexicographic order. Variables come before literal strings (so
that /foo/:id sorts before /foo/bar)."
[pathvec1 pathvec2]
(loop [pv1 (seq pathvec1)
pv2 (seq pathvec2)]
(cond
(nil? pv1) (if (nil? pv2) 0 -1)
(nil? pv2) 1
:else
(let [seg1 (first pv1)
seg2 (first pv2)]
(cond
(variable? seg1) (if (variable? seg2)
(let [res (compare (name seg1) (name seg2))]
(if (zero? res)
(recur (next pv1) (next pv2))
res))
-1)
(variable? seg2) 1
:else (let [res (compare seg1 seg2)]
(if (zero? res)
(recur (next pv1) (next pv2))
res)))))))
(defn compare-route-specs
"Uses compare-pathvecs first, breaking ties by comparing methods."
[[method1 pathvec1] [method2 pathvec2]]
(let [res (compare-pathvecs pathvec1 pathvec2)]
(if (zero? res)
(compare method1 method2)
res)))
(defn sort-dispatch-table
[dispatch-table]
(vec (sort compare-route-specs dispatch-table)))
(defn- sorted-routes
"Converts the given map of route specs -> * to a sorted map."
[routes]
(into (sorted-map-by compare-route-specs) routes))
(defn- caching-get
[m k f]
(if (contains? m k)
[m (get m k)]
(let [new-value (f)
new-map (assoc m k new-value)]
[new-map new-value])))
(def ^:private suppress-metadata-keys
"Keys to suppress when producing debugging output about function metadata; the goal is to present
just the non-standard metadata."
(cons :function (-> #'map meta keys)))
(defn- analyze*
[[routes handlers middleware namespaces-metadata] arg-resolvers dispatch-table-entry]
(if-let [[method pathvec verb-fn-sym mw-spec] dispatch-table-entry]
(t/track
(format "Analyzing resource handler function `%s'." verb-fn-sym)
(let [handler-key (PI:KEY:<KEY>END_PI "handler-key__")
routes' (assoc routes
[method (keywords->symbols pathvec)] handler-key)
[middleware' middleware-key] (caching-get middleware mw-spec #(gensym "middleware-key__"))
ns-symbol (-> verb-fn-sym namespace symbol)
[namespaces-metadata' ns-metadata] (caching-get namespaces-metadata ns-symbol
#(binding [*ns* (the-ns ns-symbol)]
(-> *ns* meta eval (dissoc :doc))))
metadata (merge ns-metadata
{:function (str verb-fn-sym)}
(meta (resolve verb-fn-sym)))
_ (l/tracef "Analyzing function `%s' w/ metadata: %s"
(:function metadata)
(utils/pretty-print (apply dissoc metadata suppress-metadata-keys)))
route-params (mapv (comp symbol name)
(filter keyword? pathvec))
context (:context (meta pathvec))
;; Should it be an error if there is more than one airty on the function? We ignore
;; all but the first.
arglist (first (:arglists metadata))
;; :arg-resolvers is an option passed to compile-dispatch-table,
;; and metadata is merged onto that.
arg-resolvers (merge arg-resolvers (:arg-resolvers metadata))
handler (cond->
{:middleware-key middleware-key
:route-params route-params
:verb-fn-sym verb-fn-sym
:arglist arglist
:arg-resolvers arg-resolvers
:metadata metadata}
context
(assoc :context (string/join "/" (cons "" context))))
handlers' (assoc handlers handler-key handler)]
[routes' handlers' middleware' namespaces-metadata']))))
(declare default-arg-resolver-factories default-arg-resolvers)
(defn analyse-dispatch-table
"Returns a map holding a map of route-spec* -> handler-sym at
key :routes, a map of route-spec -> handler-map at key :handlers and
a map of middleware-symbol -> middleware-spec at key :middleware.
The structure of handler-maps is as required by handler-form;
middleware-spec is the literal form specifying the middleware in the
dispatch table; a route-spec* is a route-spec with keywords replaced
by symbols in the pathvec.
options should be a map of options or nil. Currently only one
option is supported:
:arg-resolvers
: _Default: nil_
: Map of symbol to argument resolver (keyword or function) that
serves as a default that can be extended with function or
namespace :arg-resolvers metadata. Metadata attached to this map
will be examined; if it contains a truthy value at the key
of :replace, default arg resolvers will be excluded."
[dispatch-table options]
(let [extra-arg-resolvers (:arg-resolvers options)
arg-resolvers (if (:replace (meta extra-arg-resolvers))
extra-arg-resolvers
(if (:replace-factories (meta extra-arg-resolvers))
(if (:replace-resolvers (meta extra-arg-resolvers))
extra-arg-resolvers
(merge default-arg-resolvers extra-arg-resolvers))
(if (:replace-resolvers (meta extra-arg-resolvers))
(merge default-arg-resolver-factories extra-arg-resolvers)
(merge
default-arg-resolver-factories
default-arg-resolvers
extra-arg-resolvers))))]
(loop [analyze-state nil
entries (seq (unnest-dispatch-table dispatch-table))]
(if-let [analyze-state' (analyze* analyze-state arg-resolvers (first entries))]
(recur analyze-state' (next entries))
(let [[routes handlers middleware] analyze-state]
{:routes (sorted-routes routes)
:handlers handlers
:middleware (set/map-invert middleware)})))))
(defn- map-traversal-dispatcher
"Returns a Ring handler using the given dispatch-map to guide
dispatch. Used by build-map-traversal-handler. The optional
not-found-response argument defaults to nil; pass in a closed
channel for async operation."
([dispatch-map]
(map-traversal-dispatcher dispatch-map nil))
([dispatch-map not-found-response]
(fn rook-map-traversal-dispatcher [request]
(loop [pathvec (second (request-route-spec request))
dispatch dispatch-map
route-param-vals []]
(if-let [seg (first pathvec)]
(if (contains? dispatch seg)
(recur (next pathvec) (get dispatch seg) route-param-vals)
(if-let [dispatch' (::param dispatch)]
(recur (next pathvec) dispatch' (conj route-param-vals seg))
;; no match on path
not-found-response))
(if-let [{:keys [handler route-param-keys]}
(or (get dispatch (:request-method request))
(get dispatch :all))]
(let [route-params (zipmap route-param-keys route-param-vals)]
(handler (assoc request :route-params route-params)))
;; unsupported method for path
not-found-response))))))
(defn make-header-arg-resolver [sym]
(fn [request]
(-> request :headers (get (name sym)))))
(defn make-param-arg-resolver [sym]
(let [kw (keyword sym)]
(fn [request]
(-> request :params kw))))
(defn make-request-key-resolver [sym]
(let [kw (keyword sym)]
(fn [request]
(kw request))))
(defn make-route-param-resolver [sym]
(let [kw (keyword sym)]
(fn [request]
(-> request :route-params kw))))
(defn make-resource-uri-arg-resolver [sym]
(fn [request]
(internals/resource-uri-for request)))
(defn make-injection-resolver [sym]
(let [kw (keyword sym)]
(fn [request]
(internals/get-injection request kw))))
;;; these two maps will typically be merged, but the user can ask for
;;; either to be left out
(def default-arg-resolver-factories
"A map of keyword -> (function of symbol returning a function of
request). The functions stored in this map will be used as
\"resolver factories\" (they will be passed arg symbols and expected
to produce resolvers in return). A keyword in the value position
would cause a repeated lookup."
{:request (constantly identity)
:request-key make-request-key-resolver
:header make-header-arg-resolver
:param make-param-arg-resolver
:injection make-injection-resolver
:resource-uri make-resource-uri-arg-resolver})
(def default-arg-resolvers
"A map of symbol -> (function of request). The functions will be
used as argument resolvers."
{'request identity
'params (make-request-key-resolver :params)
'params* internals/clojurized-params-arg-resolver
'resource-uri (make-resource-uri-arg-resolver 'resource-uri)})
(def ^:private default-factory-keys
(set (filter keyword? (keys default-arg-resolvers))))
(defn- symbol-for-argument [arg]
"Returns the argument symbol for an argument; this is either the argument itself or
(if a map, for destructuring) the :as key of the map."
(if (map? arg)
(if-let [as (:as arg)]
as
(throw (ex-info "map argument has no :as key"
{:arg arg})))
arg))
(defn- find-factory [arg-resolvers tag]
(loop [tag tag]
(if (keyword? tag)
(recur (get arg-resolvers tag))
tag)))
(defn- find-resolver
[arg-resolvers arg hint]
(cond
(fn? hint)
hint
(keyword? hint)
(if-let [f (find-factory arg-resolvers hint)]
(f arg)
(throw (ex-info (format "Keyword %s does not identify a known argument resolver." hint)
{:arg arg :resolver hint :arg-resolvers arg-resolvers})))
:else
(throw (ex-info (format "Argument resolver value `%s' is neither a keyword not a function." hint)
{:arg arg :resolver hint}))))
(defn- find-argument-resolver-tag
[arg-resolvers arg arg-meta]
(let [resolver-ks (filterv #(contains? arg-resolvers %)
(filter keyword? (keys arg-meta)))]
(case (count resolver-ks)
0 nil
1 (first resolver-ks)
(throw (ex-info (format "Parameter `%s' has conflicting keywords identifying its argument resolution strategy: %s."
arg
(str/join ", " resolver-ks))
{:arg arg :resolver-tags resolver-ks})))))
(defn identify-argument-resolver
"Identifies the specific argument resolver function for an argument, which can come from many sources based on
configuration in general, metadata on the argument symbol and on the function's metadata (merged with
the containing namespace's metadata).
arg-resolvers
: See the docstring on
[[io.aviso.rook.dispatcher/default-arg-resolvers]]. The map passed
to this function will have been extended with user-supplied
resolvers and/or resolver factories.
route-params
: set of keywords
arg
: Argument, a symbol or a map (for destructuring)."
[arg-resolvers route-params arg]
(let [arg-symbol (symbol-for-argument arg)
arg-meta (meta arg-symbol)]
(t/track #(format "Identifying argument resolver for `%s'." arg-symbol)
(cond
;; route param resolution takes precedence
(contains? route-params arg)
(make-route-param-resolver arg-symbol)
;; explicit ::rook/resolver metadata takes precedence for non-route params
(contains? arg-meta :io.aviso.rook/resolver)
(find-resolver arg-resolvers arg-symbol (:io.aviso.rook/resolver arg-meta))
:else
(if-let [resolver-tag (find-argument-resolver-tag
arg-resolvers arg-symbol arg-meta)]
;; explicit tags attached to the arg symbol itself come next
(find-resolver arg-resolvers arg-symbol resolver-tag)
;; non-route-param name-based resolution is implicit and
;; should not override explicit tags, so this check comes
;; last; NB. the value at arg-symbol might be a keyword
;; identifying a resolver factory, so we still need to call
;; find-resolver
(if (contains? arg-resolvers arg-symbol)
(find-resolver arg-resolvers arg-symbol (get arg-resolvers arg-symbol))
;; only static resolution is supported
(throw (ex-info
(format "Unable to identify argument resolver for symbol `%s'." arg-symbol)
{:symbol arg-symbol
:symbol-meta arg-meta
:route-params route-params
:arg-resolvers arg-resolvers}))))))))
(defn- create-arglist-resolver
"Returns a function that is passed the Ring request and returns an array of argument values which
the resource handler function can be applied to."
[arg-resolvers route-params arglist]
(if (seq arglist)
(->>
arglist
(map (partial identify-argument-resolver arg-resolvers (set route-params)))
(apply juxt))
(constantly ())))
(defn- add-dispatch-entries
[dispatch-map method pathvec handler]
(let [pathvec' (mapv #(if (variable? %) ::param %) pathvec)
dispatch-path (conj pathvec' method)
route-params (filterv variable? pathvec)]
(assoc-in dispatch-map dispatch-path
{:handler handler
:route-param-keys (mapv keyword route-params)})))
(defn- build-dispatch-map
"Returns a dispatch-map for use with map-traversal-dispatcher."
[{:keys [routes handlers middleware]}
{:keys [async? arg-resolvers]}]
(reduce (fn [dispatch-map [[method pathvec] handler-key]]
(t/track #(format "Compiling handler for `%s'."
(get-in handlers [handler-key :verb-fn-sym]))
(let [{:keys [middleware-key route-params
verb-fn-sym arglist
metadata context]
extra-resolvers :arg-resolvers}
(get handlers handler-key)
arglist-resolver (create-arglist-resolver
(if (:replace (meta extra-resolvers))
extra-resolvers
(merge
arg-resolvers
extra-resolvers))
(set route-params)
arglist)
middleware (get middleware middleware-key)
resource-handler-fn (eval verb-fn-sym)
request-handler (fn [request]
(apply resource-handler-fn (arglist-resolver request)))
request-handler (if (and async? (:sync metadata))
(internals/ring-handler->async-handler request-handler)
request-handler)
middleware-applied (or (middleware request-handler metadata) request-handler)
context-maintaining-handler (if context
(fn [request]
(-> request
(update-in [:context] str context)
middleware-applied))
middleware-applied)
logging-handler (fn [request]
(l/debugf "Matched %s to %s"
(utils/summarize-request request)
verb-fn-sym)
(context-maintaining-handler request))]
(add-dispatch-entries dispatch-map method pathvec logging-handler))))
{}
routes))
(defn build-map-traversal-handler
"Returns a form evaluating to a Ring handler that handles dispatch
by using the pathvec and method of the incoming request to look up
an endpoint function in a nested map.
Can be passed to compile-dispatch-table using the :build-handler-fn
option."
[analysed-dispatch-table opts]
(let [dispatch-map (build-dispatch-map analysed-dispatch-table opts)]
(if (:async? opts)
(map-traversal-dispatcher dispatch-map
(doto (async/chan) (async/close!)))
(map-traversal-dispatcher dispatch-map))))
(def ^:private dispatch-table-compilation-defaults
{:async? false
:arg-resolvers default-arg-resolvers
:build-handler-fn build-map-traversal-handler})
(defn compile-dispatch-table
"Compiles the dispatch table into a Ring handler.
See the docstring of unnest-dispatch-table for a description of
dispatch table format.
Supported options and their default values:
:async?
: _Default: false_
: Determines the way in which middleware is applied to the terminal
handler. Pass in true when compiling async handlers.
: Note that when async is enabled, you must be careful to only apply middleware that
is appropriately async aware.
:build-handler-fn
: _Default: [[build-map-traversal-handler]]_
: Will be called with routes, handlers, middleware and should
produce a Ring handler.
:arg-resolvers
: _Default: [[io.aviso.rook.dispatcher/default-arg-resolvers]]_
: Map of symbol to (keyword or function of request) or keyword
to (function of symbol returning function of request). Entries of
the former provide argument resolvers to be used when resolving
arguments named by the given symbol; in the keyword case, a known
resolver factory will be used. Entries of the latter type
introduce custom resolver factories. Tag with {:replace true} to
exclude default resolvers and resolver factories; tag with
{:replace-resolvers true} or {:replace-factories true} to leave
out default resolvers or resolver factories, respectively."
([dispatch-table]
(compile-dispatch-table
dispatch-table-compilation-defaults
dispatch-table))
([options dispatch-table]
(let [options (merge dispatch-table-compilation-defaults options)
build-handler (:build-handler-fn options)
analysed-dispatch-table (analyse-dispatch-table
dispatch-table options)]
(build-handler analysed-dispatch-table options))))
(defn- simple-namespace-dispatch-table
"Examines the given namespace and produces a dispatch table in a
format intelligible to compile-dispatch-table."
([ns-sym]
(simple-namespace-dispatch-table [] ns-sym))
([context-pathvec ns-sym]
(simple-namespace-dispatch-table context-pathvec ns-sym default-namespace-middleware))
([context-pathvec ns-sym middleware]
(t/track
#(format "Identifying resource handler functions in `%s'." ns-sym)
(try
(if-not (find-ns ns-sym)
(require ns-sym))
(catch Exception e
(throw (ex-info "failed to require ns in namespace-dispatch-table"
{:context-pathvec context-pathvec
:ns ns-sym
:middleware middleware}
e))))
[(->> ns-sym
ns-publics
(keep (fn [[k v]]
(if (ifn? @v)
(t/track #(format "Building route mapping for `%s/%s'." ns-sym k)
(if-let [route-spec (or (:route-spec (meta v))
(path-spec->route-spec
(:path-spec (meta v)))
(get default-mappings k))]
(conj route-spec (symbol (name ns-sym) (name k))))))))
(list* context-pathvec middleware)
vec)])))
(defn canonicalize-ns-specs
"Handles unnesting of ns-specs."
[outer-context-pathvec outer-middleware ns-specs]
(mapcat (fn [[context-pathvec? ns-sym middleware? :as ns-spec]]
(t/track (format "Parsing namespace specification `%s'." (pr-str ns-spec))
(let [context-pathvec (if (or (nil? context-pathvec?)
(vector? context-pathvec?))
(or context-pathvec? []))
middleware (let [mw? (if context-pathvec
middleware?
ns-sym)]
(if-not (vector? mw?)
mw?))
ns-sym (if context-pathvec
ns-sym
context-pathvec?)
skip (reduce + 1
(map #(if % 1 0)
[context-pathvec middleware]))
nested (drop skip ns-spec)]
(assert (symbol? ns-sym)
(str "Malformed ns-spec: " (pr-str ns-sym)))
(concat
[[(into outer-context-pathvec context-pathvec)
ns-sym
(or middleware outer-middleware)]]
(canonicalize-ns-specs
(into outer-context-pathvec context-pathvec)
(or middleware outer-middleware)
nested)))))
ns-specs))
(def ^:private default-opts
{:context-pathvec []
:default-middleware default-namespace-middleware})
(defn namespace-dispatch-table
"Similar to [[io.aviso.rook/namespace-handler]], but stops short of
producing a handler, returning a dispatch table instead. See the
docstring of [[io.aviso.rook/namespace-handler]] for a description
of ns-spec syntax and a list of supported options (NB. `async?` is
irrelevant to the shape of the dispatch table).
The resulting dispatch table in its unnested form will include
entries such as
[:get [\"api\" \"foo\"] 'example.foo/index ns-middleware]."
[options? & ns-specs]
(let [opts (merge default-opts (if (map? options?) options?))
{outer-context-pathvec :context-pathvec
default-middleware :default-middleware} opts
ns-specs (canonicalize-ns-specs
[]
default-middleware
(if (map? options?)
ns-specs
(cons options? ns-specs)))]
[(reduce into [outer-context-pathvec default-middleware]
(map (fn [[context-pathvec ns-sym middleware]]
(simple-namespace-dispatch-table
context-pathvec ns-sym middleware))
ns-specs))]))
|
[
{
"context": "ented with \n <a href=\\\"https://github.com/palisades-lakes/faster-multimethods\\\">\n faster-multimetho",
"end": 311,
"score": 0.9961479306221008,
"start": 296,
"tag": "USERNAME",
"value": "palisades-lakes"
},
{
"context": "\">\n faster-multimethods</a>.\"\n :author \"palisades dot lakes at gmail dot com\"\n :version \"2017-12-11\"}\n \n (:require [palisa",
"end": 418,
"score": 0.8849267959594727,
"start": 382,
"tag": "EMAIL",
"value": "palisades dot lakes at gmail dot com"
}
] | src/main/clojure/palisades/lakes/fm/fill.clj | palisades-lakes/collection-experiments | 0 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.fm.fill
{:doc "A generic 'collection' <code>fill</code> function,
implemented with
<a href=\"https://github.com/palisades-lakes/faster-multimethods\">
faster-multimethods</a>."
:author "palisades dot lakes at gmail dot com"
:version "2017-12-11"}
(:require [palisades.lakes.multimethods.core :as fm]
[palisades.lakes.collex.arrays :as arrays])
(:import [java.util ArrayList LinkedList]
[clojure.lang IFn IFn$D IFn$L LazySeq
IPersistentList IPersistentVector]
[com.google.common.collect ImmutableList]))
;;----------------------------------------------------------------
;; TODO: are there performance implications to the arg order,
;; given the fact that prototype is only used for method lookup?
(fm/defmulti fill
"Fill a new 'collection' with <code>n</code> values generated
by repeated calls to a no-argument function
<code>generator</code>. For example, <code>generator</code>
may be an encapsulated iterator over some other 'collection'.
Another common case is a pseudo-random element generator for
test or benchmarking data.
<p>
<code>prototype</code> is used to
determine what kind of 'collection' is returned, and is not
modified, even if mutable and the right size. Methods are
defined for array prototypes as well as normal collections."
{} #_{:arglists '([prototype ^IFn generator ^long n])}
;; TODO: use generator class in method lookup, to support
;; Iterator/Iterable, java.util.function.Function, etc.?
(fn fill-dispatch ^Class [prototype ^IFn generator ^long n]
(class prototype)))
;;----------------------------------------------------------------
(fm/defmethod fill
arrays/double-array-type
[^doubles _ ^IFn generator ^long n]
(let [x (double-array n)]
(if (instance? IFn$D x)
(dotimes [i (int n)]
(aset-double x i (.invokePrim ^IFn$D generator)))
(dotimes [i (int n)]
(aset-double x i (double (generator)))))
x))
;;----------------------------------------------------------------
(fm/defmethod fill
arrays/object-array-type
[^objects prototype ^IFn generator ^long n]
(let [^objects x (make-array (arrays/element-type prototype) n)]
(dotimes [i (int n)] (aset x i (generator)))
x))
;;----------------------------------------------------------------
(fm/defmethod fill
ArrayList
[^ArrayList _ ^IFn generator ^long n]
(let [x (ArrayList. n)]
(dotimes [i (int n)] (.add x (generator)))
x))
;;----------------------------------------------------------------
(fm/defmethod fill
LinkedList
[^LinkedList _ ^IFn generator ^long n]
(let [x (LinkedList.)]
(dotimes [i (int n)] (.add x (generator)))
x))
;;----------------------------------------------------------------
(fm/defmethod fill
ImmutableList
[^ImmutableList _ ^IFn generator ^long n]
(let [x (ImmutableList/builder)]
(dotimes [i (int n)] (.add x (generator)))
(.build x)))
;;----------------------------------------------------------------
(def prototype-LazySeq (take 0 (iterate identity 0)))
(assert (instance? LazySeq prototype-LazySeq))
(fm/defmethod fill
LazySeq
[^LazySeq _ ^IFn generator ^long n]
(repeatedly n generator))
;;----------------------------------------------------------------
(fm/defmethod fill
IPersistentVector
[^IPersistentVector _ ^IFn generator ^long n]
(into [] (repeatedly n generator)))
;;----------------------------------------------------------------
(fm/defmethod fill
IPersistentList
[^IPersistentList _ ^IFn generator ^long n]
(into '() (repeatedly n generator)))
;;----------------------------------------------------------------
| 14390 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.fm.fill
{:doc "A generic 'collection' <code>fill</code> function,
implemented with
<a href=\"https://github.com/palisades-lakes/faster-multimethods\">
faster-multimethods</a>."
:author "<EMAIL>"
:version "2017-12-11"}
(:require [palisades.lakes.multimethods.core :as fm]
[palisades.lakes.collex.arrays :as arrays])
(:import [java.util ArrayList LinkedList]
[clojure.lang IFn IFn$D IFn$L LazySeq
IPersistentList IPersistentVector]
[com.google.common.collect ImmutableList]))
;;----------------------------------------------------------------
;; TODO: are there performance implications to the arg order,
;; given the fact that prototype is only used for method lookup?
(fm/defmulti fill
"Fill a new 'collection' with <code>n</code> values generated
by repeated calls to a no-argument function
<code>generator</code>. For example, <code>generator</code>
may be an encapsulated iterator over some other 'collection'.
Another common case is a pseudo-random element generator for
test or benchmarking data.
<p>
<code>prototype</code> is used to
determine what kind of 'collection' is returned, and is not
modified, even if mutable and the right size. Methods are
defined for array prototypes as well as normal collections."
{} #_{:arglists '([prototype ^IFn generator ^long n])}
;; TODO: use generator class in method lookup, to support
;; Iterator/Iterable, java.util.function.Function, etc.?
(fn fill-dispatch ^Class [prototype ^IFn generator ^long n]
(class prototype)))
;;----------------------------------------------------------------
(fm/defmethod fill
arrays/double-array-type
[^doubles _ ^IFn generator ^long n]
(let [x (double-array n)]
(if (instance? IFn$D x)
(dotimes [i (int n)]
(aset-double x i (.invokePrim ^IFn$D generator)))
(dotimes [i (int n)]
(aset-double x i (double (generator)))))
x))
;;----------------------------------------------------------------
(fm/defmethod fill
arrays/object-array-type
[^objects prototype ^IFn generator ^long n]
(let [^objects x (make-array (arrays/element-type prototype) n)]
(dotimes [i (int n)] (aset x i (generator)))
x))
;;----------------------------------------------------------------
(fm/defmethod fill
ArrayList
[^ArrayList _ ^IFn generator ^long n]
(let [x (ArrayList. n)]
(dotimes [i (int n)] (.add x (generator)))
x))
;;----------------------------------------------------------------
(fm/defmethod fill
LinkedList
[^LinkedList _ ^IFn generator ^long n]
(let [x (LinkedList.)]
(dotimes [i (int n)] (.add x (generator)))
x))
;;----------------------------------------------------------------
(fm/defmethod fill
ImmutableList
[^ImmutableList _ ^IFn generator ^long n]
(let [x (ImmutableList/builder)]
(dotimes [i (int n)] (.add x (generator)))
(.build x)))
;;----------------------------------------------------------------
(def prototype-LazySeq (take 0 (iterate identity 0)))
(assert (instance? LazySeq prototype-LazySeq))
(fm/defmethod fill
LazySeq
[^LazySeq _ ^IFn generator ^long n]
(repeatedly n generator))
;;----------------------------------------------------------------
(fm/defmethod fill
IPersistentVector
[^IPersistentVector _ ^IFn generator ^long n]
(into [] (repeatedly n generator)))
;;----------------------------------------------------------------
(fm/defmethod fill
IPersistentList
[^IPersistentList _ ^IFn generator ^long n]
(into '() (repeatedly n generator)))
;;----------------------------------------------------------------
| true | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.fm.fill
{:doc "A generic 'collection' <code>fill</code> function,
implemented with
<a href=\"https://github.com/palisades-lakes/faster-multimethods\">
faster-multimethods</a>."
:author "PI:EMAIL:<EMAIL>END_PI"
:version "2017-12-11"}
(:require [palisades.lakes.multimethods.core :as fm]
[palisades.lakes.collex.arrays :as arrays])
(:import [java.util ArrayList LinkedList]
[clojure.lang IFn IFn$D IFn$L LazySeq
IPersistentList IPersistentVector]
[com.google.common.collect ImmutableList]))
;;----------------------------------------------------------------
;; TODO: are there performance implications to the arg order,
;; given the fact that prototype is only used for method lookup?
(fm/defmulti fill
"Fill a new 'collection' with <code>n</code> values generated
by repeated calls to a no-argument function
<code>generator</code>. For example, <code>generator</code>
may be an encapsulated iterator over some other 'collection'.
Another common case is a pseudo-random element generator for
test or benchmarking data.
<p>
<code>prototype</code> is used to
determine what kind of 'collection' is returned, and is not
modified, even if mutable and the right size. Methods are
defined for array prototypes as well as normal collections."
{} #_{:arglists '([prototype ^IFn generator ^long n])}
;; TODO: use generator class in method lookup, to support
;; Iterator/Iterable, java.util.function.Function, etc.?
(fn fill-dispatch ^Class [prototype ^IFn generator ^long n]
(class prototype)))
;;----------------------------------------------------------------
(fm/defmethod fill
arrays/double-array-type
[^doubles _ ^IFn generator ^long n]
(let [x (double-array n)]
(if (instance? IFn$D x)
(dotimes [i (int n)]
(aset-double x i (.invokePrim ^IFn$D generator)))
(dotimes [i (int n)]
(aset-double x i (double (generator)))))
x))
;;----------------------------------------------------------------
(fm/defmethod fill
arrays/object-array-type
[^objects prototype ^IFn generator ^long n]
(let [^objects x (make-array (arrays/element-type prototype) n)]
(dotimes [i (int n)] (aset x i (generator)))
x))
;;----------------------------------------------------------------
(fm/defmethod fill
ArrayList
[^ArrayList _ ^IFn generator ^long n]
(let [x (ArrayList. n)]
(dotimes [i (int n)] (.add x (generator)))
x))
;;----------------------------------------------------------------
(fm/defmethod fill
LinkedList
[^LinkedList _ ^IFn generator ^long n]
(let [x (LinkedList.)]
(dotimes [i (int n)] (.add x (generator)))
x))
;;----------------------------------------------------------------
(fm/defmethod fill
ImmutableList
[^ImmutableList _ ^IFn generator ^long n]
(let [x (ImmutableList/builder)]
(dotimes [i (int n)] (.add x (generator)))
(.build x)))
;;----------------------------------------------------------------
(def prototype-LazySeq (take 0 (iterate identity 0)))
(assert (instance? LazySeq prototype-LazySeq))
(fm/defmethod fill
LazySeq
[^LazySeq _ ^IFn generator ^long n]
(repeatedly n generator))
;;----------------------------------------------------------------
(fm/defmethod fill
IPersistentVector
[^IPersistentVector _ ^IFn generator ^long n]
(into [] (repeatedly n generator)))
;;----------------------------------------------------------------
(fm/defmethod fill
IPersistentList
[^IPersistentList _ ^IFn generator ^long n]
(into '() (repeatedly n generator)))
;;----------------------------------------------------------------
|
[
{
"context": "est-decode-auth-cookie\n (let [password [:cached \"test-password\"]\n a-sequence-value [\"cookie-value\" 1234]\n",
"end": 1922,
"score": 0.8895902037620544,
"start": 1909,
"tag": "PASSWORD",
"value": "test-password"
}
] | waiter/test/waiter/auth/authenticator_test.clj | twosigmajab/waiter | 1 | ;;
;; Copyright (c) Two Sigma Open Source, LLC
;;
;; 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 waiter.auth.authenticator-test
(:require [clj-time.core :as t]
[clojure.string :as str]
[clojure.test :refer :all]
[waiter.auth.authentication :refer :all]
[waiter.cookie-support :as cs])
(:import (waiter.auth.authentication SingleUserAuthenticator)))
(deftest test-one-user-authenticator
(let [username (System/getProperty "user.name")
authenticator (one-user-authenticator {:run-as-user username})]
(is (instance? SingleUserAuthenticator authenticator))
(let [request-handler (wrap-auth-handler authenticator identity)
request {}
expected-request (assoc request
:authorization/principal username
:authorization/user username)
actual-result (request-handler request)]
(is (= expected-request (dissoc actual-result :headers)))
(is (str/includes? (get-in actual-result [:headers "set-cookie"]) "x-waiter-auth=")))))
(deftest test-get-auth-cookie-value
(is (= "abc123" (get-auth-cookie-value "x-waiter-auth=abc123")))
(is (= "abc123" (get-auth-cookie-value "x-waiter-auth=\"abc123\"")))
(is (= "abc123" (get-auth-cookie-value "blah=blah;x-waiter-auth=abc123"))))
(deftest test-decode-auth-cookie
(let [password [:cached "test-password"]
a-sequence-value ["cookie-value" 1234]
an-int-value 123456]
(is (= a-sequence-value (decode-auth-cookie (cs/encode-cookie a-sequence-value password) password)))
(is (nil? (decode-auth-cookie (cs/encode-cookie an-int-value password) password)))
(is (nil? (decode-auth-cookie a-sequence-value password)))
(is (nil? (decode-auth-cookie an-int-value password)))))
(deftest test-decoded-auth-valid?
(let [now-ms (System/currentTimeMillis)
one-day-in-millis (-> 1 t/days t/in-millis)]
(is (true? (decoded-auth-valid? ["test-principal" now-ms])))
(is (true? (decoded-auth-valid? ["test-principal" (-> now-ms (- one-day-in-millis) (+ 1000))])))
(is (false? (decoded-auth-valid? ["test-principal" (- now-ms one-day-in-millis 1000)])))
(is (false? (decoded-auth-valid? ["test-principal" "invalid-string-time"])))
(is (false? (decoded-auth-valid? [(rand-int 10000) "invalid-string-time"])))
(is (false? (decoded-auth-valid? ["test-principal"])))
(is (false? (decoded-auth-valid? [])))))
| 41579 | ;;
;; Copyright (c) Two Sigma Open Source, LLC
;;
;; 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 waiter.auth.authenticator-test
(:require [clj-time.core :as t]
[clojure.string :as str]
[clojure.test :refer :all]
[waiter.auth.authentication :refer :all]
[waiter.cookie-support :as cs])
(:import (waiter.auth.authentication SingleUserAuthenticator)))
(deftest test-one-user-authenticator
(let [username (System/getProperty "user.name")
authenticator (one-user-authenticator {:run-as-user username})]
(is (instance? SingleUserAuthenticator authenticator))
(let [request-handler (wrap-auth-handler authenticator identity)
request {}
expected-request (assoc request
:authorization/principal username
:authorization/user username)
actual-result (request-handler request)]
(is (= expected-request (dissoc actual-result :headers)))
(is (str/includes? (get-in actual-result [:headers "set-cookie"]) "x-waiter-auth=")))))
(deftest test-get-auth-cookie-value
(is (= "abc123" (get-auth-cookie-value "x-waiter-auth=abc123")))
(is (= "abc123" (get-auth-cookie-value "x-waiter-auth=\"abc123\"")))
(is (= "abc123" (get-auth-cookie-value "blah=blah;x-waiter-auth=abc123"))))
(deftest test-decode-auth-cookie
(let [password [:cached "<PASSWORD>"]
a-sequence-value ["cookie-value" 1234]
an-int-value 123456]
(is (= a-sequence-value (decode-auth-cookie (cs/encode-cookie a-sequence-value password) password)))
(is (nil? (decode-auth-cookie (cs/encode-cookie an-int-value password) password)))
(is (nil? (decode-auth-cookie a-sequence-value password)))
(is (nil? (decode-auth-cookie an-int-value password)))))
(deftest test-decoded-auth-valid?
(let [now-ms (System/currentTimeMillis)
one-day-in-millis (-> 1 t/days t/in-millis)]
(is (true? (decoded-auth-valid? ["test-principal" now-ms])))
(is (true? (decoded-auth-valid? ["test-principal" (-> now-ms (- one-day-in-millis) (+ 1000))])))
(is (false? (decoded-auth-valid? ["test-principal" (- now-ms one-day-in-millis 1000)])))
(is (false? (decoded-auth-valid? ["test-principal" "invalid-string-time"])))
(is (false? (decoded-auth-valid? [(rand-int 10000) "invalid-string-time"])))
(is (false? (decoded-auth-valid? ["test-principal"])))
(is (false? (decoded-auth-valid? [])))))
| true | ;;
;; Copyright (c) Two Sigma Open Source, LLC
;;
;; 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 waiter.auth.authenticator-test
(:require [clj-time.core :as t]
[clojure.string :as str]
[clojure.test :refer :all]
[waiter.auth.authentication :refer :all]
[waiter.cookie-support :as cs])
(:import (waiter.auth.authentication SingleUserAuthenticator)))
(deftest test-one-user-authenticator
(let [username (System/getProperty "user.name")
authenticator (one-user-authenticator {:run-as-user username})]
(is (instance? SingleUserAuthenticator authenticator))
(let [request-handler (wrap-auth-handler authenticator identity)
request {}
expected-request (assoc request
:authorization/principal username
:authorization/user username)
actual-result (request-handler request)]
(is (= expected-request (dissoc actual-result :headers)))
(is (str/includes? (get-in actual-result [:headers "set-cookie"]) "x-waiter-auth=")))))
(deftest test-get-auth-cookie-value
(is (= "abc123" (get-auth-cookie-value "x-waiter-auth=abc123")))
(is (= "abc123" (get-auth-cookie-value "x-waiter-auth=\"abc123\"")))
(is (= "abc123" (get-auth-cookie-value "blah=blah;x-waiter-auth=abc123"))))
(deftest test-decode-auth-cookie
(let [password [:cached "PI:PASSWORD:<PASSWORD>END_PI"]
a-sequence-value ["cookie-value" 1234]
an-int-value 123456]
(is (= a-sequence-value (decode-auth-cookie (cs/encode-cookie a-sequence-value password) password)))
(is (nil? (decode-auth-cookie (cs/encode-cookie an-int-value password) password)))
(is (nil? (decode-auth-cookie a-sequence-value password)))
(is (nil? (decode-auth-cookie an-int-value password)))))
(deftest test-decoded-auth-valid?
(let [now-ms (System/currentTimeMillis)
one-day-in-millis (-> 1 t/days t/in-millis)]
(is (true? (decoded-auth-valid? ["test-principal" now-ms])))
(is (true? (decoded-auth-valid? ["test-principal" (-> now-ms (- one-day-in-millis) (+ 1000))])))
(is (false? (decoded-auth-valid? ["test-principal" (- now-ms one-day-in-millis 1000)])))
(is (false? (decoded-auth-valid? ["test-principal" "invalid-string-time"])))
(is (false? (decoded-auth-valid? [(rand-int 10000) "invalid-string-time"])))
(is (false? (decoded-auth-valid? ["test-principal"])))
(is (false? (decoded-auth-valid? [])))))
|
[
{
"context": "no-doc pandect.utils.potemkin)\n\n;; --- copied from ztellman/potemkin\n;;\n;; Copyright (c) 2013 Zachary Tellman",
"end": 65,
"score": 0.8272819519042969,
"start": 57,
"tag": "USERNAME",
"value": "ztellman"
},
{
"context": "ed from ztellman/potemkin\n;;\n;; Copyright (c) 2013 Zachary Tellman\n;;\n;; Permission is hereby granted, free of charg",
"end": 115,
"score": 0.9998407363891602,
"start": 100,
"tag": "NAME",
"value": "Zachary Tellman"
}
] | src/clojure/pandect/utils/potemkin.clj | projetoeureka/pandect | 0 | (ns ^:no-doc pandect.utils.potemkin)
;; --- copied from ztellman/potemkin
;;
;; Copyright (c) 2013 Zachary Tellman
;;
;; 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.
;;
;; ---
;; --- potemkin.namespaces
(defn link-vars
"Makes sure that all changes to `src` are reflected in `dst`."
[src dst]
(add-watch src dst
(fn [_ src old new]
(alter-var-root dst (constantly @src))
(alter-meta! dst merge (dissoc (meta src) :name)))))
(defmacro import-fn
"Given a function in another namespace, defines a function with the
same name in the current namespace. Argument lists, doc-strings,
and original line-numbers are preserved."
([sym]
`(import-fn ~sym nil))
([sym name]
(let [vr (resolve sym)
m (meta vr)
n (or name (:name m))
arglists (:arglists m)
protocol (:protocol m)]
(when-not vr
(throw (IllegalArgumentException. (str "Don't recognize " sym))))
(when (:macro m)
(throw (IllegalArgumentException.
(str "Calling import-fn on a macro: " sym))))
`(do
(def ~(with-meta n {:protocol protocol}) (deref ~vr))
(alter-meta! (var ~n) merge (dissoc (meta ~vr) :name))
(link-vars ~vr (var ~n))
~vr))))
(defmacro import-macro
"Given a macro in another namespace, defines a macro with the same
name in the current namespace. Argument lists, doc-strings, and
original line-numbers are preserved."
([sym]
`(import-macro ~sym nil))
([sym name]
(let [vr (resolve sym)
m (meta vr)
n (or name (with-meta (:name m) {}))
arglists (:arglists m)]
(when-not vr
(throw (IllegalArgumentException. (str "Don't recognize " sym))))
(when-not (:macro m)
(throw (IllegalArgumentException.
(str "Calling import-macro on a non-macro: " sym))))
`(do
(def ~n ~(resolve sym))
(alter-meta! (var ~n) merge (dissoc (meta ~vr) :name))
(.setMacro (var ~n))
(link-vars ~vr (var ~n))
~vr))))
(defmacro import-def
"Given a regular def'd var from another namespace, defined a new var with the
same name in the current namespace."
([sym]
`(import-def ~sym nil))
([sym name]
(let [vr (resolve sym)
m (meta vr)
n (or name (:name m))
n (with-meta n (if (:dynamic m) {:dynamic true} {}))
nspace (:ns m)]
(when-not vr
(throw (IllegalArgumentException. (str "Don't recognize " sym))))
`(do
(def ~n @~vr)
(alter-meta! (var ~n) merge (dissoc (meta ~vr) :name))
(link-vars ~vr (var ~n))
~vr))))
(defmacro import-vars
"Imports a list of vars from other namespaces."
[& syms]
(let [unravel (fn unravel [x]
(if (sequential? x)
(->> x
rest
(mapcat unravel)
(map
#(symbol
(str (first x)
(when-let [n (namespace %)]
(str "." n)))
(name %))))
[x]))
syms (mapcat unravel syms)]
`(do
~@(map
(fn [sym]
(let [vr (resolve sym)
m (meta vr)]
(cond
(:macro m) `(import-macro ~sym)
(:arglists m) `(import-fn ~sym)
:else `(import-def ~sym))))
syms))))
| 121492 | (ns ^:no-doc pandect.utils.potemkin)
;; --- copied from ztellman/potemkin
;;
;; Copyright (c) 2013 <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.
;;
;; ---
;; --- potemkin.namespaces
(defn link-vars
"Makes sure that all changes to `src` are reflected in `dst`."
[src dst]
(add-watch src dst
(fn [_ src old new]
(alter-var-root dst (constantly @src))
(alter-meta! dst merge (dissoc (meta src) :name)))))
(defmacro import-fn
"Given a function in another namespace, defines a function with the
same name in the current namespace. Argument lists, doc-strings,
and original line-numbers are preserved."
([sym]
`(import-fn ~sym nil))
([sym name]
(let [vr (resolve sym)
m (meta vr)
n (or name (:name m))
arglists (:arglists m)
protocol (:protocol m)]
(when-not vr
(throw (IllegalArgumentException. (str "Don't recognize " sym))))
(when (:macro m)
(throw (IllegalArgumentException.
(str "Calling import-fn on a macro: " sym))))
`(do
(def ~(with-meta n {:protocol protocol}) (deref ~vr))
(alter-meta! (var ~n) merge (dissoc (meta ~vr) :name))
(link-vars ~vr (var ~n))
~vr))))
(defmacro import-macro
"Given a macro in another namespace, defines a macro with the same
name in the current namespace. Argument lists, doc-strings, and
original line-numbers are preserved."
([sym]
`(import-macro ~sym nil))
([sym name]
(let [vr (resolve sym)
m (meta vr)
n (or name (with-meta (:name m) {}))
arglists (:arglists m)]
(when-not vr
(throw (IllegalArgumentException. (str "Don't recognize " sym))))
(when-not (:macro m)
(throw (IllegalArgumentException.
(str "Calling import-macro on a non-macro: " sym))))
`(do
(def ~n ~(resolve sym))
(alter-meta! (var ~n) merge (dissoc (meta ~vr) :name))
(.setMacro (var ~n))
(link-vars ~vr (var ~n))
~vr))))
(defmacro import-def
"Given a regular def'd var from another namespace, defined a new var with the
same name in the current namespace."
([sym]
`(import-def ~sym nil))
([sym name]
(let [vr (resolve sym)
m (meta vr)
n (or name (:name m))
n (with-meta n (if (:dynamic m) {:dynamic true} {}))
nspace (:ns m)]
(when-not vr
(throw (IllegalArgumentException. (str "Don't recognize " sym))))
`(do
(def ~n @~vr)
(alter-meta! (var ~n) merge (dissoc (meta ~vr) :name))
(link-vars ~vr (var ~n))
~vr))))
(defmacro import-vars
"Imports a list of vars from other namespaces."
[& syms]
(let [unravel (fn unravel [x]
(if (sequential? x)
(->> x
rest
(mapcat unravel)
(map
#(symbol
(str (first x)
(when-let [n (namespace %)]
(str "." n)))
(name %))))
[x]))
syms (mapcat unravel syms)]
`(do
~@(map
(fn [sym]
(let [vr (resolve sym)
m (meta vr)]
(cond
(:macro m) `(import-macro ~sym)
(:arglists m) `(import-fn ~sym)
:else `(import-def ~sym))))
syms))))
| true | (ns ^:no-doc pandect.utils.potemkin)
;; --- copied from ztellman/potemkin
;;
;; Copyright (c) 2013 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.
;;
;; ---
;; --- potemkin.namespaces
(defn link-vars
"Makes sure that all changes to `src` are reflected in `dst`."
[src dst]
(add-watch src dst
(fn [_ src old new]
(alter-var-root dst (constantly @src))
(alter-meta! dst merge (dissoc (meta src) :name)))))
(defmacro import-fn
"Given a function in another namespace, defines a function with the
same name in the current namespace. Argument lists, doc-strings,
and original line-numbers are preserved."
([sym]
`(import-fn ~sym nil))
([sym name]
(let [vr (resolve sym)
m (meta vr)
n (or name (:name m))
arglists (:arglists m)
protocol (:protocol m)]
(when-not vr
(throw (IllegalArgumentException. (str "Don't recognize " sym))))
(when (:macro m)
(throw (IllegalArgumentException.
(str "Calling import-fn on a macro: " sym))))
`(do
(def ~(with-meta n {:protocol protocol}) (deref ~vr))
(alter-meta! (var ~n) merge (dissoc (meta ~vr) :name))
(link-vars ~vr (var ~n))
~vr))))
(defmacro import-macro
"Given a macro in another namespace, defines a macro with the same
name in the current namespace. Argument lists, doc-strings, and
original line-numbers are preserved."
([sym]
`(import-macro ~sym nil))
([sym name]
(let [vr (resolve sym)
m (meta vr)
n (or name (with-meta (:name m) {}))
arglists (:arglists m)]
(when-not vr
(throw (IllegalArgumentException. (str "Don't recognize " sym))))
(when-not (:macro m)
(throw (IllegalArgumentException.
(str "Calling import-macro on a non-macro: " sym))))
`(do
(def ~n ~(resolve sym))
(alter-meta! (var ~n) merge (dissoc (meta ~vr) :name))
(.setMacro (var ~n))
(link-vars ~vr (var ~n))
~vr))))
(defmacro import-def
"Given a regular def'd var from another namespace, defined a new var with the
same name in the current namespace."
([sym]
`(import-def ~sym nil))
([sym name]
(let [vr (resolve sym)
m (meta vr)
n (or name (:name m))
n (with-meta n (if (:dynamic m) {:dynamic true} {}))
nspace (:ns m)]
(when-not vr
(throw (IllegalArgumentException. (str "Don't recognize " sym))))
`(do
(def ~n @~vr)
(alter-meta! (var ~n) merge (dissoc (meta ~vr) :name))
(link-vars ~vr (var ~n))
~vr))))
(defmacro import-vars
"Imports a list of vars from other namespaces."
[& syms]
(let [unravel (fn unravel [x]
(if (sequential? x)
(->> x
rest
(mapcat unravel)
(map
#(symbol
(str (first x)
(when-let [n (namespace %)]
(str "." n)))
(name %))))
[x]))
syms (mapcat unravel syms)]
`(do
~@(map
(fn [sym]
(let [vr (resolve sym)
m (meta vr)]
(cond
(:macro m) `(import-macro ~sym)
(:arglists m) `(import-fn ~sym)
:else `(import-def ~sym))))
syms))))
|
[
{
"context": "ser [{~'user-id-temp :id} {:email \"felicia@metabase.com\"\n ",
"end": 5113,
"score": 0.999930202960968,
"start": 5093,
"tag": "EMAIL",
"value": "felicia@metabase.com"
},
{
"context": " :first_name \"Felicia\"\n ",
"end": 5192,
"score": 0.9998059868812561,
"start": 5185,
"tag": "NAME",
"value": "Felicia"
},
{
"context": " :last_name \"Temp\"\n ",
"end": 5268,
"score": 0.9989442229270935,
"start": 5264,
"tag": "NAME",
"value": "Temp"
},
{
"context": " :password \"fiddlesticks\"}]\n Collection [{~'personal-col",
"end": 5352,
"score": 0.9990060329437256,
"start": 5340,
"tag": "PASSWORD",
"value": "fiddlesticks"
},
{
"context": "'personal-collection-id :id} {:name \"Felicia's Personal Collection\"\n ",
"end": 5446,
"score": 0.7793717980384827,
"start": 5439,
"tag": "NAME",
"value": "Felicia"
},
{
"context": "ection [{~'pc-felicia-nested-id :id} {:name \"Felicia's Nested Collection\"\n ",
"end": 5648,
"score": 0.5554287433624268,
"start": 5642,
"tag": "NAME",
"value": "elicia"
}
] | c#-metabase/enterprise/backend/test/metabase_enterprise/serialization/test_util.clj | hanakhry/Crime_Admin | 0 | (ns metabase-enterprise.serialization.test-util
(:require [metabase-enterprise.serialization.names :as names]
[metabase.models :refer [Card Collection Dashboard DashboardCard DashboardCardSeries Database Dependency
Field Metric NativeQuerySnippet Pulse PulseCard Segment Table User]]
[metabase.models.collection :as collection]
[metabase.query-processor.store :as qp.store]
[metabase.shared.models.visualization-settings :as mb.viz]
[metabase.test :as mt]
[metabase.test.data :as data]
[toucan.db :as db]
[toucan.util.test :as tt]))
(def root-card-name "My Root Card \\ with a/nasty: (*) //n`me ' * ? \" < > | ŠĐž")
(def temp-db-name "Fingerprint test-data copy")
(defn temp-field [from-field-id table-id]
(-> from-field-id
Field
(dissoc :id)
(assoc :table_id table-id)))
(defn temp-table [from-tbl-id db-id]
(-> from-tbl-id
Table
(dissoc :id)
(update :display_name #(str "Temp " %))
(assoc :db_id db-id)))
(def virtual-card {:name nil
:display "text"
:visualization_settings {}
:dataset_query {}
:archived false})
(defn crowberto-pc-id
"Gets the personal collection ID for :crowberto (needed for tests). Must be public because the `with-world` macro
is public."
[]
(db/select-one-field :id Collection :personal_owner_id (mt/user->id :crowberto)))
(defmacro with-temp-dpc
"Wraps with-temp*, but binding `*allow-deleting-personal-collections*` to true so that temporary personal collections
can still be deleted."
[model-bindings & body]
`(binding [collection/*allow-deleting-personal-collections* true]
(tt/with-temp* ~model-bindings ~@body)))
(defmacro with-world
"Run test in the context of a minimal Metabase instance connected to our test database."
[& body]
`(with-temp-dpc [Database [{~'db-id :id} (into {:name temp-db-name} (-> (data/id)
Database
(dissoc :id :features :name)))]
Table [{~'table-id :id :as ~'table} (temp-table (data/id :venues) ~'db-id)]
Table [{~'table-id-categories :id} (temp-table (data/id :categories) ~'db-id)]
Table [{~'table-id-users :id} (temp-table (data/id :users) ~'db-id)]
Table [{~'table-id-checkins :id} (temp-table (data/id :checkins) ~'db-id)]
Field [{~'venues-pk-field-id :id} (temp-field (data/id :venues :id) ~'table-id)]
Field [{~'numeric-field-id :id} (temp-field (data/id :venues :price) ~'table-id)]
Field [{~'name-field-id :id} (temp-field (data/id :venues :name) ~'table-id)]
Field [{~'latitude-field-id :id} (temp-field (data/id :venues :latitude) ~'table-id)]
Field [{~'longitude-field-id :id} (temp-field (data/id :venues :longitude) ~'table-id)]
Field [{~'category-field-id :id} (temp-field (data/id :venues :category_id) ~'table-id)]
Field [{~'category-pk-field-id :id} (temp-field
(data/id :categories :id)
~'table-id-categories)]
Field [{~'date-field-id :id} (temp-field (data/id :checkins :date) ~'table-id-checkins)]
Field [{~'users-pk-field-id :id} (temp-field (data/id :users :id)
~'table-id-users)]
Field [{~'user-id-field-id :id} (-> (temp-field (data/id :checkins :user_id)
~'table-id-checkins)
(assoc :fk_target_field_id ~'users-pk-field-id))]
Field [{~'checkins->venues-field-id :id} (-> (temp-field (data/id :checkins :venue_id)
~'table-id-checkins)
(assoc :fk_target_field_id ~'venues-pk-field-id))]
Field [{~'last-login-field-id :id} (temp-field (data/id :users :last_login)
~'table-id-users)]
Collection [{~'collection-id :id} {:name "My Collection"}]
Collection [{~'collection-id-nested :id} {:name "My Nested Collection"
:location (format "/%s/" ~'collection-id)}]
User [{~'user-id-temp :id} {:email "felicia@metabase.com"
:first_name "Felicia"
:last_name "Temp"
:password "fiddlesticks"}]
Collection [{~'personal-collection-id :id} {:name "Felicia's Personal Collection"
:personal_owner_id ~'user-id-temp}]
Collection [{~'pc-felicia-nested-id :id} {:name "Felicia's Nested Collection"
:location (format "/%d/" ~'personal-collection-id)}]
Collection [{~'pc-nested-id :id} {:name "Nested Personal Collection"
:location (format "/%d/" (crowberto-pc-id))}]
Collection [{~'pc-deeply-nested-id :id} {:name
"Deeply Nested Personal Collection"
:location
(format "/%d/%d/" (crowberto-pc-id) ~'pc-nested-id)}]
Metric [{~'metric-id :id} {:name "My Metric"
:table_id ~'table-id
:definition {:source-table ~'table-id
:aggregation [:sum [:field ~'numeric-field-id nil]]}}]
Segment [{~'segment-id :id} {:name "My Segment"
:table_id ~'table-id
:definition {:source-table ~'table-id
:filter [:!= [:field ~'category-field-id nil] nil]}}]
Dashboard [{~'dashboard-id :id} {:name "My Dashboard"
:collection_id ~'collection-id}]
Dashboard [{~'root-dashboard-id :id} {:name "Root Dashboard"}]
Card [{~'card-id :id}
{:table_id ~'table-id
:name "My Card"
:collection_id ~'collection-id
:dataset_query {:type :query
:database ~'db-id
:query {:source-table ~'table-id
:filter [:= [:field ~'category-field-id nil] 2]
:aggregation [:sum [:field ~'numeric-field-id nil]]
:breakout [[:field ~'category-field-id nil]]
:joins [{:source-table ~'table-id-categories
:alias "cat"
:fields "all"
:condition [:=
[:field ~'category-field-id nil]
[:field
~'category-pk-field-id
{:join-alias "cat"}]]}]}}}]
Dependency [{~'dependency-id :id} {:model "Card"
:model_id ~'card-id
:dependent_on_model "Segment"
:dependent_on_id ~'segment-id
:created_at :%now}]
Card [{~'card-arch-id :id}
{;:archived true
:table_id ~'table-id
:name "My Arch Card"
:collection_id ~'collection-id
:dataset_query {:type :query
:database ~'db-id
:query {:source-table ~'table-id
:aggregation [:sum [:field ~'numeric-field-id nil]]
:breakout [[:field ~'category-field-id nil]]}}}]
Card [{~'card-id-root :id}
{:table_id ~'table-id
;; https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words
:name root-card-name
:dataset_query {:type :query
:database ~'db-id
:query {:source-table ~'table-id}
:expressions {"Price Known" [:> [:field ~'numeric-field-id nil] 0]}}}]
Card [{~'card-id-nested :id}
{:table_id ~'table-id
:name "My Nested Card"
:collection_id ~'collection-id
:dataset_query {:type :query
:database ~'db-id
:query {:source-table (str "card__" ~'card-id)}}
:visualization_settings
{:table.columns [{:name "Venue Category"
:fieldRef [:field ~'category-field-id nil]
:enabled true}]
:column_settings {(keyword (format
"[\"ref\",[\"field\",%d,null]]"
~'latitude-field-id))
{:show_mini_bar true
:column_title "Parallel"}}}}]
Card [{~'card-id-nested-query :id}
{:table_id ~'table-id
:name "My Nested Query Card"
:collection_id ~'collection-id
:dataset_query
{:type :query
:database ~'db-id
:query
{:source-query
{:source-query
{:source-table ~'table-id}}}}}]
Card [{~'card-id-native-query :id}
{:query_type :native
:name "My Native Nested Query Card"
:collection_id ~'collection-id
:dataset_query
{:type :native
:database ~'db-id
:native
{:query "SELECT * FROM {{#1}} AS subquery"
:template-tags
{"#1"{:id "72461b3b-3877-4538-a5a3-7a3041924517"
:name "#1"
:display-name "#1"
:type "card"
:card-id ~'card-id}}}}}]
DashboardCard [{~'dashcard-id :id}
{:dashboard_id ~'dashboard-id
:card_id ~'card-id}]
DashboardCard [{~'dashcard-top-level-click-id :id}
{:dashboard_id ~'dashboard-id
:card_id ~'card-id-nested
;; this is how click actions on a non-table card work (ex: a chart)
:visualization_settings {:click_behavior {:targetId ~'card-id-nested-query
:linkType :question
:type :link}}}]
DashboardCardSeries [~'_ {:dashboardcard_id ~'dashcard-id
:card_id ~'card-id
:position 0}]
DashboardCardSeries [~'_ {:dashboardcard_id ~'dashcard-top-level-click-id
:card_id ~'card-id-nested
:position 1}]
DashboardCard [{~'dashcard-with-click-actions :id}
{:dashboard_id ~'dashboard-id
:card_id ~'card-id-root
:visualization_settings (-> (mb.viz/visualization-settings)
(mb.viz/with-entity-click-action
~'numeric-field-id
::mb.viz/card
~'card-id
(mb.viz/fk-parameter-mapping
"Category"
~'category-field-id
~'numeric-field-id))
(mb.viz/with-entity-click-action
~'name-field-id
::mb.viz/dashboard
~'root-dashboard-id)
(mb.viz/with-click-action
(mb.viz/column-name->column-ref "Price Known")
(mb.viz/url-click-action "/price-info"))
(mb.viz/with-click-action
(mb.viz/field-id->column-ref ~'latitude-field-id)
(mb.viz/crossfilter-click-action {}))
mb.viz/norm->db)}]
DashboardCardSeries [~'_ {:dashboardcard_id ~'dashcard-with-click-actions
:card_id ~'card-id-root
:position 2}]
DashboardCard [{~'dashcard-with-textbox-id :id}
{:dashboard_id ~'dashboard-id
:card_id nil
:visualization_settings {:virtual_card virtual-card
:text "Textbox Card"}}]
Card [{~'card-id-root-to-collection :id}
{:table_id ~'table-id
:name "Root card based on one in collection"
:dataset_query {:type :query
:database ~'db-id
:query {:source-table (str "card__" ~'card-id)}}}]
Card [{~'card-id-collection-to-root :id}
{:table_id ~'table-id
:name "Card in collection based on root one"
:collection_id ~'collection-id
:dataset_query {:type :query
:database ~'db-id
:query {:source-table (str "card__" ~'card-id-root)}}}]
Pulse [{~'pulse-id :id} {:name "Serialization Pulse"
:collection_id ~'collection-id}]
PulseCard [{~'pulsecard-root-id :id} {:pulse_id ~'pulse-id
:card_id ~'card-id-root}]
PulseCard [{~'pulsecard-collection-id :id} {:pulse_id ~'pulse-id
:card_id ~'card-id}
:query {:source-table (str "card__" ~'card-id-root)}]
Card [{~'card-id-template-tags :id}
{:query_type :native
:name "My Native Card With Template Tags"
:collection_id ~'collection-id
:dataset_query
{:type :native
:database ~'db-id
:native {:query "SELECT * FROM venues WHERE {{category-id}}"
:template-tags
{"category-id" {:id "751880ce-ad1a-11eb-8529-0242ac130003"
:name "category-id"
:display-name "Category ID"
:type "dimension"
:dimension [:field ~'category-field-id nil]
:widget-type "id"
:required true
:default 40}}}}}]
Card [{~'card-id-filter-agg :id}
{:table_id ~'table-id
:name "Card With Filter After Aggregation"
:collection_id ~'collection-id
:dataset_query {:type :query
:database ~'db-id
:query {:source-query {:source-table
~'table-id
:aggregation
[[:aggregation-options
[:count]
{:name "num_per_type"}]]
:breakout
[[:field ~'category-field-id nil]]}
:filter [:>
[:field-literal "num_per_type" :type/Integer]
4]}}}]
Card [{~'card-id-temporal-unit :id}
{:table_id ~'table-id
:name "Card With Temporal Unit in Field Clause"
:collection_id ~'collection-id
:dataset_query {:type :query
:database ~'db-id
:query {:source-query {:source-table
~'table-id-checkins
:aggregation
[[:count]]
:breakout
[[:field ~'last-login-field-id {:source-field
~'user-id-field-id
:temporal-unit
:month}]]}}}}]
NativeQuerySnippet [{~'snippet-id :id}
{:content "price > 2"
:description "Predicate on venues table for price > 2"
:name "Pricey Venues"}]
Collection [{~'snippet-collection-id :id}
{:name "Snippet Collection"
:namespace "snippets"}]
Collection [{~'snippet-nested-collection-id :id}
{:name "Nested Snippet Collection"
:location (format "/%d/" ~'snippet-collection-id)
:namespace "snippets"}]
NativeQuerySnippet [{~'nested-snippet-id :id}
{:content "name LIKE 'A%'"
:description "Predicate on venues table for name starting with A"
:name "A Venues"
:collection_id ~'snippet-nested-collection-id}]
Card [{~'card-id-with-native-snippet :id}
{:query_type :native
:name "Card with Native Query Snippet"
:collection_id ~'collection-id
:dataset_query
{:type :native
:database ~'db-id
:native {:query (str "SELECT * FROM venues WHERE {{snippet: Pricey Venues}}"
" AND {{snippet: A Venues}}")
:template-tags {"snippet: Pricey Venues"
{:id "d34baf40-b35a-11eb-8529-0242ac130003"
:name "Snippet: Pricey Venues"
:display-name "Snippet: Pricey Venues"
:type "snippet"
:snippet-name "Pricey Venues"
:snippet-id ~'snippet-id}
"snippet: A Venues"
{:id "c0775274-b45a-11eb-8529-0242ac130003"
:name "Snippet: A Venues"
:display-name "Snippet: A Venues"
:type "snippet"
:snippet-name "A Venues"
:snippet-id ~'nested-snippet-id}}}}}]
Card [{~'card-join-card-id :id}
{:table_id ~'table-id-checkins
:name "Card Joining to Another Card"
:collection_id ~'collection-id
:dataset_query {:type :query
:database ~'db-id
:query {:source-table ~'table-id-checkins
:joins [{:source-table (str "card__" ~'card-id-root)
:alias "v"
:fields "all"
:condition [:=
[:field
~'checkins->venues-field-id
nil]
[:field
~'venues-pk-field-id
{:join-alias "v"}]]}]}}}]]
(qp.store/with-store ~@body)))
;; Don't memoize as IDs change in each `with-world` context
(alter-var-root #'names/path->context (fn [_] #'names/path->context*))
| 99641 | (ns metabase-enterprise.serialization.test-util
(:require [metabase-enterprise.serialization.names :as names]
[metabase.models :refer [Card Collection Dashboard DashboardCard DashboardCardSeries Database Dependency
Field Metric NativeQuerySnippet Pulse PulseCard Segment Table User]]
[metabase.models.collection :as collection]
[metabase.query-processor.store :as qp.store]
[metabase.shared.models.visualization-settings :as mb.viz]
[metabase.test :as mt]
[metabase.test.data :as data]
[toucan.db :as db]
[toucan.util.test :as tt]))
(def root-card-name "My Root Card \\ with a/nasty: (*) //n`me ' * ? \" < > | ŠĐž")
(def temp-db-name "Fingerprint test-data copy")
(defn temp-field [from-field-id table-id]
(-> from-field-id
Field
(dissoc :id)
(assoc :table_id table-id)))
(defn temp-table [from-tbl-id db-id]
(-> from-tbl-id
Table
(dissoc :id)
(update :display_name #(str "Temp " %))
(assoc :db_id db-id)))
(def virtual-card {:name nil
:display "text"
:visualization_settings {}
:dataset_query {}
:archived false})
(defn crowberto-pc-id
"Gets the personal collection ID for :crowberto (needed for tests). Must be public because the `with-world` macro
is public."
[]
(db/select-one-field :id Collection :personal_owner_id (mt/user->id :crowberto)))
(defmacro with-temp-dpc
"Wraps with-temp*, but binding `*allow-deleting-personal-collections*` to true so that temporary personal collections
can still be deleted."
[model-bindings & body]
`(binding [collection/*allow-deleting-personal-collections* true]
(tt/with-temp* ~model-bindings ~@body)))
(defmacro with-world
"Run test in the context of a minimal Metabase instance connected to our test database."
[& body]
`(with-temp-dpc [Database [{~'db-id :id} (into {:name temp-db-name} (-> (data/id)
Database
(dissoc :id :features :name)))]
Table [{~'table-id :id :as ~'table} (temp-table (data/id :venues) ~'db-id)]
Table [{~'table-id-categories :id} (temp-table (data/id :categories) ~'db-id)]
Table [{~'table-id-users :id} (temp-table (data/id :users) ~'db-id)]
Table [{~'table-id-checkins :id} (temp-table (data/id :checkins) ~'db-id)]
Field [{~'venues-pk-field-id :id} (temp-field (data/id :venues :id) ~'table-id)]
Field [{~'numeric-field-id :id} (temp-field (data/id :venues :price) ~'table-id)]
Field [{~'name-field-id :id} (temp-field (data/id :venues :name) ~'table-id)]
Field [{~'latitude-field-id :id} (temp-field (data/id :venues :latitude) ~'table-id)]
Field [{~'longitude-field-id :id} (temp-field (data/id :venues :longitude) ~'table-id)]
Field [{~'category-field-id :id} (temp-field (data/id :venues :category_id) ~'table-id)]
Field [{~'category-pk-field-id :id} (temp-field
(data/id :categories :id)
~'table-id-categories)]
Field [{~'date-field-id :id} (temp-field (data/id :checkins :date) ~'table-id-checkins)]
Field [{~'users-pk-field-id :id} (temp-field (data/id :users :id)
~'table-id-users)]
Field [{~'user-id-field-id :id} (-> (temp-field (data/id :checkins :user_id)
~'table-id-checkins)
(assoc :fk_target_field_id ~'users-pk-field-id))]
Field [{~'checkins->venues-field-id :id} (-> (temp-field (data/id :checkins :venue_id)
~'table-id-checkins)
(assoc :fk_target_field_id ~'venues-pk-field-id))]
Field [{~'last-login-field-id :id} (temp-field (data/id :users :last_login)
~'table-id-users)]
Collection [{~'collection-id :id} {:name "My Collection"}]
Collection [{~'collection-id-nested :id} {:name "My Nested Collection"
:location (format "/%s/" ~'collection-id)}]
User [{~'user-id-temp :id} {:email "<EMAIL>"
:first_name "<NAME>"
:last_name "<NAME>"
:password "<PASSWORD>"}]
Collection [{~'personal-collection-id :id} {:name "<NAME>'s Personal Collection"
:personal_owner_id ~'user-id-temp}]
Collection [{~'pc-felicia-nested-id :id} {:name "F<NAME>'s Nested Collection"
:location (format "/%d/" ~'personal-collection-id)}]
Collection [{~'pc-nested-id :id} {:name "Nested Personal Collection"
:location (format "/%d/" (crowberto-pc-id))}]
Collection [{~'pc-deeply-nested-id :id} {:name
"Deeply Nested Personal Collection"
:location
(format "/%d/%d/" (crowberto-pc-id) ~'pc-nested-id)}]
Metric [{~'metric-id :id} {:name "My Metric"
:table_id ~'table-id
:definition {:source-table ~'table-id
:aggregation [:sum [:field ~'numeric-field-id nil]]}}]
Segment [{~'segment-id :id} {:name "My Segment"
:table_id ~'table-id
:definition {:source-table ~'table-id
:filter [:!= [:field ~'category-field-id nil] nil]}}]
Dashboard [{~'dashboard-id :id} {:name "My Dashboard"
:collection_id ~'collection-id}]
Dashboard [{~'root-dashboard-id :id} {:name "Root Dashboard"}]
Card [{~'card-id :id}
{:table_id ~'table-id
:name "My Card"
:collection_id ~'collection-id
:dataset_query {:type :query
:database ~'db-id
:query {:source-table ~'table-id
:filter [:= [:field ~'category-field-id nil] 2]
:aggregation [:sum [:field ~'numeric-field-id nil]]
:breakout [[:field ~'category-field-id nil]]
:joins [{:source-table ~'table-id-categories
:alias "cat"
:fields "all"
:condition [:=
[:field ~'category-field-id nil]
[:field
~'category-pk-field-id
{:join-alias "cat"}]]}]}}}]
Dependency [{~'dependency-id :id} {:model "Card"
:model_id ~'card-id
:dependent_on_model "Segment"
:dependent_on_id ~'segment-id
:created_at :%now}]
Card [{~'card-arch-id :id}
{;:archived true
:table_id ~'table-id
:name "My Arch Card"
:collection_id ~'collection-id
:dataset_query {:type :query
:database ~'db-id
:query {:source-table ~'table-id
:aggregation [:sum [:field ~'numeric-field-id nil]]
:breakout [[:field ~'category-field-id nil]]}}}]
Card [{~'card-id-root :id}
{:table_id ~'table-id
;; https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words
:name root-card-name
:dataset_query {:type :query
:database ~'db-id
:query {:source-table ~'table-id}
:expressions {"Price Known" [:> [:field ~'numeric-field-id nil] 0]}}}]
Card [{~'card-id-nested :id}
{:table_id ~'table-id
:name "My Nested Card"
:collection_id ~'collection-id
:dataset_query {:type :query
:database ~'db-id
:query {:source-table (str "card__" ~'card-id)}}
:visualization_settings
{:table.columns [{:name "Venue Category"
:fieldRef [:field ~'category-field-id nil]
:enabled true}]
:column_settings {(keyword (format
"[\"ref\",[\"field\",%d,null]]"
~'latitude-field-id))
{:show_mini_bar true
:column_title "Parallel"}}}}]
Card [{~'card-id-nested-query :id}
{:table_id ~'table-id
:name "My Nested Query Card"
:collection_id ~'collection-id
:dataset_query
{:type :query
:database ~'db-id
:query
{:source-query
{:source-query
{:source-table ~'table-id}}}}}]
Card [{~'card-id-native-query :id}
{:query_type :native
:name "My Native Nested Query Card"
:collection_id ~'collection-id
:dataset_query
{:type :native
:database ~'db-id
:native
{:query "SELECT * FROM {{#1}} AS subquery"
:template-tags
{"#1"{:id "72461b3b-3877-4538-a5a3-7a3041924517"
:name "#1"
:display-name "#1"
:type "card"
:card-id ~'card-id}}}}}]
DashboardCard [{~'dashcard-id :id}
{:dashboard_id ~'dashboard-id
:card_id ~'card-id}]
DashboardCard [{~'dashcard-top-level-click-id :id}
{:dashboard_id ~'dashboard-id
:card_id ~'card-id-nested
;; this is how click actions on a non-table card work (ex: a chart)
:visualization_settings {:click_behavior {:targetId ~'card-id-nested-query
:linkType :question
:type :link}}}]
DashboardCardSeries [~'_ {:dashboardcard_id ~'dashcard-id
:card_id ~'card-id
:position 0}]
DashboardCardSeries [~'_ {:dashboardcard_id ~'dashcard-top-level-click-id
:card_id ~'card-id-nested
:position 1}]
DashboardCard [{~'dashcard-with-click-actions :id}
{:dashboard_id ~'dashboard-id
:card_id ~'card-id-root
:visualization_settings (-> (mb.viz/visualization-settings)
(mb.viz/with-entity-click-action
~'numeric-field-id
::mb.viz/card
~'card-id
(mb.viz/fk-parameter-mapping
"Category"
~'category-field-id
~'numeric-field-id))
(mb.viz/with-entity-click-action
~'name-field-id
::mb.viz/dashboard
~'root-dashboard-id)
(mb.viz/with-click-action
(mb.viz/column-name->column-ref "Price Known")
(mb.viz/url-click-action "/price-info"))
(mb.viz/with-click-action
(mb.viz/field-id->column-ref ~'latitude-field-id)
(mb.viz/crossfilter-click-action {}))
mb.viz/norm->db)}]
DashboardCardSeries [~'_ {:dashboardcard_id ~'dashcard-with-click-actions
:card_id ~'card-id-root
:position 2}]
DashboardCard [{~'dashcard-with-textbox-id :id}
{:dashboard_id ~'dashboard-id
:card_id nil
:visualization_settings {:virtual_card virtual-card
:text "Textbox Card"}}]
Card [{~'card-id-root-to-collection :id}
{:table_id ~'table-id
:name "Root card based on one in collection"
:dataset_query {:type :query
:database ~'db-id
:query {:source-table (str "card__" ~'card-id)}}}]
Card [{~'card-id-collection-to-root :id}
{:table_id ~'table-id
:name "Card in collection based on root one"
:collection_id ~'collection-id
:dataset_query {:type :query
:database ~'db-id
:query {:source-table (str "card__" ~'card-id-root)}}}]
Pulse [{~'pulse-id :id} {:name "Serialization Pulse"
:collection_id ~'collection-id}]
PulseCard [{~'pulsecard-root-id :id} {:pulse_id ~'pulse-id
:card_id ~'card-id-root}]
PulseCard [{~'pulsecard-collection-id :id} {:pulse_id ~'pulse-id
:card_id ~'card-id}
:query {:source-table (str "card__" ~'card-id-root)}]
Card [{~'card-id-template-tags :id}
{:query_type :native
:name "My Native Card With Template Tags"
:collection_id ~'collection-id
:dataset_query
{:type :native
:database ~'db-id
:native {:query "SELECT * FROM venues WHERE {{category-id}}"
:template-tags
{"category-id" {:id "751880ce-ad1a-11eb-8529-0242ac130003"
:name "category-id"
:display-name "Category ID"
:type "dimension"
:dimension [:field ~'category-field-id nil]
:widget-type "id"
:required true
:default 40}}}}}]
Card [{~'card-id-filter-agg :id}
{:table_id ~'table-id
:name "Card With Filter After Aggregation"
:collection_id ~'collection-id
:dataset_query {:type :query
:database ~'db-id
:query {:source-query {:source-table
~'table-id
:aggregation
[[:aggregation-options
[:count]
{:name "num_per_type"}]]
:breakout
[[:field ~'category-field-id nil]]}
:filter [:>
[:field-literal "num_per_type" :type/Integer]
4]}}}]
Card [{~'card-id-temporal-unit :id}
{:table_id ~'table-id
:name "Card With Temporal Unit in Field Clause"
:collection_id ~'collection-id
:dataset_query {:type :query
:database ~'db-id
:query {:source-query {:source-table
~'table-id-checkins
:aggregation
[[:count]]
:breakout
[[:field ~'last-login-field-id {:source-field
~'user-id-field-id
:temporal-unit
:month}]]}}}}]
NativeQuerySnippet [{~'snippet-id :id}
{:content "price > 2"
:description "Predicate on venues table for price > 2"
:name "Pricey Venues"}]
Collection [{~'snippet-collection-id :id}
{:name "Snippet Collection"
:namespace "snippets"}]
Collection [{~'snippet-nested-collection-id :id}
{:name "Nested Snippet Collection"
:location (format "/%d/" ~'snippet-collection-id)
:namespace "snippets"}]
NativeQuerySnippet [{~'nested-snippet-id :id}
{:content "name LIKE 'A%'"
:description "Predicate on venues table for name starting with A"
:name "A Venues"
:collection_id ~'snippet-nested-collection-id}]
Card [{~'card-id-with-native-snippet :id}
{:query_type :native
:name "Card with Native Query Snippet"
:collection_id ~'collection-id
:dataset_query
{:type :native
:database ~'db-id
:native {:query (str "SELECT * FROM venues WHERE {{snippet: Pricey Venues}}"
" AND {{snippet: A Venues}}")
:template-tags {"snippet: Pricey Venues"
{:id "d34baf40-b35a-11eb-8529-0242ac130003"
:name "Snippet: Pricey Venues"
:display-name "Snippet: Pricey Venues"
:type "snippet"
:snippet-name "Pricey Venues"
:snippet-id ~'snippet-id}
"snippet: A Venues"
{:id "c0775274-b45a-11eb-8529-0242ac130003"
:name "Snippet: A Venues"
:display-name "Snippet: A Venues"
:type "snippet"
:snippet-name "A Venues"
:snippet-id ~'nested-snippet-id}}}}}]
Card [{~'card-join-card-id :id}
{:table_id ~'table-id-checkins
:name "Card Joining to Another Card"
:collection_id ~'collection-id
:dataset_query {:type :query
:database ~'db-id
:query {:source-table ~'table-id-checkins
:joins [{:source-table (str "card__" ~'card-id-root)
:alias "v"
:fields "all"
:condition [:=
[:field
~'checkins->venues-field-id
nil]
[:field
~'venues-pk-field-id
{:join-alias "v"}]]}]}}}]]
(qp.store/with-store ~@body)))
;; Don't memoize as IDs change in each `with-world` context
(alter-var-root #'names/path->context (fn [_] #'names/path->context*))
| true | (ns metabase-enterprise.serialization.test-util
(:require [metabase-enterprise.serialization.names :as names]
[metabase.models :refer [Card Collection Dashboard DashboardCard DashboardCardSeries Database Dependency
Field Metric NativeQuerySnippet Pulse PulseCard Segment Table User]]
[metabase.models.collection :as collection]
[metabase.query-processor.store :as qp.store]
[metabase.shared.models.visualization-settings :as mb.viz]
[metabase.test :as mt]
[metabase.test.data :as data]
[toucan.db :as db]
[toucan.util.test :as tt]))
(def root-card-name "My Root Card \\ with a/nasty: (*) //n`me ' * ? \" < > | ŠĐž")
(def temp-db-name "Fingerprint test-data copy")
(defn temp-field [from-field-id table-id]
(-> from-field-id
Field
(dissoc :id)
(assoc :table_id table-id)))
(defn temp-table [from-tbl-id db-id]
(-> from-tbl-id
Table
(dissoc :id)
(update :display_name #(str "Temp " %))
(assoc :db_id db-id)))
(def virtual-card {:name nil
:display "text"
:visualization_settings {}
:dataset_query {}
:archived false})
(defn crowberto-pc-id
"Gets the personal collection ID for :crowberto (needed for tests). Must be public because the `with-world` macro
is public."
[]
(db/select-one-field :id Collection :personal_owner_id (mt/user->id :crowberto)))
(defmacro with-temp-dpc
"Wraps with-temp*, but binding `*allow-deleting-personal-collections*` to true so that temporary personal collections
can still be deleted."
[model-bindings & body]
`(binding [collection/*allow-deleting-personal-collections* true]
(tt/with-temp* ~model-bindings ~@body)))
(defmacro with-world
"Run test in the context of a minimal Metabase instance connected to our test database."
[& body]
`(with-temp-dpc [Database [{~'db-id :id} (into {:name temp-db-name} (-> (data/id)
Database
(dissoc :id :features :name)))]
Table [{~'table-id :id :as ~'table} (temp-table (data/id :venues) ~'db-id)]
Table [{~'table-id-categories :id} (temp-table (data/id :categories) ~'db-id)]
Table [{~'table-id-users :id} (temp-table (data/id :users) ~'db-id)]
Table [{~'table-id-checkins :id} (temp-table (data/id :checkins) ~'db-id)]
Field [{~'venues-pk-field-id :id} (temp-field (data/id :venues :id) ~'table-id)]
Field [{~'numeric-field-id :id} (temp-field (data/id :venues :price) ~'table-id)]
Field [{~'name-field-id :id} (temp-field (data/id :venues :name) ~'table-id)]
Field [{~'latitude-field-id :id} (temp-field (data/id :venues :latitude) ~'table-id)]
Field [{~'longitude-field-id :id} (temp-field (data/id :venues :longitude) ~'table-id)]
Field [{~'category-field-id :id} (temp-field (data/id :venues :category_id) ~'table-id)]
Field [{~'category-pk-field-id :id} (temp-field
(data/id :categories :id)
~'table-id-categories)]
Field [{~'date-field-id :id} (temp-field (data/id :checkins :date) ~'table-id-checkins)]
Field [{~'users-pk-field-id :id} (temp-field (data/id :users :id)
~'table-id-users)]
Field [{~'user-id-field-id :id} (-> (temp-field (data/id :checkins :user_id)
~'table-id-checkins)
(assoc :fk_target_field_id ~'users-pk-field-id))]
Field [{~'checkins->venues-field-id :id} (-> (temp-field (data/id :checkins :venue_id)
~'table-id-checkins)
(assoc :fk_target_field_id ~'venues-pk-field-id))]
Field [{~'last-login-field-id :id} (temp-field (data/id :users :last_login)
~'table-id-users)]
Collection [{~'collection-id :id} {:name "My Collection"}]
Collection [{~'collection-id-nested :id} {:name "My Nested Collection"
:location (format "/%s/" ~'collection-id)}]
User [{~'user-id-temp :id} {:email "PI:EMAIL:<EMAIL>END_PI"
:first_name "PI:NAME:<NAME>END_PI"
:last_name "PI:NAME:<NAME>END_PI"
:password "PI:PASSWORD:<PASSWORD>END_PI"}]
Collection [{~'personal-collection-id :id} {:name "PI:NAME:<NAME>END_PI's Personal Collection"
:personal_owner_id ~'user-id-temp}]
Collection [{~'pc-felicia-nested-id :id} {:name "FPI:NAME:<NAME>END_PI's Nested Collection"
:location (format "/%d/" ~'personal-collection-id)}]
Collection [{~'pc-nested-id :id} {:name "Nested Personal Collection"
:location (format "/%d/" (crowberto-pc-id))}]
Collection [{~'pc-deeply-nested-id :id} {:name
"Deeply Nested Personal Collection"
:location
(format "/%d/%d/" (crowberto-pc-id) ~'pc-nested-id)}]
Metric [{~'metric-id :id} {:name "My Metric"
:table_id ~'table-id
:definition {:source-table ~'table-id
:aggregation [:sum [:field ~'numeric-field-id nil]]}}]
Segment [{~'segment-id :id} {:name "My Segment"
:table_id ~'table-id
:definition {:source-table ~'table-id
:filter [:!= [:field ~'category-field-id nil] nil]}}]
Dashboard [{~'dashboard-id :id} {:name "My Dashboard"
:collection_id ~'collection-id}]
Dashboard [{~'root-dashboard-id :id} {:name "Root Dashboard"}]
Card [{~'card-id :id}
{:table_id ~'table-id
:name "My Card"
:collection_id ~'collection-id
:dataset_query {:type :query
:database ~'db-id
:query {:source-table ~'table-id
:filter [:= [:field ~'category-field-id nil] 2]
:aggregation [:sum [:field ~'numeric-field-id nil]]
:breakout [[:field ~'category-field-id nil]]
:joins [{:source-table ~'table-id-categories
:alias "cat"
:fields "all"
:condition [:=
[:field ~'category-field-id nil]
[:field
~'category-pk-field-id
{:join-alias "cat"}]]}]}}}]
Dependency [{~'dependency-id :id} {:model "Card"
:model_id ~'card-id
:dependent_on_model "Segment"
:dependent_on_id ~'segment-id
:created_at :%now}]
Card [{~'card-arch-id :id}
{;:archived true
:table_id ~'table-id
:name "My Arch Card"
:collection_id ~'collection-id
:dataset_query {:type :query
:database ~'db-id
:query {:source-table ~'table-id
:aggregation [:sum [:field ~'numeric-field-id nil]]
:breakout [[:field ~'category-field-id nil]]}}}]
Card [{~'card-id-root :id}
{:table_id ~'table-id
;; https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words
:name root-card-name
:dataset_query {:type :query
:database ~'db-id
:query {:source-table ~'table-id}
:expressions {"Price Known" [:> [:field ~'numeric-field-id nil] 0]}}}]
Card [{~'card-id-nested :id}
{:table_id ~'table-id
:name "My Nested Card"
:collection_id ~'collection-id
:dataset_query {:type :query
:database ~'db-id
:query {:source-table (str "card__" ~'card-id)}}
:visualization_settings
{:table.columns [{:name "Venue Category"
:fieldRef [:field ~'category-field-id nil]
:enabled true}]
:column_settings {(keyword (format
"[\"ref\",[\"field\",%d,null]]"
~'latitude-field-id))
{:show_mini_bar true
:column_title "Parallel"}}}}]
Card [{~'card-id-nested-query :id}
{:table_id ~'table-id
:name "My Nested Query Card"
:collection_id ~'collection-id
:dataset_query
{:type :query
:database ~'db-id
:query
{:source-query
{:source-query
{:source-table ~'table-id}}}}}]
Card [{~'card-id-native-query :id}
{:query_type :native
:name "My Native Nested Query Card"
:collection_id ~'collection-id
:dataset_query
{:type :native
:database ~'db-id
:native
{:query "SELECT * FROM {{#1}} AS subquery"
:template-tags
{"#1"{:id "72461b3b-3877-4538-a5a3-7a3041924517"
:name "#1"
:display-name "#1"
:type "card"
:card-id ~'card-id}}}}}]
DashboardCard [{~'dashcard-id :id}
{:dashboard_id ~'dashboard-id
:card_id ~'card-id}]
DashboardCard [{~'dashcard-top-level-click-id :id}
{:dashboard_id ~'dashboard-id
:card_id ~'card-id-nested
;; this is how click actions on a non-table card work (ex: a chart)
:visualization_settings {:click_behavior {:targetId ~'card-id-nested-query
:linkType :question
:type :link}}}]
DashboardCardSeries [~'_ {:dashboardcard_id ~'dashcard-id
:card_id ~'card-id
:position 0}]
DashboardCardSeries [~'_ {:dashboardcard_id ~'dashcard-top-level-click-id
:card_id ~'card-id-nested
:position 1}]
DashboardCard [{~'dashcard-with-click-actions :id}
{:dashboard_id ~'dashboard-id
:card_id ~'card-id-root
:visualization_settings (-> (mb.viz/visualization-settings)
(mb.viz/with-entity-click-action
~'numeric-field-id
::mb.viz/card
~'card-id
(mb.viz/fk-parameter-mapping
"Category"
~'category-field-id
~'numeric-field-id))
(mb.viz/with-entity-click-action
~'name-field-id
::mb.viz/dashboard
~'root-dashboard-id)
(mb.viz/with-click-action
(mb.viz/column-name->column-ref "Price Known")
(mb.viz/url-click-action "/price-info"))
(mb.viz/with-click-action
(mb.viz/field-id->column-ref ~'latitude-field-id)
(mb.viz/crossfilter-click-action {}))
mb.viz/norm->db)}]
DashboardCardSeries [~'_ {:dashboardcard_id ~'dashcard-with-click-actions
:card_id ~'card-id-root
:position 2}]
DashboardCard [{~'dashcard-with-textbox-id :id}
{:dashboard_id ~'dashboard-id
:card_id nil
:visualization_settings {:virtual_card virtual-card
:text "Textbox Card"}}]
Card [{~'card-id-root-to-collection :id}
{:table_id ~'table-id
:name "Root card based on one in collection"
:dataset_query {:type :query
:database ~'db-id
:query {:source-table (str "card__" ~'card-id)}}}]
Card [{~'card-id-collection-to-root :id}
{:table_id ~'table-id
:name "Card in collection based on root one"
:collection_id ~'collection-id
:dataset_query {:type :query
:database ~'db-id
:query {:source-table (str "card__" ~'card-id-root)}}}]
Pulse [{~'pulse-id :id} {:name "Serialization Pulse"
:collection_id ~'collection-id}]
PulseCard [{~'pulsecard-root-id :id} {:pulse_id ~'pulse-id
:card_id ~'card-id-root}]
PulseCard [{~'pulsecard-collection-id :id} {:pulse_id ~'pulse-id
:card_id ~'card-id}
:query {:source-table (str "card__" ~'card-id-root)}]
Card [{~'card-id-template-tags :id}
{:query_type :native
:name "My Native Card With Template Tags"
:collection_id ~'collection-id
:dataset_query
{:type :native
:database ~'db-id
:native {:query "SELECT * FROM venues WHERE {{category-id}}"
:template-tags
{"category-id" {:id "751880ce-ad1a-11eb-8529-0242ac130003"
:name "category-id"
:display-name "Category ID"
:type "dimension"
:dimension [:field ~'category-field-id nil]
:widget-type "id"
:required true
:default 40}}}}}]
Card [{~'card-id-filter-agg :id}
{:table_id ~'table-id
:name "Card With Filter After Aggregation"
:collection_id ~'collection-id
:dataset_query {:type :query
:database ~'db-id
:query {:source-query {:source-table
~'table-id
:aggregation
[[:aggregation-options
[:count]
{:name "num_per_type"}]]
:breakout
[[:field ~'category-field-id nil]]}
:filter [:>
[:field-literal "num_per_type" :type/Integer]
4]}}}]
Card [{~'card-id-temporal-unit :id}
{:table_id ~'table-id
:name "Card With Temporal Unit in Field Clause"
:collection_id ~'collection-id
:dataset_query {:type :query
:database ~'db-id
:query {:source-query {:source-table
~'table-id-checkins
:aggregation
[[:count]]
:breakout
[[:field ~'last-login-field-id {:source-field
~'user-id-field-id
:temporal-unit
:month}]]}}}}]
NativeQuerySnippet [{~'snippet-id :id}
{:content "price > 2"
:description "Predicate on venues table for price > 2"
:name "Pricey Venues"}]
Collection [{~'snippet-collection-id :id}
{:name "Snippet Collection"
:namespace "snippets"}]
Collection [{~'snippet-nested-collection-id :id}
{:name "Nested Snippet Collection"
:location (format "/%d/" ~'snippet-collection-id)
:namespace "snippets"}]
NativeQuerySnippet [{~'nested-snippet-id :id}
{:content "name LIKE 'A%'"
:description "Predicate on venues table for name starting with A"
:name "A Venues"
:collection_id ~'snippet-nested-collection-id}]
Card [{~'card-id-with-native-snippet :id}
{:query_type :native
:name "Card with Native Query Snippet"
:collection_id ~'collection-id
:dataset_query
{:type :native
:database ~'db-id
:native {:query (str "SELECT * FROM venues WHERE {{snippet: Pricey Venues}}"
" AND {{snippet: A Venues}}")
:template-tags {"snippet: Pricey Venues"
{:id "d34baf40-b35a-11eb-8529-0242ac130003"
:name "Snippet: Pricey Venues"
:display-name "Snippet: Pricey Venues"
:type "snippet"
:snippet-name "Pricey Venues"
:snippet-id ~'snippet-id}
"snippet: A Venues"
{:id "c0775274-b45a-11eb-8529-0242ac130003"
:name "Snippet: A Venues"
:display-name "Snippet: A Venues"
:type "snippet"
:snippet-name "A Venues"
:snippet-id ~'nested-snippet-id}}}}}]
Card [{~'card-join-card-id :id}
{:table_id ~'table-id-checkins
:name "Card Joining to Another Card"
:collection_id ~'collection-id
:dataset_query {:type :query
:database ~'db-id
:query {:source-table ~'table-id-checkins
:joins [{:source-table (str "card__" ~'card-id-root)
:alias "v"
:fields "all"
:condition [:=
[:field
~'checkins->venues-field-id
nil]
[:field
~'venues-pk-field-id
{:join-alias "v"}]]}]}}}]]
(qp.store/with-store ~@body)))
;; Don't memoize as IDs change in each `with-world` context
(alter-var-root #'names/path->context (fn [_] #'names/path->context*))
|
[
{
"context": "n Etch instance. See [[convex.db]].\"\n\n {:author \"Adam Helinski\"}\n\n (:import (convex.core.store AStore\n ",
"end": 579,
"score": 0.9994574785232544,
"start": 566,
"tag": "NAME",
"value": "Adam Helinski"
}
] | project/cvm/src/clj/main/convex/cvm/db.clj | rosejn/convex.cljc | 30 | (ns convex.cvm.db
"When a CVM instance is used, it relies on a thread-local database which can be manually retrieved using [[local]].
The thread-local database can be set usint [[local-set]]. Originally, at thread initialization, it corresponds to
the [[global]] database which is common to all threads. Its value can also be altered using [[global-set]].
Ultimately, the [[global]] database itself returns [[default]] unless user has set its value to another database.
Default [[database]] is an Etch instance. See [[convex.db]]."
{:author "Adam Helinski"}
(:import (convex.core.store AStore
Stores)))
;;;;;;;;;;
(defn global
"Returns the global database."
^AStore
[]
(Stores/getGlobalStore))
(defn global-set
"Sets the global database returned by [[global]]."
^AStore
[db]
(Stores/setGlobalStore db)
db)
(defn local
"Returns the thread-local database used by any CVM instance operating in the same thread."
^AStore
[]
(Stores/current))
(defn local-set
"Sets the thread-local database returned by [[local]]."
^AStore
[db]
(Stores/setCurrent db)
db)
(defmacro local-with
"Macro using `local-set` momentarily to execute given forms before restoring the previous thread-local database."
^AStore
[db & form+]
`(let [db# ~db
cached# (local)]
(local-set db#)
(try
~@form+
(finally
(local-set cached#)))))
| 41190 | (ns convex.cvm.db
"When a CVM instance is used, it relies on a thread-local database which can be manually retrieved using [[local]].
The thread-local database can be set usint [[local-set]]. Originally, at thread initialization, it corresponds to
the [[global]] database which is common to all threads. Its value can also be altered using [[global-set]].
Ultimately, the [[global]] database itself returns [[default]] unless user has set its value to another database.
Default [[database]] is an Etch instance. See [[convex.db]]."
{:author "<NAME>"}
(:import (convex.core.store AStore
Stores)))
;;;;;;;;;;
(defn global
"Returns the global database."
^AStore
[]
(Stores/getGlobalStore))
(defn global-set
"Sets the global database returned by [[global]]."
^AStore
[db]
(Stores/setGlobalStore db)
db)
(defn local
"Returns the thread-local database used by any CVM instance operating in the same thread."
^AStore
[]
(Stores/current))
(defn local-set
"Sets the thread-local database returned by [[local]]."
^AStore
[db]
(Stores/setCurrent db)
db)
(defmacro local-with
"Macro using `local-set` momentarily to execute given forms before restoring the previous thread-local database."
^AStore
[db & form+]
`(let [db# ~db
cached# (local)]
(local-set db#)
(try
~@form+
(finally
(local-set cached#)))))
| true | (ns convex.cvm.db
"When a CVM instance is used, it relies on a thread-local database which can be manually retrieved using [[local]].
The thread-local database can be set usint [[local-set]]. Originally, at thread initialization, it corresponds to
the [[global]] database which is common to all threads. Its value can also be altered using [[global-set]].
Ultimately, the [[global]] database itself returns [[default]] unless user has set its value to another database.
Default [[database]] is an Etch instance. See [[convex.db]]."
{:author "PI:NAME:<NAME>END_PI"}
(:import (convex.core.store AStore
Stores)))
;;;;;;;;;;
(defn global
"Returns the global database."
^AStore
[]
(Stores/getGlobalStore))
(defn global-set
"Sets the global database returned by [[global]]."
^AStore
[db]
(Stores/setGlobalStore db)
db)
(defn local
"Returns the thread-local database used by any CVM instance operating in the same thread."
^AStore
[]
(Stores/current))
(defn local-set
"Sets the thread-local database returned by [[local]]."
^AStore
[db]
(Stores/setCurrent db)
db)
(defmacro local-with
"Macro using `local-set` momentarily to execute given forms before restoring the previous thread-local database."
^AStore
[db & form+]
`(let [db# ~db
cached# (local)]
(local-set db#)
(try
~@form+
(finally
(local-set cached#)))))
|
[
{
"context": " (seed/new-account (new-uuid 100) \"Tony\" \"tony@example.com\" \"letmein\"\n ",
"end": 1715,
"score": 0.9998158812522888,
"start": 1711,
"tag": "NAME",
"value": "Tony"
},
{
"context": " (seed/new-account (new-uuid 100) \"Tony\" \"tony@example.com\" \"letmein\"\n :acco",
"end": 1734,
"score": 0.9999246597290039,
"start": 1718,
"tag": "EMAIL",
"value": "tony@example.com"
},
{
"context": " (seed/new-account (new-uuid 101) \"Sam\" \"sam@example.com\" \"letmein\")\n ",
"end": 2079,
"score": 0.9998676180839539,
"start": 2076,
"tag": "NAME",
"value": "Sam"
},
{
"context": " (seed/new-account (new-uuid 101) \"Sam\" \"sam@example.com\" \"letmein\")\n (seed/",
"end": 2097,
"score": 0.9999266862869263,
"start": 2082,
"tag": "EMAIL",
"value": "sam@example.com"
},
{
"context": " (seed/new-account (new-uuid 102) \"Sally\" \"sally@example.com\" \"letmein\")\n ",
"end": 2180,
"score": 0.9998327493667603,
"start": 2175,
"tag": "NAME",
"value": "Sally"
},
{
"context": " (seed/new-account (new-uuid 102) \"Sally\" \"sally@example.com\" \"letmein\")\n (seed/",
"end": 2200,
"score": 0.9999237060546875,
"start": 2183,
"tag": "EMAIL",
"value": "sally@example.com"
},
{
"context": " (seed/new-account (new-uuid 103) \"Barbara\" \"barb@example.com\" \"letmein\")\n ",
"end": 2285,
"score": 0.9997504949569702,
"start": 2278,
"tag": "NAME",
"value": "Barbara"
},
{
"context": " (seed/new-account (new-uuid 103) \"Barbara\" \"barb@example.com\" \"letmein\")\n (seed/",
"end": 2304,
"score": 0.9999261498451233,
"start": 2288,
"tag": "EMAIL",
"value": "barb@example.com"
},
{
"context": " (seed/new-invoice \"invoice-1\" date-1 \"Tony\"\n [(seed/new-line",
"end": 3549,
"score": 0.9961333274841309,
"start": 3545,
"tag": "NAME",
"value": "Tony"
},
{
"context": " (seed/new-invoice \"invoice-2\" date-2 \"Sally\"\n [(seed/new-line",
"end": 3769,
"score": 0.9973692297935486,
"start": 3764,
"tag": "NAME",
"value": "Sally"
},
{
"context": " (seed/new-invoice \"invoice-3\" date-3 \"Sam\"\n [(seed/new-line",
"end": 3990,
"score": 0.999800443649292,
"start": 3987,
"tag": "NAME",
"value": "Sam"
},
{
"context": " (seed/new-invoice \"invoice-4\" date-4 \"Sally\"\n [(seed/new-line",
"end": 4214,
"score": 0.997445821762085,
"start": 4209,
"tag": "NAME",
"value": "Sally"
},
{
"context": " (seed/new-invoice \"invoice-5\" date-5 \"Barbara\"\n [(seed/new-line",
"end": 4366,
"score": 0.991568386554718,
"start": 4359,
"tag": "NAME",
"value": "Barbara"
}
] | src/datomic/development.clj | aeberts/fulcro-rad-demo | 0 | (ns development
(:require
[clojure.pprint :refer [pprint]]
[clojure.repl :refer [doc source]]
[clojure.tools.namespace.repl :as tools-ns :refer [disable-reload! refresh clear set-refresh-dirs]]
[com.example.components.datomic :refer [datomic-connections]]
[com.example.components.ring-middleware]
[com.example.components.server]
[com.example.model.seed :as seed]
[com.example.model.account :as account]
[com.example.model.address :as address]
[com.fulcrologic.rad.ids :refer [new-uuid]]
[com.fulcrologic.rad.database-adapters.datomic :as datomic]
[com.fulcrologic.rad.resolvers :as res]
[mount.core :as mount]
[taoensso.timbre :as log]
[datomic.api :as d]
[com.fulcrologic.rad.attributes :as attr]
[com.fulcrologic.rad.type-support.date-time :as dt]))
(set-refresh-dirs "src/main" "src/datomic" "src/dev" "src/shared" "../fulcro-rad-datomic/src/main" "../fulcro-rad/src/main")
(comment
(let [db (d/db (:main datomic-connections))]
(d/pull db '[*] [:account/id (new-uuid 100)])))
(defn seed! []
(dt/set-timezone! "America/Los_Angeles")
(let [connection (:main datomic-connections)
date-1 (dt/html-datetime-string->inst "2020-01-01T12:00")
date-2 (dt/html-datetime-string->inst "2020-01-05T12:00")
date-3 (dt/html-datetime-string->inst "2020-02-01T12:00")
date-4 (dt/html-datetime-string->inst "2020-03-10T12:00")
date-5 (dt/html-datetime-string->inst "2020-03-21T12:00")]
(when connection
(log/info "SEEDING data.")
@(d/transact connection [(seed/new-address (new-uuid 1) "111 Main St.")
(seed/new-account (new-uuid 100) "Tony" "tony@example.com" "letmein"
:account/addresses ["111 Main St."]
:account/primary-address (seed/new-address (new-uuid 300) "222 Other")
:time-zone/zone-id :time-zone.zone-id/America-Los_Angeles)
(seed/new-account (new-uuid 101) "Sam" "sam@example.com" "letmein")
(seed/new-account (new-uuid 102) "Sally" "sally@example.com" "letmein")
(seed/new-account (new-uuid 103) "Barbara" "barb@example.com" "letmein")
(seed/new-category (new-uuid 1000) "Tools")
(seed/new-category (new-uuid 1002) "Toys")
(seed/new-category (new-uuid 1003) "Misc")
(seed/new-item (new-uuid 200) "Widget" 33.99
:item/category "Misc")
(seed/new-item (new-uuid 201) "Screwdriver" 4.99
:item/category "Tools")
(seed/new-item (new-uuid 202) "Wrench" 14.99
:item/category "Tools")
(seed/new-item (new-uuid 203) "Hammer" 14.99
:item/category "Tools")
(seed/new-item (new-uuid 204) "Doll" 4.99
:item/category "Toys")
(seed/new-item (new-uuid 205) "Robot" 94.99
:item/category "Toys")
(seed/new-item (new-uuid 206) "Building Blocks" 24.99
:item/category "Toys")
(seed/new-invoice "invoice-1" date-1 "Tony"
[(seed/new-line-item "Doll" 1 5.0M)
(seed/new-line-item "Hammer" 1 14.99M)])
(seed/new-invoice "invoice-2" date-2 "Sally"
[(seed/new-line-item "Wrench" 1 12.50M)
(seed/new-line-item "Widget" 2 32.0M)])
(seed/new-invoice "invoice-3" date-3 "Sam"
[(seed/new-line-item "Wrench" 2 12.50M)
(seed/new-line-item "Hammer" 2 12.50M)])
(seed/new-invoice "invoice-4" date-4 "Sally"
[(seed/new-line-item "Robot" 6 89.99M)])
(seed/new-invoice "invoice-5" date-5 "Barbara"
[(seed/new-line-item "Building Blocks" 10 20.0M)])]))))
(defn start []
(mount/start-with-args {:config "config/dev.edn"})
(seed!)
:ok)
(defn stop
"Stop the server."
[]
(mount/stop))
(def go start)
(defn restart
"Stop, refresh, and restart the server."
[]
(stop)
(tools-ns/refresh :after 'development/start))
(def reset #'restart)
| 41283 | (ns development
(:require
[clojure.pprint :refer [pprint]]
[clojure.repl :refer [doc source]]
[clojure.tools.namespace.repl :as tools-ns :refer [disable-reload! refresh clear set-refresh-dirs]]
[com.example.components.datomic :refer [datomic-connections]]
[com.example.components.ring-middleware]
[com.example.components.server]
[com.example.model.seed :as seed]
[com.example.model.account :as account]
[com.example.model.address :as address]
[com.fulcrologic.rad.ids :refer [new-uuid]]
[com.fulcrologic.rad.database-adapters.datomic :as datomic]
[com.fulcrologic.rad.resolvers :as res]
[mount.core :as mount]
[taoensso.timbre :as log]
[datomic.api :as d]
[com.fulcrologic.rad.attributes :as attr]
[com.fulcrologic.rad.type-support.date-time :as dt]))
(set-refresh-dirs "src/main" "src/datomic" "src/dev" "src/shared" "../fulcro-rad-datomic/src/main" "../fulcro-rad/src/main")
(comment
(let [db (d/db (:main datomic-connections))]
(d/pull db '[*] [:account/id (new-uuid 100)])))
(defn seed! []
(dt/set-timezone! "America/Los_Angeles")
(let [connection (:main datomic-connections)
date-1 (dt/html-datetime-string->inst "2020-01-01T12:00")
date-2 (dt/html-datetime-string->inst "2020-01-05T12:00")
date-3 (dt/html-datetime-string->inst "2020-02-01T12:00")
date-4 (dt/html-datetime-string->inst "2020-03-10T12:00")
date-5 (dt/html-datetime-string->inst "2020-03-21T12:00")]
(when connection
(log/info "SEEDING data.")
@(d/transact connection [(seed/new-address (new-uuid 1) "111 Main St.")
(seed/new-account (new-uuid 100) "<NAME>" "<EMAIL>" "letmein"
:account/addresses ["111 Main St."]
:account/primary-address (seed/new-address (new-uuid 300) "222 Other")
:time-zone/zone-id :time-zone.zone-id/America-Los_Angeles)
(seed/new-account (new-uuid 101) "<NAME>" "<EMAIL>" "letmein")
(seed/new-account (new-uuid 102) "<NAME>" "<EMAIL>" "letmein")
(seed/new-account (new-uuid 103) "<NAME>" "<EMAIL>" "letmein")
(seed/new-category (new-uuid 1000) "Tools")
(seed/new-category (new-uuid 1002) "Toys")
(seed/new-category (new-uuid 1003) "Misc")
(seed/new-item (new-uuid 200) "Widget" 33.99
:item/category "Misc")
(seed/new-item (new-uuid 201) "Screwdriver" 4.99
:item/category "Tools")
(seed/new-item (new-uuid 202) "Wrench" 14.99
:item/category "Tools")
(seed/new-item (new-uuid 203) "Hammer" 14.99
:item/category "Tools")
(seed/new-item (new-uuid 204) "Doll" 4.99
:item/category "Toys")
(seed/new-item (new-uuid 205) "Robot" 94.99
:item/category "Toys")
(seed/new-item (new-uuid 206) "Building Blocks" 24.99
:item/category "Toys")
(seed/new-invoice "invoice-1" date-1 "<NAME>"
[(seed/new-line-item "Doll" 1 5.0M)
(seed/new-line-item "Hammer" 1 14.99M)])
(seed/new-invoice "invoice-2" date-2 "<NAME>"
[(seed/new-line-item "Wrench" 1 12.50M)
(seed/new-line-item "Widget" 2 32.0M)])
(seed/new-invoice "invoice-3" date-3 "<NAME>"
[(seed/new-line-item "Wrench" 2 12.50M)
(seed/new-line-item "Hammer" 2 12.50M)])
(seed/new-invoice "invoice-4" date-4 "<NAME>"
[(seed/new-line-item "Robot" 6 89.99M)])
(seed/new-invoice "invoice-5" date-5 "<NAME>"
[(seed/new-line-item "Building Blocks" 10 20.0M)])]))))
(defn start []
(mount/start-with-args {:config "config/dev.edn"})
(seed!)
:ok)
(defn stop
"Stop the server."
[]
(mount/stop))
(def go start)
(defn restart
"Stop, refresh, and restart the server."
[]
(stop)
(tools-ns/refresh :after 'development/start))
(def reset #'restart)
| true | (ns development
(:require
[clojure.pprint :refer [pprint]]
[clojure.repl :refer [doc source]]
[clojure.tools.namespace.repl :as tools-ns :refer [disable-reload! refresh clear set-refresh-dirs]]
[com.example.components.datomic :refer [datomic-connections]]
[com.example.components.ring-middleware]
[com.example.components.server]
[com.example.model.seed :as seed]
[com.example.model.account :as account]
[com.example.model.address :as address]
[com.fulcrologic.rad.ids :refer [new-uuid]]
[com.fulcrologic.rad.database-adapters.datomic :as datomic]
[com.fulcrologic.rad.resolvers :as res]
[mount.core :as mount]
[taoensso.timbre :as log]
[datomic.api :as d]
[com.fulcrologic.rad.attributes :as attr]
[com.fulcrologic.rad.type-support.date-time :as dt]))
(set-refresh-dirs "src/main" "src/datomic" "src/dev" "src/shared" "../fulcro-rad-datomic/src/main" "../fulcro-rad/src/main")
(comment
(let [db (d/db (:main datomic-connections))]
(d/pull db '[*] [:account/id (new-uuid 100)])))
(defn seed! []
(dt/set-timezone! "America/Los_Angeles")
(let [connection (:main datomic-connections)
date-1 (dt/html-datetime-string->inst "2020-01-01T12:00")
date-2 (dt/html-datetime-string->inst "2020-01-05T12:00")
date-3 (dt/html-datetime-string->inst "2020-02-01T12:00")
date-4 (dt/html-datetime-string->inst "2020-03-10T12:00")
date-5 (dt/html-datetime-string->inst "2020-03-21T12:00")]
(when connection
(log/info "SEEDING data.")
@(d/transact connection [(seed/new-address (new-uuid 1) "111 Main St.")
(seed/new-account (new-uuid 100) "PI:NAME:<NAME>END_PI" "PI:EMAIL:<EMAIL>END_PI" "letmein"
:account/addresses ["111 Main St."]
:account/primary-address (seed/new-address (new-uuid 300) "222 Other")
:time-zone/zone-id :time-zone.zone-id/America-Los_Angeles)
(seed/new-account (new-uuid 101) "PI:NAME:<NAME>END_PI" "PI:EMAIL:<EMAIL>END_PI" "letmein")
(seed/new-account (new-uuid 102) "PI:NAME:<NAME>END_PI" "PI:EMAIL:<EMAIL>END_PI" "letmein")
(seed/new-account (new-uuid 103) "PI:NAME:<NAME>END_PI" "PI:EMAIL:<EMAIL>END_PI" "letmein")
(seed/new-category (new-uuid 1000) "Tools")
(seed/new-category (new-uuid 1002) "Toys")
(seed/new-category (new-uuid 1003) "Misc")
(seed/new-item (new-uuid 200) "Widget" 33.99
:item/category "Misc")
(seed/new-item (new-uuid 201) "Screwdriver" 4.99
:item/category "Tools")
(seed/new-item (new-uuid 202) "Wrench" 14.99
:item/category "Tools")
(seed/new-item (new-uuid 203) "Hammer" 14.99
:item/category "Tools")
(seed/new-item (new-uuid 204) "Doll" 4.99
:item/category "Toys")
(seed/new-item (new-uuid 205) "Robot" 94.99
:item/category "Toys")
(seed/new-item (new-uuid 206) "Building Blocks" 24.99
:item/category "Toys")
(seed/new-invoice "invoice-1" date-1 "PI:NAME:<NAME>END_PI"
[(seed/new-line-item "Doll" 1 5.0M)
(seed/new-line-item "Hammer" 1 14.99M)])
(seed/new-invoice "invoice-2" date-2 "PI:NAME:<NAME>END_PI"
[(seed/new-line-item "Wrench" 1 12.50M)
(seed/new-line-item "Widget" 2 32.0M)])
(seed/new-invoice "invoice-3" date-3 "PI:NAME:<NAME>END_PI"
[(seed/new-line-item "Wrench" 2 12.50M)
(seed/new-line-item "Hammer" 2 12.50M)])
(seed/new-invoice "invoice-4" date-4 "PI:NAME:<NAME>END_PI"
[(seed/new-line-item "Robot" 6 89.99M)])
(seed/new-invoice "invoice-5" date-5 "PI:NAME:<NAME>END_PI"
[(seed/new-line-item "Building Blocks" 10 20.0M)])]))))
(defn start []
(mount/start-with-args {:config "config/dev.edn"})
(seed!)
:ok)
(defn stop
"Stop the server."
[]
(mount/stop))
(def go start)
(defn restart
"Stop, refresh, and restart the server."
[]
(stop)
(tools-ns/refresh :after 'development/start))
(def reset #'restart)
|
[
{
"context": ";\n; Copyright © 2021 Peter Monks\n;\n; Licensed under the Apache License, Version 2.",
"end": 32,
"score": 0.9995422959327698,
"start": 21,
"tag": "NAME",
"value": "Peter Monks"
}
] | src/futbot/quizzes.clj | pmonks/futbot | 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 futbot.quizzes
(:require [clojure.tools.logging :as log]
[java-time :as tm]
[futbot.message-util :as mu]
[futbot.source.dutch-referee-blog :as drb]
[futbot.source.cnra :as cnra]))
(defn check-for-new-dutch-referee-blog-quiz-and-post!
"Checks whether a new Dutch referee blog quiz has been posted in the last time-period-hours hours (defaults to 24), and posts it to the given channel if so."
([config] (check-for-new-dutch-referee-blog-quiz-and-post! config 24))
([{:keys [discord-message-channel education-and-resources-channel-id quiz-channel-id]}
time-period-hours]
(if-let [new-quizzes (drb/quizzes (tm/minus (tm/instant) (tm/hours time-period-hours)))]
(let [_ (log/info (str (count new-quizzes) " new Dutch referee blog quizz(es) found"))
message (str "<:dfb:753779768306040863> A new **Dutch Referee Blog Laws of the Game Quiz** has been posted: "
(:link (first new-quizzes))
"\nPuzzled by an answer? Click the react and we'll discuss in " (mu/channel-link education-and-resources-channel-id) "!")
message-id (:id (mu/create-message! discord-message-channel
quiz-channel-id
:content message))]
(if message-id
(do
(mu/create-reaction! discord-message-channel quiz-channel-id message-id "1️⃣")
(mu/create-reaction! discord-message-channel quiz-channel-id message-id "2️⃣")
(mu/create-reaction! discord-message-channel quiz-channel-id message-id "3️⃣")
(mu/create-reaction! discord-message-channel quiz-channel-id message-id "4️⃣")
(mu/create-reaction! discord-message-channel quiz-channel-id message-id "5️⃣"))
(log/warn "No message id found for Dutch referee blog message - skipped adding reactions"))
nil)
(log/info "No new Dutch referee blog quizzes found"))))
(defn check-for-new-cnra-quiz-and-post!
"Checks whether any new CNRA quizzes has been posted in the last month, and posts them to the given channel if so."
[{:keys [discord-message-channel quiz-channel-id education-and-resources-channel-id]}]
(if-let [new-quizzes (cnra/quizzes (tm/minus (tm/local-date) (tm/months 1)))]
(doall
(map (fn [quiz]
(let [message (str "<:cnra:769311341751959562> The **"
(:quiz-date quiz)
" CNRA Quiz** has been posted, on the topic of **"
(:topic quiz)
"**: "
(:link quiz)
"\nPuzzled by an answer? React and we'll discuss in " education-and-resources-channel-id ".")]
(mu/create-message! discord-message-channel
quiz-channel-id
:content message)))
new-quizzes))
(log/info "No new CNRA quizzes found")))
| 90665 | ;
; 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 futbot.quizzes
(:require [clojure.tools.logging :as log]
[java-time :as tm]
[futbot.message-util :as mu]
[futbot.source.dutch-referee-blog :as drb]
[futbot.source.cnra :as cnra]))
(defn check-for-new-dutch-referee-blog-quiz-and-post!
"Checks whether a new Dutch referee blog quiz has been posted in the last time-period-hours hours (defaults to 24), and posts it to the given channel if so."
([config] (check-for-new-dutch-referee-blog-quiz-and-post! config 24))
([{:keys [discord-message-channel education-and-resources-channel-id quiz-channel-id]}
time-period-hours]
(if-let [new-quizzes (drb/quizzes (tm/minus (tm/instant) (tm/hours time-period-hours)))]
(let [_ (log/info (str (count new-quizzes) " new Dutch referee blog quizz(es) found"))
message (str "<:dfb:753779768306040863> A new **Dutch Referee Blog Laws of the Game Quiz** has been posted: "
(:link (first new-quizzes))
"\nPuzzled by an answer? Click the react and we'll discuss in " (mu/channel-link education-and-resources-channel-id) "!")
message-id (:id (mu/create-message! discord-message-channel
quiz-channel-id
:content message))]
(if message-id
(do
(mu/create-reaction! discord-message-channel quiz-channel-id message-id "1️⃣")
(mu/create-reaction! discord-message-channel quiz-channel-id message-id "2️⃣")
(mu/create-reaction! discord-message-channel quiz-channel-id message-id "3️⃣")
(mu/create-reaction! discord-message-channel quiz-channel-id message-id "4️⃣")
(mu/create-reaction! discord-message-channel quiz-channel-id message-id "5️⃣"))
(log/warn "No message id found for Dutch referee blog message - skipped adding reactions"))
nil)
(log/info "No new Dutch referee blog quizzes found"))))
(defn check-for-new-cnra-quiz-and-post!
"Checks whether any new CNRA quizzes has been posted in the last month, and posts them to the given channel if so."
[{:keys [discord-message-channel quiz-channel-id education-and-resources-channel-id]}]
(if-let [new-quizzes (cnra/quizzes (tm/minus (tm/local-date) (tm/months 1)))]
(doall
(map (fn [quiz]
(let [message (str "<:cnra:769311341751959562> The **"
(:quiz-date quiz)
" CNRA Quiz** has been posted, on the topic of **"
(:topic quiz)
"**: "
(:link quiz)
"\nPuzzled by an answer? React and we'll discuss in " education-and-resources-channel-id ".")]
(mu/create-message! discord-message-channel
quiz-channel-id
:content message)))
new-quizzes))
(log/info "No new CNRA quizzes found")))
| 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 futbot.quizzes
(:require [clojure.tools.logging :as log]
[java-time :as tm]
[futbot.message-util :as mu]
[futbot.source.dutch-referee-blog :as drb]
[futbot.source.cnra :as cnra]))
(defn check-for-new-dutch-referee-blog-quiz-and-post!
"Checks whether a new Dutch referee blog quiz has been posted in the last time-period-hours hours (defaults to 24), and posts it to the given channel if so."
([config] (check-for-new-dutch-referee-blog-quiz-and-post! config 24))
([{:keys [discord-message-channel education-and-resources-channel-id quiz-channel-id]}
time-period-hours]
(if-let [new-quizzes (drb/quizzes (tm/minus (tm/instant) (tm/hours time-period-hours)))]
(let [_ (log/info (str (count new-quizzes) " new Dutch referee blog quizz(es) found"))
message (str "<:dfb:753779768306040863> A new **Dutch Referee Blog Laws of the Game Quiz** has been posted: "
(:link (first new-quizzes))
"\nPuzzled by an answer? Click the react and we'll discuss in " (mu/channel-link education-and-resources-channel-id) "!")
message-id (:id (mu/create-message! discord-message-channel
quiz-channel-id
:content message))]
(if message-id
(do
(mu/create-reaction! discord-message-channel quiz-channel-id message-id "1️⃣")
(mu/create-reaction! discord-message-channel quiz-channel-id message-id "2️⃣")
(mu/create-reaction! discord-message-channel quiz-channel-id message-id "3️⃣")
(mu/create-reaction! discord-message-channel quiz-channel-id message-id "4️⃣")
(mu/create-reaction! discord-message-channel quiz-channel-id message-id "5️⃣"))
(log/warn "No message id found for Dutch referee blog message - skipped adding reactions"))
nil)
(log/info "No new Dutch referee blog quizzes found"))))
(defn check-for-new-cnra-quiz-and-post!
"Checks whether any new CNRA quizzes has been posted in the last month, and posts them to the given channel if so."
[{:keys [discord-message-channel quiz-channel-id education-and-resources-channel-id]}]
(if-let [new-quizzes (cnra/quizzes (tm/minus (tm/local-date) (tm/months 1)))]
(doall
(map (fn [quiz]
(let [message (str "<:cnra:769311341751959562> The **"
(:quiz-date quiz)
" CNRA Quiz** has been posted, on the topic of **"
(:topic quiz)
"**: "
(:link quiz)
"\nPuzzled by an answer? React and we'll discuss in " education-and-resources-channel-id ".")]
(mu/create-message! discord-message-channel
quiz-channel-id
:content message)))
new-quizzes))
(log/info "No new CNRA quizzes found")))
|
[
{
"context": "lojure\n;; docs in clojure/contrib/jmx.clj!!\n\n;; by Stuart Halloway\n\n;; Copyright (c) Stuart Halloway, 2009. All righ",
"end": 90,
"score": 0.9998773336410522,
"start": 75,
"tag": "NAME",
"value": "Stuart Halloway"
},
{
"context": "jmx.clj!!\n\n;; by Stuart Halloway\n\n;; Copyright (c) Stuart Halloway, 2009. All rights reserved. The use\n;; and distr",
"end": 124,
"score": 0.999879002571106,
"start": 109,
"tag": "NAME",
"value": "Stuart Halloway"
}
] | ThirdParty/clojure-contrib-1.1.0/src/clojure/contrib/jmx/client.clj | allertonm/Couverjure | 3 | ;; JMX client APIs for Clojure
;; docs in clojure/contrib/jmx.clj!!
;; by Stuart Halloway
;; Copyright (c) Stuart Halloway, 2009. All rights reserved. The use
;; and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
(in-ns 'clojure.contrib.jmx)
; TODO: needs an integration test
; TODO: why full package needed for JMXConnectorFactory?
(defmacro with-connection
"Execute body with JMX connection specified by opts (:port)."
[opts & body]
`(with-open [connector# (javax.management.remote.JMXConnectorFactory/connect
(JMXServiceURL. (jmx-url ~opts)) {})]
(binding [*connection* (.getMBeanServerConnection connector#)]
~@body)))
(defn mbean-info [n]
(.getMBeanInfo *connection* (as-object-name n)))
(defn raw-read
"Read an mbean property. Returns low-level Java object model for composites, tabulars, etc.
Most callers should use read."
[n attr]
(.getAttribute *connection* (as-object-name n) (as-str attr)))
(defvar read
(comp jmx->clj raw-read)
"Read an mbean property.")
(defvar read-exceptions
[UnsupportedOperationException
InternalError
java.io.NotSerializableException
java.lang.ClassNotFoundException
javax.management.AttributeNotFoundException]
"Exceptions that might be thrown if you try to read an unsupported attribute.
by testing agains jconsole and Tomcat. This is dreadful and ad-hoc but I did not
want to swallow all exceptions.")
(defn read-supported
"Calls read to read an mbean property, *returning* unsupported operation exceptions instead of throwing them.
Used to keep mbean from blowing up. Note that some terribly-behaved mbeans use java.lang.InternalError to
indicate an unsupported operation!"
[n attr]
(try
(read n attr)
(catch Throwable t
(let [cause (root-cause t)]
(if (some #(instance? % cause) read-exceptions)
cause
(throw t))))))
(defn write! [n attr value]
(.setAttribute
*connection*
(as-object-name n)
(Attribute. (as-str attr) value)))
(defn attribute-info
"Get the MBeanAttributeInfo for an attribute"
[object-name attr-name]
(filter #(= (as-str attr-name) (.getName %))
(.getAttributes (mbean-info object-name))))
(defn readable?
"Is attribute readable?"
[n attr]
(.isReadable () (mbean-info n)))
(defn operations
"All oeprations available on an MBean."
[n]
(.getOperations (mbean-info n)))
(defn operation
"The MBeanOperationInfo for operation op on mbean n. Used for invoke."
[n op]
(first (filter #(= (-> % .getName keyword) op) (operations n))))
(defn op-param-types
"The parameter types (as class name strings) for operation op on n. Used for invoke."
[n op]
(map #(-> % .getType) (.getSignature (operation n op))))
| 49936 | ;; JMX client APIs for Clojure
;; docs in clojure/contrib/jmx.clj!!
;; by <NAME>
;; Copyright (c) <NAME>, 2009. All rights reserved. The use
;; and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
(in-ns 'clojure.contrib.jmx)
; TODO: needs an integration test
; TODO: why full package needed for JMXConnectorFactory?
(defmacro with-connection
"Execute body with JMX connection specified by opts (:port)."
[opts & body]
`(with-open [connector# (javax.management.remote.JMXConnectorFactory/connect
(JMXServiceURL. (jmx-url ~opts)) {})]
(binding [*connection* (.getMBeanServerConnection connector#)]
~@body)))
(defn mbean-info [n]
(.getMBeanInfo *connection* (as-object-name n)))
(defn raw-read
"Read an mbean property. Returns low-level Java object model for composites, tabulars, etc.
Most callers should use read."
[n attr]
(.getAttribute *connection* (as-object-name n) (as-str attr)))
(defvar read
(comp jmx->clj raw-read)
"Read an mbean property.")
(defvar read-exceptions
[UnsupportedOperationException
InternalError
java.io.NotSerializableException
java.lang.ClassNotFoundException
javax.management.AttributeNotFoundException]
"Exceptions that might be thrown if you try to read an unsupported attribute.
by testing agains jconsole and Tomcat. This is dreadful and ad-hoc but I did not
want to swallow all exceptions.")
(defn read-supported
"Calls read to read an mbean property, *returning* unsupported operation exceptions instead of throwing them.
Used to keep mbean from blowing up. Note that some terribly-behaved mbeans use java.lang.InternalError to
indicate an unsupported operation!"
[n attr]
(try
(read n attr)
(catch Throwable t
(let [cause (root-cause t)]
(if (some #(instance? % cause) read-exceptions)
cause
(throw t))))))
(defn write! [n attr value]
(.setAttribute
*connection*
(as-object-name n)
(Attribute. (as-str attr) value)))
(defn attribute-info
"Get the MBeanAttributeInfo for an attribute"
[object-name attr-name]
(filter #(= (as-str attr-name) (.getName %))
(.getAttributes (mbean-info object-name))))
(defn readable?
"Is attribute readable?"
[n attr]
(.isReadable () (mbean-info n)))
(defn operations
"All oeprations available on an MBean."
[n]
(.getOperations (mbean-info n)))
(defn operation
"The MBeanOperationInfo for operation op on mbean n. Used for invoke."
[n op]
(first (filter #(= (-> % .getName keyword) op) (operations n))))
(defn op-param-types
"The parameter types (as class name strings) for operation op on n. Used for invoke."
[n op]
(map #(-> % .getType) (.getSignature (operation n op))))
| true | ;; JMX client APIs for Clojure
;; docs in clojure/contrib/jmx.clj!!
;; by PI:NAME:<NAME>END_PI
;; Copyright (c) PI:NAME:<NAME>END_PI, 2009. All rights reserved. The use
;; and distribution terms for this software are covered by the Eclipse
;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
;; which can be found in the file epl-v10.html at the root of this
;; distribution. By using this software in any fashion, you are
;; agreeing to be bound by the terms of this license. You must not
;; remove this notice, or any other, from this software.
(in-ns 'clojure.contrib.jmx)
; TODO: needs an integration test
; TODO: why full package needed for JMXConnectorFactory?
(defmacro with-connection
"Execute body with JMX connection specified by opts (:port)."
[opts & body]
`(with-open [connector# (javax.management.remote.JMXConnectorFactory/connect
(JMXServiceURL. (jmx-url ~opts)) {})]
(binding [*connection* (.getMBeanServerConnection connector#)]
~@body)))
(defn mbean-info [n]
(.getMBeanInfo *connection* (as-object-name n)))
(defn raw-read
"Read an mbean property. Returns low-level Java object model for composites, tabulars, etc.
Most callers should use read."
[n attr]
(.getAttribute *connection* (as-object-name n) (as-str attr)))
(defvar read
(comp jmx->clj raw-read)
"Read an mbean property.")
(defvar read-exceptions
[UnsupportedOperationException
InternalError
java.io.NotSerializableException
java.lang.ClassNotFoundException
javax.management.AttributeNotFoundException]
"Exceptions that might be thrown if you try to read an unsupported attribute.
by testing agains jconsole and Tomcat. This is dreadful and ad-hoc but I did not
want to swallow all exceptions.")
(defn read-supported
"Calls read to read an mbean property, *returning* unsupported operation exceptions instead of throwing them.
Used to keep mbean from blowing up. Note that some terribly-behaved mbeans use java.lang.InternalError to
indicate an unsupported operation!"
[n attr]
(try
(read n attr)
(catch Throwable t
(let [cause (root-cause t)]
(if (some #(instance? % cause) read-exceptions)
cause
(throw t))))))
(defn write! [n attr value]
(.setAttribute
*connection*
(as-object-name n)
(Attribute. (as-str attr) value)))
(defn attribute-info
"Get the MBeanAttributeInfo for an attribute"
[object-name attr-name]
(filter #(= (as-str attr-name) (.getName %))
(.getAttributes (mbean-info object-name))))
(defn readable?
"Is attribute readable?"
[n attr]
(.isReadable () (mbean-info n)))
(defn operations
"All oeprations available on an MBean."
[n]
(.getOperations (mbean-info n)))
(defn operation
"The MBeanOperationInfo for operation op on mbean n. Used for invoke."
[n op]
(first (filter #(= (-> % .getName keyword) op) (operations n))))
(defn op-param-types
"The parameter types (as class name strings) for operation op on n. Used for invoke."
[n op]
(map #(-> % .getType) (.getSignature (operation n op))))
|
[
{
"context": "ite-authenticator? waiter-url)\n (let [token (rand-name)\n response (post-token waiter-url (dis",
"end": 628,
"score": 0.6995441913604736,
"start": 619,
"tag": "KEY",
"value": "rand-name"
},
{
"context": " \"'\")]\n (let [token (rand-name)\n {:keys [body] :as response} (post-",
"end": 2407,
"score": 0.5375205278396606,
"start": 2403,
"tag": "KEY",
"value": "name"
},
{
"context": "ludes? body error-message)))\n (let [token (rand-name)\n {:keys [body] :as response} (post-",
"end": 3086,
"score": 0.6558275818824768,
"start": 3077,
"tag": "KEY",
"value": "rand-name"
},
{
"context": "ml-authentication? waiter-url)\n (let [token (rand-name)\n response (post-token waiter-url (-> ",
"end": 4948,
"score": 0.6198908686637878,
"start": 4939,
"tag": "KEY",
"value": "rand-name"
},
{
"context": "\n (when use-spnego\n (let [{:keys [allow-bearer-auth-api? attach-www-authenticate-on-missing-bearer-token?]",
"end": 13969,
"score": 0.887351393699646,
"start": 13947,
"tag": "KEY",
"value": "allow-bearer-auth-api?"
},
{
"context": "ego\n (let [{:keys [allow-bearer-auth-api? attach-www-authenticate-on-missing-bearer-token?]\n :or {allow-bearer-auth-api? tru",
"end": 14018,
"score": 0.8471881151199341,
"start": 13970,
"tag": "KEY",
"value": "attach-www-authenticate-on-missing-bearer-token?"
}
] | waiter/integration/waiter/authentication_test.clj | pandashadopan/waiter | 0 | (ns waiter.authentication-test
(:require [clj-time.core :as t]
[clojure.data.json :as json]
[clojure.string :as str]
[clojure.test :refer :all]
[clojure.tools.logging :as log]
[reaver :as reaver]
[waiter.status-codes :refer :all]
[waiter.util.client-tools :refer :all]
[waiter.util.utils :as utils])
(:import (java.net URI URL URLEncoder)))
(deftest ^:parallel ^:integration-fast test-default-composite-authenticator
(testing-using-waiter-url
(when (using-composite-authenticator? waiter-url)
(let [token (rand-name)
response (post-token waiter-url (dissoc (assoc (kitchen-params)
:name token
:permitted-user "*"
:run-as-user (retrieve-username)
:token token)
:authentication))]
(try
(assert-response-status response http-200-ok)
(let [{:keys [service-id body]} (make-request-with-debug-info
{:x-waiter-token token}
#(make-kitchen-request waiter-url % :path "/request-info"))
body-json (json/read-str (str body))]
(with-service-cleanup
service-id
(is (= (retrieve-username) (get-in body-json ["headers" "x-waiter-auth-principal"])))))
(finally
(delete-token-and-assert waiter-url token)))))))
(deftest ^:parallel ^:integration-fast test-token-authentication-parameter-error
(testing-using-waiter-url
(when (using-composite-authenticator? waiter-url)
(let [authentication-providers (-> waiter-url
waiter-settings
(get-in [:authenticator-config :composite :authentication-providers])
keys
(->> (map name)))
error-message (str "authentication must be one of: '"
(str/join "', '" (sort (into #{"disabled" "standard"} authentication-providers)))
"'")]
(let [token (rand-name)
{:keys [body] :as response} (post-token waiter-url (assoc (kitchen-params)
:authentication "invalid"
:name token
:permitted-user "*"
:run-as-user (retrieve-username)
:token token))]
(assert-response-status response http-400-bad-request)
(is (str/includes? body error-message)))
(let [token (rand-name)
{:keys [body] :as response} (post-token waiter-url (assoc (kitchen-params)
:authentication ""
:name token
:permitted-user "*"
:run-as-user (retrieve-username)
:token token))]
(assert-response-status response http-400-bad-request)
(is (str/includes? body error-message)))))))
(defn- perform-saml-authentication
"Perform authentication with an identity provider service.
Return map of waiter acs endpoint, saml-response and relay-state"
[saml-redirect-location]
(let [make-connection (fn [request-url]
(let [http-connection (.openConnection (URL. request-url))]
(.setDoOutput http-connection false)
(.setDoInput http-connection true)
(.setRequestMethod http-connection "GET")
(.connect http-connection)
http-connection))
conn (make-connection saml-redirect-location)]
(is (= http-200-ok (.getResponseCode conn)))
(reaver/extract (reaver/parse (slurp (.getInputStream conn))) [:waiter-saml-acs-endpoint :saml-response :relay-state]
"form" (reaver/attr :action)
"form input[name=SAMLResponse]" (reaver/attr :value)
"form input[name=RelayState]" (reaver/attr :value))))
(deftest ^:parallel ^:integration-fast test-saml-authentication
(testing-using-waiter-url
(when (supports-saml-authentication? waiter-url)
(let [token (rand-name)
response (post-token waiter-url (-> (kitchen-params)
(assoc
:authentication "saml"
:name token
:permitted-user "*"
:run-as-user (retrieve-username)
:token token)))]
(assert-response-status response http-200-ok)
(try
(let [{:keys [headers] :as response} (make-request waiter-url "/request-info" :headers {:x-waiter-token token})
_ (assert-response-status response http-302-moved-temporarily)
saml-redirect-location (get headers "location")
{:keys [relay-state saml-response waiter-saml-acs-endpoint]} (perform-saml-authentication saml-redirect-location)
{:keys [body] :as response} (make-request waiter-saml-acs-endpoint ""
:body (str "SAMLResponse=" (URLEncoder/encode saml-response)
"&RelayState=" (URLEncoder/encode relay-state))
:headers {"content-type" "application/x-www-form-urlencoded"}
:method :post)
_ (assert-response-status response http-200-ok)
{:keys [waiter-saml-auth-redirect-endpoint saml-auth-data]}
(reaver/extract (reaver/parse body) [:waiter-saml-auth-redirect-endpoint :saml-auth-data]
"form" (reaver/attr :action)
"form input[name=saml-auth-data]" (reaver/attr :value))
_ (is (= (str "http://" waiter-url "/waiter-auth/saml/auth-redirect") waiter-saml-auth-redirect-endpoint))
{:keys [cookies headers] :as response} (make-request waiter-url "/waiter-auth/saml/auth-redirect"
:body (str "saml-auth-data=" (URLEncoder/encode saml-auth-data))
:headers {"content-type" "application/x-www-form-urlencoded"}
:method :post)
_ (assert-response-status response http-303-see-other)
cookie-fn (fn [cookies name] (some #(when (= name (:name %)) %) cookies))
auth-cookie (cookie-fn cookies "x-waiter-auth")
_ (is (not (nil? auth-cookie)))
_ (is (> (:max-age auth-cookie) (-> 1 t/hours t/in-seconds)))
_ (is (= (str "http://" waiter-url "/request-info") (get headers "location")))
{:keys [body service-id] :as response} (make-request-with-debug-info
{:x-waiter-token token}
#(make-request waiter-url "/request-info" :headers % :cookies cookies))
_ (assert-response-status response http-200-ok)
body-json (json/read-str (str body))]
(with-service-cleanup
service-id
(is (= (retrieve-username) (get-in body-json ["headers" "x-waiter-auth-principal"])))))
(finally
(delete-token-and-assert waiter-url token)))))))
(defn- retrieve-access-token
[realm]
(if-let [access-token-url-env (System/getenv "WAITER_TEST_JWT_ACCESS_TOKEN_URL")]
(let [access-token-url (str/replace access-token-url-env "{HOST}" realm)
access-token-uri (URI. access-token-url)
protocol (.getScheme access-token-uri)
authority (.getAuthority access-token-uri)
path (str (.getPath access-token-uri) "?" (.getQuery access-token-uri))
access-token-response (make-request authority path :headers {"x-iam" "waiter"} :protocol protocol)
_ (assert-response-status access-token-response http-200-ok)
access-token-response-json (-> access-token-response :body str json/read-str)
access-token (get access-token-response-json "access_token")]
(log/info "retrieved access token" {:access-token access-token :realm realm})
access-token)
(throw (ex-info "WAITER_TEST_JWT_ACCESS_TOKEN_URL environment variable has not been provided" {}))))
(defmacro assert-auth-cookie
"Helper macro to assert the value of the set-cookie header."
[set-cookie assertion-message]
`(let [set-cookie# ~set-cookie
assertion-message# ~assertion-message]
(is (str/includes? set-cookie# "x-waiter-auth=") assertion-message#)
(is (str/includes? set-cookie# "Max-Age=") assertion-message#)
(is (str/includes? set-cookie# "Path=/") assertion-message#)
(is (str/includes? set-cookie# "HttpOnly=true") assertion-message#)))
;; Test disabled because JWT support is, currently, only for tokens
(deftest ^:parallel ^:integration-fast ^:explicit test-successful-jwt-authentication-waiter-realm
(testing-using-waiter-url
(if (jwt-auth-enabled? waiter-url)
(let [waiter-host (-> waiter-url sanitize-waiter-url utils/authority->host)
access-token (retrieve-access-token waiter-host)
request-headers {"authorization" (str "Bearer " access-token)
"host" waiter-host
"x-forwarded-proto" "https"}
port (waiter-settings-port waiter-url)
target-url (str waiter-host ":" port)
{:keys [body headers] :as response}
(make-request target-url "/waiter-auth" :disable-auth true :headers request-headers :method :get)
set-cookie (str (get headers "set-cookie"))
assertion-message (str {:headers headers
:set-cookie set-cookie
:target-url target-url})]
(assert-response-status response http-200-ok)
(is (= (retrieve-username) (str body)))
(is (= "jwt" (get headers "x-waiter-auth-method")) assertion-message)
(is (= (retrieve-username) (get headers "x-waiter-auth-user")) assertion-message)
(assert-auth-cookie set-cookie assertion-message))
(log/info "JWT authentication is disabled"))))
;; Test disabled because JWT support is, currently, only for tokens
(deftest ^:parallel ^:integration-fast ^:explicit test-forbidden-jwt-authentication-waiter-realm
(testing-using-waiter-url
(if (jwt-auth-enabled? waiter-url)
(let [waiter-host (-> waiter-url sanitize-waiter-url utils/authority->host)
access-token (retrieve-access-token waiter-host)
request-headers {"authorization" (str "Bearer " access-token)
"host" waiter-host
"x-forwarded-proto" "http"}
port (waiter-settings-port waiter-url)
target-url (str waiter-host ":" port)
{:keys [body headers] :as response}
(make-request target-url "/waiter-auth" :disable-auth true :headers request-headers :method :get)
set-cookie (str (get headers "set-cookie"))
assertion-message (str {:headers headers
:target-url target-url})]
(assert-response-status response http-403-forbidden)
(is (str/includes? (str body) "Must use HTTPS connection") assertion-message)
(is (str/blank? set-cookie) assertion-message))
(log/info "JWT authentication is disabled"))))
(deftest ^:parallel ^:integration-fast test-forbidden-authentication-with-bad-jwt-token-waiter-realm
(testing-using-waiter-url
(if (jwt-auth-enabled? waiter-url)
(let [waiter-host (-> waiter-url sanitize-waiter-url utils/authority->host)
port (waiter-settings-port waiter-url)
target-url (str waiter-host ":" port)]
(let [access-token (str (retrieve-access-token waiter-host) "invalid")
request-headers {"authorization" [(str "Bearer " access-token)
(str "Negotiate bad-token")
(str "SingleUser forbidden")]
"host" waiter-host
"x-forwarded-proto" "https"}
{:keys [headers] :as response}
(make-request target-url "/waiter-auth" :disable-auth true :headers request-headers :method :get)
set-cookie (str (get headers "set-cookie"))
assertion-message (str (select-keys response [:body :error :headers :status]))]
(assert-response-status response http-403-forbidden)
(is (str/blank? (get headers "www-authenticate")) assertion-message)
(is (str/blank? set-cookie) assertion-message))
(when use-spnego
(let [{:keys [allow-bearer-auth-api? attach-www-authenticate-on-missing-bearer-token?]
:or {allow-bearer-auth-api? true
attach-www-authenticate-on-missing-bearer-token? true}}
(setting waiter-url [:authenticator-config :jwt])
request-headers {"host" waiter-host
"x-forwarded-proto" "https"}
{:keys [headers] :as response}
(make-request target-url "/waiter-auth" :disable-auth true :headers request-headers :method :get)
set-cookie (str (get headers "set-cookie"))
assertion-message (str (select-keys response [:body :error :headers :status]))]
(assert-response-status response http-401-unauthorized)
(is (get headers "www-authenticate") assertion-message)
(when (and allow-bearer-auth-api? attach-www-authenticate-on-missing-bearer-token?)
(is (str/includes? (str (get headers "www-authenticate")) "Bearer") assertion-message))
(is (str/blank? set-cookie) assertion-message))))
(log/info "JWT authentication is disabled"))))
;; Test disabled because JWT support is, currently, only for tokens
(deftest ^:parallel ^:integration-fast ^:explicit test-unauthorized-jwt-authentication-waiter-realm
(testing-using-waiter-url
(if (jwt-auth-enabled? waiter-url)
(let [waiter-host (-> waiter-url sanitize-waiter-url utils/authority->host)
access-token (str (retrieve-access-token waiter-host) "invalid")
request-headers {"authorization" [(str "Bearer " access-token)
;; absence of Negotiate header also trigger an unauthorized response
(str "SingleUser unauthorized")]
"host" waiter-host
"x-forwarded-proto" "https"}
port (waiter-settings-port waiter-url)
target-url (str waiter-host ":" port)
{:keys [headers] :as response}
(make-request target-url "/waiter-auth" :disable-auth true :headers request-headers :method :get)
set-cookie (str (get headers "set-cookie"))
assertion-message (str (select-keys response [:body :error :headers :status]))]
(assert-response-status response http-401-unauthorized)
(is (str/blank? set-cookie) assertion-message)
(if-let [challenge (get headers "www-authenticate")]
(do
(is (str/includes? (str challenge) "Bearer realm"))
(is (> (count (str/split challenge #",")) 1) assertion-message))
(is false (str "www-authenticate header missing: " assertion-message))))
(log/info "JWT authentication is disabled"))))
(deftest ^:parallel ^:integration-fast test-fallback-to-alternate-auth-on-invalid-jwt-token-waiter-realm
(testing-using-waiter-url
(if (jwt-auth-enabled? waiter-url)
(let [waiter-host (-> waiter-url sanitize-waiter-url utils/authority->host)
access-token (str (retrieve-access-token waiter-host) "invalid")
request-headers {"authorization" (str "Bearer " access-token)
"host" waiter-host
"x-forwarded-proto" "https"}
port (waiter-settings-port waiter-url)
target-url (str waiter-host ":" port)
{:keys [body headers] :as response}
(make-request target-url "/waiter-auth" :headers request-headers :method :get)
set-cookie (str (get headers "set-cookie"))
assertion-message (str {:headers headers
:set-cookie set-cookie
:target-url target-url})]
(assert-response-status response http-200-ok)
(is (= (retrieve-username) (str body)))
(let [{:strs [x-waiter-auth-method]} headers]
(is (not= "jwt" x-waiter-auth-method) assertion-message)
(is (not (str/blank? x-waiter-auth-method)) assertion-message))
(is (= (retrieve-username) (get headers "x-waiter-auth-user")) assertion-message)
(assert-auth-cookie set-cookie assertion-message))
(log/info "JWT authentication is disabled"))))
(defn- create-token-name
[waiter-url service-id-prefix]
(str service-id-prefix "." (subs waiter-url 0 (str/index-of waiter-url ":"))))
(defn- validate-response
[service-id access-token auth-method {:keys [body headers] :as response}]
(let [assertion-message (str {:auth-method auth-method
:body body
:headers headers
:jwt-access-token access-token
:service-id service-id})
set-cookie (str (get headers "set-cookie"))]
(assert-response-status response http-200-ok)
(is (= auth-method (get headers "x-waiter-auth-method")) assertion-message)
(is (= (retrieve-username) (get headers "x-waiter-auth-user")) assertion-message)
(when-not (= auth-method "cookie")
(assert-auth-cookie set-cookie assertion-message))
(let [body-json (try-parse-json body)]
(is (= access-token (get-in body-json ["headers" "x-waiter-jwt"])) assertion-message))))
(deftest ^:parallel ^:integration-fast test-jwt-authentication-token-realm
(testing-using-waiter-url
(if (jwt-auth-enabled? waiter-url)
(let [waiter-host (-> waiter-url sanitize-waiter-url utils/authority->host)
host (create-token-name waiter-url (rand-name))
service-parameters (assoc (kitchen-params)
:env {"USE_BEARER_AUTH" "true"}
:name (rand-name))
token-response (post-token waiter-url (assoc service-parameters
:run-as-user (retrieve-username)
"token" host))
_ (assert-response-status token-response http-200-ok)
access-token (retrieve-access-token host)
request-headers {"authorization" (str "Bearer " access-token)
"host" host
"x-forwarded-proto" "https"}
port (waiter-settings-port waiter-url)
target-url (str waiter-host ":" port)
{:keys [cookies request-headers service-id] :as response}
(make-request-with-debug-info
request-headers
#(make-request target-url "/request-info" :disable-auth true :headers % :method :get))]
(try
(with-service-cleanup
service-id
(validate-response service-id access-token "jwt" response)
(->> (make-request target-url "/request-info"
:cookies cookies
:disable-auth true
:headers (dissoc request-headers "authorization" "x-cid")
:method :get)
(validate-response service-id access-token "cookie")))
(finally
(delete-token-and-assert waiter-url host))))
(log/info "JWT authentication is disabled"))))
(deftest ^:parallel ^:integration-fast test-fallback-to-alternate-auth-on-invalid-jwt-token-token-realm
(testing-using-waiter-url
(if (jwt-auth-enabled? waiter-url)
(let [waiter-host (-> waiter-url sanitize-waiter-url utils/authority->host)
host (create-token-name waiter-url (rand-name))
service-parameters (assoc (kitchen-params)
:env {"USE_BEARER_AUTH" "true"}
:name (rand-name))
token-response (post-token waiter-url (assoc service-parameters
:run-as-user (retrieve-username)
"token" host))
_ (assert-response-status token-response http-200-ok)
access-token (str (retrieve-access-token host) "invalid")
request-headers {"authorization" (str "Bearer " access-token)
"host" host
"x-forwarded-proto" "https"}
port (waiter-settings-port waiter-url)
target-url (str waiter-host ":" port)
{:keys [headers service-id] :as response}
(make-request-with-debug-info
request-headers
#(make-request target-url "/status" :headers % :method :get))
set-cookie (str (get headers "set-cookie"))
assertion-message (str {:headers headers
:service-id service-id
:set-cookie set-cookie
:target-url target-url})]
(try
(with-service-cleanup
service-id
(assert-response-status response http-200-ok)
(let [{:strs [x-waiter-auth-method]} headers]
(is (not= "jwt" x-waiter-auth-method) assertion-message)
(is (not (str/blank? x-waiter-auth-method)) assertion-message))
(is (= (retrieve-username) (get headers "x-waiter-auth-user")) assertion-message)
(assert-auth-cookie set-cookie assertion-message))
(finally
(delete-token-and-assert waiter-url host))))
(log/info "JWT authentication is disabled"))))
(defmacro assert-oidc-challenge-cookie
"Helper macro to assert the value of x-waiter-oidc-challenge in the set-cookie header."
[set-cookie assertion-message]
`(let [set-cookie# ~set-cookie
assertion-message# ~assertion-message]
(is (str/includes? set-cookie# "x-waiter-oidc-challenge=") assertion-message#)
(is (str/includes? set-cookie# "Max-Age=") assertion-message#)
(is (str/includes? set-cookie# "Path=/") assertion-message#)
(is (str/includes? set-cookie# "HttpOnly=true") assertion-message#)))
(defn- follow-authorize-redirects
"Asserts for query parameters on the redirect url.
Then makes requests and follows redirects until the oidc callback url is returned as a redirect."
[authorize-redirect-location]
(is (str/includes? authorize-redirect-location "client_id="))
(is (str/includes? authorize-redirect-location "code_challenge="))
(is (str/includes? authorize-redirect-location "code_challenge_method="))
(is (str/includes? authorize-redirect-location "redirect_uri="))
(is (str/includes? authorize-redirect-location "response_type="))
(is (str/includes? authorize-redirect-location "scope="))
(is (str/includes? authorize-redirect-location "state="))
(loop [iteration 1
authorize-location authorize-redirect-location]
(log/info "redirecting to" authorize-location)
(let [authorize-uri (URI. authorize-location)
authorize-protocol (.getScheme authorize-uri)
authorize-authority (.getAuthority authorize-uri)
authorize-path (str (.getPath authorize-uri) "?" (.getQuery authorize-uri))
authorize-response (make-request authorize-authority authorize-path :protocol authorize-protocol)
_ (assert-response-status authorize-response #{http-301-moved-permanently
http-302-moved-temporarily
http-307-temporary-redirect
http-308-permanent-redirect})
assertion-message (str {:headers (:headers authorize-response)
:status (:status authorize-response)
:uri authorize-location})
{:strs [location]} (:headers authorize-response)]
(is (not (str/blank? location)) assertion-message)
(if (or (>= iteration 10)
(and (str/includes? location "/oidc/v1/callback?")
(str/includes? location "code=")
(str/includes? location "state=")))
location
(recur (inc iteration) location)))))
(deftest ^:parallel ^:integration-fast test-oidc-authentication-redirect
(testing-using-waiter-url
(if (oidc-auth-enabled? waiter-url)
(let [waiter-host (-> waiter-url sanitize-waiter-url utils/authority->host)
oidc-token-from-env (System/getenv "WAITER_TEST_TOKEN_OIDC")
edit-oidc-token-from-env? (Boolean/valueOf (System/getenv "WAITER_TEST_TOKEN_OIDC_EDIT"))
waiter-token (or oidc-token-from-env (create-token-name waiter-url (rand-name)))
edit-token? (or (str/blank? oidc-token-from-env) edit-oidc-token-from-env?)
_ (when edit-token?
(let [service-parameters (assoc (kitchen-params)
:env {"USE_OIDC_AUTH" "true"}
:name (rand-name)
:run-as-user (retrieve-username))
token-response (post-token waiter-url (assoc service-parameters :token waiter-token))]
(assert-response-status token-response http-200-ok)))
;; absence of Negotiate header also triggers an unauthorized response
request-headers {"authorization" "SingleUser unauthorized"
"accept-redirect" "yes"
"host" waiter-token
"x-forwarded-proto" "https"}
port (waiter-settings-port waiter-url)
target-url (str waiter-host ":" port)
{:keys [cookies] :as initial-response}
(make-request-with-debug-info
request-headers
#(make-request target-url "/request-info" :disable-auth true :headers % :method :get))]
(try
(assert-response-status initial-response http-302-moved-temporarily)
(let [{:strs [location set-cookie]} (:headers initial-response)
assertion-message (str {:headers (:headers initial-response)
:set-cookie set-cookie
:status (:status initial-response)})]
(is (not (str/blank? location)) assertion-message)
(assert-oidc-challenge-cookie set-cookie assertion-message)
(let [callback-location (follow-authorize-redirects location)]
(is (not (str/blank? callback-location)) assertion-message)
(is (str/includes? callback-location "/oidc/v1/callback?") assertion-message)
(let [callback-uri (URI. callback-location)
callback-path (str (.getPath callback-uri) "?" (.getRawQuery callback-uri))
callback-request-headers {"host" waiter-token
"x-forwarded-proto" "https"}
{:keys [cookies] :as callback-response}
(make-request target-url callback-path
:cookies cookies
:headers callback-request-headers)]
(assert-response-status callback-response http-302-moved-temporarily)
(is (= 2 (count cookies)))
(is (zero? (:max-age (first (filter #(= (:name %) "x-waiter-oidc-challenge") cookies)))))
(is (pos? (:max-age (first (filter #(= (:name %) "x-waiter-auth") cookies)))))
(let [{:strs [location]} (:headers callback-response)
assertion-message (str {:headers (:headers callback-response)
:status (:status callback-response)})]
(is (= (str "https://" waiter-token "/request-info") location) assertion-message)))))
(finally
(when edit-token?
(delete-token-and-assert waiter-url waiter-token)))))
(log/info "OIDC+PKCE authentication is disabled"))))
| 42563 | (ns waiter.authentication-test
(:require [clj-time.core :as t]
[clojure.data.json :as json]
[clojure.string :as str]
[clojure.test :refer :all]
[clojure.tools.logging :as log]
[reaver :as reaver]
[waiter.status-codes :refer :all]
[waiter.util.client-tools :refer :all]
[waiter.util.utils :as utils])
(:import (java.net URI URL URLEncoder)))
(deftest ^:parallel ^:integration-fast test-default-composite-authenticator
(testing-using-waiter-url
(when (using-composite-authenticator? waiter-url)
(let [token (<KEY>)
response (post-token waiter-url (dissoc (assoc (kitchen-params)
:name token
:permitted-user "*"
:run-as-user (retrieve-username)
:token token)
:authentication))]
(try
(assert-response-status response http-200-ok)
(let [{:keys [service-id body]} (make-request-with-debug-info
{:x-waiter-token token}
#(make-kitchen-request waiter-url % :path "/request-info"))
body-json (json/read-str (str body))]
(with-service-cleanup
service-id
(is (= (retrieve-username) (get-in body-json ["headers" "x-waiter-auth-principal"])))))
(finally
(delete-token-and-assert waiter-url token)))))))
(deftest ^:parallel ^:integration-fast test-token-authentication-parameter-error
(testing-using-waiter-url
(when (using-composite-authenticator? waiter-url)
(let [authentication-providers (-> waiter-url
waiter-settings
(get-in [:authenticator-config :composite :authentication-providers])
keys
(->> (map name)))
error-message (str "authentication must be one of: '"
(str/join "', '" (sort (into #{"disabled" "standard"} authentication-providers)))
"'")]
(let [token (rand-<KEY>)
{:keys [body] :as response} (post-token waiter-url (assoc (kitchen-params)
:authentication "invalid"
:name token
:permitted-user "*"
:run-as-user (retrieve-username)
:token token))]
(assert-response-status response http-400-bad-request)
(is (str/includes? body error-message)))
(let [token (<KEY>)
{:keys [body] :as response} (post-token waiter-url (assoc (kitchen-params)
:authentication ""
:name token
:permitted-user "*"
:run-as-user (retrieve-username)
:token token))]
(assert-response-status response http-400-bad-request)
(is (str/includes? body error-message)))))))
(defn- perform-saml-authentication
"Perform authentication with an identity provider service.
Return map of waiter acs endpoint, saml-response and relay-state"
[saml-redirect-location]
(let [make-connection (fn [request-url]
(let [http-connection (.openConnection (URL. request-url))]
(.setDoOutput http-connection false)
(.setDoInput http-connection true)
(.setRequestMethod http-connection "GET")
(.connect http-connection)
http-connection))
conn (make-connection saml-redirect-location)]
(is (= http-200-ok (.getResponseCode conn)))
(reaver/extract (reaver/parse (slurp (.getInputStream conn))) [:waiter-saml-acs-endpoint :saml-response :relay-state]
"form" (reaver/attr :action)
"form input[name=SAMLResponse]" (reaver/attr :value)
"form input[name=RelayState]" (reaver/attr :value))))
(deftest ^:parallel ^:integration-fast test-saml-authentication
(testing-using-waiter-url
(when (supports-saml-authentication? waiter-url)
(let [token (<KEY>)
response (post-token waiter-url (-> (kitchen-params)
(assoc
:authentication "saml"
:name token
:permitted-user "*"
:run-as-user (retrieve-username)
:token token)))]
(assert-response-status response http-200-ok)
(try
(let [{:keys [headers] :as response} (make-request waiter-url "/request-info" :headers {:x-waiter-token token})
_ (assert-response-status response http-302-moved-temporarily)
saml-redirect-location (get headers "location")
{:keys [relay-state saml-response waiter-saml-acs-endpoint]} (perform-saml-authentication saml-redirect-location)
{:keys [body] :as response} (make-request waiter-saml-acs-endpoint ""
:body (str "SAMLResponse=" (URLEncoder/encode saml-response)
"&RelayState=" (URLEncoder/encode relay-state))
:headers {"content-type" "application/x-www-form-urlencoded"}
:method :post)
_ (assert-response-status response http-200-ok)
{:keys [waiter-saml-auth-redirect-endpoint saml-auth-data]}
(reaver/extract (reaver/parse body) [:waiter-saml-auth-redirect-endpoint :saml-auth-data]
"form" (reaver/attr :action)
"form input[name=saml-auth-data]" (reaver/attr :value))
_ (is (= (str "http://" waiter-url "/waiter-auth/saml/auth-redirect") waiter-saml-auth-redirect-endpoint))
{:keys [cookies headers] :as response} (make-request waiter-url "/waiter-auth/saml/auth-redirect"
:body (str "saml-auth-data=" (URLEncoder/encode saml-auth-data))
:headers {"content-type" "application/x-www-form-urlencoded"}
:method :post)
_ (assert-response-status response http-303-see-other)
cookie-fn (fn [cookies name] (some #(when (= name (:name %)) %) cookies))
auth-cookie (cookie-fn cookies "x-waiter-auth")
_ (is (not (nil? auth-cookie)))
_ (is (> (:max-age auth-cookie) (-> 1 t/hours t/in-seconds)))
_ (is (= (str "http://" waiter-url "/request-info") (get headers "location")))
{:keys [body service-id] :as response} (make-request-with-debug-info
{:x-waiter-token token}
#(make-request waiter-url "/request-info" :headers % :cookies cookies))
_ (assert-response-status response http-200-ok)
body-json (json/read-str (str body))]
(with-service-cleanup
service-id
(is (= (retrieve-username) (get-in body-json ["headers" "x-waiter-auth-principal"])))))
(finally
(delete-token-and-assert waiter-url token)))))))
(defn- retrieve-access-token
[realm]
(if-let [access-token-url-env (System/getenv "WAITER_TEST_JWT_ACCESS_TOKEN_URL")]
(let [access-token-url (str/replace access-token-url-env "{HOST}" realm)
access-token-uri (URI. access-token-url)
protocol (.getScheme access-token-uri)
authority (.getAuthority access-token-uri)
path (str (.getPath access-token-uri) "?" (.getQuery access-token-uri))
access-token-response (make-request authority path :headers {"x-iam" "waiter"} :protocol protocol)
_ (assert-response-status access-token-response http-200-ok)
access-token-response-json (-> access-token-response :body str json/read-str)
access-token (get access-token-response-json "access_token")]
(log/info "retrieved access token" {:access-token access-token :realm realm})
access-token)
(throw (ex-info "WAITER_TEST_JWT_ACCESS_TOKEN_URL environment variable has not been provided" {}))))
(defmacro assert-auth-cookie
"Helper macro to assert the value of the set-cookie header."
[set-cookie assertion-message]
`(let [set-cookie# ~set-cookie
assertion-message# ~assertion-message]
(is (str/includes? set-cookie# "x-waiter-auth=") assertion-message#)
(is (str/includes? set-cookie# "Max-Age=") assertion-message#)
(is (str/includes? set-cookie# "Path=/") assertion-message#)
(is (str/includes? set-cookie# "HttpOnly=true") assertion-message#)))
;; Test disabled because JWT support is, currently, only for tokens
(deftest ^:parallel ^:integration-fast ^:explicit test-successful-jwt-authentication-waiter-realm
(testing-using-waiter-url
(if (jwt-auth-enabled? waiter-url)
(let [waiter-host (-> waiter-url sanitize-waiter-url utils/authority->host)
access-token (retrieve-access-token waiter-host)
request-headers {"authorization" (str "Bearer " access-token)
"host" waiter-host
"x-forwarded-proto" "https"}
port (waiter-settings-port waiter-url)
target-url (str waiter-host ":" port)
{:keys [body headers] :as response}
(make-request target-url "/waiter-auth" :disable-auth true :headers request-headers :method :get)
set-cookie (str (get headers "set-cookie"))
assertion-message (str {:headers headers
:set-cookie set-cookie
:target-url target-url})]
(assert-response-status response http-200-ok)
(is (= (retrieve-username) (str body)))
(is (= "jwt" (get headers "x-waiter-auth-method")) assertion-message)
(is (= (retrieve-username) (get headers "x-waiter-auth-user")) assertion-message)
(assert-auth-cookie set-cookie assertion-message))
(log/info "JWT authentication is disabled"))))
;; Test disabled because JWT support is, currently, only for tokens
(deftest ^:parallel ^:integration-fast ^:explicit test-forbidden-jwt-authentication-waiter-realm
(testing-using-waiter-url
(if (jwt-auth-enabled? waiter-url)
(let [waiter-host (-> waiter-url sanitize-waiter-url utils/authority->host)
access-token (retrieve-access-token waiter-host)
request-headers {"authorization" (str "Bearer " access-token)
"host" waiter-host
"x-forwarded-proto" "http"}
port (waiter-settings-port waiter-url)
target-url (str waiter-host ":" port)
{:keys [body headers] :as response}
(make-request target-url "/waiter-auth" :disable-auth true :headers request-headers :method :get)
set-cookie (str (get headers "set-cookie"))
assertion-message (str {:headers headers
:target-url target-url})]
(assert-response-status response http-403-forbidden)
(is (str/includes? (str body) "Must use HTTPS connection") assertion-message)
(is (str/blank? set-cookie) assertion-message))
(log/info "JWT authentication is disabled"))))
(deftest ^:parallel ^:integration-fast test-forbidden-authentication-with-bad-jwt-token-waiter-realm
(testing-using-waiter-url
(if (jwt-auth-enabled? waiter-url)
(let [waiter-host (-> waiter-url sanitize-waiter-url utils/authority->host)
port (waiter-settings-port waiter-url)
target-url (str waiter-host ":" port)]
(let [access-token (str (retrieve-access-token waiter-host) "invalid")
request-headers {"authorization" [(str "Bearer " access-token)
(str "Negotiate bad-token")
(str "SingleUser forbidden")]
"host" waiter-host
"x-forwarded-proto" "https"}
{:keys [headers] :as response}
(make-request target-url "/waiter-auth" :disable-auth true :headers request-headers :method :get)
set-cookie (str (get headers "set-cookie"))
assertion-message (str (select-keys response [:body :error :headers :status]))]
(assert-response-status response http-403-forbidden)
(is (str/blank? (get headers "www-authenticate")) assertion-message)
(is (str/blank? set-cookie) assertion-message))
(when use-spnego
(let [{:keys [<KEY> <KEY>]
:or {allow-bearer-auth-api? true
attach-www-authenticate-on-missing-bearer-token? true}}
(setting waiter-url [:authenticator-config :jwt])
request-headers {"host" waiter-host
"x-forwarded-proto" "https"}
{:keys [headers] :as response}
(make-request target-url "/waiter-auth" :disable-auth true :headers request-headers :method :get)
set-cookie (str (get headers "set-cookie"))
assertion-message (str (select-keys response [:body :error :headers :status]))]
(assert-response-status response http-401-unauthorized)
(is (get headers "www-authenticate") assertion-message)
(when (and allow-bearer-auth-api? attach-www-authenticate-on-missing-bearer-token?)
(is (str/includes? (str (get headers "www-authenticate")) "Bearer") assertion-message))
(is (str/blank? set-cookie) assertion-message))))
(log/info "JWT authentication is disabled"))))
;; Test disabled because JWT support is, currently, only for tokens
(deftest ^:parallel ^:integration-fast ^:explicit test-unauthorized-jwt-authentication-waiter-realm
(testing-using-waiter-url
(if (jwt-auth-enabled? waiter-url)
(let [waiter-host (-> waiter-url sanitize-waiter-url utils/authority->host)
access-token (str (retrieve-access-token waiter-host) "invalid")
request-headers {"authorization" [(str "Bearer " access-token)
;; absence of Negotiate header also trigger an unauthorized response
(str "SingleUser unauthorized")]
"host" waiter-host
"x-forwarded-proto" "https"}
port (waiter-settings-port waiter-url)
target-url (str waiter-host ":" port)
{:keys [headers] :as response}
(make-request target-url "/waiter-auth" :disable-auth true :headers request-headers :method :get)
set-cookie (str (get headers "set-cookie"))
assertion-message (str (select-keys response [:body :error :headers :status]))]
(assert-response-status response http-401-unauthorized)
(is (str/blank? set-cookie) assertion-message)
(if-let [challenge (get headers "www-authenticate")]
(do
(is (str/includes? (str challenge) "Bearer realm"))
(is (> (count (str/split challenge #",")) 1) assertion-message))
(is false (str "www-authenticate header missing: " assertion-message))))
(log/info "JWT authentication is disabled"))))
(deftest ^:parallel ^:integration-fast test-fallback-to-alternate-auth-on-invalid-jwt-token-waiter-realm
(testing-using-waiter-url
(if (jwt-auth-enabled? waiter-url)
(let [waiter-host (-> waiter-url sanitize-waiter-url utils/authority->host)
access-token (str (retrieve-access-token waiter-host) "invalid")
request-headers {"authorization" (str "Bearer " access-token)
"host" waiter-host
"x-forwarded-proto" "https"}
port (waiter-settings-port waiter-url)
target-url (str waiter-host ":" port)
{:keys [body headers] :as response}
(make-request target-url "/waiter-auth" :headers request-headers :method :get)
set-cookie (str (get headers "set-cookie"))
assertion-message (str {:headers headers
:set-cookie set-cookie
:target-url target-url})]
(assert-response-status response http-200-ok)
(is (= (retrieve-username) (str body)))
(let [{:strs [x-waiter-auth-method]} headers]
(is (not= "jwt" x-waiter-auth-method) assertion-message)
(is (not (str/blank? x-waiter-auth-method)) assertion-message))
(is (= (retrieve-username) (get headers "x-waiter-auth-user")) assertion-message)
(assert-auth-cookie set-cookie assertion-message))
(log/info "JWT authentication is disabled"))))
(defn- create-token-name
[waiter-url service-id-prefix]
(str service-id-prefix "." (subs waiter-url 0 (str/index-of waiter-url ":"))))
(defn- validate-response
[service-id access-token auth-method {:keys [body headers] :as response}]
(let [assertion-message (str {:auth-method auth-method
:body body
:headers headers
:jwt-access-token access-token
:service-id service-id})
set-cookie (str (get headers "set-cookie"))]
(assert-response-status response http-200-ok)
(is (= auth-method (get headers "x-waiter-auth-method")) assertion-message)
(is (= (retrieve-username) (get headers "x-waiter-auth-user")) assertion-message)
(when-not (= auth-method "cookie")
(assert-auth-cookie set-cookie assertion-message))
(let [body-json (try-parse-json body)]
(is (= access-token (get-in body-json ["headers" "x-waiter-jwt"])) assertion-message))))
(deftest ^:parallel ^:integration-fast test-jwt-authentication-token-realm
(testing-using-waiter-url
(if (jwt-auth-enabled? waiter-url)
(let [waiter-host (-> waiter-url sanitize-waiter-url utils/authority->host)
host (create-token-name waiter-url (rand-name))
service-parameters (assoc (kitchen-params)
:env {"USE_BEARER_AUTH" "true"}
:name (rand-name))
token-response (post-token waiter-url (assoc service-parameters
:run-as-user (retrieve-username)
"token" host))
_ (assert-response-status token-response http-200-ok)
access-token (retrieve-access-token host)
request-headers {"authorization" (str "Bearer " access-token)
"host" host
"x-forwarded-proto" "https"}
port (waiter-settings-port waiter-url)
target-url (str waiter-host ":" port)
{:keys [cookies request-headers service-id] :as response}
(make-request-with-debug-info
request-headers
#(make-request target-url "/request-info" :disable-auth true :headers % :method :get))]
(try
(with-service-cleanup
service-id
(validate-response service-id access-token "jwt" response)
(->> (make-request target-url "/request-info"
:cookies cookies
:disable-auth true
:headers (dissoc request-headers "authorization" "x-cid")
:method :get)
(validate-response service-id access-token "cookie")))
(finally
(delete-token-and-assert waiter-url host))))
(log/info "JWT authentication is disabled"))))
(deftest ^:parallel ^:integration-fast test-fallback-to-alternate-auth-on-invalid-jwt-token-token-realm
(testing-using-waiter-url
(if (jwt-auth-enabled? waiter-url)
(let [waiter-host (-> waiter-url sanitize-waiter-url utils/authority->host)
host (create-token-name waiter-url (rand-name))
service-parameters (assoc (kitchen-params)
:env {"USE_BEARER_AUTH" "true"}
:name (rand-name))
token-response (post-token waiter-url (assoc service-parameters
:run-as-user (retrieve-username)
"token" host))
_ (assert-response-status token-response http-200-ok)
access-token (str (retrieve-access-token host) "invalid")
request-headers {"authorization" (str "Bearer " access-token)
"host" host
"x-forwarded-proto" "https"}
port (waiter-settings-port waiter-url)
target-url (str waiter-host ":" port)
{:keys [headers service-id] :as response}
(make-request-with-debug-info
request-headers
#(make-request target-url "/status" :headers % :method :get))
set-cookie (str (get headers "set-cookie"))
assertion-message (str {:headers headers
:service-id service-id
:set-cookie set-cookie
:target-url target-url})]
(try
(with-service-cleanup
service-id
(assert-response-status response http-200-ok)
(let [{:strs [x-waiter-auth-method]} headers]
(is (not= "jwt" x-waiter-auth-method) assertion-message)
(is (not (str/blank? x-waiter-auth-method)) assertion-message))
(is (= (retrieve-username) (get headers "x-waiter-auth-user")) assertion-message)
(assert-auth-cookie set-cookie assertion-message))
(finally
(delete-token-and-assert waiter-url host))))
(log/info "JWT authentication is disabled"))))
(defmacro assert-oidc-challenge-cookie
"Helper macro to assert the value of x-waiter-oidc-challenge in the set-cookie header."
[set-cookie assertion-message]
`(let [set-cookie# ~set-cookie
assertion-message# ~assertion-message]
(is (str/includes? set-cookie# "x-waiter-oidc-challenge=") assertion-message#)
(is (str/includes? set-cookie# "Max-Age=") assertion-message#)
(is (str/includes? set-cookie# "Path=/") assertion-message#)
(is (str/includes? set-cookie# "HttpOnly=true") assertion-message#)))
(defn- follow-authorize-redirects
"Asserts for query parameters on the redirect url.
Then makes requests and follows redirects until the oidc callback url is returned as a redirect."
[authorize-redirect-location]
(is (str/includes? authorize-redirect-location "client_id="))
(is (str/includes? authorize-redirect-location "code_challenge="))
(is (str/includes? authorize-redirect-location "code_challenge_method="))
(is (str/includes? authorize-redirect-location "redirect_uri="))
(is (str/includes? authorize-redirect-location "response_type="))
(is (str/includes? authorize-redirect-location "scope="))
(is (str/includes? authorize-redirect-location "state="))
(loop [iteration 1
authorize-location authorize-redirect-location]
(log/info "redirecting to" authorize-location)
(let [authorize-uri (URI. authorize-location)
authorize-protocol (.getScheme authorize-uri)
authorize-authority (.getAuthority authorize-uri)
authorize-path (str (.getPath authorize-uri) "?" (.getQuery authorize-uri))
authorize-response (make-request authorize-authority authorize-path :protocol authorize-protocol)
_ (assert-response-status authorize-response #{http-301-moved-permanently
http-302-moved-temporarily
http-307-temporary-redirect
http-308-permanent-redirect})
assertion-message (str {:headers (:headers authorize-response)
:status (:status authorize-response)
:uri authorize-location})
{:strs [location]} (:headers authorize-response)]
(is (not (str/blank? location)) assertion-message)
(if (or (>= iteration 10)
(and (str/includes? location "/oidc/v1/callback?")
(str/includes? location "code=")
(str/includes? location "state=")))
location
(recur (inc iteration) location)))))
(deftest ^:parallel ^:integration-fast test-oidc-authentication-redirect
(testing-using-waiter-url
(if (oidc-auth-enabled? waiter-url)
(let [waiter-host (-> waiter-url sanitize-waiter-url utils/authority->host)
oidc-token-from-env (System/getenv "WAITER_TEST_TOKEN_OIDC")
edit-oidc-token-from-env? (Boolean/valueOf (System/getenv "WAITER_TEST_TOKEN_OIDC_EDIT"))
waiter-token (or oidc-token-from-env (create-token-name waiter-url (rand-name)))
edit-token? (or (str/blank? oidc-token-from-env) edit-oidc-token-from-env?)
_ (when edit-token?
(let [service-parameters (assoc (kitchen-params)
:env {"USE_OIDC_AUTH" "true"}
:name (rand-name)
:run-as-user (retrieve-username))
token-response (post-token waiter-url (assoc service-parameters :token waiter-token))]
(assert-response-status token-response http-200-ok)))
;; absence of Negotiate header also triggers an unauthorized response
request-headers {"authorization" "SingleUser unauthorized"
"accept-redirect" "yes"
"host" waiter-token
"x-forwarded-proto" "https"}
port (waiter-settings-port waiter-url)
target-url (str waiter-host ":" port)
{:keys [cookies] :as initial-response}
(make-request-with-debug-info
request-headers
#(make-request target-url "/request-info" :disable-auth true :headers % :method :get))]
(try
(assert-response-status initial-response http-302-moved-temporarily)
(let [{:strs [location set-cookie]} (:headers initial-response)
assertion-message (str {:headers (:headers initial-response)
:set-cookie set-cookie
:status (:status initial-response)})]
(is (not (str/blank? location)) assertion-message)
(assert-oidc-challenge-cookie set-cookie assertion-message)
(let [callback-location (follow-authorize-redirects location)]
(is (not (str/blank? callback-location)) assertion-message)
(is (str/includes? callback-location "/oidc/v1/callback?") assertion-message)
(let [callback-uri (URI. callback-location)
callback-path (str (.getPath callback-uri) "?" (.getRawQuery callback-uri))
callback-request-headers {"host" waiter-token
"x-forwarded-proto" "https"}
{:keys [cookies] :as callback-response}
(make-request target-url callback-path
:cookies cookies
:headers callback-request-headers)]
(assert-response-status callback-response http-302-moved-temporarily)
(is (= 2 (count cookies)))
(is (zero? (:max-age (first (filter #(= (:name %) "x-waiter-oidc-challenge") cookies)))))
(is (pos? (:max-age (first (filter #(= (:name %) "x-waiter-auth") cookies)))))
(let [{:strs [location]} (:headers callback-response)
assertion-message (str {:headers (:headers callback-response)
:status (:status callback-response)})]
(is (= (str "https://" waiter-token "/request-info") location) assertion-message)))))
(finally
(when edit-token?
(delete-token-and-assert waiter-url waiter-token)))))
(log/info "OIDC+PKCE authentication is disabled"))))
| true | (ns waiter.authentication-test
(:require [clj-time.core :as t]
[clojure.data.json :as json]
[clojure.string :as str]
[clojure.test :refer :all]
[clojure.tools.logging :as log]
[reaver :as reaver]
[waiter.status-codes :refer :all]
[waiter.util.client-tools :refer :all]
[waiter.util.utils :as utils])
(:import (java.net URI URL URLEncoder)))
(deftest ^:parallel ^:integration-fast test-default-composite-authenticator
(testing-using-waiter-url
(when (using-composite-authenticator? waiter-url)
(let [token (PI:KEY:<KEY>END_PI)
response (post-token waiter-url (dissoc (assoc (kitchen-params)
:name token
:permitted-user "*"
:run-as-user (retrieve-username)
:token token)
:authentication))]
(try
(assert-response-status response http-200-ok)
(let [{:keys [service-id body]} (make-request-with-debug-info
{:x-waiter-token token}
#(make-kitchen-request waiter-url % :path "/request-info"))
body-json (json/read-str (str body))]
(with-service-cleanup
service-id
(is (= (retrieve-username) (get-in body-json ["headers" "x-waiter-auth-principal"])))))
(finally
(delete-token-and-assert waiter-url token)))))))
(deftest ^:parallel ^:integration-fast test-token-authentication-parameter-error
(testing-using-waiter-url
(when (using-composite-authenticator? waiter-url)
(let [authentication-providers (-> waiter-url
waiter-settings
(get-in [:authenticator-config :composite :authentication-providers])
keys
(->> (map name)))
error-message (str "authentication must be one of: '"
(str/join "', '" (sort (into #{"disabled" "standard"} authentication-providers)))
"'")]
(let [token (rand-PI:KEY:<KEY>END_PI)
{:keys [body] :as response} (post-token waiter-url (assoc (kitchen-params)
:authentication "invalid"
:name token
:permitted-user "*"
:run-as-user (retrieve-username)
:token token))]
(assert-response-status response http-400-bad-request)
(is (str/includes? body error-message)))
(let [token (PI:KEY:<KEY>END_PI)
{:keys [body] :as response} (post-token waiter-url (assoc (kitchen-params)
:authentication ""
:name token
:permitted-user "*"
:run-as-user (retrieve-username)
:token token))]
(assert-response-status response http-400-bad-request)
(is (str/includes? body error-message)))))))
(defn- perform-saml-authentication
"Perform authentication with an identity provider service.
Return map of waiter acs endpoint, saml-response and relay-state"
[saml-redirect-location]
(let [make-connection (fn [request-url]
(let [http-connection (.openConnection (URL. request-url))]
(.setDoOutput http-connection false)
(.setDoInput http-connection true)
(.setRequestMethod http-connection "GET")
(.connect http-connection)
http-connection))
conn (make-connection saml-redirect-location)]
(is (= http-200-ok (.getResponseCode conn)))
(reaver/extract (reaver/parse (slurp (.getInputStream conn))) [:waiter-saml-acs-endpoint :saml-response :relay-state]
"form" (reaver/attr :action)
"form input[name=SAMLResponse]" (reaver/attr :value)
"form input[name=RelayState]" (reaver/attr :value))))
(deftest ^:parallel ^:integration-fast test-saml-authentication
(testing-using-waiter-url
(when (supports-saml-authentication? waiter-url)
(let [token (PI:KEY:<KEY>END_PI)
response (post-token waiter-url (-> (kitchen-params)
(assoc
:authentication "saml"
:name token
:permitted-user "*"
:run-as-user (retrieve-username)
:token token)))]
(assert-response-status response http-200-ok)
(try
(let [{:keys [headers] :as response} (make-request waiter-url "/request-info" :headers {:x-waiter-token token})
_ (assert-response-status response http-302-moved-temporarily)
saml-redirect-location (get headers "location")
{:keys [relay-state saml-response waiter-saml-acs-endpoint]} (perform-saml-authentication saml-redirect-location)
{:keys [body] :as response} (make-request waiter-saml-acs-endpoint ""
:body (str "SAMLResponse=" (URLEncoder/encode saml-response)
"&RelayState=" (URLEncoder/encode relay-state))
:headers {"content-type" "application/x-www-form-urlencoded"}
:method :post)
_ (assert-response-status response http-200-ok)
{:keys [waiter-saml-auth-redirect-endpoint saml-auth-data]}
(reaver/extract (reaver/parse body) [:waiter-saml-auth-redirect-endpoint :saml-auth-data]
"form" (reaver/attr :action)
"form input[name=saml-auth-data]" (reaver/attr :value))
_ (is (= (str "http://" waiter-url "/waiter-auth/saml/auth-redirect") waiter-saml-auth-redirect-endpoint))
{:keys [cookies headers] :as response} (make-request waiter-url "/waiter-auth/saml/auth-redirect"
:body (str "saml-auth-data=" (URLEncoder/encode saml-auth-data))
:headers {"content-type" "application/x-www-form-urlencoded"}
:method :post)
_ (assert-response-status response http-303-see-other)
cookie-fn (fn [cookies name] (some #(when (= name (:name %)) %) cookies))
auth-cookie (cookie-fn cookies "x-waiter-auth")
_ (is (not (nil? auth-cookie)))
_ (is (> (:max-age auth-cookie) (-> 1 t/hours t/in-seconds)))
_ (is (= (str "http://" waiter-url "/request-info") (get headers "location")))
{:keys [body service-id] :as response} (make-request-with-debug-info
{:x-waiter-token token}
#(make-request waiter-url "/request-info" :headers % :cookies cookies))
_ (assert-response-status response http-200-ok)
body-json (json/read-str (str body))]
(with-service-cleanup
service-id
(is (= (retrieve-username) (get-in body-json ["headers" "x-waiter-auth-principal"])))))
(finally
(delete-token-and-assert waiter-url token)))))))
(defn- retrieve-access-token
[realm]
(if-let [access-token-url-env (System/getenv "WAITER_TEST_JWT_ACCESS_TOKEN_URL")]
(let [access-token-url (str/replace access-token-url-env "{HOST}" realm)
access-token-uri (URI. access-token-url)
protocol (.getScheme access-token-uri)
authority (.getAuthority access-token-uri)
path (str (.getPath access-token-uri) "?" (.getQuery access-token-uri))
access-token-response (make-request authority path :headers {"x-iam" "waiter"} :protocol protocol)
_ (assert-response-status access-token-response http-200-ok)
access-token-response-json (-> access-token-response :body str json/read-str)
access-token (get access-token-response-json "access_token")]
(log/info "retrieved access token" {:access-token access-token :realm realm})
access-token)
(throw (ex-info "WAITER_TEST_JWT_ACCESS_TOKEN_URL environment variable has not been provided" {}))))
(defmacro assert-auth-cookie
"Helper macro to assert the value of the set-cookie header."
[set-cookie assertion-message]
`(let [set-cookie# ~set-cookie
assertion-message# ~assertion-message]
(is (str/includes? set-cookie# "x-waiter-auth=") assertion-message#)
(is (str/includes? set-cookie# "Max-Age=") assertion-message#)
(is (str/includes? set-cookie# "Path=/") assertion-message#)
(is (str/includes? set-cookie# "HttpOnly=true") assertion-message#)))
;; Test disabled because JWT support is, currently, only for tokens
(deftest ^:parallel ^:integration-fast ^:explicit test-successful-jwt-authentication-waiter-realm
(testing-using-waiter-url
(if (jwt-auth-enabled? waiter-url)
(let [waiter-host (-> waiter-url sanitize-waiter-url utils/authority->host)
access-token (retrieve-access-token waiter-host)
request-headers {"authorization" (str "Bearer " access-token)
"host" waiter-host
"x-forwarded-proto" "https"}
port (waiter-settings-port waiter-url)
target-url (str waiter-host ":" port)
{:keys [body headers] :as response}
(make-request target-url "/waiter-auth" :disable-auth true :headers request-headers :method :get)
set-cookie (str (get headers "set-cookie"))
assertion-message (str {:headers headers
:set-cookie set-cookie
:target-url target-url})]
(assert-response-status response http-200-ok)
(is (= (retrieve-username) (str body)))
(is (= "jwt" (get headers "x-waiter-auth-method")) assertion-message)
(is (= (retrieve-username) (get headers "x-waiter-auth-user")) assertion-message)
(assert-auth-cookie set-cookie assertion-message))
(log/info "JWT authentication is disabled"))))
;; Test disabled because JWT support is, currently, only for tokens
(deftest ^:parallel ^:integration-fast ^:explicit test-forbidden-jwt-authentication-waiter-realm
(testing-using-waiter-url
(if (jwt-auth-enabled? waiter-url)
(let [waiter-host (-> waiter-url sanitize-waiter-url utils/authority->host)
access-token (retrieve-access-token waiter-host)
request-headers {"authorization" (str "Bearer " access-token)
"host" waiter-host
"x-forwarded-proto" "http"}
port (waiter-settings-port waiter-url)
target-url (str waiter-host ":" port)
{:keys [body headers] :as response}
(make-request target-url "/waiter-auth" :disable-auth true :headers request-headers :method :get)
set-cookie (str (get headers "set-cookie"))
assertion-message (str {:headers headers
:target-url target-url})]
(assert-response-status response http-403-forbidden)
(is (str/includes? (str body) "Must use HTTPS connection") assertion-message)
(is (str/blank? set-cookie) assertion-message))
(log/info "JWT authentication is disabled"))))
(deftest ^:parallel ^:integration-fast test-forbidden-authentication-with-bad-jwt-token-waiter-realm
(testing-using-waiter-url
(if (jwt-auth-enabled? waiter-url)
(let [waiter-host (-> waiter-url sanitize-waiter-url utils/authority->host)
port (waiter-settings-port waiter-url)
target-url (str waiter-host ":" port)]
(let [access-token (str (retrieve-access-token waiter-host) "invalid")
request-headers {"authorization" [(str "Bearer " access-token)
(str "Negotiate bad-token")
(str "SingleUser forbidden")]
"host" waiter-host
"x-forwarded-proto" "https"}
{:keys [headers] :as response}
(make-request target-url "/waiter-auth" :disable-auth true :headers request-headers :method :get)
set-cookie (str (get headers "set-cookie"))
assertion-message (str (select-keys response [:body :error :headers :status]))]
(assert-response-status response http-403-forbidden)
(is (str/blank? (get headers "www-authenticate")) assertion-message)
(is (str/blank? set-cookie) assertion-message))
(when use-spnego
(let [{:keys [PI:KEY:<KEY>END_PI PI:KEY:<KEY>END_PI]
:or {allow-bearer-auth-api? true
attach-www-authenticate-on-missing-bearer-token? true}}
(setting waiter-url [:authenticator-config :jwt])
request-headers {"host" waiter-host
"x-forwarded-proto" "https"}
{:keys [headers] :as response}
(make-request target-url "/waiter-auth" :disable-auth true :headers request-headers :method :get)
set-cookie (str (get headers "set-cookie"))
assertion-message (str (select-keys response [:body :error :headers :status]))]
(assert-response-status response http-401-unauthorized)
(is (get headers "www-authenticate") assertion-message)
(when (and allow-bearer-auth-api? attach-www-authenticate-on-missing-bearer-token?)
(is (str/includes? (str (get headers "www-authenticate")) "Bearer") assertion-message))
(is (str/blank? set-cookie) assertion-message))))
(log/info "JWT authentication is disabled"))))
;; Test disabled because JWT support is, currently, only for tokens
(deftest ^:parallel ^:integration-fast ^:explicit test-unauthorized-jwt-authentication-waiter-realm
(testing-using-waiter-url
(if (jwt-auth-enabled? waiter-url)
(let [waiter-host (-> waiter-url sanitize-waiter-url utils/authority->host)
access-token (str (retrieve-access-token waiter-host) "invalid")
request-headers {"authorization" [(str "Bearer " access-token)
;; absence of Negotiate header also trigger an unauthorized response
(str "SingleUser unauthorized")]
"host" waiter-host
"x-forwarded-proto" "https"}
port (waiter-settings-port waiter-url)
target-url (str waiter-host ":" port)
{:keys [headers] :as response}
(make-request target-url "/waiter-auth" :disable-auth true :headers request-headers :method :get)
set-cookie (str (get headers "set-cookie"))
assertion-message (str (select-keys response [:body :error :headers :status]))]
(assert-response-status response http-401-unauthorized)
(is (str/blank? set-cookie) assertion-message)
(if-let [challenge (get headers "www-authenticate")]
(do
(is (str/includes? (str challenge) "Bearer realm"))
(is (> (count (str/split challenge #",")) 1) assertion-message))
(is false (str "www-authenticate header missing: " assertion-message))))
(log/info "JWT authentication is disabled"))))
(deftest ^:parallel ^:integration-fast test-fallback-to-alternate-auth-on-invalid-jwt-token-waiter-realm
(testing-using-waiter-url
(if (jwt-auth-enabled? waiter-url)
(let [waiter-host (-> waiter-url sanitize-waiter-url utils/authority->host)
access-token (str (retrieve-access-token waiter-host) "invalid")
request-headers {"authorization" (str "Bearer " access-token)
"host" waiter-host
"x-forwarded-proto" "https"}
port (waiter-settings-port waiter-url)
target-url (str waiter-host ":" port)
{:keys [body headers] :as response}
(make-request target-url "/waiter-auth" :headers request-headers :method :get)
set-cookie (str (get headers "set-cookie"))
assertion-message (str {:headers headers
:set-cookie set-cookie
:target-url target-url})]
(assert-response-status response http-200-ok)
(is (= (retrieve-username) (str body)))
(let [{:strs [x-waiter-auth-method]} headers]
(is (not= "jwt" x-waiter-auth-method) assertion-message)
(is (not (str/blank? x-waiter-auth-method)) assertion-message))
(is (= (retrieve-username) (get headers "x-waiter-auth-user")) assertion-message)
(assert-auth-cookie set-cookie assertion-message))
(log/info "JWT authentication is disabled"))))
(defn- create-token-name
[waiter-url service-id-prefix]
(str service-id-prefix "." (subs waiter-url 0 (str/index-of waiter-url ":"))))
(defn- validate-response
[service-id access-token auth-method {:keys [body headers] :as response}]
(let [assertion-message (str {:auth-method auth-method
:body body
:headers headers
:jwt-access-token access-token
:service-id service-id})
set-cookie (str (get headers "set-cookie"))]
(assert-response-status response http-200-ok)
(is (= auth-method (get headers "x-waiter-auth-method")) assertion-message)
(is (= (retrieve-username) (get headers "x-waiter-auth-user")) assertion-message)
(when-not (= auth-method "cookie")
(assert-auth-cookie set-cookie assertion-message))
(let [body-json (try-parse-json body)]
(is (= access-token (get-in body-json ["headers" "x-waiter-jwt"])) assertion-message))))
(deftest ^:parallel ^:integration-fast test-jwt-authentication-token-realm
(testing-using-waiter-url
(if (jwt-auth-enabled? waiter-url)
(let [waiter-host (-> waiter-url sanitize-waiter-url utils/authority->host)
host (create-token-name waiter-url (rand-name))
service-parameters (assoc (kitchen-params)
:env {"USE_BEARER_AUTH" "true"}
:name (rand-name))
token-response (post-token waiter-url (assoc service-parameters
:run-as-user (retrieve-username)
"token" host))
_ (assert-response-status token-response http-200-ok)
access-token (retrieve-access-token host)
request-headers {"authorization" (str "Bearer " access-token)
"host" host
"x-forwarded-proto" "https"}
port (waiter-settings-port waiter-url)
target-url (str waiter-host ":" port)
{:keys [cookies request-headers service-id] :as response}
(make-request-with-debug-info
request-headers
#(make-request target-url "/request-info" :disable-auth true :headers % :method :get))]
(try
(with-service-cleanup
service-id
(validate-response service-id access-token "jwt" response)
(->> (make-request target-url "/request-info"
:cookies cookies
:disable-auth true
:headers (dissoc request-headers "authorization" "x-cid")
:method :get)
(validate-response service-id access-token "cookie")))
(finally
(delete-token-and-assert waiter-url host))))
(log/info "JWT authentication is disabled"))))
(deftest ^:parallel ^:integration-fast test-fallback-to-alternate-auth-on-invalid-jwt-token-token-realm
(testing-using-waiter-url
(if (jwt-auth-enabled? waiter-url)
(let [waiter-host (-> waiter-url sanitize-waiter-url utils/authority->host)
host (create-token-name waiter-url (rand-name))
service-parameters (assoc (kitchen-params)
:env {"USE_BEARER_AUTH" "true"}
:name (rand-name))
token-response (post-token waiter-url (assoc service-parameters
:run-as-user (retrieve-username)
"token" host))
_ (assert-response-status token-response http-200-ok)
access-token (str (retrieve-access-token host) "invalid")
request-headers {"authorization" (str "Bearer " access-token)
"host" host
"x-forwarded-proto" "https"}
port (waiter-settings-port waiter-url)
target-url (str waiter-host ":" port)
{:keys [headers service-id] :as response}
(make-request-with-debug-info
request-headers
#(make-request target-url "/status" :headers % :method :get))
set-cookie (str (get headers "set-cookie"))
assertion-message (str {:headers headers
:service-id service-id
:set-cookie set-cookie
:target-url target-url})]
(try
(with-service-cleanup
service-id
(assert-response-status response http-200-ok)
(let [{:strs [x-waiter-auth-method]} headers]
(is (not= "jwt" x-waiter-auth-method) assertion-message)
(is (not (str/blank? x-waiter-auth-method)) assertion-message))
(is (= (retrieve-username) (get headers "x-waiter-auth-user")) assertion-message)
(assert-auth-cookie set-cookie assertion-message))
(finally
(delete-token-and-assert waiter-url host))))
(log/info "JWT authentication is disabled"))))
(defmacro assert-oidc-challenge-cookie
"Helper macro to assert the value of x-waiter-oidc-challenge in the set-cookie header."
[set-cookie assertion-message]
`(let [set-cookie# ~set-cookie
assertion-message# ~assertion-message]
(is (str/includes? set-cookie# "x-waiter-oidc-challenge=") assertion-message#)
(is (str/includes? set-cookie# "Max-Age=") assertion-message#)
(is (str/includes? set-cookie# "Path=/") assertion-message#)
(is (str/includes? set-cookie# "HttpOnly=true") assertion-message#)))
(defn- follow-authorize-redirects
"Asserts for query parameters on the redirect url.
Then makes requests and follows redirects until the oidc callback url is returned as a redirect."
[authorize-redirect-location]
(is (str/includes? authorize-redirect-location "client_id="))
(is (str/includes? authorize-redirect-location "code_challenge="))
(is (str/includes? authorize-redirect-location "code_challenge_method="))
(is (str/includes? authorize-redirect-location "redirect_uri="))
(is (str/includes? authorize-redirect-location "response_type="))
(is (str/includes? authorize-redirect-location "scope="))
(is (str/includes? authorize-redirect-location "state="))
(loop [iteration 1
authorize-location authorize-redirect-location]
(log/info "redirecting to" authorize-location)
(let [authorize-uri (URI. authorize-location)
authorize-protocol (.getScheme authorize-uri)
authorize-authority (.getAuthority authorize-uri)
authorize-path (str (.getPath authorize-uri) "?" (.getQuery authorize-uri))
authorize-response (make-request authorize-authority authorize-path :protocol authorize-protocol)
_ (assert-response-status authorize-response #{http-301-moved-permanently
http-302-moved-temporarily
http-307-temporary-redirect
http-308-permanent-redirect})
assertion-message (str {:headers (:headers authorize-response)
:status (:status authorize-response)
:uri authorize-location})
{:strs [location]} (:headers authorize-response)]
(is (not (str/blank? location)) assertion-message)
(if (or (>= iteration 10)
(and (str/includes? location "/oidc/v1/callback?")
(str/includes? location "code=")
(str/includes? location "state=")))
location
(recur (inc iteration) location)))))
(deftest ^:parallel ^:integration-fast test-oidc-authentication-redirect
(testing-using-waiter-url
(if (oidc-auth-enabled? waiter-url)
(let [waiter-host (-> waiter-url sanitize-waiter-url utils/authority->host)
oidc-token-from-env (System/getenv "WAITER_TEST_TOKEN_OIDC")
edit-oidc-token-from-env? (Boolean/valueOf (System/getenv "WAITER_TEST_TOKEN_OIDC_EDIT"))
waiter-token (or oidc-token-from-env (create-token-name waiter-url (rand-name)))
edit-token? (or (str/blank? oidc-token-from-env) edit-oidc-token-from-env?)
_ (when edit-token?
(let [service-parameters (assoc (kitchen-params)
:env {"USE_OIDC_AUTH" "true"}
:name (rand-name)
:run-as-user (retrieve-username))
token-response (post-token waiter-url (assoc service-parameters :token waiter-token))]
(assert-response-status token-response http-200-ok)))
;; absence of Negotiate header also triggers an unauthorized response
request-headers {"authorization" "SingleUser unauthorized"
"accept-redirect" "yes"
"host" waiter-token
"x-forwarded-proto" "https"}
port (waiter-settings-port waiter-url)
target-url (str waiter-host ":" port)
{:keys [cookies] :as initial-response}
(make-request-with-debug-info
request-headers
#(make-request target-url "/request-info" :disable-auth true :headers % :method :get))]
(try
(assert-response-status initial-response http-302-moved-temporarily)
(let [{:strs [location set-cookie]} (:headers initial-response)
assertion-message (str {:headers (:headers initial-response)
:set-cookie set-cookie
:status (:status initial-response)})]
(is (not (str/blank? location)) assertion-message)
(assert-oidc-challenge-cookie set-cookie assertion-message)
(let [callback-location (follow-authorize-redirects location)]
(is (not (str/blank? callback-location)) assertion-message)
(is (str/includes? callback-location "/oidc/v1/callback?") assertion-message)
(let [callback-uri (URI. callback-location)
callback-path (str (.getPath callback-uri) "?" (.getRawQuery callback-uri))
callback-request-headers {"host" waiter-token
"x-forwarded-proto" "https"}
{:keys [cookies] :as callback-response}
(make-request target-url callback-path
:cookies cookies
:headers callback-request-headers)]
(assert-response-status callback-response http-302-moved-temporarily)
(is (= 2 (count cookies)))
(is (zero? (:max-age (first (filter #(= (:name %) "x-waiter-oidc-challenge") cookies)))))
(is (pos? (:max-age (first (filter #(= (:name %) "x-waiter-auth") cookies)))))
(let [{:strs [location]} (:headers callback-response)
assertion-message (str {:headers (:headers callback-response)
:status (:status callback-response)})]
(is (= (str "https://" waiter-token "/request-info") location) assertion-message)))))
(finally
(when edit-token?
(delete-token-and-assert waiter-url waiter-token)))))
(log/info "OIDC+PKCE authentication is disabled"))))
|
[
{
"context": "; Copyright 2010 Mark Allerton. All rights reserved.\n;\n; Redistribution and u",
"end": 33,
"score": 0.9998727440834045,
"start": 20,
"tag": "NAME",
"value": "Mark Allerton"
},
{
"context": " distribution.\n;\n; THIS SOFTWARE IS PROVIDED BY MARK ALLERTON ``AS IS'' AND ANY EXPRESS OR IMPLIED\n; WA",
"end": 642,
"score": 0.6707993745803833,
"start": 634,
"tag": "NAME",
"value": "MARK ALL"
},
{
"context": "ial policies, either expressed\n; or implied, of Mark Allerton.\n\n(ns couverjure.tools.java-model\n (:us",
"end": 1589,
"score": 0.5371687412261963,
"start": 1585,
"tag": "NAME",
"value": "Mark"
}
] | BridgeSupport/src/clojure/couverjure/tools/java_model.clj | allertonm/Couverjure | 3 | ; Copyright 2010 Mark Allerton. All rights reserved.
;
; Redistribution and use in source and binary forms, with or without modification, are
; permitted provided that the following conditions are met:
;
; 1. Redistributions of source code must retain the above copyright notice, this list of
; conditions and the following disclaimer.
;
; 2. Redistributions in binary form must reproduce the above copyright notice, this list
; of conditions and the following disclaimer in the documentation and/or other materials
; provided with the distribution.
;
; THIS SOFTWARE IS PROVIDED BY MARK ALLERTON ``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 <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.
;
; The views and conclusions contained in the software and documentation are those of the
; authors and should not be interpreted as representing official policies, either expressed
; or implied, of Mark Allerton.
(ns couverjure.tools.java-model
(:use
clojure.test
clojure.contrib.seq-utils
couverjure.struct-utils
couverjure.tools.formatter))
;
; java-model provides a code-model approach to emitting java source code
;
; the following tagged structs define the elements of our java code model
(deftagged type-spec :name)
(deftagged array-type-spec :name)
(deftagged variadic-type-spec :name)
(deftagged var-decl :type-spec :name)
(deftagged field-decl :modifiers :var-decl)
(deftagged method-decl :modifiers :type-spec :name :parameters :body)
(deftagged class-decl :modifiers :name :implements :extends :body)
(deftagged interface-decl :modifiers :name :extends :body)
(deftagged var-ref :object :name)
(deftagged modifier :name)
(deftagged package-decl :package-name)
(deftagged import-decl :package-name :class-name)
(deftagged statement :body)
(deftagged call-method :object :method :parameters)
(deftagged assignment :left :right)
(deftagged line-comment :text)
(deftagged multiline-comment :lines)
; break is a special element that allows clients to force line-breaks
(deftagged break)
; define the standard modifiers
(def public (modifier "public"))
(def static (modifier "static"))
(def abstract (modifier "abstract"))
(def native (modifier "native"))
; The emit-java multimethod emits "java source" for any code-model element
; This does not generate a formatted string. Instead it will return a sequence
; of strings and keywords, and subsequences of the same.
; The keywords act as "formatting instructions", and three keywords are
; supported:
; :break - a line break
; :indent - increase indentation level
; :unindent - decrease indentation level
;
; The structure generated by emit-java can be rendered into formatted source
; using format-java-source.
; Subsequences in the output of emit-java are treated as if inlined into the parent
; sequence - i.e the tree is flattened and has no effect on formatting.
(defmulti emit-java
; Note that we make a psuedo-tag :seq for 'everything else' - we assume the model
; contains only tagged-structs or sequences
(fn [m] (or (:tag m) :seq))) ;(if (sequential? m) :seq ) (throw (IllegalArgumentException. (str "Invalid arg to emit-java:" m))))))
(defn- emit-java-modifiers [mods]
(if (and mods (> (count mods) 0))
(emit-java mods)
nil))
(defmethod emit-java :seq [s]
(for [m s] (emit-java m)))
(defmethod emit-java :type-spec [ts]
[ (:name ts) ])
(defmethod emit-java :array-type-spec [ts]
[ (:name ts) :no-space "[]" ])
(defmethod emit-java :variadic-type-spec [ts]
[ (:name ts) :no-space "..." ])
(defmethod emit-java :var-decl [vd]
[ (emit-java (:type-spec vd)) (:name vd) ])
(defmethod emit-java :field-decl [fd]
[ (emit-java-modifiers (:modifiers fd))
(emit-java (:var-decl fd))
";" :break ])
(defmethod emit-java :method-decl [md]
[(emit-java-modifiers (:modifiers md))
(emit-java (:type-spec md))
(:name md)
"("
(interpose "," (emit-java (:parameters md)))
")"
(if (:body md)
["{" :indent :break
(emit-java (:body md))
:unindent "}" ]
";")
:break ])
(defmethod emit-java :class-decl [cd]
[ (emit-java-modifiers (:modifiers cd))
"class" (:name cd)
(if (:extends cd) "extends")
(:extends cd)
(if (:implements cd) "implements")
(:implements cd)
"{" :indent :break
(emit-java (:body cd))
:unindent
"}" :break ])
(defmethod emit-java :interface-decl [cd]
[ (emit-java-modifiers (:modifiers cd))
"interface" (:name cd)
(if (:extends cd) "extends")
(:extends cd)
"{" :indent :break
(emit-java (:body cd))
:unindent
"}" :break ])
(defmethod emit-java :var-ref [vr]
[ (:object vr) (if (:object vr) ".") (:name vr) ])
(defmethod emit-java :modifier [mod]
[ (:name mod) ])
(defmethod emit-java :statement [st]
[ (emit-java (:body st)) ";" :break ])
(defmethod emit-java :call-method [mi]
[ (:object mi)
(if (:object mi) ".")
(:method mi)
"("
(interpose "," (emit-java (:parameters mi)))
")" ])
(defmethod emit-java :assignment [as]
[ (emit-java (:left as)) "=" (emit-java (:right as)) ])
(defmethod emit-java :line-comment [c]
[ "//" (:text c) :break ])
(defmethod emit-java :multiline-comment [c]
[ "/*" :break (for [line (:lines c)] [ " *" line :break ]) " */" :break ])
(defmethod emit-java :break [c]
[:break])
(defmethod emit-java :package-decl [p]
[ "package" (:package-name p) ";" :break ])
(defmethod emit-java :import-decl [i]
[ "import" (:package-name i) "." (:class-name i) ";" :break ])
;
; formatted output
;
(defn format-java-source
[writer emitted-tree]
(format-source writer emitted-tree 4 #{ "(" "[" "." } #{ "(" ")" "]" "," "." ";" }))
(defn format-java-model
"Generate formatted source code from the model to the supplied writer"
[writer model]
(format-java-source writer (emit-java model)))
| 99542 | ; Copyright 2010 <NAME>. All rights reserved.
;
; Redistribution and use in source and binary forms, with or without modification, are
; permitted provided that the following conditions are met:
;
; 1. Redistributions of source code must retain the above copyright notice, this list of
; conditions and the following disclaimer.
;
; 2. Redistributions in binary form must reproduce the above copyright notice, this list
; of conditions and the following disclaimer in the documentation and/or other materials
; provided with the distribution.
;
; THIS SOFTWARE IS PROVIDED BY <NAME>ERTON ``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 <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.
;
; The views and conclusions contained in the software and documentation are those of the
; authors and should not be interpreted as representing official policies, either expressed
; or implied, of <NAME> Allerton.
(ns couverjure.tools.java-model
(:use
clojure.test
clojure.contrib.seq-utils
couverjure.struct-utils
couverjure.tools.formatter))
;
; java-model provides a code-model approach to emitting java source code
;
; the following tagged structs define the elements of our java code model
(deftagged type-spec :name)
(deftagged array-type-spec :name)
(deftagged variadic-type-spec :name)
(deftagged var-decl :type-spec :name)
(deftagged field-decl :modifiers :var-decl)
(deftagged method-decl :modifiers :type-spec :name :parameters :body)
(deftagged class-decl :modifiers :name :implements :extends :body)
(deftagged interface-decl :modifiers :name :extends :body)
(deftagged var-ref :object :name)
(deftagged modifier :name)
(deftagged package-decl :package-name)
(deftagged import-decl :package-name :class-name)
(deftagged statement :body)
(deftagged call-method :object :method :parameters)
(deftagged assignment :left :right)
(deftagged line-comment :text)
(deftagged multiline-comment :lines)
; break is a special element that allows clients to force line-breaks
(deftagged break)
; define the standard modifiers
(def public (modifier "public"))
(def static (modifier "static"))
(def abstract (modifier "abstract"))
(def native (modifier "native"))
; The emit-java multimethod emits "java source" for any code-model element
; This does not generate a formatted string. Instead it will return a sequence
; of strings and keywords, and subsequences of the same.
; The keywords act as "formatting instructions", and three keywords are
; supported:
; :break - a line break
; :indent - increase indentation level
; :unindent - decrease indentation level
;
; The structure generated by emit-java can be rendered into formatted source
; using format-java-source.
; Subsequences in the output of emit-java are treated as if inlined into the parent
; sequence - i.e the tree is flattened and has no effect on formatting.
(defmulti emit-java
; Note that we make a psuedo-tag :seq for 'everything else' - we assume the model
; contains only tagged-structs or sequences
(fn [m] (or (:tag m) :seq))) ;(if (sequential? m) :seq ) (throw (IllegalArgumentException. (str "Invalid arg to emit-java:" m))))))
(defn- emit-java-modifiers [mods]
(if (and mods (> (count mods) 0))
(emit-java mods)
nil))
(defmethod emit-java :seq [s]
(for [m s] (emit-java m)))
(defmethod emit-java :type-spec [ts]
[ (:name ts) ])
(defmethod emit-java :array-type-spec [ts]
[ (:name ts) :no-space "[]" ])
(defmethod emit-java :variadic-type-spec [ts]
[ (:name ts) :no-space "..." ])
(defmethod emit-java :var-decl [vd]
[ (emit-java (:type-spec vd)) (:name vd) ])
(defmethod emit-java :field-decl [fd]
[ (emit-java-modifiers (:modifiers fd))
(emit-java (:var-decl fd))
";" :break ])
(defmethod emit-java :method-decl [md]
[(emit-java-modifiers (:modifiers md))
(emit-java (:type-spec md))
(:name md)
"("
(interpose "," (emit-java (:parameters md)))
")"
(if (:body md)
["{" :indent :break
(emit-java (:body md))
:unindent "}" ]
";")
:break ])
(defmethod emit-java :class-decl [cd]
[ (emit-java-modifiers (:modifiers cd))
"class" (:name cd)
(if (:extends cd) "extends")
(:extends cd)
(if (:implements cd) "implements")
(:implements cd)
"{" :indent :break
(emit-java (:body cd))
:unindent
"}" :break ])
(defmethod emit-java :interface-decl [cd]
[ (emit-java-modifiers (:modifiers cd))
"interface" (:name cd)
(if (:extends cd) "extends")
(:extends cd)
"{" :indent :break
(emit-java (:body cd))
:unindent
"}" :break ])
(defmethod emit-java :var-ref [vr]
[ (:object vr) (if (:object vr) ".") (:name vr) ])
(defmethod emit-java :modifier [mod]
[ (:name mod) ])
(defmethod emit-java :statement [st]
[ (emit-java (:body st)) ";" :break ])
(defmethod emit-java :call-method [mi]
[ (:object mi)
(if (:object mi) ".")
(:method mi)
"("
(interpose "," (emit-java (:parameters mi)))
")" ])
(defmethod emit-java :assignment [as]
[ (emit-java (:left as)) "=" (emit-java (:right as)) ])
(defmethod emit-java :line-comment [c]
[ "//" (:text c) :break ])
(defmethod emit-java :multiline-comment [c]
[ "/*" :break (for [line (:lines c)] [ " *" line :break ]) " */" :break ])
(defmethod emit-java :break [c]
[:break])
(defmethod emit-java :package-decl [p]
[ "package" (:package-name p) ";" :break ])
(defmethod emit-java :import-decl [i]
[ "import" (:package-name i) "." (:class-name i) ";" :break ])
;
; formatted output
;
(defn format-java-source
[writer emitted-tree]
(format-source writer emitted-tree 4 #{ "(" "[" "." } #{ "(" ")" "]" "," "." ";" }))
(defn format-java-model
"Generate formatted source code from the model to the supplied writer"
[writer model]
(format-java-source writer (emit-java model)))
| true | ; Copyright 2010 PI:NAME:<NAME>END_PI. All rights reserved.
;
; Redistribution and use in source and binary forms, with or without modification, are
; permitted provided that the following conditions are met:
;
; 1. Redistributions of source code must retain the above copyright notice, this list of
; conditions and the following disclaimer.
;
; 2. Redistributions in binary form must reproduce the above copyright notice, this list
; of conditions and the following disclaimer in the documentation and/or other materials
; provided with the distribution.
;
; THIS SOFTWARE IS PROVIDED BY PI:NAME:<NAME>END_PIERTON ``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 <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.
;
; The views and conclusions contained in the software and documentation are those of the
; authors and should not be interpreted as representing official policies, either expressed
; or implied, of PI:NAME:<NAME>END_PI Allerton.
(ns couverjure.tools.java-model
(:use
clojure.test
clojure.contrib.seq-utils
couverjure.struct-utils
couverjure.tools.formatter))
;
; java-model provides a code-model approach to emitting java source code
;
; the following tagged structs define the elements of our java code model
(deftagged type-spec :name)
(deftagged array-type-spec :name)
(deftagged variadic-type-spec :name)
(deftagged var-decl :type-spec :name)
(deftagged field-decl :modifiers :var-decl)
(deftagged method-decl :modifiers :type-spec :name :parameters :body)
(deftagged class-decl :modifiers :name :implements :extends :body)
(deftagged interface-decl :modifiers :name :extends :body)
(deftagged var-ref :object :name)
(deftagged modifier :name)
(deftagged package-decl :package-name)
(deftagged import-decl :package-name :class-name)
(deftagged statement :body)
(deftagged call-method :object :method :parameters)
(deftagged assignment :left :right)
(deftagged line-comment :text)
(deftagged multiline-comment :lines)
; break is a special element that allows clients to force line-breaks
(deftagged break)
; define the standard modifiers
(def public (modifier "public"))
(def static (modifier "static"))
(def abstract (modifier "abstract"))
(def native (modifier "native"))
; The emit-java multimethod emits "java source" for any code-model element
; This does not generate a formatted string. Instead it will return a sequence
; of strings and keywords, and subsequences of the same.
; The keywords act as "formatting instructions", and three keywords are
; supported:
; :break - a line break
; :indent - increase indentation level
; :unindent - decrease indentation level
;
; The structure generated by emit-java can be rendered into formatted source
; using format-java-source.
; Subsequences in the output of emit-java are treated as if inlined into the parent
; sequence - i.e the tree is flattened and has no effect on formatting.
(defmulti emit-java
; Note that we make a psuedo-tag :seq for 'everything else' - we assume the model
; contains only tagged-structs or sequences
(fn [m] (or (:tag m) :seq))) ;(if (sequential? m) :seq ) (throw (IllegalArgumentException. (str "Invalid arg to emit-java:" m))))))
(defn- emit-java-modifiers [mods]
(if (and mods (> (count mods) 0))
(emit-java mods)
nil))
(defmethod emit-java :seq [s]
(for [m s] (emit-java m)))
(defmethod emit-java :type-spec [ts]
[ (:name ts) ])
(defmethod emit-java :array-type-spec [ts]
[ (:name ts) :no-space "[]" ])
(defmethod emit-java :variadic-type-spec [ts]
[ (:name ts) :no-space "..." ])
(defmethod emit-java :var-decl [vd]
[ (emit-java (:type-spec vd)) (:name vd) ])
(defmethod emit-java :field-decl [fd]
[ (emit-java-modifiers (:modifiers fd))
(emit-java (:var-decl fd))
";" :break ])
(defmethod emit-java :method-decl [md]
[(emit-java-modifiers (:modifiers md))
(emit-java (:type-spec md))
(:name md)
"("
(interpose "," (emit-java (:parameters md)))
")"
(if (:body md)
["{" :indent :break
(emit-java (:body md))
:unindent "}" ]
";")
:break ])
(defmethod emit-java :class-decl [cd]
[ (emit-java-modifiers (:modifiers cd))
"class" (:name cd)
(if (:extends cd) "extends")
(:extends cd)
(if (:implements cd) "implements")
(:implements cd)
"{" :indent :break
(emit-java (:body cd))
:unindent
"}" :break ])
(defmethod emit-java :interface-decl [cd]
[ (emit-java-modifiers (:modifiers cd))
"interface" (:name cd)
(if (:extends cd) "extends")
(:extends cd)
"{" :indent :break
(emit-java (:body cd))
:unindent
"}" :break ])
(defmethod emit-java :var-ref [vr]
[ (:object vr) (if (:object vr) ".") (:name vr) ])
(defmethod emit-java :modifier [mod]
[ (:name mod) ])
(defmethod emit-java :statement [st]
[ (emit-java (:body st)) ";" :break ])
(defmethod emit-java :call-method [mi]
[ (:object mi)
(if (:object mi) ".")
(:method mi)
"("
(interpose "," (emit-java (:parameters mi)))
")" ])
(defmethod emit-java :assignment [as]
[ (emit-java (:left as)) "=" (emit-java (:right as)) ])
(defmethod emit-java :line-comment [c]
[ "//" (:text c) :break ])
(defmethod emit-java :multiline-comment [c]
[ "/*" :break (for [line (:lines c)] [ " *" line :break ]) " */" :break ])
(defmethod emit-java :break [c]
[:break])
(defmethod emit-java :package-decl [p]
[ "package" (:package-name p) ";" :break ])
(defmethod emit-java :import-decl [i]
[ "import" (:package-name i) "." (:class-name i) ";" :break ])
;
; formatted output
;
(defn format-java-source
[writer emitted-tree]
(format-source writer emitted-tree 4 #{ "(" "[" "." } #{ "(" ")" "]" "," "." ";" }))
(defn format-java-model
"Generate formatted source code from the model to the supplied writer"
[writer model]
(format-java-source writer (emit-java model)))
|
[
{
"context": "le-data\n []\n [{:inv/color \"blue\"\n :inv/name \"adam\"}\n #_{:inv/color \"red\"\n :inv/name \"beatrice\"",
"end": 785,
"score": 0.8952719569206238,
"start": 781,
"tag": "NAME",
"value": "adam"
},
{
"context": "ame \"adam\"}\n #_{:inv/color \"red\"\n :inv/name \"beatrice\"}])\n\n(def sample-data (create-sample-data))\n;;(pp",
"end": 834,
"score": 0.905852198600769,
"start": 826,
"tag": "NAME",
"value": "beatrice"
},
{
"context": "d/q '{:find [?name]\n :where [[?e :inv/name \"adam\"]\n [?e :inv/color ?color]\n ",
"end": 1266,
"score": 0.8661068081855774,
"start": 1262,
"tag": "NAME",
"value": "adam"
}
] | src/datomic/raw_index.clj | michelemendel/datomic-playground | 0 | (ns datomic.raw-index
(:require [datomic.client.api :as d]
[clojure.pprint :as pp]))
;; Raw index
;; https://docs.datomic.com/cloud/query/raw-index-access.html
;; See tutorial-inventory for the full data set
(def cfg {:server-type :dev-local
:system "datomic-tutorial"})
(def client (d/client cfg))
(def db-name "raw-index")
(d/delete-database client {:db-name db-name})
(d/create-database client {:db-name db-name})
(def conn (d/connect client {:db-name db-name}))
(def schema-1
[{:db/ident :inv/name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
{:db/ident :inv/color
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
])
(defn create-sample-data
[]
[{:inv/color "blue"
:inv/name "adam"}
#_{:inv/color "red"
:inv/name "beatrice"}])
(def sample-data (create-sample-data))
;;(pp/pprint sample-data)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Transactions
(def schema-tx (d/transact conn {:tx-data schema-1}))
;;(pp/pprint schema-tx)
(def sample-data-tx (d/transact conn {:tx-data sample-data}))
;;(pp/pprint sample-data-tx)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Raw indexes
(def db (d/db conn))
(d/q '{:find [?name]
:where [[?e :inv/name "adam"]
[?e :inv/color ?color]
[?e2 :inv/color ?color]
[?e2 :inv/name ?name]]}
db)
(comment
(d/datoms db {:index :eavt})
(d/datoms db {:index :aevt})
(d/datoms db {:index :avet})
(d/datoms db {:index :vaet})
)
(comment
(pp/pprint (d/datoms db {:index :eavt :components [:inv/color]}))
(pp/pprint (d/datoms db {:index :aevt :components [:inv/color]}))
(pp/pprint (d/datoms db {:index :avet :components [:inv/color]}))
(pp/pprint (d/datoms db {:index :vaet :components [:inv/color]}))
)
(comment
(pp/pprint (->> (d/datoms db {:index :eavt :components [:inv/color]}) (map (juxt :e :a :v))))
(pp/pprint (->> (d/datoms db {:index :aevt :components [:inv/color]}) (map (juxt :e :a :v))))
(pp/pprint (->> (d/datoms db {:index :avet :components [:inv/color]}) (map (juxt :e :a :v))))
)
(comment
(pp/pprint (d/datoms db {:index :eavt :components [:inv/color]}))
(pp/pprint (d/datoms db {:index :eavt :components [:db/ident]}))
(d/index-range db {:attrid :inv/color})
)
| 103590 | (ns datomic.raw-index
(:require [datomic.client.api :as d]
[clojure.pprint :as pp]))
;; Raw index
;; https://docs.datomic.com/cloud/query/raw-index-access.html
;; See tutorial-inventory for the full data set
(def cfg {:server-type :dev-local
:system "datomic-tutorial"})
(def client (d/client cfg))
(def db-name "raw-index")
(d/delete-database client {:db-name db-name})
(d/create-database client {:db-name db-name})
(def conn (d/connect client {:db-name db-name}))
(def schema-1
[{:db/ident :inv/name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
{:db/ident :inv/color
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
])
(defn create-sample-data
[]
[{:inv/color "blue"
:inv/name "<NAME>"}
#_{:inv/color "red"
:inv/name "<NAME>"}])
(def sample-data (create-sample-data))
;;(pp/pprint sample-data)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Transactions
(def schema-tx (d/transact conn {:tx-data schema-1}))
;;(pp/pprint schema-tx)
(def sample-data-tx (d/transact conn {:tx-data sample-data}))
;;(pp/pprint sample-data-tx)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Raw indexes
(def db (d/db conn))
(d/q '{:find [?name]
:where [[?e :inv/name "<NAME>"]
[?e :inv/color ?color]
[?e2 :inv/color ?color]
[?e2 :inv/name ?name]]}
db)
(comment
(d/datoms db {:index :eavt})
(d/datoms db {:index :aevt})
(d/datoms db {:index :avet})
(d/datoms db {:index :vaet})
)
(comment
(pp/pprint (d/datoms db {:index :eavt :components [:inv/color]}))
(pp/pprint (d/datoms db {:index :aevt :components [:inv/color]}))
(pp/pprint (d/datoms db {:index :avet :components [:inv/color]}))
(pp/pprint (d/datoms db {:index :vaet :components [:inv/color]}))
)
(comment
(pp/pprint (->> (d/datoms db {:index :eavt :components [:inv/color]}) (map (juxt :e :a :v))))
(pp/pprint (->> (d/datoms db {:index :aevt :components [:inv/color]}) (map (juxt :e :a :v))))
(pp/pprint (->> (d/datoms db {:index :avet :components [:inv/color]}) (map (juxt :e :a :v))))
)
(comment
(pp/pprint (d/datoms db {:index :eavt :components [:inv/color]}))
(pp/pprint (d/datoms db {:index :eavt :components [:db/ident]}))
(d/index-range db {:attrid :inv/color})
)
| true | (ns datomic.raw-index
(:require [datomic.client.api :as d]
[clojure.pprint :as pp]))
;; Raw index
;; https://docs.datomic.com/cloud/query/raw-index-access.html
;; See tutorial-inventory for the full data set
(def cfg {:server-type :dev-local
:system "datomic-tutorial"})
(def client (d/client cfg))
(def db-name "raw-index")
(d/delete-database client {:db-name db-name})
(d/create-database client {:db-name db-name})
(def conn (d/connect client {:db-name db-name}))
(def schema-1
[{:db/ident :inv/name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
{:db/ident :inv/color
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one}
])
(defn create-sample-data
[]
[{:inv/color "blue"
:inv/name "PI:NAME:<NAME>END_PI"}
#_{:inv/color "red"
:inv/name "PI:NAME:<NAME>END_PI"}])
(def sample-data (create-sample-data))
;;(pp/pprint sample-data)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Transactions
(def schema-tx (d/transact conn {:tx-data schema-1}))
;;(pp/pprint schema-tx)
(def sample-data-tx (d/transact conn {:tx-data sample-data}))
;;(pp/pprint sample-data-tx)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Raw indexes
(def db (d/db conn))
(d/q '{:find [?name]
:where [[?e :inv/name "PI:NAME:<NAME>END_PI"]
[?e :inv/color ?color]
[?e2 :inv/color ?color]
[?e2 :inv/name ?name]]}
db)
(comment
(d/datoms db {:index :eavt})
(d/datoms db {:index :aevt})
(d/datoms db {:index :avet})
(d/datoms db {:index :vaet})
)
(comment
(pp/pprint (d/datoms db {:index :eavt :components [:inv/color]}))
(pp/pprint (d/datoms db {:index :aevt :components [:inv/color]}))
(pp/pprint (d/datoms db {:index :avet :components [:inv/color]}))
(pp/pprint (d/datoms db {:index :vaet :components [:inv/color]}))
)
(comment
(pp/pprint (->> (d/datoms db {:index :eavt :components [:inv/color]}) (map (juxt :e :a :v))))
(pp/pprint (->> (d/datoms db {:index :aevt :components [:inv/color]}) (map (juxt :e :a :v))))
(pp/pprint (->> (d/datoms db {:index :avet :components [:inv/color]}) (map (juxt :e :a :v))))
)
(comment
(pp/pprint (d/datoms db {:index :eavt :components [:inv/color]}))
(pp/pprint (d/datoms db {:index :eavt :components [:db/ident]}))
(d/index-range db {:attrid :inv/color})
)
|
[
{
"context": ";;\n;;\n;; Copyright 2013 Netflix, Inc.\n;;\n;; Licensed under the Apache Lic",
"end": 28,
"score": 0.938123881816864,
"start": 25,
"tag": "NAME",
"value": "Net"
}
] | src/main/clojure/pigpen/local.clj | magomimmo/PigPen | 1 | ;;
;;
;; Copyright 2013 Netflix, Inc.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;;
(ns pigpen.local
"Contains functions for running PigPen locally.
Nothing in here will be used directly with normal PigPen usage.
See pigpen.core and pigpen.exec
"
(:refer-clojure :exclude [load])
(:require [clojure.edn :as edn]
[clojure.java.io :as io]
[pigpen.rx.extensions.core :refer [multicast]]
[pigpen.pig :as pig])
(:import [pigpen PigPenException]
[org.apache.pig EvalFunc]
[org.apache.pig.data Tuple DataBag DataByteArray]
[rx Observable Observer Subscription]
[rx.concurrency Schedulers]
[rx.observables GroupedObservable BlockingObservable]
[rx.util.functions Action0]
[java.util.regex Pattern]
[java.io Writer]
[java.util List]))
(set! *warn-on-reflection* true)
(defn dereference
"Pig handles tuples implicitly. This gets the first value if the field is a tuple."
([value] (dereference value 0))
([value index]
(if (instance? Tuple value)
(.get ^Tuple value index)
value)))
;; TODO add option to skip this for faster execution
(defn ^:private eval-code [{:keys [return expr args]} values]
(let [{:keys [init func]} expr
^EvalFunc instance (eval `(new ~(symbol (str "pigpen.PigPenFn" return)) ~(str init) ~(str func)))
^Tuple tuple (->> args
(map #(if ((some-fn symbol? vector?) %) (dereference (values %)) %))
(apply pig/tuple))]
(try
(.exec instance tuple)
(catch PigPenException z (throw (.getCause z))))))
(defn ^:private cross-product [data]
(if (empty? data) [{}]
(let [head (first data)]
(apply concat
(for [child (cross-product (rest data))]
(for [value head]
(merge child value)))))))
;; TODO use the script options for this
(def debug false)
(defmulti graph->local (fn [command data] (:type command)))
(defn graph->local* [{:keys [id] :as command} data]
(let [first (atom true)
data' (for [^Observable d data]
(.map d (fn [v]
(when @first
(println id "start")
(reset! first false))
v)))
^Observable o (graph->local command data')]
(-> o
(.finallyDo
(reify Action0
(call [this] (println id "stop")))))))
(defn ^:private find-next-o [observable-lookup]
(fn [command]
{:pre [(map? command)]}
(let [ancestors (map observable-lookup (:ancestors command))]
(if (every? (comp not nil?) ancestors)
(let [^Observable o ((if debug graph->local* graph->local) command (map #(%) ancestors))]
[(:id command) (multicast o (if debug (:id command)))])))))
(defn graph->observable
([commands]
{:pre [(sequential? commands)]}
(let [observable (graph->observable (->> commands
(map (juxt :id identity))
(into {}))
[])]
(observable)))
([command-lookup observables]
(if (empty? command-lookup) (second (last observables))
(let [[id _ :as o] (some (find-next-o (into {} observables)) (vals command-lookup))]
(recur (dissoc command-lookup id) (conj observables o))))))
(defn dereference-all ^Observable [^Observable o]
(.map o #(->> %
(map (fn [[k v]] [k (dereference v)]))
(into {}))))
(defn observable->clj [^Observable o]
(-> o
BlockingObservable/toIterable
seq
vec))
(defn observable->data
^Observable [^Observable o]
(-> o
(dereference-all)
(.map (comp 'value pig/thaw-values))
observable->clj))
(defn observable->raw-data
^Observable [^Observable o]
(-> o
(dereference-all)
(.map pig/thaw-anything)
observable->clj))
;; ********** Util **********
(defmethod graph->local :register [_ _]
(Observable/just nil))
(defmethod graph->local :option [_ _]
(Observable/just nil))
;; ********** IO **********
(defn load* [description read-fn]
(->
(Observable/create
(fn [^Observer o]
(let [cancel (atom false)]
(future
(try
(do
(println "Start reading from " description)
(read-fn #(.onNext o %) (fn [_] @cancel))
(.onCompleted o))
(catch Exception e (.onError o e))))
(reify Subscription
(unsubscribe [this] (reset! cancel true))))))
(.finallyDo
(reify Action0
(call [this] (println "Stop reading from " description))))
(.observeOn (Schedulers/threadPoolForIO))))
(defmulti load #(get-in % [:storage :func]))
(defmethod load "PigStorage" [{:keys [location fields storage opts]}]
(let [{:keys [cast]} opts
delimiter (-> storage :args first edn/read-string)
delimiter (if delimiter (Pattern/compile (str delimiter)) #"\t")]
(load* (str "PigStorage:" location)
(fn [on-next cancel?]
(with-open [rdr (io/reader location)]
(doseq [line (take-while (complement cancel?) (line-seq rdr))]
(on-next
(->>
(clojure.string/split line delimiter)
(map (fn [^String s] (pig/cast-bytes cast (.getBytes s))))
(zipmap fields)))))))))
(defmulti store (fn [command data] (get-in command [:storage :func])))
(defmethod store "PigStorage" [{:keys [location fields]} ^Observable data]
(let [writer (delay
(println "Start writing to PigStorage:" location)
(io/writer location))]
(-> data
(dereference-all)
(.filter
(fn [value]
(let [line (str (clojure.string/join "\t" (for [f fields] (str (f value)))) "\n")]
(.write ^Writer @writer line))
false))
(.finallyDo
(reify Action0
(call [this] (when (realized? writer)
(println "Stop writing to PigStorage:" location)
(.close ^Writer @writer))))))))
(defmethod graph->local :load [command _]
(load command))
(defmethod graph->local :store [command data]
(store command (first data)))
(defmethod graph->local :return [{:keys [^Iterable data]} _]
(Observable/from data))
;; ********** Map **********
(defmethod graph->local :projection-field [{:keys [field alias]} values]
(cond
(symbol? field) [{alias (field values)}]
(vector? field) [{alias (values field)}]
(number? field) [{alias (dereference (first (vals values)) field)}]
:else (throw (IllegalStateException. (str "Unknown field " field)))))
(defmethod graph->local :projection-func [{:keys [code alias]} values]
[{alias (eval-code code values)}])
(defmethod graph->local :projection-flat [{:keys [code alias]} values]
(let [result (eval-code code values)]
(cond
;; Following Pig logic, Bags are actually flattened
(instance? DataBag result) (for [v' result]
{alias v'})
;; While Tuples just expand their elements
(instance? Tuple result) (->>
(.getAll ^Tuple result)
(map-indexed vector)
(into {}))
:else (throw (IllegalStateException.
(str "Don't know how to flatten a " (type result)))))))
(defmethod graph->local :generate [{:keys [projections] :as command} data]
(let [^Observable data (first data)]
(.mapMany data
(fn [values]
(let [^Iterable result (->> projections
(map (fn [p] (graph->local p values)))
(cross-product))]
(Observable/from result))))))
(defn ^:private pig-compare [[key order & sort-keys] x y]
(let [r (compare (key x) (key y))]
(if (= r 0)
(if sort-keys
(recur sort-keys x y)
(int 0))
(case order
:asc r
:desc (int (- r))))))
(defmethod graph->local :order [{:keys [sort-keys]} data]
(let [^Observable data (first data)]
(-> data
(.toSortedList (partial pig-compare sort-keys))
(.mapMany #(Observable/from ^Iterable %)))))
(defmethod graph->local :rank [{:keys [sort-keys]} data]
(let [^Observable data (first data)]
(if (not-empty sort-keys)
(-> data
(.toSortedList (partial pig-compare sort-keys))
(.mapMany #(Observable/from ^Iterable (map-indexed (fn [i v] (assoc v '$0 i)) %))))
(let [i (atom -1)]
(-> data
(.map (fn [v] (assoc v '$0 (swap! i inc)))))))))
;; ********** Filter **********
(defmethod graph->local :filter [{:keys [code]} data]
(let [^Observable data (first data)]
(.filter data
(fn [values] (eval-code code values)))))
(defmethod graph->local :filter-native [{:keys [fields expr]} data]
(if-not expr (first data)
(let [^Observable data (first data)
f (eval `(fn [{:syms ~fields}] ~expr))]
(.filter data
(fn [values] (f values))))))
(defmethod graph->local :distinct [_ data]
(let [^Observable data (first data)
seen (atom [false #{}])]
(.filter data
(fn [values]
(let [[c _] (swap! seen (fn [[_ s]] [(contains? s values)
(conj s values)]))]
(not c))))))
(defmethod graph->local :limit [{:keys [n]} data]
(let [^Observable data (first data)]
(.take data n)))
(defmethod graph->local :sample [{:keys [p]} data]
(let [^Observable data (first data)]
(.filter data
(fn [values] (< (rand) p)))))
;; ********** Join **********
(defmethod graph->local :union [_ ^List data]
(Observable/merge data))
(defn ^:private graph->local-group [{:keys [ancestors keys join-types fields]} data]
(->
^List
(mapv (fn [a k ^Observable d j]
(.mapMany d (fn [values]
;; This selects all of the fields that are in this relation
(let [^Iterable result
(for [[[r] v :as f] (next fields)
:when (= r a)]
{:values (pig/tuple (values v))
;; This is to emulate the way pig handles nils
;; This changes a nil values into a relation specific nil value
:key (mapv #(or (values %) (keyword (name a) "nil")) k)
:relation f
:required (= j :required)})]
(Observable/from result)))))
ancestors keys data join-types)
(Observable/merge)
(.groupBy :key)
(.mapMany (fn [^Observable o]
(-> o
(.groupBy :relation)
(.mapMany #(-> ^Observable %
(.toList)
(.map (fn [v] [(if (keyword? (.getKey ^GroupedObservable %)) nil (.getKey ^GroupedObservable %))
(apply pig/bag (mapv :values v))]))))
;; Start with the group key. If it's a single value, flatten it.
;; Keywords are the fake nils we put in earlier
(.reduce {(first fields) (let [k (.getKey ^GroupedObservable o)
k (if (= 1 (count k)) (first k) k)
k (if (keyword? k) nil k)]
k)}
(fn [values [k v]]
(assoc values k v))))))
;; TODO This is a bad way to do inner groupings
(.filter (fn [g]
(every? identity
(map (fn [a [k] j] (or (= j :optional) (contains? g [[a] k]))) ancestors keys join-types))))))
(defn ^:private graph->local-group-all [{:keys [fields]} data]
(->
^List
(mapv (fn [[r v] ^Observable d]
(.map d (fn [values]
;; TODO clean up pig dereferencing
(let [v' (v values)]
{:values (if (instance? Tuple v') v' (pig/tuple v'))
:relation [r v]}))))
(next fields) data)
(Observable/merge)
(.groupBy :relation)
(.mapMany #(-> ^Observable %
(.toList)
(.map (fn [v] [(.getKey ^GroupedObservable %) (apply pig/bag (mapv :values v))]))))
(.reduce {(first fields) nil}
(fn [values [k v]]
(assoc values k v)))))
(defmethod graph->local :group [{:keys [keys] :as command} data]
(if (= keys [:pigpen.raw/group-all])
(graph->local-group-all command data)
(graph->local-group command data)))
(defmethod graph->local :join [{:keys [ancestors keys join-types fields]} data]
(->
^List
(mapv (fn [a k ^Observable d]
(.map d (fn [values]
;; This selects all of the fields that are in this relation
{:values (into {} (for [[[r v] :as f] fields
:when (= r a)]
[f (values v)]))
;; This is to emulate the way pig handles nils
;; This changes a nil values into a relation specific nil value
:key (mapv #(or (values %) (keyword (name a) "nil")) k)
:relation a})))
ancestors keys data)
(Observable/merge)
(.groupBy :key)
(.mapMany (fn [^Observable key-grouping]
(-> key-grouping
(.groupBy :relation)
(.mapMany #(-> ^Observable %
(.toList)
(.map (fn [v] [(.getKey ^GroupedObservable %) (map :values v)]))))
(.reduce (->>
;; This seeds the inner/outer joins, by placing a
;; defualt empty value for inner joins
(zipmap ancestors join-types)
(filter (fn [[_ j]] (= j :required)))
(map (fn [[a _]] [a []]))
(into {}))
(fn [values [k v]]
(assoc values k v)))
(.mapMany (fn [relation-grouping]
(Observable/from ^Iterable (cross-product (vals relation-grouping))))))))))
;; ********** Script **********
(defmethod graph->local :script [_ data]
(Observable/merge ^List (vec data)))
| 95010 | ;;
;;
;; Copyright 2013 <NAME>flix, Inc.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;;
(ns pigpen.local
"Contains functions for running PigPen locally.
Nothing in here will be used directly with normal PigPen usage.
See pigpen.core and pigpen.exec
"
(:refer-clojure :exclude [load])
(:require [clojure.edn :as edn]
[clojure.java.io :as io]
[pigpen.rx.extensions.core :refer [multicast]]
[pigpen.pig :as pig])
(:import [pigpen PigPenException]
[org.apache.pig EvalFunc]
[org.apache.pig.data Tuple DataBag DataByteArray]
[rx Observable Observer Subscription]
[rx.concurrency Schedulers]
[rx.observables GroupedObservable BlockingObservable]
[rx.util.functions Action0]
[java.util.regex Pattern]
[java.io Writer]
[java.util List]))
(set! *warn-on-reflection* true)
(defn dereference
"Pig handles tuples implicitly. This gets the first value if the field is a tuple."
([value] (dereference value 0))
([value index]
(if (instance? Tuple value)
(.get ^Tuple value index)
value)))
;; TODO add option to skip this for faster execution
(defn ^:private eval-code [{:keys [return expr args]} values]
(let [{:keys [init func]} expr
^EvalFunc instance (eval `(new ~(symbol (str "pigpen.PigPenFn" return)) ~(str init) ~(str func)))
^Tuple tuple (->> args
(map #(if ((some-fn symbol? vector?) %) (dereference (values %)) %))
(apply pig/tuple))]
(try
(.exec instance tuple)
(catch PigPenException z (throw (.getCause z))))))
(defn ^:private cross-product [data]
(if (empty? data) [{}]
(let [head (first data)]
(apply concat
(for [child (cross-product (rest data))]
(for [value head]
(merge child value)))))))
;; TODO use the script options for this
(def debug false)
(defmulti graph->local (fn [command data] (:type command)))
(defn graph->local* [{:keys [id] :as command} data]
(let [first (atom true)
data' (for [^Observable d data]
(.map d (fn [v]
(when @first
(println id "start")
(reset! first false))
v)))
^Observable o (graph->local command data')]
(-> o
(.finallyDo
(reify Action0
(call [this] (println id "stop")))))))
(defn ^:private find-next-o [observable-lookup]
(fn [command]
{:pre [(map? command)]}
(let [ancestors (map observable-lookup (:ancestors command))]
(if (every? (comp not nil?) ancestors)
(let [^Observable o ((if debug graph->local* graph->local) command (map #(%) ancestors))]
[(:id command) (multicast o (if debug (:id command)))])))))
(defn graph->observable
([commands]
{:pre [(sequential? commands)]}
(let [observable (graph->observable (->> commands
(map (juxt :id identity))
(into {}))
[])]
(observable)))
([command-lookup observables]
(if (empty? command-lookup) (second (last observables))
(let [[id _ :as o] (some (find-next-o (into {} observables)) (vals command-lookup))]
(recur (dissoc command-lookup id) (conj observables o))))))
(defn dereference-all ^Observable [^Observable o]
(.map o #(->> %
(map (fn [[k v]] [k (dereference v)]))
(into {}))))
(defn observable->clj [^Observable o]
(-> o
BlockingObservable/toIterable
seq
vec))
(defn observable->data
^Observable [^Observable o]
(-> o
(dereference-all)
(.map (comp 'value pig/thaw-values))
observable->clj))
(defn observable->raw-data
^Observable [^Observable o]
(-> o
(dereference-all)
(.map pig/thaw-anything)
observable->clj))
;; ********** Util **********
(defmethod graph->local :register [_ _]
(Observable/just nil))
(defmethod graph->local :option [_ _]
(Observable/just nil))
;; ********** IO **********
(defn load* [description read-fn]
(->
(Observable/create
(fn [^Observer o]
(let [cancel (atom false)]
(future
(try
(do
(println "Start reading from " description)
(read-fn #(.onNext o %) (fn [_] @cancel))
(.onCompleted o))
(catch Exception e (.onError o e))))
(reify Subscription
(unsubscribe [this] (reset! cancel true))))))
(.finallyDo
(reify Action0
(call [this] (println "Stop reading from " description))))
(.observeOn (Schedulers/threadPoolForIO))))
(defmulti load #(get-in % [:storage :func]))
(defmethod load "PigStorage" [{:keys [location fields storage opts]}]
(let [{:keys [cast]} opts
delimiter (-> storage :args first edn/read-string)
delimiter (if delimiter (Pattern/compile (str delimiter)) #"\t")]
(load* (str "PigStorage:" location)
(fn [on-next cancel?]
(with-open [rdr (io/reader location)]
(doseq [line (take-while (complement cancel?) (line-seq rdr))]
(on-next
(->>
(clojure.string/split line delimiter)
(map (fn [^String s] (pig/cast-bytes cast (.getBytes s))))
(zipmap fields)))))))))
(defmulti store (fn [command data] (get-in command [:storage :func])))
(defmethod store "PigStorage" [{:keys [location fields]} ^Observable data]
(let [writer (delay
(println "Start writing to PigStorage:" location)
(io/writer location))]
(-> data
(dereference-all)
(.filter
(fn [value]
(let [line (str (clojure.string/join "\t" (for [f fields] (str (f value)))) "\n")]
(.write ^Writer @writer line))
false))
(.finallyDo
(reify Action0
(call [this] (when (realized? writer)
(println "Stop writing to PigStorage:" location)
(.close ^Writer @writer))))))))
(defmethod graph->local :load [command _]
(load command))
(defmethod graph->local :store [command data]
(store command (first data)))
(defmethod graph->local :return [{:keys [^Iterable data]} _]
(Observable/from data))
;; ********** Map **********
(defmethod graph->local :projection-field [{:keys [field alias]} values]
(cond
(symbol? field) [{alias (field values)}]
(vector? field) [{alias (values field)}]
(number? field) [{alias (dereference (first (vals values)) field)}]
:else (throw (IllegalStateException. (str "Unknown field " field)))))
(defmethod graph->local :projection-func [{:keys [code alias]} values]
[{alias (eval-code code values)}])
(defmethod graph->local :projection-flat [{:keys [code alias]} values]
(let [result (eval-code code values)]
(cond
;; Following Pig logic, Bags are actually flattened
(instance? DataBag result) (for [v' result]
{alias v'})
;; While Tuples just expand their elements
(instance? Tuple result) (->>
(.getAll ^Tuple result)
(map-indexed vector)
(into {}))
:else (throw (IllegalStateException.
(str "Don't know how to flatten a " (type result)))))))
(defmethod graph->local :generate [{:keys [projections] :as command} data]
(let [^Observable data (first data)]
(.mapMany data
(fn [values]
(let [^Iterable result (->> projections
(map (fn [p] (graph->local p values)))
(cross-product))]
(Observable/from result))))))
(defn ^:private pig-compare [[key order & sort-keys] x y]
(let [r (compare (key x) (key y))]
(if (= r 0)
(if sort-keys
(recur sort-keys x y)
(int 0))
(case order
:asc r
:desc (int (- r))))))
(defmethod graph->local :order [{:keys [sort-keys]} data]
(let [^Observable data (first data)]
(-> data
(.toSortedList (partial pig-compare sort-keys))
(.mapMany #(Observable/from ^Iterable %)))))
(defmethod graph->local :rank [{:keys [sort-keys]} data]
(let [^Observable data (first data)]
(if (not-empty sort-keys)
(-> data
(.toSortedList (partial pig-compare sort-keys))
(.mapMany #(Observable/from ^Iterable (map-indexed (fn [i v] (assoc v '$0 i)) %))))
(let [i (atom -1)]
(-> data
(.map (fn [v] (assoc v '$0 (swap! i inc)))))))))
;; ********** Filter **********
(defmethod graph->local :filter [{:keys [code]} data]
(let [^Observable data (first data)]
(.filter data
(fn [values] (eval-code code values)))))
(defmethod graph->local :filter-native [{:keys [fields expr]} data]
(if-not expr (first data)
(let [^Observable data (first data)
f (eval `(fn [{:syms ~fields}] ~expr))]
(.filter data
(fn [values] (f values))))))
(defmethod graph->local :distinct [_ data]
(let [^Observable data (first data)
seen (atom [false #{}])]
(.filter data
(fn [values]
(let [[c _] (swap! seen (fn [[_ s]] [(contains? s values)
(conj s values)]))]
(not c))))))
(defmethod graph->local :limit [{:keys [n]} data]
(let [^Observable data (first data)]
(.take data n)))
(defmethod graph->local :sample [{:keys [p]} data]
(let [^Observable data (first data)]
(.filter data
(fn [values] (< (rand) p)))))
;; ********** Join **********
(defmethod graph->local :union [_ ^List data]
(Observable/merge data))
(defn ^:private graph->local-group [{:keys [ancestors keys join-types fields]} data]
(->
^List
(mapv (fn [a k ^Observable d j]
(.mapMany d (fn [values]
;; This selects all of the fields that are in this relation
(let [^Iterable result
(for [[[r] v :as f] (next fields)
:when (= r a)]
{:values (pig/tuple (values v))
;; This is to emulate the way pig handles nils
;; This changes a nil values into a relation specific nil value
:key (mapv #(or (values %) (keyword (name a) "nil")) k)
:relation f
:required (= j :required)})]
(Observable/from result)))))
ancestors keys data join-types)
(Observable/merge)
(.groupBy :key)
(.mapMany (fn [^Observable o]
(-> o
(.groupBy :relation)
(.mapMany #(-> ^Observable %
(.toList)
(.map (fn [v] [(if (keyword? (.getKey ^GroupedObservable %)) nil (.getKey ^GroupedObservable %))
(apply pig/bag (mapv :values v))]))))
;; Start with the group key. If it's a single value, flatten it.
;; Keywords are the fake nils we put in earlier
(.reduce {(first fields) (let [k (.getKey ^GroupedObservable o)
k (if (= 1 (count k)) (first k) k)
k (if (keyword? k) nil k)]
k)}
(fn [values [k v]]
(assoc values k v))))))
;; TODO This is a bad way to do inner groupings
(.filter (fn [g]
(every? identity
(map (fn [a [k] j] (or (= j :optional) (contains? g [[a] k]))) ancestors keys join-types))))))
(defn ^:private graph->local-group-all [{:keys [fields]} data]
(->
^List
(mapv (fn [[r v] ^Observable d]
(.map d (fn [values]
;; TODO clean up pig dereferencing
(let [v' (v values)]
{:values (if (instance? Tuple v') v' (pig/tuple v'))
:relation [r v]}))))
(next fields) data)
(Observable/merge)
(.groupBy :relation)
(.mapMany #(-> ^Observable %
(.toList)
(.map (fn [v] [(.getKey ^GroupedObservable %) (apply pig/bag (mapv :values v))]))))
(.reduce {(first fields) nil}
(fn [values [k v]]
(assoc values k v)))))
(defmethod graph->local :group [{:keys [keys] :as command} data]
(if (= keys [:pigpen.raw/group-all])
(graph->local-group-all command data)
(graph->local-group command data)))
(defmethod graph->local :join [{:keys [ancestors keys join-types fields]} data]
(->
^List
(mapv (fn [a k ^Observable d]
(.map d (fn [values]
;; This selects all of the fields that are in this relation
{:values (into {} (for [[[r v] :as f] fields
:when (= r a)]
[f (values v)]))
;; This is to emulate the way pig handles nils
;; This changes a nil values into a relation specific nil value
:key (mapv #(or (values %) (keyword (name a) "nil")) k)
:relation a})))
ancestors keys data)
(Observable/merge)
(.groupBy :key)
(.mapMany (fn [^Observable key-grouping]
(-> key-grouping
(.groupBy :relation)
(.mapMany #(-> ^Observable %
(.toList)
(.map (fn [v] [(.getKey ^GroupedObservable %) (map :values v)]))))
(.reduce (->>
;; This seeds the inner/outer joins, by placing a
;; defualt empty value for inner joins
(zipmap ancestors join-types)
(filter (fn [[_ j]] (= j :required)))
(map (fn [[a _]] [a []]))
(into {}))
(fn [values [k v]]
(assoc values k v)))
(.mapMany (fn [relation-grouping]
(Observable/from ^Iterable (cross-product (vals relation-grouping))))))))))
;; ********** Script **********
(defmethod graph->local :script [_ data]
(Observable/merge ^List (vec data)))
| true | ;;
;;
;; Copyright 2013 PI:NAME:<NAME>END_PIflix, Inc.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;;
(ns pigpen.local
"Contains functions for running PigPen locally.
Nothing in here will be used directly with normal PigPen usage.
See pigpen.core and pigpen.exec
"
(:refer-clojure :exclude [load])
(:require [clojure.edn :as edn]
[clojure.java.io :as io]
[pigpen.rx.extensions.core :refer [multicast]]
[pigpen.pig :as pig])
(:import [pigpen PigPenException]
[org.apache.pig EvalFunc]
[org.apache.pig.data Tuple DataBag DataByteArray]
[rx Observable Observer Subscription]
[rx.concurrency Schedulers]
[rx.observables GroupedObservable BlockingObservable]
[rx.util.functions Action0]
[java.util.regex Pattern]
[java.io Writer]
[java.util List]))
(set! *warn-on-reflection* true)
(defn dereference
"Pig handles tuples implicitly. This gets the first value if the field is a tuple."
([value] (dereference value 0))
([value index]
(if (instance? Tuple value)
(.get ^Tuple value index)
value)))
;; TODO add option to skip this for faster execution
(defn ^:private eval-code [{:keys [return expr args]} values]
(let [{:keys [init func]} expr
^EvalFunc instance (eval `(new ~(symbol (str "pigpen.PigPenFn" return)) ~(str init) ~(str func)))
^Tuple tuple (->> args
(map #(if ((some-fn symbol? vector?) %) (dereference (values %)) %))
(apply pig/tuple))]
(try
(.exec instance tuple)
(catch PigPenException z (throw (.getCause z))))))
(defn ^:private cross-product [data]
(if (empty? data) [{}]
(let [head (first data)]
(apply concat
(for [child (cross-product (rest data))]
(for [value head]
(merge child value)))))))
;; TODO use the script options for this
(def debug false)
(defmulti graph->local (fn [command data] (:type command)))
(defn graph->local* [{:keys [id] :as command} data]
(let [first (atom true)
data' (for [^Observable d data]
(.map d (fn [v]
(when @first
(println id "start")
(reset! first false))
v)))
^Observable o (graph->local command data')]
(-> o
(.finallyDo
(reify Action0
(call [this] (println id "stop")))))))
(defn ^:private find-next-o [observable-lookup]
(fn [command]
{:pre [(map? command)]}
(let [ancestors (map observable-lookup (:ancestors command))]
(if (every? (comp not nil?) ancestors)
(let [^Observable o ((if debug graph->local* graph->local) command (map #(%) ancestors))]
[(:id command) (multicast o (if debug (:id command)))])))))
(defn graph->observable
([commands]
{:pre [(sequential? commands)]}
(let [observable (graph->observable (->> commands
(map (juxt :id identity))
(into {}))
[])]
(observable)))
([command-lookup observables]
(if (empty? command-lookup) (second (last observables))
(let [[id _ :as o] (some (find-next-o (into {} observables)) (vals command-lookup))]
(recur (dissoc command-lookup id) (conj observables o))))))
(defn dereference-all ^Observable [^Observable o]
(.map o #(->> %
(map (fn [[k v]] [k (dereference v)]))
(into {}))))
(defn observable->clj [^Observable o]
(-> o
BlockingObservable/toIterable
seq
vec))
(defn observable->data
^Observable [^Observable o]
(-> o
(dereference-all)
(.map (comp 'value pig/thaw-values))
observable->clj))
(defn observable->raw-data
^Observable [^Observable o]
(-> o
(dereference-all)
(.map pig/thaw-anything)
observable->clj))
;; ********** Util **********
(defmethod graph->local :register [_ _]
(Observable/just nil))
(defmethod graph->local :option [_ _]
(Observable/just nil))
;; ********** IO **********
(defn load* [description read-fn]
(->
(Observable/create
(fn [^Observer o]
(let [cancel (atom false)]
(future
(try
(do
(println "Start reading from " description)
(read-fn #(.onNext o %) (fn [_] @cancel))
(.onCompleted o))
(catch Exception e (.onError o e))))
(reify Subscription
(unsubscribe [this] (reset! cancel true))))))
(.finallyDo
(reify Action0
(call [this] (println "Stop reading from " description))))
(.observeOn (Schedulers/threadPoolForIO))))
(defmulti load #(get-in % [:storage :func]))
(defmethod load "PigStorage" [{:keys [location fields storage opts]}]
(let [{:keys [cast]} opts
delimiter (-> storage :args first edn/read-string)
delimiter (if delimiter (Pattern/compile (str delimiter)) #"\t")]
(load* (str "PigStorage:" location)
(fn [on-next cancel?]
(with-open [rdr (io/reader location)]
(doseq [line (take-while (complement cancel?) (line-seq rdr))]
(on-next
(->>
(clojure.string/split line delimiter)
(map (fn [^String s] (pig/cast-bytes cast (.getBytes s))))
(zipmap fields)))))))))
(defmulti store (fn [command data] (get-in command [:storage :func])))
(defmethod store "PigStorage" [{:keys [location fields]} ^Observable data]
(let [writer (delay
(println "Start writing to PigStorage:" location)
(io/writer location))]
(-> data
(dereference-all)
(.filter
(fn [value]
(let [line (str (clojure.string/join "\t" (for [f fields] (str (f value)))) "\n")]
(.write ^Writer @writer line))
false))
(.finallyDo
(reify Action0
(call [this] (when (realized? writer)
(println "Stop writing to PigStorage:" location)
(.close ^Writer @writer))))))))
(defmethod graph->local :load [command _]
(load command))
(defmethod graph->local :store [command data]
(store command (first data)))
(defmethod graph->local :return [{:keys [^Iterable data]} _]
(Observable/from data))
;; ********** Map **********
(defmethod graph->local :projection-field [{:keys [field alias]} values]
(cond
(symbol? field) [{alias (field values)}]
(vector? field) [{alias (values field)}]
(number? field) [{alias (dereference (first (vals values)) field)}]
:else (throw (IllegalStateException. (str "Unknown field " field)))))
(defmethod graph->local :projection-func [{:keys [code alias]} values]
[{alias (eval-code code values)}])
(defmethod graph->local :projection-flat [{:keys [code alias]} values]
(let [result (eval-code code values)]
(cond
;; Following Pig logic, Bags are actually flattened
(instance? DataBag result) (for [v' result]
{alias v'})
;; While Tuples just expand their elements
(instance? Tuple result) (->>
(.getAll ^Tuple result)
(map-indexed vector)
(into {}))
:else (throw (IllegalStateException.
(str "Don't know how to flatten a " (type result)))))))
(defmethod graph->local :generate [{:keys [projections] :as command} data]
(let [^Observable data (first data)]
(.mapMany data
(fn [values]
(let [^Iterable result (->> projections
(map (fn [p] (graph->local p values)))
(cross-product))]
(Observable/from result))))))
(defn ^:private pig-compare [[key order & sort-keys] x y]
(let [r (compare (key x) (key y))]
(if (= r 0)
(if sort-keys
(recur sort-keys x y)
(int 0))
(case order
:asc r
:desc (int (- r))))))
(defmethod graph->local :order [{:keys [sort-keys]} data]
(let [^Observable data (first data)]
(-> data
(.toSortedList (partial pig-compare sort-keys))
(.mapMany #(Observable/from ^Iterable %)))))
(defmethod graph->local :rank [{:keys [sort-keys]} data]
(let [^Observable data (first data)]
(if (not-empty sort-keys)
(-> data
(.toSortedList (partial pig-compare sort-keys))
(.mapMany #(Observable/from ^Iterable (map-indexed (fn [i v] (assoc v '$0 i)) %))))
(let [i (atom -1)]
(-> data
(.map (fn [v] (assoc v '$0 (swap! i inc)))))))))
;; ********** Filter **********
(defmethod graph->local :filter [{:keys [code]} data]
(let [^Observable data (first data)]
(.filter data
(fn [values] (eval-code code values)))))
(defmethod graph->local :filter-native [{:keys [fields expr]} data]
(if-not expr (first data)
(let [^Observable data (first data)
f (eval `(fn [{:syms ~fields}] ~expr))]
(.filter data
(fn [values] (f values))))))
(defmethod graph->local :distinct [_ data]
(let [^Observable data (first data)
seen (atom [false #{}])]
(.filter data
(fn [values]
(let [[c _] (swap! seen (fn [[_ s]] [(contains? s values)
(conj s values)]))]
(not c))))))
(defmethod graph->local :limit [{:keys [n]} data]
(let [^Observable data (first data)]
(.take data n)))
(defmethod graph->local :sample [{:keys [p]} data]
(let [^Observable data (first data)]
(.filter data
(fn [values] (< (rand) p)))))
;; ********** Join **********
(defmethod graph->local :union [_ ^List data]
(Observable/merge data))
(defn ^:private graph->local-group [{:keys [ancestors keys join-types fields]} data]
(->
^List
(mapv (fn [a k ^Observable d j]
(.mapMany d (fn [values]
;; This selects all of the fields that are in this relation
(let [^Iterable result
(for [[[r] v :as f] (next fields)
:when (= r a)]
{:values (pig/tuple (values v))
;; This is to emulate the way pig handles nils
;; This changes a nil values into a relation specific nil value
:key (mapv #(or (values %) (keyword (name a) "nil")) k)
:relation f
:required (= j :required)})]
(Observable/from result)))))
ancestors keys data join-types)
(Observable/merge)
(.groupBy :key)
(.mapMany (fn [^Observable o]
(-> o
(.groupBy :relation)
(.mapMany #(-> ^Observable %
(.toList)
(.map (fn [v] [(if (keyword? (.getKey ^GroupedObservable %)) nil (.getKey ^GroupedObservable %))
(apply pig/bag (mapv :values v))]))))
;; Start with the group key. If it's a single value, flatten it.
;; Keywords are the fake nils we put in earlier
(.reduce {(first fields) (let [k (.getKey ^GroupedObservable o)
k (if (= 1 (count k)) (first k) k)
k (if (keyword? k) nil k)]
k)}
(fn [values [k v]]
(assoc values k v))))))
;; TODO This is a bad way to do inner groupings
(.filter (fn [g]
(every? identity
(map (fn [a [k] j] (or (= j :optional) (contains? g [[a] k]))) ancestors keys join-types))))))
(defn ^:private graph->local-group-all [{:keys [fields]} data]
(->
^List
(mapv (fn [[r v] ^Observable d]
(.map d (fn [values]
;; TODO clean up pig dereferencing
(let [v' (v values)]
{:values (if (instance? Tuple v') v' (pig/tuple v'))
:relation [r v]}))))
(next fields) data)
(Observable/merge)
(.groupBy :relation)
(.mapMany #(-> ^Observable %
(.toList)
(.map (fn [v] [(.getKey ^GroupedObservable %) (apply pig/bag (mapv :values v))]))))
(.reduce {(first fields) nil}
(fn [values [k v]]
(assoc values k v)))))
(defmethod graph->local :group [{:keys [keys] :as command} data]
(if (= keys [:pigpen.raw/group-all])
(graph->local-group-all command data)
(graph->local-group command data)))
(defmethod graph->local :join [{:keys [ancestors keys join-types fields]} data]
(->
^List
(mapv (fn [a k ^Observable d]
(.map d (fn [values]
;; This selects all of the fields that are in this relation
{:values (into {} (for [[[r v] :as f] fields
:when (= r a)]
[f (values v)]))
;; This is to emulate the way pig handles nils
;; This changes a nil values into a relation specific nil value
:key (mapv #(or (values %) (keyword (name a) "nil")) k)
:relation a})))
ancestors keys data)
(Observable/merge)
(.groupBy :key)
(.mapMany (fn [^Observable key-grouping]
(-> key-grouping
(.groupBy :relation)
(.mapMany #(-> ^Observable %
(.toList)
(.map (fn [v] [(.getKey ^GroupedObservable %) (map :values v)]))))
(.reduce (->>
;; This seeds the inner/outer joins, by placing a
;; defualt empty value for inner joins
(zipmap ancestors join-types)
(filter (fn [[_ j]] (= j :required)))
(map (fn [[a _]] [a []]))
(into {}))
(fn [values [k v]]
(assoc values k v)))
(.mapMany (fn [relation-grouping]
(Observable/from ^Iterable (cross-product (vals relation-grouping))))))))))
;; ********** Script **********
(defmethod graph->local :script [_ data]
(Observable/merge ^List (vec data)))
|
[
{
"context": "name-goes-as-password\n (is (not (authenticate \"zxcv\" \"notvalid\"))))\n\n(deftest not-username-fails-as-p",
"end": 148,
"score": 0.7933185696601868,
"start": 144,
"tag": "USERNAME",
"value": "zxcv"
},
{
"context": "rname-fails-as-password\n (is (not (authenticate \"Esko\" \"esko2\"))))\n\n(deftest not-existing-username-fail",
"end": 236,
"score": 0.986555278301239,
"start": 232,
"tag": "USERNAME",
"value": "Esko"
},
{
"context": "ails-as-password\n (is (not (authenticate \"Esko\" \"esko2\"))))\n\n(deftest not-existing-username-fails-as-pas",
"end": 244,
"score": 0.7099063992500305,
"start": 239,
"tag": "PASSWORD",
"value": "esko2"
},
{
"context": "rname-fails-as-password\n (is (not (authenticate \"Esko2\" \"esko2\"))))\n\n(deftest auth-token-can-be-decrypte",
"end": 331,
"score": 0.9051188230514526,
"start": 326,
"tag": "USERNAME",
"value": "Esko2"
},
{
"context": "ils-as-password\n (is (not (authenticate \"Esko2\" \"esko2\"))))\n\n(deftest auth-token-can-be-decrypted\n (is ",
"end": 339,
"score": 0.7462155818939209,
"start": 334,
"tag": "PASSWORD",
"value": "esko2"
},
{
"context": " \"Esko|RXNrbw##\" (decrypt (auth-token {:username \"Esko\" :passwordHash \"RXNrbw##\"})))))\n",
"end": 445,
"score": 0.9976489543914795,
"start": 441,
"tag": "USERNAME",
"value": "Esko"
},
{
"context": "rypt (auth-token {:username \"Esko\" :passwordHash \"RXNrbw##\"})))))\n",
"end": 468,
"score": 0.9984540939331055,
"start": 462,
"tag": "PASSWORD",
"value": "RXNrbw"
}
] | test/ontrail/test/auth.clj | jrosti/ontrail | 1 | (ns ontrail.test.auth
(:use [ontrail auth user crypto]
clojure.test))
(deftest username-goes-as-password
(is (not (authenticate "zxcv" "notvalid"))))
(deftest not-username-fails-as-password
(is (not (authenticate "Esko" "esko2"))))
(deftest not-existing-username-fails-as-password
(is (not (authenticate "Esko2" "esko2"))))
(deftest auth-token-can-be-decrypted
(is (= "Esko|RXNrbw##" (decrypt (auth-token {:username "Esko" :passwordHash "RXNrbw##"})))))
| 87685 | (ns ontrail.test.auth
(:use [ontrail auth user crypto]
clojure.test))
(deftest username-goes-as-password
(is (not (authenticate "zxcv" "notvalid"))))
(deftest not-username-fails-as-password
(is (not (authenticate "Esko" "<PASSWORD>"))))
(deftest not-existing-username-fails-as-password
(is (not (authenticate "Esko2" "<PASSWORD>"))))
(deftest auth-token-can-be-decrypted
(is (= "Esko|RXNrbw##" (decrypt (auth-token {:username "Esko" :passwordHash "<PASSWORD>##"})))))
| true | (ns ontrail.test.auth
(:use [ontrail auth user crypto]
clojure.test))
(deftest username-goes-as-password
(is (not (authenticate "zxcv" "notvalid"))))
(deftest not-username-fails-as-password
(is (not (authenticate "Esko" "PI:PASSWORD:<PASSWORD>END_PI"))))
(deftest not-existing-username-fails-as-password
(is (not (authenticate "Esko2" "PI:PASSWORD:<PASSWORD>END_PI"))))
(deftest auth-token-can-be-decrypted
(is (= "Esko|RXNrbw##" (decrypt (auth-token {:username "Esko" :passwordHash "PI:PASSWORD:<PASSWORD>END_PI##"})))))
|
[
{
"context": "e record\"\n (let [org (org/create {:user-email \"esau@sand.org\" :user-name \"esau\" :name \"nilenso\"}) ;; creating ",
"end": 631,
"score": 0.9999184608459473,
"start": 618,
"tag": "EMAIL",
"value": "esau@sand.org"
},
{
"context": "g/create {:user-email \"esau@sand.org\" :user-name \"esau\" :name \"nilenso\"}) ;; creating an admin user\n ",
"end": 649,
"score": 0.9286391735076904,
"start": 645,
"tag": "USERNAME",
"value": "esau"
},
{
"context": "er-email \"esau@sand.org\" :user-name \"esau\" :name \"nilenso\"}) ;; creating an admin user\n oru (org/",
"end": 665,
"score": 0.8977410793304443,
"start": 658,
"tag": "USERNAME",
"value": "nilenso"
},
{
"context": "r\n oru (org/member-user-create {:email \"jacob@sand.org\"\n :organiz",
"end": 757,
"score": 0.9999117851257324,
"start": 743,
"tag": "EMAIL",
"value": "jacob@sand.org"
},
{
"context": " :password \"foobar\"})\n user (count (users/lookup-by-id (:us",
"end": 885,
"score": 0.999479353427887,
"start": 879,
"tag": "PASSWORD",
"value": "foobar"
}
] | test/kulu_backend/users/model_test.clj | vkrmis/kulu-backend | 3 | (ns kulu-backend.users.model-test
(:require [conjure.core :refer :all]
[kulu-backend.db :as db]
[kulu-backend.users.model :as users]
[kulu-backend.organizations.model :as org]
[kulu-backend.test-helper :refer :all]
[clojure.test :refer :all]))
(use-fixtures :each isolate-db)
(use-fixtures :once (join-fixtures [set-test-env
migrate-test-db
silence-logging]))
(deftest create-a-member-user
(testing "creates a user and a join table record"
(let [org (org/create {:user-email "esau@sand.org" :user-name "esau" :name "nilenso"}) ;; creating an admin user
oru (org/member-user-create {:email "jacob@sand.org"
:organization_name "nilenso"
:password "foobar"})
user (count (users/lookup-by-id (:user_id oru)))
org-count (count (org/all))]
(is (= 1 org-count)))))
| 11891 | (ns kulu-backend.users.model-test
(:require [conjure.core :refer :all]
[kulu-backend.db :as db]
[kulu-backend.users.model :as users]
[kulu-backend.organizations.model :as org]
[kulu-backend.test-helper :refer :all]
[clojure.test :refer :all]))
(use-fixtures :each isolate-db)
(use-fixtures :once (join-fixtures [set-test-env
migrate-test-db
silence-logging]))
(deftest create-a-member-user
(testing "creates a user and a join table record"
(let [org (org/create {:user-email "<EMAIL>" :user-name "esau" :name "nilenso"}) ;; creating an admin user
oru (org/member-user-create {:email "<EMAIL>"
:organization_name "nilenso"
:password "<PASSWORD>"})
user (count (users/lookup-by-id (:user_id oru)))
org-count (count (org/all))]
(is (= 1 org-count)))))
| true | (ns kulu-backend.users.model-test
(:require [conjure.core :refer :all]
[kulu-backend.db :as db]
[kulu-backend.users.model :as users]
[kulu-backend.organizations.model :as org]
[kulu-backend.test-helper :refer :all]
[clojure.test :refer :all]))
(use-fixtures :each isolate-db)
(use-fixtures :once (join-fixtures [set-test-env
migrate-test-db
silence-logging]))
(deftest create-a-member-user
(testing "creates a user and a join table record"
(let [org (org/create {:user-email "PI:EMAIL:<EMAIL>END_PI" :user-name "esau" :name "nilenso"}) ;; creating an admin user
oru (org/member-user-create {:email "PI:EMAIL:<EMAIL>END_PI"
:organization_name "nilenso"
:password "PI:PASSWORD:<PASSWORD>END_PI"})
user (count (users/lookup-by-id (:user_id oru)))
org-count (count (org/all))]
(is (= 1 org-count)))))
|
[
{
"context": "\n; ;; Receiver-Schedules objects\n; [{:signal-key \"test-receiver\"\n; :receiver-schedule {:schedule-type ",
"end": 319,
"score": 0.533907413482666,
"start": 315,
"tag": "KEY",
"value": "test"
}
] | Software-Projects/service-orchestrator/src/xtrax/service_orchestrator/scheduler/receiver_scheduler.clj | briancabbott/xtrax | 2 | (ns xtrax.service-orchestrator.scheduler.receiver-scheduler
(:require [clj-time.types :refer [date-time?]]
[xtrax.service-orchestrator.receiver-coordinator :as coordinator]
[xtrax.service-orchestrator.db.data-store.core :as data-store]))
;
; ;; Receiver-Schedules objects
; [{:signal-key "test-receiver"
; :receiver-schedule {:schedule-type (:single-instance | :continuous)
; :first-run-on (:now | DateTimeObject) ;; Optional when type is continuous...
; ;; Only valid for :continuous operations
; :rest-run-on {:repeat-every {:value 1 :scale (:second | :minute | :hour | :day | :week | :month | :year)}
; :repeat-on (:monday :tuesday :wednesday :thursday :friday :saturday :sunday)
; :ends-on (:never {:on DateTime Object} {:after DateTimeObject})}}}]
;
(declare is-receiver-schedule-valid?)
(defn create-new-receiver-schedule
"Create a new Receiver-Schedule Record in the configured Datra-Store and, if
its first start-time is within the current orchestration-executor's
scheduling-period, start it."
[receiver-schedule-object]
(if (is-receiver-schedule-valid? receiver-schedule-object)
(do
(data-store/persist-object :receiver-schedule-object receiver-schedule-object)
(coordinator/check-execute-on-scheduler receiver-schedule-object))
(do
;; throw an exception
(throw (ex-info "Recevier-Schedule Object failed validation" {})))))
(defn is-receiver-schedule-valid? [receiver-schedule-object]
(if (not (nil? receiver-schedule-object))
(let [receiver-schedule (:receiver-schedule receiver-schedule-object)
schedule-type (:schedule-type receiver-schedule)
first-run (:first-run-on receiver-schedule)
rest-run (:rest-run-on receiver-schedule)
repeat-scale (-> rest-run :repeat-every :scale)
repeat-value (-> rest-run :repeat-every :value)
repeat-on (-> rest-run :repeat-on)
repeat-scale-valid? (or
(= repeat-scale :second)
(= repeat-scale :minute)
(= repeat-scale :hour)
(= repeat-scale :day)
(= repeat-scale :week)
(= repeat-scale :month)
(= repeat-scale :year))
repeat-value-valid? (and repeat-scale-valid? (> repeat-value 0))
ends-on (-> rest-run :ends-on)
ends-on-has-on-term? (and (map? ends-on) (contains? ends-on :on) (date-time? (:on ends-on)))
ends-on-has-after-term? (and (map? ends-on) (contains? ends-on :after) (date-time? (:after ends-on)))]
(let [schedule-type-valid? (or (= schedule-type :single-instance) (= schedule-type :continuous))
first-run-on-valid? (or (= first-run :now) (date-time? first-run))
repeat-on-valid? (and
(and
(not repeat-scale-valid?)
(not repeat-value-valid?))
(or (= repeat-on :monday)
(= repeat-on :tuesday)
(= repeat-on :wednesday)
(= repeat-on :thursday)
(= repeat-on :friday)
(= repeat-on :saturday)
(= repeat-on :sunday)))
ends-on-valid? (or
(and
(= ends-on :never)
(not ends-on-has-on-term?)
(not ends-on-has-after-term?))
(and
ends-on-has-on-term?
(not ends-on-has-after-term?))
(and
ends-on-has-after-term?
(not ends-on-has-on-term?)))]
(and schedule-type-valid? first-run-on-valid? repeat-on-valid? ends-on-valid?)))
false))
| 53741 | (ns xtrax.service-orchestrator.scheduler.receiver-scheduler
(:require [clj-time.types :refer [date-time?]]
[xtrax.service-orchestrator.receiver-coordinator :as coordinator]
[xtrax.service-orchestrator.db.data-store.core :as data-store]))
;
; ;; Receiver-Schedules objects
; [{:signal-key "<KEY>-receiver"
; :receiver-schedule {:schedule-type (:single-instance | :continuous)
; :first-run-on (:now | DateTimeObject) ;; Optional when type is continuous...
; ;; Only valid for :continuous operations
; :rest-run-on {:repeat-every {:value 1 :scale (:second | :minute | :hour | :day | :week | :month | :year)}
; :repeat-on (:monday :tuesday :wednesday :thursday :friday :saturday :sunday)
; :ends-on (:never {:on DateTime Object} {:after DateTimeObject})}}}]
;
(declare is-receiver-schedule-valid?)
(defn create-new-receiver-schedule
"Create a new Receiver-Schedule Record in the configured Datra-Store and, if
its first start-time is within the current orchestration-executor's
scheduling-period, start it."
[receiver-schedule-object]
(if (is-receiver-schedule-valid? receiver-schedule-object)
(do
(data-store/persist-object :receiver-schedule-object receiver-schedule-object)
(coordinator/check-execute-on-scheduler receiver-schedule-object))
(do
;; throw an exception
(throw (ex-info "Recevier-Schedule Object failed validation" {})))))
(defn is-receiver-schedule-valid? [receiver-schedule-object]
(if (not (nil? receiver-schedule-object))
(let [receiver-schedule (:receiver-schedule receiver-schedule-object)
schedule-type (:schedule-type receiver-schedule)
first-run (:first-run-on receiver-schedule)
rest-run (:rest-run-on receiver-schedule)
repeat-scale (-> rest-run :repeat-every :scale)
repeat-value (-> rest-run :repeat-every :value)
repeat-on (-> rest-run :repeat-on)
repeat-scale-valid? (or
(= repeat-scale :second)
(= repeat-scale :minute)
(= repeat-scale :hour)
(= repeat-scale :day)
(= repeat-scale :week)
(= repeat-scale :month)
(= repeat-scale :year))
repeat-value-valid? (and repeat-scale-valid? (> repeat-value 0))
ends-on (-> rest-run :ends-on)
ends-on-has-on-term? (and (map? ends-on) (contains? ends-on :on) (date-time? (:on ends-on)))
ends-on-has-after-term? (and (map? ends-on) (contains? ends-on :after) (date-time? (:after ends-on)))]
(let [schedule-type-valid? (or (= schedule-type :single-instance) (= schedule-type :continuous))
first-run-on-valid? (or (= first-run :now) (date-time? first-run))
repeat-on-valid? (and
(and
(not repeat-scale-valid?)
(not repeat-value-valid?))
(or (= repeat-on :monday)
(= repeat-on :tuesday)
(= repeat-on :wednesday)
(= repeat-on :thursday)
(= repeat-on :friday)
(= repeat-on :saturday)
(= repeat-on :sunday)))
ends-on-valid? (or
(and
(= ends-on :never)
(not ends-on-has-on-term?)
(not ends-on-has-after-term?))
(and
ends-on-has-on-term?
(not ends-on-has-after-term?))
(and
ends-on-has-after-term?
(not ends-on-has-on-term?)))]
(and schedule-type-valid? first-run-on-valid? repeat-on-valid? ends-on-valid?)))
false))
| true | (ns xtrax.service-orchestrator.scheduler.receiver-scheduler
(:require [clj-time.types :refer [date-time?]]
[xtrax.service-orchestrator.receiver-coordinator :as coordinator]
[xtrax.service-orchestrator.db.data-store.core :as data-store]))
;
; ;; Receiver-Schedules objects
; [{:signal-key "PI:KEY:<KEY>END_PI-receiver"
; :receiver-schedule {:schedule-type (:single-instance | :continuous)
; :first-run-on (:now | DateTimeObject) ;; Optional when type is continuous...
; ;; Only valid for :continuous operations
; :rest-run-on {:repeat-every {:value 1 :scale (:second | :minute | :hour | :day | :week | :month | :year)}
; :repeat-on (:monday :tuesday :wednesday :thursday :friday :saturday :sunday)
; :ends-on (:never {:on DateTime Object} {:after DateTimeObject})}}}]
;
(declare is-receiver-schedule-valid?)
(defn create-new-receiver-schedule
"Create a new Receiver-Schedule Record in the configured Datra-Store and, if
its first start-time is within the current orchestration-executor's
scheduling-period, start it."
[receiver-schedule-object]
(if (is-receiver-schedule-valid? receiver-schedule-object)
(do
(data-store/persist-object :receiver-schedule-object receiver-schedule-object)
(coordinator/check-execute-on-scheduler receiver-schedule-object))
(do
;; throw an exception
(throw (ex-info "Recevier-Schedule Object failed validation" {})))))
(defn is-receiver-schedule-valid? [receiver-schedule-object]
(if (not (nil? receiver-schedule-object))
(let [receiver-schedule (:receiver-schedule receiver-schedule-object)
schedule-type (:schedule-type receiver-schedule)
first-run (:first-run-on receiver-schedule)
rest-run (:rest-run-on receiver-schedule)
repeat-scale (-> rest-run :repeat-every :scale)
repeat-value (-> rest-run :repeat-every :value)
repeat-on (-> rest-run :repeat-on)
repeat-scale-valid? (or
(= repeat-scale :second)
(= repeat-scale :minute)
(= repeat-scale :hour)
(= repeat-scale :day)
(= repeat-scale :week)
(= repeat-scale :month)
(= repeat-scale :year))
repeat-value-valid? (and repeat-scale-valid? (> repeat-value 0))
ends-on (-> rest-run :ends-on)
ends-on-has-on-term? (and (map? ends-on) (contains? ends-on :on) (date-time? (:on ends-on)))
ends-on-has-after-term? (and (map? ends-on) (contains? ends-on :after) (date-time? (:after ends-on)))]
(let [schedule-type-valid? (or (= schedule-type :single-instance) (= schedule-type :continuous))
first-run-on-valid? (or (= first-run :now) (date-time? first-run))
repeat-on-valid? (and
(and
(not repeat-scale-valid?)
(not repeat-value-valid?))
(or (= repeat-on :monday)
(= repeat-on :tuesday)
(= repeat-on :wednesday)
(= repeat-on :thursday)
(= repeat-on :friday)
(= repeat-on :saturday)
(= repeat-on :sunday)))
ends-on-valid? (or
(and
(= ends-on :never)
(not ends-on-has-on-term?)
(not ends-on-has-after-term?))
(and
ends-on-has-on-term?
(not ends-on-has-after-term?))
(and
ends-on-has-after-term?
(not ends-on-has-on-term?)))]
(and schedule-type-valid? first-run-on-valid? repeat-on-valid? ends-on-valid?)))
false))
|
[
{
"context": ";; Copyright 2014-2020 King\n;; Copyright 2009-2014 Ragnar Svensson, Christian Murray\n;; Licensed under the Defold Li",
"end": 111,
"score": 0.9998161792755127,
"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.999819278717041,
"start": 113,
"tag": "NAME",
"value": "Christian Murray"
}
] | editor/src/clj/editor/core.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.core
"Essential node types"
(:require [clojure.set :as set]
[cognitect.transit :as transit]
[dynamo.graph :as g]
[editor.types :as types]))
(set! *warn-on-reflection* true)
;; ---------------------------------------------------------------------------
;; Copy/paste support
;; ---------------------------------------------------------------------------
(def ^:dynamic *serialization-handlers*
{:read {"class" (transit/read-handler
(fn [rep] (java.lang.Class/forName ^String rep)))}
:write {java.lang.Class (transit/write-handler
(constantly "class")
(fn [^Class v] (.getName v)))}})
(defn register-read-handler!
[tag handler]
(alter-var-root #'*serialization-handlers* assoc-in [:read tag] handler))
(defn register-write-handler!
[class handler]
(alter-var-root #'*serialization-handlers* assoc-in [:write class] handler))
(defn register-record-type!
[type]
(alter-var-root #'*serialization-handlers*
#(-> %
(update :read merge (transit/record-read-handlers type))
(update :write merge (transit/record-write-handlers type)))))
(defn read-handlers [] (:read *serialization-handlers*))
(defn write-handlers [] (:write *serialization-handlers*))
;; ---------------------------------------------------------------------------
;; Bootstrapping the core node types
;; ---------------------------------------------------------------------------
(g/defnode Scope
"Scope provides a level of grouping for nodes. Scopes nest.
When a node is added to a Scope, the node's :_node-id output will be
connected to the Scope's :nodes input.
When a Scope is deleted, all nodes within that scope will also be deleted."
(input nodes g/Any :array :cascade-delete))
(defn scope
([node-id]
(scope (g/now) node-id))
([basis node-id]
(assert (some? node-id))
(let [[_ _ scope _] (first
(filter
(fn [[src src-lbl tgt tgt-lbl]]
(and (= src-lbl :_node-id)
(= tgt-lbl :nodes)))
(g/outputs basis node-id)))]
scope)))
(defn scope-of-type
([node-id node-type]
(scope-of-type (g/now) node-id node-type))
([basis node-id node-type]
(when-let [scope-id (scope basis node-id)]
(if (g/node-instance? basis node-type scope-id)
scope-id
(recur basis scope-id node-type)))))
(g/defnode Saveable
"Mixin. Content root nodes (i.e., top level nodes for an editor tab) can inherit
this node to indicate that 'Save' is a meaningful action.
Inheritors are required to supply a production function for the :save output."
(output save g/Keyword :abstract))
(g/defnode ResourceNode
"Mixin. Any node loaded from the filesystem should inherit this."
(property filename types/PathManipulation (dynamic visible (g/constantly false)))
(output content g/Any :abstract))
(g/defnode OutlineNode
"Mixin. Any OutlineNode can be shown in an outline view.
Inputs:
- children `[OutlineItem]` - Input values that will be nested beneath this node.
Outputs:
- tree `OutlineItem` - A single value that contains the display info for this node and all its children."
(output outline-children [types/OutlineItem] (g/constantly []))
(output outline-label g/Str :abstract)
(output outline-commands [types/OutlineCommand] (g/constantly []))
(output outline-tree types/OutlineItem
(g/fnk [_node-id outline-label outline-commands outline-children]
{:label outline-label
;; :icon "my type of icon"
:node-ref _node-id
:commands outline-commands
:children outline-children})))
(defprotocol Adaptable
(adapt [this t]))
| 53631 | ;; 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.core
"Essential node types"
(:require [clojure.set :as set]
[cognitect.transit :as transit]
[dynamo.graph :as g]
[editor.types :as types]))
(set! *warn-on-reflection* true)
;; ---------------------------------------------------------------------------
;; Copy/paste support
;; ---------------------------------------------------------------------------
(def ^:dynamic *serialization-handlers*
{:read {"class" (transit/read-handler
(fn [rep] (java.lang.Class/forName ^String rep)))}
:write {java.lang.Class (transit/write-handler
(constantly "class")
(fn [^Class v] (.getName v)))}})
(defn register-read-handler!
[tag handler]
(alter-var-root #'*serialization-handlers* assoc-in [:read tag] handler))
(defn register-write-handler!
[class handler]
(alter-var-root #'*serialization-handlers* assoc-in [:write class] handler))
(defn register-record-type!
[type]
(alter-var-root #'*serialization-handlers*
#(-> %
(update :read merge (transit/record-read-handlers type))
(update :write merge (transit/record-write-handlers type)))))
(defn read-handlers [] (:read *serialization-handlers*))
(defn write-handlers [] (:write *serialization-handlers*))
;; ---------------------------------------------------------------------------
;; Bootstrapping the core node types
;; ---------------------------------------------------------------------------
(g/defnode Scope
"Scope provides a level of grouping for nodes. Scopes nest.
When a node is added to a Scope, the node's :_node-id output will be
connected to the Scope's :nodes input.
When a Scope is deleted, all nodes within that scope will also be deleted."
(input nodes g/Any :array :cascade-delete))
(defn scope
([node-id]
(scope (g/now) node-id))
([basis node-id]
(assert (some? node-id))
(let [[_ _ scope _] (first
(filter
(fn [[src src-lbl tgt tgt-lbl]]
(and (= src-lbl :_node-id)
(= tgt-lbl :nodes)))
(g/outputs basis node-id)))]
scope)))
(defn scope-of-type
([node-id node-type]
(scope-of-type (g/now) node-id node-type))
([basis node-id node-type]
(when-let [scope-id (scope basis node-id)]
(if (g/node-instance? basis node-type scope-id)
scope-id
(recur basis scope-id node-type)))))
(g/defnode Saveable
"Mixin. Content root nodes (i.e., top level nodes for an editor tab) can inherit
this node to indicate that 'Save' is a meaningful action.
Inheritors are required to supply a production function for the :save output."
(output save g/Keyword :abstract))
(g/defnode ResourceNode
"Mixin. Any node loaded from the filesystem should inherit this."
(property filename types/PathManipulation (dynamic visible (g/constantly false)))
(output content g/Any :abstract))
(g/defnode OutlineNode
"Mixin. Any OutlineNode can be shown in an outline view.
Inputs:
- children `[OutlineItem]` - Input values that will be nested beneath this node.
Outputs:
- tree `OutlineItem` - A single value that contains the display info for this node and all its children."
(output outline-children [types/OutlineItem] (g/constantly []))
(output outline-label g/Str :abstract)
(output outline-commands [types/OutlineCommand] (g/constantly []))
(output outline-tree types/OutlineItem
(g/fnk [_node-id outline-label outline-commands outline-children]
{:label outline-label
;; :icon "my type of icon"
:node-ref _node-id
:commands outline-commands
:children outline-children})))
(defprotocol Adaptable
(adapt [this t]))
| 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.core
"Essential node types"
(:require [clojure.set :as set]
[cognitect.transit :as transit]
[dynamo.graph :as g]
[editor.types :as types]))
(set! *warn-on-reflection* true)
;; ---------------------------------------------------------------------------
;; Copy/paste support
;; ---------------------------------------------------------------------------
(def ^:dynamic *serialization-handlers*
{:read {"class" (transit/read-handler
(fn [rep] (java.lang.Class/forName ^String rep)))}
:write {java.lang.Class (transit/write-handler
(constantly "class")
(fn [^Class v] (.getName v)))}})
(defn register-read-handler!
[tag handler]
(alter-var-root #'*serialization-handlers* assoc-in [:read tag] handler))
(defn register-write-handler!
[class handler]
(alter-var-root #'*serialization-handlers* assoc-in [:write class] handler))
(defn register-record-type!
[type]
(alter-var-root #'*serialization-handlers*
#(-> %
(update :read merge (transit/record-read-handlers type))
(update :write merge (transit/record-write-handlers type)))))
(defn read-handlers [] (:read *serialization-handlers*))
(defn write-handlers [] (:write *serialization-handlers*))
;; ---------------------------------------------------------------------------
;; Bootstrapping the core node types
;; ---------------------------------------------------------------------------
(g/defnode Scope
"Scope provides a level of grouping for nodes. Scopes nest.
When a node is added to a Scope, the node's :_node-id output will be
connected to the Scope's :nodes input.
When a Scope is deleted, all nodes within that scope will also be deleted."
(input nodes g/Any :array :cascade-delete))
(defn scope
([node-id]
(scope (g/now) node-id))
([basis node-id]
(assert (some? node-id))
(let [[_ _ scope _] (first
(filter
(fn [[src src-lbl tgt tgt-lbl]]
(and (= src-lbl :_node-id)
(= tgt-lbl :nodes)))
(g/outputs basis node-id)))]
scope)))
(defn scope-of-type
([node-id node-type]
(scope-of-type (g/now) node-id node-type))
([basis node-id node-type]
(when-let [scope-id (scope basis node-id)]
(if (g/node-instance? basis node-type scope-id)
scope-id
(recur basis scope-id node-type)))))
(g/defnode Saveable
"Mixin. Content root nodes (i.e., top level nodes for an editor tab) can inherit
this node to indicate that 'Save' is a meaningful action.
Inheritors are required to supply a production function for the :save output."
(output save g/Keyword :abstract))
(g/defnode ResourceNode
"Mixin. Any node loaded from the filesystem should inherit this."
(property filename types/PathManipulation (dynamic visible (g/constantly false)))
(output content g/Any :abstract))
(g/defnode OutlineNode
"Mixin. Any OutlineNode can be shown in an outline view.
Inputs:
- children `[OutlineItem]` - Input values that will be nested beneath this node.
Outputs:
- tree `OutlineItem` - A single value that contains the display info for this node and all its children."
(output outline-children [types/OutlineItem] (g/constantly []))
(output outline-label g/Str :abstract)
(output outline-commands [types/OutlineCommand] (g/constantly []))
(output outline-tree types/OutlineItem
(g/fnk [_node-id outline-label outline-commands outline-children]
{:label outline-label
;; :icon "my type of icon"
:node-ref _node-id
:commands outline-commands
:children outline-children})))
(defprotocol Adaptable
(adapt [this t]))
|
[
{
"context": "\"Email\"] [:th \"age\"]]\r\n [:tr [:td \"1\"] [:td \"Milos\"] [:td \"Marinkovic\"] [:td \"marinkovicmilos@gmail.",
"end": 659,
"score": 0.9997867941856384,
"start": 654,
"tag": "NAME",
"value": "Milos"
},
{
"context": "\"age\"]]\r\n [:tr [:td \"1\"] [:td \"Milos\"] [:td \"Marinkovic\"] [:td \"marinkovicmilos@gmail.com\"] [:td \"26\"]]\r\n",
"end": 678,
"score": 0.9997571706771851,
"start": 668,
"tag": "NAME",
"value": "Marinkovic"
},
{
"context": " [:td \"1\"] [:td \"Milos\"] [:td \"Marinkovic\"] [:td \"marinkovicmilos@gmail.com\"] [:td \"26\"]]\r\n [:tr [:td \"2\"] [:td \"Matija\"",
"end": 712,
"score": 0.9999288320541382,
"start": 687,
"tag": "EMAIL",
"value": "marinkovicmilos@gmail.com"
},
{
"context": "ail.com\"] [:td \"26\"]]\r\n [:tr [:td \"2\"] [:td \"Matija\"] [:td \"Marjanovic\"] [:td \"marjanovicmatija@gmail",
"end": 761,
"score": 0.9997269511222839,
"start": 755,
"tag": "NAME",
"value": "Matija"
},
{
"context": "\"26\"]]\r\n [:tr [:td \"2\"] [:td \"Matija\"] [:td \"Marjanovic\"] [:td \"marjanovicmatija@gmail.com\"] [:td \"25\"]]]",
"end": 780,
"score": 0.9997731447219849,
"start": 770,
"tag": "NAME",
"value": "Marjanovic"
},
{
"context": "[:td \"2\"] [:td \"Matija\"] [:td \"Marjanovic\"] [:td \"marjanovicmatija@gmail.com\"] [:td \"25\"]]]))\r\n\r\n",
"end": 815,
"score": 0.999929666519165,
"start": 789,
"tag": "EMAIL",
"value": "marjanovicmatija@gmail.com"
}
] | src/views/customerview.clj | marinkovicmilos/practice-clojure | 0 | (ns views.customerview
(:require [clojure.string :as str]
[hiccup.page :as page]))
(defn gen-page-head
[title]
[:head
[:title (str "Customers: " title)]])
(def header-links
[:div#header-links
"[ "
[:a {:href "/"} "Home"]
" | "
[:a {:href "/add-customer"} "Add a customer"]
" | "
[:a {:href "/customers"} "View all customers"]
" ]"])
(defn all-customers-page
[]
(page/html5
(gen-page-head "Add a Customer")
header-links
[:h1 "All Customers"]
[:table
[:tr [:th "id"] [:th "First Name"] [:th "Last Name"] [:th "Email"] [:th "age"]]
[:tr [:td "1"] [:td "Milos"] [:td "Marinkovic"] [:td "marinkovicmilos@gmail.com"] [:td "26"]]
[:tr [:td "2"] [:td "Matija"] [:td "Marjanovic"] [:td "marjanovicmatija@gmail.com"] [:td "25"]]]))
| 37216 | (ns views.customerview
(:require [clojure.string :as str]
[hiccup.page :as page]))
(defn gen-page-head
[title]
[:head
[:title (str "Customers: " title)]])
(def header-links
[:div#header-links
"[ "
[:a {:href "/"} "Home"]
" | "
[:a {:href "/add-customer"} "Add a customer"]
" | "
[:a {:href "/customers"} "View all customers"]
" ]"])
(defn all-customers-page
[]
(page/html5
(gen-page-head "Add a Customer")
header-links
[:h1 "All Customers"]
[:table
[:tr [:th "id"] [:th "First Name"] [:th "Last Name"] [:th "Email"] [:th "age"]]
[:tr [:td "1"] [:td "<NAME>"] [:td "<NAME>"] [:td "<EMAIL>"] [:td "26"]]
[:tr [:td "2"] [:td "<NAME>"] [:td "<NAME>"] [:td "<EMAIL>"] [:td "25"]]]))
| true | (ns views.customerview
(:require [clojure.string :as str]
[hiccup.page :as page]))
(defn gen-page-head
[title]
[:head
[:title (str "Customers: " title)]])
(def header-links
[:div#header-links
"[ "
[:a {:href "/"} "Home"]
" | "
[:a {:href "/add-customer"} "Add a customer"]
" | "
[:a {:href "/customers"} "View all customers"]
" ]"])
(defn all-customers-page
[]
(page/html5
(gen-page-head "Add a Customer")
header-links
[:h1 "All Customers"]
[:table
[:tr [:th "id"] [:th "First Name"] [:th "Last Name"] [:th "Email"] [:th "age"]]
[:tr [:td "1"] [:td "PI:NAME:<NAME>END_PI"] [:td "PI:NAME:<NAME>END_PI"] [:td "PI:EMAIL:<EMAIL>END_PI"] [:td "26"]]
[:tr [:td "2"] [:td "PI:NAME:<NAME>END_PI"] [:td "PI:NAME:<NAME>END_PI"] [:td "PI:EMAIL:<EMAIL>END_PI"] [:td "25"]]]))
|
[
{
"context": ";; Original author Hirokuni Kim\n;; Modifications by Kevin Kredit\n;; Licensed unde",
"end": 31,
"score": 0.9997705817222595,
"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.9998779296875,
"start": 52,
"tag": "NAME",
"value": "Kevin Kredit"
}
] | clojure/p07-closure/src/p07_closure/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/#closure
(ns p07-closure.core)
(defn inner
[from-outer]
(fn [] (println from-outer)))
(defn -main
"Main"
[]
(def outer1 (inner "this is from outer"))
(def outer2 (inner "this is yet another from outer"))
(outer1)
(outer2)
)
| 46707 | ;; Original author <NAME>
;; Modifications by <NAME>
;; Licensed under https://www.apache.org/licenses/LICENSE-2.0
;; See https://kimh.github.io/clojure-by-example/#closure
(ns p07-closure.core)
(defn inner
[from-outer]
(fn [] (println from-outer)))
(defn -main
"Main"
[]
(def outer1 (inner "this is from outer"))
(def outer2 (inner "this is yet another from outer"))
(outer1)
(outer2)
)
| 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/#closure
(ns p07-closure.core)
(defn inner
[from-outer]
(fn [] (println from-outer)))
(defn -main
"Main"
[]
(def outer1 (inner "this is from outer"))
(def outer2 (inner "this is yet another from outer"))
(outer1)
(outer2)
)
|
[
{
"context": " :name \"Abel\"\n ",
"end": 522,
"score": 0.999821126461029,
"start": 518,
"tag": "NAME",
"value": "Abel"
},
{
"context": "ustomer customer-id ..http..) => {:customer-name \"Abel\"}\n (db.saving-account/add-account! (contains {",
"end": 712,
"score": 0.9998191595077515,
"start": 708,
"tag": "NAME",
"value": "Abel"
},
{
"context": "(db.saving-account/add-account! (contains {:name \"Abel\"}) ..storage..) => irrelevant))\n",
"end": 773,
"score": 0.9997963309288025,
"start": 769,
"tag": "NAME",
"value": "Abel"
}
] | test/basic_microservice_example/controller_test.clj | miguelemosreverte/basic-microservice-example | 3 | (ns basic-microservice-example.controller-test
(:require [midje.sweet :refer :all]
[basic-microservice-example.db.saving-account :as db.saving-account]
[basic-microservice-example.controller :as controller])
(:import [java.util UUID]))
(def customer-id (UUID/randomUUID))
(fact "Sketching account creation"
(controller/create-account! customer-id ..storage.. ..http..) => (just {:id uuid?
:name "Abel"
:customer-id customer-id})
(provided
(controller/get-customer customer-id ..http..) => {:customer-name "Abel"}
(db.saving-account/add-account! (contains {:name "Abel"}) ..storage..) => irrelevant))
| 61318 | (ns basic-microservice-example.controller-test
(:require [midje.sweet :refer :all]
[basic-microservice-example.db.saving-account :as db.saving-account]
[basic-microservice-example.controller :as controller])
(:import [java.util UUID]))
(def customer-id (UUID/randomUUID))
(fact "Sketching account creation"
(controller/create-account! customer-id ..storage.. ..http..) => (just {:id uuid?
:name "<NAME>"
:customer-id customer-id})
(provided
(controller/get-customer customer-id ..http..) => {:customer-name "<NAME>"}
(db.saving-account/add-account! (contains {:name "<NAME>"}) ..storage..) => irrelevant))
| true | (ns basic-microservice-example.controller-test
(:require [midje.sweet :refer :all]
[basic-microservice-example.db.saving-account :as db.saving-account]
[basic-microservice-example.controller :as controller])
(:import [java.util UUID]))
(def customer-id (UUID/randomUUID))
(fact "Sketching account creation"
(controller/create-account! customer-id ..storage.. ..http..) => (just {:id uuid?
:name "PI:NAME:<NAME>END_PI"
:customer-id customer-id})
(provided
(controller/get-customer customer-id ..http..) => {:customer-name "PI:NAME:<NAME>END_PI"}
(db.saving-account/add-account! (contains {:name "PI:NAME:<NAME>END_PI"}) ..storage..) => irrelevant))
|
[
{
"context": "; Copyright (C) 2014, 2015 Dr. Thomas Schank (DrTom@schank.ch, Thomas.Schank@algocon.ch)\n; Re",
"end": 44,
"score": 0.9997866153717041,
"start": 31,
"tag": "NAME",
"value": "Thomas Schank"
},
{
"context": "; Copyright (C) 2014, 2015 Dr. Thomas Schank (DrTom@schank.ch, Thomas.Schank@algocon.ch)\n; Released under the M",
"end": 62,
"score": 0.9999213814735413,
"start": 47,
"tag": "EMAIL",
"value": "DrTom@schank.ch"
},
{
"context": "C) 2014, 2015 Dr. Thomas Schank (DrTom@schank.ch, Thomas.Schank@algocon.ch)\n; Released under the MIT license.\n\n(ns json-roa.",
"end": 88,
"score": 0.9999220371246338,
"start": 64,
"tag": "EMAIL",
"value": "Thomas.Schank@algocon.ch"
}
] | test/json_roa/ring_middleware/response_test.clj | json-roa/json-roa_clj-utils | 0 | ; Copyright (C) 2014, 2015 Dr. Thomas Schank (DrTom@schank.ch, Thomas.Schank@algocon.ch)
; Released under the MIT license.
(ns json-roa.ring-middleware.response-test
(:require
[ring.util.response]
[json-roa.ring-middleware.response]
[clojure.data.json :as json]
[cheshire.core :as cheshire]
[clojure.tools.logging :as logging]
[clj-logging-config.log4j :as logging-config]
)
(:use clojure.test))
(defn- default-json-decoder [json-str]
(json/read-str json-str :key-fn keyword))
(deftest test-wrap-roa-json-response
(testing "a response with body of type map including json-roa data"
(let [input-response {:body {:_json-roa {:relations {}
:about {:version "0.0.0"}
}}}
built-response ((json-roa.ring-middleware.response/wrap
identity) input-response)]
(logging/debug test-wrap-roa-json-response {:built-response built-response})
(testing "the built response"
(is built-response)
(let [headers (-> built-response :headers)]
(logging/debug {:headers headers})
(testing "has the correct header"
(is (re-matches #".*application\/json-roa\+json.*" (str headers)))))
(let [data (-> built-response :body default-json-decoder)]
(logging/debug test-wrap-roa-json-response {:data data})
(testing "the parsed json data"
(is (map? data))
(is (:_json-roa data))
)))))
(testing "a response with body of type vector including json-roa data"
(let [input-response {:body [{:_json-roa {:relations {}
:about {:version "0.0.0"}
}}]}
built-response ((json-roa.ring-middleware.response/wrap
identity) input-response)]
(logging/debug test-wrap-roa-json-response {:built-response built-response})
(testing "the built response"
(is built-response)
(testing "has the correct header"
(is (re-matches #".*application\/json-roa\+json.*" (-> built-response :headers str))))
(let [data (-> built-response :body default-json-decoder)]
(logging/debug test-wrap-roa-json-response {:data data})
(testing "the parsed json data"
(is (coll? data))
(is (-> data first :_json-roa))
)))))
(testing "using cheshire as a custom json encoder"
(let [input-response {:body {:_json-roa {:relations {}
:about {:version "0.0.0"}
}}}
built-response ((json-roa.ring-middleware.response/wrap
identity :json-encoder cheshire/generate-string) input-response)]
(logging/debug test-wrap-roa-json-response {:built-response built-response})
(testing "the built response"
(is built-response)
(let [headers (-> built-response :headers)]
(logging/debug {:headers headers})
(testing "has the correct header"
(is (re-matches #".*application\/json-roa\+json.*" (str headers)))))
(let [data (-> built-response :body default-json-decoder)]
(logging/debug test-wrap-roa-json-response {:data data})
(testing "the parsed json data"
(is (map? data))
(is (:_json-roa data))
)))))
(testing "a response with body of type map not including json-roa data"
(let [input-response {:body {:x 5}}
built-response ((json-roa.ring-middleware.response/wrap
identity) input-response)]
(testing "has not been modified at all"
(is (= input-response built-response)))))
(testing "a response with body of type vector not including json-roa data"
(let [input-response {:body [:x]}
built-response ((json-roa.ring-middleware.response/wrap
identity) input-response)]
(testing "has not been modified at all"
(is (= input-response built-response)))))
)
| 120248 | ; Copyright (C) 2014, 2015 Dr. <NAME> (<EMAIL>, <EMAIL>)
; Released under the MIT license.
(ns json-roa.ring-middleware.response-test
(:require
[ring.util.response]
[json-roa.ring-middleware.response]
[clojure.data.json :as json]
[cheshire.core :as cheshire]
[clojure.tools.logging :as logging]
[clj-logging-config.log4j :as logging-config]
)
(:use clojure.test))
(defn- default-json-decoder [json-str]
(json/read-str json-str :key-fn keyword))
(deftest test-wrap-roa-json-response
(testing "a response with body of type map including json-roa data"
(let [input-response {:body {:_json-roa {:relations {}
:about {:version "0.0.0"}
}}}
built-response ((json-roa.ring-middleware.response/wrap
identity) input-response)]
(logging/debug test-wrap-roa-json-response {:built-response built-response})
(testing "the built response"
(is built-response)
(let [headers (-> built-response :headers)]
(logging/debug {:headers headers})
(testing "has the correct header"
(is (re-matches #".*application\/json-roa\+json.*" (str headers)))))
(let [data (-> built-response :body default-json-decoder)]
(logging/debug test-wrap-roa-json-response {:data data})
(testing "the parsed json data"
(is (map? data))
(is (:_json-roa data))
)))))
(testing "a response with body of type vector including json-roa data"
(let [input-response {:body [{:_json-roa {:relations {}
:about {:version "0.0.0"}
}}]}
built-response ((json-roa.ring-middleware.response/wrap
identity) input-response)]
(logging/debug test-wrap-roa-json-response {:built-response built-response})
(testing "the built response"
(is built-response)
(testing "has the correct header"
(is (re-matches #".*application\/json-roa\+json.*" (-> built-response :headers str))))
(let [data (-> built-response :body default-json-decoder)]
(logging/debug test-wrap-roa-json-response {:data data})
(testing "the parsed json data"
(is (coll? data))
(is (-> data first :_json-roa))
)))))
(testing "using cheshire as a custom json encoder"
(let [input-response {:body {:_json-roa {:relations {}
:about {:version "0.0.0"}
}}}
built-response ((json-roa.ring-middleware.response/wrap
identity :json-encoder cheshire/generate-string) input-response)]
(logging/debug test-wrap-roa-json-response {:built-response built-response})
(testing "the built response"
(is built-response)
(let [headers (-> built-response :headers)]
(logging/debug {:headers headers})
(testing "has the correct header"
(is (re-matches #".*application\/json-roa\+json.*" (str headers)))))
(let [data (-> built-response :body default-json-decoder)]
(logging/debug test-wrap-roa-json-response {:data data})
(testing "the parsed json data"
(is (map? data))
(is (:_json-roa data))
)))))
(testing "a response with body of type map not including json-roa data"
(let [input-response {:body {:x 5}}
built-response ((json-roa.ring-middleware.response/wrap
identity) input-response)]
(testing "has not been modified at all"
(is (= input-response built-response)))))
(testing "a response with body of type vector not including json-roa data"
(let [input-response {:body [:x]}
built-response ((json-roa.ring-middleware.response/wrap
identity) input-response)]
(testing "has not been modified at all"
(is (= input-response built-response)))))
)
| true | ; Copyright (C) 2014, 2015 Dr. PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI, PI:EMAIL:<EMAIL>END_PI)
; Released under the MIT license.
(ns json-roa.ring-middleware.response-test
(:require
[ring.util.response]
[json-roa.ring-middleware.response]
[clojure.data.json :as json]
[cheshire.core :as cheshire]
[clojure.tools.logging :as logging]
[clj-logging-config.log4j :as logging-config]
)
(:use clojure.test))
(defn- default-json-decoder [json-str]
(json/read-str json-str :key-fn keyword))
(deftest test-wrap-roa-json-response
(testing "a response with body of type map including json-roa data"
(let [input-response {:body {:_json-roa {:relations {}
:about {:version "0.0.0"}
}}}
built-response ((json-roa.ring-middleware.response/wrap
identity) input-response)]
(logging/debug test-wrap-roa-json-response {:built-response built-response})
(testing "the built response"
(is built-response)
(let [headers (-> built-response :headers)]
(logging/debug {:headers headers})
(testing "has the correct header"
(is (re-matches #".*application\/json-roa\+json.*" (str headers)))))
(let [data (-> built-response :body default-json-decoder)]
(logging/debug test-wrap-roa-json-response {:data data})
(testing "the parsed json data"
(is (map? data))
(is (:_json-roa data))
)))))
(testing "a response with body of type vector including json-roa data"
(let [input-response {:body [{:_json-roa {:relations {}
:about {:version "0.0.0"}
}}]}
built-response ((json-roa.ring-middleware.response/wrap
identity) input-response)]
(logging/debug test-wrap-roa-json-response {:built-response built-response})
(testing "the built response"
(is built-response)
(testing "has the correct header"
(is (re-matches #".*application\/json-roa\+json.*" (-> built-response :headers str))))
(let [data (-> built-response :body default-json-decoder)]
(logging/debug test-wrap-roa-json-response {:data data})
(testing "the parsed json data"
(is (coll? data))
(is (-> data first :_json-roa))
)))))
(testing "using cheshire as a custom json encoder"
(let [input-response {:body {:_json-roa {:relations {}
:about {:version "0.0.0"}
}}}
built-response ((json-roa.ring-middleware.response/wrap
identity :json-encoder cheshire/generate-string) input-response)]
(logging/debug test-wrap-roa-json-response {:built-response built-response})
(testing "the built response"
(is built-response)
(let [headers (-> built-response :headers)]
(logging/debug {:headers headers})
(testing "has the correct header"
(is (re-matches #".*application\/json-roa\+json.*" (str headers)))))
(let [data (-> built-response :body default-json-decoder)]
(logging/debug test-wrap-roa-json-response {:data data})
(testing "the parsed json data"
(is (map? data))
(is (:_json-roa data))
)))))
(testing "a response with body of type map not including json-roa data"
(let [input-response {:body {:x 5}}
built-response ((json-roa.ring-middleware.response/wrap
identity) input-response)]
(testing "has not been modified at all"
(is (= input-response built-response)))))
(testing "a response with body of type vector not including json-roa data"
(let [input-response {:body [:x]}
built-response ((json-roa.ring-middleware.response/wrap
identity) input-response)]
(testing "has not been modified at all"
(is (= input-response built-response)))))
)
|
[
{
"context": "ue}))\n\n(def table-contents\n [{:id 1 :first-name \"Bram\" :last-name \"Moolenaar\" :known-for \"Vim\"}\n ",
"end": 183,
"score": 0.9997382164001465,
"start": 179,
"tag": "NAME",
"value": "Bram"
},
{
"context": "tents\n [{:id 1 :first-name \"Bram\" :last-name \"Moolenaar\" :known-for \"Vim\"}\n {:id 2 :first-name \"Richar",
"end": 209,
"score": 0.9997186660766602,
"start": 200,
"tag": "NAME",
"value": "Moolenaar"
},
{
"context": "ame \"Bram\" :last-name \"Moolenaar\" :known-for \"Vim\"}\n {:id 2 :first-name \"Richard\" :last-name \"Sta",
"end": 227,
"score": 0.9993927478790283,
"start": 224,
"tag": "NAME",
"value": "Vim"
},
{
"context": "lenaar\" :known-for \"Vim\"}\n {:id 2 :first-name \"Richard\" :last-name \"Stallman\" :known-for \"GNU\"}\n {:i",
"end": 260,
"score": 0.9997479319572449,
"start": 253,
"tag": "NAME",
"value": "Richard"
},
{
"context": "Vim\"}\n {:id 2 :first-name \"Richard\" :last-name \"Stallman\" :known-for \"GNU\"}\n {:id 3 :first-name \"Denni",
"end": 282,
"score": 0.999376118183136,
"start": 274,
"tag": "NAME",
"value": "Stallman"
},
{
"context": "llman\" :known-for \"GNU\"}\n {:id 3 :first-name \"Dennis\" :last-name \"Ritchie\" :known-for \"C\"}\n {:id",
"end": 333,
"score": 0.9997411370277405,
"start": 327,
"tag": "NAME",
"value": "Dennis"
},
{
"context": "GNU\"}\n {:id 3 :first-name \"Dennis\" :last-name \"Ritchie\" :known-for \"C\"}\n {:id 4 :first-name \"Rich\" ",
"end": 355,
"score": 0.9996252059936523,
"start": 348,
"tag": "NAME",
"value": "Ritchie"
},
{
"context": "itchie\" :known-for \"C\"}\n {:id 4 :first-name \"Rich\" :last-name \"Hickey\" :known-for \"Clojure\"}",
"end": 403,
"score": 0.9997335076332092,
"start": 399,
"tag": "NAME",
"value": "Rich"
},
{
"context": " \"C\"}\n {:id 4 :first-name \"Rich\" :last-name \"Hickey\" :known-for \"Clojure\"}\n {:id 5 :first-name ",
"end": 426,
"score": 0.9995028972625732,
"start": 420,
"tag": "NAME",
"value": "Hickey"
},
{
"context": " :known-for \"Clojure\"}\n {:id 5 :first-name \"Guido\" :last-name \"Van Rossum\" :known-for \"Python\"}\n ",
"end": 482,
"score": 0.9997792840003967,
"start": 477,
"tag": "NAME",
"value": "Guido"
},
{
"context": "ure\"}\n {:id 5 :first-name \"Guido\" :last-name \"Van Rossum\" :known-for \"Python\"}\n {:id 6 :first-name \"Linu",
"end": 508,
"score": 0.9996957778930664,
"start": 498,
"tag": "NAME",
"value": "Van Rossum"
},
{
"context": "ssum\" :known-for \"Python\"}\n {:id 6 :first-name \"Linus\" :last-name \"Torvalds\" :known-for \"Linux\"}\n ",
"end": 559,
"score": 0.9997839331626892,
"start": 554,
"tag": "NAME",
"value": "Linus"
},
{
"context": "hon\"}\n {:id 6 :first-name \"Linus\" :last-name \"Torvalds\" :known-for \"Linux\"}\n {:id 7 :first-name \"Yeh",
"end": 583,
"score": 0.9958711266517639,
"start": 575,
"tag": "NAME",
"value": "Torvalds"
},
{
"context": "lds\" :known-for \"Linux\"}\n {:id 7 :first-name \"Yehuda\" :last-name \"Katz\" :known-for \"Ember\"}])\n\n",
"end": 636,
"score": 0.9997739195823669,
"start": 630,
"tag": "NAME",
"value": "Yehuda"
},
{
"context": "nux\"}\n {:id 7 :first-name \"Yehuda\" :last-name \"Katz\" :known-for \"Ember\"}])\n\n(defn update-sort-v",
"end": 655,
"score": 0.9989825487136841,
"start": 651,
"tag": "NAME",
"value": "Katz"
},
{
"context": "d (:first-name person)] \n [:td (:last-name person)] \n [:td (:known-for person)]])]])\n\n(defn",
"end": 1542,
"score": 0.7846976518630981,
"start": 1536,
"tag": "NAME",
"value": "person"
}
] | recipes/sort-table/src/cljs/sort_table/core.cljs | yatesj9/reagent-cookbook | 1 | (ns sort-table.core
(:require [reagent.core :as reagent]))
(def app-state (reagent/atom {:sort-val :first-name :ascending true}))
(def table-contents
[{:id 1 :first-name "Bram" :last-name "Moolenaar" :known-for "Vim"}
{:id 2 :first-name "Richard" :last-name "Stallman" :known-for "GNU"}
{:id 3 :first-name "Dennis" :last-name "Ritchie" :known-for "C"}
{:id 4 :first-name "Rich" :last-name "Hickey" :known-for "Clojure"}
{:id 5 :first-name "Guido" :last-name "Van Rossum" :known-for "Python"}
{:id 6 :first-name "Linus" :last-name "Torvalds" :known-for "Linux"}
{:id 7 :first-name "Yehuda" :last-name "Katz" :known-for "Ember"}])
(defn update-sort-value [new-val]
(if (= new-val (:sort-val @app-state))
(swap! app-state update-in [:ascending] not)
(swap! app-state assoc :ascending true))
(swap! app-state assoc :sort-val new-val))
(defn sorted-contents []
(let [sorted-contents (sort-by (:sort-val @app-state) table-contents)]
(if (:ascending @app-state)
sorted-contents
(rseq sorted-contents))))
(defn table []
[:table
[:thead
[:tr
[:th {:width "200" :on-click #(update-sort-value :first-name)} "First Name"]
[:th {:width "200" :on-click #(update-sort-value :last-name) } "Last Name"]
[:th {:width "200" :on-click #(update-sort-value :known-for) } "Known For"]]]
[:tbody
(for [person (sorted-contents)]
^{:key (:id person)}
[:tr [:td (:first-name person)]
[:td (:last-name person)]
[:td (:known-for person)]])]])
(defn home []
[:div {:style {:margin "auto"
:padding-top "30px"
:width "600px"}}
[table]])
(defn ^:export main []
(reagent/render [home]
(.getElementById js/document "app")))
| 90646 | (ns sort-table.core
(:require [reagent.core :as reagent]))
(def app-state (reagent/atom {:sort-val :first-name :ascending true}))
(def table-contents
[{:id 1 :first-name "<NAME>" :last-name "<NAME>" :known-for "<NAME>"}
{:id 2 :first-name "<NAME>" :last-name "<NAME>" :known-for "GNU"}
{:id 3 :first-name "<NAME>" :last-name "<NAME>" :known-for "C"}
{:id 4 :first-name "<NAME>" :last-name "<NAME>" :known-for "Clojure"}
{:id 5 :first-name "<NAME>" :last-name "<NAME>" :known-for "Python"}
{:id 6 :first-name "<NAME>" :last-name "<NAME>" :known-for "Linux"}
{:id 7 :first-name "<NAME>" :last-name "<NAME>" :known-for "Ember"}])
(defn update-sort-value [new-val]
(if (= new-val (:sort-val @app-state))
(swap! app-state update-in [:ascending] not)
(swap! app-state assoc :ascending true))
(swap! app-state assoc :sort-val new-val))
(defn sorted-contents []
(let [sorted-contents (sort-by (:sort-val @app-state) table-contents)]
(if (:ascending @app-state)
sorted-contents
(rseq sorted-contents))))
(defn table []
[:table
[:thead
[:tr
[:th {:width "200" :on-click #(update-sort-value :first-name)} "First Name"]
[:th {:width "200" :on-click #(update-sort-value :last-name) } "Last Name"]
[:th {:width "200" :on-click #(update-sort-value :known-for) } "Known For"]]]
[:tbody
(for [person (sorted-contents)]
^{:key (:id person)}
[:tr [:td (:first-name person)]
[:td (:last-name <NAME>)]
[:td (:known-for person)]])]])
(defn home []
[:div {:style {:margin "auto"
:padding-top "30px"
:width "600px"}}
[table]])
(defn ^:export main []
(reagent/render [home]
(.getElementById js/document "app")))
| true | (ns sort-table.core
(:require [reagent.core :as reagent]))
(def app-state (reagent/atom {:sort-val :first-name :ascending true}))
(def table-contents
[{:id 1 :first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :known-for "PI:NAME:<NAME>END_PI"}
{:id 2 :first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :known-for "GNU"}
{:id 3 :first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :known-for "C"}
{:id 4 :first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :known-for "Clojure"}
{:id 5 :first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :known-for "Python"}
{:id 6 :first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :known-for "Linux"}
{:id 7 :first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI" :known-for "Ember"}])
(defn update-sort-value [new-val]
(if (= new-val (:sort-val @app-state))
(swap! app-state update-in [:ascending] not)
(swap! app-state assoc :ascending true))
(swap! app-state assoc :sort-val new-val))
(defn sorted-contents []
(let [sorted-contents (sort-by (:sort-val @app-state) table-contents)]
(if (:ascending @app-state)
sorted-contents
(rseq sorted-contents))))
(defn table []
[:table
[:thead
[:tr
[:th {:width "200" :on-click #(update-sort-value :first-name)} "First Name"]
[:th {:width "200" :on-click #(update-sort-value :last-name) } "Last Name"]
[:th {:width "200" :on-click #(update-sort-value :known-for) } "Known For"]]]
[:tbody
(for [person (sorted-contents)]
^{:key (:id person)}
[:tr [:td (:first-name person)]
[:td (:last-name PI:NAME:<NAME>END_PI)]
[:td (:known-for person)]])]])
(defn home []
[:div {:style {:margin "auto"
:padding-top "30px"
:width "600px"}}
[table]])
(defn ^:export main []
(reagent/render [home]
(.getElementById js/document "app")))
|
[
{
"context": "cro network\n NetworkRoot\n {})\n\n(s/def ::name #{\"Arnold\" \"Bea\" \"Dude\" \"Girl\"})\n\n(mutations/defmutation se",
"end": 8427,
"score": 0.9996871948242188,
"start": 8421,
"tag": "NAME",
"value": "Arnold"
},
{
"context": "rk\n NetworkRoot\n {})\n\n(s/def ::name #{\"Arnold\" \"Bea\" \"Dude\" \"Girl\"})\n\n(mutations/defmutation send-som",
"end": 8433,
"score": 0.9995400905609131,
"start": 8430,
"tag": "NAME",
"value": "Bea"
},
{
"context": "etworkRoot\n {})\n\n(s/def ::name #{\"Arnold\" \"Bea\" \"Dude\" \"Girl\"})\n\n(mutations/defmutation send-something ",
"end": 8440,
"score": 0.999382495880127,
"start": 8436,
"tag": "NAME",
"value": "Dude"
},
{
"context": "oot\n {})\n\n(s/def ::name #{\"Arnold\" \"Bea\" \"Dude\" \"Girl\"})\n\n(mutations/defmutation send-something [_]\n (",
"end": 8447,
"score": 0.9965874552726746,
"start": 8443,
"tag": "NAME",
"value": "Girl"
}
] | devcards/fulcro/inspect/ui/network_cards.cljs | mitchelkuijpers/fulcro-inspect | 0 | (ns fulcro.inspect.ui.network-cards
(:require
[devcards.core :refer-macros [defcard]]
[fulcro-css.css :as css]
[fulcro.client.cards :refer-macros [defcard-fulcro]]
[fulcro.inspect.ui.network :as network]
[fulcro.client.primitives :as fp]
[fulcro.client.network :as f.network]
[fulcro.client.data-fetch :as fetch]
[fulcro.client.mutations :as mutations]
[clojure.test.check.generators :as gen]
[fulcro.client.dom :as dom]
[cljs.spec.alpha :as s]))
(def request-samples
[{:in [:hello :world]
:out {:hello "data"
:world "value"}}
`{:in [(do-something {:foo "bar"})]
:out {do-something {}}}
{:in [{:ui/root
[{:ui/inspector
[:fulcro.inspect.core/inspectors
{:fulcro.inspect.core/current-app
[:fulcro.inspect.ui.inspector/tab
:fulcro.inspect.ui.inspector/id
{:fulcro.inspect.ui.inspector/app-state
[:fulcro.inspect.ui.data-watcher/id
{:fulcro.inspect.ui.data-watcher/root-data
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:fulcro.inspect.ui.data-watcher/watches
[:ui/expanded?
:fulcro.inspect.ui.data-watcher/watch-id
:fulcro.inspect.ui.data-watcher/watch-path
{:fulcro.inspect.ui.data-watcher/data-viewer
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}]}]}
{:fulcro.inspect.ui.inspector/network
[:fulcro.inspect.ui.network/history-id
{:fulcro.inspect.ui.network/requests
[:fulcro.inspect.ui.network/request-id
:fulcro.inspect.ui.network/request-edn
:fulcro.inspect.ui.network/request-edn-row-view
:fulcro.inspect.ui.network/response-edn
:fulcro.inspect.ui.network/request-started-at
:fulcro.inspect.ui.network/request-finished-at
:fulcro.inspect.ui.network/error]}
{:fulcro.inspect.ui.network/active-request
[:fulcro.inspect.ui.network/request-id
:fulcro.inspect.ui.network/request-edn
:fulcro.inspect.ui.network/response-edn
:fulcro.inspect.ui.network/request-started-at
:fulcro.inspect.ui.network/request-finished-at
:fulcro.inspect.ui.network/error
{:ui/request-edn-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/response-edn-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/error-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}]}]}
{:fulcro.inspect.ui.inspector/transactions
[:fulcro.inspect.ui.transactions/tx-list-id
:fulcro.inspect.ui.transactions/tx-filter
{:fulcro.inspect.ui.transactions/active-tx
[:fulcro.inspect.ui.transactions/tx-id
:fulcro.inspect.ui.transactions/timestamp
:tx
:ret
:sends
:old-state
:new-state
:ref
:component
{:ui/tx-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/ret-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/tx-row-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/sends-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/old-state-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/new-state-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/diff-add-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/diff-rem-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}]}
{:fulcro.inspect.ui.transactions/tx-list
[:fulcro.inspect.ui.transactions/tx-id
:fulcro.inspect.ui.transactions/timestamp
:ref
:tx
{:ui/tx-row-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}]}]}]}]}
:ui/size
:ui/visible?]}
:ui/react-key]
:out {}}])
(defn gen-remote []
(gen/generate (gen/frequency [[6 (gen/return :remote)] [1 (gen/return :other)]])))
(defn success? []
(gen/generate (gen/frequency [[8 (gen/return true)] [1 (gen/return false)]])))
(defn gen-request [this]
(let [id (random-uuid)
reconciler (fp/get-reconciler this)
remote (gen-remote)
{:keys [in out]} (rand-nth request-samples)]
(fp/transact! reconciler [::network/history-id "main"]
[`(network/request-start ~{::network/remote remote
::network/request-id id
::network/request-edn in})])
(js/setTimeout
(fn []
(let [suc? (success?)]
(fp/transact! reconciler [::network/history-id "main"]
[`(network/request-finish ~(cond-> {::network/remote remote
::network/request-id id}
suc? (assoc ::network/response-edn out)
(not suc?) (assoc ::network/error {:error "bad"})))])))
(gen/generate (gen/large-integer* {:min 30 :max 7000})))))
(fp/defui ^:once NetworkRoot
static fp/InitialAppState
(initial-state [_ _] {:ui/react-key (random-uuid)
:ui/root (assoc (fp/get-initial-state network/NetworkHistory {})
::network/history-id "main")})
static fp/IQuery
(query [_] [{:ui/root (fp/get-query network/NetworkHistory)}
:ui/react-key])
static css/CSS
(local-rules [_] [[:.container {:height "500px"
:display "flex"
:flex-direction "column"}]])
(include-children [_] [network/NetworkHistory])
Object
(render [this]
(let [{:keys [ui/react-key ui/root]} (fp/props this)
css (css/get-classnames NetworkRoot)]
(dom/div #js {:key react-key :className (:container css)}
(dom/button #js {:onClick #(gen-request this)}
"Generate request")
(network/network-history root)))))
(defcard-fulcro network
NetworkRoot
{})
(s/def ::name #{"Arnold" "Bea" "Dude" "Girl"})
(mutations/defmutation send-something [_]
(action [_] (js/console.log "send something"))
(remote [_] true))
(fp/defsc NameLoader
[this {::keys [name]} computed]
{:initial-state {::id "name-loader"}
:ident [::id ::id]
:query [::id ::name]}
(let [css (css/get-classnames NameLoader)]
(dom/div nil
(dom/button #js {:onClick #(fetch/load-field this ::name)}
"Load name")
(if name
(str "The name is: " name))
(dom/div nil
(dom/button #js {:onClick #(fp/transact! this [`(send-something {})])}
"Send")))))
(def name-loader (fp/factory NameLoader))
(fp/defui ^:once NameLoaderRoot
static fp/InitialAppState
(initial-state [_ _] {:ui/react-key (random-uuid)
:ui/root (fp/get-initial-state NameLoader {})})
static fp/IQuery
(query [_] [{:ui/root (fp/get-query NameLoader)}
:ui/react-key])
static css/CSS
(local-rules [_] [])
(include-children [_] [NameLoader])
Object
(render [this]
(let [{:keys [ui/react-key ui/root]} (fp/props this)]
(dom/div #js {:key react-key}
(name-loader root)))))
(defcard-fulcro network-sampler
NameLoaderRoot
{}
{:fulcro {:networking
(reify
f.network/FulcroNetwork
(send [this edn ok error]
(ok {[::id "name-loader"] {::name (gen/generate (s/gen ::name))}}))
(start [_]))}})
(defcard-fulcro network-sampler-remote-i
NameLoaderRoot
{}
{:fulcro {:networking
(reify
f.network/FulcroRemoteI
(transmit [this {::f.network/keys [edn ok-handler]}]
(ok-handler {:transaction edn
:body {[::id "name-loader"] {::name (gen/generate (s/gen ::name))}}}))
(abort [_ _]))}})
(css/upsert-css "network" NetworkRoot)
| 26947 | (ns fulcro.inspect.ui.network-cards
(:require
[devcards.core :refer-macros [defcard]]
[fulcro-css.css :as css]
[fulcro.client.cards :refer-macros [defcard-fulcro]]
[fulcro.inspect.ui.network :as network]
[fulcro.client.primitives :as fp]
[fulcro.client.network :as f.network]
[fulcro.client.data-fetch :as fetch]
[fulcro.client.mutations :as mutations]
[clojure.test.check.generators :as gen]
[fulcro.client.dom :as dom]
[cljs.spec.alpha :as s]))
(def request-samples
[{:in [:hello :world]
:out {:hello "data"
:world "value"}}
`{:in [(do-something {:foo "bar"})]
:out {do-something {}}}
{:in [{:ui/root
[{:ui/inspector
[:fulcro.inspect.core/inspectors
{:fulcro.inspect.core/current-app
[:fulcro.inspect.ui.inspector/tab
:fulcro.inspect.ui.inspector/id
{:fulcro.inspect.ui.inspector/app-state
[:fulcro.inspect.ui.data-watcher/id
{:fulcro.inspect.ui.data-watcher/root-data
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:fulcro.inspect.ui.data-watcher/watches
[:ui/expanded?
:fulcro.inspect.ui.data-watcher/watch-id
:fulcro.inspect.ui.data-watcher/watch-path
{:fulcro.inspect.ui.data-watcher/data-viewer
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}]}]}
{:fulcro.inspect.ui.inspector/network
[:fulcro.inspect.ui.network/history-id
{:fulcro.inspect.ui.network/requests
[:fulcro.inspect.ui.network/request-id
:fulcro.inspect.ui.network/request-edn
:fulcro.inspect.ui.network/request-edn-row-view
:fulcro.inspect.ui.network/response-edn
:fulcro.inspect.ui.network/request-started-at
:fulcro.inspect.ui.network/request-finished-at
:fulcro.inspect.ui.network/error]}
{:fulcro.inspect.ui.network/active-request
[:fulcro.inspect.ui.network/request-id
:fulcro.inspect.ui.network/request-edn
:fulcro.inspect.ui.network/response-edn
:fulcro.inspect.ui.network/request-started-at
:fulcro.inspect.ui.network/request-finished-at
:fulcro.inspect.ui.network/error
{:ui/request-edn-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/response-edn-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/error-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}]}]}
{:fulcro.inspect.ui.inspector/transactions
[:fulcro.inspect.ui.transactions/tx-list-id
:fulcro.inspect.ui.transactions/tx-filter
{:fulcro.inspect.ui.transactions/active-tx
[:fulcro.inspect.ui.transactions/tx-id
:fulcro.inspect.ui.transactions/timestamp
:tx
:ret
:sends
:old-state
:new-state
:ref
:component
{:ui/tx-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/ret-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/tx-row-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/sends-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/old-state-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/new-state-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/diff-add-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/diff-rem-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}]}
{:fulcro.inspect.ui.transactions/tx-list
[:fulcro.inspect.ui.transactions/tx-id
:fulcro.inspect.ui.transactions/timestamp
:ref
:tx
{:ui/tx-row-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}]}]}]}]}
:ui/size
:ui/visible?]}
:ui/react-key]
:out {}}])
(defn gen-remote []
(gen/generate (gen/frequency [[6 (gen/return :remote)] [1 (gen/return :other)]])))
(defn success? []
(gen/generate (gen/frequency [[8 (gen/return true)] [1 (gen/return false)]])))
(defn gen-request [this]
(let [id (random-uuid)
reconciler (fp/get-reconciler this)
remote (gen-remote)
{:keys [in out]} (rand-nth request-samples)]
(fp/transact! reconciler [::network/history-id "main"]
[`(network/request-start ~{::network/remote remote
::network/request-id id
::network/request-edn in})])
(js/setTimeout
(fn []
(let [suc? (success?)]
(fp/transact! reconciler [::network/history-id "main"]
[`(network/request-finish ~(cond-> {::network/remote remote
::network/request-id id}
suc? (assoc ::network/response-edn out)
(not suc?) (assoc ::network/error {:error "bad"})))])))
(gen/generate (gen/large-integer* {:min 30 :max 7000})))))
(fp/defui ^:once NetworkRoot
static fp/InitialAppState
(initial-state [_ _] {:ui/react-key (random-uuid)
:ui/root (assoc (fp/get-initial-state network/NetworkHistory {})
::network/history-id "main")})
static fp/IQuery
(query [_] [{:ui/root (fp/get-query network/NetworkHistory)}
:ui/react-key])
static css/CSS
(local-rules [_] [[:.container {:height "500px"
:display "flex"
:flex-direction "column"}]])
(include-children [_] [network/NetworkHistory])
Object
(render [this]
(let [{:keys [ui/react-key ui/root]} (fp/props this)
css (css/get-classnames NetworkRoot)]
(dom/div #js {:key react-key :className (:container css)}
(dom/button #js {:onClick #(gen-request this)}
"Generate request")
(network/network-history root)))))
(defcard-fulcro network
NetworkRoot
{})
(s/def ::name #{"<NAME>" "<NAME>" "<NAME>" "<NAME>"})
(mutations/defmutation send-something [_]
(action [_] (js/console.log "send something"))
(remote [_] true))
(fp/defsc NameLoader
[this {::keys [name]} computed]
{:initial-state {::id "name-loader"}
:ident [::id ::id]
:query [::id ::name]}
(let [css (css/get-classnames NameLoader)]
(dom/div nil
(dom/button #js {:onClick #(fetch/load-field this ::name)}
"Load name")
(if name
(str "The name is: " name))
(dom/div nil
(dom/button #js {:onClick #(fp/transact! this [`(send-something {})])}
"Send")))))
(def name-loader (fp/factory NameLoader))
(fp/defui ^:once NameLoaderRoot
static fp/InitialAppState
(initial-state [_ _] {:ui/react-key (random-uuid)
:ui/root (fp/get-initial-state NameLoader {})})
static fp/IQuery
(query [_] [{:ui/root (fp/get-query NameLoader)}
:ui/react-key])
static css/CSS
(local-rules [_] [])
(include-children [_] [NameLoader])
Object
(render [this]
(let [{:keys [ui/react-key ui/root]} (fp/props this)]
(dom/div #js {:key react-key}
(name-loader root)))))
(defcard-fulcro network-sampler
NameLoaderRoot
{}
{:fulcro {:networking
(reify
f.network/FulcroNetwork
(send [this edn ok error]
(ok {[::id "name-loader"] {::name (gen/generate (s/gen ::name))}}))
(start [_]))}})
(defcard-fulcro network-sampler-remote-i
NameLoaderRoot
{}
{:fulcro {:networking
(reify
f.network/FulcroRemoteI
(transmit [this {::f.network/keys [edn ok-handler]}]
(ok-handler {:transaction edn
:body {[::id "name-loader"] {::name (gen/generate (s/gen ::name))}}}))
(abort [_ _]))}})
(css/upsert-css "network" NetworkRoot)
| true | (ns fulcro.inspect.ui.network-cards
(:require
[devcards.core :refer-macros [defcard]]
[fulcro-css.css :as css]
[fulcro.client.cards :refer-macros [defcard-fulcro]]
[fulcro.inspect.ui.network :as network]
[fulcro.client.primitives :as fp]
[fulcro.client.network :as f.network]
[fulcro.client.data-fetch :as fetch]
[fulcro.client.mutations :as mutations]
[clojure.test.check.generators :as gen]
[fulcro.client.dom :as dom]
[cljs.spec.alpha :as s]))
(def request-samples
[{:in [:hello :world]
:out {:hello "data"
:world "value"}}
`{:in [(do-something {:foo "bar"})]
:out {do-something {}}}
{:in [{:ui/root
[{:ui/inspector
[:fulcro.inspect.core/inspectors
{:fulcro.inspect.core/current-app
[:fulcro.inspect.ui.inspector/tab
:fulcro.inspect.ui.inspector/id
{:fulcro.inspect.ui.inspector/app-state
[:fulcro.inspect.ui.data-watcher/id
{:fulcro.inspect.ui.data-watcher/root-data
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:fulcro.inspect.ui.data-watcher/watches
[:ui/expanded?
:fulcro.inspect.ui.data-watcher/watch-id
:fulcro.inspect.ui.data-watcher/watch-path
{:fulcro.inspect.ui.data-watcher/data-viewer
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}]}]}
{:fulcro.inspect.ui.inspector/network
[:fulcro.inspect.ui.network/history-id
{:fulcro.inspect.ui.network/requests
[:fulcro.inspect.ui.network/request-id
:fulcro.inspect.ui.network/request-edn
:fulcro.inspect.ui.network/request-edn-row-view
:fulcro.inspect.ui.network/response-edn
:fulcro.inspect.ui.network/request-started-at
:fulcro.inspect.ui.network/request-finished-at
:fulcro.inspect.ui.network/error]}
{:fulcro.inspect.ui.network/active-request
[:fulcro.inspect.ui.network/request-id
:fulcro.inspect.ui.network/request-edn
:fulcro.inspect.ui.network/response-edn
:fulcro.inspect.ui.network/request-started-at
:fulcro.inspect.ui.network/request-finished-at
:fulcro.inspect.ui.network/error
{:ui/request-edn-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/response-edn-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/error-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}]}]}
{:fulcro.inspect.ui.inspector/transactions
[:fulcro.inspect.ui.transactions/tx-list-id
:fulcro.inspect.ui.transactions/tx-filter
{:fulcro.inspect.ui.transactions/active-tx
[:fulcro.inspect.ui.transactions/tx-id
:fulcro.inspect.ui.transactions/timestamp
:tx
:ret
:sends
:old-state
:new-state
:ref
:component
{:ui/tx-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/ret-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/tx-row-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/sends-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/old-state-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/new-state-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/diff-add-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}
{:ui/diff-rem-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}]}
{:fulcro.inspect.ui.transactions/tx-list
[:fulcro.inspect.ui.transactions/tx-id
:fulcro.inspect.ui.transactions/timestamp
:ref
:tx
{:ui/tx-row-view
[:fulcro.inspect.ui.data-viewer/id
:fulcro.inspect.ui.data-viewer/content
:fulcro.inspect.ui.data-viewer/expanded]}]}]}]}]}
:ui/size
:ui/visible?]}
:ui/react-key]
:out {}}])
(defn gen-remote []
(gen/generate (gen/frequency [[6 (gen/return :remote)] [1 (gen/return :other)]])))
(defn success? []
(gen/generate (gen/frequency [[8 (gen/return true)] [1 (gen/return false)]])))
(defn gen-request [this]
(let [id (random-uuid)
reconciler (fp/get-reconciler this)
remote (gen-remote)
{:keys [in out]} (rand-nth request-samples)]
(fp/transact! reconciler [::network/history-id "main"]
[`(network/request-start ~{::network/remote remote
::network/request-id id
::network/request-edn in})])
(js/setTimeout
(fn []
(let [suc? (success?)]
(fp/transact! reconciler [::network/history-id "main"]
[`(network/request-finish ~(cond-> {::network/remote remote
::network/request-id id}
suc? (assoc ::network/response-edn out)
(not suc?) (assoc ::network/error {:error "bad"})))])))
(gen/generate (gen/large-integer* {:min 30 :max 7000})))))
(fp/defui ^:once NetworkRoot
static fp/InitialAppState
(initial-state [_ _] {:ui/react-key (random-uuid)
:ui/root (assoc (fp/get-initial-state network/NetworkHistory {})
::network/history-id "main")})
static fp/IQuery
(query [_] [{:ui/root (fp/get-query network/NetworkHistory)}
:ui/react-key])
static css/CSS
(local-rules [_] [[:.container {:height "500px"
:display "flex"
:flex-direction "column"}]])
(include-children [_] [network/NetworkHistory])
Object
(render [this]
(let [{:keys [ui/react-key ui/root]} (fp/props this)
css (css/get-classnames NetworkRoot)]
(dom/div #js {:key react-key :className (:container css)}
(dom/button #js {:onClick #(gen-request this)}
"Generate request")
(network/network-history root)))))
(defcard-fulcro network
NetworkRoot
{})
(s/def ::name #{"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"})
(mutations/defmutation send-something [_]
(action [_] (js/console.log "send something"))
(remote [_] true))
(fp/defsc NameLoader
[this {::keys [name]} computed]
{:initial-state {::id "name-loader"}
:ident [::id ::id]
:query [::id ::name]}
(let [css (css/get-classnames NameLoader)]
(dom/div nil
(dom/button #js {:onClick #(fetch/load-field this ::name)}
"Load name")
(if name
(str "The name is: " name))
(dom/div nil
(dom/button #js {:onClick #(fp/transact! this [`(send-something {})])}
"Send")))))
(def name-loader (fp/factory NameLoader))
(fp/defui ^:once NameLoaderRoot
static fp/InitialAppState
(initial-state [_ _] {:ui/react-key (random-uuid)
:ui/root (fp/get-initial-state NameLoader {})})
static fp/IQuery
(query [_] [{:ui/root (fp/get-query NameLoader)}
:ui/react-key])
static css/CSS
(local-rules [_] [])
(include-children [_] [NameLoader])
Object
(render [this]
(let [{:keys [ui/react-key ui/root]} (fp/props this)]
(dom/div #js {:key react-key}
(name-loader root)))))
(defcard-fulcro network-sampler
NameLoaderRoot
{}
{:fulcro {:networking
(reify
f.network/FulcroNetwork
(send [this edn ok error]
(ok {[::id "name-loader"] {::name (gen/generate (s/gen ::name))}}))
(start [_]))}})
(defcard-fulcro network-sampler-remote-i
NameLoaderRoot
{}
{:fulcro {:networking
(reify
f.network/FulcroRemoteI
(transmit [this {::f.network/keys [edn ok-handler]}]
(ok-handler {:transaction edn
:body {[::id "name-loader"] {::name (gen/generate (s/gen ::name))}}}))
(abort [_ _]))}})
(css/upsert-css "network" NetworkRoot)
|
[
{
"context": "dio.covid19-clj-viz.italian-situation\n \"Following Alan Marazzi's 'The Italian COVID-19 situation' [1] with ortho",
"end": 84,
"score": 0.9873863458633423,
"start": 72,
"tag": "NAME",
"value": "Alan Marazzi"
}
] | src/appliedsciencestudio/covid19_clj_viz/italian_situation.clj | noorfathima11/covid19-clj-viz | 0 | (ns appliedsciencestudio.covid19-clj-viz.italian-situation
"Following Alan Marazzi's 'The Italian COVID-19 situation' [1] with orthodox Clojure rather than Panthera
Run the original in NextJournal at https://nextjournal.com/alan/getting-started-with-italian-data-on-covid-19
[1] https://alanmarazzi.gitlab.io/blog/posts/2020-3-19-italy-covid/"
(:require [clojure.data.csv :as csv]
[meta-csv.core :as mcsv]
[clojure.string :as string]))
;; We can get province data out of Italy's CSV data using the orthodox
;; Clojure approach, `clojure.data.csv`:
(def provinces
(let [hdr [:date :state :region-code :region-name
:province-code :province-name :province-abbrev
:lat :lon :cases]
rows (csv/read-csv (slurp "resources/Italia-COVID-19/dati-province/dpc-covid19-ita-province.csv"))]
(map zipmap
(repeat hdr)
(rest rows))))
;; Or, we could use Nils Grunwald's `meta-csv`, which does the
;; automatic parsing that we often want.
;; First, an Italian-to-English translation mapping for header names.
(def fields-it->en
{;; For provinces (and some for regions too)
"data" :date
"stato" :state
"codice_regione" :region-code
"denominazione_regione" :region-name
"codice_provincia" :province-code
"denominazione_provincia" :province-name
"sigla_provincia" :province-abbreviation
"lat" :lat
"long" :lon
"totale_casi" :cases
;; For regions
"ricoverati_con_sintomi" :hospitalized
"terapia_intensiva" :icu
"totale_ospedalizzati" :tot-hospitalized
"isolamento_domiciliare" :quarantined
"totale_attualmente_positivi" :tot-positives
"nuovi_attualmente_positivi" :new-positives
"dimessi_guariti" :recovered
"deceduti" :dead
"tamponi" :tests})
;; Now we can just read the CSV.
(def provinces2
(mcsv/read-csv "resources/Italia-COVID-19/dati-province/dpc-covid19-ita-province-latest.csv"
{:field-names-fn fields-it->en}))
(comment
;;;; Let's examine the data.
;; Instead of `pt/names`:
(keys (first provinces))
(keys (first provinces2))
;;;; I often use an alternative approach when reading CSVs,
;;;; transforming rather than replacing the header:
(let [[hdr & rows] (csv/read-csv (slurp "resources/Italia-COVID-19/dati-province/dpc-covid19-ita-province.csv"))]
(map zipmap
(repeat (map (comp keyword #(string/replace % "_" "-")) hdr))
rows))
;;;; Check the data
;; Do we have the right number of provinces?
(count (distinct (map :province-name provinces))) ;; be sure to evaluate the inner forms as well
;; No, there's an extra "In fase di definizione/aggiornamento", or cases not attributed to a province.
;; Let's ignore those.
(remove (comp #{"In fase di definizione/aggiornamento"} :province-name) provinces)
)
;; Again, we can use the DIY approach with Clojure's standard CSV parser:
(def regions
(let [hdr [:date :state :region-code :region-name :lat :lon
:hospitalized :icu :total-hospitalized :quarantined
:total-positives :new-positives :recovered :dead :tests]
[_ & rows] (csv/read-csv (slurp "resources/Italia-COVID-19/dati-regioni/dpc-covid19-ita-regioni.csv"))]
(->> (map zipmap (repeat hdr) rows)
(map (comp (fn [m] (update m :quarantined #(Integer/parseInt %)))
(fn [m] (update m :hospitalized #(Integer/parseInt %)))
(fn [m] (update m :icu #(Integer/parseInt %)))
(fn [m] (update m :dead #(Integer/parseInt %)))
(fn [m] (update m :recovered #(Integer/parseInt %)))
(fn [m] (update m :total-hospitalized #(Integer/parseInt %)))
(fn [m] (update m :total-positives #(Integer/parseInt %)))
(fn [m] (update m :new-positives #(Integer/parseInt %)))
(fn [m] (update m :tests #(Integer/parseInt %))))))))
;;;; Calculate daily changes
;; Now we want to determine how many new tests were performed each
;; day, and the proportion that were positive.
;; The following is equivalent to `regions-tests`:
(def tests-by-date
(reduce (fn [acc [date ms]]
(conj acc {:date date
:tests (apply + (map :tests ms))
:new-positives (reduce + (map :new-positives ms))}))
[]
(group-by :date regions)))
(comment
;; Take a quick look at the data
(sort-by :date tests-by-date)
;; And calculate our result using Clojure's sequence & collection libraries:
(reduce (fn [acc [m1 m2]]
(conj acc (let [daily-tests (- (:tests m2) (:tests m1))]
(assoc m2
:daily-tests daily-tests
:new-by-test (double (/ (:new-positives m2)
daily-tests))))))
[]
(partition 2 1 (conj (sort-by :date tests-by-date)
{:tests 0})))
)
| 13319 | (ns appliedsciencestudio.covid19-clj-viz.italian-situation
"Following <NAME>'s 'The Italian COVID-19 situation' [1] with orthodox Clojure rather than Panthera
Run the original in NextJournal at https://nextjournal.com/alan/getting-started-with-italian-data-on-covid-19
[1] https://alanmarazzi.gitlab.io/blog/posts/2020-3-19-italy-covid/"
(:require [clojure.data.csv :as csv]
[meta-csv.core :as mcsv]
[clojure.string :as string]))
;; We can get province data out of Italy's CSV data using the orthodox
;; Clojure approach, `clojure.data.csv`:
(def provinces
(let [hdr [:date :state :region-code :region-name
:province-code :province-name :province-abbrev
:lat :lon :cases]
rows (csv/read-csv (slurp "resources/Italia-COVID-19/dati-province/dpc-covid19-ita-province.csv"))]
(map zipmap
(repeat hdr)
(rest rows))))
;; Or, we could use Nils Grunwald's `meta-csv`, which does the
;; automatic parsing that we often want.
;; First, an Italian-to-English translation mapping for header names.
(def fields-it->en
{;; For provinces (and some for regions too)
"data" :date
"stato" :state
"codice_regione" :region-code
"denominazione_regione" :region-name
"codice_provincia" :province-code
"denominazione_provincia" :province-name
"sigla_provincia" :province-abbreviation
"lat" :lat
"long" :lon
"totale_casi" :cases
;; For regions
"ricoverati_con_sintomi" :hospitalized
"terapia_intensiva" :icu
"totale_ospedalizzati" :tot-hospitalized
"isolamento_domiciliare" :quarantined
"totale_attualmente_positivi" :tot-positives
"nuovi_attualmente_positivi" :new-positives
"dimessi_guariti" :recovered
"deceduti" :dead
"tamponi" :tests})
;; Now we can just read the CSV.
(def provinces2
(mcsv/read-csv "resources/Italia-COVID-19/dati-province/dpc-covid19-ita-province-latest.csv"
{:field-names-fn fields-it->en}))
(comment
;;;; Let's examine the data.
;; Instead of `pt/names`:
(keys (first provinces))
(keys (first provinces2))
;;;; I often use an alternative approach when reading CSVs,
;;;; transforming rather than replacing the header:
(let [[hdr & rows] (csv/read-csv (slurp "resources/Italia-COVID-19/dati-province/dpc-covid19-ita-province.csv"))]
(map zipmap
(repeat (map (comp keyword #(string/replace % "_" "-")) hdr))
rows))
;;;; Check the data
;; Do we have the right number of provinces?
(count (distinct (map :province-name provinces))) ;; be sure to evaluate the inner forms as well
;; No, there's an extra "In fase di definizione/aggiornamento", or cases not attributed to a province.
;; Let's ignore those.
(remove (comp #{"In fase di definizione/aggiornamento"} :province-name) provinces)
)
;; Again, we can use the DIY approach with Clojure's standard CSV parser:
(def regions
(let [hdr [:date :state :region-code :region-name :lat :lon
:hospitalized :icu :total-hospitalized :quarantined
:total-positives :new-positives :recovered :dead :tests]
[_ & rows] (csv/read-csv (slurp "resources/Italia-COVID-19/dati-regioni/dpc-covid19-ita-regioni.csv"))]
(->> (map zipmap (repeat hdr) rows)
(map (comp (fn [m] (update m :quarantined #(Integer/parseInt %)))
(fn [m] (update m :hospitalized #(Integer/parseInt %)))
(fn [m] (update m :icu #(Integer/parseInt %)))
(fn [m] (update m :dead #(Integer/parseInt %)))
(fn [m] (update m :recovered #(Integer/parseInt %)))
(fn [m] (update m :total-hospitalized #(Integer/parseInt %)))
(fn [m] (update m :total-positives #(Integer/parseInt %)))
(fn [m] (update m :new-positives #(Integer/parseInt %)))
(fn [m] (update m :tests #(Integer/parseInt %))))))))
;;;; Calculate daily changes
;; Now we want to determine how many new tests were performed each
;; day, and the proportion that were positive.
;; The following is equivalent to `regions-tests`:
(def tests-by-date
(reduce (fn [acc [date ms]]
(conj acc {:date date
:tests (apply + (map :tests ms))
:new-positives (reduce + (map :new-positives ms))}))
[]
(group-by :date regions)))
(comment
;; Take a quick look at the data
(sort-by :date tests-by-date)
;; And calculate our result using Clojure's sequence & collection libraries:
(reduce (fn [acc [m1 m2]]
(conj acc (let [daily-tests (- (:tests m2) (:tests m1))]
(assoc m2
:daily-tests daily-tests
:new-by-test (double (/ (:new-positives m2)
daily-tests))))))
[]
(partition 2 1 (conj (sort-by :date tests-by-date)
{:tests 0})))
)
| true | (ns appliedsciencestudio.covid19-clj-viz.italian-situation
"Following PI:NAME:<NAME>END_PI's 'The Italian COVID-19 situation' [1] with orthodox Clojure rather than Panthera
Run the original in NextJournal at https://nextjournal.com/alan/getting-started-with-italian-data-on-covid-19
[1] https://alanmarazzi.gitlab.io/blog/posts/2020-3-19-italy-covid/"
(:require [clojure.data.csv :as csv]
[meta-csv.core :as mcsv]
[clojure.string :as string]))
;; We can get province data out of Italy's CSV data using the orthodox
;; Clojure approach, `clojure.data.csv`:
(def provinces
(let [hdr [:date :state :region-code :region-name
:province-code :province-name :province-abbrev
:lat :lon :cases]
rows (csv/read-csv (slurp "resources/Italia-COVID-19/dati-province/dpc-covid19-ita-province.csv"))]
(map zipmap
(repeat hdr)
(rest rows))))
;; Or, we could use Nils Grunwald's `meta-csv`, which does the
;; automatic parsing that we often want.
;; First, an Italian-to-English translation mapping for header names.
(def fields-it->en
{;; For provinces (and some for regions too)
"data" :date
"stato" :state
"codice_regione" :region-code
"denominazione_regione" :region-name
"codice_provincia" :province-code
"denominazione_provincia" :province-name
"sigla_provincia" :province-abbreviation
"lat" :lat
"long" :lon
"totale_casi" :cases
;; For regions
"ricoverati_con_sintomi" :hospitalized
"terapia_intensiva" :icu
"totale_ospedalizzati" :tot-hospitalized
"isolamento_domiciliare" :quarantined
"totale_attualmente_positivi" :tot-positives
"nuovi_attualmente_positivi" :new-positives
"dimessi_guariti" :recovered
"deceduti" :dead
"tamponi" :tests})
;; Now we can just read the CSV.
(def provinces2
(mcsv/read-csv "resources/Italia-COVID-19/dati-province/dpc-covid19-ita-province-latest.csv"
{:field-names-fn fields-it->en}))
(comment
;;;; Let's examine the data.
;; Instead of `pt/names`:
(keys (first provinces))
(keys (first provinces2))
;;;; I often use an alternative approach when reading CSVs,
;;;; transforming rather than replacing the header:
(let [[hdr & rows] (csv/read-csv (slurp "resources/Italia-COVID-19/dati-province/dpc-covid19-ita-province.csv"))]
(map zipmap
(repeat (map (comp keyword #(string/replace % "_" "-")) hdr))
rows))
;;;; Check the data
;; Do we have the right number of provinces?
(count (distinct (map :province-name provinces))) ;; be sure to evaluate the inner forms as well
;; No, there's an extra "In fase di definizione/aggiornamento", or cases not attributed to a province.
;; Let's ignore those.
(remove (comp #{"In fase di definizione/aggiornamento"} :province-name) provinces)
)
;; Again, we can use the DIY approach with Clojure's standard CSV parser:
(def regions
(let [hdr [:date :state :region-code :region-name :lat :lon
:hospitalized :icu :total-hospitalized :quarantined
:total-positives :new-positives :recovered :dead :tests]
[_ & rows] (csv/read-csv (slurp "resources/Italia-COVID-19/dati-regioni/dpc-covid19-ita-regioni.csv"))]
(->> (map zipmap (repeat hdr) rows)
(map (comp (fn [m] (update m :quarantined #(Integer/parseInt %)))
(fn [m] (update m :hospitalized #(Integer/parseInt %)))
(fn [m] (update m :icu #(Integer/parseInt %)))
(fn [m] (update m :dead #(Integer/parseInt %)))
(fn [m] (update m :recovered #(Integer/parseInt %)))
(fn [m] (update m :total-hospitalized #(Integer/parseInt %)))
(fn [m] (update m :total-positives #(Integer/parseInt %)))
(fn [m] (update m :new-positives #(Integer/parseInt %)))
(fn [m] (update m :tests #(Integer/parseInt %))))))))
;;;; Calculate daily changes
;; Now we want to determine how many new tests were performed each
;; day, and the proportion that were positive.
;; The following is equivalent to `regions-tests`:
(def tests-by-date
(reduce (fn [acc [date ms]]
(conj acc {:date date
:tests (apply + (map :tests ms))
:new-positives (reduce + (map :new-positives ms))}))
[]
(group-by :date regions)))
(comment
;; Take a quick look at the data
(sort-by :date tests-by-date)
;; And calculate our result using Clojure's sequence & collection libraries:
(reduce (fn [acc [m1 m2]]
(conj acc (let [daily-tests (- (:tests m2) (:tests m1))]
(assoc m2
:daily-tests daily-tests
:new-by-test (double (/ (:new-positives m2)
daily-tests))))))
[]
(partition 2 1 (conj (sort-by :date tests-by-date)
{:tests 0})))
)
|
[
{
"context": "ECEIVE #####//\n(try \n (let [gstore (gmail/store \"user@gmail.com\" \"password\")\n inbox-messages (inbox gstore",
"end": 293,
"score": 0.9999184608459473,
"start": 279,
"tag": "EMAIL",
"value": "user@gmail.com"
},
{
"context": "##### SEND #####//\n(try \n (send-message { :from \"me@draines.com\"\n :to [\"mom@example.com\" \"dad@ex",
"end": 544,
"score": 0.9999309182167053,
"start": 530,
"tag": "EMAIL",
"value": "me@draines.com"
},
{
"context": " { :from \"me@draines.com\"\n :to [\"mom@example.com\" \"dad@example.com\"]\n :cc \"bob@ex",
"end": 585,
"score": 0.9999279975891113,
"start": 570,
"tag": "EMAIL",
"value": "mom@example.com"
},
{
"context": "es.com\"\n :to [\"mom@example.com\" \"dad@example.com\"]\n :cc \"bob@example.com\"\n ",
"end": 603,
"score": 0.9999311566352844,
"start": 588,
"tag": "EMAIL",
"value": "dad@example.com"
},
{
"context": "le.com\" \"dad@example.com\"]\n :cc \"bob@example.com\"\n :subject \"Hi!\"\n ",
"end": 644,
"score": 0.9999314546585083,
"start": 629,
"tag": "EMAIL",
"value": "bob@example.com"
}
] | email/src/emailcl/core.clj | caahab/cli-webbots | 0 | (ns emailcl.core
(:gen-class)
(:require [postal.core :refer :all]
[clojure-mail.core :refer :all]
[clojure-mail.gmail :as gmail]
[clojure-mail.message :refer (read-message)]))
;;//##### RECEIVE #####//
(try
(let [gstore (gmail/store "user@gmail.com" "password")
inbox-messages (inbox gstore)
latest (read-message (first inbox-messages))]
(:subject latest)
(keys latest))
(catch Exception e (println e)))
;;//##### SEND #####//
(try
(send-message { :from "me@draines.com"
:to ["mom@example.com" "dad@example.com"]
:cc "bob@example.com"
:subject "Hi!"
:body "Test."
:X-Tra "Something else"})
(catch Exception e (println e)))
(defn -main
"I don't do a whole lot ... yet."
[& args]
(println "Hello, World!"))
| 88939 | (ns emailcl.core
(:gen-class)
(:require [postal.core :refer :all]
[clojure-mail.core :refer :all]
[clojure-mail.gmail :as gmail]
[clojure-mail.message :refer (read-message)]))
;;//##### RECEIVE #####//
(try
(let [gstore (gmail/store "<EMAIL>" "password")
inbox-messages (inbox gstore)
latest (read-message (first inbox-messages))]
(:subject latest)
(keys latest))
(catch Exception e (println e)))
;;//##### SEND #####//
(try
(send-message { :from "<EMAIL>"
:to ["<EMAIL>" "<EMAIL>"]
:cc "<EMAIL>"
:subject "Hi!"
:body "Test."
:X-Tra "Something else"})
(catch Exception e (println e)))
(defn -main
"I don't do a whole lot ... yet."
[& args]
(println "Hello, World!"))
| true | (ns emailcl.core
(:gen-class)
(:require [postal.core :refer :all]
[clojure-mail.core :refer :all]
[clojure-mail.gmail :as gmail]
[clojure-mail.message :refer (read-message)]))
;;//##### RECEIVE #####//
(try
(let [gstore (gmail/store "PI:EMAIL:<EMAIL>END_PI" "password")
inbox-messages (inbox gstore)
latest (read-message (first inbox-messages))]
(:subject latest)
(keys latest))
(catch Exception e (println e)))
;;//##### SEND #####//
(try
(send-message { :from "PI:EMAIL:<EMAIL>END_PI"
:to ["PI:EMAIL:<EMAIL>END_PI" "PI:EMAIL:<EMAIL>END_PI"]
:cc "PI:EMAIL:<EMAIL>END_PI"
:subject "Hi!"
:body "Test."
:X-Tra "Something else"})
(catch Exception e (println e)))
(defn -main
"I don't do a whole lot ... yet."
[& args]
(println "Hello, World!"))
|
[
{
"context": "eld]]))\n\n(def currencies\n [{:code \"IQD\", :name \"Iraqi Dinar\", :symbol \"IQD\", :symbol_native \"د.ع.\"}\n {:cod",
"end": 356,
"score": 0.9132674336433411,
"start": 346,
"tag": "NAME",
"value": "raqi Dinar"
},
{
"context": ", :symbol_native \"د.ع.\"}\n {:code \"MAD\", :name \"Moroccan Dirham\", :symbol \"MAD\", :symbol_native \"د.م.\"}\n {:cod",
"end": 437,
"score": 0.9913339614868164,
"start": 422,
"tag": "NAME",
"value": "Moroccan Dirham"
},
{
"context": ", :symbol_native \"$\"}\n {:code \"KHR\", :name \"Cambodian Riel\", :symbol \"KHR\", :symbol_native \"៛\"}\n {:code \"M",
"end": 822,
"score": 0.716555118560791,
"start": 812,
"tag": "NAME",
"value": "odian Riel"
},
{
"context": "KHR\", :symbol_native \"៛\"}\n {:code \"MKD\", :name \"Macedonian Denar\", :symbol \"MKD\", :symbol_native \"MKD\"}\n {:code ",
"end": 900,
"score": 0.8985555171966553,
"start": 884,
"tag": "NAME",
"value": "Macedonian Denar"
},
{
"context": "bol_native \"£\"}\n {:code \"TOP\", :name \"Tongan Paʻanga\", :symbol \"T$\", :symbol_native \"T$\"}\n {:code \"H",
"end": 1060,
"score": 0.6845256090164185,
"start": 1056,
"tag": "NAME",
"value": "anga"
},
{
"context": "$\", :symbol_native \"T$\"}\n {:code \"HNL\", :name \"Honduran Lempira\", :symbol \"HNL\", :symbol_native \"L\"}\n {:code \"K",
"end": 1138,
"score": 0.7930172085762024,
"start": 1123,
"tag": "NAME",
"value": "onduran Lempira"
},
{
"context": "L\", :symbol_native \"L\"}\n {:code \"KWD\", :name \"Kuwaiti Dinar\", :symbol \"KD\", :symbol_native \"د.ك.\"}\n {:code",
"end": 1213,
"score": 0.7668051719665527,
"start": 1202,
"tag": "NAME",
"value": "waiti Dinar"
},
{
"context": "ve \"د.ك.\"}\n {:code \"PAB\", :name \"Panamanian Balboa\", :symbol \"B/.\", :symbol_native \"B/.\"}\n {:code",
"end": 1294,
"score": 0.5689734816551208,
"start": 1292,
"tag": "NAME",
"value": "bo"
},
{
"context": "\", :symbol_native \"B/.\"}\n {:code \"KES\", :name \"Kenyan Shilling\", :symbol \"Ksh\", :symbol_native \"Ksh\"}\n {:code ",
"end": 1374,
"score": 0.7962391972541809,
"start": 1360,
"tag": "NAME",
"value": "enyan Shilling"
},
{
"context": "\", :symbol_native \"դր.\"}\n {:code \"NIO\", :name \"Nicaraguan Córdoba\", :symbol \"C$\", :symbol_native \"C$\"}\n {",
"end": 1525,
"score": 0.636756181716919,
"start": 1516,
"tag": "NAME",
"value": "icaraguan"
},
{
"context": "native \"դր.\"}\n {:code \"NIO\", :name \"Nicaraguan Córdoba\", :symbol \"C$\", :symbol_native \"C$\"}\n {:code \"P",
"end": 1533,
"score": 0.7862637639045715,
"start": 1527,
"tag": "NAME",
"value": "órdoba"
},
{
"context": "l_native \"C$\"}\n {:code \"PKR\", :name \"Pakistani Rupee\", :symbol \"PKRs\", :symbol_native \"₨\"}\n {:code \"",
"end": 1610,
"score": 0.5912864804267883,
"start": 1606,
"tag": "NAME",
"value": "upee"
},
{
"context": ":symbol_native \"RM\"}\n {:code \"KZT\", :name \"Kazakhstani Tenge\", :symbol \"KZT\", :symbol_native \"тңг.\"}\n ",
"end": 1763,
"score": 0.6080793738365173,
"start": 1757,
"tag": "NAME",
"value": "hstani"
},
{
"context": "tive \"RM\"}\n {:code \"KZT\", :name \"Kazakhstani Tenge\", :symbol \"KZT\", :symbol_native \"тңг.\"}\n {:code",
"end": 1769,
"score": 0.6643732786178589,
"start": 1767,
"tag": "NAME",
"value": "ge"
},
{
"context": "bol_native \"тңг.\"}\n {:code \"ZMK\", :name \"Zambian Kwacha\", :symbol \"ZK\", :symbol_native \"ZK\"}\n {:code \"B",
"end": 1848,
"score": 0.658811092376709,
"start": 1842,
"tag": "NAME",
"value": "Kwacha"
},
{
"context": "ymbol_native \"Bs\"}\n {:code \"CRC\", :name \"Costa Rican Colón\", :symbol \"₡\", :symbol_native \"₡\"}\n {:code \"J",
"end": 2005,
"score": 0.5841432809829712,
"start": 1997,
"tag": "NAME",
"value": "ican Col"
},
{
"context": "\"₡\", :symbol_native \"₡\"}\n {:code \"JOD\", :name \"Jordanian Dinar\", :symbol \"JD\", :symbol_native \"د.أ.\"}\n {:code",
"end": 2082,
"score": 0.718970000743866,
"start": 2068,
"tag": "NAME",
"value": "ordanian Dinar"
},
{
"context": "\", :symbol_native \"$\"}\n {:code \"LYD\", :name \"Libyan Dinar\", :symbol \"LD\", :symbol_native \"د.ل.\"}\n {:code",
"end": 2472,
"score": 0.876977264881134,
"start": 2463,
"tag": "NAME",
"value": "yan Dinar"
},
{
"context": ", :symbol_native \"GH₵\"}\n {:code \"SYP\", :name \"Syrian Pound\", :symbol \"SY£\", :symbol_native \"ل.س.\"}\n ",
"end": 6507,
"score": 0.5302888751029968,
"start": 6503,
"tag": "NAME",
"value": "rian"
},
{
"context": "bol_native \"GH₵\"}\n {:code \"SYP\", :name \"Syrian Pound\", :symbol \"SY£\", :symbol_native \"ل.س.\"}\n {:cod",
"end": 6513,
"score": 0.5842548608779907,
"start": 6509,
"tag": "NAME",
"value": "ound"
},
{
"context": "native \"SDG\"}\n {:code \"ISK\", :name \"Icelandic Króna\", :symbol \"Ikr\", :symbol_native \"kr\"}\n {:code \"",
"end": 7513,
"score": 0.7141221165657043,
"start": 7510,
"tag": "NAME",
"value": "óna"
},
{
"context": "ol_native \"kr\"}\n {:code \"BHD\", :name \"Bahraini Dinar\", :symbol \"BD\", :symbol_native \"د.ب.\"}\n {:code",
"end": 7590,
"score": 0.7110542058944702,
"start": 7586,
"tag": "NAME",
"value": "inar"
},
{
"context": " :symbol_native \"د.ب.\"}\n {:code \"HRK\", :name \"Croatian Kuna\", :symbol \"kn\", :symbol_native \"kn\"}\n {:code \"G",
"end": 7668,
"score": 0.8833309412002563,
"start": 7656,
"tag": "NAME",
"value": "roatian Kuna"
},
{
"context": "\", :symbol_native \"kn\"}\n {:code \"GEL\", :name \"Georgian Lari\", :symbol \"GEL\", :symbol_native \"GEL\"}\n {:code ",
"end": 7743,
"score": 0.9033252000808716,
"start": 7732,
"tag": "NAME",
"value": "orgian Lari"
},
{
"context": "L\", :symbol_native \"GEL\"}\n {:code \"MOP\", :name \"Macanese Pataca\", :symbol \"MOP$\", :symbol_native \"MOP$\"}\n {:cod",
"end": 7822,
"score": 0.9877129793167114,
"start": 7807,
"tag": "NAME",
"value": "Macanese Pataca"
}
] | src/cljs/wkok/buy2let/currencies.cljs | wkok/re-frame-buy2let | 0 | (ns wkok.buy2let.currencies
(:require-macros [reagent-mui.util :refer [react-component]])
(:require [reagent.core :as ra]
[reagent-mui.material.autocomplete :refer [autocomplete] :rename {autocomplete mui-autocomplete}]
[reagent-mui.material.text-field :refer [text-field]]))
(def currencies
[{:code "IQD", :name "Iraqi Dinar", :symbol "IQD", :symbol_native "د.ع."}
{:code "MAD", :name "Moroccan Dirham", :symbol "MAD", :symbol_native "د.م."}
{:code "CHF", :name "Swiss Franc", :symbol "CHF", :symbol_native "CHF"}
{:code "GNF", :name "Guinean Franc", :symbol "FG", :symbol_native "FG"}
{:code "DOP", :name "Dominican Peso", :symbol "RD$", :symbol_native "RD$"}
{:code "SGD", :name "Singapore Dollar", :symbol "S$", :symbol_native "$"}
{:code "KHR", :name "Cambodian Riel", :symbol "KHR", :symbol_native "៛"}
{:code "MKD", :name "Macedonian Denar", :symbol "MKD", :symbol_native "MKD"}
{:code "GBP", :name "British Pound Sterling", :symbol "£", :symbol_native "£"}
{:code "TOP", :name "Tongan Paʻanga", :symbol "T$", :symbol_native "T$"}
{:code "HNL", :name "Honduran Lempira", :symbol "HNL", :symbol_native "L"}
{:code "KWD", :name "Kuwaiti Dinar", :symbol "KD", :symbol_native "د.ك."}
{:code "PAB", :name "Panamanian Balboa", :symbol "B/.", :symbol_native "B/."}
{:code "KES", :name "Kenyan Shilling", :symbol "Ksh", :symbol_native "Ksh"}
{:code "AMD", :name "Armenian Dram", :symbol "AMD", :symbol_native "դր."}
{:code "NIO", :name "Nicaraguan Córdoba", :symbol "C$", :symbol_native "C$"}
{:code "PKR", :name "Pakistani Rupee", :symbol "PKRs", :symbol_native "₨"}
{:code "MYR", :name "Malaysian Ringgit", :symbol "RM", :symbol_native "RM"}
{:code "KZT", :name "Kazakhstani Tenge", :symbol "KZT", :symbol_native "тңг."}
{:code "ZMK", :name "Zambian Kwacha", :symbol "ZK", :symbol_native "ZK"}
{:code "BOB", :name "Bolivian Boliviano", :symbol "Bs", :symbol_native "Bs"}
{:code "CRC", :name "Costa Rican Colón", :symbol "₡", :symbol_native "₡"}
{:code "JOD", :name "Jordanian Dinar", :symbol "JD", :symbol_native "د.أ."}
{:code "ERN", :name "Eritrean Nakfa", :symbol "Nfk", :symbol_native "Nfk"}
{:code "CZK", :name "Czech Republic Koruna", :symbol "Kč", :symbol_native "Kč"}
{:code "LVL", :name "Latvian Lats", :symbol "Ls", :symbol_native "Ls"}
{:code "HKD", :name "Hong Kong Dollar", :symbol "HK$", :symbol_native "$"}
{:code "LYD", :name "Libyan Dinar", :symbol "LD", :symbol_native "د.ل."}
{:code "XAF", :name "CFA Franc BEAC", :symbol "FCFA", :symbol_native "FCFA"}
{:code "GTQ", :name "Guatemalan Quetzal", :symbol "GTQ", :symbol_native "Q"}
{:code "DJF", :name "Djiboutian Franc", :symbol "Fdj", :symbol_native "Fdj"}
{:code "UAH", :name "Ukrainian Hryvnia", :symbol "₴", :symbol_native "₴"}
{:code "RWF", :name "Rwandan Franc", :symbol "RWF", :symbol_native "FR"}
{:code "BWP", :name "Botswanan Pula", :symbol "BWP", :symbol_native "P"}
{:code "CLP", :name "Chilean Peso", :symbol "CL$", :symbol_native "$"}
{:code "ZWL", :name "Zimbabwean Dollar", :symbol "ZWL$", :symbol_native "ZWL$"}
{:code "OMR", :name "Omani Rial", :symbol "OMR", :symbol_native "ر.ع."}
{:code "PLN", :name "Polish Zloty", :symbol "zł", :symbol_native "zł"}
{:code "MZN", :name "Mozambican Metical", :symbol "MTn", :symbol_native "MTn"}
{:code "AFN", :name "Afghan Afghani", :symbol "Af", :symbol_native "؋"}
{:code "PYG", :name "Paraguayan Guarani", :symbol "₲", :symbol_native "₲"}
{:code "TRY", :name "Turkish Lira", :symbol "TL", :symbol_native "TL"}
{:code "BZD", :name "Belize Dollar", :symbol "BZ$", :symbol_native "$"}
{:code "MDL", :name "Moldovan Leu", :symbol "MDL", :symbol_native "MDL"}
{:code "JPY", :name "Japanese Yen", :symbol "¥", :symbol_native "¥"}
{:code "INR", :name "Indian Rupee", :symbol "Rs", :symbol_native "টকা"}
{:code "RSD", :name "Serbian Dinar", :symbol "din.", :symbol_native "дин."}
{:code "TTD", :name "Trinidad and Tobago Dollar", :symbol "TT$", :symbol_native "$"}
{:code "BIF", :name "Burundian Franc", :symbol "FBu", :symbol_native "FBu"}
{:code "SEK", :name "Swedish Krona", :symbol "Skr", :symbol_native "kr"}
{:code "IDR", :name "Indonesian Rupiah", :symbol "Rp", :symbol_native "Rp"}
{:code "ARS", :name "Argentine Peso", :symbol "AR$", :symbol_native "$"}
{:code "VND", :name "Vietnamese Dong", :symbol "₫", :symbol_native "₫"}
{:code "MUR", :name "Mauritian Rupee", :symbol "MURs", :symbol_native "MURs"}
{:code "NGN", :name "Nigerian Naira", :symbol "₦", :symbol_native "₦"}
{:code "KRW", :name "South Korean Won", :symbol "₩", :symbol_native "₩"}
{:code "MGA", :name "Malagasy Ariary", :symbol "MGA", :symbol_native "MGA"}
{:code "KMF", :name "Comorian Franc", :symbol "CF", :symbol_native "FC"}
{:code "BYN", :name "Belarusian Ruble", :symbol "Br", :symbol_native "руб."}
{:code "AED", :name "United Arab Emirates Dirham", :symbol "AED", :symbol_native "د.إ."}
{:code "EGP", :name "Egyptian Pound", :symbol "EGP", :symbol_native "ج.م."}
{:code "THB", :name "Thai Baht", :symbol "฿", :symbol_native "฿"}
{:code "DZD", :name "Algerian Dinar", :symbol "DA", :symbol_native "د.ج."}
{:code "TZS", :name "Tanzanian Shilling", :symbol "TSh", :symbol_native "TSh"}
{:code "LKR", :name "Sri Lankan Rupee", :symbol "SLRs", :symbol_native "SL Re"}
{:code "YER", :name "Yemeni Rial", :symbol "YR", :symbol_native "ر.ي."}
{:code "NZD", :name "New Zealand Dollar", :symbol "NZ$", :symbol_native "$"}
{:code "USD", :name "US Dollar", :symbol "$", :symbol_native "$"}
{:code "UGX", :name "Ugandan Shilling", :symbol "USh", :symbol_native "USh"}
{:code "TWD", :name "New Taiwan Dollar", :symbol "NT$", :symbol_native "NT$"}
{:code "CAD", :name "Canadian Dollar", :symbol "CA$", :symbol_native "$"}
{:code "ILS", :name "Israeli New Sheqel", :symbol "₪", :symbol_native "₪"}
{:code "MMK", :name "Myanma Kyat", :symbol "MMK", :symbol_native "K"}
{:code "CNY", :name "Chinese Yuan", :symbol "CN¥", :symbol_native "CN¥"}
{:code "MXN", :name "Mexican Peso", :symbol "MX$", :symbol_native "$"}
{:code "PEN", :name "Peruvian Nuevo Sol", :symbol "S/.", :symbol_native "S/."}
{:code "IRR", :name "Iranian Rial", :symbol "IRR", :symbol_native "﷼"}
{:code "CDF", :name "Congolese Franc", :symbol "CDF", :symbol_native "FrCD"}
{:code "GHS", :name "Ghanaian Cedi", :symbol "GH₵", :symbol_native "GH₵"}
{:code "SYP", :name "Syrian Pound", :symbol "SY£", :symbol_native "ل.س."}
{:code "SOS", :name "Somali Shilling", :symbol "Ssh", :symbol_native "Ssh"}
{:code "BDT", :name "Bangladeshi Taka", :symbol "Tk", :symbol_native "৳"}
{:code "EUR", :name "Euro", :symbol "€", :symbol_native "€"}
{:code "RUB", :name "Russian Ruble", :symbol "RUB", :symbol_native "₽."}
{:code "UZS", :name "Uzbekistan Som", :symbol "UZS", :symbol_native "UZS"}
{:code "RON", :name "Romanian Leu", :symbol "RON", :symbol_native "RON"}
{:code "ALL", :name "Albanian Lek", :symbol "ALL", :symbol_native "Lek"}
{:code "NAD", :name "Namibian Dollar", :symbol "N$", :symbol_native "N$"}
{:code "NOK", :name "Norwegian Krone", :symbol "Nkr", :symbol_native "kr"}
{:code "NPR", :name "Nepalese Rupee", :symbol "NPRs", :symbol_native "नेरू"}
{:code "LBP", :name "Lebanese Pound", :symbol "LB£", :symbol_native "ل.ل."}
{:code "SDG", :name "Sudanese Pound", :symbol "SDG", :symbol_native "SDG"}
{:code "ISK", :name "Icelandic Króna", :symbol "Ikr", :symbol_native "kr"}
{:code "BHD", :name "Bahraini Dinar", :symbol "BD", :symbol_native "د.ب."}
{:code "HRK", :name "Croatian Kuna", :symbol "kn", :symbol_native "kn"}
{:code "GEL", :name "Georgian Lari", :symbol "GEL", :symbol_native "GEL"}
{:code "MOP", :name "Macanese Pataca", :symbol "MOP$", :symbol_native "MOP$"}
{:code "PHP", :name "Philippine Peso", :symbol "₱", :symbol_native "₱"}
{:code "BND", :name "Brunei Dollar", :symbol "BN$", :symbol_native "$"}
{:code "HUF", :name "Hungarian Forint", :symbol "Ft", :symbol_native "Ft"}
{:code "TND", :name "Tunisian Dinar", :symbol "DT", :symbol_native "د.ت."}
{:code "LTL", :name "Lithuanian Litas", :symbol "Lt", :symbol_native "Lt"}
{:code "SAR", :name "Saudi Riyal", :symbol "SR", :symbol_native "ر.س."}
{:code "COP", :name "Colombian Peso", :symbol "CO$", :symbol_native "$"}
{:code "UYU", :name "Uruguayan Peso", :symbol "$U", :symbol_native "$"}
{:code "CVE", :name "Cape Verdean Escudo", :symbol "CV$", :symbol_native "CV$"}
{:code "BAM", :name "Bosnia-Herzegovina Convertible Mark", :symbol "KM", :symbol_native "KM"}
{:code "AZN", :name "Azerbaijani Manat", :symbol "man.", :symbol_native "ман."}
{:code "AUD", :name "Australian Dollar", :symbol "AU$", :symbol_native "$"}
{:code "BRL", :name "Brazilian Real", :symbol "R$", :symbol_native "R$"}
{:code "JMD", :name "Jamaican Dollar", :symbol "J$", :symbol_native "$"}
{:code "DKK", :name "Danish Krone", :symbol "Dkr", :symbol_native "kr"}
{:code "ETB", :name "Ethiopian Birr", :symbol "Br", :symbol_native "Br"}
{:code "QAR", :name "Qatari Rial", :symbol "QR", :symbol_native "ر.ق."}
{:code "ZAR", :name "South African Rand", :symbol "R", :symbol_native "R"}
{:code "VEF", :name "Venezuelan Bolívar", :symbol "Bs.F.", :symbol_native "Bs.F."}
{:code "BGN", :name "Bulgarian Lev", :symbol "BGN", :symbol_native "лв."}
{:code "EEK", :name "Estonian Kroon", :symbol "Ekr", :symbol_native "kr"}
{:code "XOF", :name "CFA Franc BCEAO", :symbol "CFA", :symbol_native "CFA"}])
(defn select-currency
[{:keys [class value on-change error helper-text]}]
(let [options (sort-by :code currencies)]
[mui-autocomplete
{:id "select-currency-demo"
:class class
:options options
:render-input (react-component [props]
[text-field (merge props
{:variant :standard
:label "Currency"
:error error
:helper-text helper-text})])
:render-option (react-component [props option]
[:li props
(str (:code option) " - " (:name option))])
:get-option-label #(let [option (js->clj %)]
(str (get option "code") " - " (get option "name")))
:is-option-equal-to-value #(let [option (js->clj %1)
value (js->clj %2)]
(= (get option "code") (get value "code")))
:value (->> options
(filter #(= (:code %) value))
first)
:on-change (fn [_ value _]
(let [selected (js->clj value)
code (get selected "code")]
(on-change code)))}]))
| 100056 | (ns wkok.buy2let.currencies
(:require-macros [reagent-mui.util :refer [react-component]])
(:require [reagent.core :as ra]
[reagent-mui.material.autocomplete :refer [autocomplete] :rename {autocomplete mui-autocomplete}]
[reagent-mui.material.text-field :refer [text-field]]))
(def currencies
[{:code "IQD", :name "I<NAME>", :symbol "IQD", :symbol_native "د.ع."}
{:code "MAD", :name "<NAME>", :symbol "MAD", :symbol_native "د.م."}
{:code "CHF", :name "Swiss Franc", :symbol "CHF", :symbol_native "CHF"}
{:code "GNF", :name "Guinean Franc", :symbol "FG", :symbol_native "FG"}
{:code "DOP", :name "Dominican Peso", :symbol "RD$", :symbol_native "RD$"}
{:code "SGD", :name "Singapore Dollar", :symbol "S$", :symbol_native "$"}
{:code "KHR", :name "Camb<NAME>", :symbol "KHR", :symbol_native "៛"}
{:code "MKD", :name "<NAME>", :symbol "MKD", :symbol_native "MKD"}
{:code "GBP", :name "British Pound Sterling", :symbol "£", :symbol_native "£"}
{:code "TOP", :name "Tongan Paʻ<NAME>", :symbol "T$", :symbol_native "T$"}
{:code "HNL", :name "H<NAME>", :symbol "HNL", :symbol_native "L"}
{:code "KWD", :name "Ku<NAME>", :symbol "KD", :symbol_native "د.ك."}
{:code "PAB", :name "Panamanian Bal<NAME>a", :symbol "B/.", :symbol_native "B/."}
{:code "KES", :name "K<NAME>", :symbol "Ksh", :symbol_native "Ksh"}
{:code "AMD", :name "Armenian Dram", :symbol "AMD", :symbol_native "դր."}
{:code "NIO", :name "N<NAME> C<NAME>", :symbol "C$", :symbol_native "C$"}
{:code "PKR", :name "Pakistani R<NAME>", :symbol "PKRs", :symbol_native "₨"}
{:code "MYR", :name "Malaysian Ringgit", :symbol "RM", :symbol_native "RM"}
{:code "KZT", :name "Kazak<NAME> Ten<NAME>", :symbol "KZT", :symbol_native "тңг."}
{:code "ZMK", :name "Zambian <NAME>", :symbol "ZK", :symbol_native "ZK"}
{:code "BOB", :name "Bolivian Boliviano", :symbol "Bs", :symbol_native "Bs"}
{:code "CRC", :name "Costa R<NAME>ón", :symbol "₡", :symbol_native "₡"}
{:code "JOD", :name "J<NAME>", :symbol "JD", :symbol_native "د.أ."}
{:code "ERN", :name "Eritrean Nakfa", :symbol "Nfk", :symbol_native "Nfk"}
{:code "CZK", :name "Czech Republic Koruna", :symbol "Kč", :symbol_native "Kč"}
{:code "LVL", :name "Latvian Lats", :symbol "Ls", :symbol_native "Ls"}
{:code "HKD", :name "Hong Kong Dollar", :symbol "HK$", :symbol_native "$"}
{:code "LYD", :name "Lib<NAME>", :symbol "LD", :symbol_native "د.ل."}
{:code "XAF", :name "CFA Franc BEAC", :symbol "FCFA", :symbol_native "FCFA"}
{:code "GTQ", :name "Guatemalan Quetzal", :symbol "GTQ", :symbol_native "Q"}
{:code "DJF", :name "Djiboutian Franc", :symbol "Fdj", :symbol_native "Fdj"}
{:code "UAH", :name "Ukrainian Hryvnia", :symbol "₴", :symbol_native "₴"}
{:code "RWF", :name "Rwandan Franc", :symbol "RWF", :symbol_native "FR"}
{:code "BWP", :name "Botswanan Pula", :symbol "BWP", :symbol_native "P"}
{:code "CLP", :name "Chilean Peso", :symbol "CL$", :symbol_native "$"}
{:code "ZWL", :name "Zimbabwean Dollar", :symbol "ZWL$", :symbol_native "ZWL$"}
{:code "OMR", :name "Omani Rial", :symbol "OMR", :symbol_native "ر.ع."}
{:code "PLN", :name "Polish Zloty", :symbol "zł", :symbol_native "zł"}
{:code "MZN", :name "Mozambican Metical", :symbol "MTn", :symbol_native "MTn"}
{:code "AFN", :name "Afghan Afghani", :symbol "Af", :symbol_native "؋"}
{:code "PYG", :name "Paraguayan Guarani", :symbol "₲", :symbol_native "₲"}
{:code "TRY", :name "Turkish Lira", :symbol "TL", :symbol_native "TL"}
{:code "BZD", :name "Belize Dollar", :symbol "BZ$", :symbol_native "$"}
{:code "MDL", :name "Moldovan Leu", :symbol "MDL", :symbol_native "MDL"}
{:code "JPY", :name "Japanese Yen", :symbol "¥", :symbol_native "¥"}
{:code "INR", :name "Indian Rupee", :symbol "Rs", :symbol_native "টকা"}
{:code "RSD", :name "Serbian Dinar", :symbol "din.", :symbol_native "дин."}
{:code "TTD", :name "Trinidad and Tobago Dollar", :symbol "TT$", :symbol_native "$"}
{:code "BIF", :name "Burundian Franc", :symbol "FBu", :symbol_native "FBu"}
{:code "SEK", :name "Swedish Krona", :symbol "Skr", :symbol_native "kr"}
{:code "IDR", :name "Indonesian Rupiah", :symbol "Rp", :symbol_native "Rp"}
{:code "ARS", :name "Argentine Peso", :symbol "AR$", :symbol_native "$"}
{:code "VND", :name "Vietnamese Dong", :symbol "₫", :symbol_native "₫"}
{:code "MUR", :name "Mauritian Rupee", :symbol "MURs", :symbol_native "MURs"}
{:code "NGN", :name "Nigerian Naira", :symbol "₦", :symbol_native "₦"}
{:code "KRW", :name "South Korean Won", :symbol "₩", :symbol_native "₩"}
{:code "MGA", :name "Malagasy Ariary", :symbol "MGA", :symbol_native "MGA"}
{:code "KMF", :name "Comorian Franc", :symbol "CF", :symbol_native "FC"}
{:code "BYN", :name "Belarusian Ruble", :symbol "Br", :symbol_native "руб."}
{:code "AED", :name "United Arab Emirates Dirham", :symbol "AED", :symbol_native "د.إ."}
{:code "EGP", :name "Egyptian Pound", :symbol "EGP", :symbol_native "ج.م."}
{:code "THB", :name "Thai Baht", :symbol "฿", :symbol_native "฿"}
{:code "DZD", :name "Algerian Dinar", :symbol "DA", :symbol_native "د.ج."}
{:code "TZS", :name "Tanzanian Shilling", :symbol "TSh", :symbol_native "TSh"}
{:code "LKR", :name "Sri Lankan Rupee", :symbol "SLRs", :symbol_native "SL Re"}
{:code "YER", :name "Yemeni Rial", :symbol "YR", :symbol_native "ر.ي."}
{:code "NZD", :name "New Zealand Dollar", :symbol "NZ$", :symbol_native "$"}
{:code "USD", :name "US Dollar", :symbol "$", :symbol_native "$"}
{:code "UGX", :name "Ugandan Shilling", :symbol "USh", :symbol_native "USh"}
{:code "TWD", :name "New Taiwan Dollar", :symbol "NT$", :symbol_native "NT$"}
{:code "CAD", :name "Canadian Dollar", :symbol "CA$", :symbol_native "$"}
{:code "ILS", :name "Israeli New Sheqel", :symbol "₪", :symbol_native "₪"}
{:code "MMK", :name "Myanma Kyat", :symbol "MMK", :symbol_native "K"}
{:code "CNY", :name "Chinese Yuan", :symbol "CN¥", :symbol_native "CN¥"}
{:code "MXN", :name "Mexican Peso", :symbol "MX$", :symbol_native "$"}
{:code "PEN", :name "Peruvian Nuevo Sol", :symbol "S/.", :symbol_native "S/."}
{:code "IRR", :name "Iranian Rial", :symbol "IRR", :symbol_native "﷼"}
{:code "CDF", :name "Congolese Franc", :symbol "CDF", :symbol_native "FrCD"}
{:code "GHS", :name "Ghanaian Cedi", :symbol "GH₵", :symbol_native "GH₵"}
{:code "SYP", :name "Sy<NAME> P<NAME>", :symbol "SY£", :symbol_native "ل.س."}
{:code "SOS", :name "Somali Shilling", :symbol "Ssh", :symbol_native "Ssh"}
{:code "BDT", :name "Bangladeshi Taka", :symbol "Tk", :symbol_native "৳"}
{:code "EUR", :name "Euro", :symbol "€", :symbol_native "€"}
{:code "RUB", :name "Russian Ruble", :symbol "RUB", :symbol_native "₽."}
{:code "UZS", :name "Uzbekistan Som", :symbol "UZS", :symbol_native "UZS"}
{:code "RON", :name "Romanian Leu", :symbol "RON", :symbol_native "RON"}
{:code "ALL", :name "Albanian Lek", :symbol "ALL", :symbol_native "Lek"}
{:code "NAD", :name "Namibian Dollar", :symbol "N$", :symbol_native "N$"}
{:code "NOK", :name "Norwegian Krone", :symbol "Nkr", :symbol_native "kr"}
{:code "NPR", :name "Nepalese Rupee", :symbol "NPRs", :symbol_native "नेरू"}
{:code "LBP", :name "Lebanese Pound", :symbol "LB£", :symbol_native "ل.ل."}
{:code "SDG", :name "Sudanese Pound", :symbol "SDG", :symbol_native "SDG"}
{:code "ISK", :name "Icelandic Kr<NAME>", :symbol "Ikr", :symbol_native "kr"}
{:code "BHD", :name "Bahraini D<NAME>", :symbol "BD", :symbol_native "د.ب."}
{:code "HRK", :name "C<NAME>", :symbol "kn", :symbol_native "kn"}
{:code "GEL", :name "Ge<NAME>", :symbol "GEL", :symbol_native "GEL"}
{:code "MOP", :name "<NAME>", :symbol "MOP$", :symbol_native "MOP$"}
{:code "PHP", :name "Philippine Peso", :symbol "₱", :symbol_native "₱"}
{:code "BND", :name "Brunei Dollar", :symbol "BN$", :symbol_native "$"}
{:code "HUF", :name "Hungarian Forint", :symbol "Ft", :symbol_native "Ft"}
{:code "TND", :name "Tunisian Dinar", :symbol "DT", :symbol_native "د.ت."}
{:code "LTL", :name "Lithuanian Litas", :symbol "Lt", :symbol_native "Lt"}
{:code "SAR", :name "Saudi Riyal", :symbol "SR", :symbol_native "ر.س."}
{:code "COP", :name "Colombian Peso", :symbol "CO$", :symbol_native "$"}
{:code "UYU", :name "Uruguayan Peso", :symbol "$U", :symbol_native "$"}
{:code "CVE", :name "Cape Verdean Escudo", :symbol "CV$", :symbol_native "CV$"}
{:code "BAM", :name "Bosnia-Herzegovina Convertible Mark", :symbol "KM", :symbol_native "KM"}
{:code "AZN", :name "Azerbaijani Manat", :symbol "man.", :symbol_native "ман."}
{:code "AUD", :name "Australian Dollar", :symbol "AU$", :symbol_native "$"}
{:code "BRL", :name "Brazilian Real", :symbol "R$", :symbol_native "R$"}
{:code "JMD", :name "Jamaican Dollar", :symbol "J$", :symbol_native "$"}
{:code "DKK", :name "Danish Krone", :symbol "Dkr", :symbol_native "kr"}
{:code "ETB", :name "Ethiopian Birr", :symbol "Br", :symbol_native "Br"}
{:code "QAR", :name "Qatari Rial", :symbol "QR", :symbol_native "ر.ق."}
{:code "ZAR", :name "South African Rand", :symbol "R", :symbol_native "R"}
{:code "VEF", :name "Venezuelan Bolívar", :symbol "Bs.F.", :symbol_native "Bs.F."}
{:code "BGN", :name "Bulgarian Lev", :symbol "BGN", :symbol_native "лв."}
{:code "EEK", :name "Estonian Kroon", :symbol "Ekr", :symbol_native "kr"}
{:code "XOF", :name "CFA Franc BCEAO", :symbol "CFA", :symbol_native "CFA"}])
(defn select-currency
[{:keys [class value on-change error helper-text]}]
(let [options (sort-by :code currencies)]
[mui-autocomplete
{:id "select-currency-demo"
:class class
:options options
:render-input (react-component [props]
[text-field (merge props
{:variant :standard
:label "Currency"
:error error
:helper-text helper-text})])
:render-option (react-component [props option]
[:li props
(str (:code option) " - " (:name option))])
:get-option-label #(let [option (js->clj %)]
(str (get option "code") " - " (get option "name")))
:is-option-equal-to-value #(let [option (js->clj %1)
value (js->clj %2)]
(= (get option "code") (get value "code")))
:value (->> options
(filter #(= (:code %) value))
first)
:on-change (fn [_ value _]
(let [selected (js->clj value)
code (get selected "code")]
(on-change code)))}]))
| true | (ns wkok.buy2let.currencies
(:require-macros [reagent-mui.util :refer [react-component]])
(:require [reagent.core :as ra]
[reagent-mui.material.autocomplete :refer [autocomplete] :rename {autocomplete mui-autocomplete}]
[reagent-mui.material.text-field :refer [text-field]]))
(def currencies
[{:code "IQD", :name "IPI:NAME:<NAME>END_PI", :symbol "IQD", :symbol_native "د.ع."}
{:code "MAD", :name "PI:NAME:<NAME>END_PI", :symbol "MAD", :symbol_native "د.م."}
{:code "CHF", :name "Swiss Franc", :symbol "CHF", :symbol_native "CHF"}
{:code "GNF", :name "Guinean Franc", :symbol "FG", :symbol_native "FG"}
{:code "DOP", :name "Dominican Peso", :symbol "RD$", :symbol_native "RD$"}
{:code "SGD", :name "Singapore Dollar", :symbol "S$", :symbol_native "$"}
{:code "KHR", :name "CambPI:NAME:<NAME>END_PI", :symbol "KHR", :symbol_native "៛"}
{:code "MKD", :name "PI:NAME:<NAME>END_PI", :symbol "MKD", :symbol_native "MKD"}
{:code "GBP", :name "British Pound Sterling", :symbol "£", :symbol_native "£"}
{:code "TOP", :name "Tongan PaʻPI:NAME:<NAME>END_PI", :symbol "T$", :symbol_native "T$"}
{:code "HNL", :name "HPI:NAME:<NAME>END_PI", :symbol "HNL", :symbol_native "L"}
{:code "KWD", :name "KuPI:NAME:<NAME>END_PI", :symbol "KD", :symbol_native "د.ك."}
{:code "PAB", :name "Panamanian BalPI:NAME:<NAME>END_PIa", :symbol "B/.", :symbol_native "B/."}
{:code "KES", :name "KPI:NAME:<NAME>END_PI", :symbol "Ksh", :symbol_native "Ksh"}
{:code "AMD", :name "Armenian Dram", :symbol "AMD", :symbol_native "դր."}
{:code "NIO", :name "NPI:NAME:<NAME>END_PI CPI:NAME:<NAME>END_PI", :symbol "C$", :symbol_native "C$"}
{:code "PKR", :name "Pakistani RPI:NAME:<NAME>END_PI", :symbol "PKRs", :symbol_native "₨"}
{:code "MYR", :name "Malaysian Ringgit", :symbol "RM", :symbol_native "RM"}
{:code "KZT", :name "KazakPI:NAME:<NAME>END_PI TenPI:NAME:<NAME>END_PI", :symbol "KZT", :symbol_native "тңг."}
{:code "ZMK", :name "Zambian PI:NAME:<NAME>END_PI", :symbol "ZK", :symbol_native "ZK"}
{:code "BOB", :name "Bolivian Boliviano", :symbol "Bs", :symbol_native "Bs"}
{:code "CRC", :name "Costa RPI:NAME:<NAME>END_PIón", :symbol "₡", :symbol_native "₡"}
{:code "JOD", :name "JPI:NAME:<NAME>END_PI", :symbol "JD", :symbol_native "د.أ."}
{:code "ERN", :name "Eritrean Nakfa", :symbol "Nfk", :symbol_native "Nfk"}
{:code "CZK", :name "Czech Republic Koruna", :symbol "Kč", :symbol_native "Kč"}
{:code "LVL", :name "Latvian Lats", :symbol "Ls", :symbol_native "Ls"}
{:code "HKD", :name "Hong Kong Dollar", :symbol "HK$", :symbol_native "$"}
{:code "LYD", :name "LibPI:NAME:<NAME>END_PI", :symbol "LD", :symbol_native "د.ل."}
{:code "XAF", :name "CFA Franc BEAC", :symbol "FCFA", :symbol_native "FCFA"}
{:code "GTQ", :name "Guatemalan Quetzal", :symbol "GTQ", :symbol_native "Q"}
{:code "DJF", :name "Djiboutian Franc", :symbol "Fdj", :symbol_native "Fdj"}
{:code "UAH", :name "Ukrainian Hryvnia", :symbol "₴", :symbol_native "₴"}
{:code "RWF", :name "Rwandan Franc", :symbol "RWF", :symbol_native "FR"}
{:code "BWP", :name "Botswanan Pula", :symbol "BWP", :symbol_native "P"}
{:code "CLP", :name "Chilean Peso", :symbol "CL$", :symbol_native "$"}
{:code "ZWL", :name "Zimbabwean Dollar", :symbol "ZWL$", :symbol_native "ZWL$"}
{:code "OMR", :name "Omani Rial", :symbol "OMR", :symbol_native "ر.ع."}
{:code "PLN", :name "Polish Zloty", :symbol "zł", :symbol_native "zł"}
{:code "MZN", :name "Mozambican Metical", :symbol "MTn", :symbol_native "MTn"}
{:code "AFN", :name "Afghan Afghani", :symbol "Af", :symbol_native "؋"}
{:code "PYG", :name "Paraguayan Guarani", :symbol "₲", :symbol_native "₲"}
{:code "TRY", :name "Turkish Lira", :symbol "TL", :symbol_native "TL"}
{:code "BZD", :name "Belize Dollar", :symbol "BZ$", :symbol_native "$"}
{:code "MDL", :name "Moldovan Leu", :symbol "MDL", :symbol_native "MDL"}
{:code "JPY", :name "Japanese Yen", :symbol "¥", :symbol_native "¥"}
{:code "INR", :name "Indian Rupee", :symbol "Rs", :symbol_native "টকা"}
{:code "RSD", :name "Serbian Dinar", :symbol "din.", :symbol_native "дин."}
{:code "TTD", :name "Trinidad and Tobago Dollar", :symbol "TT$", :symbol_native "$"}
{:code "BIF", :name "Burundian Franc", :symbol "FBu", :symbol_native "FBu"}
{:code "SEK", :name "Swedish Krona", :symbol "Skr", :symbol_native "kr"}
{:code "IDR", :name "Indonesian Rupiah", :symbol "Rp", :symbol_native "Rp"}
{:code "ARS", :name "Argentine Peso", :symbol "AR$", :symbol_native "$"}
{:code "VND", :name "Vietnamese Dong", :symbol "₫", :symbol_native "₫"}
{:code "MUR", :name "Mauritian Rupee", :symbol "MURs", :symbol_native "MURs"}
{:code "NGN", :name "Nigerian Naira", :symbol "₦", :symbol_native "₦"}
{:code "KRW", :name "South Korean Won", :symbol "₩", :symbol_native "₩"}
{:code "MGA", :name "Malagasy Ariary", :symbol "MGA", :symbol_native "MGA"}
{:code "KMF", :name "Comorian Franc", :symbol "CF", :symbol_native "FC"}
{:code "BYN", :name "Belarusian Ruble", :symbol "Br", :symbol_native "руб."}
{:code "AED", :name "United Arab Emirates Dirham", :symbol "AED", :symbol_native "د.إ."}
{:code "EGP", :name "Egyptian Pound", :symbol "EGP", :symbol_native "ج.م."}
{:code "THB", :name "Thai Baht", :symbol "฿", :symbol_native "฿"}
{:code "DZD", :name "Algerian Dinar", :symbol "DA", :symbol_native "د.ج."}
{:code "TZS", :name "Tanzanian Shilling", :symbol "TSh", :symbol_native "TSh"}
{:code "LKR", :name "Sri Lankan Rupee", :symbol "SLRs", :symbol_native "SL Re"}
{:code "YER", :name "Yemeni Rial", :symbol "YR", :symbol_native "ر.ي."}
{:code "NZD", :name "New Zealand Dollar", :symbol "NZ$", :symbol_native "$"}
{:code "USD", :name "US Dollar", :symbol "$", :symbol_native "$"}
{:code "UGX", :name "Ugandan Shilling", :symbol "USh", :symbol_native "USh"}
{:code "TWD", :name "New Taiwan Dollar", :symbol "NT$", :symbol_native "NT$"}
{:code "CAD", :name "Canadian Dollar", :symbol "CA$", :symbol_native "$"}
{:code "ILS", :name "Israeli New Sheqel", :symbol "₪", :symbol_native "₪"}
{:code "MMK", :name "Myanma Kyat", :symbol "MMK", :symbol_native "K"}
{:code "CNY", :name "Chinese Yuan", :symbol "CN¥", :symbol_native "CN¥"}
{:code "MXN", :name "Mexican Peso", :symbol "MX$", :symbol_native "$"}
{:code "PEN", :name "Peruvian Nuevo Sol", :symbol "S/.", :symbol_native "S/."}
{:code "IRR", :name "Iranian Rial", :symbol "IRR", :symbol_native "﷼"}
{:code "CDF", :name "Congolese Franc", :symbol "CDF", :symbol_native "FrCD"}
{:code "GHS", :name "Ghanaian Cedi", :symbol "GH₵", :symbol_native "GH₵"}
{:code "SYP", :name "SyPI:NAME:<NAME>END_PI PPI:NAME:<NAME>END_PI", :symbol "SY£", :symbol_native "ل.س."}
{:code "SOS", :name "Somali Shilling", :symbol "Ssh", :symbol_native "Ssh"}
{:code "BDT", :name "Bangladeshi Taka", :symbol "Tk", :symbol_native "৳"}
{:code "EUR", :name "Euro", :symbol "€", :symbol_native "€"}
{:code "RUB", :name "Russian Ruble", :symbol "RUB", :symbol_native "₽."}
{:code "UZS", :name "Uzbekistan Som", :symbol "UZS", :symbol_native "UZS"}
{:code "RON", :name "Romanian Leu", :symbol "RON", :symbol_native "RON"}
{:code "ALL", :name "Albanian Lek", :symbol "ALL", :symbol_native "Lek"}
{:code "NAD", :name "Namibian Dollar", :symbol "N$", :symbol_native "N$"}
{:code "NOK", :name "Norwegian Krone", :symbol "Nkr", :symbol_native "kr"}
{:code "NPR", :name "Nepalese Rupee", :symbol "NPRs", :symbol_native "नेरू"}
{:code "LBP", :name "Lebanese Pound", :symbol "LB£", :symbol_native "ل.ل."}
{:code "SDG", :name "Sudanese Pound", :symbol "SDG", :symbol_native "SDG"}
{:code "ISK", :name "Icelandic KrPI:NAME:<NAME>END_PI", :symbol "Ikr", :symbol_native "kr"}
{:code "BHD", :name "Bahraini DPI:NAME:<NAME>END_PI", :symbol "BD", :symbol_native "د.ب."}
{:code "HRK", :name "CPI:NAME:<NAME>END_PI", :symbol "kn", :symbol_native "kn"}
{:code "GEL", :name "GePI:NAME:<NAME>END_PI", :symbol "GEL", :symbol_native "GEL"}
{:code "MOP", :name "PI:NAME:<NAME>END_PI", :symbol "MOP$", :symbol_native "MOP$"}
{:code "PHP", :name "Philippine Peso", :symbol "₱", :symbol_native "₱"}
{:code "BND", :name "Brunei Dollar", :symbol "BN$", :symbol_native "$"}
{:code "HUF", :name "Hungarian Forint", :symbol "Ft", :symbol_native "Ft"}
{:code "TND", :name "Tunisian Dinar", :symbol "DT", :symbol_native "د.ت."}
{:code "LTL", :name "Lithuanian Litas", :symbol "Lt", :symbol_native "Lt"}
{:code "SAR", :name "Saudi Riyal", :symbol "SR", :symbol_native "ر.س."}
{:code "COP", :name "Colombian Peso", :symbol "CO$", :symbol_native "$"}
{:code "UYU", :name "Uruguayan Peso", :symbol "$U", :symbol_native "$"}
{:code "CVE", :name "Cape Verdean Escudo", :symbol "CV$", :symbol_native "CV$"}
{:code "BAM", :name "Bosnia-Herzegovina Convertible Mark", :symbol "KM", :symbol_native "KM"}
{:code "AZN", :name "Azerbaijani Manat", :symbol "man.", :symbol_native "ман."}
{:code "AUD", :name "Australian Dollar", :symbol "AU$", :symbol_native "$"}
{:code "BRL", :name "Brazilian Real", :symbol "R$", :symbol_native "R$"}
{:code "JMD", :name "Jamaican Dollar", :symbol "J$", :symbol_native "$"}
{:code "DKK", :name "Danish Krone", :symbol "Dkr", :symbol_native "kr"}
{:code "ETB", :name "Ethiopian Birr", :symbol "Br", :symbol_native "Br"}
{:code "QAR", :name "Qatari Rial", :symbol "QR", :symbol_native "ر.ق."}
{:code "ZAR", :name "South African Rand", :symbol "R", :symbol_native "R"}
{:code "VEF", :name "Venezuelan Bolívar", :symbol "Bs.F.", :symbol_native "Bs.F."}
{:code "BGN", :name "Bulgarian Lev", :symbol "BGN", :symbol_native "лв."}
{:code "EEK", :name "Estonian Kroon", :symbol "Ekr", :symbol_native "kr"}
{:code "XOF", :name "CFA Franc BCEAO", :symbol "CFA", :symbol_native "CFA"}])
(defn select-currency
[{:keys [class value on-change error helper-text]}]
(let [options (sort-by :code currencies)]
[mui-autocomplete
{:id "select-currency-demo"
:class class
:options options
:render-input (react-component [props]
[text-field (merge props
{:variant :standard
:label "Currency"
:error error
:helper-text helper-text})])
:render-option (react-component [props option]
[:li props
(str (:code option) " - " (:name option))])
:get-option-label #(let [option (js->clj %)]
(str (get option "code") " - " (get option "name")))
:is-option-equal-to-value #(let [option (js->clj %1)
value (js->clj %2)]
(= (get option "code") (get value "code")))
:value (->> options
(filter #(= (:code %) value))
first)
:on-change (fn [_ value _]
(let [selected (js->clj value)
code (get selected "code")]
(on-change code)))}]))
|
[
{
"context": ";; Solution for 112. Sequs Horribilis\n\n\n\n;; Create a function which takes an integer an",
"end": 37,
"score": 0.9990574717521667,
"start": 21,
"tag": "NAME",
"value": "Sequs Horribilis"
}
] | solutions/medium/112.clj | realead/my4clojure | 0 | ;; Solution for 112. Sequs Horribilis
;; Create a function which takes an integer and a nested collection of integers as arguments. Analyze the elements of the input collection and return a sequence which maintains the nested structure,
;; and which includes all elements starting from the head whose sum is less than or equal to the input integer.
;;N.B. It is not clear from description but from examples, that the sequence should stop after first element with sum > n
(defn seq-hor
[col mask]
(if (empty? col)
['(), nil]
(let [el (first col)]
(if (sequential? el)
(let [[new_el new_mask] (seq-hor el mask)
[new_tail new_mask] (seq-hor (rest col) new_mask)]
[(conj new_tail new_el) new_mask]
)
(if (first mask)
(let [[tail new_mask] (seq-hor (rest col) (rest mask))]
[(conj tail el) new_mask]
)
['(), nil];stop, first element with sum > n
)
)
)
)
)
(defn do-seq-hor
[n col]
(let [[res mask] (seq-hor col (map #(<= % n) (reductions + (flatten col))))]
res
)
)
(def __ do-seq-hor)
(__ 0 [1 2 [3 [4 5] 6] 7])
;tests
(= (__ 10 [1 2 [3 [4 5] 6] 7])
'(1 2 (3 (4))))
(= (__ 30 [1 2 [3 [4 [5 [6 [7 8]] 9]] 10] 11])
'(1 2 (3 (4 (5 (6 (7)))))))
(= (__ 9 (range))
'(0 1 2 3))
(= (__ 1 [[[[[1]]]]])
'(((((1))))))
(= (__ 0 [1 2 [3 [4 5] 6] 7])
'())
(= (__ 0 [0 0 [0 [0]]])
'(0 0 (0 (0))))
(= (__ 1 [-10 [1 [2 3 [4 5 [6 7 [8]]]]]])
'(-10 (1 (2 3 (4)))))
| 80039 | ;; Solution for 112. <NAME>
;; Create a function which takes an integer and a nested collection of integers as arguments. Analyze the elements of the input collection and return a sequence which maintains the nested structure,
;; and which includes all elements starting from the head whose sum is less than or equal to the input integer.
;;N.B. It is not clear from description but from examples, that the sequence should stop after first element with sum > n
(defn seq-hor
[col mask]
(if (empty? col)
['(), nil]
(let [el (first col)]
(if (sequential? el)
(let [[new_el new_mask] (seq-hor el mask)
[new_tail new_mask] (seq-hor (rest col) new_mask)]
[(conj new_tail new_el) new_mask]
)
(if (first mask)
(let [[tail new_mask] (seq-hor (rest col) (rest mask))]
[(conj tail el) new_mask]
)
['(), nil];stop, first element with sum > n
)
)
)
)
)
(defn do-seq-hor
[n col]
(let [[res mask] (seq-hor col (map #(<= % n) (reductions + (flatten col))))]
res
)
)
(def __ do-seq-hor)
(__ 0 [1 2 [3 [4 5] 6] 7])
;tests
(= (__ 10 [1 2 [3 [4 5] 6] 7])
'(1 2 (3 (4))))
(= (__ 30 [1 2 [3 [4 [5 [6 [7 8]] 9]] 10] 11])
'(1 2 (3 (4 (5 (6 (7)))))))
(= (__ 9 (range))
'(0 1 2 3))
(= (__ 1 [[[[[1]]]]])
'(((((1))))))
(= (__ 0 [1 2 [3 [4 5] 6] 7])
'())
(= (__ 0 [0 0 [0 [0]]])
'(0 0 (0 (0))))
(= (__ 1 [-10 [1 [2 3 [4 5 [6 7 [8]]]]]])
'(-10 (1 (2 3 (4)))))
| true | ;; Solution for 112. PI:NAME:<NAME>END_PI
;; Create a function which takes an integer and a nested collection of integers as arguments. Analyze the elements of the input collection and return a sequence which maintains the nested structure,
;; and which includes all elements starting from the head whose sum is less than or equal to the input integer.
;;N.B. It is not clear from description but from examples, that the sequence should stop after first element with sum > n
(defn seq-hor
[col mask]
(if (empty? col)
['(), nil]
(let [el (first col)]
(if (sequential? el)
(let [[new_el new_mask] (seq-hor el mask)
[new_tail new_mask] (seq-hor (rest col) new_mask)]
[(conj new_tail new_el) new_mask]
)
(if (first mask)
(let [[tail new_mask] (seq-hor (rest col) (rest mask))]
[(conj tail el) new_mask]
)
['(), nil];stop, first element with sum > n
)
)
)
)
)
(defn do-seq-hor
[n col]
(let [[res mask] (seq-hor col (map #(<= % n) (reductions + (flatten col))))]
res
)
)
(def __ do-seq-hor)
(__ 0 [1 2 [3 [4 5] 6] 7])
;tests
(= (__ 10 [1 2 [3 [4 5] 6] 7])
'(1 2 (3 (4))))
(= (__ 30 [1 2 [3 [4 [5 [6 [7 8]] 9]] 10] 11])
'(1 2 (3 (4 (5 (6 (7)))))))
(= (__ 9 (range))
'(0 1 2 3))
(= (__ 1 [[[[[1]]]]])
'(((((1))))))
(= (__ 0 [1 2 [3 [4 5] 6] 7])
'())
(= (__ 0 [0 0 [0 [0]]])
'(0 0 (0 (0))))
(= (__ 1 [-10 [1 [2 3 [4 5 [6 7 [8]]]]]])
'(-10 (1 (2 3 (4)))))
|
[
{
"context": " [next.jdbc :as jdbc]))\n\n(def yoda {:name \"yoda\" :movie :star-wars :age 900})\n(def leia {:name \"l",
"end": 246,
"score": 0.993683397769928,
"start": 242,
"tag": "NAME",
"value": "yoda"
},
{
"context": "a\" :movie :star-wars :age 900})\n(def leia {:name \"leia\" :movie :star-wars :age 60})\n(def rey {:name \"rey",
"end": 299,
"score": 0.9888125658035278,
"start": 295,
"tag": "NAME",
"value": "leia"
},
{
"context": "eia\" :movie :star-wars :age 60})\n(def rey {:name \"rey\" :movie :star-wars :age 35})\n\n(defn- make-test-db",
"end": 349,
"score": 0.9865534901618958,
"start": 346,
"tag": "NAME",
"value": "rey"
}
] | test/daaku/sqjson_test.clj | daaku/sqjson-clj | 0 | (ns daaku.sqjson-test
(:refer-clojure :exclude [replace count])
(:require [clojure.string :as str]
[clojure.test :refer [deftest is]]
[daaku.sqjson :as sqjson]
[next.jdbc :as jdbc]))
(def yoda {:name "yoda" :movie :star-wars :age 900})
(def leia {:name "leia" :movie :star-wars :age 60})
(def rey {:name "rey" :movie :star-wars :age 35})
(defn- make-test-db []
(let [ds (jdbc/get-connection (jdbc/get-datasource "jdbc:sqlite::memory:"))]
(run! #(next.jdbc/execute! ds [%]) (:migrations sqjson/*opts*))
ds))
(deftest encode-sql-param
(is (= (sqjson/encode-sql-param "a") "'a'"))
(is (= (sqjson/encode-sql-param 1) "1"))
(is (= (sqjson/encode-sql-param true) "true"))
(is (= (sqjson/encode-sql-param :answer) "'[\"!kw\",\"answer\"]'"))
(is (= (sqjson/encode-sql-param ["a"]) "'[\"a\"]'")))
(deftest where-unexpected
(is (thrown? RuntimeException #"unexpected where"
(sqjson/encode-where #{:a})))
(is (thrown? RuntimeException #"unexpected where"
(sqjson/encode-where [:a]))))
(defn- where-sql [sql]
(-> sql
(str/replace "c1" (sqjson/encode-path "c1"))
(str/replace "c2" (sqjson/encode-path "c2"))))
(defn- where-test [in out]
(is (= (where-sql out) (sqjson/encode-where in))))
(deftest where-map
(where-test {:c1 1} "c1=1"))
(deftest where-map-and
(where-test {:c1 1 :c2 2} "(c1=1 and c2=2)"))
(deftest where-seq
(where-test [:> :c1 1] "c1>1"))
(deftest where-seq-and
(where-test [:and [:= :c1 1] [:> :c2 2]]
"(c1=1 and c2>2)"))
(deftest where-seq-or
(where-test [:or [:= :c1 1] [:> :c2 2]]
"(c1=1 or c2>2)"))
(deftest where-seq-with-nil
(where-test [:or [:= :c1 1] nil]
"c1=1"))
(deftest where-like
(where-test [:like :c1 1]
"c1 like 1"))
(deftest where-not-like
(where-test [:not-like :c1 1]
"c1 not like 1"))
(deftest where-in
(where-test [:in :c1 [1 2]]
"c1 in (1,2)"))
(deftest where-not-in
(where-test [:not-in :c1 [1 2]]
"c1 not in (1,2)"))
(deftest where-is-null
(where-test [:= :c1 nil]
"c1 is null"))
(deftest where-is-not-null
(where-test [:<> :c1 nil]
"c1 is not null"))
(deftest encode-query
(run! (fn [[where opts out]]
(is (= out (sqjson/encode-query where opts))))
[[{:a 1}
{:order-by [:id] :limit 2 :offset 3}
["json_extract(data, '$.a')=1 order by json_extract(data, '$.id') limit ? offset ?"
[2 3]]]]))
(deftest unique-id-index
(let [db (make-test-db)
doc (sqjson/insert db yoda)]
(is (thrown-with-msg? org.sqlite.SQLiteException #"SQLITE_CONSTRAINT_UNIQUE"
(sqjson/insert db doc)))))
(deftest json-mapper
(let [db (make-test-db)
doc {:id 1
:keyword :keyword
:set #{:a :b}
:vec [1 2]
:offset-date-time (java.time.OffsetDateTime/now)
:local-date-time (java.time.LocalDateTime/now)}]
(is (= doc (sqjson/insert db doc)))))
(deftest insert-get-delete-get
(let [db (make-test-db)
{:keys [id] :as doc} (sqjson/insert db yoda)]
(is (some? (:id doc))
"expect an id")
(is (= doc (sqjson/get db {:id id}))
"get the doc by id")
(is (= doc (sqjson/get db {:age 900}))
"get the doc by age")
(is (= doc (sqjson/delete db {:id id}))
"delete should work and return the doc")
(is (nil? (sqjson/get db {:id id}))
"get should now return nil")
(is (nil? (sqjson/delete db {:id id}))
"second delete should return nil")))
(deftest patch
(let [db (make-test-db)
{:keys [id] :as doc} (sqjson/insert db yoda)
with-gender (assoc doc :gender :male)
with-gender-age (assoc with-gender :age 950)]
(is (= doc (sqjson/get db {:id id}))
"start with the original doc")
(is (= with-gender (sqjson/patch db {:id id} {:gender :male}))
"patch includes gender")
(is (= with-gender (sqjson/get db {:id id}))
"get includes gender")
(is (= with-gender-age (sqjson/patch db {:id id} {:age 950}))
"patch includes gender-age")
(is (= with-gender-age (sqjson/get db {:id id}))
"get includes gender-age")))
(deftest patch-all
(let [db (make-test-db)]
(is (= 0 (sqjson/patch-all db {:movie :star-wars} {:release 1977})))
(sqjson/insert db yoda)
(sqjson/insert db leia)
(is (= 2 (sqjson/patch-all db {:movie :star-wars} {:release 1977})))
(is (= [1977 1977] (map :release (sqjson/select db {:movie :star-wars}))))))
(deftest replace
(let [db (make-test-db)
{:keys [id] :as doc} (sqjson/insert db yoda)
leia-with-id (assoc leia :id id)]
(is (= doc (sqjson/get db {:id id}))
"start with the original doc")
(is (= leia-with-id (sqjson/replace db {:id id} leia-with-id))
"replace returns new doc")
(is (= leia-with-id (sqjson/get db {:id id}))
"get returns new doc")))
(deftest upsert
(let [db (make-test-db)
{:keys [id] :as doc} (sqjson/upsert db yoda)
leia-with-id (assoc leia :id id)]
(is (= doc (sqjson/get db {:id id}))
"start with the original doc")
(is (= leia-with-id (sqjson/upsert db leia-with-id))
"upsert returns new doc")
(is (= leia-with-id (sqjson/get db {:id id}))
"get returns new doc")))
(deftest count
(let [db (make-test-db)]
(is (= 0 (sqjson/count db {:movie :star-wars})))
(sqjson/insert db yoda)
(sqjson/insert db leia)
(is (= 2 (sqjson/count db {:movie :star-wars})))))
(deftest select
(let [db (make-test-db)
yoda (sqjson/insert db yoda)
leia (sqjson/insert db leia)
rey (sqjson/insert db rey)]
(is (= #{yoda leia rey} (set (sqjson/select db {:movie :star-wars}))))
(is (= #{rey} (set (sqjson/select db {:movie :star-wars}
:order-by [:age]
:limit 1))))
(is (= #{yoda leia} (set (sqjson/select db {:movie :star-wars}
:order-by [[:age :desc]]
:limit 2))))
(is (= #{leia} (set (sqjson/select db {:movie :star-wars}
:order-by [[:age :desc]]
:limit 1
:offset 1))))))
(deftest select-empty
(is (empty? (sqjson/select (make-test-db) {}))))
(deftest delete-all
(let [db (make-test-db)]
(is (= 0 (sqjson/delete-all db {})))
(sqjson/insert db yoda)
(sqjson/insert db leia)
(is (= 2 (sqjson/delete-all db {})))))
(deftest count-where-like
(let [db (make-test-db)]
(jdbc/execute! db [(str "create index if not exists doc_blob_url on doc("
(sqjson/encode-path :url) " collate nocase) "
"where " (sqjson/encode-path :type)
" = '" (sqjson/encode-doc :blob) "'")])
(sqjson/insert db {:type :blob :url "abc1"})
(sqjson/insert db {:type :blob :url "abc2"})
(sqjson/insert db {:type :blob :url "def1"})
(sqjson/insert db {:type :blob :url "def2"})
(is (= 2 (sqjson/count db [:and
[:= :type :blob]
[:like :url "abc%"]])))))
| 94587 | (ns daaku.sqjson-test
(:refer-clojure :exclude [replace count])
(:require [clojure.string :as str]
[clojure.test :refer [deftest is]]
[daaku.sqjson :as sqjson]
[next.jdbc :as jdbc]))
(def yoda {:name "<NAME>" :movie :star-wars :age 900})
(def leia {:name "<NAME>" :movie :star-wars :age 60})
(def rey {:name "<NAME>" :movie :star-wars :age 35})
(defn- make-test-db []
(let [ds (jdbc/get-connection (jdbc/get-datasource "jdbc:sqlite::memory:"))]
(run! #(next.jdbc/execute! ds [%]) (:migrations sqjson/*opts*))
ds))
(deftest encode-sql-param
(is (= (sqjson/encode-sql-param "a") "'a'"))
(is (= (sqjson/encode-sql-param 1) "1"))
(is (= (sqjson/encode-sql-param true) "true"))
(is (= (sqjson/encode-sql-param :answer) "'[\"!kw\",\"answer\"]'"))
(is (= (sqjson/encode-sql-param ["a"]) "'[\"a\"]'")))
(deftest where-unexpected
(is (thrown? RuntimeException #"unexpected where"
(sqjson/encode-where #{:a})))
(is (thrown? RuntimeException #"unexpected where"
(sqjson/encode-where [:a]))))
(defn- where-sql [sql]
(-> sql
(str/replace "c1" (sqjson/encode-path "c1"))
(str/replace "c2" (sqjson/encode-path "c2"))))
(defn- where-test [in out]
(is (= (where-sql out) (sqjson/encode-where in))))
(deftest where-map
(where-test {:c1 1} "c1=1"))
(deftest where-map-and
(where-test {:c1 1 :c2 2} "(c1=1 and c2=2)"))
(deftest where-seq
(where-test [:> :c1 1] "c1>1"))
(deftest where-seq-and
(where-test [:and [:= :c1 1] [:> :c2 2]]
"(c1=1 and c2>2)"))
(deftest where-seq-or
(where-test [:or [:= :c1 1] [:> :c2 2]]
"(c1=1 or c2>2)"))
(deftest where-seq-with-nil
(where-test [:or [:= :c1 1] nil]
"c1=1"))
(deftest where-like
(where-test [:like :c1 1]
"c1 like 1"))
(deftest where-not-like
(where-test [:not-like :c1 1]
"c1 not like 1"))
(deftest where-in
(where-test [:in :c1 [1 2]]
"c1 in (1,2)"))
(deftest where-not-in
(where-test [:not-in :c1 [1 2]]
"c1 not in (1,2)"))
(deftest where-is-null
(where-test [:= :c1 nil]
"c1 is null"))
(deftest where-is-not-null
(where-test [:<> :c1 nil]
"c1 is not null"))
(deftest encode-query
(run! (fn [[where opts out]]
(is (= out (sqjson/encode-query where opts))))
[[{:a 1}
{:order-by [:id] :limit 2 :offset 3}
["json_extract(data, '$.a')=1 order by json_extract(data, '$.id') limit ? offset ?"
[2 3]]]]))
(deftest unique-id-index
(let [db (make-test-db)
doc (sqjson/insert db yoda)]
(is (thrown-with-msg? org.sqlite.SQLiteException #"SQLITE_CONSTRAINT_UNIQUE"
(sqjson/insert db doc)))))
(deftest json-mapper
(let [db (make-test-db)
doc {:id 1
:keyword :keyword
:set #{:a :b}
:vec [1 2]
:offset-date-time (java.time.OffsetDateTime/now)
:local-date-time (java.time.LocalDateTime/now)}]
(is (= doc (sqjson/insert db doc)))))
(deftest insert-get-delete-get
(let [db (make-test-db)
{:keys [id] :as doc} (sqjson/insert db yoda)]
(is (some? (:id doc))
"expect an id")
(is (= doc (sqjson/get db {:id id}))
"get the doc by id")
(is (= doc (sqjson/get db {:age 900}))
"get the doc by age")
(is (= doc (sqjson/delete db {:id id}))
"delete should work and return the doc")
(is (nil? (sqjson/get db {:id id}))
"get should now return nil")
(is (nil? (sqjson/delete db {:id id}))
"second delete should return nil")))
(deftest patch
(let [db (make-test-db)
{:keys [id] :as doc} (sqjson/insert db yoda)
with-gender (assoc doc :gender :male)
with-gender-age (assoc with-gender :age 950)]
(is (= doc (sqjson/get db {:id id}))
"start with the original doc")
(is (= with-gender (sqjson/patch db {:id id} {:gender :male}))
"patch includes gender")
(is (= with-gender (sqjson/get db {:id id}))
"get includes gender")
(is (= with-gender-age (sqjson/patch db {:id id} {:age 950}))
"patch includes gender-age")
(is (= with-gender-age (sqjson/get db {:id id}))
"get includes gender-age")))
(deftest patch-all
(let [db (make-test-db)]
(is (= 0 (sqjson/patch-all db {:movie :star-wars} {:release 1977})))
(sqjson/insert db yoda)
(sqjson/insert db leia)
(is (= 2 (sqjson/patch-all db {:movie :star-wars} {:release 1977})))
(is (= [1977 1977] (map :release (sqjson/select db {:movie :star-wars}))))))
(deftest replace
(let [db (make-test-db)
{:keys [id] :as doc} (sqjson/insert db yoda)
leia-with-id (assoc leia :id id)]
(is (= doc (sqjson/get db {:id id}))
"start with the original doc")
(is (= leia-with-id (sqjson/replace db {:id id} leia-with-id))
"replace returns new doc")
(is (= leia-with-id (sqjson/get db {:id id}))
"get returns new doc")))
(deftest upsert
(let [db (make-test-db)
{:keys [id] :as doc} (sqjson/upsert db yoda)
leia-with-id (assoc leia :id id)]
(is (= doc (sqjson/get db {:id id}))
"start with the original doc")
(is (= leia-with-id (sqjson/upsert db leia-with-id))
"upsert returns new doc")
(is (= leia-with-id (sqjson/get db {:id id}))
"get returns new doc")))
(deftest count
(let [db (make-test-db)]
(is (= 0 (sqjson/count db {:movie :star-wars})))
(sqjson/insert db yoda)
(sqjson/insert db leia)
(is (= 2 (sqjson/count db {:movie :star-wars})))))
(deftest select
(let [db (make-test-db)
yoda (sqjson/insert db yoda)
leia (sqjson/insert db leia)
rey (sqjson/insert db rey)]
(is (= #{yoda leia rey} (set (sqjson/select db {:movie :star-wars}))))
(is (= #{rey} (set (sqjson/select db {:movie :star-wars}
:order-by [:age]
:limit 1))))
(is (= #{yoda leia} (set (sqjson/select db {:movie :star-wars}
:order-by [[:age :desc]]
:limit 2))))
(is (= #{leia} (set (sqjson/select db {:movie :star-wars}
:order-by [[:age :desc]]
:limit 1
:offset 1))))))
(deftest select-empty
(is (empty? (sqjson/select (make-test-db) {}))))
(deftest delete-all
(let [db (make-test-db)]
(is (= 0 (sqjson/delete-all db {})))
(sqjson/insert db yoda)
(sqjson/insert db leia)
(is (= 2 (sqjson/delete-all db {})))))
(deftest count-where-like
(let [db (make-test-db)]
(jdbc/execute! db [(str "create index if not exists doc_blob_url on doc("
(sqjson/encode-path :url) " collate nocase) "
"where " (sqjson/encode-path :type)
" = '" (sqjson/encode-doc :blob) "'")])
(sqjson/insert db {:type :blob :url "abc1"})
(sqjson/insert db {:type :blob :url "abc2"})
(sqjson/insert db {:type :blob :url "def1"})
(sqjson/insert db {:type :blob :url "def2"})
(is (= 2 (sqjson/count db [:and
[:= :type :blob]
[:like :url "abc%"]])))))
| true | (ns daaku.sqjson-test
(:refer-clojure :exclude [replace count])
(:require [clojure.string :as str]
[clojure.test :refer [deftest is]]
[daaku.sqjson :as sqjson]
[next.jdbc :as jdbc]))
(def yoda {:name "PI:NAME:<NAME>END_PI" :movie :star-wars :age 900})
(def leia {:name "PI:NAME:<NAME>END_PI" :movie :star-wars :age 60})
(def rey {:name "PI:NAME:<NAME>END_PI" :movie :star-wars :age 35})
(defn- make-test-db []
(let [ds (jdbc/get-connection (jdbc/get-datasource "jdbc:sqlite::memory:"))]
(run! #(next.jdbc/execute! ds [%]) (:migrations sqjson/*opts*))
ds))
(deftest encode-sql-param
(is (= (sqjson/encode-sql-param "a") "'a'"))
(is (= (sqjson/encode-sql-param 1) "1"))
(is (= (sqjson/encode-sql-param true) "true"))
(is (= (sqjson/encode-sql-param :answer) "'[\"!kw\",\"answer\"]'"))
(is (= (sqjson/encode-sql-param ["a"]) "'[\"a\"]'")))
(deftest where-unexpected
(is (thrown? RuntimeException #"unexpected where"
(sqjson/encode-where #{:a})))
(is (thrown? RuntimeException #"unexpected where"
(sqjson/encode-where [:a]))))
(defn- where-sql [sql]
(-> sql
(str/replace "c1" (sqjson/encode-path "c1"))
(str/replace "c2" (sqjson/encode-path "c2"))))
(defn- where-test [in out]
(is (= (where-sql out) (sqjson/encode-where in))))
(deftest where-map
(where-test {:c1 1} "c1=1"))
(deftest where-map-and
(where-test {:c1 1 :c2 2} "(c1=1 and c2=2)"))
(deftest where-seq
(where-test [:> :c1 1] "c1>1"))
(deftest where-seq-and
(where-test [:and [:= :c1 1] [:> :c2 2]]
"(c1=1 and c2>2)"))
(deftest where-seq-or
(where-test [:or [:= :c1 1] [:> :c2 2]]
"(c1=1 or c2>2)"))
(deftest where-seq-with-nil
(where-test [:or [:= :c1 1] nil]
"c1=1"))
(deftest where-like
(where-test [:like :c1 1]
"c1 like 1"))
(deftest where-not-like
(where-test [:not-like :c1 1]
"c1 not like 1"))
(deftest where-in
(where-test [:in :c1 [1 2]]
"c1 in (1,2)"))
(deftest where-not-in
(where-test [:not-in :c1 [1 2]]
"c1 not in (1,2)"))
(deftest where-is-null
(where-test [:= :c1 nil]
"c1 is null"))
(deftest where-is-not-null
(where-test [:<> :c1 nil]
"c1 is not null"))
(deftest encode-query
(run! (fn [[where opts out]]
(is (= out (sqjson/encode-query where opts))))
[[{:a 1}
{:order-by [:id] :limit 2 :offset 3}
["json_extract(data, '$.a')=1 order by json_extract(data, '$.id') limit ? offset ?"
[2 3]]]]))
(deftest unique-id-index
(let [db (make-test-db)
doc (sqjson/insert db yoda)]
(is (thrown-with-msg? org.sqlite.SQLiteException #"SQLITE_CONSTRAINT_UNIQUE"
(sqjson/insert db doc)))))
(deftest json-mapper
(let [db (make-test-db)
doc {:id 1
:keyword :keyword
:set #{:a :b}
:vec [1 2]
:offset-date-time (java.time.OffsetDateTime/now)
:local-date-time (java.time.LocalDateTime/now)}]
(is (= doc (sqjson/insert db doc)))))
(deftest insert-get-delete-get
(let [db (make-test-db)
{:keys [id] :as doc} (sqjson/insert db yoda)]
(is (some? (:id doc))
"expect an id")
(is (= doc (sqjson/get db {:id id}))
"get the doc by id")
(is (= doc (sqjson/get db {:age 900}))
"get the doc by age")
(is (= doc (sqjson/delete db {:id id}))
"delete should work and return the doc")
(is (nil? (sqjson/get db {:id id}))
"get should now return nil")
(is (nil? (sqjson/delete db {:id id}))
"second delete should return nil")))
(deftest patch
(let [db (make-test-db)
{:keys [id] :as doc} (sqjson/insert db yoda)
with-gender (assoc doc :gender :male)
with-gender-age (assoc with-gender :age 950)]
(is (= doc (sqjson/get db {:id id}))
"start with the original doc")
(is (= with-gender (sqjson/patch db {:id id} {:gender :male}))
"patch includes gender")
(is (= with-gender (sqjson/get db {:id id}))
"get includes gender")
(is (= with-gender-age (sqjson/patch db {:id id} {:age 950}))
"patch includes gender-age")
(is (= with-gender-age (sqjson/get db {:id id}))
"get includes gender-age")))
(deftest patch-all
(let [db (make-test-db)]
(is (= 0 (sqjson/patch-all db {:movie :star-wars} {:release 1977})))
(sqjson/insert db yoda)
(sqjson/insert db leia)
(is (= 2 (sqjson/patch-all db {:movie :star-wars} {:release 1977})))
(is (= [1977 1977] (map :release (sqjson/select db {:movie :star-wars}))))))
(deftest replace
(let [db (make-test-db)
{:keys [id] :as doc} (sqjson/insert db yoda)
leia-with-id (assoc leia :id id)]
(is (= doc (sqjson/get db {:id id}))
"start with the original doc")
(is (= leia-with-id (sqjson/replace db {:id id} leia-with-id))
"replace returns new doc")
(is (= leia-with-id (sqjson/get db {:id id}))
"get returns new doc")))
(deftest upsert
(let [db (make-test-db)
{:keys [id] :as doc} (sqjson/upsert db yoda)
leia-with-id (assoc leia :id id)]
(is (= doc (sqjson/get db {:id id}))
"start with the original doc")
(is (= leia-with-id (sqjson/upsert db leia-with-id))
"upsert returns new doc")
(is (= leia-with-id (sqjson/get db {:id id}))
"get returns new doc")))
(deftest count
(let [db (make-test-db)]
(is (= 0 (sqjson/count db {:movie :star-wars})))
(sqjson/insert db yoda)
(sqjson/insert db leia)
(is (= 2 (sqjson/count db {:movie :star-wars})))))
(deftest select
(let [db (make-test-db)
yoda (sqjson/insert db yoda)
leia (sqjson/insert db leia)
rey (sqjson/insert db rey)]
(is (= #{yoda leia rey} (set (sqjson/select db {:movie :star-wars}))))
(is (= #{rey} (set (sqjson/select db {:movie :star-wars}
:order-by [:age]
:limit 1))))
(is (= #{yoda leia} (set (sqjson/select db {:movie :star-wars}
:order-by [[:age :desc]]
:limit 2))))
(is (= #{leia} (set (sqjson/select db {:movie :star-wars}
:order-by [[:age :desc]]
:limit 1
:offset 1))))))
(deftest select-empty
(is (empty? (sqjson/select (make-test-db) {}))))
(deftest delete-all
(let [db (make-test-db)]
(is (= 0 (sqjson/delete-all db {})))
(sqjson/insert db yoda)
(sqjson/insert db leia)
(is (= 2 (sqjson/delete-all db {})))))
(deftest count-where-like
(let [db (make-test-db)]
(jdbc/execute! db [(str "create index if not exists doc_blob_url on doc("
(sqjson/encode-path :url) " collate nocase) "
"where " (sqjson/encode-path :type)
" = '" (sqjson/encode-doc :blob) "'")])
(sqjson/insert db {:type :blob :url "abc1"})
(sqjson/insert db {:type :blob :url "abc2"})
(sqjson/insert db {:type :blob :url "def1"})
(sqjson/insert db {:type :blob :url "def2"})
(is (= 2 (sqjson/count db [:and
[:= :type :blob]
[:like :url "abc%"]])))))
|
[
{
"context": " ;;\n;; Author: Jon Anthony ",
"end": 1839,
"score": 0.9998331069946289,
"start": 1828,
"tag": "NAME",
"value": "Jon Anthony"
}
] | src/aerial/utils/math/infoth.clj | jsa-aerial/aerial.utils | 5 | ;;--------------------------------------------------------------------------;;
;; ;;
;; U T I L S . I N F O T H ;;
;; ;;
;; 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. ;;
;; ;;
;; Author: Jon Anthony ;;
;; ;;
;;--------------------------------------------------------------------------;;
;;
(ns aerial.utils.math.infoth
"Various Information Theory functions and measures rooted in Shannon
Entropy measure and targetting a variety of sequence and string
data."
(:require [clojure.math.numeric-tower :as math]
[clojure.string :as str]
[clojure.set :as set]
[aerial.utils.misc
:refer [raise catch-all]]
[aerial.utils.coll
:refer [reducem subsets vfold]]
[aerial.utils.string :as austr
:refer [codepoints]]
[aerial.utils.math
:refer [sum log2]]
[aerial.utils.math.combinatorics
:refer [combins]]
[aerial.utils.math.probs-stats
:refer [joint-probability freqn probs word-letter-pairs]]
))
(defn shannon-entropy
"Returns the Shannon entropy of a sequence: -sum(* pi (log pi)),
where i ranges over the unique elements of S and pi is the
probability of i in S: (freq i s)/(count s)"
[s & {logfn :logfn :or {logfn log2}}]
(let [fs (frequencies s)
cnt (double (sum fs))
H (sum (fn[[_ v]]
(let [p (double (/ v cnt))]
(double (* p (double (logfn p))))))
fs)]
(double (- H))))
(defn entropy
"Entropy calculation for the probability distribution dist.
Typically dist is a map giving the PMF of some sample space. If it
is a string or vector, this calls shannon-entropy on dist.
"
[dist & {logfn :logfn :or {logfn log2}}]
(if (or (string? dist) (vector? dist))
(shannon-entropy dist :logfn logfn)
(let [dist (if (map? dist) (vals dist) dist)]
(- (sum (fn[v]
(let [v (double v)]
(if (= 0.0 v)
0.0
(double (* v (logfn v))))))
dist)))))
(defn joint-entropy
"Given a set of collections c1, c2, c3, .. cn, and combinator, a
function of n variables which generates joint occurances from {ci},
returns the joint entropy over all the set:
-sum(* px1..xn (log2 px1..xn))
OPTS is a map of options, currently sym? and logfn. The defaults
are false and log2. If sym? is true, treat [x y] and [y x] as
equal. logfn can be used to provide a log of a different base.
log2, the default, reports in bits. If no options are required,
the empty map must be passed: (joint-entropy transpose {} my-coll)
"
([combinator opts coll]
(let [{:keys [sym? logfn] :or {sym? false logfn log2}} opts]
(entropy (joint-probability combinator sym? coll)
:logfn logfn)))
([combinator opts coll & colls]
(let [{:keys [sym? logfn] :or {sym? false logfn log2}} opts]
(entropy (apply joint-probability combinator sym? coll colls)
:logfn logfn))))
(defn HXY
"Synonym for joint-entropy"
[& args]
(apply joint-entropy args))
(defn cond-entropy
"Given the joint probability distribution PXY and the distribution
PY, return the conditional entropy of X given Y = H(X,Y) - H(Y).
Alternatively, given a set of collections c1, c2, c3, .. cn, and
combinator, a function of n variables which generates joint
occurances from {ci}, returns the multivariate conditional entropy
induced from the joint probability distributions.
OPTS is a map of options, currently sym? and logfn. The defaults
are false and log2. If sym? is true, treat [x y] and [y x] as
equal. logfn can be used to provide a log of a different base.
log2, the default, reports in bits. If no options are required,
the empty map must be passed: (cond-entropy transpose {} my-coll)
For the case of i > 2, uses the recursive chain rule for
conditional entropy (bottoming out in the two collection case):
H(X1,..Xn-1|Xn) = (sum H(Xi|Xn,X1..Xi-1) (range 1 (inc n)))
"
([PXY PY]
(- (entropy PXY) (entropy PY)))
([combinator opts coll1 coll2]
(let [{:keys [sym? logfn] :or {sym? false logfn log2}} opts]
(- (entropy (joint-probability combinator sym? coll1 coll2) :logfn logfn)
(entropy (probs 1 coll2) :logfn logfn))))
([combinator opts coll1 coll2 & colls]
(let [{:keys [sym? logfn] :or {sym? false logfn log2}} opts]
;; Apply chain rule...
(- (entropy (apply joint-probability combinator sym? coll1 coll2 colls)
:logfn logfn)
(apply cond-entropy combinator opts coll2 colls)))))
(defn HX|Y
"Synonym for cond-entropy"
[& args]
(apply cond-entropy args))
(defn combin-joint-entropy
"Given a set of collections c1, c2, c3, .. cn, return the joint
entropy: - (sum (* px1..xn (log2 px1..xn)) all-pairs-over {ci}).
Where all-pairs-over is an exhaustive combination of elements of
{ci} taken n at a time, where each n-tuple has exactly one element
from each ci (i.e., the cross product of {ci}).
Reports in bits (logfn = log2) and treats [x y] [y x] elements as
the same.
"
([coll1 coll2]
(joint-entropy
(fn[s1 s2] (reducem (fn[x y] [[x y]]) concat s1 s2))
{:sym? true}
coll1 coll2))
([coll1 coll2 & colls]
(apply joint-entropy
(fn[& cs]
(apply reducem (fn[& args] [args]) concat cs))
{:sym? true} coll1 coll2 colls)))
(defn seq-joint-entropy
"Returns the joint entropy of a sequence with itself: -sum(* pi (log
pi)), where probabilities pi are of combinations of elements of S
taken 2 at a time. If sym?, treat [x y] and [y x] as equal.
"
[s & {:keys [sym? logfn] :or {sym? false logfn log2}}]
(joint-entropy #(combins 2 %) sym? s))
(defn relative-entropy
"Take two distributions (that must be over the same space) and
compute the expectation of their log ratio: Let px be the PMF of
pdist1 and py be the PMF pdist2, return
(sum (fn[px py] (* px (log2 (/ px py)))) xs ys)
Here, pdist(1|2) are maps giving the probability distributions (and
implicitly the pmfs), as provided by freqs-probs, probs,
cc-freqs-probs, combins-freqs-probs, cc-combins-freqs-probs,
et. al. Or any map where the values are the probabilities of the
occurance of the keys over some sample space. Any summation term
where (or (= px 0) (= py 0)), is taken as 0.0.
NOTE: maps should have same keys! If this is violated it is likely
you will get a :negRE exception or worse, bogus results. However,
as long as the maps reflect distributions _over the same sample
space_, they do not need to be a complete sampling (a key/value for
all sample space items) - missing keys will be included as 0.0
values.
Also known as Kullback-Leibler Divergence (KLD)
KLD >= 0.0 in all cases.
"
[pdist1 pdist2 & {:keys [logfn] :or {logfn log2}}]
;; Actually, we try to 'normalize' maps to same sample space.
(let [Omega (set/union (set (keys pdist1)) (set (keys pdist2)))
KLD (sum (fn[k]
(let [pi (get pdist1 k 0.0)
qi (get pdist2 k 0.0)]
(if (or (= pi 0.0) (= qi 0.0))
(double 0.0)
(* pi (logfn (/ pi qi))))))
Omega)]
(cond
(>= KLD 0.0) KLD
(< (math/abs KLD) 1.0E-10) 0.0
:else
(raise
:type :negRE :KLD KLD :Pdist pdist1 :Qdist pdist2))))
(defn KLD
"Synonym for relative-entropy.
args is [pd1 pd2 & {:keys [logfn] :or {logfn log2}}"
[& args] (apply relative-entropy args))
(defn DX||Y
"Synonym for relative-entropy.
args is [pd1 pd2 & {:keys [logfn] :or {logfn log2}}"
[& args] (apply relative-entropy args))
(defn mutual-information
"Mutual information between the content of coll1 and coll2 as
combined by combinator, a function of two variables, presumed to be
over coll1 and coll2 returning a collection of combined elements.
OPTS is a map of options, currently sym? and logfn. The defaults
are false and log2. If sym? is true, treat [x y] and [y x] as
equal. logfn can be used to provide a log of a different base.
log2, the default, reports in bits. If no options are required,
the empty map must be passed: (mutual-information transpose {} my-coll)
Mutual information is the relative entropy (KLD) of the joint
probability distribution to the product distribution. Here the
distributions arise out of the frequencies over coll1 and coll2
individually and jointly over the result of combinator on coll1 and
coll2.
Let C be (combinator coll1 coll2). Computes
(sum (* pxy (log2 (/ pxy (* px py)))) xs ys) =
(+ (shannon-entropy coll1) (shannon-entropy coll2) (- (joint-entropy C))) =
Hx + Hy - Hxy = I(X,Y)
(<= 0.0 I(X,Y) (min [Hx Hy]))
"
[combinator opts coll1 coll2]
(let [{:keys [sym? logfn] :or {sym? false logfn log2}} opts
HX (shannon-entropy coll1 :logfn logfn)
HY (shannon-entropy coll2 :logfn logfn)
HXY (joint-entropy combinator opts coll1 coll2)
IXY (+ HX HY (- HXY))]
(cond
(>= IXY 0.0) IXY
(< (math/abs IXY) 1.0E-10) 0.0
:else
(raise
:type :negIxy :Ixy IXY :Hxy HXY :Hx HX :Hy HY))))
(defn IXY "Synonym for mutual information"
[combinator opts coll1 coll2]
(mutual-information combinator opts coll1 coll2))
(defn conditional-mutual-information
"Conditional mutual information I(X;Y|Z). Conditional mutual
information is the relative entropy (KLD) of the conditional
distribution (of two random variables on a third) with the product
distribution of the distributed conditionals.
Here these arise out of frequencies for the information in collz
individually, collx & collz and colly & collz jointly as the result
of combinator, and collx & colly & collz jointly as the result of
combinator as well. Hence, combinator needs to be able to handle
the cases of 2 and 3 collections passed to it (collectively or as
variadic).
OPTS is a map of options, currently sym? and logfn. The defaults
are false and log2. If sym? is true, treat [x y] and [y x] as
equal. logfn can be used to provide a log of a different base.
log2, the default, reports in bits. If no options are required,
the empty map must be passed: (conditional-mutual-information
transpose {} my-coll)
Other interpretations/meanings: Conditional mutual information is
the mutual information of two random variables conditioned on a
third. Or, put another way, it is the expected value of the mutual
information of two RV over the values of a third. It measures the
amount of information shared by X & Y beyond that provided by a
common \"mediator\".
Let XYZ be (combinator collx colly collz)
XZ be (combinator collx collz)
YZ be (combinator colly collz)
Computes
sum (* pxy|z (log2 (/ pxy|z (* px|z py|z)))) xs ys zs =
... (some algebra and applications of Bayes) ...
sum (* pxyz (log2 (/ (* pz pxyz) (* pxz pyz)))) xyzs xzs yzs
... (some more algebra and entropy identitities) ...
(+ H(X,Z) H(Y,Z) -H(X,Y,Z) -H(Z))
which is easier to work with...
"
[combinator opts collx colly collz]
(let [{:keys [sym? logfn] :or {sym? false logfn log2}} opts
PXYZ (vals (joint-probability combinator sym? collx colly collz))
HXYZ (entropy PXYZ :logfn logfn)
PXZ (vals (joint-probability combinator sym? collx collz))
HXZ (entropy PXZ :logfn logfn)
PYZ (vals (joint-probability combinator sym? colly collz))
HYZ (entropy PYZ :logfn logfn)
PZ (probs 1 collz)
HZ (entropy PZ :logfn logfn)
IXY|Z (+ HXZ HYZ (- HXYZ) (- HZ))]
(cond
(>= IXY|Z 0.0) IXY|Z
(< (math/abs IXY|Z) 1.0E-10) 0.0
:else
(raise
:type :negIxy|z
:Ixy|z IXY|Z :Hxz HXZ :Hyz HYZ :Hxyz HXYZ :Hz HZ))))
(defn IXY|Z "Synonym for conditional mutual information"
[combinator opts collx colly collz]
(conditional-mutual-information combinator opts collx colly collz))
(defn variation-information
""
[combinator opts coll1 coll2]
(let [Hxy (joint-entropy combinator opts coll1 coll2)
Ixy (mutual-information combinator opts coll1 coll2)]
(- 1.0 (double (/ Ixy Hxy)))))
(defn total-correlation
"One of two forms of multivariate mutual information provided here.
The other is \"interaction information\". Total correlation
computes what is effectively the _total redundancy_ of the
information in the provided content - here the information in coll1
.. colln. As such it can give somewhat unexpected answers in
certain situations.
Information content \"measure\" is based on the distributions
arising out of the frequencies over coll1 .. colln _individually_,
and jointly over the result of combinator applied to coll1 .. colln
collectively.
OPTS is a map of options, currently sym? and logfn. The defaults
are false and log2. If sym? is true, treat [x y] and [y x] as
equal. logfn can be used to provide a log of a different base.
log2, the default, reports in bits. If no options are required,
the empty map must be passed: (total-correlation transpose {}
my-coll)
NOTE: the \"degenerate\" case of only two colls, is simply mutual
information.
Let C be (combinator coll1 coll2 .. colln), so xi1..xin in C is an
element in the joint sample space, and xi in colli is an element in
a \"marginal\" space . Computes
sum (* px1..xn (log2 (/ px1..xn (* px1 px2 .. pxn)))) x1s x2s .. xns =
Hx1 + Hx2 + .. + Hxn - Hx1x2..xn
(<= 0.0
TC(X1,..,Xn)
(min|i (sum Hx1 .. Hxi Hxi+2 .. Hxn, i = 0..n-1, Hx0=Hxn+1=0)))
Ex:
(shannon-entropy \"AAAUUUGGGGCCCUUUAAA\")
=> 1.9440097497163569
(total-correlation transpose {}
\"AAAUUUGGGGCCCUUUAAA\" \"AAAUUUGGGGCCCUUUAAA\")
=> 1.9440097497163569 ; not surprising
(total-correlation transpose {}
\"AAAUUUGGGGCCCUUUAAA\" \"AAAUUUGGGGCCCUUUAAA\"
\"AAAUUUGGGGCCCUUUAAA\" \"AAAUUUGGGGCCCUUUAAA\")
=> 5.832029249149071 ; possibly surprising if not noting tripled redundancy
"
([combinator opts coll1 coll2]
(mutual-information combinator opts coll1 coll2))
([combinator opts coll1 coll2 & colls]
(let [{:keys [sym? logfn] :or {sym? false logfn log2}} opts
colls (cons coll1 (cons coll2 colls))
Hxs (map #(shannon-entropy % :logfn logfn) colls)
HX1-Xn (apply joint-entropy combinator opts coll1 coll2 colls)
TC (- (sum Hxs) HX1-Xn)]
(cond
(>= TC 0.0) TC
(< (math/abs TC) 1.0E-10) 0.0
:else
(raise
:type :negTC
:TC TC :Hxs Hxs :HX1-XN HX1-Xn)))))
(defn TCI
"Synonym for total-correlation information"
[combinator opts coll1 coll2 & colls]
(apply total-correlation combinator opts coll1 coll2 colls))
(defn interaction-information
"One of two forms of multivariate mutual information provided here.
The other is \"total correlation\". Interaction information
computes the amount of information bound up in a set of variables,
beyond that present in _any subset_ of those variables. Well, that
seems to be the most widely held view, but there are disputes. This
can either indicate inhibition/redundancy or facilitation/synergy
between the variables. It helps to look at the 3 variable case, as
it at least lends itself to 'information' (or info venn) diagrams.
II(X,Y,Z) = I(X,Y|Z) - I(X,Y)
II measures the influence of Z on the information connection
between X and Y. Since I(X,Y|Z) < I(X,Y) is possible, II can be
negative, as well as 0 and positive. For example if Z completely
determines the information content between X & Y, then I(X,Y|Z) -
I(X,Y) would be 0 (as overlap contributed by X & Y alone is totally
redundant), while for X & Y independent of Z, I(X,Y) could still be
> 0. A _negative_ interaction indicates Z inhibits (accounts for,
causes to be irrelevant/redundant) the connection between X & Y. A
_positive_ interaction indicates Z promotes, is synergistic with,
or enhances the connection. The case of 0 is obvious...
If we use the typical info theory venn diagrams, then II is
represented as the area in all the circles. It is possible (and
typically so done) to draw the Hxi (xi in {X,Y,Z}) circles so that
all 3 have an overlap. In this case the information between any
two (the mutual information...) is partially accounted for by the
third. The extra overlap accounts for the negative value
\"correction\" of II in this case.
However, it is also possible to draw the circles so that any two
overlap but all three have null intersect. In this case, the third
variable provides an extra connection between the other two (beyond
their MI), something like a \"mediator\". This extra connection
accounts for the positive value \"facillitation\" of II in this
case.
It should be reasonably clear at this point that negative II is the
much more intuitive/typical case, and that positive cases are
surprising and typically more interesting and informative (so to
speak...). A positive example, would be the case of two mutually
exclusive causes for a common effect (third variable). In such a
case, knowing any two completely determines the other.
All of this can be bumped up to N variables via typical chain rule
recurrance.
In this implementation, the information content \"measure\" is
based on the distributions arising out of the frequencies over
coll1 .. colln _individually_, and jointly over the result of
combinator applied collectively to all subsets of coll1 .. colln.
OPTS is a map of options, currently sym? and logfn. The defaults
are false and log2. If sym? is true, treat [x y] and [y x] as
equal. logfn can be used to provide a log of a different base.
log2, the default, reports in bits. If no options are required,
the empty map must be passed: (interaction-information transpose {}
my-coll)
For collections coll1..colln and variadic combinator over any
subset of collections, Computes:
(sum (fn[ss] (* (expt -1 (- n |ss|))
(HXY combinator sym? ss)))
(subsets all-colls))
|ss| = cardinality/count of subset ss. ss is a subset of
coll1..colln. If sym? is true, treat reversable combined items as
equal (see HYX/joint-entropy).
For n=3, this reduces to (- (IXY|Z combinator sym? collx colly collz)
(IXY combinator sym? collx colly))
Ex:
(interaction-information transpose {}
\"AAAGGGUUUUAAUAUUAAAAUUU\"
\"AAAGGGUGGGAAUAUUCCCAUUU\"
\"AAAGGGUGGGAAUAUUCCCAUUU\")
=> -1.1673250256261127
Ex:
(interaction-information transpose {}
\"AAAGGGUUUUAAUAUUAAAAUUU\"
\"AAAGGGUGGGAAUAUUCCCAUUU\"
(reverse-compliment \"AAAGGGUGGGAAUAUUCCCAUUU\"))
=> -0.282614135781623
Ex: Shows synergy (positive value)
(let [X1 [0 1] ; 7 independent binary vars
X2 [0 1]
X3 [0 1]
X4 [0 1]
X5 [0 1]
X6 [0 1]
X7 [0 1]
X8 [0 1]
Y1 [X1 X2 X3 X4 X5 X6 X7]
Y2 [X4 X5 X6 X7]
Y3 [X5 X6 X7]
Y4 [X7]
bitval #(loop [bits (reverse %) n 0 v 0]
(if (empty? bits)
v
(recur (rest bits)
(inc n)
(+ v (* (first bits) (math/expt 2 n))))))
rfn #(map bitval (apply reducem (fn[& args] [args]) concat %))
;; Turn to (partially redundant) value sets - each Yi is the set
;; of all numbers for all (count Yi) bit patterns. So, Y1, Y2,
;; and Y3 share all values of 3 bits, while the group with Y4
;; added shares just all 1 bit patterns
Y1 (rfn Y1)
Y2 (rfn Y2)
Y3 (rfn Y3)
Y4 (rfn Y4)]
[(interaction-information concat {} Y1 Y2 Y3)
(interaction-information concat {} Y1 Y2 Y3 Y4)])
=> [-3.056592722891465 ; Intuitive, since 3 way sharing
1.0803297840536592] ; Unintuitive, since 1 way sharing induces synergy!?
"
#_([combinator opts collx colly collz]
(let [Ixy|z (IXY|Z combinator opts collx colly collz)
Ixy (IXY combinator opts collx colly)]
(- Ixy|z Ixy)))
([combinator opts collx colly collz & colls]
(let [colls (->> colls (cons collz) (cons colly) (cons collx))
ssets (remove empty? (subsets colls))
tcnt (count colls)]
(- (sum (fn[ss]
(let [sscnt (count ss)]
(* (math/expt -1.0 (- tcnt sscnt))
(apply joint-entropy combinator opts ss))))
ssets)))))
(defn II
"Synonym for interaction-information"
[combinator opts collx colly collz & colls]
(apply interaction-information combinator opts collx colly collz colls))
(defn lambda-divergence
"Computes a symmetrized KLD variant based on a probability
parameter, typically notated lambda, in [0..1] for each
distribution:
(+ (* lambda (DX||Y Pdist M)) (* (- 1 lambda) (DX||Y Qdist M)))
Where M = (+ (* lambda Pdist) (* (- 1 lambda) Qdist))
= (merge-with (fn[pi qi] (+ (* lambda pi) (* (- 1 lambda) qi)))
Pdist Qdist)
For lambda = 1/2, this reduces to
M = 1/2 (merge-with (fn[pi qi] (+ pi qi)) P Q)
and (/ (+ (DX||Y Pdist M) (DX||Y Qdist M)) 2) = jensen shannon
"
[lambda Pdist Qdist]
(let [Omega (set/union (set (keys Pdist)) (set (keys Qdist)))
M (reduce (fn[M k]
(assoc M k (+ (* lambda (get Pdist k 0.0))
(* (- 1 lambda) (get Qdist k 0.0)))))
{}
Omega)]
(+ (* lambda (DX||Y Pdist M)) (* (- 1 lambda) (DX||Y Qdist M)))))
(defn DLX||Y
"Synonym for lambda divergence"
[l Pdist Qdist]
(lambda-divergence l Pdist Qdist))
(defn jensen-shannon
"Computes Jensen-Shannon Divergence of the two distributions Pdist
and Qdist. Pdist and Qdist _must_ be over the same sample space!"
[Pdist Qdist]
#_(let [Omega (set/union (set (keys Pdist)) (set (keys Qdist)))
M (reduce (fn[M k]
(assoc M k (/ (+ (get Pdist k 0.0)
(get Qdist k 0.0))
2.0)))
{}
Omega)]
(/ (+ (DX||Y Pdist M) (DX||Y Qdist M)) 2.0))
(lambda-divergence 0.5 Pdist Qdist))
(defn log-odds [frq1 frq2]
(log2 (/ frq1 frq2)))
(defn lod-score [qij pi pj]
(log2 (/ qij (* pi pj))))
(defn raw-lod-score [qij pi pj & {scaling :scaling :or {scaling 1.0}}]
(if (= scaling 1.0)
(lod-score qij pi pj)
(int (/ (lod-score qij pi pj) scaling))))
;;; ----------------------------------------------------------------------
;;;
;;; Fixed cost Edit distance.
;;;
;;; (levenshtein "this" "")
;;; (assert (= 0 (levenshtein "" "")))
;;; (assert (= 3 (levenshtein "foo" "foobar")))
;;; (assert (= 3 (levenshtein "kitten" "sitting")))
;;; (assert (= 3 (levenshtein "Saturday" "Sunday")))
;;; (assert (= 22 (levenshtein
;;; "TATATTTGGAGTTATACTATGTCTCTAAGCACTGAAGCAAA"
;;; "TATATATTTTGGAGATGCACAT"))
;;;
(defn- new-row [prev-row row-elem t]
(reduce
(fn [row [d-1 d e]]
(conj row (if (= row-elem e) d-1 (inc (min (peek row) d d-1)))))
[(inc (first prev-row))]
(map vector prev-row (next prev-row) t)))
(defn levenshtein
"Compute the Levenshtein (edit) distance between S and T, where S
and T are either sequences or strings.
Examples: (levenshtein [1 2 3 4] [1 1 3]) ==> 2
(levenshtein \"abcde\" \"bcdea\") ==> 2
"
[s t]
(cond
(or (= s t "") (and (empty? s) (empty? t))) 0
(= 0 (count s)) (count t)
(= 0 (count t)) (count s)
:else
(peek (reduce
(fn [prev-row s-elem] (new-row prev-row s-elem t))
(range (inc (count t)))
s))))
(defn- hamming-stgs [s1 s2]
(let [sz1 (long (count s1))
len (long (min sz1 (long (count s2))))]
(loop [i (long 0)
cnt (long (Math/abs (- len sz1)))]
(if (= i len)
cnt
(if (= (austr/get s1 i) (austr/get s2 i))
(recur (inc i) cnt)
(recur (inc i) (inc cnt)))))))
(defn hamming
"Compute hamming distance between sequences S1 and S2. If both s1
and s2 are strings, performs an optimized version"
[s1 s2]
(if (and (string? s1) (string? s2))
(hamming-stgs s1 s2)
(reduce + (map (fn [b1 b2] (if (= b1 b2) 0 1)) s1 s2))))
(defn diff-fn
"Return the function that is 1-F applied to its args: (1-(apply f
args)). Intended for normalized distance metrics.
Ex: (let [dice-diff (diff-fn dice-coeff) ...]
(dice-diff some-set1 some-set2))
"
[f]
(fn [& args] (- 1 (apply f args))))
(defn dice-coeff [s1 s2]
(/ (* 2 (count (set/intersection s1 s2)))
(+ (count s1) (count s2))))
(defn jaccard-index [s1 s2]
(/ (count (set/intersection s1 s2))
(count (set/union s1 s2))))
(defn tversky-index
"Tversky index of two sets S1 and S2. A generalized NON metric
similarity 'measure'. Generalization is through the ALPHA and BETA
coefficients:
TI(S1,S2) = (/ |S1^S2| (+ |S1^S2| (* ALPHA |S1-S2|) (* BETA |S2-S1|)))
For example, with alpha=beta=1, TI is jaccard-index
with alpha=beta=1/2 TI is dice-coeff
"
[s1 s2 alpha beta]
(let [s1&s2 (count (set/intersection s1 s2))
s1-s2 (count (set/difference s1 s2))
s2-s1 (count (set/difference s2 s1))]
(/ s1&s2
(+ s1&s2 (* alpha s1-s2) (* beta s2-s1)))))
(def
^{:doc
"Named version of (diff-fn jaccard-index s1 s2). This difference
function is a similarity that is a proper _distance_ metric (hence
usable in metric trees like bk-trees)."
:arglists '([s1 s2])}
jaccard-dist
(diff-fn jaccard-index))
(defn freq-jaccard-index
""
[s1 s2]
(let [freq-s1 (set s1)
freq-s2 (set s2)
c1 (sum (set/intersection freq-s1 freq-s2))
c2 (sum (set/union freq-s1 freq-s2))]
(/ c1 c2)))
(defn bi-tri-grams [s]
(let [bi-grams (set (keys (freqn 2 s)))
tri-grams (set (keys (freqn 3 s)))]
[(set/union bi-grams tri-grams)
[bi-grams tri-grams]]))
(defn all-grams [s]
(let [all-gram-sets
(for [n (range 1 (count s))]
(-> (freqn n s) keys set))]
[(apply set/union all-gram-sets) all-gram-sets]))
(defn ngram-compare
""
[s1 s2 & {uc? :uc? n :n scfn :scfn ngfn :ngfn
:or {n 2 uc? false scfn dice-coeff ngfn word-letter-pairs}}]
(let [s1 (ngfn n (if uc? (str/upper-case s1) s1))
s2 (ngfn n (if uc? (str/upper-case s2) s2))]
(scfn s1 s2)))
;;;(float (ngram-compare "FRANCE" "french"))
;;;(float (ngram-compare "FRANCE" "REPUBLIC OF FRANCE"))
;;;(float (ngram-compare "FRENCH REPUBLIC" "republic of france"))
;;;(float (ngram-compare
;;; "TATATTTGGAGTTATACTATGTCTCTAAGCACTGAAGCAAA"
;;; "TATATATTTTGGAGATGCACAT"))
(defn normed-codepoints [s]
(vec (map #(let [nc (- % 97)]
(cond
(>= nc 0) nc
(= % 32) 27
:else 28))
(codepoints s))))
(defn ngram-vec [s & {n :n :or {n 2}}]
(let [ngrams (word-letter-pairs s n)
ngram-points (map (fn [[x y]]
(int (+ (* x 27) y)))
(map normed-codepoints ngrams))
v (int-array 784 0)]
(doseq [i ngram-points]
(aset v i 1))
v))
;;;-------------------------------------------------------------------------;;;
;;; ;;;
;;; Minimization and Maximization of Entropy Principles ;;;
;;; ;;;
;;; Cumulative Relative Entropy, Centroid Frequency and Probability ;;;
;;; dictionaries, information capacity, et.al. ;;;
;;; ;;;
;;;-------------------------------------------------------------------------;;;
(defn expected-qdict [q-1 q-2 & {:keys [alpha] :or {alpha ["A" "U" "G" "C"]}}]
(reduce (fn[m lmer]
(let [l (dec (count lmer))
x (subs lmer 1)
y (subs lmer 0 l)
z (subs lmer 1 l)]
(if (and (q-1 x) (q-1 y) (q-2 z))
(assoc m lmer (/ (* (q-1 x) (q-1 y)) (q-2 z)))
m)))
{} (for [x (keys q-1) a alpha] (str x a))))
(defn freq-xdict-dict
[q sq]
(let [ext-sq (str sq "X")
residue-key (subs ext-sq (- (count sq) (- q 1)))
q-xfreq-dict (freqn q ext-sq)
q-freq-dict (dissoc q-xfreq-dict residue-key)]
[q-xfreq-dict q-freq-dict]))
(defn q-1-dict
([q-xdict]
(reduce (fn[m [k v]]
(let [l (count k)
pre (subs k 0 (dec l))]
(assoc m pre (+ (get m pre 0) v))))
{} q-xdict))
([q sq]
(probs (dec q) sq)))
(defn q1-xdict-dict
[q sq & {:keys [ffn] :or {ffn probs}}]
(let [[q-xfreq-dict q-freq-dict] (freq-xdict-dict q sq)
q-xpdf-dict (probs q-xfreq-dict)
q-pdf-dict (probs q-freq-dict)]
{:xfreq q-xfreq-dict :xpdf q-xpdf-dict
:freq q-freq-dict :pdf q-pdf-dict}))
(defn reconstruct-dict
[l sq & {:keys [alpha] :or {alpha ["A" "U" "G" "C"]}}]
{:pre [(> l 2)]}
(let [q (dec l)
qmaps (q1-xdict-dict q sq)
[q-xdict q-dict] (map qmaps [:xpdf :pdf])
q-1dict (q-1-dict q-xdict)]
(expected-qdict q-dict q-1dict :alpha alpha)))
(defn max-qdict-entropy
[q & {:keys [alpha] :or {alpha ["A" "U" "G" "C"]}}]
(let [base (count alpha)]
(* q (log2 base))))
(defn informativity
([q sq]
(- (max-qdict-entropy q) (entropy (probs q sq))))
([q-dict]
(let [q (count (first (keys q-dict)))]
(- (max-qdict-entropy q) (entropy q-dict)))))
(defn limit-entropy
[q|q-dict sq|q-1dict &
{:keys [alpha NA] :or {alpha ["A" "U" "G" "C"] NA -1.0}}]
{:pre [(or (and (integer? q|q-dict)
(or (string? sq|q-1dict) (coll? sq|q-1dict)))
(and (map? q|q-dict) (map? sq|q-1dict)))]}
(if (map? q|q-dict)
(let [q-dict q|q-dict
q-1dict sq|q-1dict]
(/ (- (entropy q-dict) (entropy q-1dict))
(log2 (count alpha))))
(let [q q|q-dict
sq sq|q-1dict
lgcnt (log2 (count alpha))]
(if (= q 1)
(/ (entropy (probs 1 sq)) lgcnt)
(let [qmaps (q1-xdict-dict q sq)
[q-xdict q-dict] (map qmaps [:xpdf :pdf])
q-1dict (q-1-dict q-xdict)]
(if (< (count q-dict) (count q-1dict))
(if (fn? NA) (NA q-dict q-1dict) NA)
(/ (- (entropy q-dict) (entropy q-1dict)) lgcnt)))))))
(defn limit-informativity
([q sq]
)
([q-dict]
))
(defn CREl
[l sq & {:keys [limit alpha]
:or {limit 15}}]
{:pre [(> l 2) alpha]}
(sum (fn[k]
(catch-all (DX||Y
(probs k sq)
(reconstruct-dict k sq :alpha alpha))))
(range l (inc limit))))
(defn information-capacity
[q sq & {:keys [cmpfn] :or {cmpfn jensen-shannon}}]
(catch-all (cmpfn (probs q sq)
(reconstruct-dict q sq))))
(defn hybrid-dictionary
"Compute the 'hybrid', aka centroid, dictionary or Feature Frequency
Profile (FFP) for sqs. SQS is either a collection of already
computed FFPs (probability maps) of sequences, or a collection of
sequences, or a string denoting a sequence file (sto, fasta, aln,
...) giving a collection of sequences. In the latter cases, the
sequences will have their FFPs computed based on word/feature
length L (resolution size). In all cases the FFPs are combined,
using the minimum entropy principle, into a joint ('hybrid' /
centroid) FFP.
"
[l sqs]
{:pre [(or (string? sqs) (coll? sqs))]}
(let [sqs (if (-> sqs first map?)
sqs
(if (coll? sqs) sqs (raise :type :old-read-seqs :sqs sqs)))
cnt (count sqs)
par (max (math/floor (/ cnt 10)) 2)
dicts (if (-> sqs first map?) sqs (vfold #(probs l %) sqs))
hybrid (apply merge-with +
(vfold (fn[subset] (apply merge-with + subset))
(partition-all (/ (count dicts) par) dicts)))]
(reduce (fn[m [k v]] (assoc m k (double (/ v cnt))))
{} hybrid)))
| 51767 | ;;--------------------------------------------------------------------------;;
;; ;;
;; U T I L S . I N F O T H ;;
;; ;;
;; 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. ;;
;; ;;
;; Author: <NAME> ;;
;; ;;
;;--------------------------------------------------------------------------;;
;;
(ns aerial.utils.math.infoth
"Various Information Theory functions and measures rooted in Shannon
Entropy measure and targetting a variety of sequence and string
data."
(:require [clojure.math.numeric-tower :as math]
[clojure.string :as str]
[clojure.set :as set]
[aerial.utils.misc
:refer [raise catch-all]]
[aerial.utils.coll
:refer [reducem subsets vfold]]
[aerial.utils.string :as austr
:refer [codepoints]]
[aerial.utils.math
:refer [sum log2]]
[aerial.utils.math.combinatorics
:refer [combins]]
[aerial.utils.math.probs-stats
:refer [joint-probability freqn probs word-letter-pairs]]
))
(defn shannon-entropy
"Returns the Shannon entropy of a sequence: -sum(* pi (log pi)),
where i ranges over the unique elements of S and pi is the
probability of i in S: (freq i s)/(count s)"
[s & {logfn :logfn :or {logfn log2}}]
(let [fs (frequencies s)
cnt (double (sum fs))
H (sum (fn[[_ v]]
(let [p (double (/ v cnt))]
(double (* p (double (logfn p))))))
fs)]
(double (- H))))
(defn entropy
"Entropy calculation for the probability distribution dist.
Typically dist is a map giving the PMF of some sample space. If it
is a string or vector, this calls shannon-entropy on dist.
"
[dist & {logfn :logfn :or {logfn log2}}]
(if (or (string? dist) (vector? dist))
(shannon-entropy dist :logfn logfn)
(let [dist (if (map? dist) (vals dist) dist)]
(- (sum (fn[v]
(let [v (double v)]
(if (= 0.0 v)
0.0
(double (* v (logfn v))))))
dist)))))
(defn joint-entropy
"Given a set of collections c1, c2, c3, .. cn, and combinator, a
function of n variables which generates joint occurances from {ci},
returns the joint entropy over all the set:
-sum(* px1..xn (log2 px1..xn))
OPTS is a map of options, currently sym? and logfn. The defaults
are false and log2. If sym? is true, treat [x y] and [y x] as
equal. logfn can be used to provide a log of a different base.
log2, the default, reports in bits. If no options are required,
the empty map must be passed: (joint-entropy transpose {} my-coll)
"
([combinator opts coll]
(let [{:keys [sym? logfn] :or {sym? false logfn log2}} opts]
(entropy (joint-probability combinator sym? coll)
:logfn logfn)))
([combinator opts coll & colls]
(let [{:keys [sym? logfn] :or {sym? false logfn log2}} opts]
(entropy (apply joint-probability combinator sym? coll colls)
:logfn logfn))))
(defn HXY
"Synonym for joint-entropy"
[& args]
(apply joint-entropy args))
(defn cond-entropy
"Given the joint probability distribution PXY and the distribution
PY, return the conditional entropy of X given Y = H(X,Y) - H(Y).
Alternatively, given a set of collections c1, c2, c3, .. cn, and
combinator, a function of n variables which generates joint
occurances from {ci}, returns the multivariate conditional entropy
induced from the joint probability distributions.
OPTS is a map of options, currently sym? and logfn. The defaults
are false and log2. If sym? is true, treat [x y] and [y x] as
equal. logfn can be used to provide a log of a different base.
log2, the default, reports in bits. If no options are required,
the empty map must be passed: (cond-entropy transpose {} my-coll)
For the case of i > 2, uses the recursive chain rule for
conditional entropy (bottoming out in the two collection case):
H(X1,..Xn-1|Xn) = (sum H(Xi|Xn,X1..Xi-1) (range 1 (inc n)))
"
([PXY PY]
(- (entropy PXY) (entropy PY)))
([combinator opts coll1 coll2]
(let [{:keys [sym? logfn] :or {sym? false logfn log2}} opts]
(- (entropy (joint-probability combinator sym? coll1 coll2) :logfn logfn)
(entropy (probs 1 coll2) :logfn logfn))))
([combinator opts coll1 coll2 & colls]
(let [{:keys [sym? logfn] :or {sym? false logfn log2}} opts]
;; Apply chain rule...
(- (entropy (apply joint-probability combinator sym? coll1 coll2 colls)
:logfn logfn)
(apply cond-entropy combinator opts coll2 colls)))))
(defn HX|Y
"Synonym for cond-entropy"
[& args]
(apply cond-entropy args))
(defn combin-joint-entropy
"Given a set of collections c1, c2, c3, .. cn, return the joint
entropy: - (sum (* px1..xn (log2 px1..xn)) all-pairs-over {ci}).
Where all-pairs-over is an exhaustive combination of elements of
{ci} taken n at a time, where each n-tuple has exactly one element
from each ci (i.e., the cross product of {ci}).
Reports in bits (logfn = log2) and treats [x y] [y x] elements as
the same.
"
([coll1 coll2]
(joint-entropy
(fn[s1 s2] (reducem (fn[x y] [[x y]]) concat s1 s2))
{:sym? true}
coll1 coll2))
([coll1 coll2 & colls]
(apply joint-entropy
(fn[& cs]
(apply reducem (fn[& args] [args]) concat cs))
{:sym? true} coll1 coll2 colls)))
(defn seq-joint-entropy
"Returns the joint entropy of a sequence with itself: -sum(* pi (log
pi)), where probabilities pi are of combinations of elements of S
taken 2 at a time. If sym?, treat [x y] and [y x] as equal.
"
[s & {:keys [sym? logfn] :or {sym? false logfn log2}}]
(joint-entropy #(combins 2 %) sym? s))
(defn relative-entropy
"Take two distributions (that must be over the same space) and
compute the expectation of their log ratio: Let px be the PMF of
pdist1 and py be the PMF pdist2, return
(sum (fn[px py] (* px (log2 (/ px py)))) xs ys)
Here, pdist(1|2) are maps giving the probability distributions (and
implicitly the pmfs), as provided by freqs-probs, probs,
cc-freqs-probs, combins-freqs-probs, cc-combins-freqs-probs,
et. al. Or any map where the values are the probabilities of the
occurance of the keys over some sample space. Any summation term
where (or (= px 0) (= py 0)), is taken as 0.0.
NOTE: maps should have same keys! If this is violated it is likely
you will get a :negRE exception or worse, bogus results. However,
as long as the maps reflect distributions _over the same sample
space_, they do not need to be a complete sampling (a key/value for
all sample space items) - missing keys will be included as 0.0
values.
Also known as Kullback-Leibler Divergence (KLD)
KLD >= 0.0 in all cases.
"
[pdist1 pdist2 & {:keys [logfn] :or {logfn log2}}]
;; Actually, we try to 'normalize' maps to same sample space.
(let [Omega (set/union (set (keys pdist1)) (set (keys pdist2)))
KLD (sum (fn[k]
(let [pi (get pdist1 k 0.0)
qi (get pdist2 k 0.0)]
(if (or (= pi 0.0) (= qi 0.0))
(double 0.0)
(* pi (logfn (/ pi qi))))))
Omega)]
(cond
(>= KLD 0.0) KLD
(< (math/abs KLD) 1.0E-10) 0.0
:else
(raise
:type :negRE :KLD KLD :Pdist pdist1 :Qdist pdist2))))
(defn KLD
"Synonym for relative-entropy.
args is [pd1 pd2 & {:keys [logfn] :or {logfn log2}}"
[& args] (apply relative-entropy args))
(defn DX||Y
"Synonym for relative-entropy.
args is [pd1 pd2 & {:keys [logfn] :or {logfn log2}}"
[& args] (apply relative-entropy args))
(defn mutual-information
"Mutual information between the content of coll1 and coll2 as
combined by combinator, a function of two variables, presumed to be
over coll1 and coll2 returning a collection of combined elements.
OPTS is a map of options, currently sym? and logfn. The defaults
are false and log2. If sym? is true, treat [x y] and [y x] as
equal. logfn can be used to provide a log of a different base.
log2, the default, reports in bits. If no options are required,
the empty map must be passed: (mutual-information transpose {} my-coll)
Mutual information is the relative entropy (KLD) of the joint
probability distribution to the product distribution. Here the
distributions arise out of the frequencies over coll1 and coll2
individually and jointly over the result of combinator on coll1 and
coll2.
Let C be (combinator coll1 coll2). Computes
(sum (* pxy (log2 (/ pxy (* px py)))) xs ys) =
(+ (shannon-entropy coll1) (shannon-entropy coll2) (- (joint-entropy C))) =
Hx + Hy - Hxy = I(X,Y)
(<= 0.0 I(X,Y) (min [Hx Hy]))
"
[combinator opts coll1 coll2]
(let [{:keys [sym? logfn] :or {sym? false logfn log2}} opts
HX (shannon-entropy coll1 :logfn logfn)
HY (shannon-entropy coll2 :logfn logfn)
HXY (joint-entropy combinator opts coll1 coll2)
IXY (+ HX HY (- HXY))]
(cond
(>= IXY 0.0) IXY
(< (math/abs IXY) 1.0E-10) 0.0
:else
(raise
:type :negIxy :Ixy IXY :Hxy HXY :Hx HX :Hy HY))))
(defn IXY "Synonym for mutual information"
[combinator opts coll1 coll2]
(mutual-information combinator opts coll1 coll2))
(defn conditional-mutual-information
"Conditional mutual information I(X;Y|Z). Conditional mutual
information is the relative entropy (KLD) of the conditional
distribution (of two random variables on a third) with the product
distribution of the distributed conditionals.
Here these arise out of frequencies for the information in collz
individually, collx & collz and colly & collz jointly as the result
of combinator, and collx & colly & collz jointly as the result of
combinator as well. Hence, combinator needs to be able to handle
the cases of 2 and 3 collections passed to it (collectively or as
variadic).
OPTS is a map of options, currently sym? and logfn. The defaults
are false and log2. If sym? is true, treat [x y] and [y x] as
equal. logfn can be used to provide a log of a different base.
log2, the default, reports in bits. If no options are required,
the empty map must be passed: (conditional-mutual-information
transpose {} my-coll)
Other interpretations/meanings: Conditional mutual information is
the mutual information of two random variables conditioned on a
third. Or, put another way, it is the expected value of the mutual
information of two RV over the values of a third. It measures the
amount of information shared by X & Y beyond that provided by a
common \"mediator\".
Let XYZ be (combinator collx colly collz)
XZ be (combinator collx collz)
YZ be (combinator colly collz)
Computes
sum (* pxy|z (log2 (/ pxy|z (* px|z py|z)))) xs ys zs =
... (some algebra and applications of Bayes) ...
sum (* pxyz (log2 (/ (* pz pxyz) (* pxz pyz)))) xyzs xzs yzs
... (some more algebra and entropy identitities) ...
(+ H(X,Z) H(Y,Z) -H(X,Y,Z) -H(Z))
which is easier to work with...
"
[combinator opts collx colly collz]
(let [{:keys [sym? logfn] :or {sym? false logfn log2}} opts
PXYZ (vals (joint-probability combinator sym? collx colly collz))
HXYZ (entropy PXYZ :logfn logfn)
PXZ (vals (joint-probability combinator sym? collx collz))
HXZ (entropy PXZ :logfn logfn)
PYZ (vals (joint-probability combinator sym? colly collz))
HYZ (entropy PYZ :logfn logfn)
PZ (probs 1 collz)
HZ (entropy PZ :logfn logfn)
IXY|Z (+ HXZ HYZ (- HXYZ) (- HZ))]
(cond
(>= IXY|Z 0.0) IXY|Z
(< (math/abs IXY|Z) 1.0E-10) 0.0
:else
(raise
:type :negIxy|z
:Ixy|z IXY|Z :Hxz HXZ :Hyz HYZ :Hxyz HXYZ :Hz HZ))))
(defn IXY|Z "Synonym for conditional mutual information"
[combinator opts collx colly collz]
(conditional-mutual-information combinator opts collx colly collz))
(defn variation-information
""
[combinator opts coll1 coll2]
(let [Hxy (joint-entropy combinator opts coll1 coll2)
Ixy (mutual-information combinator opts coll1 coll2)]
(- 1.0 (double (/ Ixy Hxy)))))
(defn total-correlation
"One of two forms of multivariate mutual information provided here.
The other is \"interaction information\". Total correlation
computes what is effectively the _total redundancy_ of the
information in the provided content - here the information in coll1
.. colln. As such it can give somewhat unexpected answers in
certain situations.
Information content \"measure\" is based on the distributions
arising out of the frequencies over coll1 .. colln _individually_,
and jointly over the result of combinator applied to coll1 .. colln
collectively.
OPTS is a map of options, currently sym? and logfn. The defaults
are false and log2. If sym? is true, treat [x y] and [y x] as
equal. logfn can be used to provide a log of a different base.
log2, the default, reports in bits. If no options are required,
the empty map must be passed: (total-correlation transpose {}
my-coll)
NOTE: the \"degenerate\" case of only two colls, is simply mutual
information.
Let C be (combinator coll1 coll2 .. colln), so xi1..xin in C is an
element in the joint sample space, and xi in colli is an element in
a \"marginal\" space . Computes
sum (* px1..xn (log2 (/ px1..xn (* px1 px2 .. pxn)))) x1s x2s .. xns =
Hx1 + Hx2 + .. + Hxn - Hx1x2..xn
(<= 0.0
TC(X1,..,Xn)
(min|i (sum Hx1 .. Hxi Hxi+2 .. Hxn, i = 0..n-1, Hx0=Hxn+1=0)))
Ex:
(shannon-entropy \"AAAUUUGGGGCCCUUUAAA\")
=> 1.9440097497163569
(total-correlation transpose {}
\"AAAUUUGGGGCCCUUUAAA\" \"AAAUUUGGGGCCCUUUAAA\")
=> 1.9440097497163569 ; not surprising
(total-correlation transpose {}
\"AAAUUUGGGGCCCUUUAAA\" \"AAAUUUGGGGCCCUUUAAA\"
\"AAAUUUGGGGCCCUUUAAA\" \"AAAUUUGGGGCCCUUUAAA\")
=> 5.832029249149071 ; possibly surprising if not noting tripled redundancy
"
([combinator opts coll1 coll2]
(mutual-information combinator opts coll1 coll2))
([combinator opts coll1 coll2 & colls]
(let [{:keys [sym? logfn] :or {sym? false logfn log2}} opts
colls (cons coll1 (cons coll2 colls))
Hxs (map #(shannon-entropy % :logfn logfn) colls)
HX1-Xn (apply joint-entropy combinator opts coll1 coll2 colls)
TC (- (sum Hxs) HX1-Xn)]
(cond
(>= TC 0.0) TC
(< (math/abs TC) 1.0E-10) 0.0
:else
(raise
:type :negTC
:TC TC :Hxs Hxs :HX1-XN HX1-Xn)))))
(defn TCI
"Synonym for total-correlation information"
[combinator opts coll1 coll2 & colls]
(apply total-correlation combinator opts coll1 coll2 colls))
(defn interaction-information
"One of two forms of multivariate mutual information provided here.
The other is \"total correlation\". Interaction information
computes the amount of information bound up in a set of variables,
beyond that present in _any subset_ of those variables. Well, that
seems to be the most widely held view, but there are disputes. This
can either indicate inhibition/redundancy or facilitation/synergy
between the variables. It helps to look at the 3 variable case, as
it at least lends itself to 'information' (or info venn) diagrams.
II(X,Y,Z) = I(X,Y|Z) - I(X,Y)
II measures the influence of Z on the information connection
between X and Y. Since I(X,Y|Z) < I(X,Y) is possible, II can be
negative, as well as 0 and positive. For example if Z completely
determines the information content between X & Y, then I(X,Y|Z) -
I(X,Y) would be 0 (as overlap contributed by X & Y alone is totally
redundant), while for X & Y independent of Z, I(X,Y) could still be
> 0. A _negative_ interaction indicates Z inhibits (accounts for,
causes to be irrelevant/redundant) the connection between X & Y. A
_positive_ interaction indicates Z promotes, is synergistic with,
or enhances the connection. The case of 0 is obvious...
If we use the typical info theory venn diagrams, then II is
represented as the area in all the circles. It is possible (and
typically so done) to draw the Hxi (xi in {X,Y,Z}) circles so that
all 3 have an overlap. In this case the information between any
two (the mutual information...) is partially accounted for by the
third. The extra overlap accounts for the negative value
\"correction\" of II in this case.
However, it is also possible to draw the circles so that any two
overlap but all three have null intersect. In this case, the third
variable provides an extra connection between the other two (beyond
their MI), something like a \"mediator\". This extra connection
accounts for the positive value \"facillitation\" of II in this
case.
It should be reasonably clear at this point that negative II is the
much more intuitive/typical case, and that positive cases are
surprising and typically more interesting and informative (so to
speak...). A positive example, would be the case of two mutually
exclusive causes for a common effect (third variable). In such a
case, knowing any two completely determines the other.
All of this can be bumped up to N variables via typical chain rule
recurrance.
In this implementation, the information content \"measure\" is
based on the distributions arising out of the frequencies over
coll1 .. colln _individually_, and jointly over the result of
combinator applied collectively to all subsets of coll1 .. colln.
OPTS is a map of options, currently sym? and logfn. The defaults
are false and log2. If sym? is true, treat [x y] and [y x] as
equal. logfn can be used to provide a log of a different base.
log2, the default, reports in bits. If no options are required,
the empty map must be passed: (interaction-information transpose {}
my-coll)
For collections coll1..colln and variadic combinator over any
subset of collections, Computes:
(sum (fn[ss] (* (expt -1 (- n |ss|))
(HXY combinator sym? ss)))
(subsets all-colls))
|ss| = cardinality/count of subset ss. ss is a subset of
coll1..colln. If sym? is true, treat reversable combined items as
equal (see HYX/joint-entropy).
For n=3, this reduces to (- (IXY|Z combinator sym? collx colly collz)
(IXY combinator sym? collx colly))
Ex:
(interaction-information transpose {}
\"AAAGGGUUUUAAUAUUAAAAUUU\"
\"AAAGGGUGGGAAUAUUCCCAUUU\"
\"AAAGGGUGGGAAUAUUCCCAUUU\")
=> -1.1673250256261127
Ex:
(interaction-information transpose {}
\"AAAGGGUUUUAAUAUUAAAAUUU\"
\"AAAGGGUGGGAAUAUUCCCAUUU\"
(reverse-compliment \"AAAGGGUGGGAAUAUUCCCAUUU\"))
=> -0.282614135781623
Ex: Shows synergy (positive value)
(let [X1 [0 1] ; 7 independent binary vars
X2 [0 1]
X3 [0 1]
X4 [0 1]
X5 [0 1]
X6 [0 1]
X7 [0 1]
X8 [0 1]
Y1 [X1 X2 X3 X4 X5 X6 X7]
Y2 [X4 X5 X6 X7]
Y3 [X5 X6 X7]
Y4 [X7]
bitval #(loop [bits (reverse %) n 0 v 0]
(if (empty? bits)
v
(recur (rest bits)
(inc n)
(+ v (* (first bits) (math/expt 2 n))))))
rfn #(map bitval (apply reducem (fn[& args] [args]) concat %))
;; Turn to (partially redundant) value sets - each Yi is the set
;; of all numbers for all (count Yi) bit patterns. So, Y1, Y2,
;; and Y3 share all values of 3 bits, while the group with Y4
;; added shares just all 1 bit patterns
Y1 (rfn Y1)
Y2 (rfn Y2)
Y3 (rfn Y3)
Y4 (rfn Y4)]
[(interaction-information concat {} Y1 Y2 Y3)
(interaction-information concat {} Y1 Y2 Y3 Y4)])
=> [-3.056592722891465 ; Intuitive, since 3 way sharing
1.0803297840536592] ; Unintuitive, since 1 way sharing induces synergy!?
"
#_([combinator opts collx colly collz]
(let [Ixy|z (IXY|Z combinator opts collx colly collz)
Ixy (IXY combinator opts collx colly)]
(- Ixy|z Ixy)))
([combinator opts collx colly collz & colls]
(let [colls (->> colls (cons collz) (cons colly) (cons collx))
ssets (remove empty? (subsets colls))
tcnt (count colls)]
(- (sum (fn[ss]
(let [sscnt (count ss)]
(* (math/expt -1.0 (- tcnt sscnt))
(apply joint-entropy combinator opts ss))))
ssets)))))
(defn II
"Synonym for interaction-information"
[combinator opts collx colly collz & colls]
(apply interaction-information combinator opts collx colly collz colls))
(defn lambda-divergence
"Computes a symmetrized KLD variant based on a probability
parameter, typically notated lambda, in [0..1] for each
distribution:
(+ (* lambda (DX||Y Pdist M)) (* (- 1 lambda) (DX||Y Qdist M)))
Where M = (+ (* lambda Pdist) (* (- 1 lambda) Qdist))
= (merge-with (fn[pi qi] (+ (* lambda pi) (* (- 1 lambda) qi)))
Pdist Qdist)
For lambda = 1/2, this reduces to
M = 1/2 (merge-with (fn[pi qi] (+ pi qi)) P Q)
and (/ (+ (DX||Y Pdist M) (DX||Y Qdist M)) 2) = jensen shannon
"
[lambda Pdist Qdist]
(let [Omega (set/union (set (keys Pdist)) (set (keys Qdist)))
M (reduce (fn[M k]
(assoc M k (+ (* lambda (get Pdist k 0.0))
(* (- 1 lambda) (get Qdist k 0.0)))))
{}
Omega)]
(+ (* lambda (DX||Y Pdist M)) (* (- 1 lambda) (DX||Y Qdist M)))))
(defn DLX||Y
"Synonym for lambda divergence"
[l Pdist Qdist]
(lambda-divergence l Pdist Qdist))
(defn jensen-shannon
"Computes Jensen-Shannon Divergence of the two distributions Pdist
and Qdist. Pdist and Qdist _must_ be over the same sample space!"
[Pdist Qdist]
#_(let [Omega (set/union (set (keys Pdist)) (set (keys Qdist)))
M (reduce (fn[M k]
(assoc M k (/ (+ (get Pdist k 0.0)
(get Qdist k 0.0))
2.0)))
{}
Omega)]
(/ (+ (DX||Y Pdist M) (DX||Y Qdist M)) 2.0))
(lambda-divergence 0.5 Pdist Qdist))
(defn log-odds [frq1 frq2]
(log2 (/ frq1 frq2)))
(defn lod-score [qij pi pj]
(log2 (/ qij (* pi pj))))
(defn raw-lod-score [qij pi pj & {scaling :scaling :or {scaling 1.0}}]
(if (= scaling 1.0)
(lod-score qij pi pj)
(int (/ (lod-score qij pi pj) scaling))))
;;; ----------------------------------------------------------------------
;;;
;;; Fixed cost Edit distance.
;;;
;;; (levenshtein "this" "")
;;; (assert (= 0 (levenshtein "" "")))
;;; (assert (= 3 (levenshtein "foo" "foobar")))
;;; (assert (= 3 (levenshtein "kitten" "sitting")))
;;; (assert (= 3 (levenshtein "Saturday" "Sunday")))
;;; (assert (= 22 (levenshtein
;;; "TATATTTGGAGTTATACTATGTCTCTAAGCACTGAAGCAAA"
;;; "TATATATTTTGGAGATGCACAT"))
;;;
(defn- new-row [prev-row row-elem t]
(reduce
(fn [row [d-1 d e]]
(conj row (if (= row-elem e) d-1 (inc (min (peek row) d d-1)))))
[(inc (first prev-row))]
(map vector prev-row (next prev-row) t)))
(defn levenshtein
"Compute the Levenshtein (edit) distance between S and T, where S
and T are either sequences or strings.
Examples: (levenshtein [1 2 3 4] [1 1 3]) ==> 2
(levenshtein \"abcde\" \"bcdea\") ==> 2
"
[s t]
(cond
(or (= s t "") (and (empty? s) (empty? t))) 0
(= 0 (count s)) (count t)
(= 0 (count t)) (count s)
:else
(peek (reduce
(fn [prev-row s-elem] (new-row prev-row s-elem t))
(range (inc (count t)))
s))))
(defn- hamming-stgs [s1 s2]
(let [sz1 (long (count s1))
len (long (min sz1 (long (count s2))))]
(loop [i (long 0)
cnt (long (Math/abs (- len sz1)))]
(if (= i len)
cnt
(if (= (austr/get s1 i) (austr/get s2 i))
(recur (inc i) cnt)
(recur (inc i) (inc cnt)))))))
(defn hamming
"Compute hamming distance between sequences S1 and S2. If both s1
and s2 are strings, performs an optimized version"
[s1 s2]
(if (and (string? s1) (string? s2))
(hamming-stgs s1 s2)
(reduce + (map (fn [b1 b2] (if (= b1 b2) 0 1)) s1 s2))))
(defn diff-fn
"Return the function that is 1-F applied to its args: (1-(apply f
args)). Intended for normalized distance metrics.
Ex: (let [dice-diff (diff-fn dice-coeff) ...]
(dice-diff some-set1 some-set2))
"
[f]
(fn [& args] (- 1 (apply f args))))
(defn dice-coeff [s1 s2]
(/ (* 2 (count (set/intersection s1 s2)))
(+ (count s1) (count s2))))
(defn jaccard-index [s1 s2]
(/ (count (set/intersection s1 s2))
(count (set/union s1 s2))))
(defn tversky-index
"Tversky index of two sets S1 and S2. A generalized NON metric
similarity 'measure'. Generalization is through the ALPHA and BETA
coefficients:
TI(S1,S2) = (/ |S1^S2| (+ |S1^S2| (* ALPHA |S1-S2|) (* BETA |S2-S1|)))
For example, with alpha=beta=1, TI is jaccard-index
with alpha=beta=1/2 TI is dice-coeff
"
[s1 s2 alpha beta]
(let [s1&s2 (count (set/intersection s1 s2))
s1-s2 (count (set/difference s1 s2))
s2-s1 (count (set/difference s2 s1))]
(/ s1&s2
(+ s1&s2 (* alpha s1-s2) (* beta s2-s1)))))
(def
^{:doc
"Named version of (diff-fn jaccard-index s1 s2). This difference
function is a similarity that is a proper _distance_ metric (hence
usable in metric trees like bk-trees)."
:arglists '([s1 s2])}
jaccard-dist
(diff-fn jaccard-index))
(defn freq-jaccard-index
""
[s1 s2]
(let [freq-s1 (set s1)
freq-s2 (set s2)
c1 (sum (set/intersection freq-s1 freq-s2))
c2 (sum (set/union freq-s1 freq-s2))]
(/ c1 c2)))
(defn bi-tri-grams [s]
(let [bi-grams (set (keys (freqn 2 s)))
tri-grams (set (keys (freqn 3 s)))]
[(set/union bi-grams tri-grams)
[bi-grams tri-grams]]))
(defn all-grams [s]
(let [all-gram-sets
(for [n (range 1 (count s))]
(-> (freqn n s) keys set))]
[(apply set/union all-gram-sets) all-gram-sets]))
(defn ngram-compare
""
[s1 s2 & {uc? :uc? n :n scfn :scfn ngfn :ngfn
:or {n 2 uc? false scfn dice-coeff ngfn word-letter-pairs}}]
(let [s1 (ngfn n (if uc? (str/upper-case s1) s1))
s2 (ngfn n (if uc? (str/upper-case s2) s2))]
(scfn s1 s2)))
;;;(float (ngram-compare "FRANCE" "french"))
;;;(float (ngram-compare "FRANCE" "REPUBLIC OF FRANCE"))
;;;(float (ngram-compare "FRENCH REPUBLIC" "republic of france"))
;;;(float (ngram-compare
;;; "TATATTTGGAGTTATACTATGTCTCTAAGCACTGAAGCAAA"
;;; "TATATATTTTGGAGATGCACAT"))
(defn normed-codepoints [s]
(vec (map #(let [nc (- % 97)]
(cond
(>= nc 0) nc
(= % 32) 27
:else 28))
(codepoints s))))
(defn ngram-vec [s & {n :n :or {n 2}}]
(let [ngrams (word-letter-pairs s n)
ngram-points (map (fn [[x y]]
(int (+ (* x 27) y)))
(map normed-codepoints ngrams))
v (int-array 784 0)]
(doseq [i ngram-points]
(aset v i 1))
v))
;;;-------------------------------------------------------------------------;;;
;;; ;;;
;;; Minimization and Maximization of Entropy Principles ;;;
;;; ;;;
;;; Cumulative Relative Entropy, Centroid Frequency and Probability ;;;
;;; dictionaries, information capacity, et.al. ;;;
;;; ;;;
;;;-------------------------------------------------------------------------;;;
(defn expected-qdict [q-1 q-2 & {:keys [alpha] :or {alpha ["A" "U" "G" "C"]}}]
(reduce (fn[m lmer]
(let [l (dec (count lmer))
x (subs lmer 1)
y (subs lmer 0 l)
z (subs lmer 1 l)]
(if (and (q-1 x) (q-1 y) (q-2 z))
(assoc m lmer (/ (* (q-1 x) (q-1 y)) (q-2 z)))
m)))
{} (for [x (keys q-1) a alpha] (str x a))))
(defn freq-xdict-dict
[q sq]
(let [ext-sq (str sq "X")
residue-key (subs ext-sq (- (count sq) (- q 1)))
q-xfreq-dict (freqn q ext-sq)
q-freq-dict (dissoc q-xfreq-dict residue-key)]
[q-xfreq-dict q-freq-dict]))
(defn q-1-dict
([q-xdict]
(reduce (fn[m [k v]]
(let [l (count k)
pre (subs k 0 (dec l))]
(assoc m pre (+ (get m pre 0) v))))
{} q-xdict))
([q sq]
(probs (dec q) sq)))
(defn q1-xdict-dict
[q sq & {:keys [ffn] :or {ffn probs}}]
(let [[q-xfreq-dict q-freq-dict] (freq-xdict-dict q sq)
q-xpdf-dict (probs q-xfreq-dict)
q-pdf-dict (probs q-freq-dict)]
{:xfreq q-xfreq-dict :xpdf q-xpdf-dict
:freq q-freq-dict :pdf q-pdf-dict}))
(defn reconstruct-dict
[l sq & {:keys [alpha] :or {alpha ["A" "U" "G" "C"]}}]
{:pre [(> l 2)]}
(let [q (dec l)
qmaps (q1-xdict-dict q sq)
[q-xdict q-dict] (map qmaps [:xpdf :pdf])
q-1dict (q-1-dict q-xdict)]
(expected-qdict q-dict q-1dict :alpha alpha)))
(defn max-qdict-entropy
[q & {:keys [alpha] :or {alpha ["A" "U" "G" "C"]}}]
(let [base (count alpha)]
(* q (log2 base))))
(defn informativity
([q sq]
(- (max-qdict-entropy q) (entropy (probs q sq))))
([q-dict]
(let [q (count (first (keys q-dict)))]
(- (max-qdict-entropy q) (entropy q-dict)))))
(defn limit-entropy
[q|q-dict sq|q-1dict &
{:keys [alpha NA] :or {alpha ["A" "U" "G" "C"] NA -1.0}}]
{:pre [(or (and (integer? q|q-dict)
(or (string? sq|q-1dict) (coll? sq|q-1dict)))
(and (map? q|q-dict) (map? sq|q-1dict)))]}
(if (map? q|q-dict)
(let [q-dict q|q-dict
q-1dict sq|q-1dict]
(/ (- (entropy q-dict) (entropy q-1dict))
(log2 (count alpha))))
(let [q q|q-dict
sq sq|q-1dict
lgcnt (log2 (count alpha))]
(if (= q 1)
(/ (entropy (probs 1 sq)) lgcnt)
(let [qmaps (q1-xdict-dict q sq)
[q-xdict q-dict] (map qmaps [:xpdf :pdf])
q-1dict (q-1-dict q-xdict)]
(if (< (count q-dict) (count q-1dict))
(if (fn? NA) (NA q-dict q-1dict) NA)
(/ (- (entropy q-dict) (entropy q-1dict)) lgcnt)))))))
(defn limit-informativity
([q sq]
)
([q-dict]
))
(defn CREl
[l sq & {:keys [limit alpha]
:or {limit 15}}]
{:pre [(> l 2) alpha]}
(sum (fn[k]
(catch-all (DX||Y
(probs k sq)
(reconstruct-dict k sq :alpha alpha))))
(range l (inc limit))))
(defn information-capacity
[q sq & {:keys [cmpfn] :or {cmpfn jensen-shannon}}]
(catch-all (cmpfn (probs q sq)
(reconstruct-dict q sq))))
(defn hybrid-dictionary
"Compute the 'hybrid', aka centroid, dictionary or Feature Frequency
Profile (FFP) for sqs. SQS is either a collection of already
computed FFPs (probability maps) of sequences, or a collection of
sequences, or a string denoting a sequence file (sto, fasta, aln,
...) giving a collection of sequences. In the latter cases, the
sequences will have their FFPs computed based on word/feature
length L (resolution size). In all cases the FFPs are combined,
using the minimum entropy principle, into a joint ('hybrid' /
centroid) FFP.
"
[l sqs]
{:pre [(or (string? sqs) (coll? sqs))]}
(let [sqs (if (-> sqs first map?)
sqs
(if (coll? sqs) sqs (raise :type :old-read-seqs :sqs sqs)))
cnt (count sqs)
par (max (math/floor (/ cnt 10)) 2)
dicts (if (-> sqs first map?) sqs (vfold #(probs l %) sqs))
hybrid (apply merge-with +
(vfold (fn[subset] (apply merge-with + subset))
(partition-all (/ (count dicts) par) dicts)))]
(reduce (fn[m [k v]] (assoc m k (double (/ v cnt))))
{} hybrid)))
| true | ;;--------------------------------------------------------------------------;;
;; ;;
;; U T I L S . I N F O T H ;;
;; ;;
;; 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. ;;
;; ;;
;; Author: PI:NAME:<NAME>END_PI ;;
;; ;;
;;--------------------------------------------------------------------------;;
;;
(ns aerial.utils.math.infoth
"Various Information Theory functions and measures rooted in Shannon
Entropy measure and targetting a variety of sequence and string
data."
(:require [clojure.math.numeric-tower :as math]
[clojure.string :as str]
[clojure.set :as set]
[aerial.utils.misc
:refer [raise catch-all]]
[aerial.utils.coll
:refer [reducem subsets vfold]]
[aerial.utils.string :as austr
:refer [codepoints]]
[aerial.utils.math
:refer [sum log2]]
[aerial.utils.math.combinatorics
:refer [combins]]
[aerial.utils.math.probs-stats
:refer [joint-probability freqn probs word-letter-pairs]]
))
(defn shannon-entropy
"Returns the Shannon entropy of a sequence: -sum(* pi (log pi)),
where i ranges over the unique elements of S and pi is the
probability of i in S: (freq i s)/(count s)"
[s & {logfn :logfn :or {logfn log2}}]
(let [fs (frequencies s)
cnt (double (sum fs))
H (sum (fn[[_ v]]
(let [p (double (/ v cnt))]
(double (* p (double (logfn p))))))
fs)]
(double (- H))))
(defn entropy
"Entropy calculation for the probability distribution dist.
Typically dist is a map giving the PMF of some sample space. If it
is a string or vector, this calls shannon-entropy on dist.
"
[dist & {logfn :logfn :or {logfn log2}}]
(if (or (string? dist) (vector? dist))
(shannon-entropy dist :logfn logfn)
(let [dist (if (map? dist) (vals dist) dist)]
(- (sum (fn[v]
(let [v (double v)]
(if (= 0.0 v)
0.0
(double (* v (logfn v))))))
dist)))))
(defn joint-entropy
"Given a set of collections c1, c2, c3, .. cn, and combinator, a
function of n variables which generates joint occurances from {ci},
returns the joint entropy over all the set:
-sum(* px1..xn (log2 px1..xn))
OPTS is a map of options, currently sym? and logfn. The defaults
are false and log2. If sym? is true, treat [x y] and [y x] as
equal. logfn can be used to provide a log of a different base.
log2, the default, reports in bits. If no options are required,
the empty map must be passed: (joint-entropy transpose {} my-coll)
"
([combinator opts coll]
(let [{:keys [sym? logfn] :or {sym? false logfn log2}} opts]
(entropy (joint-probability combinator sym? coll)
:logfn logfn)))
([combinator opts coll & colls]
(let [{:keys [sym? logfn] :or {sym? false logfn log2}} opts]
(entropy (apply joint-probability combinator sym? coll colls)
:logfn logfn))))
(defn HXY
"Synonym for joint-entropy"
[& args]
(apply joint-entropy args))
(defn cond-entropy
"Given the joint probability distribution PXY and the distribution
PY, return the conditional entropy of X given Y = H(X,Y) - H(Y).
Alternatively, given a set of collections c1, c2, c3, .. cn, and
combinator, a function of n variables which generates joint
occurances from {ci}, returns the multivariate conditional entropy
induced from the joint probability distributions.
OPTS is a map of options, currently sym? and logfn. The defaults
are false and log2. If sym? is true, treat [x y] and [y x] as
equal. logfn can be used to provide a log of a different base.
log2, the default, reports in bits. If no options are required,
the empty map must be passed: (cond-entropy transpose {} my-coll)
For the case of i > 2, uses the recursive chain rule for
conditional entropy (bottoming out in the two collection case):
H(X1,..Xn-1|Xn) = (sum H(Xi|Xn,X1..Xi-1) (range 1 (inc n)))
"
([PXY PY]
(- (entropy PXY) (entropy PY)))
([combinator opts coll1 coll2]
(let [{:keys [sym? logfn] :or {sym? false logfn log2}} opts]
(- (entropy (joint-probability combinator sym? coll1 coll2) :logfn logfn)
(entropy (probs 1 coll2) :logfn logfn))))
([combinator opts coll1 coll2 & colls]
(let [{:keys [sym? logfn] :or {sym? false logfn log2}} opts]
;; Apply chain rule...
(- (entropy (apply joint-probability combinator sym? coll1 coll2 colls)
:logfn logfn)
(apply cond-entropy combinator opts coll2 colls)))))
(defn HX|Y
"Synonym for cond-entropy"
[& args]
(apply cond-entropy args))
(defn combin-joint-entropy
"Given a set of collections c1, c2, c3, .. cn, return the joint
entropy: - (sum (* px1..xn (log2 px1..xn)) all-pairs-over {ci}).
Where all-pairs-over is an exhaustive combination of elements of
{ci} taken n at a time, where each n-tuple has exactly one element
from each ci (i.e., the cross product of {ci}).
Reports in bits (logfn = log2) and treats [x y] [y x] elements as
the same.
"
([coll1 coll2]
(joint-entropy
(fn[s1 s2] (reducem (fn[x y] [[x y]]) concat s1 s2))
{:sym? true}
coll1 coll2))
([coll1 coll2 & colls]
(apply joint-entropy
(fn[& cs]
(apply reducem (fn[& args] [args]) concat cs))
{:sym? true} coll1 coll2 colls)))
(defn seq-joint-entropy
"Returns the joint entropy of a sequence with itself: -sum(* pi (log
pi)), where probabilities pi are of combinations of elements of S
taken 2 at a time. If sym?, treat [x y] and [y x] as equal.
"
[s & {:keys [sym? logfn] :or {sym? false logfn log2}}]
(joint-entropy #(combins 2 %) sym? s))
(defn relative-entropy
"Take two distributions (that must be over the same space) and
compute the expectation of their log ratio: Let px be the PMF of
pdist1 and py be the PMF pdist2, return
(sum (fn[px py] (* px (log2 (/ px py)))) xs ys)
Here, pdist(1|2) are maps giving the probability distributions (and
implicitly the pmfs), as provided by freqs-probs, probs,
cc-freqs-probs, combins-freqs-probs, cc-combins-freqs-probs,
et. al. Or any map where the values are the probabilities of the
occurance of the keys over some sample space. Any summation term
where (or (= px 0) (= py 0)), is taken as 0.0.
NOTE: maps should have same keys! If this is violated it is likely
you will get a :negRE exception or worse, bogus results. However,
as long as the maps reflect distributions _over the same sample
space_, they do not need to be a complete sampling (a key/value for
all sample space items) - missing keys will be included as 0.0
values.
Also known as Kullback-Leibler Divergence (KLD)
KLD >= 0.0 in all cases.
"
[pdist1 pdist2 & {:keys [logfn] :or {logfn log2}}]
;; Actually, we try to 'normalize' maps to same sample space.
(let [Omega (set/union (set (keys pdist1)) (set (keys pdist2)))
KLD (sum (fn[k]
(let [pi (get pdist1 k 0.0)
qi (get pdist2 k 0.0)]
(if (or (= pi 0.0) (= qi 0.0))
(double 0.0)
(* pi (logfn (/ pi qi))))))
Omega)]
(cond
(>= KLD 0.0) KLD
(< (math/abs KLD) 1.0E-10) 0.0
:else
(raise
:type :negRE :KLD KLD :Pdist pdist1 :Qdist pdist2))))
(defn KLD
"Synonym for relative-entropy.
args is [pd1 pd2 & {:keys [logfn] :or {logfn log2}}"
[& args] (apply relative-entropy args))
(defn DX||Y
"Synonym for relative-entropy.
args is [pd1 pd2 & {:keys [logfn] :or {logfn log2}}"
[& args] (apply relative-entropy args))
(defn mutual-information
"Mutual information between the content of coll1 and coll2 as
combined by combinator, a function of two variables, presumed to be
over coll1 and coll2 returning a collection of combined elements.
OPTS is a map of options, currently sym? and logfn. The defaults
are false and log2. If sym? is true, treat [x y] and [y x] as
equal. logfn can be used to provide a log of a different base.
log2, the default, reports in bits. If no options are required,
the empty map must be passed: (mutual-information transpose {} my-coll)
Mutual information is the relative entropy (KLD) of the joint
probability distribution to the product distribution. Here the
distributions arise out of the frequencies over coll1 and coll2
individually and jointly over the result of combinator on coll1 and
coll2.
Let C be (combinator coll1 coll2). Computes
(sum (* pxy (log2 (/ pxy (* px py)))) xs ys) =
(+ (shannon-entropy coll1) (shannon-entropy coll2) (- (joint-entropy C))) =
Hx + Hy - Hxy = I(X,Y)
(<= 0.0 I(X,Y) (min [Hx Hy]))
"
[combinator opts coll1 coll2]
(let [{:keys [sym? logfn] :or {sym? false logfn log2}} opts
HX (shannon-entropy coll1 :logfn logfn)
HY (shannon-entropy coll2 :logfn logfn)
HXY (joint-entropy combinator opts coll1 coll2)
IXY (+ HX HY (- HXY))]
(cond
(>= IXY 0.0) IXY
(< (math/abs IXY) 1.0E-10) 0.0
:else
(raise
:type :negIxy :Ixy IXY :Hxy HXY :Hx HX :Hy HY))))
(defn IXY "Synonym for mutual information"
[combinator opts coll1 coll2]
(mutual-information combinator opts coll1 coll2))
(defn conditional-mutual-information
"Conditional mutual information I(X;Y|Z). Conditional mutual
information is the relative entropy (KLD) of the conditional
distribution (of two random variables on a third) with the product
distribution of the distributed conditionals.
Here these arise out of frequencies for the information in collz
individually, collx & collz and colly & collz jointly as the result
of combinator, and collx & colly & collz jointly as the result of
combinator as well. Hence, combinator needs to be able to handle
the cases of 2 and 3 collections passed to it (collectively or as
variadic).
OPTS is a map of options, currently sym? and logfn. The defaults
are false and log2. If sym? is true, treat [x y] and [y x] as
equal. logfn can be used to provide a log of a different base.
log2, the default, reports in bits. If no options are required,
the empty map must be passed: (conditional-mutual-information
transpose {} my-coll)
Other interpretations/meanings: Conditional mutual information is
the mutual information of two random variables conditioned on a
third. Or, put another way, it is the expected value of the mutual
information of two RV over the values of a third. It measures the
amount of information shared by X & Y beyond that provided by a
common \"mediator\".
Let XYZ be (combinator collx colly collz)
XZ be (combinator collx collz)
YZ be (combinator colly collz)
Computes
sum (* pxy|z (log2 (/ pxy|z (* px|z py|z)))) xs ys zs =
... (some algebra and applications of Bayes) ...
sum (* pxyz (log2 (/ (* pz pxyz) (* pxz pyz)))) xyzs xzs yzs
... (some more algebra and entropy identitities) ...
(+ H(X,Z) H(Y,Z) -H(X,Y,Z) -H(Z))
which is easier to work with...
"
[combinator opts collx colly collz]
(let [{:keys [sym? logfn] :or {sym? false logfn log2}} opts
PXYZ (vals (joint-probability combinator sym? collx colly collz))
HXYZ (entropy PXYZ :logfn logfn)
PXZ (vals (joint-probability combinator sym? collx collz))
HXZ (entropy PXZ :logfn logfn)
PYZ (vals (joint-probability combinator sym? colly collz))
HYZ (entropy PYZ :logfn logfn)
PZ (probs 1 collz)
HZ (entropy PZ :logfn logfn)
IXY|Z (+ HXZ HYZ (- HXYZ) (- HZ))]
(cond
(>= IXY|Z 0.0) IXY|Z
(< (math/abs IXY|Z) 1.0E-10) 0.0
:else
(raise
:type :negIxy|z
:Ixy|z IXY|Z :Hxz HXZ :Hyz HYZ :Hxyz HXYZ :Hz HZ))))
(defn IXY|Z "Synonym for conditional mutual information"
[combinator opts collx colly collz]
(conditional-mutual-information combinator opts collx colly collz))
(defn variation-information
""
[combinator opts coll1 coll2]
(let [Hxy (joint-entropy combinator opts coll1 coll2)
Ixy (mutual-information combinator opts coll1 coll2)]
(- 1.0 (double (/ Ixy Hxy)))))
(defn total-correlation
"One of two forms of multivariate mutual information provided here.
The other is \"interaction information\". Total correlation
computes what is effectively the _total redundancy_ of the
information in the provided content - here the information in coll1
.. colln. As such it can give somewhat unexpected answers in
certain situations.
Information content \"measure\" is based on the distributions
arising out of the frequencies over coll1 .. colln _individually_,
and jointly over the result of combinator applied to coll1 .. colln
collectively.
OPTS is a map of options, currently sym? and logfn. The defaults
are false and log2. If sym? is true, treat [x y] and [y x] as
equal. logfn can be used to provide a log of a different base.
log2, the default, reports in bits. If no options are required,
the empty map must be passed: (total-correlation transpose {}
my-coll)
NOTE: the \"degenerate\" case of only two colls, is simply mutual
information.
Let C be (combinator coll1 coll2 .. colln), so xi1..xin in C is an
element in the joint sample space, and xi in colli is an element in
a \"marginal\" space . Computes
sum (* px1..xn (log2 (/ px1..xn (* px1 px2 .. pxn)))) x1s x2s .. xns =
Hx1 + Hx2 + .. + Hxn - Hx1x2..xn
(<= 0.0
TC(X1,..,Xn)
(min|i (sum Hx1 .. Hxi Hxi+2 .. Hxn, i = 0..n-1, Hx0=Hxn+1=0)))
Ex:
(shannon-entropy \"AAAUUUGGGGCCCUUUAAA\")
=> 1.9440097497163569
(total-correlation transpose {}
\"AAAUUUGGGGCCCUUUAAA\" \"AAAUUUGGGGCCCUUUAAA\")
=> 1.9440097497163569 ; not surprising
(total-correlation transpose {}
\"AAAUUUGGGGCCCUUUAAA\" \"AAAUUUGGGGCCCUUUAAA\"
\"AAAUUUGGGGCCCUUUAAA\" \"AAAUUUGGGGCCCUUUAAA\")
=> 5.832029249149071 ; possibly surprising if not noting tripled redundancy
"
([combinator opts coll1 coll2]
(mutual-information combinator opts coll1 coll2))
([combinator opts coll1 coll2 & colls]
(let [{:keys [sym? logfn] :or {sym? false logfn log2}} opts
colls (cons coll1 (cons coll2 colls))
Hxs (map #(shannon-entropy % :logfn logfn) colls)
HX1-Xn (apply joint-entropy combinator opts coll1 coll2 colls)
TC (- (sum Hxs) HX1-Xn)]
(cond
(>= TC 0.0) TC
(< (math/abs TC) 1.0E-10) 0.0
:else
(raise
:type :negTC
:TC TC :Hxs Hxs :HX1-XN HX1-Xn)))))
(defn TCI
"Synonym for total-correlation information"
[combinator opts coll1 coll2 & colls]
(apply total-correlation combinator opts coll1 coll2 colls))
(defn interaction-information
"One of two forms of multivariate mutual information provided here.
The other is \"total correlation\". Interaction information
computes the amount of information bound up in a set of variables,
beyond that present in _any subset_ of those variables. Well, that
seems to be the most widely held view, but there are disputes. This
can either indicate inhibition/redundancy or facilitation/synergy
between the variables. It helps to look at the 3 variable case, as
it at least lends itself to 'information' (or info venn) diagrams.
II(X,Y,Z) = I(X,Y|Z) - I(X,Y)
II measures the influence of Z on the information connection
between X and Y. Since I(X,Y|Z) < I(X,Y) is possible, II can be
negative, as well as 0 and positive. For example if Z completely
determines the information content between X & Y, then I(X,Y|Z) -
I(X,Y) would be 0 (as overlap contributed by X & Y alone is totally
redundant), while for X & Y independent of Z, I(X,Y) could still be
> 0. A _negative_ interaction indicates Z inhibits (accounts for,
causes to be irrelevant/redundant) the connection between X & Y. A
_positive_ interaction indicates Z promotes, is synergistic with,
or enhances the connection. The case of 0 is obvious...
If we use the typical info theory venn diagrams, then II is
represented as the area in all the circles. It is possible (and
typically so done) to draw the Hxi (xi in {X,Y,Z}) circles so that
all 3 have an overlap. In this case the information between any
two (the mutual information...) is partially accounted for by the
third. The extra overlap accounts for the negative value
\"correction\" of II in this case.
However, it is also possible to draw the circles so that any two
overlap but all three have null intersect. In this case, the third
variable provides an extra connection between the other two (beyond
their MI), something like a \"mediator\". This extra connection
accounts for the positive value \"facillitation\" of II in this
case.
It should be reasonably clear at this point that negative II is the
much more intuitive/typical case, and that positive cases are
surprising and typically more interesting and informative (so to
speak...). A positive example, would be the case of two mutually
exclusive causes for a common effect (third variable). In such a
case, knowing any two completely determines the other.
All of this can be bumped up to N variables via typical chain rule
recurrance.
In this implementation, the information content \"measure\" is
based on the distributions arising out of the frequencies over
coll1 .. colln _individually_, and jointly over the result of
combinator applied collectively to all subsets of coll1 .. colln.
OPTS is a map of options, currently sym? and logfn. The defaults
are false and log2. If sym? is true, treat [x y] and [y x] as
equal. logfn can be used to provide a log of a different base.
log2, the default, reports in bits. If no options are required,
the empty map must be passed: (interaction-information transpose {}
my-coll)
For collections coll1..colln and variadic combinator over any
subset of collections, Computes:
(sum (fn[ss] (* (expt -1 (- n |ss|))
(HXY combinator sym? ss)))
(subsets all-colls))
|ss| = cardinality/count of subset ss. ss is a subset of
coll1..colln. If sym? is true, treat reversable combined items as
equal (see HYX/joint-entropy).
For n=3, this reduces to (- (IXY|Z combinator sym? collx colly collz)
(IXY combinator sym? collx colly))
Ex:
(interaction-information transpose {}
\"AAAGGGUUUUAAUAUUAAAAUUU\"
\"AAAGGGUGGGAAUAUUCCCAUUU\"
\"AAAGGGUGGGAAUAUUCCCAUUU\")
=> -1.1673250256261127
Ex:
(interaction-information transpose {}
\"AAAGGGUUUUAAUAUUAAAAUUU\"
\"AAAGGGUGGGAAUAUUCCCAUUU\"
(reverse-compliment \"AAAGGGUGGGAAUAUUCCCAUUU\"))
=> -0.282614135781623
Ex: Shows synergy (positive value)
(let [X1 [0 1] ; 7 independent binary vars
X2 [0 1]
X3 [0 1]
X4 [0 1]
X5 [0 1]
X6 [0 1]
X7 [0 1]
X8 [0 1]
Y1 [X1 X2 X3 X4 X5 X6 X7]
Y2 [X4 X5 X6 X7]
Y3 [X5 X6 X7]
Y4 [X7]
bitval #(loop [bits (reverse %) n 0 v 0]
(if (empty? bits)
v
(recur (rest bits)
(inc n)
(+ v (* (first bits) (math/expt 2 n))))))
rfn #(map bitval (apply reducem (fn[& args] [args]) concat %))
;; Turn to (partially redundant) value sets - each Yi is the set
;; of all numbers for all (count Yi) bit patterns. So, Y1, Y2,
;; and Y3 share all values of 3 bits, while the group with Y4
;; added shares just all 1 bit patterns
Y1 (rfn Y1)
Y2 (rfn Y2)
Y3 (rfn Y3)
Y4 (rfn Y4)]
[(interaction-information concat {} Y1 Y2 Y3)
(interaction-information concat {} Y1 Y2 Y3 Y4)])
=> [-3.056592722891465 ; Intuitive, since 3 way sharing
1.0803297840536592] ; Unintuitive, since 1 way sharing induces synergy!?
"
#_([combinator opts collx colly collz]
(let [Ixy|z (IXY|Z combinator opts collx colly collz)
Ixy (IXY combinator opts collx colly)]
(- Ixy|z Ixy)))
([combinator opts collx colly collz & colls]
(let [colls (->> colls (cons collz) (cons colly) (cons collx))
ssets (remove empty? (subsets colls))
tcnt (count colls)]
(- (sum (fn[ss]
(let [sscnt (count ss)]
(* (math/expt -1.0 (- tcnt sscnt))
(apply joint-entropy combinator opts ss))))
ssets)))))
(defn II
"Synonym for interaction-information"
[combinator opts collx colly collz & colls]
(apply interaction-information combinator opts collx colly collz colls))
(defn lambda-divergence
"Computes a symmetrized KLD variant based on a probability
parameter, typically notated lambda, in [0..1] for each
distribution:
(+ (* lambda (DX||Y Pdist M)) (* (- 1 lambda) (DX||Y Qdist M)))
Where M = (+ (* lambda Pdist) (* (- 1 lambda) Qdist))
= (merge-with (fn[pi qi] (+ (* lambda pi) (* (- 1 lambda) qi)))
Pdist Qdist)
For lambda = 1/2, this reduces to
M = 1/2 (merge-with (fn[pi qi] (+ pi qi)) P Q)
and (/ (+ (DX||Y Pdist M) (DX||Y Qdist M)) 2) = jensen shannon
"
[lambda Pdist Qdist]
(let [Omega (set/union (set (keys Pdist)) (set (keys Qdist)))
M (reduce (fn[M k]
(assoc M k (+ (* lambda (get Pdist k 0.0))
(* (- 1 lambda) (get Qdist k 0.0)))))
{}
Omega)]
(+ (* lambda (DX||Y Pdist M)) (* (- 1 lambda) (DX||Y Qdist M)))))
(defn DLX||Y
"Synonym for lambda divergence"
[l Pdist Qdist]
(lambda-divergence l Pdist Qdist))
(defn jensen-shannon
"Computes Jensen-Shannon Divergence of the two distributions Pdist
and Qdist. Pdist and Qdist _must_ be over the same sample space!"
[Pdist Qdist]
#_(let [Omega (set/union (set (keys Pdist)) (set (keys Qdist)))
M (reduce (fn[M k]
(assoc M k (/ (+ (get Pdist k 0.0)
(get Qdist k 0.0))
2.0)))
{}
Omega)]
(/ (+ (DX||Y Pdist M) (DX||Y Qdist M)) 2.0))
(lambda-divergence 0.5 Pdist Qdist))
(defn log-odds [frq1 frq2]
(log2 (/ frq1 frq2)))
(defn lod-score [qij pi pj]
(log2 (/ qij (* pi pj))))
(defn raw-lod-score [qij pi pj & {scaling :scaling :or {scaling 1.0}}]
(if (= scaling 1.0)
(lod-score qij pi pj)
(int (/ (lod-score qij pi pj) scaling))))
;;; ----------------------------------------------------------------------
;;;
;;; Fixed cost Edit distance.
;;;
;;; (levenshtein "this" "")
;;; (assert (= 0 (levenshtein "" "")))
;;; (assert (= 3 (levenshtein "foo" "foobar")))
;;; (assert (= 3 (levenshtein "kitten" "sitting")))
;;; (assert (= 3 (levenshtein "Saturday" "Sunday")))
;;; (assert (= 22 (levenshtein
;;; "TATATTTGGAGTTATACTATGTCTCTAAGCACTGAAGCAAA"
;;; "TATATATTTTGGAGATGCACAT"))
;;;
(defn- new-row [prev-row row-elem t]
(reduce
(fn [row [d-1 d e]]
(conj row (if (= row-elem e) d-1 (inc (min (peek row) d d-1)))))
[(inc (first prev-row))]
(map vector prev-row (next prev-row) t)))
(defn levenshtein
"Compute the Levenshtein (edit) distance between S and T, where S
and T are either sequences or strings.
Examples: (levenshtein [1 2 3 4] [1 1 3]) ==> 2
(levenshtein \"abcde\" \"bcdea\") ==> 2
"
[s t]
(cond
(or (= s t "") (and (empty? s) (empty? t))) 0
(= 0 (count s)) (count t)
(= 0 (count t)) (count s)
:else
(peek (reduce
(fn [prev-row s-elem] (new-row prev-row s-elem t))
(range (inc (count t)))
s))))
(defn- hamming-stgs [s1 s2]
(let [sz1 (long (count s1))
len (long (min sz1 (long (count s2))))]
(loop [i (long 0)
cnt (long (Math/abs (- len sz1)))]
(if (= i len)
cnt
(if (= (austr/get s1 i) (austr/get s2 i))
(recur (inc i) cnt)
(recur (inc i) (inc cnt)))))))
(defn hamming
"Compute hamming distance between sequences S1 and S2. If both s1
and s2 are strings, performs an optimized version"
[s1 s2]
(if (and (string? s1) (string? s2))
(hamming-stgs s1 s2)
(reduce + (map (fn [b1 b2] (if (= b1 b2) 0 1)) s1 s2))))
(defn diff-fn
"Return the function that is 1-F applied to its args: (1-(apply f
args)). Intended for normalized distance metrics.
Ex: (let [dice-diff (diff-fn dice-coeff) ...]
(dice-diff some-set1 some-set2))
"
[f]
(fn [& args] (- 1 (apply f args))))
(defn dice-coeff [s1 s2]
(/ (* 2 (count (set/intersection s1 s2)))
(+ (count s1) (count s2))))
(defn jaccard-index [s1 s2]
(/ (count (set/intersection s1 s2))
(count (set/union s1 s2))))
(defn tversky-index
"Tversky index of two sets S1 and S2. A generalized NON metric
similarity 'measure'. Generalization is through the ALPHA and BETA
coefficients:
TI(S1,S2) = (/ |S1^S2| (+ |S1^S2| (* ALPHA |S1-S2|) (* BETA |S2-S1|)))
For example, with alpha=beta=1, TI is jaccard-index
with alpha=beta=1/2 TI is dice-coeff
"
[s1 s2 alpha beta]
(let [s1&s2 (count (set/intersection s1 s2))
s1-s2 (count (set/difference s1 s2))
s2-s1 (count (set/difference s2 s1))]
(/ s1&s2
(+ s1&s2 (* alpha s1-s2) (* beta s2-s1)))))
(def
^{:doc
"Named version of (diff-fn jaccard-index s1 s2). This difference
function is a similarity that is a proper _distance_ metric (hence
usable in metric trees like bk-trees)."
:arglists '([s1 s2])}
jaccard-dist
(diff-fn jaccard-index))
(defn freq-jaccard-index
""
[s1 s2]
(let [freq-s1 (set s1)
freq-s2 (set s2)
c1 (sum (set/intersection freq-s1 freq-s2))
c2 (sum (set/union freq-s1 freq-s2))]
(/ c1 c2)))
(defn bi-tri-grams [s]
(let [bi-grams (set (keys (freqn 2 s)))
tri-grams (set (keys (freqn 3 s)))]
[(set/union bi-grams tri-grams)
[bi-grams tri-grams]]))
(defn all-grams [s]
(let [all-gram-sets
(for [n (range 1 (count s))]
(-> (freqn n s) keys set))]
[(apply set/union all-gram-sets) all-gram-sets]))
(defn ngram-compare
""
[s1 s2 & {uc? :uc? n :n scfn :scfn ngfn :ngfn
:or {n 2 uc? false scfn dice-coeff ngfn word-letter-pairs}}]
(let [s1 (ngfn n (if uc? (str/upper-case s1) s1))
s2 (ngfn n (if uc? (str/upper-case s2) s2))]
(scfn s1 s2)))
;;;(float (ngram-compare "FRANCE" "french"))
;;;(float (ngram-compare "FRANCE" "REPUBLIC OF FRANCE"))
;;;(float (ngram-compare "FRENCH REPUBLIC" "republic of france"))
;;;(float (ngram-compare
;;; "TATATTTGGAGTTATACTATGTCTCTAAGCACTGAAGCAAA"
;;; "TATATATTTTGGAGATGCACAT"))
(defn normed-codepoints [s]
(vec (map #(let [nc (- % 97)]
(cond
(>= nc 0) nc
(= % 32) 27
:else 28))
(codepoints s))))
(defn ngram-vec [s & {n :n :or {n 2}}]
(let [ngrams (word-letter-pairs s n)
ngram-points (map (fn [[x y]]
(int (+ (* x 27) y)))
(map normed-codepoints ngrams))
v (int-array 784 0)]
(doseq [i ngram-points]
(aset v i 1))
v))
;;;-------------------------------------------------------------------------;;;
;;; ;;;
;;; Minimization and Maximization of Entropy Principles ;;;
;;; ;;;
;;; Cumulative Relative Entropy, Centroid Frequency and Probability ;;;
;;; dictionaries, information capacity, et.al. ;;;
;;; ;;;
;;;-------------------------------------------------------------------------;;;
(defn expected-qdict [q-1 q-2 & {:keys [alpha] :or {alpha ["A" "U" "G" "C"]}}]
(reduce (fn[m lmer]
(let [l (dec (count lmer))
x (subs lmer 1)
y (subs lmer 0 l)
z (subs lmer 1 l)]
(if (and (q-1 x) (q-1 y) (q-2 z))
(assoc m lmer (/ (* (q-1 x) (q-1 y)) (q-2 z)))
m)))
{} (for [x (keys q-1) a alpha] (str x a))))
(defn freq-xdict-dict
[q sq]
(let [ext-sq (str sq "X")
residue-key (subs ext-sq (- (count sq) (- q 1)))
q-xfreq-dict (freqn q ext-sq)
q-freq-dict (dissoc q-xfreq-dict residue-key)]
[q-xfreq-dict q-freq-dict]))
(defn q-1-dict
([q-xdict]
(reduce (fn[m [k v]]
(let [l (count k)
pre (subs k 0 (dec l))]
(assoc m pre (+ (get m pre 0) v))))
{} q-xdict))
([q sq]
(probs (dec q) sq)))
(defn q1-xdict-dict
[q sq & {:keys [ffn] :or {ffn probs}}]
(let [[q-xfreq-dict q-freq-dict] (freq-xdict-dict q sq)
q-xpdf-dict (probs q-xfreq-dict)
q-pdf-dict (probs q-freq-dict)]
{:xfreq q-xfreq-dict :xpdf q-xpdf-dict
:freq q-freq-dict :pdf q-pdf-dict}))
(defn reconstruct-dict
[l sq & {:keys [alpha] :or {alpha ["A" "U" "G" "C"]}}]
{:pre [(> l 2)]}
(let [q (dec l)
qmaps (q1-xdict-dict q sq)
[q-xdict q-dict] (map qmaps [:xpdf :pdf])
q-1dict (q-1-dict q-xdict)]
(expected-qdict q-dict q-1dict :alpha alpha)))
(defn max-qdict-entropy
[q & {:keys [alpha] :or {alpha ["A" "U" "G" "C"]}}]
(let [base (count alpha)]
(* q (log2 base))))
(defn informativity
([q sq]
(- (max-qdict-entropy q) (entropy (probs q sq))))
([q-dict]
(let [q (count (first (keys q-dict)))]
(- (max-qdict-entropy q) (entropy q-dict)))))
(defn limit-entropy
[q|q-dict sq|q-1dict &
{:keys [alpha NA] :or {alpha ["A" "U" "G" "C"] NA -1.0}}]
{:pre [(or (and (integer? q|q-dict)
(or (string? sq|q-1dict) (coll? sq|q-1dict)))
(and (map? q|q-dict) (map? sq|q-1dict)))]}
(if (map? q|q-dict)
(let [q-dict q|q-dict
q-1dict sq|q-1dict]
(/ (- (entropy q-dict) (entropy q-1dict))
(log2 (count alpha))))
(let [q q|q-dict
sq sq|q-1dict
lgcnt (log2 (count alpha))]
(if (= q 1)
(/ (entropy (probs 1 sq)) lgcnt)
(let [qmaps (q1-xdict-dict q sq)
[q-xdict q-dict] (map qmaps [:xpdf :pdf])
q-1dict (q-1-dict q-xdict)]
(if (< (count q-dict) (count q-1dict))
(if (fn? NA) (NA q-dict q-1dict) NA)
(/ (- (entropy q-dict) (entropy q-1dict)) lgcnt)))))))
(defn limit-informativity
([q sq]
)
([q-dict]
))
(defn CREl
[l sq & {:keys [limit alpha]
:or {limit 15}}]
{:pre [(> l 2) alpha]}
(sum (fn[k]
(catch-all (DX||Y
(probs k sq)
(reconstruct-dict k sq :alpha alpha))))
(range l (inc limit))))
(defn information-capacity
[q sq & {:keys [cmpfn] :or {cmpfn jensen-shannon}}]
(catch-all (cmpfn (probs q sq)
(reconstruct-dict q sq))))
(defn hybrid-dictionary
"Compute the 'hybrid', aka centroid, dictionary or Feature Frequency
Profile (FFP) for sqs. SQS is either a collection of already
computed FFPs (probability maps) of sequences, or a collection of
sequences, or a string denoting a sequence file (sto, fasta, aln,
...) giving a collection of sequences. In the latter cases, the
sequences will have their FFPs computed based on word/feature
length L (resolution size). In all cases the FFPs are combined,
using the minimum entropy principle, into a joint ('hybrid' /
centroid) FFP.
"
[l sqs]
{:pre [(or (string? sqs) (coll? sqs))]}
(let [sqs (if (-> sqs first map?)
sqs
(if (coll? sqs) sqs (raise :type :old-read-seqs :sqs sqs)))
cnt (count sqs)
par (max (math/floor (/ cnt 10)) 2)
dicts (if (-> sqs first map?) sqs (vfold #(probs l %) sqs))
hybrid (apply merge-with +
(vfold (fn[subset] (apply merge-with + subset))
(partition-all (/ (count dicts) par) dicts)))]
(reduce (fn[m [k v]] (assoc m k (double (/ v cnt))))
{} hybrid)))
|
[
{
"context": ";; Author: @Sid220\n(defn is-small? [number]\n (if (== number 1) (pri",
"end": 18,
"score": 0.9995507001876831,
"start": 11,
"tag": "USERNAME",
"value": "@Sid220"
},
{
"context": "efn is-small? [number]\n (if (== number 1) (print\"Joe Mama\") (print\"Joe Biden\")))\n(is-small? (rand-int 2))\n",
"end": 79,
"score": 0.9998717308044434,
"start": 71,
"tag": "NAME",
"value": "Joe Mama"
},
{
"context": "ber]\n (if (== number 1) (print\"Joe Mama\") (print\"Joe Biden\")))\n(is-small? (rand-int 2))\n",
"end": 98,
"score": 0.9998871684074402,
"start": 89,
"tag": "NAME",
"value": "Joe Biden"
}
] | clojure.clj | Sid220/joe-mama-or-joe-biden | 3 | ;; Author: @Sid220
(defn is-small? [number]
(if (== number 1) (print"Joe Mama") (print"Joe Biden")))
(is-small? (rand-int 2))
| 27619 | ;; Author: @Sid220
(defn is-small? [number]
(if (== number 1) (print"<NAME>") (print"<NAME>")))
(is-small? (rand-int 2))
| true | ;; Author: @Sid220
(defn is-small? [number]
(if (== number 1) (print"PI:NAME:<NAME>END_PI") (print"PI:NAME:<NAME>END_PI")))
(is-small? (rand-int 2))
|
[
{
"context": "mes (str \"Hello \" name)))))\n(greeting)\n(greeting \"Sue\")\n(greeting \"Sue\" 4)\n\n\n\n(macroexpand '(go (printl",
"end": 4275,
"score": 0.6091238260269165,
"start": 4272,
"tag": "NAME",
"value": "Sue"
},
{
"context": "name)))))\n(greeting)\n(greeting \"Sue\")\n(greeting \"Sue\" 4)\n\n\n\n(macroexpand '(go (println \"hey\")))\n\n\n\n\n\n;",
"end": 4292,
"score": 0.5974019169807434,
"start": 4290,
"tag": "NAME",
"value": "ue"
}
] | src/clj/clj_intro1.clj | chrisfjones/clj-intro | 2 | (use 'mikera.image.core)
(-> (load-image-resource "logo.png")
show
(.setAlwaysOnTop true))
;;;;;;;;;;;;;;;;;;;;
;; 1. Live coding ;;
;;;;;;;;;;;;;;;;;;;;
(* (+ 2 3) 3)
(+ 1 1 3 4)
;;;;;;;;;;;;;;;;;;;;;
;; 2. Java interop ;;
;;;;;;;;;;;;;;;;;;;;;
(System/currentTimeMillis)
(get (System/getProperties) "java.version")
(filter (fn [k] (.startsWith k "java")) (keys (System/getProperties)))
(new java.util.Date)
(org.apache.commons.math3.util.ArithmeticUtils/addAndCheck Long/MAX_VALUE 1)
;;;;;;;;;;;;;;;;;;;;;
;; 3. Data as Code ;;
;;;;;;;;;;;;;;;;;;;;;
; vector
[1 2 3 5]
; map
{:key1 "foo" :key2 "bar"}
; set
#{:a :b :c}
; seq
'(1 2 3)
;;;;;;;;;;;;;;;;;;;;;
;; 4. Code as Data ;;
;;;;;;;;;;;;;;;;;;;;;
(fn [x] (* x x))
((fn [x] (* x x)) 4)
(def sqr (fn [x] (* x x)))
(defn sqr [x] (* x x))
(sqr 5)
((identity sqr) 2)
; eval
'(+ 1 1)
(eval '(+ 1 1))
(read-string "(+ 1 1)")
(eval (read-string "(+ 1 1)"))
; macros
; (+ 1 1) -> (1 1 +)
(defmacro postfix-notation [expression]
(conj (butlast expression) (last expression)))
(macroexpand '(postfix-notation (1 2 +)))
(postfix-notation
(1 2 +))
(macroexpand
'(with-open [in-stream (clojure.java.io/input-stream "resources/textfile.txt")]
(.available in-stream)))
(with-open [in-stream (clojure.java.io/input-stream "resources/textfile.txt")]
(.available in-stream))
(if (= 1 2)
:blue
:red)
(loop [n 11]
(when (not (= 0 n))
(println "hey")
(Thread/sleep 200)
(recur (dec n))))
(dotimes [n 10] (println "hey"))
;;;;;;;;;;;;;;;;;;;;;
;; 5. Immutability ;;
;;;;;;;;;;;;;;;;;;;;;
(def list-a [1 2 3])
list-a
(def list-b (conj list-a 4))
list-a
list-b
(def list-c (vec (rest list-b)))
list-a
list-b
list-c
; immutable efficiency
(-> (load-image-resource "lists.png")
show
(.setAlwaysOnTop true))
;;;;;;;;;;;;;;;;;;;;
;; 6. atoms (cas) ;;
;;;;;;;;;;;;;;;;;;;;
(def list-atom (atom [1 2 3 4 5 6]))
list-atom
@list-atom
(swap! list-atom rest)
@list-atom
(def my-snapshot @list-atom)
my-snapshot
(-> (load-image-resource "epochal-time-model.png")
show
(.setAlwaysOnTop true))
; refs (stm)
(def my-account (ref 100))
(def your-account (ref 100))
@my-account
@your-account
(dosync
(let [amt 50]
(alter your-account - amt)
(alter my-account + amt)
amt))
@my-account
@your-account
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 7. high-order functions ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def coll (range 10))
coll
(filter even? coll)
(defn doublify [x] (* 2 x))
(map doublify coll)
(reduce + (range 10))
(group-by
count
["a" "as" "asd" "aa" "asdf" "qwer"])
;;;;;;;;;;;;;;;;;;;;;;;;;
;; 8. threading macros ;;
;;;;;;;;;;;;;;;;;;;;;;;;;
; thread first
(-> {}
(assoc :foo "bar")
(assoc :fuz "baz")
keys
count)
; thread last
(->> (range 100)
(filter even?)
(map doublify)
(reduce +))
;;;;;;;;;;;;;;;;;;;;
;; 9. concurrency ;;
;;;;;;;;;;;;;;;;;;;;
(defn stupid-doublify [x]
(Thread/sleep 100)
(* 2 x))
(map stupid-doublify (range 50))
; pmap
(pmap stupid-doublify (range 50))
; future
(def thing (atom nil))
(future
(Thread/sleep 5000)
(reset! thing :foo))
@thing
; promise
(def promise-thing (promise))
(future
(Thread/sleep 5000)
(deliver promise-thing :bar))
@promise-thing
;;;;;;;;;;;;;;;;;;;;
;; 10. core.async ;;
;;;;;;;;;;;;;;;;;;;;
(require ['clojure.core.async :as 'async
:refer '[go go-loop chan close! timeout alts! put! <! <!! >! >!!]])
(<!!
(go
(<! (timeout 2000))
(+ 1 1)))
; channel
(def channel (chan 10))
(go-loop
[n 10]
(if (> n 0)
(do
(<! (timeout 2000))
(>! channel n)
(recur (dec n)))
(close! channel)))
(<!! channel)
(let [c1 (chan)
c2 (chan)]
(go (while true
(let [[v ch] (alts! [c1 c2])]
(println "Read" v "from" ch))))
(put! c1 "hi")
(put! c2 "there"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 10. just the good bits from OOP ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; multi-arity
(defn greeting
([] (greeting "Stranger" 1))
([name] (greeting name 1))
([name times]
(clojure.string/join ", " (repeat times (str "Hello " name)))))
(greeting)
(greeting "Sue")
(greeting "Sue" 4)
(macroexpand '(go (println "hey")))
; multi-method
(defmulti silly-math (fn [x]
(cond
(odd? x) :odd
(> x 10) :big
(even? x) :small-even)))
(defmethod silly-math :odd [x] (inc x))
(defmethod silly-math :big [x] (* x x))
(defmethod silly-math :small-even [x] (+ (* 2 x) 3))
(silly-math 8)
(silly-math 17)
(silly-math 22)
; protocols
(defprotocol Shape
(area [s])
(perimiter [s]))
(defrecord Rectangle [w h]
Shape
(area [this] (* w h))
(perimiter [this] (+ (* 2 w)
(* 2 h))))
(defrecord Circle [r]
Shape
(area [this] (* Math/PI r r))
(perimiter [this] (* 2 Math/PI r)))
(def rect1 (->Rectangle 10 12))
(def circ1 (->Circle 6))
(area rect1)
(perimiter rect1)
(area circ1)
(perimiter circ1)
(use 'clojure.string)
(extend java.lang.String
Shape
{:area (fn [this]
)})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 11. namespaces and general organization ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
| 61305 | (use 'mikera.image.core)
(-> (load-image-resource "logo.png")
show
(.setAlwaysOnTop true))
;;;;;;;;;;;;;;;;;;;;
;; 1. Live coding ;;
;;;;;;;;;;;;;;;;;;;;
(* (+ 2 3) 3)
(+ 1 1 3 4)
;;;;;;;;;;;;;;;;;;;;;
;; 2. Java interop ;;
;;;;;;;;;;;;;;;;;;;;;
(System/currentTimeMillis)
(get (System/getProperties) "java.version")
(filter (fn [k] (.startsWith k "java")) (keys (System/getProperties)))
(new java.util.Date)
(org.apache.commons.math3.util.ArithmeticUtils/addAndCheck Long/MAX_VALUE 1)
;;;;;;;;;;;;;;;;;;;;;
;; 3. Data as Code ;;
;;;;;;;;;;;;;;;;;;;;;
; vector
[1 2 3 5]
; map
{:key1 "foo" :key2 "bar"}
; set
#{:a :b :c}
; seq
'(1 2 3)
;;;;;;;;;;;;;;;;;;;;;
;; 4. Code as Data ;;
;;;;;;;;;;;;;;;;;;;;;
(fn [x] (* x x))
((fn [x] (* x x)) 4)
(def sqr (fn [x] (* x x)))
(defn sqr [x] (* x x))
(sqr 5)
((identity sqr) 2)
; eval
'(+ 1 1)
(eval '(+ 1 1))
(read-string "(+ 1 1)")
(eval (read-string "(+ 1 1)"))
; macros
; (+ 1 1) -> (1 1 +)
(defmacro postfix-notation [expression]
(conj (butlast expression) (last expression)))
(macroexpand '(postfix-notation (1 2 +)))
(postfix-notation
(1 2 +))
(macroexpand
'(with-open [in-stream (clojure.java.io/input-stream "resources/textfile.txt")]
(.available in-stream)))
(with-open [in-stream (clojure.java.io/input-stream "resources/textfile.txt")]
(.available in-stream))
(if (= 1 2)
:blue
:red)
(loop [n 11]
(when (not (= 0 n))
(println "hey")
(Thread/sleep 200)
(recur (dec n))))
(dotimes [n 10] (println "hey"))
;;;;;;;;;;;;;;;;;;;;;
;; 5. Immutability ;;
;;;;;;;;;;;;;;;;;;;;;
(def list-a [1 2 3])
list-a
(def list-b (conj list-a 4))
list-a
list-b
(def list-c (vec (rest list-b)))
list-a
list-b
list-c
; immutable efficiency
(-> (load-image-resource "lists.png")
show
(.setAlwaysOnTop true))
;;;;;;;;;;;;;;;;;;;;
;; 6. atoms (cas) ;;
;;;;;;;;;;;;;;;;;;;;
(def list-atom (atom [1 2 3 4 5 6]))
list-atom
@list-atom
(swap! list-atom rest)
@list-atom
(def my-snapshot @list-atom)
my-snapshot
(-> (load-image-resource "epochal-time-model.png")
show
(.setAlwaysOnTop true))
; refs (stm)
(def my-account (ref 100))
(def your-account (ref 100))
@my-account
@your-account
(dosync
(let [amt 50]
(alter your-account - amt)
(alter my-account + amt)
amt))
@my-account
@your-account
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 7. high-order functions ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def coll (range 10))
coll
(filter even? coll)
(defn doublify [x] (* 2 x))
(map doublify coll)
(reduce + (range 10))
(group-by
count
["a" "as" "asd" "aa" "asdf" "qwer"])
;;;;;;;;;;;;;;;;;;;;;;;;;
;; 8. threading macros ;;
;;;;;;;;;;;;;;;;;;;;;;;;;
; thread first
(-> {}
(assoc :foo "bar")
(assoc :fuz "baz")
keys
count)
; thread last
(->> (range 100)
(filter even?)
(map doublify)
(reduce +))
;;;;;;;;;;;;;;;;;;;;
;; 9. concurrency ;;
;;;;;;;;;;;;;;;;;;;;
(defn stupid-doublify [x]
(Thread/sleep 100)
(* 2 x))
(map stupid-doublify (range 50))
; pmap
(pmap stupid-doublify (range 50))
; future
(def thing (atom nil))
(future
(Thread/sleep 5000)
(reset! thing :foo))
@thing
; promise
(def promise-thing (promise))
(future
(Thread/sleep 5000)
(deliver promise-thing :bar))
@promise-thing
;;;;;;;;;;;;;;;;;;;;
;; 10. core.async ;;
;;;;;;;;;;;;;;;;;;;;
(require ['clojure.core.async :as 'async
:refer '[go go-loop chan close! timeout alts! put! <! <!! >! >!!]])
(<!!
(go
(<! (timeout 2000))
(+ 1 1)))
; channel
(def channel (chan 10))
(go-loop
[n 10]
(if (> n 0)
(do
(<! (timeout 2000))
(>! channel n)
(recur (dec n)))
(close! channel)))
(<!! channel)
(let [c1 (chan)
c2 (chan)]
(go (while true
(let [[v ch] (alts! [c1 c2])]
(println "Read" v "from" ch))))
(put! c1 "hi")
(put! c2 "there"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 10. just the good bits from OOP ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; multi-arity
(defn greeting
([] (greeting "Stranger" 1))
([name] (greeting name 1))
([name times]
(clojure.string/join ", " (repeat times (str "Hello " name)))))
(greeting)
(greeting "<NAME>")
(greeting "S<NAME>" 4)
(macroexpand '(go (println "hey")))
; multi-method
(defmulti silly-math (fn [x]
(cond
(odd? x) :odd
(> x 10) :big
(even? x) :small-even)))
(defmethod silly-math :odd [x] (inc x))
(defmethod silly-math :big [x] (* x x))
(defmethod silly-math :small-even [x] (+ (* 2 x) 3))
(silly-math 8)
(silly-math 17)
(silly-math 22)
; protocols
(defprotocol Shape
(area [s])
(perimiter [s]))
(defrecord Rectangle [w h]
Shape
(area [this] (* w h))
(perimiter [this] (+ (* 2 w)
(* 2 h))))
(defrecord Circle [r]
Shape
(area [this] (* Math/PI r r))
(perimiter [this] (* 2 Math/PI r)))
(def rect1 (->Rectangle 10 12))
(def circ1 (->Circle 6))
(area rect1)
(perimiter rect1)
(area circ1)
(perimiter circ1)
(use 'clojure.string)
(extend java.lang.String
Shape
{:area (fn [this]
)})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 11. namespaces and general organization ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
| true | (use 'mikera.image.core)
(-> (load-image-resource "logo.png")
show
(.setAlwaysOnTop true))
;;;;;;;;;;;;;;;;;;;;
;; 1. Live coding ;;
;;;;;;;;;;;;;;;;;;;;
(* (+ 2 3) 3)
(+ 1 1 3 4)
;;;;;;;;;;;;;;;;;;;;;
;; 2. Java interop ;;
;;;;;;;;;;;;;;;;;;;;;
(System/currentTimeMillis)
(get (System/getProperties) "java.version")
(filter (fn [k] (.startsWith k "java")) (keys (System/getProperties)))
(new java.util.Date)
(org.apache.commons.math3.util.ArithmeticUtils/addAndCheck Long/MAX_VALUE 1)
;;;;;;;;;;;;;;;;;;;;;
;; 3. Data as Code ;;
;;;;;;;;;;;;;;;;;;;;;
; vector
[1 2 3 5]
; map
{:key1 "foo" :key2 "bar"}
; set
#{:a :b :c}
; seq
'(1 2 3)
;;;;;;;;;;;;;;;;;;;;;
;; 4. Code as Data ;;
;;;;;;;;;;;;;;;;;;;;;
(fn [x] (* x x))
((fn [x] (* x x)) 4)
(def sqr (fn [x] (* x x)))
(defn sqr [x] (* x x))
(sqr 5)
((identity sqr) 2)
; eval
'(+ 1 1)
(eval '(+ 1 1))
(read-string "(+ 1 1)")
(eval (read-string "(+ 1 1)"))
; macros
; (+ 1 1) -> (1 1 +)
(defmacro postfix-notation [expression]
(conj (butlast expression) (last expression)))
(macroexpand '(postfix-notation (1 2 +)))
(postfix-notation
(1 2 +))
(macroexpand
'(with-open [in-stream (clojure.java.io/input-stream "resources/textfile.txt")]
(.available in-stream)))
(with-open [in-stream (clojure.java.io/input-stream "resources/textfile.txt")]
(.available in-stream))
(if (= 1 2)
:blue
:red)
(loop [n 11]
(when (not (= 0 n))
(println "hey")
(Thread/sleep 200)
(recur (dec n))))
(dotimes [n 10] (println "hey"))
;;;;;;;;;;;;;;;;;;;;;
;; 5. Immutability ;;
;;;;;;;;;;;;;;;;;;;;;
(def list-a [1 2 3])
list-a
(def list-b (conj list-a 4))
list-a
list-b
(def list-c (vec (rest list-b)))
list-a
list-b
list-c
; immutable efficiency
(-> (load-image-resource "lists.png")
show
(.setAlwaysOnTop true))
;;;;;;;;;;;;;;;;;;;;
;; 6. atoms (cas) ;;
;;;;;;;;;;;;;;;;;;;;
(def list-atom (atom [1 2 3 4 5 6]))
list-atom
@list-atom
(swap! list-atom rest)
@list-atom
(def my-snapshot @list-atom)
my-snapshot
(-> (load-image-resource "epochal-time-model.png")
show
(.setAlwaysOnTop true))
; refs (stm)
(def my-account (ref 100))
(def your-account (ref 100))
@my-account
@your-account
(dosync
(let [amt 50]
(alter your-account - amt)
(alter my-account + amt)
amt))
@my-account
@your-account
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 7. high-order functions ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def coll (range 10))
coll
(filter even? coll)
(defn doublify [x] (* 2 x))
(map doublify coll)
(reduce + (range 10))
(group-by
count
["a" "as" "asd" "aa" "asdf" "qwer"])
;;;;;;;;;;;;;;;;;;;;;;;;;
;; 8. threading macros ;;
;;;;;;;;;;;;;;;;;;;;;;;;;
; thread first
(-> {}
(assoc :foo "bar")
(assoc :fuz "baz")
keys
count)
; thread last
(->> (range 100)
(filter even?)
(map doublify)
(reduce +))
;;;;;;;;;;;;;;;;;;;;
;; 9. concurrency ;;
;;;;;;;;;;;;;;;;;;;;
(defn stupid-doublify [x]
(Thread/sleep 100)
(* 2 x))
(map stupid-doublify (range 50))
; pmap
(pmap stupid-doublify (range 50))
; future
(def thing (atom nil))
(future
(Thread/sleep 5000)
(reset! thing :foo))
@thing
; promise
(def promise-thing (promise))
(future
(Thread/sleep 5000)
(deliver promise-thing :bar))
@promise-thing
;;;;;;;;;;;;;;;;;;;;
;; 10. core.async ;;
;;;;;;;;;;;;;;;;;;;;
(require ['clojure.core.async :as 'async
:refer '[go go-loop chan close! timeout alts! put! <! <!! >! >!!]])
(<!!
(go
(<! (timeout 2000))
(+ 1 1)))
; channel
(def channel (chan 10))
(go-loop
[n 10]
(if (> n 0)
(do
(<! (timeout 2000))
(>! channel n)
(recur (dec n)))
(close! channel)))
(<!! channel)
(let [c1 (chan)
c2 (chan)]
(go (while true
(let [[v ch] (alts! [c1 c2])]
(println "Read" v "from" ch))))
(put! c1 "hi")
(put! c2 "there"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 10. just the good bits from OOP ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; multi-arity
(defn greeting
([] (greeting "Stranger" 1))
([name] (greeting name 1))
([name times]
(clojure.string/join ", " (repeat times (str "Hello " name)))))
(greeting)
(greeting "PI:NAME:<NAME>END_PI")
(greeting "SPI:NAME:<NAME>END_PI" 4)
(macroexpand '(go (println "hey")))
; multi-method
(defmulti silly-math (fn [x]
(cond
(odd? x) :odd
(> x 10) :big
(even? x) :small-even)))
(defmethod silly-math :odd [x] (inc x))
(defmethod silly-math :big [x] (* x x))
(defmethod silly-math :small-even [x] (+ (* 2 x) 3))
(silly-math 8)
(silly-math 17)
(silly-math 22)
; protocols
(defprotocol Shape
(area [s])
(perimiter [s]))
(defrecord Rectangle [w h]
Shape
(area [this] (* w h))
(perimiter [this] (+ (* 2 w)
(* 2 h))))
(defrecord Circle [r]
Shape
(area [this] (* Math/PI r r))
(perimiter [this] (* 2 Math/PI r)))
(def rect1 (->Rectangle 10 12))
(def circ1 (->Circle 6))
(area rect1)
(perimiter rect1)
(area circ1)
(perimiter circ1)
(use 'clojure.string)
(extend java.lang.String
Shape
{:area (fn [this]
)})
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; 11. namespaces and general organization ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
[
{
"context": "t-Based Inference\n;;; =============\n;;; Written by Jonathan P. Bona\n;;; Ported to Clojure by Daniel R. Schlegel\n;;; ",
"end": 82,
"score": 0.9998895525932312,
"start": 66,
"tag": "NAME",
"value": "Jonathan P. Bona"
},
{
"context": "itten by Jonathan P. Bona\n;;; Ported to Clojure by Daniel R. Schlegel\n;;; \n;;; The contents of this file are subject",
"end": 126,
"score": 0.9998854994773865,
"start": 108,
"tag": "NAME",
"value": "Daniel R. Schlegel"
}
] | src/clj/zinc/snip_slot_based.clj | martinodb/Zinc | 0 | ;;; CSNePS: Slot-Based Inference
;;; =============
;;; Written by Jonathan P. Bona
;;; Ported to Clojure by Daniel R. Schlegel
;;;
;;; The contents of this file are subject to the University at Buffalo
;;; Public 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 at http://www.cse.buffalo.edu/sneps/Downloads/ubpl.pdf.
;;;
;;; Software distributed under the License is distributed on an "AS IS"
;;; basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
;;; the License for the specific language governing rights and limitations
;;; under the License.
;;;
;;; The Original Code is CSNePS.
;;;
;;; The Initial Developer of the Original Code is Research Foundation of
;;; State University of New York, on behalf of University at Buffalo.
;;;
;;; Portions created by the Initial Developer are Copyright (C) 2012
;;; Research Foundation of State University of New York, on behalf of
;;; University at Buffalo. All Rights Reserved.
;;;
;;; Contributor(s): ______________________________________.
(in-ns 'zinc.snip)
(declare covers valid-adjust)
(defmulti slot-based-entails
(fn [source target] [(syntactic-type-of source) (syntactic-type-of target)]))
;;; Slot-based entailment never applies to an atom and anything
(defmethod slot-based-entails [:zinc.core/Atom :zinc.core/Molecular] [source target])
(defmethod slot-based-entails [:zinc.core/Molecular :zinc.core/Atom] [source target])
(defmethod slot-based-entails [:zinc.core/Atom :zinc.core/Atom] [source target])
(defmethod slot-based-entails
[:zinc.core/Negation :zinc.core/Nand] [source target]
;; nor -> nand
;; (nor (and P Q) R) |= (nand P Q)
;; if any of the source's fillers is a conjunction X s.t.
;; X's fillers are a subset of the target's fillers,
;; then the source entails the target so return it.
(loop
[args (find-utils/findto source 'nor)]
(let [arg (first args)]
(cond
(and (= (syntactic-type-of arg) :zinc.core/Conjunction)
(subset? (find-utils/findto arg 'and) (find-utils/findto target 'andorargs)))
target
(nil? (rest args))
nil
:else
(recur (rest args))))))
(defmethod slot-based-entails
[:zinc.core/Implication :zinc.core/Implication] [source target]
(let [src-ant (nth (@down-cableset source) 0)
src-cq (nth (@down-cableset target) 1)
tgt-ant (nth (@down-cableset source) 0)
tgt-cq (nth (@down-cableset target) 1)]
(when (and (subset? src-ant tgt-ant) (subset? tgt-cq src-cq))
target)))
(defmethod slot-based-entails
[:zinc.core/Andor :zinc.core/Andor] [source target]
(let [i (:min source)
j (:max source)
src-set (nth (@down-cableset source) 0)
tgt-set (nth (@down-cableset target) 0)
k (- (count src-set) (count tgt-set))]
(when (or
(and (>= k 0)
(subset? tgt-set src-set)
(= (max (- i k) 0) (:min target))
(= (min j (count tgt-set)) (:max target)))
(and (subset? src-set tgt-set)
(= i (:min target))
(= (- j k) (:max target))))
target)))
(defmethod slot-based-entails
[:zinc.core/Thresh :zinc.core/Thresh] [source target]
(let [i (:min source)
j (:max source)
src-set (nth (@down-cableset source) 0)
tgt-set (nth (@down-cableset target) 0)
k (- (count src-set) (count tgt-set))]
(when (or
(and (>= k 0)
(subset? tgt-set src-set)
(= (min i (count tgt-set)) (:min target))
(= (max (- j k) i) (:max target)))
(and (subset? src-set tgt-set)
(= (- i k) (:min target))
(= j (:max target))))
target)))
(defmethod slot-based-entails
[:zinc.core/Negation :zinc.core/Negation] [negsource negtarget]
(when (not= negsource negtarget)
(let [sourceset (find-utils/findto negsource 'nor)
targetset (find-utils/findto negtarget 'nor)]
;; If the source and target sets are singletons, perform normal slot-based inference
(if (and (= (count sourceset) 1) (= (count targetset) 1))
(let [source (first sourceset)
target (first targetset)]
;; If source and target are molecular, and have compatible frames
;; TODO: should this "adjustable" check be eliminated?
(if (and (isa? (syntactic-type-of target) :zinc.core/Molecular)
(isa? (syntactic-type-of source) :zinc.core/Molecular)
(cf/adjustable? (@caseframe source) (@caseframe target)))
;; Return targetset if the fillers of every source slot can
;; be validly adjusted to the fillers of the corresponding target slot
(when (every?
#(valid-adjust (:negadjust %)
(:min %)
(:max %)
(pb-findtos (hash-set source) %)
(pb-findtos (hash-set target) %))
(:slots (@caseframe source)))
targetset)))
;; Else (not singletons; special nor case):
;; return targetset if the source set covers the target set
(when (covers sourceset targetset) targetset)))))
(defmethod slot-based-entails
[:zinc.core/Molecular :zinc.core/Molecular] [source target]
;(println "Here" (cf/adjustable? (:caseframe source) (:caseframe target)))
(when (and (cf/adjustable? (@caseframe source) (@caseframe target))
(every?
#(valid-adjust (:posadjust %)
(:min %)
(:max %)
(pb-findtos (hash-set source) %)
(pb-findtos (hash-set target) %))
(:slots (@caseframe source))))
target))
(defn covers
"Returns true if target and source are sets of propositions
such that every proposition in target is eq to,
or is slot-based-entailed by some proposition in source"
[source target]
(every? (fn [tgt]
(some
(fn [src] (or (= src tgt)
(slot-based-entails src tgt)))
source))
target))
;; TODO: I used case here. ecase was used in the CL impl. Check on effects.
(defn valid-adjust
"Returns t if the sourcefillers can be adjusted
via the adjust type adj to the targetfillers"
[adj min max sourcefillers targetfillers]
(when-not (or (empty? sourcefillers) (empty? targetfillers))
(and (<= min (count targetfillers))
(or (nil? max) (<= (count targetfillers) max))
(case adj
reduce (or (= targetfillers sourcefillers)
(subset? (set targetfillers) (set sourcefillers)))
expand (or (= sourcefillers targetfillers)
(subset? (set sourcefillers) (set targetfillers)))
none (= sourcefillers targetfillers)))))
(defn sb-derivable-test
"Returns t if target is slot-based-entailed by term
and if term is asserted in context;
Else, returns nil."
[term target context termstack]
(and
(not= term target)
(not-any? (hash-set term) termstack)
(slot-based-entails term target)
(seq (askif term context (cons target termstack)))))
(defn slot-based-derivable
"If the term [target] is entailed in the given context
via slot-based-inference
assert it,
and return a set containing it;
else return the empty set.
The termstack is a stack of propositions
that this goal is a subgoal of."
[target context termstack]
(if (isa? (type-of target) :zinc.core/Molecular)
(do
;;Look at the terms stored in the target's caseframe
(when @goaltrace
(cl-format true "~&I will consider using Slot&Path-Based inference.~%"))
(or
(loop
[terms @(:terms (@caseframe target))]
(cond
(empty? terms)
nil
(sb-derivable-test (first terms) target context termstack)
(do
(assertTrace (first terms) nil target "Slot-Based inference" context)
(hash-set (list target)))
:else (recur (rest terms))))
;; For each caseframe cf that can be adjusted to the target's frame,
;; look at each of cf's stored terms
(loop
[cfs @(:adj-from (@caseframe target))]
(let [cf (first cfs)
res (when cf
(loop
[terms @(:terms cf)]
(cond
(empty? terms)
nil
(sb-derivable-test (first terms) target context termstack)
(do
(assertTrace (first terms) nil target "Slot-Based inference" context)
(hash-set (list target)))
:else (recur (rest terms)))))]
(when-not (nil? cf)
(recur (rest cfs)))))
(hash-set)))
(hash-set))) | 81625 | ;;; CSNePS: Slot-Based Inference
;;; =============
;;; Written by <NAME>
;;; Ported to Clojure by <NAME>
;;;
;;; The contents of this file are subject to the University at Buffalo
;;; Public 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 at http://www.cse.buffalo.edu/sneps/Downloads/ubpl.pdf.
;;;
;;; Software distributed under the License is distributed on an "AS IS"
;;; basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
;;; the License for the specific language governing rights and limitations
;;; under the License.
;;;
;;; The Original Code is CSNePS.
;;;
;;; The Initial Developer of the Original Code is Research Foundation of
;;; State University of New York, on behalf of University at Buffalo.
;;;
;;; Portions created by the Initial Developer are Copyright (C) 2012
;;; Research Foundation of State University of New York, on behalf of
;;; University at Buffalo. All Rights Reserved.
;;;
;;; Contributor(s): ______________________________________.
(in-ns 'zinc.snip)
(declare covers valid-adjust)
(defmulti slot-based-entails
(fn [source target] [(syntactic-type-of source) (syntactic-type-of target)]))
;;; Slot-based entailment never applies to an atom and anything
(defmethod slot-based-entails [:zinc.core/Atom :zinc.core/Molecular] [source target])
(defmethod slot-based-entails [:zinc.core/Molecular :zinc.core/Atom] [source target])
(defmethod slot-based-entails [:zinc.core/Atom :zinc.core/Atom] [source target])
(defmethod slot-based-entails
[:zinc.core/Negation :zinc.core/Nand] [source target]
;; nor -> nand
;; (nor (and P Q) R) |= (nand P Q)
;; if any of the source's fillers is a conjunction X s.t.
;; X's fillers are a subset of the target's fillers,
;; then the source entails the target so return it.
(loop
[args (find-utils/findto source 'nor)]
(let [arg (first args)]
(cond
(and (= (syntactic-type-of arg) :zinc.core/Conjunction)
(subset? (find-utils/findto arg 'and) (find-utils/findto target 'andorargs)))
target
(nil? (rest args))
nil
:else
(recur (rest args))))))
(defmethod slot-based-entails
[:zinc.core/Implication :zinc.core/Implication] [source target]
(let [src-ant (nth (@down-cableset source) 0)
src-cq (nth (@down-cableset target) 1)
tgt-ant (nth (@down-cableset source) 0)
tgt-cq (nth (@down-cableset target) 1)]
(when (and (subset? src-ant tgt-ant) (subset? tgt-cq src-cq))
target)))
(defmethod slot-based-entails
[:zinc.core/Andor :zinc.core/Andor] [source target]
(let [i (:min source)
j (:max source)
src-set (nth (@down-cableset source) 0)
tgt-set (nth (@down-cableset target) 0)
k (- (count src-set) (count tgt-set))]
(when (or
(and (>= k 0)
(subset? tgt-set src-set)
(= (max (- i k) 0) (:min target))
(= (min j (count tgt-set)) (:max target)))
(and (subset? src-set tgt-set)
(= i (:min target))
(= (- j k) (:max target))))
target)))
(defmethod slot-based-entails
[:zinc.core/Thresh :zinc.core/Thresh] [source target]
(let [i (:min source)
j (:max source)
src-set (nth (@down-cableset source) 0)
tgt-set (nth (@down-cableset target) 0)
k (- (count src-set) (count tgt-set))]
(when (or
(and (>= k 0)
(subset? tgt-set src-set)
(= (min i (count tgt-set)) (:min target))
(= (max (- j k) i) (:max target)))
(and (subset? src-set tgt-set)
(= (- i k) (:min target))
(= j (:max target))))
target)))
(defmethod slot-based-entails
[:zinc.core/Negation :zinc.core/Negation] [negsource negtarget]
(when (not= negsource negtarget)
(let [sourceset (find-utils/findto negsource 'nor)
targetset (find-utils/findto negtarget 'nor)]
;; If the source and target sets are singletons, perform normal slot-based inference
(if (and (= (count sourceset) 1) (= (count targetset) 1))
(let [source (first sourceset)
target (first targetset)]
;; If source and target are molecular, and have compatible frames
;; TODO: should this "adjustable" check be eliminated?
(if (and (isa? (syntactic-type-of target) :zinc.core/Molecular)
(isa? (syntactic-type-of source) :zinc.core/Molecular)
(cf/adjustable? (@caseframe source) (@caseframe target)))
;; Return targetset if the fillers of every source slot can
;; be validly adjusted to the fillers of the corresponding target slot
(when (every?
#(valid-adjust (:negadjust %)
(:min %)
(:max %)
(pb-findtos (hash-set source) %)
(pb-findtos (hash-set target) %))
(:slots (@caseframe source)))
targetset)))
;; Else (not singletons; special nor case):
;; return targetset if the source set covers the target set
(when (covers sourceset targetset) targetset)))))
(defmethod slot-based-entails
[:zinc.core/Molecular :zinc.core/Molecular] [source target]
;(println "Here" (cf/adjustable? (:caseframe source) (:caseframe target)))
(when (and (cf/adjustable? (@caseframe source) (@caseframe target))
(every?
#(valid-adjust (:posadjust %)
(:min %)
(:max %)
(pb-findtos (hash-set source) %)
(pb-findtos (hash-set target) %))
(:slots (@caseframe source))))
target))
(defn covers
"Returns true if target and source are sets of propositions
such that every proposition in target is eq to,
or is slot-based-entailed by some proposition in source"
[source target]
(every? (fn [tgt]
(some
(fn [src] (or (= src tgt)
(slot-based-entails src tgt)))
source))
target))
;; TODO: I used case here. ecase was used in the CL impl. Check on effects.
(defn valid-adjust
"Returns t if the sourcefillers can be adjusted
via the adjust type adj to the targetfillers"
[adj min max sourcefillers targetfillers]
(when-not (or (empty? sourcefillers) (empty? targetfillers))
(and (<= min (count targetfillers))
(or (nil? max) (<= (count targetfillers) max))
(case adj
reduce (or (= targetfillers sourcefillers)
(subset? (set targetfillers) (set sourcefillers)))
expand (or (= sourcefillers targetfillers)
(subset? (set sourcefillers) (set targetfillers)))
none (= sourcefillers targetfillers)))))
(defn sb-derivable-test
"Returns t if target is slot-based-entailed by term
and if term is asserted in context;
Else, returns nil."
[term target context termstack]
(and
(not= term target)
(not-any? (hash-set term) termstack)
(slot-based-entails term target)
(seq (askif term context (cons target termstack)))))
(defn slot-based-derivable
"If the term [target] is entailed in the given context
via slot-based-inference
assert it,
and return a set containing it;
else return the empty set.
The termstack is a stack of propositions
that this goal is a subgoal of."
[target context termstack]
(if (isa? (type-of target) :zinc.core/Molecular)
(do
;;Look at the terms stored in the target's caseframe
(when @goaltrace
(cl-format true "~&I will consider using Slot&Path-Based inference.~%"))
(or
(loop
[terms @(:terms (@caseframe target))]
(cond
(empty? terms)
nil
(sb-derivable-test (first terms) target context termstack)
(do
(assertTrace (first terms) nil target "Slot-Based inference" context)
(hash-set (list target)))
:else (recur (rest terms))))
;; For each caseframe cf that can be adjusted to the target's frame,
;; look at each of cf's stored terms
(loop
[cfs @(:adj-from (@caseframe target))]
(let [cf (first cfs)
res (when cf
(loop
[terms @(:terms cf)]
(cond
(empty? terms)
nil
(sb-derivable-test (first terms) target context termstack)
(do
(assertTrace (first terms) nil target "Slot-Based inference" context)
(hash-set (list target)))
:else (recur (rest terms)))))]
(when-not (nil? cf)
(recur (rest cfs)))))
(hash-set)))
(hash-set))) | true | ;;; CSNePS: Slot-Based Inference
;;; =============
;;; Written by PI:NAME:<NAME>END_PI
;;; Ported to Clojure by PI:NAME:<NAME>END_PI
;;;
;;; The contents of this file are subject to the University at Buffalo
;;; Public 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 at http://www.cse.buffalo.edu/sneps/Downloads/ubpl.pdf.
;;;
;;; Software distributed under the License is distributed on an "AS IS"
;;; basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
;;; the License for the specific language governing rights and limitations
;;; under the License.
;;;
;;; The Original Code is CSNePS.
;;;
;;; The Initial Developer of the Original Code is Research Foundation of
;;; State University of New York, on behalf of University at Buffalo.
;;;
;;; Portions created by the Initial Developer are Copyright (C) 2012
;;; Research Foundation of State University of New York, on behalf of
;;; University at Buffalo. All Rights Reserved.
;;;
;;; Contributor(s): ______________________________________.
(in-ns 'zinc.snip)
(declare covers valid-adjust)
(defmulti slot-based-entails
(fn [source target] [(syntactic-type-of source) (syntactic-type-of target)]))
;;; Slot-based entailment never applies to an atom and anything
(defmethod slot-based-entails [:zinc.core/Atom :zinc.core/Molecular] [source target])
(defmethod slot-based-entails [:zinc.core/Molecular :zinc.core/Atom] [source target])
(defmethod slot-based-entails [:zinc.core/Atom :zinc.core/Atom] [source target])
(defmethod slot-based-entails
[:zinc.core/Negation :zinc.core/Nand] [source target]
;; nor -> nand
;; (nor (and P Q) R) |= (nand P Q)
;; if any of the source's fillers is a conjunction X s.t.
;; X's fillers are a subset of the target's fillers,
;; then the source entails the target so return it.
(loop
[args (find-utils/findto source 'nor)]
(let [arg (first args)]
(cond
(and (= (syntactic-type-of arg) :zinc.core/Conjunction)
(subset? (find-utils/findto arg 'and) (find-utils/findto target 'andorargs)))
target
(nil? (rest args))
nil
:else
(recur (rest args))))))
(defmethod slot-based-entails
[:zinc.core/Implication :zinc.core/Implication] [source target]
(let [src-ant (nth (@down-cableset source) 0)
src-cq (nth (@down-cableset target) 1)
tgt-ant (nth (@down-cableset source) 0)
tgt-cq (nth (@down-cableset target) 1)]
(when (and (subset? src-ant tgt-ant) (subset? tgt-cq src-cq))
target)))
(defmethod slot-based-entails
[:zinc.core/Andor :zinc.core/Andor] [source target]
(let [i (:min source)
j (:max source)
src-set (nth (@down-cableset source) 0)
tgt-set (nth (@down-cableset target) 0)
k (- (count src-set) (count tgt-set))]
(when (or
(and (>= k 0)
(subset? tgt-set src-set)
(= (max (- i k) 0) (:min target))
(= (min j (count tgt-set)) (:max target)))
(and (subset? src-set tgt-set)
(= i (:min target))
(= (- j k) (:max target))))
target)))
(defmethod slot-based-entails
[:zinc.core/Thresh :zinc.core/Thresh] [source target]
(let [i (:min source)
j (:max source)
src-set (nth (@down-cableset source) 0)
tgt-set (nth (@down-cableset target) 0)
k (- (count src-set) (count tgt-set))]
(when (or
(and (>= k 0)
(subset? tgt-set src-set)
(= (min i (count tgt-set)) (:min target))
(= (max (- j k) i) (:max target)))
(and (subset? src-set tgt-set)
(= (- i k) (:min target))
(= j (:max target))))
target)))
(defmethod slot-based-entails
[:zinc.core/Negation :zinc.core/Negation] [negsource negtarget]
(when (not= negsource negtarget)
(let [sourceset (find-utils/findto negsource 'nor)
targetset (find-utils/findto negtarget 'nor)]
;; If the source and target sets are singletons, perform normal slot-based inference
(if (and (= (count sourceset) 1) (= (count targetset) 1))
(let [source (first sourceset)
target (first targetset)]
;; If source and target are molecular, and have compatible frames
;; TODO: should this "adjustable" check be eliminated?
(if (and (isa? (syntactic-type-of target) :zinc.core/Molecular)
(isa? (syntactic-type-of source) :zinc.core/Molecular)
(cf/adjustable? (@caseframe source) (@caseframe target)))
;; Return targetset if the fillers of every source slot can
;; be validly adjusted to the fillers of the corresponding target slot
(when (every?
#(valid-adjust (:negadjust %)
(:min %)
(:max %)
(pb-findtos (hash-set source) %)
(pb-findtos (hash-set target) %))
(:slots (@caseframe source)))
targetset)))
;; Else (not singletons; special nor case):
;; return targetset if the source set covers the target set
(when (covers sourceset targetset) targetset)))))
(defmethod slot-based-entails
[:zinc.core/Molecular :zinc.core/Molecular] [source target]
;(println "Here" (cf/adjustable? (:caseframe source) (:caseframe target)))
(when (and (cf/adjustable? (@caseframe source) (@caseframe target))
(every?
#(valid-adjust (:posadjust %)
(:min %)
(:max %)
(pb-findtos (hash-set source) %)
(pb-findtos (hash-set target) %))
(:slots (@caseframe source))))
target))
(defn covers
"Returns true if target and source are sets of propositions
such that every proposition in target is eq to,
or is slot-based-entailed by some proposition in source"
[source target]
(every? (fn [tgt]
(some
(fn [src] (or (= src tgt)
(slot-based-entails src tgt)))
source))
target))
;; TODO: I used case here. ecase was used in the CL impl. Check on effects.
(defn valid-adjust
"Returns t if the sourcefillers can be adjusted
via the adjust type adj to the targetfillers"
[adj min max sourcefillers targetfillers]
(when-not (or (empty? sourcefillers) (empty? targetfillers))
(and (<= min (count targetfillers))
(or (nil? max) (<= (count targetfillers) max))
(case adj
reduce (or (= targetfillers sourcefillers)
(subset? (set targetfillers) (set sourcefillers)))
expand (or (= sourcefillers targetfillers)
(subset? (set sourcefillers) (set targetfillers)))
none (= sourcefillers targetfillers)))))
(defn sb-derivable-test
"Returns t if target is slot-based-entailed by term
and if term is asserted in context;
Else, returns nil."
[term target context termstack]
(and
(not= term target)
(not-any? (hash-set term) termstack)
(slot-based-entails term target)
(seq (askif term context (cons target termstack)))))
(defn slot-based-derivable
"If the term [target] is entailed in the given context
via slot-based-inference
assert it,
and return a set containing it;
else return the empty set.
The termstack is a stack of propositions
that this goal is a subgoal of."
[target context termstack]
(if (isa? (type-of target) :zinc.core/Molecular)
(do
;;Look at the terms stored in the target's caseframe
(when @goaltrace
(cl-format true "~&I will consider using Slot&Path-Based inference.~%"))
(or
(loop
[terms @(:terms (@caseframe target))]
(cond
(empty? terms)
nil
(sb-derivable-test (first terms) target context termstack)
(do
(assertTrace (first terms) nil target "Slot-Based inference" context)
(hash-set (list target)))
:else (recur (rest terms))))
;; For each caseframe cf that can be adjusted to the target's frame,
;; look at each of cf's stored terms
(loop
[cfs @(:adj-from (@caseframe target))]
(let [cf (first cfs)
res (when cf
(loop
[terms @(:terms cf)]
(cond
(empty? terms)
nil
(sb-derivable-test (first terms) target context termstack)
(do
(assertTrace (first terms) nil target "Slot-Based inference" context)
(hash-set (list target)))
:else (recur (rest terms)))))]
(when-not (nil? cf)
(recur (rest cfs)))))
(hash-set)))
(hash-set))) |
[
{
"context": "ntifies this request in the cache\n :cache-key \"/sample|:get||||\"\n\n ;; the response returned by the handler in c",
"end": 6857,
"score": 0.8420186638832092,
"start": 6842,
"tag": "KEY",
"value": "sample|:get||||"
}
] | src/com/brunobonacci/ring_boost/core.clj | BrunoBonacci/ring-boost | 10 | (ns com.brunobonacci.ring-boost.core
(:require [clojure.java.io :as io]
[clojure.pprint :refer [pprint]]
[clojure.string :as str]
[com.brunobonacci.sophia :as sph]
[pandect.algo.md5 :as digest]
[safely.core :refer [safely]]
[samsara.trackit :refer [track-rate]]
[where.core :refer [where]])
(:import [java.io ByteArrayInputStream ByteArrayOutputStream InputStream]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ---==| B U I L D I N G F U N C T I O N S |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^:const default-keys
[:uri :request-method :server-name :server-port :query-string :body-fingerprint])
(defn build-matcher
[{:keys [match matcher] :as profile}]
(if matcher
profile
(assoc profile :matcher (where match))))
(defn matching-profile
[profiles request]
(some (fn [{:keys [matcher] :as p}]
(when (and matcher (matcher request))
p)) profiles))
(defn make-key
[segments]
(->> segments
(map (fn [k]
(if (vector? k)
#(get-in % k)
#(get % k))))
(apply juxt)
(comp (partial str/join "|"))))
(defn build-key-maker
[{:keys [keys key-maker] :as profile}]
(if key-maker
profile
(assoc profile :key-maker (make-key (or keys default-keys)))))
(defn build-profiles
[profiles]
(mapv
(comp build-key-maker
build-matcher)
(filter :enabled profiles)))
(defn load-version
[config]
(assoc config :boost-version
(safely
(str/trim (slurp (io/resource "ring-boost.version")))
:on-error
:default "v???")))
(defn compile-processor
[{:keys [processor-seq] :as boost-config}]
(->> (drop 1 processor-seq)
reverse
(map :call)
(apply comp)))
(defn debug-compile-processor
[{:keys [processor-seq] :as boost-config}]
(->> processor-seq
(map (fn [{:keys [name call]}]
{:name name
:call (fn [ctx]
(println "calling: " name)
(call ctx))}))
(drop 1)
reverse
(map :call)
(apply comp)))
(defn compile-configuration
[boost-config]
(as-> boost-config $
(load-version $)
(update $ :profiles build-profiles)
(assoc $ :cache
(sph/sophia (:storage $)))
(assoc $ :processor (compile-processor $))))
;; defined later
(declare default-processor-seq)
(defn after-call
[{:keys [processor-seq] :as config} call-name new-call]
(let [processor-seq (or processor-seq (default-processor-seq))
pre (take-while (where :name not= call-name) processor-seq)
it (filter (where :name = call-name) processor-seq)
post (rest (drop-while (where :name not= call-name) processor-seq))]
(when-not (seq it)
(throw (ex-info (str call-name " call not found.")
{:processor-seq (or processor-seq (default-processor-seq))
:call-name call-name})))
(assoc config :processor-seq
(concat pre it [new-call] post))))
(defn before-call
[{:keys [processor-seq] :as config} call-name new-call]
(let [processor-seq (or processor-seq (default-processor-seq))
pre (take-while (where :name not= call-name) processor-seq)
it (filter (where :name = call-name) processor-seq)
post (rest (drop-while (where :name not= call-name) processor-seq))]
(when-not (seq it)
(throw (ex-info (str call-name " call not found.")
{:processor-seq (or processor-seq (default-processor-seq))
:call-name call-name})))
(assoc config :processor-seq
(concat pre [new-call] it post))))
(defn remove-call
[{:keys [processor-seq] :as config} call-name]
(update config :processor-seq
#(remove
(where :name = call-name)
(or % (default-processor-seq)))))
(defn replace-call
[{:keys [processor-seq] :as config} call-name new-call]
(let [processor-seq (or processor-seq (default-processor-seq))
pre (take-while (where :name not= call-name) processor-seq)
it (filter (where :name = call-name) processor-seq)
post (rest (drop-while (where :name not= call-name) processor-seq))]
(when-not (seq it)
(throw (ex-info (str call-name " call not found.")
{:processor-seq (or processor-seq (default-processor-seq))
:call-name call-name})))
(assoc config :processor-seq
(concat pre [new-call] post))))
(defn fetch [body]
(when body
(cond
(instance? java.io.InputStream body)
(let [^java.io.ByteArrayOutputStream out (java.io.ByteArrayOutputStream.)]
(io/copy body out)
(.toByteArray out))
(string? body)
(let [^String sbody body]
(.getBytes sbody))
:else
body)))
(def byte-array-type
(type (byte-array 0)))
(defn byte-array?
[v]
(= byte-array-type (type v)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ---==| C O N T E X T P R O C E S S I N G |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(comment
;;
;; This is how the context map looks like
;;
{;; contains the compiled boost configuration and the reference to the database
:boost {;; whether of not the cache is enabled
:enabled true/false
;; storage layer configuration
:storage {}
;; profile configuration
:profiles []
;; list of context processing function
:processor-seq []
;; current ring-boost version
:boost-version "x.y.z"
;; database reference
:cache {}
;; compiled processor (from :processor-seq)
:processor fn
}
;; the handler to execute in case of a cache miss
:handler handler-fn
;; the user request
:req {:request-method :get, :uri "/sample", :body nil}
;; the matched boost profile if found, nil otherwise
:cacheable-profile {:enabled true, :cache-for 10, :profile :test,
:match predicate-fn, :matcher fn, :key-maker fn}
;; this is the computed key which identifies this request in the cache
:cache-key "/sample|:get||||"
;; the response returned by the handler in case of a cache miss
;; or a cached response in cache of cache hit.
:resp {:status 200 :body [bytes] :headers {"etag" "foo"}}
;; whether or not to store the response into the cache
:resp-cacheable? true/false
;; whether or not the response was stored
:stored true/false
;; computed statistics cache hits/misses for the given cache-key
;; and the profile as a whole.
:stats {:key {} :profile {}}
}
)
(defn lift-request
[boost handler]
(fn [req]
{:boost boost :handler handler :req req}))
(defn cacheable-profilie
[{:keys [boost req] :as ctx}]
(assoc ctx :cacheable-profile
(matching-profile (:profiles boost) req)))
(defn request-body-fingerprint
[{:keys [boost cacheable-profile req] :as ctx}]
(if-not cacheable-profile
ctx
(let [body (fetch (:body req))
fingerprint (when (byte-array? body) (digest/md5 body))
normal-body (if (byte-array? body) (java.io.ByteArrayInputStream. body) body)]
(-> ctx
(assoc-in [:req :body] normal-body)
(assoc-in [:req :body-fingerprint] fingerprint)))))
(defn cache-lookup
[{:keys [boost cacheable-profile req] :as ctx}]
(if-not cacheable-profile
ctx
(let [key* (:key-maker cacheable-profile)
key (key* req)]
(assoc ctx
:cached (safely
(sph/get-value (:cache boost) "cache" key)
:on-error
:message "ring-boost cache lookup"
:track-as "ring_boost.cache.lookup"
:default nil)
:cache-key key))))
(defn is-cache-expired?
[{:keys [cacheable-profile cached] :as ctx}]
(if-not cached
ctx
(let [cache-for (:cache-for cacheable-profile)
elapsed (- (System/currentTimeMillis)
(or (:timestamp cached) 0))
expired? (> elapsed (if (= :forever cache-for)
Long/MAX_VALUE (* 1000 cache-for)))]
(if expired?
(dissoc ctx :cached)
ctx))))
(defn is-skip-cache?
[{:keys [req cached] :as ctx}]
(if (and cached (get-in req [:headers "x-cache-skip"] false))
(dissoc ctx :cached)
ctx))
(defn- safe-metric-name
[name]
(-> (str name)
(str/replace #"[^a-zA-Z0-9_]+" "_")
(str/replace #"^_+|_+$" "")))
(defn track-cache-metrics
[{:keys [cacheable-profile cached resp-cacheable?] :as ctx}]
(if cacheable-profile
(let [profile (safe-metric-name (:profile cacheable-profile))]
(if cached
(track-rate (str "ring_boost.profile." profile ".hit_rate"))
(track-rate (str "ring_boost.profile." profile ".miss_rate")))
(when (and (not cached) (not resp-cacheable?))
(track-rate (str "ring_boost.profile." profile ".not_cacheable_rate"))))
(track-rate "ring_boost.no_profile.rate"))
ctx)
(defn- increment-stats-by!
"increments the stats for a given profile/key by the given amount"
[boost {:keys [profile key hit miss not-cacheable]}]
(safely
(sph/transact! (:cache boost)
(fn [tx]
(sph/upsert-value! tx "stats" (str profile ":" key)
(fnil (partial merge-with +) {:profile profile
:key key
:hit 0
:miss 0
:not-cacheable 0})
{:hit hit :miss miss :not-cacheable not-cacheable})
(sph/upsert-value! tx "stats" (str profile)
(fnil (partial merge-with +) {:profile profile
:hit 0
:miss 0
:not-cacheable 0})
{:hit hit :miss miss :not-cacheable not-cacheable})))
:on-error
:max-retry 3
:message "ring-boost update statistics"
:track-as "ring_boost.stats.update"))
(defn- async-do!
"It runs the given function presumably with side effect
without affecting the state of the agent."
[f]
(fn [state & args]
(apply f args)
state))
(defn update-cache-stats
[{:keys [boost cacheable-profile cache-key resp cached resp-cacheable?] :as ctx}]
(when cacheable-profile
;; asynchronously update the stats
(send-off (:async-agent boost)
(async-do! increment-stats-by!) boost
{:profile (:profile cacheable-profile)
:key cache-key
:hit (if cached 1 0)
:miss (if cached 0 1)
:not-cacheable (if (and (not cached) (not resp-cacheable?)) 1 0)}))
ctx)
(defn fetch-cache-stats
[{:keys [boost cacheable-profile cache-key req cached resp-cacheable?] :as ctx}]
(if (and cacheable-profile (get-in req [:headers "x-cache-debug"]))
(safely
(let [profile (:profile cacheable-profile)
stats (sph/get-value (:cache boost) "stats"
(str profile ":" cache-key)
{:profile profile
:key cache-key
:hit 0
:miss 0
:not-cacheable 0})
pstats (sph/get-value (:cache boost) "stats"
(str profile)
{:profile profile
:hit 0
:miss 0
:not-cacheable 0})]
(assoc ctx :stats {:key stats :profile pstats}))
;; if transaction fail, ignore stats update
;; faster times are more important than accurate
;; stats. Maybe consider to update stats async.
:on-error
:default ctx
:message "ring-boost fetch statistics"
:track-as "ring_boost.stats.fecth")
ctx))
(defn fetch-response
[{:keys [req cached handler] :as ctx}]
(assoc ctx :resp (if cached (:payload cached) (handler req))))
(defn response-cacheable?
[{:keys [req resp cached handler] :as ctx}]
(assoc ctx :resp-cacheable?
(and resp (<= 200 (:status resp) 299))))
(defn cache-store!
[{:keys [boost cacheable-profile cache-key resp cached resp-cacheable?] :as ctx}]
;; when the user asked to cache this request
;; and this response didn't come from the cache
;; but it was fetched and the response is cacheable
;; then save it into the cache
(let [stored? (when (and cacheable-profile (not cached) resp-cacheable?)
(let [data {:timestamp (System/currentTimeMillis) :payload resp}]
(safely
(sph/set-value! (:cache boost) "cache" cache-key data)
:on-error
:message "ring-boost cache store"
:track-as "ring_boost.cache.store"
:default false)))]
(assoc ctx :stored (boolean stored?))))
(defn return-response
[{:keys [resp]}]
(if (byte-array? (:body resp))
(update resp :body #(java.io.ByteArrayInputStream. %))
resp))
(defn debug-headers
[{:keys [req cached boost] :as ctx}]
(if (get-in req [:headers "x-cache-debug"])
(update ctx :resp
(fn [resp]
(when resp
(update resp :headers (fnil conj {})
{"X-CACHE" (str "RING-BOOST/v" (:boost-version boost))
"X-RING-BOOST-CACHE" (if (:cached ctx) "CACHE-HIT" "CACHE-MISS")
"X-RING-BOOST-CACHE-PROFILE" (or (str (-> ctx :cacheable-profile :profile)) "unknown")}
(when (:stats ctx)
{"X-RING-BOOST-CACHE-STATS1"
(str/join "/"
[(get-in ctx [:stats :key :hit])
(get-in ctx [:stats :key :miss])
(get-in ctx [:stats :key :not-cacheable])])
"X-RING-BOOST-CACHE-STATS2"
(str/join "/"
[(get-in ctx [:stats :profile :hit])
(get-in ctx [:stats :profile :miss])
(get-in ctx [:stats :profile :not-cacheable])])})))))
ctx))
(defn debug-print-context
[ctx]
(pprint ctx)
ctx)
(defn response-body-normalize
[{:keys [cacheable-profile resp cached] :as ctx}]
(if-not (and cacheable-profile (not cached) (:body resp))
ctx
(cond
(instance? java.io.InputStream (:body resp))
(update-in ctx [:resp :body] fetch)
(string? (:body resp))
(update-in ctx [:resp :body]
(fn [^String body] (.getBytes body)))
:else
ctx)))
(defn add-cache-headers
[{:keys [resp] :as ctx}]
(if (and (byte-array? (get resp :body))
(not (or (get-in resp [:headers "etag"])
(get-in resp [:headers "ETag"]))))
(assoc-in ctx [:resp :headers "etag"]
(digest/md5 (get resp :body)))
ctx))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ----==| D E F A U L T C O N F I G U R A T I O N |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn default-processor-seq []
[{:name :lift-request }
{:name :cacheable-profilie :call cacheable-profilie}
{:name :request-body-fingerprint :call request-body-fingerprint}
{:name :cache-lookup :call cache-lookup }
{:name :is-cache-expired? :call is-cache-expired? }
{:name :is-skip-cache? :call is-skip-cache? }
{:name :fetch-response :call fetch-response }
{:name :response-cacheable? :call response-cacheable?}
{:name :response-body-normalize :call response-body-normalize}
{:name :add-cache-headers :call add-cache-headers }
{:name :cache-store! :call cache-store! }
{:name :track-cache-metrics :call track-cache-metrics}
{:name :update-cache-stats :call update-cache-stats}
{:name :fetch-cache-stats :call fetch-cache-stats }
{:name :debug-headers :call debug-headers }
{:name :return-response :call return-response }])
(def ^:const default-profile-config
{;; whether or not this profile is enabled
;; when disabled it won't be considered at all
:enabled true
;; profile name is (REQUIRED)
;;:profile :this-profile
;; match specification (REQUIRED)
;; :match [:and
;; [:uri :starts-with? "/something/cacheable/"]
;; [:request-method = :get]]
;; the duration in seconds for how long ring-boost should
;; serve the item from the cache if present
;; use `:forever` to cache immutable responses
;; default 0
:cache-for 0})
(def default-boost-config
{;; Whether the ring-boost cache is enabled or not.
;; when not enabled the handler will behave as if
;; the ring-boost wasn't there at all.
:enabled true
;; cache storage configuration
:storage {:sophia.path "/tmp/ring-boost-cache" :dbs ["cache" "stats"]}
;; caching profiles. see `default-profile-config`
:profiles []
;; sequence of processing function for this boost configuration
;; unless specified differently in a caching profile
;; this one will be used.
:processor-seq (default-processor-seq)
;; agent for async operations
;; like updating the stats
:async-agent (agent {})
})
(defn deep-merge
"Like merge, but merges maps recursively."
[& maps]
(let [maps (filter (comp not nil?) maps)]
(if (every? map? maps)
(apply merge-with deep-merge maps)
(last maps))))
(defn- apply-defaults
[config]
(-> (deep-merge default-boost-config config)
(update :profiles (partial mapv (partial deep-merge default-profile-config)))))
(defn ring-boost
[handler boost-config]
(let [{:keys [enabled] :as conf}
(-> boost-config apply-defaults compile-configuration)]
(if-not enabled
;; if boost is not enabled, then just return the handler
handler
(let [processor (comp (:processor conf) (lift-request conf handler))]
(fn [req]
(processor req))))))
| 77478 | (ns com.brunobonacci.ring-boost.core
(:require [clojure.java.io :as io]
[clojure.pprint :refer [pprint]]
[clojure.string :as str]
[com.brunobonacci.sophia :as sph]
[pandect.algo.md5 :as digest]
[safely.core :refer [safely]]
[samsara.trackit :refer [track-rate]]
[where.core :refer [where]])
(:import [java.io ByteArrayInputStream ByteArrayOutputStream InputStream]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ---==| B U I L D I N G F U N C T I O N S |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^:const default-keys
[:uri :request-method :server-name :server-port :query-string :body-fingerprint])
(defn build-matcher
[{:keys [match matcher] :as profile}]
(if matcher
profile
(assoc profile :matcher (where match))))
(defn matching-profile
[profiles request]
(some (fn [{:keys [matcher] :as p}]
(when (and matcher (matcher request))
p)) profiles))
(defn make-key
[segments]
(->> segments
(map (fn [k]
(if (vector? k)
#(get-in % k)
#(get % k))))
(apply juxt)
(comp (partial str/join "|"))))
(defn build-key-maker
[{:keys [keys key-maker] :as profile}]
(if key-maker
profile
(assoc profile :key-maker (make-key (or keys default-keys)))))
(defn build-profiles
[profiles]
(mapv
(comp build-key-maker
build-matcher)
(filter :enabled profiles)))
(defn load-version
[config]
(assoc config :boost-version
(safely
(str/trim (slurp (io/resource "ring-boost.version")))
:on-error
:default "v???")))
(defn compile-processor
[{:keys [processor-seq] :as boost-config}]
(->> (drop 1 processor-seq)
reverse
(map :call)
(apply comp)))
(defn debug-compile-processor
[{:keys [processor-seq] :as boost-config}]
(->> processor-seq
(map (fn [{:keys [name call]}]
{:name name
:call (fn [ctx]
(println "calling: " name)
(call ctx))}))
(drop 1)
reverse
(map :call)
(apply comp)))
(defn compile-configuration
[boost-config]
(as-> boost-config $
(load-version $)
(update $ :profiles build-profiles)
(assoc $ :cache
(sph/sophia (:storage $)))
(assoc $ :processor (compile-processor $))))
;; defined later
(declare default-processor-seq)
(defn after-call
[{:keys [processor-seq] :as config} call-name new-call]
(let [processor-seq (or processor-seq (default-processor-seq))
pre (take-while (where :name not= call-name) processor-seq)
it (filter (where :name = call-name) processor-seq)
post (rest (drop-while (where :name not= call-name) processor-seq))]
(when-not (seq it)
(throw (ex-info (str call-name " call not found.")
{:processor-seq (or processor-seq (default-processor-seq))
:call-name call-name})))
(assoc config :processor-seq
(concat pre it [new-call] post))))
(defn before-call
[{:keys [processor-seq] :as config} call-name new-call]
(let [processor-seq (or processor-seq (default-processor-seq))
pre (take-while (where :name not= call-name) processor-seq)
it (filter (where :name = call-name) processor-seq)
post (rest (drop-while (where :name not= call-name) processor-seq))]
(when-not (seq it)
(throw (ex-info (str call-name " call not found.")
{:processor-seq (or processor-seq (default-processor-seq))
:call-name call-name})))
(assoc config :processor-seq
(concat pre [new-call] it post))))
(defn remove-call
[{:keys [processor-seq] :as config} call-name]
(update config :processor-seq
#(remove
(where :name = call-name)
(or % (default-processor-seq)))))
(defn replace-call
[{:keys [processor-seq] :as config} call-name new-call]
(let [processor-seq (or processor-seq (default-processor-seq))
pre (take-while (where :name not= call-name) processor-seq)
it (filter (where :name = call-name) processor-seq)
post (rest (drop-while (where :name not= call-name) processor-seq))]
(when-not (seq it)
(throw (ex-info (str call-name " call not found.")
{:processor-seq (or processor-seq (default-processor-seq))
:call-name call-name})))
(assoc config :processor-seq
(concat pre [new-call] post))))
(defn fetch [body]
(when body
(cond
(instance? java.io.InputStream body)
(let [^java.io.ByteArrayOutputStream out (java.io.ByteArrayOutputStream.)]
(io/copy body out)
(.toByteArray out))
(string? body)
(let [^String sbody body]
(.getBytes sbody))
:else
body)))
(def byte-array-type
(type (byte-array 0)))
(defn byte-array?
[v]
(= byte-array-type (type v)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ---==| C O N T E X T P R O C E S S I N G |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(comment
;;
;; This is how the context map looks like
;;
{;; contains the compiled boost configuration and the reference to the database
:boost {;; whether of not the cache is enabled
:enabled true/false
;; storage layer configuration
:storage {}
;; profile configuration
:profiles []
;; list of context processing function
:processor-seq []
;; current ring-boost version
:boost-version "x.y.z"
;; database reference
:cache {}
;; compiled processor (from :processor-seq)
:processor fn
}
;; the handler to execute in case of a cache miss
:handler handler-fn
;; the user request
:req {:request-method :get, :uri "/sample", :body nil}
;; the matched boost profile if found, nil otherwise
:cacheable-profile {:enabled true, :cache-for 10, :profile :test,
:match predicate-fn, :matcher fn, :key-maker fn}
;; this is the computed key which identifies this request in the cache
:cache-key "/<KEY>"
;; the response returned by the handler in case of a cache miss
;; or a cached response in cache of cache hit.
:resp {:status 200 :body [bytes] :headers {"etag" "foo"}}
;; whether or not to store the response into the cache
:resp-cacheable? true/false
;; whether or not the response was stored
:stored true/false
;; computed statistics cache hits/misses for the given cache-key
;; and the profile as a whole.
:stats {:key {} :profile {}}
}
)
(defn lift-request
[boost handler]
(fn [req]
{:boost boost :handler handler :req req}))
(defn cacheable-profilie
[{:keys [boost req] :as ctx}]
(assoc ctx :cacheable-profile
(matching-profile (:profiles boost) req)))
(defn request-body-fingerprint
[{:keys [boost cacheable-profile req] :as ctx}]
(if-not cacheable-profile
ctx
(let [body (fetch (:body req))
fingerprint (when (byte-array? body) (digest/md5 body))
normal-body (if (byte-array? body) (java.io.ByteArrayInputStream. body) body)]
(-> ctx
(assoc-in [:req :body] normal-body)
(assoc-in [:req :body-fingerprint] fingerprint)))))
(defn cache-lookup
[{:keys [boost cacheable-profile req] :as ctx}]
(if-not cacheable-profile
ctx
(let [key* (:key-maker cacheable-profile)
key (key* req)]
(assoc ctx
:cached (safely
(sph/get-value (:cache boost) "cache" key)
:on-error
:message "ring-boost cache lookup"
:track-as "ring_boost.cache.lookup"
:default nil)
:cache-key key))))
(defn is-cache-expired?
[{:keys [cacheable-profile cached] :as ctx}]
(if-not cached
ctx
(let [cache-for (:cache-for cacheable-profile)
elapsed (- (System/currentTimeMillis)
(or (:timestamp cached) 0))
expired? (> elapsed (if (= :forever cache-for)
Long/MAX_VALUE (* 1000 cache-for)))]
(if expired?
(dissoc ctx :cached)
ctx))))
(defn is-skip-cache?
[{:keys [req cached] :as ctx}]
(if (and cached (get-in req [:headers "x-cache-skip"] false))
(dissoc ctx :cached)
ctx))
(defn- safe-metric-name
[name]
(-> (str name)
(str/replace #"[^a-zA-Z0-9_]+" "_")
(str/replace #"^_+|_+$" "")))
(defn track-cache-metrics
[{:keys [cacheable-profile cached resp-cacheable?] :as ctx}]
(if cacheable-profile
(let [profile (safe-metric-name (:profile cacheable-profile))]
(if cached
(track-rate (str "ring_boost.profile." profile ".hit_rate"))
(track-rate (str "ring_boost.profile." profile ".miss_rate")))
(when (and (not cached) (not resp-cacheable?))
(track-rate (str "ring_boost.profile." profile ".not_cacheable_rate"))))
(track-rate "ring_boost.no_profile.rate"))
ctx)
(defn- increment-stats-by!
"increments the stats for a given profile/key by the given amount"
[boost {:keys [profile key hit miss not-cacheable]}]
(safely
(sph/transact! (:cache boost)
(fn [tx]
(sph/upsert-value! tx "stats" (str profile ":" key)
(fnil (partial merge-with +) {:profile profile
:key key
:hit 0
:miss 0
:not-cacheable 0})
{:hit hit :miss miss :not-cacheable not-cacheable})
(sph/upsert-value! tx "stats" (str profile)
(fnil (partial merge-with +) {:profile profile
:hit 0
:miss 0
:not-cacheable 0})
{:hit hit :miss miss :not-cacheable not-cacheable})))
:on-error
:max-retry 3
:message "ring-boost update statistics"
:track-as "ring_boost.stats.update"))
(defn- async-do!
"It runs the given function presumably with side effect
without affecting the state of the agent."
[f]
(fn [state & args]
(apply f args)
state))
(defn update-cache-stats
[{:keys [boost cacheable-profile cache-key resp cached resp-cacheable?] :as ctx}]
(when cacheable-profile
;; asynchronously update the stats
(send-off (:async-agent boost)
(async-do! increment-stats-by!) boost
{:profile (:profile cacheable-profile)
:key cache-key
:hit (if cached 1 0)
:miss (if cached 0 1)
:not-cacheable (if (and (not cached) (not resp-cacheable?)) 1 0)}))
ctx)
(defn fetch-cache-stats
[{:keys [boost cacheable-profile cache-key req cached resp-cacheable?] :as ctx}]
(if (and cacheable-profile (get-in req [:headers "x-cache-debug"]))
(safely
(let [profile (:profile cacheable-profile)
stats (sph/get-value (:cache boost) "stats"
(str profile ":" cache-key)
{:profile profile
:key cache-key
:hit 0
:miss 0
:not-cacheable 0})
pstats (sph/get-value (:cache boost) "stats"
(str profile)
{:profile profile
:hit 0
:miss 0
:not-cacheable 0})]
(assoc ctx :stats {:key stats :profile pstats}))
;; if transaction fail, ignore stats update
;; faster times are more important than accurate
;; stats. Maybe consider to update stats async.
:on-error
:default ctx
:message "ring-boost fetch statistics"
:track-as "ring_boost.stats.fecth")
ctx))
(defn fetch-response
[{:keys [req cached handler] :as ctx}]
(assoc ctx :resp (if cached (:payload cached) (handler req))))
(defn response-cacheable?
[{:keys [req resp cached handler] :as ctx}]
(assoc ctx :resp-cacheable?
(and resp (<= 200 (:status resp) 299))))
(defn cache-store!
[{:keys [boost cacheable-profile cache-key resp cached resp-cacheable?] :as ctx}]
;; when the user asked to cache this request
;; and this response didn't come from the cache
;; but it was fetched and the response is cacheable
;; then save it into the cache
(let [stored? (when (and cacheable-profile (not cached) resp-cacheable?)
(let [data {:timestamp (System/currentTimeMillis) :payload resp}]
(safely
(sph/set-value! (:cache boost) "cache" cache-key data)
:on-error
:message "ring-boost cache store"
:track-as "ring_boost.cache.store"
:default false)))]
(assoc ctx :stored (boolean stored?))))
(defn return-response
[{:keys [resp]}]
(if (byte-array? (:body resp))
(update resp :body #(java.io.ByteArrayInputStream. %))
resp))
(defn debug-headers
[{:keys [req cached boost] :as ctx}]
(if (get-in req [:headers "x-cache-debug"])
(update ctx :resp
(fn [resp]
(when resp
(update resp :headers (fnil conj {})
{"X-CACHE" (str "RING-BOOST/v" (:boost-version boost))
"X-RING-BOOST-CACHE" (if (:cached ctx) "CACHE-HIT" "CACHE-MISS")
"X-RING-BOOST-CACHE-PROFILE" (or (str (-> ctx :cacheable-profile :profile)) "unknown")}
(when (:stats ctx)
{"X-RING-BOOST-CACHE-STATS1"
(str/join "/"
[(get-in ctx [:stats :key :hit])
(get-in ctx [:stats :key :miss])
(get-in ctx [:stats :key :not-cacheable])])
"X-RING-BOOST-CACHE-STATS2"
(str/join "/"
[(get-in ctx [:stats :profile :hit])
(get-in ctx [:stats :profile :miss])
(get-in ctx [:stats :profile :not-cacheable])])})))))
ctx))
(defn debug-print-context
[ctx]
(pprint ctx)
ctx)
(defn response-body-normalize
[{:keys [cacheable-profile resp cached] :as ctx}]
(if-not (and cacheable-profile (not cached) (:body resp))
ctx
(cond
(instance? java.io.InputStream (:body resp))
(update-in ctx [:resp :body] fetch)
(string? (:body resp))
(update-in ctx [:resp :body]
(fn [^String body] (.getBytes body)))
:else
ctx)))
(defn add-cache-headers
[{:keys [resp] :as ctx}]
(if (and (byte-array? (get resp :body))
(not (or (get-in resp [:headers "etag"])
(get-in resp [:headers "ETag"]))))
(assoc-in ctx [:resp :headers "etag"]
(digest/md5 (get resp :body)))
ctx))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ----==| D E F A U L T C O N F I G U R A T I O N |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn default-processor-seq []
[{:name :lift-request }
{:name :cacheable-profilie :call cacheable-profilie}
{:name :request-body-fingerprint :call request-body-fingerprint}
{:name :cache-lookup :call cache-lookup }
{:name :is-cache-expired? :call is-cache-expired? }
{:name :is-skip-cache? :call is-skip-cache? }
{:name :fetch-response :call fetch-response }
{:name :response-cacheable? :call response-cacheable?}
{:name :response-body-normalize :call response-body-normalize}
{:name :add-cache-headers :call add-cache-headers }
{:name :cache-store! :call cache-store! }
{:name :track-cache-metrics :call track-cache-metrics}
{:name :update-cache-stats :call update-cache-stats}
{:name :fetch-cache-stats :call fetch-cache-stats }
{:name :debug-headers :call debug-headers }
{:name :return-response :call return-response }])
(def ^:const default-profile-config
{;; whether or not this profile is enabled
;; when disabled it won't be considered at all
:enabled true
;; profile name is (REQUIRED)
;;:profile :this-profile
;; match specification (REQUIRED)
;; :match [:and
;; [:uri :starts-with? "/something/cacheable/"]
;; [:request-method = :get]]
;; the duration in seconds for how long ring-boost should
;; serve the item from the cache if present
;; use `:forever` to cache immutable responses
;; default 0
:cache-for 0})
(def default-boost-config
{;; Whether the ring-boost cache is enabled or not.
;; when not enabled the handler will behave as if
;; the ring-boost wasn't there at all.
:enabled true
;; cache storage configuration
:storage {:sophia.path "/tmp/ring-boost-cache" :dbs ["cache" "stats"]}
;; caching profiles. see `default-profile-config`
:profiles []
;; sequence of processing function for this boost configuration
;; unless specified differently in a caching profile
;; this one will be used.
:processor-seq (default-processor-seq)
;; agent for async operations
;; like updating the stats
:async-agent (agent {})
})
(defn deep-merge
"Like merge, but merges maps recursively."
[& maps]
(let [maps (filter (comp not nil?) maps)]
(if (every? map? maps)
(apply merge-with deep-merge maps)
(last maps))))
(defn- apply-defaults
[config]
(-> (deep-merge default-boost-config config)
(update :profiles (partial mapv (partial deep-merge default-profile-config)))))
(defn ring-boost
[handler boost-config]
(let [{:keys [enabled] :as conf}
(-> boost-config apply-defaults compile-configuration)]
(if-not enabled
;; if boost is not enabled, then just return the handler
handler
(let [processor (comp (:processor conf) (lift-request conf handler))]
(fn [req]
(processor req))))))
| true | (ns com.brunobonacci.ring-boost.core
(:require [clojure.java.io :as io]
[clojure.pprint :refer [pprint]]
[clojure.string :as str]
[com.brunobonacci.sophia :as sph]
[pandect.algo.md5 :as digest]
[safely.core :refer [safely]]
[samsara.trackit :refer [track-rate]]
[where.core :refer [where]])
(:import [java.io ByteArrayInputStream ByteArrayOutputStream InputStream]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ---==| B U I L D I N G F U N C T I O N S |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^:const default-keys
[:uri :request-method :server-name :server-port :query-string :body-fingerprint])
(defn build-matcher
[{:keys [match matcher] :as profile}]
(if matcher
profile
(assoc profile :matcher (where match))))
(defn matching-profile
[profiles request]
(some (fn [{:keys [matcher] :as p}]
(when (and matcher (matcher request))
p)) profiles))
(defn make-key
[segments]
(->> segments
(map (fn [k]
(if (vector? k)
#(get-in % k)
#(get % k))))
(apply juxt)
(comp (partial str/join "|"))))
(defn build-key-maker
[{:keys [keys key-maker] :as profile}]
(if key-maker
profile
(assoc profile :key-maker (make-key (or keys default-keys)))))
(defn build-profiles
[profiles]
(mapv
(comp build-key-maker
build-matcher)
(filter :enabled profiles)))
(defn load-version
[config]
(assoc config :boost-version
(safely
(str/trim (slurp (io/resource "ring-boost.version")))
:on-error
:default "v???")))
(defn compile-processor
[{:keys [processor-seq] :as boost-config}]
(->> (drop 1 processor-seq)
reverse
(map :call)
(apply comp)))
(defn debug-compile-processor
[{:keys [processor-seq] :as boost-config}]
(->> processor-seq
(map (fn [{:keys [name call]}]
{:name name
:call (fn [ctx]
(println "calling: " name)
(call ctx))}))
(drop 1)
reverse
(map :call)
(apply comp)))
(defn compile-configuration
[boost-config]
(as-> boost-config $
(load-version $)
(update $ :profiles build-profiles)
(assoc $ :cache
(sph/sophia (:storage $)))
(assoc $ :processor (compile-processor $))))
;; defined later
(declare default-processor-seq)
(defn after-call
[{:keys [processor-seq] :as config} call-name new-call]
(let [processor-seq (or processor-seq (default-processor-seq))
pre (take-while (where :name not= call-name) processor-seq)
it (filter (where :name = call-name) processor-seq)
post (rest (drop-while (where :name not= call-name) processor-seq))]
(when-not (seq it)
(throw (ex-info (str call-name " call not found.")
{:processor-seq (or processor-seq (default-processor-seq))
:call-name call-name})))
(assoc config :processor-seq
(concat pre it [new-call] post))))
(defn before-call
[{:keys [processor-seq] :as config} call-name new-call]
(let [processor-seq (or processor-seq (default-processor-seq))
pre (take-while (where :name not= call-name) processor-seq)
it (filter (where :name = call-name) processor-seq)
post (rest (drop-while (where :name not= call-name) processor-seq))]
(when-not (seq it)
(throw (ex-info (str call-name " call not found.")
{:processor-seq (or processor-seq (default-processor-seq))
:call-name call-name})))
(assoc config :processor-seq
(concat pre [new-call] it post))))
(defn remove-call
[{:keys [processor-seq] :as config} call-name]
(update config :processor-seq
#(remove
(where :name = call-name)
(or % (default-processor-seq)))))
(defn replace-call
[{:keys [processor-seq] :as config} call-name new-call]
(let [processor-seq (or processor-seq (default-processor-seq))
pre (take-while (where :name not= call-name) processor-seq)
it (filter (where :name = call-name) processor-seq)
post (rest (drop-while (where :name not= call-name) processor-seq))]
(when-not (seq it)
(throw (ex-info (str call-name " call not found.")
{:processor-seq (or processor-seq (default-processor-seq))
:call-name call-name})))
(assoc config :processor-seq
(concat pre [new-call] post))))
(defn fetch [body]
(when body
(cond
(instance? java.io.InputStream body)
(let [^java.io.ByteArrayOutputStream out (java.io.ByteArrayOutputStream.)]
(io/copy body out)
(.toByteArray out))
(string? body)
(let [^String sbody body]
(.getBytes sbody))
:else
body)))
(def byte-array-type
(type (byte-array 0)))
(defn byte-array?
[v]
(= byte-array-type (type v)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ---==| C O N T E X T P R O C E S S I N G |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(comment
;;
;; This is how the context map looks like
;;
{;; contains the compiled boost configuration and the reference to the database
:boost {;; whether of not the cache is enabled
:enabled true/false
;; storage layer configuration
:storage {}
;; profile configuration
:profiles []
;; list of context processing function
:processor-seq []
;; current ring-boost version
:boost-version "x.y.z"
;; database reference
:cache {}
;; compiled processor (from :processor-seq)
:processor fn
}
;; the handler to execute in case of a cache miss
:handler handler-fn
;; the user request
:req {:request-method :get, :uri "/sample", :body nil}
;; the matched boost profile if found, nil otherwise
:cacheable-profile {:enabled true, :cache-for 10, :profile :test,
:match predicate-fn, :matcher fn, :key-maker fn}
;; this is the computed key which identifies this request in the cache
:cache-key "/PI:KEY:<KEY>END_PI"
;; the response returned by the handler in case of a cache miss
;; or a cached response in cache of cache hit.
:resp {:status 200 :body [bytes] :headers {"etag" "foo"}}
;; whether or not to store the response into the cache
:resp-cacheable? true/false
;; whether or not the response was stored
:stored true/false
;; computed statistics cache hits/misses for the given cache-key
;; and the profile as a whole.
:stats {:key {} :profile {}}
}
)
(defn lift-request
[boost handler]
(fn [req]
{:boost boost :handler handler :req req}))
(defn cacheable-profilie
[{:keys [boost req] :as ctx}]
(assoc ctx :cacheable-profile
(matching-profile (:profiles boost) req)))
(defn request-body-fingerprint
[{:keys [boost cacheable-profile req] :as ctx}]
(if-not cacheable-profile
ctx
(let [body (fetch (:body req))
fingerprint (when (byte-array? body) (digest/md5 body))
normal-body (if (byte-array? body) (java.io.ByteArrayInputStream. body) body)]
(-> ctx
(assoc-in [:req :body] normal-body)
(assoc-in [:req :body-fingerprint] fingerprint)))))
(defn cache-lookup
[{:keys [boost cacheable-profile req] :as ctx}]
(if-not cacheable-profile
ctx
(let [key* (:key-maker cacheable-profile)
key (key* req)]
(assoc ctx
:cached (safely
(sph/get-value (:cache boost) "cache" key)
:on-error
:message "ring-boost cache lookup"
:track-as "ring_boost.cache.lookup"
:default nil)
:cache-key key))))
(defn is-cache-expired?
[{:keys [cacheable-profile cached] :as ctx}]
(if-not cached
ctx
(let [cache-for (:cache-for cacheable-profile)
elapsed (- (System/currentTimeMillis)
(or (:timestamp cached) 0))
expired? (> elapsed (if (= :forever cache-for)
Long/MAX_VALUE (* 1000 cache-for)))]
(if expired?
(dissoc ctx :cached)
ctx))))
(defn is-skip-cache?
[{:keys [req cached] :as ctx}]
(if (and cached (get-in req [:headers "x-cache-skip"] false))
(dissoc ctx :cached)
ctx))
(defn- safe-metric-name
[name]
(-> (str name)
(str/replace #"[^a-zA-Z0-9_]+" "_")
(str/replace #"^_+|_+$" "")))
(defn track-cache-metrics
[{:keys [cacheable-profile cached resp-cacheable?] :as ctx}]
(if cacheable-profile
(let [profile (safe-metric-name (:profile cacheable-profile))]
(if cached
(track-rate (str "ring_boost.profile." profile ".hit_rate"))
(track-rate (str "ring_boost.profile." profile ".miss_rate")))
(when (and (not cached) (not resp-cacheable?))
(track-rate (str "ring_boost.profile." profile ".not_cacheable_rate"))))
(track-rate "ring_boost.no_profile.rate"))
ctx)
(defn- increment-stats-by!
"increments the stats for a given profile/key by the given amount"
[boost {:keys [profile key hit miss not-cacheable]}]
(safely
(sph/transact! (:cache boost)
(fn [tx]
(sph/upsert-value! tx "stats" (str profile ":" key)
(fnil (partial merge-with +) {:profile profile
:key key
:hit 0
:miss 0
:not-cacheable 0})
{:hit hit :miss miss :not-cacheable not-cacheable})
(sph/upsert-value! tx "stats" (str profile)
(fnil (partial merge-with +) {:profile profile
:hit 0
:miss 0
:not-cacheable 0})
{:hit hit :miss miss :not-cacheable not-cacheable})))
:on-error
:max-retry 3
:message "ring-boost update statistics"
:track-as "ring_boost.stats.update"))
(defn- async-do!
"It runs the given function presumably with side effect
without affecting the state of the agent."
[f]
(fn [state & args]
(apply f args)
state))
(defn update-cache-stats
[{:keys [boost cacheable-profile cache-key resp cached resp-cacheable?] :as ctx}]
(when cacheable-profile
;; asynchronously update the stats
(send-off (:async-agent boost)
(async-do! increment-stats-by!) boost
{:profile (:profile cacheable-profile)
:key cache-key
:hit (if cached 1 0)
:miss (if cached 0 1)
:not-cacheable (if (and (not cached) (not resp-cacheable?)) 1 0)}))
ctx)
(defn fetch-cache-stats
[{:keys [boost cacheable-profile cache-key req cached resp-cacheable?] :as ctx}]
(if (and cacheable-profile (get-in req [:headers "x-cache-debug"]))
(safely
(let [profile (:profile cacheable-profile)
stats (sph/get-value (:cache boost) "stats"
(str profile ":" cache-key)
{:profile profile
:key cache-key
:hit 0
:miss 0
:not-cacheable 0})
pstats (sph/get-value (:cache boost) "stats"
(str profile)
{:profile profile
:hit 0
:miss 0
:not-cacheable 0})]
(assoc ctx :stats {:key stats :profile pstats}))
;; if transaction fail, ignore stats update
;; faster times are more important than accurate
;; stats. Maybe consider to update stats async.
:on-error
:default ctx
:message "ring-boost fetch statistics"
:track-as "ring_boost.stats.fecth")
ctx))
(defn fetch-response
[{:keys [req cached handler] :as ctx}]
(assoc ctx :resp (if cached (:payload cached) (handler req))))
(defn response-cacheable?
[{:keys [req resp cached handler] :as ctx}]
(assoc ctx :resp-cacheable?
(and resp (<= 200 (:status resp) 299))))
(defn cache-store!
[{:keys [boost cacheable-profile cache-key resp cached resp-cacheable?] :as ctx}]
;; when the user asked to cache this request
;; and this response didn't come from the cache
;; but it was fetched and the response is cacheable
;; then save it into the cache
(let [stored? (when (and cacheable-profile (not cached) resp-cacheable?)
(let [data {:timestamp (System/currentTimeMillis) :payload resp}]
(safely
(sph/set-value! (:cache boost) "cache" cache-key data)
:on-error
:message "ring-boost cache store"
:track-as "ring_boost.cache.store"
:default false)))]
(assoc ctx :stored (boolean stored?))))
(defn return-response
[{:keys [resp]}]
(if (byte-array? (:body resp))
(update resp :body #(java.io.ByteArrayInputStream. %))
resp))
(defn debug-headers
[{:keys [req cached boost] :as ctx}]
(if (get-in req [:headers "x-cache-debug"])
(update ctx :resp
(fn [resp]
(when resp
(update resp :headers (fnil conj {})
{"X-CACHE" (str "RING-BOOST/v" (:boost-version boost))
"X-RING-BOOST-CACHE" (if (:cached ctx) "CACHE-HIT" "CACHE-MISS")
"X-RING-BOOST-CACHE-PROFILE" (or (str (-> ctx :cacheable-profile :profile)) "unknown")}
(when (:stats ctx)
{"X-RING-BOOST-CACHE-STATS1"
(str/join "/"
[(get-in ctx [:stats :key :hit])
(get-in ctx [:stats :key :miss])
(get-in ctx [:stats :key :not-cacheable])])
"X-RING-BOOST-CACHE-STATS2"
(str/join "/"
[(get-in ctx [:stats :profile :hit])
(get-in ctx [:stats :profile :miss])
(get-in ctx [:stats :profile :not-cacheable])])})))))
ctx))
(defn debug-print-context
[ctx]
(pprint ctx)
ctx)
(defn response-body-normalize
[{:keys [cacheable-profile resp cached] :as ctx}]
(if-not (and cacheable-profile (not cached) (:body resp))
ctx
(cond
(instance? java.io.InputStream (:body resp))
(update-in ctx [:resp :body] fetch)
(string? (:body resp))
(update-in ctx [:resp :body]
(fn [^String body] (.getBytes body)))
:else
ctx)))
(defn add-cache-headers
[{:keys [resp] :as ctx}]
(if (and (byte-array? (get resp :body))
(not (or (get-in resp [:headers "etag"])
(get-in resp [:headers "ETag"]))))
(assoc-in ctx [:resp :headers "etag"]
(digest/md5 (get resp :body)))
ctx))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ----==| D E F A U L T C O N F I G U R A T I O N |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn default-processor-seq []
[{:name :lift-request }
{:name :cacheable-profilie :call cacheable-profilie}
{:name :request-body-fingerprint :call request-body-fingerprint}
{:name :cache-lookup :call cache-lookup }
{:name :is-cache-expired? :call is-cache-expired? }
{:name :is-skip-cache? :call is-skip-cache? }
{:name :fetch-response :call fetch-response }
{:name :response-cacheable? :call response-cacheable?}
{:name :response-body-normalize :call response-body-normalize}
{:name :add-cache-headers :call add-cache-headers }
{:name :cache-store! :call cache-store! }
{:name :track-cache-metrics :call track-cache-metrics}
{:name :update-cache-stats :call update-cache-stats}
{:name :fetch-cache-stats :call fetch-cache-stats }
{:name :debug-headers :call debug-headers }
{:name :return-response :call return-response }])
(def ^:const default-profile-config
{;; whether or not this profile is enabled
;; when disabled it won't be considered at all
:enabled true
;; profile name is (REQUIRED)
;;:profile :this-profile
;; match specification (REQUIRED)
;; :match [:and
;; [:uri :starts-with? "/something/cacheable/"]
;; [:request-method = :get]]
;; the duration in seconds for how long ring-boost should
;; serve the item from the cache if present
;; use `:forever` to cache immutable responses
;; default 0
:cache-for 0})
(def default-boost-config
{;; Whether the ring-boost cache is enabled or not.
;; when not enabled the handler will behave as if
;; the ring-boost wasn't there at all.
:enabled true
;; cache storage configuration
:storage {:sophia.path "/tmp/ring-boost-cache" :dbs ["cache" "stats"]}
;; caching profiles. see `default-profile-config`
:profiles []
;; sequence of processing function for this boost configuration
;; unless specified differently in a caching profile
;; this one will be used.
:processor-seq (default-processor-seq)
;; agent for async operations
;; like updating the stats
:async-agent (agent {})
})
(defn deep-merge
"Like merge, but merges maps recursively."
[& maps]
(let [maps (filter (comp not nil?) maps)]
(if (every? map? maps)
(apply merge-with deep-merge maps)
(last maps))))
(defn- apply-defaults
[config]
(-> (deep-merge default-boost-config config)
(update :profiles (partial mapv (partial deep-merge default-profile-config)))))
(defn ring-boost
[handler boost-config]
(let [{:keys [enabled] :as conf}
(-> boost-config apply-defaults compile-configuration)]
(if-not enabled
;; if boost is not enabled, then just return the handler
handler
(let [processor (comp (:processor conf) (lift-request conf handler))]
(fn [req]
(processor req))))))
|
[
{
"context": "nv v v')))))))\n\n(comment\n (def db\n [[0 :name \"Peter\"]\n [0 :age 40]\n [0 :likes \"Pizza\"]\n [",
"end": 2221,
"score": 0.9989039897918701,
"start": 2216,
"tag": "NAME",
"value": "Peter"
},
{
"context": "0 :age 40]\n [0 :likes \"Pizza\"]\n [1 :name \"Erik\"]\n [1 :likes \"Pizza\"]\n [1 :age 30]\n [",
"end": 2284,
"score": 0.9991365671157837,
"start": 2280,
"tag": "NAME",
"value": "Erik"
}
] | src/clj/lhrb/engine.clj | lhrb/datahog | 3 | (ns lhrb.engine
(:refer-clojure :exclude [==])
(:require [clojure.string :as str]
[clojure.core.match :refer [match]]
[lhrb.ukanren :as k :refer [lvar? walk unify == conj' disj' conj+ disj+ take-all bind]]))
(defn create-index
"creates an index from eav data
(create-index [[e a v] ...] 0 1)
=> {e {a #{[e a v] ...}}}"
[data idx1 idx2]
(->> data
(reduce
(fn [index elem]
(update-in index
[(get elem idx1) (get elem idx2)]
(fnil conj #{}) elem))
{})))
(comment
(create-index [[1 2 3] [1 2 4]] 0 1)
,)
(def mem-index (memoize create-index))
(defn for-index
"retrieves data from memoized index-fn"
([db idx1 idx2 e]
(->> (get-in (mem-index db idx1 idx2) [e])
(mapcat (fn [[_ v]] v))
;; remove into?
(into #{})))
([db idx1 idx2 e1 e2]
(get-in (mem-index db idx1 idx2) [e1 e2])))
(comment
(k/lcons
(for [[_ _ c] (for-index [[1 2 3] [1 2 4] [2 3 5]] 0 1 1)]
(unify {} c 'a)))
(get-in [[1] 2 3] [0 0])
,)
(defn grounded? [x]
(not (lvar? x)))
(defn q-db [db e a v]
(fn [env]
(k/lcons
(let [e' (walk env e)
a' (walk env a)
v' (walk env v)]
(case [(grounded? e') (grounded? a') (grounded? v')]
[false true true] (for [[e _ _] (for-index db 1 2 a' v')]
(unify env e e'))
[true false true] (for [[_ a _] (for-index db 0 2 e' v')]
(unify env a a'))
[true true false] (for [[_ _ v] (for-index db 0 1 e' a')]
(unify env v v'))
[true false false] (for [[_ a v] (for-index db 0 1 e')]
(-> env (unify a a') (unify v v')))
[false true false] (for [[e _ v] (for-index db 1 2 a')]
(-> env (unify e e') (unify v v')))
[false false true] (for [[e a _] (for-index db 2 1 v')]
(-> env (unify e e') (unify a a')))
[true true true] (for [[_ _ v] (for-index db 0 1 e' a')]
(unify env v v')))))))
(comment
(def db
[[0 :name "Peter"]
[0 :age 40]
[0 :likes "Pizza"]
[1 :name "Erik"]
[1 :likes "Pizza"]
[1 :age 30]
[2 :age 40]
[2 :likes "Pizza"]])
(take-all
((conj+
(q-db db 'a :likes "Pizza")
(q-db db 'a :age 40)) {}))
(bind '({a 2} {a 1} {a 0}) (q-db db 'a :age 40))
((q-db db 'a :age 40) {'a 1})
((q-db db 'a :likes "Pizza") {})
((q-db db 'a :likes "Pizza") {})
(require '[lhrb.readcsv :refer [create-got-db]])
(def db (create-got-db))
(count db)
'(:battle/attacker_commander
:battle/defender_1
:battle/attacker_size
:battle/attacker_4
:battle/defender_king
:battle/attacker_2
:battle/year
:battle/name
:battle/attacker_3
:battle/summer
:battle/location
:battle/attacker_king
:battle/defender_2
:battle/battle_number
:battle/region
:battle/defender_commander
:battle/attacker_1
:battle/defender_size
:battle/major_capture
:battle/battle_type
:battle/major_death
:battle/attacker_outcome
:battle/note
:char/Gender
:char/Name
:char/Nobility
:char/Allegiances
:char/DeathYear)
(take-all
((conj+
(q-db db 'battle :battle/battle_type 'type)) {}))
(time (take-all
((conj+
(q-db db 'battle :battle/battle_type "ambush")
(q-db db 'battle :battle/attacker_commander 'names)
(q-db db 'person :char/Name 'names)
(q-db db 'person :char/Allegiances 'house)) {})))
;; define a rule
(defn house-attacking-commander [db ?battle]
(conj+
(q-db db ?battle :battle/attacker_commander 'names)
(q-db db 'person :char/Name 'names)
(q-db db 'person :char/Allegiances 'house)))
(take-all
((conj+
(q-db db 'battle :battle/battle_type "ambush")
(house-attacking-commander db 'battle)) {}))
(take-all
((conj+
(q-db db 'battle :battle/battle_type "ambush")
(q-db db 'battle :battle/year 'byear)
(disj+
(q-db db 'battle :battle/attacker_commander 'names)
(q-db db 'battle :battle/defending_commander 'names))) {}))
,)
(defn reify-var [& vars]
(fn [env-stream] ;; maybe don't return a fn?
(->> env-stream
(mapv
(fn [env]
(mapv ;; extract and use juxt?
(fn [var] (walk env var)) vars))))))
(defmacro run [& clauses]
`(take-all
((conj+ ~@clauses) {})))
(defn run [& clauses]
(->> [{}]
((apply conj' clauses))))
(comment
"experiment with juxt ((juxt a b c) x) => [(a x) (b x) (c x)]
more concise vs readability?"
(let [extract (fn [var]
(fn [env] (walk env var)))]
(->> [{'a 1 'b 2} {'a 3 'b 4 'c 5} {'a 4 'b 10}]
(map
(apply juxt (map extract ['a 'b])))))
(run
;(reify-var 'names 'house)
(q-db db 'battle :battle/battle_type "ambush")
(q-db db 'battle :battle/attacker_commander 'names)
(q-db db 'person :char/Name 'names)
(q-db db 'person :char/Allegiances 'house))
,)
(defn filtero [op ?var c]
(fn [envs]
(->> envs
(filter
(fn [env] (op (walk env ?var) c))))))
(defn substitutions [clause db]
(match [clause]
;; [?e :age (> ?a 10)]
[[e a ([(op :guard #{'= '> '>= '< '<=}) var value] :seq)]]
`[(filtero ~op ~var ~value)
(q-db ~db ~e ~a ~var)]
;; [?e :age (or 10 15)]
;; TODO find a good way to make it work on all pos
[[e a (['or & cases] :seq)]]
(let [c-cases (map
(fn [v] `(q-db ~db ~e ~a ~v))
cases)]
`[(disj' ~@c-cases)])
;; [?e :age 10]
[[e a v]]
`(q-db ~db ~e ~a ~v)
:else clause))
(defn compile-where-clauses
"transforms vector clauses into q-db queries
e.g. [?a :age 10] => (q-db db ?a :age 10)
added
[?e :age (> ?age 10)]
=> ((filtero > ?age 10) (q-db db ?a :age ?age))"
[clauses db]
(->> clauses
(map (fn [clause] (substitutions clause db)))
(reduce (fn [acc e] (if (vector? e)
(into acc e)
(conj acc e)))
[])))
(defn find-lvars
"finds and returns all unique logic-variables.
A logic var begins with an '?'"
[find where] ;; maybe decouple from concrete impl?
(->> (into find where)
(flatten)
(filter
(fn [s]
(and
(lvar? s)
(str/starts-with? (str s) "?"))))
(distinct)))
#_(defmacro fresh [expr]
(let [lvars (find-lvars expr)
]))
(defn reify [vars result]
(->> result
(mapv (fn [env]
(mapv (fn [var] (walk env var)) vars)))))
;; TODO add _ as don't care
(defmacro q [{:keys [find where]} db]
(let [;; test if vars in find clause are also in where clause
lvars (find-lvars find where)
where-compiled (compile-where-clauses where db)]
`(let [~@(interleave lvars (map
(fn [sym]
`(gensym ~(name sym)))
lvars))]
(reify ~find (run ~@where-compiled)))))
(comment
(macroexpand
'(q {:find [?name ?noble]
:where [[?b :battle/location "Storm's End"]
[?b :battle/defender_commander ?name]
[?p :char/Name ?name]
[?p :char/Nobility ?noble]]}
db))
(q {:find [?name ?noble]
:where [[?b :battle/location "Storm's End"]
[?b :battle/defender_commander ?name]
[?p :char/Name ?name]
[?p :char/Nobility ?noble]]}
db)
(macroexpand
'(q {:find [?num]
:where [[?b :battle/attacker_size (> ?num 100)]]}
db))
(q {:find [?name ?num]
:where [[?b :battle/name ?name]
[?b :battle/attacker_size (> ?num 100)]]}
db)
*e
;; see filtero now
(defn gr-th [?is count]
(fn [envs]
(->> envs
(filter
(fn [env] (> (walk env ?is) count))))))
(->> [{'?is 300} {'?is 150} {'?is 350}]
((disj'
(== '?is 150)
(gr-th '?is 200))))
,)
(defn missing?
"Keeps envs where the given attribute is missing.
?e needs to be ground when walking an enviroment i.e.
all envs getting thrown away if ?e is not in the env"
[db ?e attr]
(fn [envs]
(->> envs
(filter
(fn [env]
(some? (for-index db 0 1 (walk env ?e) attr)))))))
(comment
(q {:find [?name]
:where [(missing? db ?e :char/DeathYear)
[?e :char/Name ?name]]}
db)
(= #{}
(clojure.set/difference
(into #{}
(q {:find [?name]
:where [[?e :char/Name ?name]
[?e :char/DeathYear ?d]]}
db))
(into #{}
(q {:find [?name]
:where [(missing? db ?e :char/DeathYear)
[?e :char/Name ?name]]}
db))))
(q {:find [?e]
:where [[?e :char/Name (or "Randa" "Drogo")]]}
db)
(q {:find [?e]
:where [[?e :char/Name (or (if true "Randa" nil) "Drogo")]]}
db)
;; try recursive rule
(def db
[[0 :name "North America"]
[1 :name "United State"]
[1 :within 0]
[2 :name "Idaho"]
[2 :within 1]])
(defn within-recursive [db ?location ?name]
(conj'
(q-db db )))
,)
#_(eval (clojure.edn/read-string "(q {:find [?e]
:where [[?e :char/Name (or (if true \"Randa\" nil) \"Drogo\")]]}
db)"))
| 8494 | (ns lhrb.engine
(:refer-clojure :exclude [==])
(:require [clojure.string :as str]
[clojure.core.match :refer [match]]
[lhrb.ukanren :as k :refer [lvar? walk unify == conj' disj' conj+ disj+ take-all bind]]))
(defn create-index
"creates an index from eav data
(create-index [[e a v] ...] 0 1)
=> {e {a #{[e a v] ...}}}"
[data idx1 idx2]
(->> data
(reduce
(fn [index elem]
(update-in index
[(get elem idx1) (get elem idx2)]
(fnil conj #{}) elem))
{})))
(comment
(create-index [[1 2 3] [1 2 4]] 0 1)
,)
(def mem-index (memoize create-index))
(defn for-index
"retrieves data from memoized index-fn"
([db idx1 idx2 e]
(->> (get-in (mem-index db idx1 idx2) [e])
(mapcat (fn [[_ v]] v))
;; remove into?
(into #{})))
([db idx1 idx2 e1 e2]
(get-in (mem-index db idx1 idx2) [e1 e2])))
(comment
(k/lcons
(for [[_ _ c] (for-index [[1 2 3] [1 2 4] [2 3 5]] 0 1 1)]
(unify {} c 'a)))
(get-in [[1] 2 3] [0 0])
,)
(defn grounded? [x]
(not (lvar? x)))
(defn q-db [db e a v]
(fn [env]
(k/lcons
(let [e' (walk env e)
a' (walk env a)
v' (walk env v)]
(case [(grounded? e') (grounded? a') (grounded? v')]
[false true true] (for [[e _ _] (for-index db 1 2 a' v')]
(unify env e e'))
[true false true] (for [[_ a _] (for-index db 0 2 e' v')]
(unify env a a'))
[true true false] (for [[_ _ v] (for-index db 0 1 e' a')]
(unify env v v'))
[true false false] (for [[_ a v] (for-index db 0 1 e')]
(-> env (unify a a') (unify v v')))
[false true false] (for [[e _ v] (for-index db 1 2 a')]
(-> env (unify e e') (unify v v')))
[false false true] (for [[e a _] (for-index db 2 1 v')]
(-> env (unify e e') (unify a a')))
[true true true] (for [[_ _ v] (for-index db 0 1 e' a')]
(unify env v v')))))))
(comment
(def db
[[0 :name "<NAME>"]
[0 :age 40]
[0 :likes "Pizza"]
[1 :name "<NAME>"]
[1 :likes "Pizza"]
[1 :age 30]
[2 :age 40]
[2 :likes "Pizza"]])
(take-all
((conj+
(q-db db 'a :likes "Pizza")
(q-db db 'a :age 40)) {}))
(bind '({a 2} {a 1} {a 0}) (q-db db 'a :age 40))
((q-db db 'a :age 40) {'a 1})
((q-db db 'a :likes "Pizza") {})
((q-db db 'a :likes "Pizza") {})
(require '[lhrb.readcsv :refer [create-got-db]])
(def db (create-got-db))
(count db)
'(:battle/attacker_commander
:battle/defender_1
:battle/attacker_size
:battle/attacker_4
:battle/defender_king
:battle/attacker_2
:battle/year
:battle/name
:battle/attacker_3
:battle/summer
:battle/location
:battle/attacker_king
:battle/defender_2
:battle/battle_number
:battle/region
:battle/defender_commander
:battle/attacker_1
:battle/defender_size
:battle/major_capture
:battle/battle_type
:battle/major_death
:battle/attacker_outcome
:battle/note
:char/Gender
:char/Name
:char/Nobility
:char/Allegiances
:char/DeathYear)
(take-all
((conj+
(q-db db 'battle :battle/battle_type 'type)) {}))
(time (take-all
((conj+
(q-db db 'battle :battle/battle_type "ambush")
(q-db db 'battle :battle/attacker_commander 'names)
(q-db db 'person :char/Name 'names)
(q-db db 'person :char/Allegiances 'house)) {})))
;; define a rule
(defn house-attacking-commander [db ?battle]
(conj+
(q-db db ?battle :battle/attacker_commander 'names)
(q-db db 'person :char/Name 'names)
(q-db db 'person :char/Allegiances 'house)))
(take-all
((conj+
(q-db db 'battle :battle/battle_type "ambush")
(house-attacking-commander db 'battle)) {}))
(take-all
((conj+
(q-db db 'battle :battle/battle_type "ambush")
(q-db db 'battle :battle/year 'byear)
(disj+
(q-db db 'battle :battle/attacker_commander 'names)
(q-db db 'battle :battle/defending_commander 'names))) {}))
,)
(defn reify-var [& vars]
(fn [env-stream] ;; maybe don't return a fn?
(->> env-stream
(mapv
(fn [env]
(mapv ;; extract and use juxt?
(fn [var] (walk env var)) vars))))))
(defmacro run [& clauses]
`(take-all
((conj+ ~@clauses) {})))
(defn run [& clauses]
(->> [{}]
((apply conj' clauses))))
(comment
"experiment with juxt ((juxt a b c) x) => [(a x) (b x) (c x)]
more concise vs readability?"
(let [extract (fn [var]
(fn [env] (walk env var)))]
(->> [{'a 1 'b 2} {'a 3 'b 4 'c 5} {'a 4 'b 10}]
(map
(apply juxt (map extract ['a 'b])))))
(run
;(reify-var 'names 'house)
(q-db db 'battle :battle/battle_type "ambush")
(q-db db 'battle :battle/attacker_commander 'names)
(q-db db 'person :char/Name 'names)
(q-db db 'person :char/Allegiances 'house))
,)
(defn filtero [op ?var c]
(fn [envs]
(->> envs
(filter
(fn [env] (op (walk env ?var) c))))))
(defn substitutions [clause db]
(match [clause]
;; [?e :age (> ?a 10)]
[[e a ([(op :guard #{'= '> '>= '< '<=}) var value] :seq)]]
`[(filtero ~op ~var ~value)
(q-db ~db ~e ~a ~var)]
;; [?e :age (or 10 15)]
;; TODO find a good way to make it work on all pos
[[e a (['or & cases] :seq)]]
(let [c-cases (map
(fn [v] `(q-db ~db ~e ~a ~v))
cases)]
`[(disj' ~@c-cases)])
;; [?e :age 10]
[[e a v]]
`(q-db ~db ~e ~a ~v)
:else clause))
(defn compile-where-clauses
"transforms vector clauses into q-db queries
e.g. [?a :age 10] => (q-db db ?a :age 10)
added
[?e :age (> ?age 10)]
=> ((filtero > ?age 10) (q-db db ?a :age ?age))"
[clauses db]
(->> clauses
(map (fn [clause] (substitutions clause db)))
(reduce (fn [acc e] (if (vector? e)
(into acc e)
(conj acc e)))
[])))
(defn find-lvars
"finds and returns all unique logic-variables.
A logic var begins with an '?'"
[find where] ;; maybe decouple from concrete impl?
(->> (into find where)
(flatten)
(filter
(fn [s]
(and
(lvar? s)
(str/starts-with? (str s) "?"))))
(distinct)))
#_(defmacro fresh [expr]
(let [lvars (find-lvars expr)
]))
(defn reify [vars result]
(->> result
(mapv (fn [env]
(mapv (fn [var] (walk env var)) vars)))))
;; TODO add _ as don't care
(defmacro q [{:keys [find where]} db]
(let [;; test if vars in find clause are also in where clause
lvars (find-lvars find where)
where-compiled (compile-where-clauses where db)]
`(let [~@(interleave lvars (map
(fn [sym]
`(gensym ~(name sym)))
lvars))]
(reify ~find (run ~@where-compiled)))))
(comment
(macroexpand
'(q {:find [?name ?noble]
:where [[?b :battle/location "Storm's End"]
[?b :battle/defender_commander ?name]
[?p :char/Name ?name]
[?p :char/Nobility ?noble]]}
db))
(q {:find [?name ?noble]
:where [[?b :battle/location "Storm's End"]
[?b :battle/defender_commander ?name]
[?p :char/Name ?name]
[?p :char/Nobility ?noble]]}
db)
(macroexpand
'(q {:find [?num]
:where [[?b :battle/attacker_size (> ?num 100)]]}
db))
(q {:find [?name ?num]
:where [[?b :battle/name ?name]
[?b :battle/attacker_size (> ?num 100)]]}
db)
*e
;; see filtero now
(defn gr-th [?is count]
(fn [envs]
(->> envs
(filter
(fn [env] (> (walk env ?is) count))))))
(->> [{'?is 300} {'?is 150} {'?is 350}]
((disj'
(== '?is 150)
(gr-th '?is 200))))
,)
(defn missing?
"Keeps envs where the given attribute is missing.
?e needs to be ground when walking an enviroment i.e.
all envs getting thrown away if ?e is not in the env"
[db ?e attr]
(fn [envs]
(->> envs
(filter
(fn [env]
(some? (for-index db 0 1 (walk env ?e) attr)))))))
(comment
(q {:find [?name]
:where [(missing? db ?e :char/DeathYear)
[?e :char/Name ?name]]}
db)
(= #{}
(clojure.set/difference
(into #{}
(q {:find [?name]
:where [[?e :char/Name ?name]
[?e :char/DeathYear ?d]]}
db))
(into #{}
(q {:find [?name]
:where [(missing? db ?e :char/DeathYear)
[?e :char/Name ?name]]}
db))))
(q {:find [?e]
:where [[?e :char/Name (or "Randa" "Drogo")]]}
db)
(q {:find [?e]
:where [[?e :char/Name (or (if true "Randa" nil) "Drogo")]]}
db)
;; try recursive rule
(def db
[[0 :name "North America"]
[1 :name "United State"]
[1 :within 0]
[2 :name "Idaho"]
[2 :within 1]])
(defn within-recursive [db ?location ?name]
(conj'
(q-db db )))
,)
#_(eval (clojure.edn/read-string "(q {:find [?e]
:where [[?e :char/Name (or (if true \"Randa\" nil) \"Drogo\")]]}
db)"))
| true | (ns lhrb.engine
(:refer-clojure :exclude [==])
(:require [clojure.string :as str]
[clojure.core.match :refer [match]]
[lhrb.ukanren :as k :refer [lvar? walk unify == conj' disj' conj+ disj+ take-all bind]]))
(defn create-index
"creates an index from eav data
(create-index [[e a v] ...] 0 1)
=> {e {a #{[e a v] ...}}}"
[data idx1 idx2]
(->> data
(reduce
(fn [index elem]
(update-in index
[(get elem idx1) (get elem idx2)]
(fnil conj #{}) elem))
{})))
(comment
(create-index [[1 2 3] [1 2 4]] 0 1)
,)
(def mem-index (memoize create-index))
(defn for-index
"retrieves data from memoized index-fn"
([db idx1 idx2 e]
(->> (get-in (mem-index db idx1 idx2) [e])
(mapcat (fn [[_ v]] v))
;; remove into?
(into #{})))
([db idx1 idx2 e1 e2]
(get-in (mem-index db idx1 idx2) [e1 e2])))
(comment
(k/lcons
(for [[_ _ c] (for-index [[1 2 3] [1 2 4] [2 3 5]] 0 1 1)]
(unify {} c 'a)))
(get-in [[1] 2 3] [0 0])
,)
(defn grounded? [x]
(not (lvar? x)))
(defn q-db [db e a v]
(fn [env]
(k/lcons
(let [e' (walk env e)
a' (walk env a)
v' (walk env v)]
(case [(grounded? e') (grounded? a') (grounded? v')]
[false true true] (for [[e _ _] (for-index db 1 2 a' v')]
(unify env e e'))
[true false true] (for [[_ a _] (for-index db 0 2 e' v')]
(unify env a a'))
[true true false] (for [[_ _ v] (for-index db 0 1 e' a')]
(unify env v v'))
[true false false] (for [[_ a v] (for-index db 0 1 e')]
(-> env (unify a a') (unify v v')))
[false true false] (for [[e _ v] (for-index db 1 2 a')]
(-> env (unify e e') (unify v v')))
[false false true] (for [[e a _] (for-index db 2 1 v')]
(-> env (unify e e') (unify a a')))
[true true true] (for [[_ _ v] (for-index db 0 1 e' a')]
(unify env v v')))))))
(comment
(def db
[[0 :name "PI:NAME:<NAME>END_PI"]
[0 :age 40]
[0 :likes "Pizza"]
[1 :name "PI:NAME:<NAME>END_PI"]
[1 :likes "Pizza"]
[1 :age 30]
[2 :age 40]
[2 :likes "Pizza"]])
(take-all
((conj+
(q-db db 'a :likes "Pizza")
(q-db db 'a :age 40)) {}))
(bind '({a 2} {a 1} {a 0}) (q-db db 'a :age 40))
((q-db db 'a :age 40) {'a 1})
((q-db db 'a :likes "Pizza") {})
((q-db db 'a :likes "Pizza") {})
(require '[lhrb.readcsv :refer [create-got-db]])
(def db (create-got-db))
(count db)
'(:battle/attacker_commander
:battle/defender_1
:battle/attacker_size
:battle/attacker_4
:battle/defender_king
:battle/attacker_2
:battle/year
:battle/name
:battle/attacker_3
:battle/summer
:battle/location
:battle/attacker_king
:battle/defender_2
:battle/battle_number
:battle/region
:battle/defender_commander
:battle/attacker_1
:battle/defender_size
:battle/major_capture
:battle/battle_type
:battle/major_death
:battle/attacker_outcome
:battle/note
:char/Gender
:char/Name
:char/Nobility
:char/Allegiances
:char/DeathYear)
(take-all
((conj+
(q-db db 'battle :battle/battle_type 'type)) {}))
(time (take-all
((conj+
(q-db db 'battle :battle/battle_type "ambush")
(q-db db 'battle :battle/attacker_commander 'names)
(q-db db 'person :char/Name 'names)
(q-db db 'person :char/Allegiances 'house)) {})))
;; define a rule
(defn house-attacking-commander [db ?battle]
(conj+
(q-db db ?battle :battle/attacker_commander 'names)
(q-db db 'person :char/Name 'names)
(q-db db 'person :char/Allegiances 'house)))
(take-all
((conj+
(q-db db 'battle :battle/battle_type "ambush")
(house-attacking-commander db 'battle)) {}))
(take-all
((conj+
(q-db db 'battle :battle/battle_type "ambush")
(q-db db 'battle :battle/year 'byear)
(disj+
(q-db db 'battle :battle/attacker_commander 'names)
(q-db db 'battle :battle/defending_commander 'names))) {}))
,)
(defn reify-var [& vars]
(fn [env-stream] ;; maybe don't return a fn?
(->> env-stream
(mapv
(fn [env]
(mapv ;; extract and use juxt?
(fn [var] (walk env var)) vars))))))
(defmacro run [& clauses]
`(take-all
((conj+ ~@clauses) {})))
(defn run [& clauses]
(->> [{}]
((apply conj' clauses))))
(comment
"experiment with juxt ((juxt a b c) x) => [(a x) (b x) (c x)]
more concise vs readability?"
(let [extract (fn [var]
(fn [env] (walk env var)))]
(->> [{'a 1 'b 2} {'a 3 'b 4 'c 5} {'a 4 'b 10}]
(map
(apply juxt (map extract ['a 'b])))))
(run
;(reify-var 'names 'house)
(q-db db 'battle :battle/battle_type "ambush")
(q-db db 'battle :battle/attacker_commander 'names)
(q-db db 'person :char/Name 'names)
(q-db db 'person :char/Allegiances 'house))
,)
(defn filtero [op ?var c]
(fn [envs]
(->> envs
(filter
(fn [env] (op (walk env ?var) c))))))
(defn substitutions [clause db]
(match [clause]
;; [?e :age (> ?a 10)]
[[e a ([(op :guard #{'= '> '>= '< '<=}) var value] :seq)]]
`[(filtero ~op ~var ~value)
(q-db ~db ~e ~a ~var)]
;; [?e :age (or 10 15)]
;; TODO find a good way to make it work on all pos
[[e a (['or & cases] :seq)]]
(let [c-cases (map
(fn [v] `(q-db ~db ~e ~a ~v))
cases)]
`[(disj' ~@c-cases)])
;; [?e :age 10]
[[e a v]]
`(q-db ~db ~e ~a ~v)
:else clause))
(defn compile-where-clauses
"transforms vector clauses into q-db queries
e.g. [?a :age 10] => (q-db db ?a :age 10)
added
[?e :age (> ?age 10)]
=> ((filtero > ?age 10) (q-db db ?a :age ?age))"
[clauses db]
(->> clauses
(map (fn [clause] (substitutions clause db)))
(reduce (fn [acc e] (if (vector? e)
(into acc e)
(conj acc e)))
[])))
(defn find-lvars
"finds and returns all unique logic-variables.
A logic var begins with an '?'"
[find where] ;; maybe decouple from concrete impl?
(->> (into find where)
(flatten)
(filter
(fn [s]
(and
(lvar? s)
(str/starts-with? (str s) "?"))))
(distinct)))
#_(defmacro fresh [expr]
(let [lvars (find-lvars expr)
]))
(defn reify [vars result]
(->> result
(mapv (fn [env]
(mapv (fn [var] (walk env var)) vars)))))
;; TODO add _ as don't care
(defmacro q [{:keys [find where]} db]
(let [;; test if vars in find clause are also in where clause
lvars (find-lvars find where)
where-compiled (compile-where-clauses where db)]
`(let [~@(interleave lvars (map
(fn [sym]
`(gensym ~(name sym)))
lvars))]
(reify ~find (run ~@where-compiled)))))
(comment
(macroexpand
'(q {:find [?name ?noble]
:where [[?b :battle/location "Storm's End"]
[?b :battle/defender_commander ?name]
[?p :char/Name ?name]
[?p :char/Nobility ?noble]]}
db))
(q {:find [?name ?noble]
:where [[?b :battle/location "Storm's End"]
[?b :battle/defender_commander ?name]
[?p :char/Name ?name]
[?p :char/Nobility ?noble]]}
db)
(macroexpand
'(q {:find [?num]
:where [[?b :battle/attacker_size (> ?num 100)]]}
db))
(q {:find [?name ?num]
:where [[?b :battle/name ?name]
[?b :battle/attacker_size (> ?num 100)]]}
db)
*e
;; see filtero now
(defn gr-th [?is count]
(fn [envs]
(->> envs
(filter
(fn [env] (> (walk env ?is) count))))))
(->> [{'?is 300} {'?is 150} {'?is 350}]
((disj'
(== '?is 150)
(gr-th '?is 200))))
,)
(defn missing?
"Keeps envs where the given attribute is missing.
?e needs to be ground when walking an enviroment i.e.
all envs getting thrown away if ?e is not in the env"
[db ?e attr]
(fn [envs]
(->> envs
(filter
(fn [env]
(some? (for-index db 0 1 (walk env ?e) attr)))))))
(comment
(q {:find [?name]
:where [(missing? db ?e :char/DeathYear)
[?e :char/Name ?name]]}
db)
(= #{}
(clojure.set/difference
(into #{}
(q {:find [?name]
:where [[?e :char/Name ?name]
[?e :char/DeathYear ?d]]}
db))
(into #{}
(q {:find [?name]
:where [(missing? db ?e :char/DeathYear)
[?e :char/Name ?name]]}
db))))
(q {:find [?e]
:where [[?e :char/Name (or "Randa" "Drogo")]]}
db)
(q {:find [?e]
:where [[?e :char/Name (or (if true "Randa" nil) "Drogo")]]}
db)
;; try recursive rule
(def db
[[0 :name "North America"]
[1 :name "United State"]
[1 :within 0]
[2 :name "Idaho"]
[2 :within 1]])
(defn within-recursive [db ?location ?name]
(conj'
(q-db db )))
,)
#_(eval (clojure.edn/read-string "(q {:find [?e]
:where [[?e :char/Name (or (if true \"Randa\" nil) \"Drogo\")]]}
db)"))
|
[
{
"context": "578.jpeg\"}\n {:name \"Gungan Bongo Submarine\", :image \"/img/databank_gunganbongosubmarine_01_1",
"end": 1628,
"score": 0.9667905569076538,
"start": 1606,
"tag": "NAME",
"value": "Gungan Bongo Submarine"
},
{
"context": "6be.jpeg\"}\n {:name \"Flash Speeder\", :image \"/img/databank_flashspeeder_01_169_48978",
"end": 1749,
"score": 0.7123990058898926,
"start": 1736,
"tag": "NAME",
"value": "Flash Speeder"
},
{
"context": "def.jpeg\"}\n {:name \"Gian Speeder\", :image \"/img/databank_gianspeeder_01_169_70b621",
"end": 1861,
"score": 0.9909820556640625,
"start": 1849,
"tag": "NAME",
"value": "Gian Speeder"
},
{
"context": "8ce.jpeg\"}\n {:name \"Sith Speeder\", :image \"/img/databank_sithspeeder_01_169_cfa01a",
"end": 2112,
"score": 0.9377570152282715,
"start": 2100,
"tag": "NAME",
"value": "Sith Speeder"
},
{
"context": "9bc.jpeg\"}\n {:name \"Sebulba’s Podracer\", :image \"/img/sebulbas-pod-racer_11e3",
"end": 2599,
"score": 0.8981281518936157,
"start": 2592,
"tag": "NAME",
"value": "Sebulba"
},
{
"context": "\"}\n {:name \"Sebulba’s Podracer\", :image \"/img/sebulbas-pod-racer_11e322",
"end": 2601,
"score": 0.5610753297805786,
"start": 2600,
"tag": "NAME",
"value": "s"
},
{
"context": "2c6.jpeg\"}\n {:name \"Anakin’s Podracer\", :image \"/img/databank_anakinskywalke",
"end": 2706,
"score": 0.8308232426643372,
"start": 2700,
"tag": "NAME",
"value": "Anakin"
},
{
"context": "62d.jpeg\"}\n {:name \"Mon Calamari Star Cruiser\", :image \"/img/e6d_ia_2581_47f64de7.jpeg\"",
"end": 3822,
"score": 0.8806265592575073,
"start": 3805,
"tag": "NAME",
"value": "Mon Calamari Star"
},
{
"context": " {:name \"Mon Calamari Star Cruiser\", :image \"/img/e6d_ia_2581_47f64de7.jpeg\"}\n ",
"end": 3830,
"score": 0.5608795881271362,
"start": 3824,
"tag": "NAME",
"value": "ruiser"
},
{
"context": ".jpeg\"}\n {:name \"The Khetanna\", :image \"/img/the-khetanna_d1d5b294.jpeg\"}\n ",
"end": 4020,
"score": 0.6558535695075989,
"start": 4012,
"tag": "NAME",
"value": "Khetanna"
},
{
"context": "294.jpeg\"}\n {:name \"TIE Bomber\", :image \"/img/ep5_key_504_6c3982bb.jpeg\"}\n ",
"end": 4114,
"score": 0.9889720678329468,
"start": 4104,
"tag": "NAME",
"value": "TIE Bomber"
},
{
"context": " {:name \"TIE Bomber\", :image \"/img/ep5_key_504_6c3982bb.jpeg\"}\n {:name ",
"end": 4146,
"score": 0.5939798355102539,
"start": 4144,
"tag": "KEY",
"value": "39"
}
] | src/understanding_re_frame/subscriptions.cljs | lispcast/understanding-re-frame | 14 | (ns understanding-re-frame.subscriptions
(:require [reagent.core :as reagent]
[clojure.string :as str]
[re-frame.core :as rf]
[day8.re-frame.http-fx]
[ajax.core :as ajax]
[re-frame.db :as db]))
(def vehicles (zipmap (range) [{:name "V-Wing Fighter", :image "/img/v-wing_8d8d05aa.jpeg"}
{:name "Coruscant Air Taxi", :image "/img/databank_coruscantairtaxi_01_169_a36dcf1f.jpeg"}
{:name "AAT Battle Tank", :image "/img/databank_aatbattletank_01_169_9de46aea.jpeg"}
{:name "Naboo N-1 Starfighter", :image "/img/databank_naboon1starfighter_01_169_26691adf.jpeg"}
{:name "Vulture Droid", :image "/img/databank_vulturedroid_01_169_6ef9fd50.jpeg"}
{:name "Soulless One", :image "/img/databank_soullessone_01_169_08305d9b.jpeg"}
{:name "Republic Cruiser", :image "/img/databank_republiccruiser_01_169_fd769e33.jpeg"}
{:name "Naboo Royal Starship", :image "/img/databank_nabooroyalstarship_01_169_e61f677e.jpeg"}
{:name "Republic Attack Gunship", :image "/img/databank_republicattackgunship_01_169_4ed5c0a7.jpeg"}
{:name "Republic Attack Cruiser", :image "/img/databank_republicattackcruiser_01_169_812f153d.jpeg"}
{:name "Solar Sailer", :image "/img/databank_geonosiansolarsailer_01_169_b3873578.jpeg"}
{:name "Gungan Bongo Submarine", :image "/img/databank_gunganbongosubmarine_01_169_fc9286be.jpeg"}
{:name "Flash Speeder", :image "/img/databank_flashspeeder_01_169_48978def.jpeg"}
{:name "Gian Speeder", :image "/img/databank_gianspeeder_01_169_70b62187.jpeg"}
{:name "Trade Federation Battleship", :image "/img/databank_tradefederationbattleship_01_169_fc5458ce.jpeg"}
{:name "Sith Speeder", :image "/img/databank_sithspeeder_01_169_cfa01a05.jpeg"}
{:name "Trade Federation Landing Ships", :image "/img/databank_tradefederationlandingship_01_169_00567a01.jpeg"}
{:name "ETA-2 Jedi Starfighter", :image "/img/ETA-2-starfighter-main-image_bedd3aaa.jpeg"}
{:name "Delta-7 Jedi Starfighter", :image "/img/delta-7-starfighter_fe9a59bc.jpeg"}
{:name "Sebulba’s Podracer", :image "/img/sebulbas-pod-racer_11e322c6.jpeg"}
{:name "Anakin’s Podracer", :image "/img/databank_anakinskywalkerspodracer_01_169_fe359d32.jpeg"}
{:name "General Grievous’ Tsmeu-6 Wheel Bike", :image "/img/ep3_ia_96565_46396938.jpeg"}
{:name "AT-TE Walker", :image "/img/databank_attewalker_01_169_4292c02c.jpeg"}
{:name "Tantive IV", :image "/img/tantive-iv-main_f1ea3fa5.jpeg"}
{:name "Cloud Car", :image "/img/cloud-car-main-image_8d2e4e89.jpeg"}
{:name "Sith Infiltrator", :image "/img/databank_sithinfiltrator_01_169_1bd0a638.jpeg"}
{:name "B-Wing", :image "/img/databank_bwingfighter_01_169_460cc528.jpeg"}
{:name "Escape Pod", :image "/img/databank_escapepod_01_169_2d71b62d.jpeg"}
{:name "Y-Wing Fighter", :image "/img/Y-Wing-Fighter_0e78c9ae.jpeg"}
{:name "GR-75 Medium Transport", :image "/img/gr-75-medium-transport_cd04862d.jpeg"}
{:name "Mon Calamari Star Cruiser", :image "/img/e6d_ia_2581_47f64de7.jpeg"}
{:name "AT-ST Walker", :image "/img/e6d_ia_5724_a150e6d4.jpeg"}
{:name "The Khetanna", :image "/img/the-khetanna_d1d5b294.jpeg"}
{:name "TIE Bomber", :image "/img/ep5_key_504_6c3982bb.jpeg"}
{:name "A-Wing Fighter", :image "/img/screen_shot_2015-05-26_at_5_16a39e17.png.jpeg"}
{:name "Snowspeeder", :image "/img/snowspeeder_ef2f9334.jpeg"}
{:name "Imperial Shuttle", :image "/img/veh_ia_1752_040381b2.jpeg"}
{:name "Super Star Destroyer", :image "/img/databank_superstardestroyer_01_169_d5757b90.jpeg"}
{:name "Sandcrawler", :image "/img/databank_sandcrawler_01_169_55acf6cb.jpeg"}
{:name "TIE Interceptor", :image "/img/tie-interceptor-2_b2250e79.jpeg"}
{:name "TIE Advanced x1", :image "/img/vaders-tie-fighter_8bcb92e1.jpeg"}
{:name "X-34 Landspeeder", :image "/img/E4D_IA_1136_6b8704fa.jpeg"}
{:name "Speeder Bike", :image "/img/speeder-bike-main_73f43e3a.jpeg"}
{:name "Death Star", :image "/img/Death-Star-I-copy_36ad2500.jpeg"}
{:name "AT-AT Walkers", :image "/img/AT-AT_89d0105f.jpeg"}
{:name "Imperial Star Destroyer", :image "/img/Star-Destroyer_ab6b94bb.jpeg"}
{:name "X-Wing Fighter", :image "/img/X-Wing-Fighter_47c7c342.jpeg"}
{:name "TIE Fighter", :image "/img/TIE-Fighter_25397c64.jpeg"}
{:name "Slave I", :image "/img/slave-i-main_1f3c9b0d.jpeg"}
{:name "Millennium Falcon", :image "/img/millennium-falcon-main-tlj-a_7cf89d3a.jpeg"}]))
(rf/reg-event-db
:initialize-vehicles
(fn [db]
(assoc db :vehicles vehicles)))
(rf/reg-event-db
:like
(fn [db [_ id]]
(update-in db [:user :likes] (fnil conj #{}) id)))
(rf/reg-event-db
:unlike
(fn [db [_ id]]
(update-in db [:user :likes] disj id)))
(rf/reg-sub
:vehicles
(fn [db]
(:vehicles db)))
(rf/reg-sub
:vehicle-ids
(fn []
(rf/subscribe [:vehicles]))
(fn [vehicles]
(sort (keys vehicles))))
(rf/reg-sub
:vehicle
(fn []
(rf/subscribe [:vehicles]))
(fn [vehicles [_ id]]
(get vehicles id)))
(rf/reg-sub
:likes
(fn [db]
(get-in db [:user :likes] #{})))
(rf/reg-sub
:liked?
(fn []
(rf/subscribe [:likes]))
(fn [likes [_ id]]
(contains? likes id)))
(rf/reg-sub
:liked-vehicle
(fn [[_ id]]
[(rf/subscribe [:vehicle id])
(rf/subscribe [:liked? id])])
(fn [[vehicle liked?]]
(assoc vehicle :liked? liked?)))
(defn vehicle-component [id]
(let [vehicle @(rf/subscribe [:liked-vehicle id])
liked? (:liked? vehicle)]
[:div {:style {:display :inline-block
:width 80}}
[:img {:src (:image vehicle)
:style {:max-width "100%"}}]
[:a {:on-click (fn [e]
(.preventDefault e)
(if liked?
(rf/dispatch [:unlike id])
(rf/dispatch [:like id])))
:href "#"
:style {:color (if liked?
:red
:grey)
:text-decoration :none}}
"♥"]]))
(defn subscriptions-panel []
[:div
[:h1 "Subscriptions"]
[:div
(doall
(for [id @(rf/subscribe [:vehicle-ids])]
[:span {:key id}
[vehicle-component id]]))
[:div
(pr-str @(rf/subscribe [:likes]))]]])
(rf/dispatch [:initialize-vehicles])
(comment
vehicles
(conj nil 1)
)
| 64401 | (ns understanding-re-frame.subscriptions
(:require [reagent.core :as reagent]
[clojure.string :as str]
[re-frame.core :as rf]
[day8.re-frame.http-fx]
[ajax.core :as ajax]
[re-frame.db :as db]))
(def vehicles (zipmap (range) [{:name "V-Wing Fighter", :image "/img/v-wing_8d8d05aa.jpeg"}
{:name "Coruscant Air Taxi", :image "/img/databank_coruscantairtaxi_01_169_a36dcf1f.jpeg"}
{:name "AAT Battle Tank", :image "/img/databank_aatbattletank_01_169_9de46aea.jpeg"}
{:name "Naboo N-1 Starfighter", :image "/img/databank_naboon1starfighter_01_169_26691adf.jpeg"}
{:name "Vulture Droid", :image "/img/databank_vulturedroid_01_169_6ef9fd50.jpeg"}
{:name "Soulless One", :image "/img/databank_soullessone_01_169_08305d9b.jpeg"}
{:name "Republic Cruiser", :image "/img/databank_republiccruiser_01_169_fd769e33.jpeg"}
{:name "Naboo Royal Starship", :image "/img/databank_nabooroyalstarship_01_169_e61f677e.jpeg"}
{:name "Republic Attack Gunship", :image "/img/databank_republicattackgunship_01_169_4ed5c0a7.jpeg"}
{:name "Republic Attack Cruiser", :image "/img/databank_republicattackcruiser_01_169_812f153d.jpeg"}
{:name "Solar Sailer", :image "/img/databank_geonosiansolarsailer_01_169_b3873578.jpeg"}
{:name "<NAME>", :image "/img/databank_gunganbongosubmarine_01_169_fc9286be.jpeg"}
{:name "<NAME>", :image "/img/databank_flashspeeder_01_169_48978def.jpeg"}
{:name "<NAME>", :image "/img/databank_gianspeeder_01_169_70b62187.jpeg"}
{:name "Trade Federation Battleship", :image "/img/databank_tradefederationbattleship_01_169_fc5458ce.jpeg"}
{:name "<NAME>", :image "/img/databank_sithspeeder_01_169_cfa01a05.jpeg"}
{:name "Trade Federation Landing Ships", :image "/img/databank_tradefederationlandingship_01_169_00567a01.jpeg"}
{:name "ETA-2 Jedi Starfighter", :image "/img/ETA-2-starfighter-main-image_bedd3aaa.jpeg"}
{:name "Delta-7 Jedi Starfighter", :image "/img/delta-7-starfighter_fe9a59bc.jpeg"}
{:name "<NAME>’<NAME> Podracer", :image "/img/sebulbas-pod-racer_11e322c6.jpeg"}
{:name "<NAME>’s Podracer", :image "/img/databank_anakinskywalkerspodracer_01_169_fe359d32.jpeg"}
{:name "General Grievous’ Tsmeu-6 Wheel Bike", :image "/img/ep3_ia_96565_46396938.jpeg"}
{:name "AT-TE Walker", :image "/img/databank_attewalker_01_169_4292c02c.jpeg"}
{:name "Tantive IV", :image "/img/tantive-iv-main_f1ea3fa5.jpeg"}
{:name "Cloud Car", :image "/img/cloud-car-main-image_8d2e4e89.jpeg"}
{:name "Sith Infiltrator", :image "/img/databank_sithinfiltrator_01_169_1bd0a638.jpeg"}
{:name "B-Wing", :image "/img/databank_bwingfighter_01_169_460cc528.jpeg"}
{:name "Escape Pod", :image "/img/databank_escapepod_01_169_2d71b62d.jpeg"}
{:name "Y-Wing Fighter", :image "/img/Y-Wing-Fighter_0e78c9ae.jpeg"}
{:name "GR-75 Medium Transport", :image "/img/gr-75-medium-transport_cd04862d.jpeg"}
{:name "<NAME> C<NAME>", :image "/img/e6d_ia_2581_47f64de7.jpeg"}
{:name "AT-ST Walker", :image "/img/e6d_ia_5724_a150e6d4.jpeg"}
{:name "The <NAME>", :image "/img/the-khetanna_d1d5b294.jpeg"}
{:name "<NAME>", :image "/img/ep5_key_504_6c<KEY>82bb.jpeg"}
{:name "A-Wing Fighter", :image "/img/screen_shot_2015-05-26_at_5_16a39e17.png.jpeg"}
{:name "Snowspeeder", :image "/img/snowspeeder_ef2f9334.jpeg"}
{:name "Imperial Shuttle", :image "/img/veh_ia_1752_040381b2.jpeg"}
{:name "Super Star Destroyer", :image "/img/databank_superstardestroyer_01_169_d5757b90.jpeg"}
{:name "Sandcrawler", :image "/img/databank_sandcrawler_01_169_55acf6cb.jpeg"}
{:name "TIE Interceptor", :image "/img/tie-interceptor-2_b2250e79.jpeg"}
{:name "TIE Advanced x1", :image "/img/vaders-tie-fighter_8bcb92e1.jpeg"}
{:name "X-34 Landspeeder", :image "/img/E4D_IA_1136_6b8704fa.jpeg"}
{:name "Speeder Bike", :image "/img/speeder-bike-main_73f43e3a.jpeg"}
{:name "Death Star", :image "/img/Death-Star-I-copy_36ad2500.jpeg"}
{:name "AT-AT Walkers", :image "/img/AT-AT_89d0105f.jpeg"}
{:name "Imperial Star Destroyer", :image "/img/Star-Destroyer_ab6b94bb.jpeg"}
{:name "X-Wing Fighter", :image "/img/X-Wing-Fighter_47c7c342.jpeg"}
{:name "TIE Fighter", :image "/img/TIE-Fighter_25397c64.jpeg"}
{:name "Slave I", :image "/img/slave-i-main_1f3c9b0d.jpeg"}
{:name "Millennium Falcon", :image "/img/millennium-falcon-main-tlj-a_7cf89d3a.jpeg"}]))
(rf/reg-event-db
:initialize-vehicles
(fn [db]
(assoc db :vehicles vehicles)))
(rf/reg-event-db
:like
(fn [db [_ id]]
(update-in db [:user :likes] (fnil conj #{}) id)))
(rf/reg-event-db
:unlike
(fn [db [_ id]]
(update-in db [:user :likes] disj id)))
(rf/reg-sub
:vehicles
(fn [db]
(:vehicles db)))
(rf/reg-sub
:vehicle-ids
(fn []
(rf/subscribe [:vehicles]))
(fn [vehicles]
(sort (keys vehicles))))
(rf/reg-sub
:vehicle
(fn []
(rf/subscribe [:vehicles]))
(fn [vehicles [_ id]]
(get vehicles id)))
(rf/reg-sub
:likes
(fn [db]
(get-in db [:user :likes] #{})))
(rf/reg-sub
:liked?
(fn []
(rf/subscribe [:likes]))
(fn [likes [_ id]]
(contains? likes id)))
(rf/reg-sub
:liked-vehicle
(fn [[_ id]]
[(rf/subscribe [:vehicle id])
(rf/subscribe [:liked? id])])
(fn [[vehicle liked?]]
(assoc vehicle :liked? liked?)))
(defn vehicle-component [id]
(let [vehicle @(rf/subscribe [:liked-vehicle id])
liked? (:liked? vehicle)]
[:div {:style {:display :inline-block
:width 80}}
[:img {:src (:image vehicle)
:style {:max-width "100%"}}]
[:a {:on-click (fn [e]
(.preventDefault e)
(if liked?
(rf/dispatch [:unlike id])
(rf/dispatch [:like id])))
:href "#"
:style {:color (if liked?
:red
:grey)
:text-decoration :none}}
"♥"]]))
(defn subscriptions-panel []
[:div
[:h1 "Subscriptions"]
[:div
(doall
(for [id @(rf/subscribe [:vehicle-ids])]
[:span {:key id}
[vehicle-component id]]))
[:div
(pr-str @(rf/subscribe [:likes]))]]])
(rf/dispatch [:initialize-vehicles])
(comment
vehicles
(conj nil 1)
)
| true | (ns understanding-re-frame.subscriptions
(:require [reagent.core :as reagent]
[clojure.string :as str]
[re-frame.core :as rf]
[day8.re-frame.http-fx]
[ajax.core :as ajax]
[re-frame.db :as db]))
(def vehicles (zipmap (range) [{:name "V-Wing Fighter", :image "/img/v-wing_8d8d05aa.jpeg"}
{:name "Coruscant Air Taxi", :image "/img/databank_coruscantairtaxi_01_169_a36dcf1f.jpeg"}
{:name "AAT Battle Tank", :image "/img/databank_aatbattletank_01_169_9de46aea.jpeg"}
{:name "Naboo N-1 Starfighter", :image "/img/databank_naboon1starfighter_01_169_26691adf.jpeg"}
{:name "Vulture Droid", :image "/img/databank_vulturedroid_01_169_6ef9fd50.jpeg"}
{:name "Soulless One", :image "/img/databank_soullessone_01_169_08305d9b.jpeg"}
{:name "Republic Cruiser", :image "/img/databank_republiccruiser_01_169_fd769e33.jpeg"}
{:name "Naboo Royal Starship", :image "/img/databank_nabooroyalstarship_01_169_e61f677e.jpeg"}
{:name "Republic Attack Gunship", :image "/img/databank_republicattackgunship_01_169_4ed5c0a7.jpeg"}
{:name "Republic Attack Cruiser", :image "/img/databank_republicattackcruiser_01_169_812f153d.jpeg"}
{:name "Solar Sailer", :image "/img/databank_geonosiansolarsailer_01_169_b3873578.jpeg"}
{:name "PI:NAME:<NAME>END_PI", :image "/img/databank_gunganbongosubmarine_01_169_fc9286be.jpeg"}
{:name "PI:NAME:<NAME>END_PI", :image "/img/databank_flashspeeder_01_169_48978def.jpeg"}
{:name "PI:NAME:<NAME>END_PI", :image "/img/databank_gianspeeder_01_169_70b62187.jpeg"}
{:name "Trade Federation Battleship", :image "/img/databank_tradefederationbattleship_01_169_fc5458ce.jpeg"}
{:name "PI:NAME:<NAME>END_PI", :image "/img/databank_sithspeeder_01_169_cfa01a05.jpeg"}
{:name "Trade Federation Landing Ships", :image "/img/databank_tradefederationlandingship_01_169_00567a01.jpeg"}
{:name "ETA-2 Jedi Starfighter", :image "/img/ETA-2-starfighter-main-image_bedd3aaa.jpeg"}
{:name "Delta-7 Jedi Starfighter", :image "/img/delta-7-starfighter_fe9a59bc.jpeg"}
{:name "PI:NAME:<NAME>END_PI’PI:NAME:<NAME>END_PI Podracer", :image "/img/sebulbas-pod-racer_11e322c6.jpeg"}
{:name "PI:NAME:<NAME>END_PI’s Podracer", :image "/img/databank_anakinskywalkerspodracer_01_169_fe359d32.jpeg"}
{:name "General Grievous’ Tsmeu-6 Wheel Bike", :image "/img/ep3_ia_96565_46396938.jpeg"}
{:name "AT-TE Walker", :image "/img/databank_attewalker_01_169_4292c02c.jpeg"}
{:name "Tantive IV", :image "/img/tantive-iv-main_f1ea3fa5.jpeg"}
{:name "Cloud Car", :image "/img/cloud-car-main-image_8d2e4e89.jpeg"}
{:name "Sith Infiltrator", :image "/img/databank_sithinfiltrator_01_169_1bd0a638.jpeg"}
{:name "B-Wing", :image "/img/databank_bwingfighter_01_169_460cc528.jpeg"}
{:name "Escape Pod", :image "/img/databank_escapepod_01_169_2d71b62d.jpeg"}
{:name "Y-Wing Fighter", :image "/img/Y-Wing-Fighter_0e78c9ae.jpeg"}
{:name "GR-75 Medium Transport", :image "/img/gr-75-medium-transport_cd04862d.jpeg"}
{:name "PI:NAME:<NAME>END_PI CPI:NAME:<NAME>END_PI", :image "/img/e6d_ia_2581_47f64de7.jpeg"}
{:name "AT-ST Walker", :image "/img/e6d_ia_5724_a150e6d4.jpeg"}
{:name "The PI:NAME:<NAME>END_PI", :image "/img/the-khetanna_d1d5b294.jpeg"}
{:name "PI:NAME:<NAME>END_PI", :image "/img/ep5_key_504_6cPI:KEY:<KEY>END_PI82bb.jpeg"}
{:name "A-Wing Fighter", :image "/img/screen_shot_2015-05-26_at_5_16a39e17.png.jpeg"}
{:name "Snowspeeder", :image "/img/snowspeeder_ef2f9334.jpeg"}
{:name "Imperial Shuttle", :image "/img/veh_ia_1752_040381b2.jpeg"}
{:name "Super Star Destroyer", :image "/img/databank_superstardestroyer_01_169_d5757b90.jpeg"}
{:name "Sandcrawler", :image "/img/databank_sandcrawler_01_169_55acf6cb.jpeg"}
{:name "TIE Interceptor", :image "/img/tie-interceptor-2_b2250e79.jpeg"}
{:name "TIE Advanced x1", :image "/img/vaders-tie-fighter_8bcb92e1.jpeg"}
{:name "X-34 Landspeeder", :image "/img/E4D_IA_1136_6b8704fa.jpeg"}
{:name "Speeder Bike", :image "/img/speeder-bike-main_73f43e3a.jpeg"}
{:name "Death Star", :image "/img/Death-Star-I-copy_36ad2500.jpeg"}
{:name "AT-AT Walkers", :image "/img/AT-AT_89d0105f.jpeg"}
{:name "Imperial Star Destroyer", :image "/img/Star-Destroyer_ab6b94bb.jpeg"}
{:name "X-Wing Fighter", :image "/img/X-Wing-Fighter_47c7c342.jpeg"}
{:name "TIE Fighter", :image "/img/TIE-Fighter_25397c64.jpeg"}
{:name "Slave I", :image "/img/slave-i-main_1f3c9b0d.jpeg"}
{:name "Millennium Falcon", :image "/img/millennium-falcon-main-tlj-a_7cf89d3a.jpeg"}]))
(rf/reg-event-db
:initialize-vehicles
(fn [db]
(assoc db :vehicles vehicles)))
(rf/reg-event-db
:like
(fn [db [_ id]]
(update-in db [:user :likes] (fnil conj #{}) id)))
(rf/reg-event-db
:unlike
(fn [db [_ id]]
(update-in db [:user :likes] disj id)))
(rf/reg-sub
:vehicles
(fn [db]
(:vehicles db)))
(rf/reg-sub
:vehicle-ids
(fn []
(rf/subscribe [:vehicles]))
(fn [vehicles]
(sort (keys vehicles))))
(rf/reg-sub
:vehicle
(fn []
(rf/subscribe [:vehicles]))
(fn [vehicles [_ id]]
(get vehicles id)))
(rf/reg-sub
:likes
(fn [db]
(get-in db [:user :likes] #{})))
(rf/reg-sub
:liked?
(fn []
(rf/subscribe [:likes]))
(fn [likes [_ id]]
(contains? likes id)))
(rf/reg-sub
:liked-vehicle
(fn [[_ id]]
[(rf/subscribe [:vehicle id])
(rf/subscribe [:liked? id])])
(fn [[vehicle liked?]]
(assoc vehicle :liked? liked?)))
(defn vehicle-component [id]
(let [vehicle @(rf/subscribe [:liked-vehicle id])
liked? (:liked? vehicle)]
[:div {:style {:display :inline-block
:width 80}}
[:img {:src (:image vehicle)
:style {:max-width "100%"}}]
[:a {:on-click (fn [e]
(.preventDefault e)
(if liked?
(rf/dispatch [:unlike id])
(rf/dispatch [:like id])))
:href "#"
:style {:color (if liked?
:red
:grey)
:text-decoration :none}}
"♥"]]))
(defn subscriptions-panel []
[:div
[:h1 "Subscriptions"]
[:div
(doall
(for [id @(rf/subscribe [:vehicle-ids])]
[:span {:key id}
[vehicle-component id]]))
[:div
(pr-str @(rf/subscribe [:likes]))]]])
(rf/dispatch [:initialize-vehicles])
(comment
vehicles
(conj nil 1)
)
|
[
{
"context": "s str]\n [clojure.test :refer [deftest is]]))\n\n;; Van Eck's sequence https://youtu.be/etMJxB-igrc\n(defn tur",
"end": 107,
"score": 0.643992006778717,
"start": 100,
"tag": "NAME",
"value": "Van Eck"
}
] | src/aoc/2020/15.clj | callum-oakley/advent-of-code | 2 | (ns aoc.2020.15
(:require
[clojure.string :as str]
[clojure.test :refer [deftest is]]))
;; Van Eck's sequence https://youtu.be/etMJxB-igrc
(defn turn [[prev i mem]]
(let [seen (get mem prev)
age (if seen (- i seen) 0)]
[age (inc i) (assoc! mem prev i)]))
(defn game [n seed]
(nth
(->> (iterate
turn
[(last seed)
(dec (count seed))
(transient
(apply assoc (vec (repeat n nil))
(flatten (map-indexed (fn [i m] [m i]) (drop-last seed)))))])
rest
(map first)
(concat seed))
(dec n)))
(defn part-1 []
(->> (str/split (slurp "input/2020/15") #",")
(map read-string)
(game 2020)))
(defn part-2 []
(->> (str/split (slurp "input/2020/15") #",")
(map read-string)
(game 30000000)))
(deftest test-examples
(is (= (game 2020 [0 3 6]) 436))
(is (= (game 30000000 [0 3 6]) 175594)))
| 64561 | (ns aoc.2020.15
(:require
[clojure.string :as str]
[clojure.test :refer [deftest is]]))
;; <NAME>'s sequence https://youtu.be/etMJxB-igrc
(defn turn [[prev i mem]]
(let [seen (get mem prev)
age (if seen (- i seen) 0)]
[age (inc i) (assoc! mem prev i)]))
(defn game [n seed]
(nth
(->> (iterate
turn
[(last seed)
(dec (count seed))
(transient
(apply assoc (vec (repeat n nil))
(flatten (map-indexed (fn [i m] [m i]) (drop-last seed)))))])
rest
(map first)
(concat seed))
(dec n)))
(defn part-1 []
(->> (str/split (slurp "input/2020/15") #",")
(map read-string)
(game 2020)))
(defn part-2 []
(->> (str/split (slurp "input/2020/15") #",")
(map read-string)
(game 30000000)))
(deftest test-examples
(is (= (game 2020 [0 3 6]) 436))
(is (= (game 30000000 [0 3 6]) 175594)))
| true | (ns aoc.2020.15
(:require
[clojure.string :as str]
[clojure.test :refer [deftest is]]))
;; PI:NAME:<NAME>END_PI's sequence https://youtu.be/etMJxB-igrc
(defn turn [[prev i mem]]
(let [seen (get mem prev)
age (if seen (- i seen) 0)]
[age (inc i) (assoc! mem prev i)]))
(defn game [n seed]
(nth
(->> (iterate
turn
[(last seed)
(dec (count seed))
(transient
(apply assoc (vec (repeat n nil))
(flatten (map-indexed (fn [i m] [m i]) (drop-last seed)))))])
rest
(map first)
(concat seed))
(dec n)))
(defn part-1 []
(->> (str/split (slurp "input/2020/15") #",")
(map read-string)
(game 2020)))
(defn part-2 []
(->> (str/split (slurp "input/2020/15") #",")
(map read-string)
(game 30000000)))
(deftest test-examples
(is (= (game 2020 [0 3 6]) 436))
(is (= (game 30000000 [0 3 6]) 175594)))
|
[
{
"context": ".9.5-pre10\"]\n [com.oracle/ojdbc7 \"12.1.0.1\"]\n [buddy/buddy-auth \"1.4.1\"]\n ",
"end": 903,
"score": 0.9996148347854614,
"start": 895,
"tag": "IP_ADDRESS",
"value": "12.1.0.1"
}
] | project.clj | ithaka/artstor-metadata-service-os | 0 | (defproject artstor-metadata-service-os "1.0.0"
:description "Artstor Metadata Service"
:url "http://www.artstor.org/"
:license {:name "MIT License"
:url "https://opensource.org/licenses/MIT"}
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/data.json "0.2.6"]
[org.clojure/data.codec "0.1.0"]
[org.clojure/core.cache "0.6.5"]
[org.clojure/data.zip "0.1.2"]
[org.clojure/tools.logging "0.3.1"]
[clj-sequoia "3.0.3"]
[clj-http "2.3.0"]
[clj-time "0.14.0"]
[cheshire "5.7.0"]
[compojure "1.6.0"]
[commons-codec/commons-codec "1.4"]
[com.amazonaws/aws-java-sdk-core "1.11.98"]
[com.mchange/c3p0 "0.9.5-pre10"]
[com.oracle/ojdbc7 "12.1.0.1"]
[buddy/buddy-auth "1.4.1"]
[environ "1.1.0"]
[ring "1.6.2"]
[ring-logger "0.7.7"]
[ring/ring-json "0.4.0"]
[ring/ring-codec "1.0.1"]
[ring/ring-mock "0.3.0"]
[hiccup "1.0.5"]
[yesql "0.5.3"]
[metosin/compojure-api "2.0.0-alpha6"]
[prismatic/schema "1.1.3"]]
:profiles {:test {:env {:artstor-metadata-db-url "jdbc:h2:/tmp/artstor-metadata-test.db"}
:dependencies [[szew/h2 "0.1.1"]
[org.clojure/tools.nrepl "0.2.12"]
[org.clojure/test.check "0.9.0"]
[ragtime "0.6.3"]]
:ragtime {:database "jdbc:h2:/tmp/artstor-metadata-test.db"}}}
:ring {:handler artstor-metadata-service-os.core/app :port 8080}
:plugins [[lein-ring "0.10.0"]
[lein-environ "1.1.0"]
[lein-marginalia "0.9.0"]])
| 15850 | (defproject artstor-metadata-service-os "1.0.0"
:description "Artstor Metadata Service"
:url "http://www.artstor.org/"
:license {:name "MIT License"
:url "https://opensource.org/licenses/MIT"}
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/data.json "0.2.6"]
[org.clojure/data.codec "0.1.0"]
[org.clojure/core.cache "0.6.5"]
[org.clojure/data.zip "0.1.2"]
[org.clojure/tools.logging "0.3.1"]
[clj-sequoia "3.0.3"]
[clj-http "2.3.0"]
[clj-time "0.14.0"]
[cheshire "5.7.0"]
[compojure "1.6.0"]
[commons-codec/commons-codec "1.4"]
[com.amazonaws/aws-java-sdk-core "1.11.98"]
[com.mchange/c3p0 "0.9.5-pre10"]
[com.oracle/ojdbc7 "192.168.3.11"]
[buddy/buddy-auth "1.4.1"]
[environ "1.1.0"]
[ring "1.6.2"]
[ring-logger "0.7.7"]
[ring/ring-json "0.4.0"]
[ring/ring-codec "1.0.1"]
[ring/ring-mock "0.3.0"]
[hiccup "1.0.5"]
[yesql "0.5.3"]
[metosin/compojure-api "2.0.0-alpha6"]
[prismatic/schema "1.1.3"]]
:profiles {:test {:env {:artstor-metadata-db-url "jdbc:h2:/tmp/artstor-metadata-test.db"}
:dependencies [[szew/h2 "0.1.1"]
[org.clojure/tools.nrepl "0.2.12"]
[org.clojure/test.check "0.9.0"]
[ragtime "0.6.3"]]
:ragtime {:database "jdbc:h2:/tmp/artstor-metadata-test.db"}}}
:ring {:handler artstor-metadata-service-os.core/app :port 8080}
:plugins [[lein-ring "0.10.0"]
[lein-environ "1.1.0"]
[lein-marginalia "0.9.0"]])
| true | (defproject artstor-metadata-service-os "1.0.0"
:description "Artstor Metadata Service"
:url "http://www.artstor.org/"
:license {:name "MIT License"
:url "https://opensource.org/licenses/MIT"}
:dependencies [[org.clojure/clojure "1.8.0"]
[org.clojure/data.json "0.2.6"]
[org.clojure/data.codec "0.1.0"]
[org.clojure/core.cache "0.6.5"]
[org.clojure/data.zip "0.1.2"]
[org.clojure/tools.logging "0.3.1"]
[clj-sequoia "3.0.3"]
[clj-http "2.3.0"]
[clj-time "0.14.0"]
[cheshire "5.7.0"]
[compojure "1.6.0"]
[commons-codec/commons-codec "1.4"]
[com.amazonaws/aws-java-sdk-core "1.11.98"]
[com.mchange/c3p0 "0.9.5-pre10"]
[com.oracle/ojdbc7 "PI:IP_ADDRESS:192.168.3.11END_PI"]
[buddy/buddy-auth "1.4.1"]
[environ "1.1.0"]
[ring "1.6.2"]
[ring-logger "0.7.7"]
[ring/ring-json "0.4.0"]
[ring/ring-codec "1.0.1"]
[ring/ring-mock "0.3.0"]
[hiccup "1.0.5"]
[yesql "0.5.3"]
[metosin/compojure-api "2.0.0-alpha6"]
[prismatic/schema "1.1.3"]]
:profiles {:test {:env {:artstor-metadata-db-url "jdbc:h2:/tmp/artstor-metadata-test.db"}
:dependencies [[szew/h2 "0.1.1"]
[org.clojure/tools.nrepl "0.2.12"]
[org.clojure/test.check "0.9.0"]
[ragtime "0.6.3"]]
:ragtime {:database "jdbc:h2:/tmp/artstor-metadata-test.db"}}}
:ring {:handler artstor-metadata-service-os.core/app :port 8080}
:plugins [[lein-ring "0.10.0"]
[lein-environ "1.1.0"]
[lein-marginalia "0.9.0"]])
|
[
{
"context": "t the data then add a password.\n ;; :password [:salted \"your-pass\"]\n\n ;; If you wish track how much ti",
"end": 4714,
"score": 0.9912814497947693,
"start": 4708,
"tag": "PASSWORD",
"value": "salted"
},
{
"context": "ta then add a password.\n ;; :password [:salted \"your-pass\"]\n\n ;; If you wish track how much time the seri",
"end": 4725,
"score": 0.9980078339576721,
"start": 4716,
"tag": "PASSWORD",
"value": "your-pass"
}
] | service/src/optimus/service/backends/middleware/binary_kv_store.clj | trainline/optimus | 13 | ;; Copyright (c) Trainline Limited, 2017. All rights reserved.
;; See LICENSE.txt in the project root for license information
(ns optimus.service.backends.middleware.binary-kv-store
"This is a implementation of the KV store protocol
which encodes the value as a binary payload it optionally
compress it. This can be used as a middleware between
the client and the actual storage engine."
(:require [optimus.service
[backend :refer :all]
[util :refer [metrics-name]]]
[samsara.trackit :refer [track-distribution track-time]]
[taoensso.nippy :as nippy]
[taoensso.nippy.compression :as compression])
(:import java.nio.HeapByteBuffer))
;;
;; We want to be able to deserialize only when the value is serialized
;; for a particular version. This means that on the same database we
;; could have a dataset/table which was loaded before this change,
;; therefore it will be a clojure map or string, and the same
;; dataset/table have a newer version which is serialized with nippy.
;; If the code detects that the value returned from the underlying
;; datastore is a byte[] then it will assume it has been serialized
;; with nippy and it will attempt to deserialize. If the returned
;; value is anything else then it will be just passed down.
;;
;; TODO: this in the future should come from a dataset/table/version
;; configuration.
;;
;;
;; Raw serialization functions
;;
(defn- raw-serialize [val config]
(nippy/freeze val config))
(def ^:const byte-array-type (type (byte-array 1)))
(defn byte-array? [val]
(= (type val) byte-array-type))
(defn byte-buffer? [val]
(= (type val) java.nio.HeapByteBuffer))
(defn- raw-deserialize [val config]
(cond
(byte-buffer? val) (nippy/thaw (.array ^java.nio.HeapByteBuffer val) config)
(byte-array? val) (nippy/thaw val config)
:else val))
;;
;; Instrumented version of the serialize and deserialize
;;
(defn iserialize [val {:keys [metrics-prefix] :as config}]
(let [val' (track-time
(metrics-name metrics-prefix :serialize :time)
(raw-serialize val config))
;; track compressed size
_ (track-distribution
(metrics-name metrics-prefix :serialize :size)
(count val'))]
;; return serialized value
val'))
(defn ideserialize [val {:keys [metrics-prefix] :as config}]
(track-time
(metrics-name metrics-prefix :deserialize :time)
(raw-deserialize val config)))
;;
;; General version
;;
(defn serialize [val {:keys [metrics-prefix] :as config}]
(if metrics-prefix
(iserialize val config)
(raw-serialize val config)))
(defn deserialize [val {:keys [metrics-prefix] :as config}]
(if metrics-prefix
(ideserialize val config)
(raw-deserialize val config)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ---==| B I N A R Y K V S T O R E |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord BinaryKVStore [config backend]
KV
(put-one [_ {:keys [version dataset table key] :as akey} val]
(BinaryKVStore. config
(put-one backend akey (serialize val config))))
(get-one [kvstore {:keys [version dataset table key] :as akey}]
(some-> (get-one backend akey)
(deserialize config)))
(get-many [kvstore keys]
(->> (get-many backend keys)
(map (fn [[k v]] [k (deserialize v config)]))
(into {})))
(put-many [kvstore entries]
(BinaryKVStore. config
(->> entries
(map (fn [[k v]] [k (serialize v config)]))
(into {})
(put-many backend)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ---==| C O N F I G |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^:const DEFAULT_CONFIG
{;; The compressor used to compress the binary data
;; possible options are: :none, :lz4, snappy, :lzma2,
;; :lz4hc. Default :lz4
:compressor :lz4
;; The encryption algorithm used to encrypt the payload
;; :encryptor aes128-encryptor
;; If you wish to encrypt the data then add a password.
;; :password [:salted "your-pass"]
;; If you wish track how much time the serialization
;; takes and how big is the payload you need to
;; provide a `:metrics-prefix` value
;; :metrics-prefix ["kv" "binary"]
})
(defn binary-kv-store
([backend]
(binary-kv-store backend {}))
([backend config]
(-> (merge DEFAULT_CONFIG config)
(update :compressor #(case %
:lz4 compression/lz4-compressor
:snappy compression/snappy-compressor
:lzma2 compression/lzma2-compressor
:lz4hc compression/lz4hc-compressor
:none nil
:default nil))
(BinaryKVStore. backend))))
| 93481 | ;; Copyright (c) Trainline Limited, 2017. All rights reserved.
;; See LICENSE.txt in the project root for license information
(ns optimus.service.backends.middleware.binary-kv-store
"This is a implementation of the KV store protocol
which encodes the value as a binary payload it optionally
compress it. This can be used as a middleware between
the client and the actual storage engine."
(:require [optimus.service
[backend :refer :all]
[util :refer [metrics-name]]]
[samsara.trackit :refer [track-distribution track-time]]
[taoensso.nippy :as nippy]
[taoensso.nippy.compression :as compression])
(:import java.nio.HeapByteBuffer))
;;
;; We want to be able to deserialize only when the value is serialized
;; for a particular version. This means that on the same database we
;; could have a dataset/table which was loaded before this change,
;; therefore it will be a clojure map or string, and the same
;; dataset/table have a newer version which is serialized with nippy.
;; If the code detects that the value returned from the underlying
;; datastore is a byte[] then it will assume it has been serialized
;; with nippy and it will attempt to deserialize. If the returned
;; value is anything else then it will be just passed down.
;;
;; TODO: this in the future should come from a dataset/table/version
;; configuration.
;;
;;
;; Raw serialization functions
;;
(defn- raw-serialize [val config]
(nippy/freeze val config))
(def ^:const byte-array-type (type (byte-array 1)))
(defn byte-array? [val]
(= (type val) byte-array-type))
(defn byte-buffer? [val]
(= (type val) java.nio.HeapByteBuffer))
(defn- raw-deserialize [val config]
(cond
(byte-buffer? val) (nippy/thaw (.array ^java.nio.HeapByteBuffer val) config)
(byte-array? val) (nippy/thaw val config)
:else val))
;;
;; Instrumented version of the serialize and deserialize
;;
(defn iserialize [val {:keys [metrics-prefix] :as config}]
(let [val' (track-time
(metrics-name metrics-prefix :serialize :time)
(raw-serialize val config))
;; track compressed size
_ (track-distribution
(metrics-name metrics-prefix :serialize :size)
(count val'))]
;; return serialized value
val'))
(defn ideserialize [val {:keys [metrics-prefix] :as config}]
(track-time
(metrics-name metrics-prefix :deserialize :time)
(raw-deserialize val config)))
;;
;; General version
;;
(defn serialize [val {:keys [metrics-prefix] :as config}]
(if metrics-prefix
(iserialize val config)
(raw-serialize val config)))
(defn deserialize [val {:keys [metrics-prefix] :as config}]
(if metrics-prefix
(ideserialize val config)
(raw-deserialize val config)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ---==| B I N A R Y K V S T O R E |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord BinaryKVStore [config backend]
KV
(put-one [_ {:keys [version dataset table key] :as akey} val]
(BinaryKVStore. config
(put-one backend akey (serialize val config))))
(get-one [kvstore {:keys [version dataset table key] :as akey}]
(some-> (get-one backend akey)
(deserialize config)))
(get-many [kvstore keys]
(->> (get-many backend keys)
(map (fn [[k v]] [k (deserialize v config)]))
(into {})))
(put-many [kvstore entries]
(BinaryKVStore. config
(->> entries
(map (fn [[k v]] [k (serialize v config)]))
(into {})
(put-many backend)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ---==| C O N F I G |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^:const DEFAULT_CONFIG
{;; The compressor used to compress the binary data
;; possible options are: :none, :lz4, snappy, :lzma2,
;; :lz4hc. Default :lz4
:compressor :lz4
;; The encryption algorithm used to encrypt the payload
;; :encryptor aes128-encryptor
;; If you wish to encrypt the data then add a password.
;; :password [:<PASSWORD> "<PASSWORD>"]
;; If you wish track how much time the serialization
;; takes and how big is the payload you need to
;; provide a `:metrics-prefix` value
;; :metrics-prefix ["kv" "binary"]
})
(defn binary-kv-store
([backend]
(binary-kv-store backend {}))
([backend config]
(-> (merge DEFAULT_CONFIG config)
(update :compressor #(case %
:lz4 compression/lz4-compressor
:snappy compression/snappy-compressor
:lzma2 compression/lzma2-compressor
:lz4hc compression/lz4hc-compressor
:none nil
:default nil))
(BinaryKVStore. backend))))
| true | ;; Copyright (c) Trainline Limited, 2017. All rights reserved.
;; See LICENSE.txt in the project root for license information
(ns optimus.service.backends.middleware.binary-kv-store
"This is a implementation of the KV store protocol
which encodes the value as a binary payload it optionally
compress it. This can be used as a middleware between
the client and the actual storage engine."
(:require [optimus.service
[backend :refer :all]
[util :refer [metrics-name]]]
[samsara.trackit :refer [track-distribution track-time]]
[taoensso.nippy :as nippy]
[taoensso.nippy.compression :as compression])
(:import java.nio.HeapByteBuffer))
;;
;; We want to be able to deserialize only when the value is serialized
;; for a particular version. This means that on the same database we
;; could have a dataset/table which was loaded before this change,
;; therefore it will be a clojure map or string, and the same
;; dataset/table have a newer version which is serialized with nippy.
;; If the code detects that the value returned from the underlying
;; datastore is a byte[] then it will assume it has been serialized
;; with nippy and it will attempt to deserialize. If the returned
;; value is anything else then it will be just passed down.
;;
;; TODO: this in the future should come from a dataset/table/version
;; configuration.
;;
;;
;; Raw serialization functions
;;
(defn- raw-serialize [val config]
(nippy/freeze val config))
(def ^:const byte-array-type (type (byte-array 1)))
(defn byte-array? [val]
(= (type val) byte-array-type))
(defn byte-buffer? [val]
(= (type val) java.nio.HeapByteBuffer))
(defn- raw-deserialize [val config]
(cond
(byte-buffer? val) (nippy/thaw (.array ^java.nio.HeapByteBuffer val) config)
(byte-array? val) (nippy/thaw val config)
:else val))
;;
;; Instrumented version of the serialize and deserialize
;;
(defn iserialize [val {:keys [metrics-prefix] :as config}]
(let [val' (track-time
(metrics-name metrics-prefix :serialize :time)
(raw-serialize val config))
;; track compressed size
_ (track-distribution
(metrics-name metrics-prefix :serialize :size)
(count val'))]
;; return serialized value
val'))
(defn ideserialize [val {:keys [metrics-prefix] :as config}]
(track-time
(metrics-name metrics-prefix :deserialize :time)
(raw-deserialize val config)))
;;
;; General version
;;
(defn serialize [val {:keys [metrics-prefix] :as config}]
(if metrics-prefix
(iserialize val config)
(raw-serialize val config)))
(defn deserialize [val {:keys [metrics-prefix] :as config}]
(if metrics-prefix
(ideserialize val config)
(raw-deserialize val config)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ---==| B I N A R Y K V S T O R E |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord BinaryKVStore [config backend]
KV
(put-one [_ {:keys [version dataset table key] :as akey} val]
(BinaryKVStore. config
(put-one backend akey (serialize val config))))
(get-one [kvstore {:keys [version dataset table key] :as akey}]
(some-> (get-one backend akey)
(deserialize config)))
(get-many [kvstore keys]
(->> (get-many backend keys)
(map (fn [[k v]] [k (deserialize v config)]))
(into {})))
(put-many [kvstore entries]
(BinaryKVStore. config
(->> entries
(map (fn [[k v]] [k (serialize v config)]))
(into {})
(put-many backend)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; ---==| C O N F I G |==---- ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^:const DEFAULT_CONFIG
{;; The compressor used to compress the binary data
;; possible options are: :none, :lz4, snappy, :lzma2,
;; :lz4hc. Default :lz4
:compressor :lz4
;; The encryption algorithm used to encrypt the payload
;; :encryptor aes128-encryptor
;; If you wish to encrypt the data then add a password.
;; :password [:PI:PASSWORD:<PASSWORD>END_PI "PI:PASSWORD:<PASSWORD>END_PI"]
;; If you wish track how much time the serialization
;; takes and how big is the payload you need to
;; provide a `:metrics-prefix` value
;; :metrics-prefix ["kv" "binary"]
})
(defn binary-kv-store
([backend]
(binary-kv-store backend {}))
([backend config]
(-> (merge DEFAULT_CONFIG config)
(update :compressor #(case %
:lz4 compression/lz4-compressor
:snappy compression/snappy-compressor
:lzma2 compression/lzma2-compressor
:lz4hc compression/lz4hc-compressor
:none nil
:default nil))
(BinaryKVStore. backend))))
|
[
{
"context": "nk \"https://www.mcnallyjackson.com\"\n :storeName \"McNally Jackson\"}\n {:id 6\n :city :nyc\n :type :site\n :map {:cen",
"end": 1578,
"score": 0.999719500541687,
"start": 1563,
"tag": "NAME",
"value": "McNally Jackson"
},
{
"context": "k \"https://www.stmarksbookshop.com\"\n :storeName \"St. Mark's Bookshop\"}\n {:id 7\n :city :nyc\n :type :",
"end": 1826,
"score": 0.5532766580581665,
"start": 1824,
"tag": "NAME",
"value": "St"
},
{
"context": "://www.brooklinebooksmith-shop.com\"\n :storeName \"Brookline Booksmith\"}\n {:id 9\n :city :bos\n :type :site\n :map {:cen",
"end": 2381,
"score": 0.8568409085273743,
"start": 2362,
"tag": "NAME",
"value": "Brookline Booksmith"
},
{
"context": "eLink \"https://www.annieblooms.com\"\n :storeName \"Annie Bloom's Books\"}\n {:id 22\n :city :pdx\n :type :site\n :ma",
"end": 5880,
"score": 0.9331329464912415,
"start": 5867,
"tag": "NAME",
"value": "Annie Bloom's"
}
] | config/stores.clj | ericqweinstein/quixote | 0 | [{:id 0
:city :nyc
:type :site
:map {:center {:latitude 40.763754 :longitude -73.923849} :zoom 14}
:phone "tel:+1-718-278-2665"
:address "31-29 31st St, New York, NY 11106"
:storeLink "https://www.astoriabookshop.com"
:storeName "Astoria Bookshop"}
{:id 1
:city :nyc
:type :site
:map {:center {:latitude 40.805786 :longitude -73.966143} :zoom 14}
:phone "tel:+1-212-678-1654"
:address "2780 Broadway, New York, NY 10025"
:storeLink "https://www.bankstreetbooks.com"
:storeName "Bank Street Books"}
{:id 2
:city :nyc
:type :site
:map {:center {:latitude 40.805135 :longitude -73.964991} :zoom 14}
:phone "tel:+1-212-865-1588"
:address "536 W 112th St, New York, NY 10025"
:storeLink "https://www.bookculture.com"
:storeName "Book Culture"}
{:id 3
:city :nyc
:type :booksite
:map {:center {:latitude 40.672900 :longitude -73.976457} :zoom 14}
:phone "tel:+1-718-783-3075"
:address "143 7th Ave, Brooklyn, NY 11215"
:storeLink "https://site.booksite.com/6994"
:storeName "Community Bookstore"}
{:id 4
:city :nyc
:type :site
:map {:center {:latitude 40.686502 :longitude -73.974571} :zoom 14}
:phone "tel:+1-718-246-0200"
:address "686 Fulton St, Brooklyn, NY 11217"
:storeLink "https://www.greenlightbookstore.com"
:storeName "Greenlight Bookstore"}
{:id 5
:city :nyc
:type :solr
:map {:center {:latitude 40.723518 :longitude -73.996061} :zoom 14}
:phone "tel:+1-212-274-1160"
:address "52 Prince St, New York, NY 10012"
:storeLink "https://www.mcnallyjackson.com"
:storeName "McNally Jackson"}
{:id 6
:city :nyc
:type :site
:map {:center {:latitude 40.724005 :longitude -73.985879} :zoom 14}
:phone "tel:+1-212-260-7853"
:address "136 E 3rd St, New York, NY 10009"
:storeLink "https://www.stmarksbookshop.com"
:storeName "St. Mark's Bookshop"}
{:id 7
:city :nyc
:type :site
:map {:center {:latitude 40.729197 :longitude -73.957319} :zoom 14}
:phone "tel:+1-718-383-0096"
:address "126 Franklin St, Brooklyn, NY 11222"
:storeLink "https://www.wordbookstores.com"
:storeName "Word Bookstore"}
{:id 8
:city :bos
:type :site
:map {:center {:latitude 42.342695 :longitude -71.121423} :zoom 14}
:phone "tel:+1-617-566-6660"
:address "279 Harvard St, Brookline, MA 02446"
:storeLink "https://www.brooklinebooksmith-shop.com"
:storeName "Brookline Booksmith"}
{:id 9
:city :bos
:type :site
:map {:center {:latitude 42.314296 :longitude -71.210320} :zoom 14}
:phone "tel:+1-617-964-7440"
:address "82 Needham St, Newton, MA 02461"
:storeLink "https://www.nebookfair.com"
:storeName "New England Mobile Book Fair"}
{:id 10
:city :bos
:type :solr
:map {:center {:latitude 42.366121 :longitude -71.105278} :zoom 14}
:phone "tel:+1-617-547-3721"
:address "4 Pleasant St, Cambridge, MA 02139"
:storeLink "https://www.pandemoniumbooks.com"
:storeName "Pandemonium Books and Games"}
{:id 11
:city :bos
:type :site
:map {:center {:latitude 42.389177 :longitude -71.118252} :zoom 14}
:phone "tel:+1-617-491-2220"
:address "25 White St, Cambridge, MA 02140"
:storeLink "https://www.portersquarebooks.com"
:storeName "Porter Square Books"}
{:id 12
:city :chi
:type :site
:map {:center {:latitude 41.967562 :longitude -87.687986} :zoom 14}
:phone "tel:+1-773-293-2665"
:address "4736 N Lincoln Ave, Chicago, IL 60625"
:storeLink "https://www.bookcellarinc.com"
:storeName "The Book Cellar"}
{:id 13
:city :chi
:type :solr
:map {:center {:latitude 41.926976 :longitude -87.707253} :zoom 14}
:phone "tel:+1-773-235-2523"
:address "2523 N Kedzie Blvd, Chicago, IL 60647"
:storeLink "https://www.citylitbooks.com"
:storeName "City Lit Books"}
{:id 14
:city :chi
:type :site
:map {:center {:latitude 41.790024 :longitude -87.595605} :zoom 14}
:phone "tel:+1-773-752-4381"
:address "5751 S Woodlawn Ave, Chicago, IL 60637"
:storeLink "https://www.semcoop.com"
:storeName "Seminary Co-op Bookstores"}
{:id 15
:city :chi
:type :solr
:map {:center {:latitude 41.941585 :longitude -87.643732} :zoom 14}
:phone "tel:+1-773-883-9119"
:address "3251 N Broadway St, Chicago, IL 60657"
:storeLink "https://www.unabridgedbookstore.com"
:storeName "Unabridged Bookstore"}
{:id 16
:city :chi
:type :solr
:map {:center {:latitude 41.977334 :longitude -87.667873} :zoom 14}
:phone "tel:+1-773-769-9299"
:address "5233 N Clark St, Chicago, IL 60640"
:storeLink "https://www.womenandchildrenfirst.com"
:storeName "Women and Children First"}
{:id 17
:city :msp
:type :site
:map {:center {:latitude 44.940447 :longitude -93.166282} :zoom 14}
:phone "tel:+1-651-225-8989"
:address "38 Snelling Ave S, St Paul, MN 55105"
:storeLink "https://www.commongoodbooks.com"
:storeName "Common Good Books"}
{:id 18
:city :msp
:type :site
:map {:center {:latitude 44.940247 :longitude -93.137250} :zoom 14}
:phone "tel:+1-651-224-8320"
:address "891 Grand Ave, St Paul, MN 55105"
:storeLink "https://www.redballoonbookshop.com"
:storeName "Red Balloon Bookshop"}
{:id 19
:city :msp
:type :site
:map {:center {:latitude 45.057563 :longitude -92.805685} :zoom 14}
:phone "tel:+1-651-430-3385"
:address "217 Main St N, Stillwater, MN 55082"
:storeLink "https://www.valleybookseller.com"
:storeName "Valley Bookseller"}
{:id 20
:city :msp
:type :site
:map {:center {:latitude 44.924730 :longitude -93.313411} :zoom 14}
:phone "tel:+1-612-920-5005"
:address "2720 W 43rd St, Minneapolis, MN 55410"
:storeLink "https://www.wildrumpusbooks.com"
:storeName "Wild Rumpus"}
{:id 21
:city :pdx
:type :site
:map {:center {:latitude 45.467730 :longitude -122.713105} :zoom 14}
:phone "tel:+1-503-246-0053"
:address "7834 SW Capitol Hwy, Portland, OR 97219"
:storeLink "https://www.annieblooms.com"
:storeName "Annie Bloom's Books"}
{:id 22
:city :pdx
:type :site
:map {:center {:latitude 45.535182 :longitude -122.648269} :zoom 14}
:phone "tel:+1-503-284-1726"
:address "1714 NE Broadway St, Portland, OR 97232"
:storeLink "https://www.broadwaybooks.net"
:storeName "Broadway Books"}
{:id 23
:city :pdx
:type :powells
:map {:center {:latitude 45.523377 :longitude -122.681319} :zoom 14}
:phone "tel:+1-503-228-4651"
:address "1005 W Burnside St, Portland, OR 97209"
:storeLink "https://www.powells.com/"
:storeName "Powell's Books"}
{:id 24
:city :sea
:type :site
:map {:center {:latitude 47.614661 :longitude -122.319602} :zoom 14}
:phone "tel:+1-206-624-6600"
:address "1521 10th Ave, Seattle, WA 98122"
:storeLink "https://www.elliottbaybook.com"
:storeName "The Elliott Bay Book Company"}
{:id 25
:city :sea
:type :site
:map {:center {:latitude 47.261673 :longitude -122.445302} :zoom 14}
:phone "tel:+1-253-272-8801"
:address "218 St Helens Ave, Tacoma, WA 98402"
:storeLink "https://www.kingsbookstore.com"
:storeName "King's Books"}
{:id 26
:city :sea
:type :site
:map {:center {:latitude 47.602697 :longitude -122.332991} :zoom 14}
:phone "tel:+1-206-587-5737"
:address "117 Cherry St, Seattle, WA 98104"
:storeLink "https://www.seattlemystery.com"
:storeName "Seattle Mystery Bookshop"}
{:id 27
:city :sea
:type :solr
:map {:center {:latitude 47.668888 :longitude -122.384664} :zoom 14}
:phone "tel:+1-206-789-5006"
:address "2214 NW Market St, Seattle, WA 98107"
:storeLink "https://www.secretgardenbooks.com"
:storeName "The Secret Garden Bookshop"}
{:id 28
:city :sea
:type :site
:map {:center {:latitude 47.753232 :longitude -122.280014} :zoom 14}
:phone "tel:+1-206-366-3333"
:address "6504 20th Ave NE, Seattle, WA 98115"
:storeLink "https://www.thirdplacebooks.com"
:storeName "Third Place Books"}]
| 66079 | [{:id 0
:city :nyc
:type :site
:map {:center {:latitude 40.763754 :longitude -73.923849} :zoom 14}
:phone "tel:+1-718-278-2665"
:address "31-29 31st St, New York, NY 11106"
:storeLink "https://www.astoriabookshop.com"
:storeName "Astoria Bookshop"}
{:id 1
:city :nyc
:type :site
:map {:center {:latitude 40.805786 :longitude -73.966143} :zoom 14}
:phone "tel:+1-212-678-1654"
:address "2780 Broadway, New York, NY 10025"
:storeLink "https://www.bankstreetbooks.com"
:storeName "Bank Street Books"}
{:id 2
:city :nyc
:type :site
:map {:center {:latitude 40.805135 :longitude -73.964991} :zoom 14}
:phone "tel:+1-212-865-1588"
:address "536 W 112th St, New York, NY 10025"
:storeLink "https://www.bookculture.com"
:storeName "Book Culture"}
{:id 3
:city :nyc
:type :booksite
:map {:center {:latitude 40.672900 :longitude -73.976457} :zoom 14}
:phone "tel:+1-718-783-3075"
:address "143 7th Ave, Brooklyn, NY 11215"
:storeLink "https://site.booksite.com/6994"
:storeName "Community Bookstore"}
{:id 4
:city :nyc
:type :site
:map {:center {:latitude 40.686502 :longitude -73.974571} :zoom 14}
:phone "tel:+1-718-246-0200"
:address "686 Fulton St, Brooklyn, NY 11217"
:storeLink "https://www.greenlightbookstore.com"
:storeName "Greenlight Bookstore"}
{:id 5
:city :nyc
:type :solr
:map {:center {:latitude 40.723518 :longitude -73.996061} :zoom 14}
:phone "tel:+1-212-274-1160"
:address "52 Prince St, New York, NY 10012"
:storeLink "https://www.mcnallyjackson.com"
:storeName "<NAME>"}
{:id 6
:city :nyc
:type :site
:map {:center {:latitude 40.724005 :longitude -73.985879} :zoom 14}
:phone "tel:+1-212-260-7853"
:address "136 E 3rd St, New York, NY 10009"
:storeLink "https://www.stmarksbookshop.com"
:storeName "<NAME>. Mark's Bookshop"}
{:id 7
:city :nyc
:type :site
:map {:center {:latitude 40.729197 :longitude -73.957319} :zoom 14}
:phone "tel:+1-718-383-0096"
:address "126 Franklin St, Brooklyn, NY 11222"
:storeLink "https://www.wordbookstores.com"
:storeName "Word Bookstore"}
{:id 8
:city :bos
:type :site
:map {:center {:latitude 42.342695 :longitude -71.121423} :zoom 14}
:phone "tel:+1-617-566-6660"
:address "279 Harvard St, Brookline, MA 02446"
:storeLink "https://www.brooklinebooksmith-shop.com"
:storeName "<NAME>"}
{:id 9
:city :bos
:type :site
:map {:center {:latitude 42.314296 :longitude -71.210320} :zoom 14}
:phone "tel:+1-617-964-7440"
:address "82 Needham St, Newton, MA 02461"
:storeLink "https://www.nebookfair.com"
:storeName "New England Mobile Book Fair"}
{:id 10
:city :bos
:type :solr
:map {:center {:latitude 42.366121 :longitude -71.105278} :zoom 14}
:phone "tel:+1-617-547-3721"
:address "4 Pleasant St, Cambridge, MA 02139"
:storeLink "https://www.pandemoniumbooks.com"
:storeName "Pandemonium Books and Games"}
{:id 11
:city :bos
:type :site
:map {:center {:latitude 42.389177 :longitude -71.118252} :zoom 14}
:phone "tel:+1-617-491-2220"
:address "25 White St, Cambridge, MA 02140"
:storeLink "https://www.portersquarebooks.com"
:storeName "Porter Square Books"}
{:id 12
:city :chi
:type :site
:map {:center {:latitude 41.967562 :longitude -87.687986} :zoom 14}
:phone "tel:+1-773-293-2665"
:address "4736 N Lincoln Ave, Chicago, IL 60625"
:storeLink "https://www.bookcellarinc.com"
:storeName "The Book Cellar"}
{:id 13
:city :chi
:type :solr
:map {:center {:latitude 41.926976 :longitude -87.707253} :zoom 14}
:phone "tel:+1-773-235-2523"
:address "2523 N Kedzie Blvd, Chicago, IL 60647"
:storeLink "https://www.citylitbooks.com"
:storeName "City Lit Books"}
{:id 14
:city :chi
:type :site
:map {:center {:latitude 41.790024 :longitude -87.595605} :zoom 14}
:phone "tel:+1-773-752-4381"
:address "5751 S Woodlawn Ave, Chicago, IL 60637"
:storeLink "https://www.semcoop.com"
:storeName "Seminary Co-op Bookstores"}
{:id 15
:city :chi
:type :solr
:map {:center {:latitude 41.941585 :longitude -87.643732} :zoom 14}
:phone "tel:+1-773-883-9119"
:address "3251 N Broadway St, Chicago, IL 60657"
:storeLink "https://www.unabridgedbookstore.com"
:storeName "Unabridged Bookstore"}
{:id 16
:city :chi
:type :solr
:map {:center {:latitude 41.977334 :longitude -87.667873} :zoom 14}
:phone "tel:+1-773-769-9299"
:address "5233 N Clark St, Chicago, IL 60640"
:storeLink "https://www.womenandchildrenfirst.com"
:storeName "Women and Children First"}
{:id 17
:city :msp
:type :site
:map {:center {:latitude 44.940447 :longitude -93.166282} :zoom 14}
:phone "tel:+1-651-225-8989"
:address "38 Snelling Ave S, St Paul, MN 55105"
:storeLink "https://www.commongoodbooks.com"
:storeName "Common Good Books"}
{:id 18
:city :msp
:type :site
:map {:center {:latitude 44.940247 :longitude -93.137250} :zoom 14}
:phone "tel:+1-651-224-8320"
:address "891 Grand Ave, St Paul, MN 55105"
:storeLink "https://www.redballoonbookshop.com"
:storeName "Red Balloon Bookshop"}
{:id 19
:city :msp
:type :site
:map {:center {:latitude 45.057563 :longitude -92.805685} :zoom 14}
:phone "tel:+1-651-430-3385"
:address "217 Main St N, Stillwater, MN 55082"
:storeLink "https://www.valleybookseller.com"
:storeName "Valley Bookseller"}
{:id 20
:city :msp
:type :site
:map {:center {:latitude 44.924730 :longitude -93.313411} :zoom 14}
:phone "tel:+1-612-920-5005"
:address "2720 W 43rd St, Minneapolis, MN 55410"
:storeLink "https://www.wildrumpusbooks.com"
:storeName "Wild Rumpus"}
{:id 21
:city :pdx
:type :site
:map {:center {:latitude 45.467730 :longitude -122.713105} :zoom 14}
:phone "tel:+1-503-246-0053"
:address "7834 SW Capitol Hwy, Portland, OR 97219"
:storeLink "https://www.annieblooms.com"
:storeName "<NAME> Books"}
{:id 22
:city :pdx
:type :site
:map {:center {:latitude 45.535182 :longitude -122.648269} :zoom 14}
:phone "tel:+1-503-284-1726"
:address "1714 NE Broadway St, Portland, OR 97232"
:storeLink "https://www.broadwaybooks.net"
:storeName "Broadway Books"}
{:id 23
:city :pdx
:type :powells
:map {:center {:latitude 45.523377 :longitude -122.681319} :zoom 14}
:phone "tel:+1-503-228-4651"
:address "1005 W Burnside St, Portland, OR 97209"
:storeLink "https://www.powells.com/"
:storeName "Powell's Books"}
{:id 24
:city :sea
:type :site
:map {:center {:latitude 47.614661 :longitude -122.319602} :zoom 14}
:phone "tel:+1-206-624-6600"
:address "1521 10th Ave, Seattle, WA 98122"
:storeLink "https://www.elliottbaybook.com"
:storeName "The Elliott Bay Book Company"}
{:id 25
:city :sea
:type :site
:map {:center {:latitude 47.261673 :longitude -122.445302} :zoom 14}
:phone "tel:+1-253-272-8801"
:address "218 St Helens Ave, Tacoma, WA 98402"
:storeLink "https://www.kingsbookstore.com"
:storeName "King's Books"}
{:id 26
:city :sea
:type :site
:map {:center {:latitude 47.602697 :longitude -122.332991} :zoom 14}
:phone "tel:+1-206-587-5737"
:address "117 Cherry St, Seattle, WA 98104"
:storeLink "https://www.seattlemystery.com"
:storeName "Seattle Mystery Bookshop"}
{:id 27
:city :sea
:type :solr
:map {:center {:latitude 47.668888 :longitude -122.384664} :zoom 14}
:phone "tel:+1-206-789-5006"
:address "2214 NW Market St, Seattle, WA 98107"
:storeLink "https://www.secretgardenbooks.com"
:storeName "The Secret Garden Bookshop"}
{:id 28
:city :sea
:type :site
:map {:center {:latitude 47.753232 :longitude -122.280014} :zoom 14}
:phone "tel:+1-206-366-3333"
:address "6504 20th Ave NE, Seattle, WA 98115"
:storeLink "https://www.thirdplacebooks.com"
:storeName "Third Place Books"}]
| true | [{:id 0
:city :nyc
:type :site
:map {:center {:latitude 40.763754 :longitude -73.923849} :zoom 14}
:phone "tel:+1-718-278-2665"
:address "31-29 31st St, New York, NY 11106"
:storeLink "https://www.astoriabookshop.com"
:storeName "Astoria Bookshop"}
{:id 1
:city :nyc
:type :site
:map {:center {:latitude 40.805786 :longitude -73.966143} :zoom 14}
:phone "tel:+1-212-678-1654"
:address "2780 Broadway, New York, NY 10025"
:storeLink "https://www.bankstreetbooks.com"
:storeName "Bank Street Books"}
{:id 2
:city :nyc
:type :site
:map {:center {:latitude 40.805135 :longitude -73.964991} :zoom 14}
:phone "tel:+1-212-865-1588"
:address "536 W 112th St, New York, NY 10025"
:storeLink "https://www.bookculture.com"
:storeName "Book Culture"}
{:id 3
:city :nyc
:type :booksite
:map {:center {:latitude 40.672900 :longitude -73.976457} :zoom 14}
:phone "tel:+1-718-783-3075"
:address "143 7th Ave, Brooklyn, NY 11215"
:storeLink "https://site.booksite.com/6994"
:storeName "Community Bookstore"}
{:id 4
:city :nyc
:type :site
:map {:center {:latitude 40.686502 :longitude -73.974571} :zoom 14}
:phone "tel:+1-718-246-0200"
:address "686 Fulton St, Brooklyn, NY 11217"
:storeLink "https://www.greenlightbookstore.com"
:storeName "Greenlight Bookstore"}
{:id 5
:city :nyc
:type :solr
:map {:center {:latitude 40.723518 :longitude -73.996061} :zoom 14}
:phone "tel:+1-212-274-1160"
:address "52 Prince St, New York, NY 10012"
:storeLink "https://www.mcnallyjackson.com"
:storeName "PI:NAME:<NAME>END_PI"}
{:id 6
:city :nyc
:type :site
:map {:center {:latitude 40.724005 :longitude -73.985879} :zoom 14}
:phone "tel:+1-212-260-7853"
:address "136 E 3rd St, New York, NY 10009"
:storeLink "https://www.stmarksbookshop.com"
:storeName "PI:NAME:<NAME>END_PI. Mark's Bookshop"}
{:id 7
:city :nyc
:type :site
:map {:center {:latitude 40.729197 :longitude -73.957319} :zoom 14}
:phone "tel:+1-718-383-0096"
:address "126 Franklin St, Brooklyn, NY 11222"
:storeLink "https://www.wordbookstores.com"
:storeName "Word Bookstore"}
{:id 8
:city :bos
:type :site
:map {:center {:latitude 42.342695 :longitude -71.121423} :zoom 14}
:phone "tel:+1-617-566-6660"
:address "279 Harvard St, Brookline, MA 02446"
:storeLink "https://www.brooklinebooksmith-shop.com"
:storeName "PI:NAME:<NAME>END_PI"}
{:id 9
:city :bos
:type :site
:map {:center {:latitude 42.314296 :longitude -71.210320} :zoom 14}
:phone "tel:+1-617-964-7440"
:address "82 Needham St, Newton, MA 02461"
:storeLink "https://www.nebookfair.com"
:storeName "New England Mobile Book Fair"}
{:id 10
:city :bos
:type :solr
:map {:center {:latitude 42.366121 :longitude -71.105278} :zoom 14}
:phone "tel:+1-617-547-3721"
:address "4 Pleasant St, Cambridge, MA 02139"
:storeLink "https://www.pandemoniumbooks.com"
:storeName "Pandemonium Books and Games"}
{:id 11
:city :bos
:type :site
:map {:center {:latitude 42.389177 :longitude -71.118252} :zoom 14}
:phone "tel:+1-617-491-2220"
:address "25 White St, Cambridge, MA 02140"
:storeLink "https://www.portersquarebooks.com"
:storeName "Porter Square Books"}
{:id 12
:city :chi
:type :site
:map {:center {:latitude 41.967562 :longitude -87.687986} :zoom 14}
:phone "tel:+1-773-293-2665"
:address "4736 N Lincoln Ave, Chicago, IL 60625"
:storeLink "https://www.bookcellarinc.com"
:storeName "The Book Cellar"}
{:id 13
:city :chi
:type :solr
:map {:center {:latitude 41.926976 :longitude -87.707253} :zoom 14}
:phone "tel:+1-773-235-2523"
:address "2523 N Kedzie Blvd, Chicago, IL 60647"
:storeLink "https://www.citylitbooks.com"
:storeName "City Lit Books"}
{:id 14
:city :chi
:type :site
:map {:center {:latitude 41.790024 :longitude -87.595605} :zoom 14}
:phone "tel:+1-773-752-4381"
:address "5751 S Woodlawn Ave, Chicago, IL 60637"
:storeLink "https://www.semcoop.com"
:storeName "Seminary Co-op Bookstores"}
{:id 15
:city :chi
:type :solr
:map {:center {:latitude 41.941585 :longitude -87.643732} :zoom 14}
:phone "tel:+1-773-883-9119"
:address "3251 N Broadway St, Chicago, IL 60657"
:storeLink "https://www.unabridgedbookstore.com"
:storeName "Unabridged Bookstore"}
{:id 16
:city :chi
:type :solr
:map {:center {:latitude 41.977334 :longitude -87.667873} :zoom 14}
:phone "tel:+1-773-769-9299"
:address "5233 N Clark St, Chicago, IL 60640"
:storeLink "https://www.womenandchildrenfirst.com"
:storeName "Women and Children First"}
{:id 17
:city :msp
:type :site
:map {:center {:latitude 44.940447 :longitude -93.166282} :zoom 14}
:phone "tel:+1-651-225-8989"
:address "38 Snelling Ave S, St Paul, MN 55105"
:storeLink "https://www.commongoodbooks.com"
:storeName "Common Good Books"}
{:id 18
:city :msp
:type :site
:map {:center {:latitude 44.940247 :longitude -93.137250} :zoom 14}
:phone "tel:+1-651-224-8320"
:address "891 Grand Ave, St Paul, MN 55105"
:storeLink "https://www.redballoonbookshop.com"
:storeName "Red Balloon Bookshop"}
{:id 19
:city :msp
:type :site
:map {:center {:latitude 45.057563 :longitude -92.805685} :zoom 14}
:phone "tel:+1-651-430-3385"
:address "217 Main St N, Stillwater, MN 55082"
:storeLink "https://www.valleybookseller.com"
:storeName "Valley Bookseller"}
{:id 20
:city :msp
:type :site
:map {:center {:latitude 44.924730 :longitude -93.313411} :zoom 14}
:phone "tel:+1-612-920-5005"
:address "2720 W 43rd St, Minneapolis, MN 55410"
:storeLink "https://www.wildrumpusbooks.com"
:storeName "Wild Rumpus"}
{:id 21
:city :pdx
:type :site
:map {:center {:latitude 45.467730 :longitude -122.713105} :zoom 14}
:phone "tel:+1-503-246-0053"
:address "7834 SW Capitol Hwy, Portland, OR 97219"
:storeLink "https://www.annieblooms.com"
:storeName "PI:NAME:<NAME>END_PI Books"}
{:id 22
:city :pdx
:type :site
:map {:center {:latitude 45.535182 :longitude -122.648269} :zoom 14}
:phone "tel:+1-503-284-1726"
:address "1714 NE Broadway St, Portland, OR 97232"
:storeLink "https://www.broadwaybooks.net"
:storeName "Broadway Books"}
{:id 23
:city :pdx
:type :powells
:map {:center {:latitude 45.523377 :longitude -122.681319} :zoom 14}
:phone "tel:+1-503-228-4651"
:address "1005 W Burnside St, Portland, OR 97209"
:storeLink "https://www.powells.com/"
:storeName "Powell's Books"}
{:id 24
:city :sea
:type :site
:map {:center {:latitude 47.614661 :longitude -122.319602} :zoom 14}
:phone "tel:+1-206-624-6600"
:address "1521 10th Ave, Seattle, WA 98122"
:storeLink "https://www.elliottbaybook.com"
:storeName "The Elliott Bay Book Company"}
{:id 25
:city :sea
:type :site
:map {:center {:latitude 47.261673 :longitude -122.445302} :zoom 14}
:phone "tel:+1-253-272-8801"
:address "218 St Helens Ave, Tacoma, WA 98402"
:storeLink "https://www.kingsbookstore.com"
:storeName "King's Books"}
{:id 26
:city :sea
:type :site
:map {:center {:latitude 47.602697 :longitude -122.332991} :zoom 14}
:phone "tel:+1-206-587-5737"
:address "117 Cherry St, Seattle, WA 98104"
:storeLink "https://www.seattlemystery.com"
:storeName "Seattle Mystery Bookshop"}
{:id 27
:city :sea
:type :solr
:map {:center {:latitude 47.668888 :longitude -122.384664} :zoom 14}
:phone "tel:+1-206-789-5006"
:address "2214 NW Market St, Seattle, WA 98107"
:storeLink "https://www.secretgardenbooks.com"
:storeName "The Secret Garden Bookshop"}
{:id 28
:city :sea
:type :site
:map {:center {:latitude 47.753232 :longitude -122.280014} :zoom 14}
:phone "tel:+1-206-366-3333"
:address "6504 20th Ave NE, Seattle, WA 98115"
:storeLink "https://www.thirdplacebooks.com"
:storeName "Third Place Books"}]
|
[
{
"context": "{\n :server-port 8080\n :users {\"admin\" \"password\"}\n :default-node \"hbase-zookeeper:2181",
"end": 36,
"score": 0.9853060841560364,
"start": 31,
"tag": "USERNAME",
"value": "admin"
},
{
"context": "{\n :server-port 8080\n :users {\"admin\" \"password\"}\n :default-node \"hbase-zookeeper:2181/\"\n}\n",
"end": 47,
"score": 0.9986995458602905,
"start": 39,
"tag": "PASSWORD",
"value": "password"
}
] | config/zkweb/zk-web-conf.clj | Stono/bigdata-fun | 15 | {
:server-port 8080
:users {"admin" "password"}
:default-node "hbase-zookeeper:2181/"
}
| 83096 | {
:server-port 8080
:users {"admin" "<PASSWORD>"}
:default-node "hbase-zookeeper:2181/"
}
| true | {
:server-port 8080
:users {"admin" "PI:PASSWORD:<PASSWORD>END_PI"}
:default-node "hbase-zookeeper:2181/"
}
|
[
{
"context": " :where [[?v :vehicle/brand \"Aston Martin\"]]})))\n\n (t/is (= #{[{}]}\n (xt",
"end": 941,
"score": 0.9897982478141785,
"start": 929,
"tag": "NAME",
"value": "Aston Martin"
},
{
"context": " :where [[?v :vehicle/brand \"Aston Martin\"]]}))))\n\n (t/testing \"simple props\"\n (let",
"end": 1098,
"score": 0.9933660626411438,
"start": 1086,
"tag": "NAME",
"value": "Aston Martin"
},
{
"context": "e props\"\n (let [expected #{[{:vehicle/brand \"Aston Martin\", :vehicle/model \"DB5\"}]\n [",
"end": 1191,
"score": 0.9943954944610596,
"start": 1179,
"tag": "NAME",
"value": "Aston Martin"
},
{
"context": " \"DB5\"}]\n [{:vehicle/brand \"Aston Martin\", :vehicle/model \"DB10\"}]\n ",
"end": 1270,
"score": 0.993615448474884,
"start": 1258,
"tag": "NAME",
"value": "Aston Martin"
},
{
"context": "\"DB10\"}]\n [{:vehicle/brand \"Aston Martin\", :vehicle/model \"DBS\"}]\n [",
"end": 1350,
"score": 0.9934303164482117,
"start": 1338,
"tag": "NAME",
"value": "Aston Martin"
},
{
"context": " \"DBS\"}]\n [{:vehicle/brand \"Aston Martin\", :vehicle/model \"DBS V12\"}]\n ",
"end": 1429,
"score": 0.9885937571525574,
"start": 1417,
"tag": "NAME",
"value": "Aston Martin"
},
{
"context": "S V12\"}]\n [{:vehicle/brand \"Aston Martin\", :vehicle/model \"V8 Vantage Volante\"}]\n ",
"end": 1512,
"score": 0.991319477558136,
"start": 1500,
"tag": "NAME",
"value": "Aston Martin"
},
{
"context": "lante\"}]\n [{:vehicle/brand \"Aston Martin\", :vehicle/model \"V12 Vanquish\"}]}]\n (let ",
"end": 1606,
"score": 0.9897994995117188,
"start": 1594,
"tag": "NAME",
"value": "Aston Martin"
},
{
"context": " :where [[?v :vehicle/brand \"Aston Martin\"]]})))\n (t/is (= [6] @!lookup-counts) ",
"end": 1940,
"score": 0.999267578125,
"start": 1928,
"tag": "NAME",
"value": "Aston Martin"
},
{
"context": " :where [[?v :vehicle/brand \"Aston Martin\"]]\n :batch-size 3}",
"end": 2310,
"score": 0.9989873766899109,
"start": 2298,
"tag": "NAME",
"value": "Aston Martin"
},
{
"context": " (t/testing \"renames\"\n (t/is (= #{[{:brand \"Aston Martin\", :model \"DB5\"}]\n [{:brand \"Aston",
"end": 2497,
"score": 0.999460756778717,
"start": 2485,
"tag": "NAME",
"value": "Aston Martin"
},
{
"context": "artin\", :model \"DB5\"}]\n [{:brand \"Aston Martin\", :model \"DB10\"}]\n [{:brand \"Asto",
"end": 2554,
"score": 0.9992084503173828,
"start": 2542,
"tag": "NAME",
"value": "Aston Martin"
},
{
"context": "rtin\", :model \"DB10\"}]\n [{:brand \"Aston Martin\", :model \"DBS\"}]\n [{:brand \"Aston",
"end": 2612,
"score": 0.9993272423744202,
"start": 2600,
"tag": "NAME",
"value": "Aston Martin"
},
{
"context": "artin\", :model \"DBS\"}]\n [{:brand \"Aston Martin\", :model \"DBS V12\"}]\n [{:brand \"A",
"end": 2669,
"score": 0.9992287755012512,
"start": 2657,
"tag": "NAME",
"value": "Aston Martin"
},
{
"context": "n\", :model \"DBS V12\"}]\n [{:brand \"Aston Martin\", :model \"V8 Vantage Volante\"}]\n ",
"end": 2730,
"score": 0.9990230202674866,
"start": 2718,
"tag": "NAME",
"value": "Aston Martin"
},
{
"context": "\"V8 Vantage Volante\"}]\n [{:brand \"Aston Martin\", :model \"V12 Vanquish\"}]}\n\n (xt/q ",
"end": 2802,
"score": 0.9991539120674133,
"start": 2790,
"tag": "NAME",
"value": "Aston Martin"
},
{
"context": " :where [[?v :vehicle/brand \"Aston Martin\"]]}))))\n\n (t/testing \"forward joins\"\n (le",
"end": 3046,
"score": 0.9990711212158203,
"start": 3034,
"tag": "NAME",
"value": "Aston Martin"
},
{
"context": "\n :film/bond {:person/name \"Pierce Brosnan\"},\n :film/director {:person",
"end": 3353,
"score": 0.9998612999916077,
"start": 3339,
"tag": "NAME",
"value": "Pierce Brosnan"
},
{
"context": " :film/director {:person/name \"Lee Tamahori\"},\n :film/vehicles #{{:vehi",
"end": 3422,
"score": 0.9998809695243835,
"start": 3410,
"tag": "NAME",
"value": "Lee Tamahori"
},
{
"context": " {:vehicle/brand \"Aston Martin\", :vehicle/model \"V12 Vanquish\"}\n ",
"end": 3583,
"score": 0.9270407557487488,
"start": 3571,
"tag": "NAME",
"value": "Aston Martin"
},
{
"context": "kup-counts)]\n (t/is (= #{[{:person/name \"Daniel Craig\",\n :film/_bond #{#:film{:na",
"end": 4474,
"score": 0.9998794198036194,
"start": 4462,
"tag": "NAME",
"value": "Daniel Craig"
},
{
"context": " :where [[?dc :person/name \"Daniel Craig\"]]})))\n (t/is (= [5] @!lookup-counts) \"b",
"end": 5030,
"score": 0.9998689889907837,
"start": 5018,
"tag": "NAME",
"value": "Daniel Craig"
},
{
"context": "e joins, rename\"\n (t/is (= #{[{:person/name \"Daniel Craig\",\n :films [#:film{:name \"Skyfal",
"end": 5186,
"score": 0.9998697638511658,
"start": 5174,
"tag": "NAME",
"value": "Daniel Craig"
},
{
"context": " :where [[?dc :person/name \"Daniel Craig\"]]}))))\n\n (t/testing \"pull *\"\n (t/is (= #",
"end": 5691,
"score": 0.997124195098877,
"start": 5679,
"tag": "NAME",
"value": "Daniel Craig"
},
{
"context": " (t/testing \"pull *\"\n (t/is (= #{[{:xt/id :daniel-craig\n :person/name \"Daniel Craig\",\n ",
"end": 5764,
"score": 0.9976711273193359,
"start": 5752,
"tag": "USERNAME",
"value": "daniel-craig"
},
{
"context": "id :daniel-craig\n :person/name \"Daniel Craig\",\n :type :person}]}\n ",
"end": 5810,
"score": 0.9998557567596436,
"start": 5798,
"tag": "NAME",
"value": "Daniel Craig"
},
{
"context": " :where [[?dc :person/name \"Daniel Craig\"]]}))))\n\n (t/testing \"pull fn\"\n (t/is (= ",
"end": 5963,
"score": 0.9997530579566956,
"start": 5951,
"tag": "NAME",
"value": "Daniel Craig"
},
{
"context": "\n :film/bond {:person/name \"Pierce Brosnan\"},\n :film/director {:person",
"end": 8320,
"score": 0.999886691570282,
"start": 8306,
"tag": "NAME",
"value": "Pierce Brosnan"
},
{
"context": " :film/director {:person/name \"Lee Tamahori\"},\n :film/vehicles #{{:vehi",
"end": 8389,
"score": 0.999899685382843,
"start": 8377,
"tag": "NAME",
"value": "Lee Tamahori"
},
{
"context": "kup-counts)]\n (t/is (= #{[{:person/name \"Daniel Craig\",\n :film/_bond #{#:film{:na",
"end": 9266,
"score": 0.9998672008514404,
"start": 9254,
"tag": "NAME",
"value": "Daniel Craig"
},
{
"context": " :where [[?dc :person/name \"Daniel Craig\"]]})))\n (t/is (= [3] @!lookup-counts) \"b",
"end": 9666,
"score": 0.9998660087585449,
"start": 9654,
"tag": "NAME",
"value": "Daniel Craig"
}
] | core/test/xtdb/pull_test.clj | juxt/ding | 0 | (ns xtdb.pull-test
(:require [clojure.test :as t]
[xtdb.api :as xt]
[xtdb.fixtures :as fix :refer [*api*]]
[xtdb.pull :as pull]
[clojure.java.io :as io]))
(t/use-fixtures :each fix/with-node)
(defn- submit-bond []
(fix/submit+await-tx (for [doc (read-string (slurp (io/resource "data/james-bond.edn")))]
[::xt/put doc]))
(xt/db *api*))
(def ->lookup-docs
(let [f @#'pull/lookup-docs]
(fn [!lookup-counts]
(fn [v db]
(swap! !lookup-counts conj (count (::pull/hashes (meta v))))
(f v db)))))
(t/deftest test-pull
(let [db (submit-bond)]
(t/testing "empty cases"
(t/is (= #{}
(xt/q db '{:find [(pull ?v [])]
:where [[?v :not/here "N/A"]]})))
(t/is (= #{[nil]}
(xt/q db '{:find [(pull ?v [])]
:where [[?v :vehicle/brand "Aston Martin"]]})))
(t/is (= #{[{}]}
(xt/q db '{:find [(pull ?v [:doesntexist])]
:where [[?v :vehicle/brand "Aston Martin"]]}))))
(t/testing "simple props"
(let [expected #{[{:vehicle/brand "Aston Martin", :vehicle/model "DB5"}]
[{:vehicle/brand "Aston Martin", :vehicle/model "DB10"}]
[{:vehicle/brand "Aston Martin", :vehicle/model "DBS"}]
[{:vehicle/brand "Aston Martin", :vehicle/model "DBS V12"}]
[{:vehicle/brand "Aston Martin", :vehicle/model "V8 Vantage Volante"}]
[{:vehicle/brand "Aston Martin", :vehicle/model "V12 Vanquish"}]}]
(let [!lookup-counts (atom [])]
(with-redefs [pull/lookup-docs (->lookup-docs !lookup-counts)]
(t/is (= expected
(xt/q db '{:find [(pull ?v [:vehicle/brand :vehicle/model])]
:where [[?v :vehicle/brand "Aston Martin"]]})))
(t/is (= [6] @!lookup-counts) "batching lookups")))
(let [!lookup-counts (atom [])]
(with-redefs [pull/lookup-docs (->lookup-docs !lookup-counts)]
(t/is (= expected
(xt/q db '{:find [(pull ?v [:vehicle/brand :vehicle/model])]
:where [[?v :vehicle/brand "Aston Martin"]]
:batch-size 3})))
(t/is (= [3 3] @!lookup-counts) "batching lookups")))))
(t/testing "renames"
(t/is (= #{[{:brand "Aston Martin", :model "DB5"}]
[{:brand "Aston Martin", :model "DB10"}]
[{:brand "Aston Martin", :model "DBS"}]
[{:brand "Aston Martin", :model "DBS V12"}]
[{:brand "Aston Martin", :model "V8 Vantage Volante"}]
[{:brand "Aston Martin", :model "V12 Vanquish"}]}
(xt/q db '{:find [(pull ?v [(:vehicle/brand {:as :brand})
(:vehicle/model {:as :model})])]
:where [[?v :vehicle/brand "Aston Martin"]]}))))
(t/testing "forward joins"
(let [!lookup-counts (atom [])]
(with-redefs [pull/lookup-docs (->lookup-docs !lookup-counts)]
(t/is (= #{[{:film/year "2002",
:film/name "Die Another Day"
:film/bond {:person/name "Pierce Brosnan"},
:film/director {:person/name "Lee Tamahori"},
:film/vehicles #{{:vehicle/brand "Jaguar", :vehicle/model "XKR"}
{:vehicle/brand "Aston Martin", :vehicle/model "V12 Vanquish"}
{:vehicle/brand "Ford", :vehicle/model "Thunderbird"}
{:vehicle/brand "Ford", :vehicle/model "Fairlane"}}}]}
(xt/q db '{:find [(pull ?f [{:film/bond [:person/name]}
{:film/director [:person/name]}
{(:film/vehicles {:into #{}}) [:vehicle/brand :vehicle/model]}
:film/name :film/year])]
:where [[?f :film/name "Die Another Day"]]})))
(t/is (= [1 6] @!lookup-counts) "batching lookups"))))
(t/testing "reverse joins"
(let [!lookup-counts (atom [])]
(with-redefs [pull/lookup-docs (->lookup-docs !lookup-counts)]
(t/is (= #{[{:person/name "Daniel Craig",
:film/_bond #{#:film{:name "Skyfall", :year "2012"}
#:film{:name "Spectre", :year "2015"}
#:film{:name "Casino Royale", :year "2006"}
#:film{:name "Quantum of Solace", :year "2008"}}}]}
(xt/q db '{:find [(pull ?dc [:person/name
{(:film/_bond {:into #{}}) [:film/name :film/year]}])]
:where [[?dc :person/name "Daniel Craig"]]})))
(t/is (= [5] @!lookup-counts) "batching lookups"))))
(t/testing "reverse joins, rename"
(t/is (= #{[{:person/name "Daniel Craig",
:films [#:film{:name "Skyfall", :year "2012"}
#:film{:name "Spectre", :year "2015"}
#:film{:name "Casino Royale", :year "2006"}
#:film{:name "Quantum of Solace", :year "2008"}]}]}
(xt/q db '{:find [(pull ?dc [:person/name
{(:film/_bond {:as :films}) [:film/name :film/year]}])]
:where [[?dc :person/name "Daniel Craig"]]}))))
(t/testing "pull *"
(t/is (= #{[{:xt/id :daniel-craig
:person/name "Daniel Craig",
:type :person}]}
(xt/q db '{:find [(pull ?dc [*])]
:where [[?dc :person/name "Daniel Craig"]]}))))
(t/testing "pull fn"
(t/is (= #:film{:name "Spectre", :year "2015"}
(xt/pull db (pr-str [:film/name :film/year]) :spectre)))
(t/is (= #:film{:name "Spectre", :year "2015"}
(xt/pull db [:film/name :film/year] :spectre))))
(t/testing "pullMany fn"
(t/is (= #{#:film{:name "Skyfall", :year "2012"}
#:film{:name "Spectre", :year "2015"}}
(set (xt/pull-many db (pr-str [:film/name :film/year]) #{:skyfall :spectre}))))
(t/is (= #{#:film{:name "Skyfall", :year "2012"}
#:film{:name "Spectre", :year "2015"}}
(set (xt/pull-many db [:film/name :film/year] #{:skyfall :spectre})))))
(t/testing "pull many respects order and cardinality of input eids"
(t/is [= [#:film{:name "Spectre", :year "2015"}
nil
#:film{:name "Skyfall", :year "2012"}]
(xt/pull-many db [:film/name :film/year] [:spectre :doesnt-exist :skyfall])])
(t/is [= [#:film{:name "Skyfall", :year "2012"}
nil
#:film{:name "Spectre", :year "2015"}
nil]
(xt/pull-many db [:film/name :film/year] [:skyfall :doesnt-exist :spectre :nor-does-this])]))
(t/testing "pullMany fn vector"
(t/is (= #{#:film {:name "Skyfall", :year "2012"}
#:film {:name "Spectre", :year "2015"}}
(set (xt/pull-many db (pr-str [:film/name :film/year]) #{:skyfall :spectre}))))
(t/is (= #{#:film {:name "Skyfall", :year "2012"}
#:film {:name "Spectre", :year "2015"}}
(set (xt/pull-many db [:film/name :film/year] #{:skyfall :spectre})))))))
(t/deftest test-limit
(let [db (submit-bond)]
(t/testing "props"
(t/is (= #{[{:film/name "Die Another Day"
:film/vehicles #{:xkr :v12-vanquish}}]}
(xt/q db '{:find [(pull ?f [:film/name (:film/vehicles {:into #{}, :limit 2})])]
:where [[?f :film/name "Die Another Day"]]}))))
(t/testing "forward joins"
(let [!lookup-counts (atom [])]
(with-redefs [pull/lookup-docs (->lookup-docs !lookup-counts)]
(t/is (= #{[{:film/year "2002",
:film/name "Die Another Day"
:film/bond {:person/name "Pierce Brosnan"},
:film/director {:person/name "Lee Tamahori"},
:film/vehicles #{{:vehicle/brand "Jaguar", :vehicle/model "XKR"}
{:vehicle/brand "Aston Martin", :vehicle/model "V12 Vanquish"}}}]}
(xt/q db '{:find [(pull ?f [{:film/bond [:person/name]}
{:film/director [:person/name]}
{(:film/vehicles {:into #{}, :limit 2}) [:vehicle/brand :vehicle/model]}
:film/name :film/year])]
:where [[?f :film/name "Die Another Day"]]})))
(t/is (= [1 4] @!lookup-counts) "batching lookups"))))
(t/testing "reverse joins"
(let [!lookup-counts (atom [])]
(with-redefs [pull/lookup-docs (->lookup-docs !lookup-counts)]
(t/is (= #{[{:person/name "Daniel Craig",
:film/_bond #{#:film{:name "Skyfall", :year "2012"}
#:film{:name "Spectre", :year "2015"}}}]}
(xt/q db '{:find [(pull ?dc [:person/name
{(:film/_bond {:into #{}, :limit 2}) [:film/name :film/year]}])]
:where [[?dc :person/name "Daniel Craig"]]})))
(t/is (= [3] @!lookup-counts) "batching lookups"))))))
(t/deftest test-union
(fix/submit+await-tx [[::xt/put {:xt/id :foo
:type :a
:x 2
:y "this"
:z :not-this}]
[::xt/put {:xt/id :bar
:type :b
:y "not this"
:z 5}]])
(t/is (= #{[{:xt/id :foo, :x 2, :y "this"}]
[{:xt/id :bar, :z 5}]}
(xt/q (xt/db *api*)
'{:find [(pull ?it [{:type {:a [:x :y], :b [:z]}}
:xt/id])]
:where [[?it :xt/id]]}))))
(t/deftest test-recursive
(fix/submit+await-tx [[::xt/put {:xt/id :root}]
[::xt/put {:xt/id :a
:parent :root}]
[::xt/put {:xt/id :b
:parent :root}]
[::xt/put {:xt/id :aa
:parent :a}]
[::xt/put {:xt/id :ab
:parent :a}]
[::xt/put {:xt/id :aba
:parent :ab}]
[::xt/put {:xt/id :abb
:parent :ab}]])
(t/testing "forward unbounded recursion"
(t/is (= {:xt/id :aba
:parent {:xt/id :ab
:parent {:xt/id :a
:parent {:xt/id :root}}}}
(ffirst (xt/q (xt/db *api*)
'{:find [(pull ?aba [:xt/id {:parent ...}])]
:where [[?aba :xt/id :aba]]})))))
(t/testing "forward bounded recursion"
(t/is (= {:xt/id :aba
:parent {:xt/id :ab
:parent {:xt/id :a}}}
(ffirst (xt/q (xt/db *api*)
'{:find [(pull ?aba [:xt/id {:parent 2}])]
:where [[?aba :xt/id :aba]]})))))
(t/testing "reverse unbounded recursion"
(t/is (= {:xt/id :root
:_parent [{:xt/id :a
:_parent [{:xt/id :aa}
{:xt/id :ab
:_parent [{:xt/id :aba}
{:xt/id :abb}]}]}
{:xt/id :b}]}
(ffirst (xt/q (xt/db *api*)
'{:find [(pull ?root [:xt/id {:_parent ...}])]
:where [[?root :xt/id :root]]})))))
(t/testing "reverse bounded recursion"
(t/is (= {:xt/id :root
:_parent [{:xt/id :a
:_parent [{:xt/id :aa}
{:xt/id :ab}]}
{:xt/id :b}]}
(ffirst (xt/q (xt/db *api*)
'{:find [(pull ?root [:xt/id {:_parent 2}])]
:where [[?root :xt/id :root]]}))))))
(t/deftest test-doesnt-hang-on-unknown-eid
(t/is (= #{[nil]}
(xt/q (xt/db *api*)
'{:find [(pull ?e [*])]
:in [?e]
:timeout 500}
"doesntexist")))
(t/is (nil? (xt/pull (xt/db *api*) '[*] "doesntexist"))))
(t/deftest test-with-speculative-doc-store
(let [db (xt/with-tx (xt/db *api*) [[::xt/put {:xt/id :foo}]])]
(t/is (= #{[{:xt/id :foo}]}
(xt/q db
'{:find [(pull ?e [*])]
:where [[?e :xt/id :foo]]})))))
(t/deftest test-missing-forward-join
(fix/submit+await-tx [[::xt/put {:xt/id :foo :ref [:bar :baz]}]
[::xt/put {:xt/id :bar}]])
(t/is (= #{[{:ref [{:xt/id :bar} nil]}]}
(xt/q (xt/db *api*)
'{:find [(pull ?it [{:ref [:xt/id]}])]
:where [[?it :xt/id :foo]]}))))
(t/deftest test-missing-forward-join-collection-error-handling-1710
(fix/submit+await-tx [[::xt/put {:xt/id :foo :ref '(:bar :baz)}]
[::xt/put {:xt/id :bar}]])
(t/is (= #{[{}]}
(xt/q (xt/db *api*)
'{:find [(pull ?it [{:ref [:xt/id]}])]
:where [[?it :xt/id :foo]]}))))
| 4308 | (ns xtdb.pull-test
(:require [clojure.test :as t]
[xtdb.api :as xt]
[xtdb.fixtures :as fix :refer [*api*]]
[xtdb.pull :as pull]
[clojure.java.io :as io]))
(t/use-fixtures :each fix/with-node)
(defn- submit-bond []
(fix/submit+await-tx (for [doc (read-string (slurp (io/resource "data/james-bond.edn")))]
[::xt/put doc]))
(xt/db *api*))
(def ->lookup-docs
(let [f @#'pull/lookup-docs]
(fn [!lookup-counts]
(fn [v db]
(swap! !lookup-counts conj (count (::pull/hashes (meta v))))
(f v db)))))
(t/deftest test-pull
(let [db (submit-bond)]
(t/testing "empty cases"
(t/is (= #{}
(xt/q db '{:find [(pull ?v [])]
:where [[?v :not/here "N/A"]]})))
(t/is (= #{[nil]}
(xt/q db '{:find [(pull ?v [])]
:where [[?v :vehicle/brand "<NAME>"]]})))
(t/is (= #{[{}]}
(xt/q db '{:find [(pull ?v [:doesntexist])]
:where [[?v :vehicle/brand "<NAME>"]]}))))
(t/testing "simple props"
(let [expected #{[{:vehicle/brand "<NAME>", :vehicle/model "DB5"}]
[{:vehicle/brand "<NAME>", :vehicle/model "DB10"}]
[{:vehicle/brand "<NAME>", :vehicle/model "DBS"}]
[{:vehicle/brand "<NAME>", :vehicle/model "DBS V12"}]
[{:vehicle/brand "<NAME>", :vehicle/model "V8 Vantage Volante"}]
[{:vehicle/brand "<NAME>", :vehicle/model "V12 Vanquish"}]}]
(let [!lookup-counts (atom [])]
(with-redefs [pull/lookup-docs (->lookup-docs !lookup-counts)]
(t/is (= expected
(xt/q db '{:find [(pull ?v [:vehicle/brand :vehicle/model])]
:where [[?v :vehicle/brand "<NAME>"]]})))
(t/is (= [6] @!lookup-counts) "batching lookups")))
(let [!lookup-counts (atom [])]
(with-redefs [pull/lookup-docs (->lookup-docs !lookup-counts)]
(t/is (= expected
(xt/q db '{:find [(pull ?v [:vehicle/brand :vehicle/model])]
:where [[?v :vehicle/brand "<NAME>"]]
:batch-size 3})))
(t/is (= [3 3] @!lookup-counts) "batching lookups")))))
(t/testing "renames"
(t/is (= #{[{:brand "<NAME>", :model "DB5"}]
[{:brand "<NAME>", :model "DB10"}]
[{:brand "<NAME>", :model "DBS"}]
[{:brand "<NAME>", :model "DBS V12"}]
[{:brand "<NAME>", :model "V8 Vantage Volante"}]
[{:brand "<NAME>", :model "V12 Vanquish"}]}
(xt/q db '{:find [(pull ?v [(:vehicle/brand {:as :brand})
(:vehicle/model {:as :model})])]
:where [[?v :vehicle/brand "<NAME>"]]}))))
(t/testing "forward joins"
(let [!lookup-counts (atom [])]
(with-redefs [pull/lookup-docs (->lookup-docs !lookup-counts)]
(t/is (= #{[{:film/year "2002",
:film/name "Die Another Day"
:film/bond {:person/name "<NAME>"},
:film/director {:person/name "<NAME>"},
:film/vehicles #{{:vehicle/brand "Jaguar", :vehicle/model "XKR"}
{:vehicle/brand "<NAME>", :vehicle/model "V12 Vanquish"}
{:vehicle/brand "Ford", :vehicle/model "Thunderbird"}
{:vehicle/brand "Ford", :vehicle/model "Fairlane"}}}]}
(xt/q db '{:find [(pull ?f [{:film/bond [:person/name]}
{:film/director [:person/name]}
{(:film/vehicles {:into #{}}) [:vehicle/brand :vehicle/model]}
:film/name :film/year])]
:where [[?f :film/name "Die Another Day"]]})))
(t/is (= [1 6] @!lookup-counts) "batching lookups"))))
(t/testing "reverse joins"
(let [!lookup-counts (atom [])]
(with-redefs [pull/lookup-docs (->lookup-docs !lookup-counts)]
(t/is (= #{[{:person/name "<NAME>",
:film/_bond #{#:film{:name "Skyfall", :year "2012"}
#:film{:name "Spectre", :year "2015"}
#:film{:name "Casino Royale", :year "2006"}
#:film{:name "Quantum of Solace", :year "2008"}}}]}
(xt/q db '{:find [(pull ?dc [:person/name
{(:film/_bond {:into #{}}) [:film/name :film/year]}])]
:where [[?dc :person/name "<NAME>"]]})))
(t/is (= [5] @!lookup-counts) "batching lookups"))))
(t/testing "reverse joins, rename"
(t/is (= #{[{:person/name "<NAME>",
:films [#:film{:name "Skyfall", :year "2012"}
#:film{:name "Spectre", :year "2015"}
#:film{:name "Casino Royale", :year "2006"}
#:film{:name "Quantum of Solace", :year "2008"}]}]}
(xt/q db '{:find [(pull ?dc [:person/name
{(:film/_bond {:as :films}) [:film/name :film/year]}])]
:where [[?dc :person/name "<NAME>"]]}))))
(t/testing "pull *"
(t/is (= #{[{:xt/id :daniel-craig
:person/name "<NAME>",
:type :person}]}
(xt/q db '{:find [(pull ?dc [*])]
:where [[?dc :person/name "<NAME>"]]}))))
(t/testing "pull fn"
(t/is (= #:film{:name "Spectre", :year "2015"}
(xt/pull db (pr-str [:film/name :film/year]) :spectre)))
(t/is (= #:film{:name "Spectre", :year "2015"}
(xt/pull db [:film/name :film/year] :spectre))))
(t/testing "pullMany fn"
(t/is (= #{#:film{:name "Skyfall", :year "2012"}
#:film{:name "Spectre", :year "2015"}}
(set (xt/pull-many db (pr-str [:film/name :film/year]) #{:skyfall :spectre}))))
(t/is (= #{#:film{:name "Skyfall", :year "2012"}
#:film{:name "Spectre", :year "2015"}}
(set (xt/pull-many db [:film/name :film/year] #{:skyfall :spectre})))))
(t/testing "pull many respects order and cardinality of input eids"
(t/is [= [#:film{:name "Spectre", :year "2015"}
nil
#:film{:name "Skyfall", :year "2012"}]
(xt/pull-many db [:film/name :film/year] [:spectre :doesnt-exist :skyfall])])
(t/is [= [#:film{:name "Skyfall", :year "2012"}
nil
#:film{:name "Spectre", :year "2015"}
nil]
(xt/pull-many db [:film/name :film/year] [:skyfall :doesnt-exist :spectre :nor-does-this])]))
(t/testing "pullMany fn vector"
(t/is (= #{#:film {:name "Skyfall", :year "2012"}
#:film {:name "Spectre", :year "2015"}}
(set (xt/pull-many db (pr-str [:film/name :film/year]) #{:skyfall :spectre}))))
(t/is (= #{#:film {:name "Skyfall", :year "2012"}
#:film {:name "Spectre", :year "2015"}}
(set (xt/pull-many db [:film/name :film/year] #{:skyfall :spectre})))))))
(t/deftest test-limit
(let [db (submit-bond)]
(t/testing "props"
(t/is (= #{[{:film/name "Die Another Day"
:film/vehicles #{:xkr :v12-vanquish}}]}
(xt/q db '{:find [(pull ?f [:film/name (:film/vehicles {:into #{}, :limit 2})])]
:where [[?f :film/name "Die Another Day"]]}))))
(t/testing "forward joins"
(let [!lookup-counts (atom [])]
(with-redefs [pull/lookup-docs (->lookup-docs !lookup-counts)]
(t/is (= #{[{:film/year "2002",
:film/name "Die Another Day"
:film/bond {:person/name "<NAME>"},
:film/director {:person/name "<NAME>"},
:film/vehicles #{{:vehicle/brand "Jaguar", :vehicle/model "XKR"}
{:vehicle/brand "Aston Martin", :vehicle/model "V12 Vanquish"}}}]}
(xt/q db '{:find [(pull ?f [{:film/bond [:person/name]}
{:film/director [:person/name]}
{(:film/vehicles {:into #{}, :limit 2}) [:vehicle/brand :vehicle/model]}
:film/name :film/year])]
:where [[?f :film/name "Die Another Day"]]})))
(t/is (= [1 4] @!lookup-counts) "batching lookups"))))
(t/testing "reverse joins"
(let [!lookup-counts (atom [])]
(with-redefs [pull/lookup-docs (->lookup-docs !lookup-counts)]
(t/is (= #{[{:person/name "<NAME>",
:film/_bond #{#:film{:name "Skyfall", :year "2012"}
#:film{:name "Spectre", :year "2015"}}}]}
(xt/q db '{:find [(pull ?dc [:person/name
{(:film/_bond {:into #{}, :limit 2}) [:film/name :film/year]}])]
:where [[?dc :person/name "<NAME>"]]})))
(t/is (= [3] @!lookup-counts) "batching lookups"))))))
(t/deftest test-union
(fix/submit+await-tx [[::xt/put {:xt/id :foo
:type :a
:x 2
:y "this"
:z :not-this}]
[::xt/put {:xt/id :bar
:type :b
:y "not this"
:z 5}]])
(t/is (= #{[{:xt/id :foo, :x 2, :y "this"}]
[{:xt/id :bar, :z 5}]}
(xt/q (xt/db *api*)
'{:find [(pull ?it [{:type {:a [:x :y], :b [:z]}}
:xt/id])]
:where [[?it :xt/id]]}))))
(t/deftest test-recursive
(fix/submit+await-tx [[::xt/put {:xt/id :root}]
[::xt/put {:xt/id :a
:parent :root}]
[::xt/put {:xt/id :b
:parent :root}]
[::xt/put {:xt/id :aa
:parent :a}]
[::xt/put {:xt/id :ab
:parent :a}]
[::xt/put {:xt/id :aba
:parent :ab}]
[::xt/put {:xt/id :abb
:parent :ab}]])
(t/testing "forward unbounded recursion"
(t/is (= {:xt/id :aba
:parent {:xt/id :ab
:parent {:xt/id :a
:parent {:xt/id :root}}}}
(ffirst (xt/q (xt/db *api*)
'{:find [(pull ?aba [:xt/id {:parent ...}])]
:where [[?aba :xt/id :aba]]})))))
(t/testing "forward bounded recursion"
(t/is (= {:xt/id :aba
:parent {:xt/id :ab
:parent {:xt/id :a}}}
(ffirst (xt/q (xt/db *api*)
'{:find [(pull ?aba [:xt/id {:parent 2}])]
:where [[?aba :xt/id :aba]]})))))
(t/testing "reverse unbounded recursion"
(t/is (= {:xt/id :root
:_parent [{:xt/id :a
:_parent [{:xt/id :aa}
{:xt/id :ab
:_parent [{:xt/id :aba}
{:xt/id :abb}]}]}
{:xt/id :b}]}
(ffirst (xt/q (xt/db *api*)
'{:find [(pull ?root [:xt/id {:_parent ...}])]
:where [[?root :xt/id :root]]})))))
(t/testing "reverse bounded recursion"
(t/is (= {:xt/id :root
:_parent [{:xt/id :a
:_parent [{:xt/id :aa}
{:xt/id :ab}]}
{:xt/id :b}]}
(ffirst (xt/q (xt/db *api*)
'{:find [(pull ?root [:xt/id {:_parent 2}])]
:where [[?root :xt/id :root]]}))))))
(t/deftest test-doesnt-hang-on-unknown-eid
(t/is (= #{[nil]}
(xt/q (xt/db *api*)
'{:find [(pull ?e [*])]
:in [?e]
:timeout 500}
"doesntexist")))
(t/is (nil? (xt/pull (xt/db *api*) '[*] "doesntexist"))))
(t/deftest test-with-speculative-doc-store
(let [db (xt/with-tx (xt/db *api*) [[::xt/put {:xt/id :foo}]])]
(t/is (= #{[{:xt/id :foo}]}
(xt/q db
'{:find [(pull ?e [*])]
:where [[?e :xt/id :foo]]})))))
(t/deftest test-missing-forward-join
(fix/submit+await-tx [[::xt/put {:xt/id :foo :ref [:bar :baz]}]
[::xt/put {:xt/id :bar}]])
(t/is (= #{[{:ref [{:xt/id :bar} nil]}]}
(xt/q (xt/db *api*)
'{:find [(pull ?it [{:ref [:xt/id]}])]
:where [[?it :xt/id :foo]]}))))
(t/deftest test-missing-forward-join-collection-error-handling-1710
(fix/submit+await-tx [[::xt/put {:xt/id :foo :ref '(:bar :baz)}]
[::xt/put {:xt/id :bar}]])
(t/is (= #{[{}]}
(xt/q (xt/db *api*)
'{:find [(pull ?it [{:ref [:xt/id]}])]
:where [[?it :xt/id :foo]]}))))
| true | (ns xtdb.pull-test
(:require [clojure.test :as t]
[xtdb.api :as xt]
[xtdb.fixtures :as fix :refer [*api*]]
[xtdb.pull :as pull]
[clojure.java.io :as io]))
(t/use-fixtures :each fix/with-node)
(defn- submit-bond []
(fix/submit+await-tx (for [doc (read-string (slurp (io/resource "data/james-bond.edn")))]
[::xt/put doc]))
(xt/db *api*))
(def ->lookup-docs
(let [f @#'pull/lookup-docs]
(fn [!lookup-counts]
(fn [v db]
(swap! !lookup-counts conj (count (::pull/hashes (meta v))))
(f v db)))))
(t/deftest test-pull
(let [db (submit-bond)]
(t/testing "empty cases"
(t/is (= #{}
(xt/q db '{:find [(pull ?v [])]
:where [[?v :not/here "N/A"]]})))
(t/is (= #{[nil]}
(xt/q db '{:find [(pull ?v [])]
:where [[?v :vehicle/brand "PI:NAME:<NAME>END_PI"]]})))
(t/is (= #{[{}]}
(xt/q db '{:find [(pull ?v [:doesntexist])]
:where [[?v :vehicle/brand "PI:NAME:<NAME>END_PI"]]}))))
(t/testing "simple props"
(let [expected #{[{:vehicle/brand "PI:NAME:<NAME>END_PI", :vehicle/model "DB5"}]
[{:vehicle/brand "PI:NAME:<NAME>END_PI", :vehicle/model "DB10"}]
[{:vehicle/brand "PI:NAME:<NAME>END_PI", :vehicle/model "DBS"}]
[{:vehicle/brand "PI:NAME:<NAME>END_PI", :vehicle/model "DBS V12"}]
[{:vehicle/brand "PI:NAME:<NAME>END_PI", :vehicle/model "V8 Vantage Volante"}]
[{:vehicle/brand "PI:NAME:<NAME>END_PI", :vehicle/model "V12 Vanquish"}]}]
(let [!lookup-counts (atom [])]
(with-redefs [pull/lookup-docs (->lookup-docs !lookup-counts)]
(t/is (= expected
(xt/q db '{:find [(pull ?v [:vehicle/brand :vehicle/model])]
:where [[?v :vehicle/brand "PI:NAME:<NAME>END_PI"]]})))
(t/is (= [6] @!lookup-counts) "batching lookups")))
(let [!lookup-counts (atom [])]
(with-redefs [pull/lookup-docs (->lookup-docs !lookup-counts)]
(t/is (= expected
(xt/q db '{:find [(pull ?v [:vehicle/brand :vehicle/model])]
:where [[?v :vehicle/brand "PI:NAME:<NAME>END_PI"]]
:batch-size 3})))
(t/is (= [3 3] @!lookup-counts) "batching lookups")))))
(t/testing "renames"
(t/is (= #{[{:brand "PI:NAME:<NAME>END_PI", :model "DB5"}]
[{:brand "PI:NAME:<NAME>END_PI", :model "DB10"}]
[{:brand "PI:NAME:<NAME>END_PI", :model "DBS"}]
[{:brand "PI:NAME:<NAME>END_PI", :model "DBS V12"}]
[{:brand "PI:NAME:<NAME>END_PI", :model "V8 Vantage Volante"}]
[{:brand "PI:NAME:<NAME>END_PI", :model "V12 Vanquish"}]}
(xt/q db '{:find [(pull ?v [(:vehicle/brand {:as :brand})
(:vehicle/model {:as :model})])]
:where [[?v :vehicle/brand "PI:NAME:<NAME>END_PI"]]}))))
(t/testing "forward joins"
(let [!lookup-counts (atom [])]
(with-redefs [pull/lookup-docs (->lookup-docs !lookup-counts)]
(t/is (= #{[{:film/year "2002",
:film/name "Die Another Day"
:film/bond {:person/name "PI:NAME:<NAME>END_PI"},
:film/director {:person/name "PI:NAME:<NAME>END_PI"},
:film/vehicles #{{:vehicle/brand "Jaguar", :vehicle/model "XKR"}
{:vehicle/brand "PI:NAME:<NAME>END_PI", :vehicle/model "V12 Vanquish"}
{:vehicle/brand "Ford", :vehicle/model "Thunderbird"}
{:vehicle/brand "Ford", :vehicle/model "Fairlane"}}}]}
(xt/q db '{:find [(pull ?f [{:film/bond [:person/name]}
{:film/director [:person/name]}
{(:film/vehicles {:into #{}}) [:vehicle/brand :vehicle/model]}
:film/name :film/year])]
:where [[?f :film/name "Die Another Day"]]})))
(t/is (= [1 6] @!lookup-counts) "batching lookups"))))
(t/testing "reverse joins"
(let [!lookup-counts (atom [])]
(with-redefs [pull/lookup-docs (->lookup-docs !lookup-counts)]
(t/is (= #{[{:person/name "PI:NAME:<NAME>END_PI",
:film/_bond #{#:film{:name "Skyfall", :year "2012"}
#:film{:name "Spectre", :year "2015"}
#:film{:name "Casino Royale", :year "2006"}
#:film{:name "Quantum of Solace", :year "2008"}}}]}
(xt/q db '{:find [(pull ?dc [:person/name
{(:film/_bond {:into #{}}) [:film/name :film/year]}])]
:where [[?dc :person/name "PI:NAME:<NAME>END_PI"]]})))
(t/is (= [5] @!lookup-counts) "batching lookups"))))
(t/testing "reverse joins, rename"
(t/is (= #{[{:person/name "PI:NAME:<NAME>END_PI",
:films [#:film{:name "Skyfall", :year "2012"}
#:film{:name "Spectre", :year "2015"}
#:film{:name "Casino Royale", :year "2006"}
#:film{:name "Quantum of Solace", :year "2008"}]}]}
(xt/q db '{:find [(pull ?dc [:person/name
{(:film/_bond {:as :films}) [:film/name :film/year]}])]
:where [[?dc :person/name "PI:NAME:<NAME>END_PI"]]}))))
(t/testing "pull *"
(t/is (= #{[{:xt/id :daniel-craig
:person/name "PI:NAME:<NAME>END_PI",
:type :person}]}
(xt/q db '{:find [(pull ?dc [*])]
:where [[?dc :person/name "PI:NAME:<NAME>END_PI"]]}))))
(t/testing "pull fn"
(t/is (= #:film{:name "Spectre", :year "2015"}
(xt/pull db (pr-str [:film/name :film/year]) :spectre)))
(t/is (= #:film{:name "Spectre", :year "2015"}
(xt/pull db [:film/name :film/year] :spectre))))
(t/testing "pullMany fn"
(t/is (= #{#:film{:name "Skyfall", :year "2012"}
#:film{:name "Spectre", :year "2015"}}
(set (xt/pull-many db (pr-str [:film/name :film/year]) #{:skyfall :spectre}))))
(t/is (= #{#:film{:name "Skyfall", :year "2012"}
#:film{:name "Spectre", :year "2015"}}
(set (xt/pull-many db [:film/name :film/year] #{:skyfall :spectre})))))
(t/testing "pull many respects order and cardinality of input eids"
(t/is [= [#:film{:name "Spectre", :year "2015"}
nil
#:film{:name "Skyfall", :year "2012"}]
(xt/pull-many db [:film/name :film/year] [:spectre :doesnt-exist :skyfall])])
(t/is [= [#:film{:name "Skyfall", :year "2012"}
nil
#:film{:name "Spectre", :year "2015"}
nil]
(xt/pull-many db [:film/name :film/year] [:skyfall :doesnt-exist :spectre :nor-does-this])]))
(t/testing "pullMany fn vector"
(t/is (= #{#:film {:name "Skyfall", :year "2012"}
#:film {:name "Spectre", :year "2015"}}
(set (xt/pull-many db (pr-str [:film/name :film/year]) #{:skyfall :spectre}))))
(t/is (= #{#:film {:name "Skyfall", :year "2012"}
#:film {:name "Spectre", :year "2015"}}
(set (xt/pull-many db [:film/name :film/year] #{:skyfall :spectre})))))))
(t/deftest test-limit
(let [db (submit-bond)]
(t/testing "props"
(t/is (= #{[{:film/name "Die Another Day"
:film/vehicles #{:xkr :v12-vanquish}}]}
(xt/q db '{:find [(pull ?f [:film/name (:film/vehicles {:into #{}, :limit 2})])]
:where [[?f :film/name "Die Another Day"]]}))))
(t/testing "forward joins"
(let [!lookup-counts (atom [])]
(with-redefs [pull/lookup-docs (->lookup-docs !lookup-counts)]
(t/is (= #{[{:film/year "2002",
:film/name "Die Another Day"
:film/bond {:person/name "PI:NAME:<NAME>END_PI"},
:film/director {:person/name "PI:NAME:<NAME>END_PI"},
:film/vehicles #{{:vehicle/brand "Jaguar", :vehicle/model "XKR"}
{:vehicle/brand "Aston Martin", :vehicle/model "V12 Vanquish"}}}]}
(xt/q db '{:find [(pull ?f [{:film/bond [:person/name]}
{:film/director [:person/name]}
{(:film/vehicles {:into #{}, :limit 2}) [:vehicle/brand :vehicle/model]}
:film/name :film/year])]
:where [[?f :film/name "Die Another Day"]]})))
(t/is (= [1 4] @!lookup-counts) "batching lookups"))))
(t/testing "reverse joins"
(let [!lookup-counts (atom [])]
(with-redefs [pull/lookup-docs (->lookup-docs !lookup-counts)]
(t/is (= #{[{:person/name "PI:NAME:<NAME>END_PI",
:film/_bond #{#:film{:name "Skyfall", :year "2012"}
#:film{:name "Spectre", :year "2015"}}}]}
(xt/q db '{:find [(pull ?dc [:person/name
{(:film/_bond {:into #{}, :limit 2}) [:film/name :film/year]}])]
:where [[?dc :person/name "PI:NAME:<NAME>END_PI"]]})))
(t/is (= [3] @!lookup-counts) "batching lookups"))))))
(t/deftest test-union
(fix/submit+await-tx [[::xt/put {:xt/id :foo
:type :a
:x 2
:y "this"
:z :not-this}]
[::xt/put {:xt/id :bar
:type :b
:y "not this"
:z 5}]])
(t/is (= #{[{:xt/id :foo, :x 2, :y "this"}]
[{:xt/id :bar, :z 5}]}
(xt/q (xt/db *api*)
'{:find [(pull ?it [{:type {:a [:x :y], :b [:z]}}
:xt/id])]
:where [[?it :xt/id]]}))))
(t/deftest test-recursive
(fix/submit+await-tx [[::xt/put {:xt/id :root}]
[::xt/put {:xt/id :a
:parent :root}]
[::xt/put {:xt/id :b
:parent :root}]
[::xt/put {:xt/id :aa
:parent :a}]
[::xt/put {:xt/id :ab
:parent :a}]
[::xt/put {:xt/id :aba
:parent :ab}]
[::xt/put {:xt/id :abb
:parent :ab}]])
(t/testing "forward unbounded recursion"
(t/is (= {:xt/id :aba
:parent {:xt/id :ab
:parent {:xt/id :a
:parent {:xt/id :root}}}}
(ffirst (xt/q (xt/db *api*)
'{:find [(pull ?aba [:xt/id {:parent ...}])]
:where [[?aba :xt/id :aba]]})))))
(t/testing "forward bounded recursion"
(t/is (= {:xt/id :aba
:parent {:xt/id :ab
:parent {:xt/id :a}}}
(ffirst (xt/q (xt/db *api*)
'{:find [(pull ?aba [:xt/id {:parent 2}])]
:where [[?aba :xt/id :aba]]})))))
(t/testing "reverse unbounded recursion"
(t/is (= {:xt/id :root
:_parent [{:xt/id :a
:_parent [{:xt/id :aa}
{:xt/id :ab
:_parent [{:xt/id :aba}
{:xt/id :abb}]}]}
{:xt/id :b}]}
(ffirst (xt/q (xt/db *api*)
'{:find [(pull ?root [:xt/id {:_parent ...}])]
:where [[?root :xt/id :root]]})))))
(t/testing "reverse bounded recursion"
(t/is (= {:xt/id :root
:_parent [{:xt/id :a
:_parent [{:xt/id :aa}
{:xt/id :ab}]}
{:xt/id :b}]}
(ffirst (xt/q (xt/db *api*)
'{:find [(pull ?root [:xt/id {:_parent 2}])]
:where [[?root :xt/id :root]]}))))))
(t/deftest test-doesnt-hang-on-unknown-eid
(t/is (= #{[nil]}
(xt/q (xt/db *api*)
'{:find [(pull ?e [*])]
:in [?e]
:timeout 500}
"doesntexist")))
(t/is (nil? (xt/pull (xt/db *api*) '[*] "doesntexist"))))
(t/deftest test-with-speculative-doc-store
(let [db (xt/with-tx (xt/db *api*) [[::xt/put {:xt/id :foo}]])]
(t/is (= #{[{:xt/id :foo}]}
(xt/q db
'{:find [(pull ?e [*])]
:where [[?e :xt/id :foo]]})))))
(t/deftest test-missing-forward-join
(fix/submit+await-tx [[::xt/put {:xt/id :foo :ref [:bar :baz]}]
[::xt/put {:xt/id :bar}]])
(t/is (= #{[{:ref [{:xt/id :bar} nil]}]}
(xt/q (xt/db *api*)
'{:find [(pull ?it [{:ref [:xt/id]}])]
:where [[?it :xt/id :foo]]}))))
(t/deftest test-missing-forward-join-collection-error-handling-1710
(fix/submit+await-tx [[::xt/put {:xt/id :foo :ref '(:bar :baz)}]
[::xt/put {:xt/id :bar}]])
(t/is (= #{[{}]}
(xt/q (xt/db *api*)
'{:find [(pull ?it [{:ref [:xt/id]}])]
:where [[?it :xt/id :foo]]}))))
|
[
{
"context": "o be useful in user-written code.\"\n :author \"Simon Brooke\"}\n adl-support.core\n (:require [clojure.core.me",
"end": 149,
"score": 0.9998884201049805,
"start": 137,
"tag": "NAME",
"value": "Simon Brooke"
},
{
"context": "nse for more details.\n;;;;\n;;;; Copyright (C) 2018 Simon Brooke\n;;;;\n;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;",
"end": 959,
"score": 0.9998829960823059,
"start": 947,
"tag": "NAME",
"value": "Simon Brooke"
}
] | src/adl_support/core.clj | simon-brooke/adl-support | 0 | (ns ^{:doc "Application Description Language support - utility functions likely
to be useful in user-written code."
:author "Simon Brooke"}
adl-support.core
(:require [clojure.core.memoize :as memo]
[clojure.data.json :as json]
[clojure.java.io :as io]
[clojure.string :refer [split join]]
[clojure.tools.logging]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;
;;;; adl-support.core: functions used by ADL-generated code.
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the MIT-style licence provided; see LICENSE.
;;;;
;;;; This program 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
;;;; License for more details.
;;;;
;;;; Copyright (C) 2018 Simon Brooke
;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^:dynamic *warn*
"The idea here is to have a function with which to show warnings to the user,
which can be dynamically bound. Any binding should be a function of one
argument, which it should print, log, or otherwise display."
(fn [s] (println s)))
(defn massage-value
"Return a map with one key, this `k` as a keyword, whose value is the binding of
`k` in map `m`, as read by read."
[k m]
(let [v (m k)
vr (if
(string? v)
(try
(json/read-str v)
(catch Exception _ nil)))]
(cond
(nil? v) {}
(= v "") {}
(and
(number? vr)
;; there's a problem that json/read-str will read "07777 888999" as 7777
(re-matches #"^[0-9.]+$" v)) {(keyword k) vr}
true
{(keyword k) v})))
(defn raw-massage-params
"Sending empty strings, or numbers as strings, to the database often isn't
helpful. Massage these `params` and `form-params` to eliminate these problems.
Date and time fields also need massaging."
([request entity]
(let
[params (:params request)
form-params (:form-params request)
p (reduce
merge
{}
(map
#(massage-value % params)
(keys params)))]
(if
(empty? (keys form-params))
p
(reduce
merge
;; do the keyfields first, from params
p
;; then merge in everything from form-params, potentially overriding what
;; we got from params.
(map
#(massage-value % form-params)
(keys form-params))))))
([request]
(raw-massage-params request nil)))
(def massage-params
"Sending empty strings, or numbers as strings, to the database often isn't
helpful. Massage these `params` and `form-params` to eliminate these problems.
We must take key field values out of just params, but we should take all other
values out of form-params - because we need the key to load the form in
the first place, but just accepting values of other params would allow spoofing."
(memo/ttl raw-massage-params {} :ttl/threshold 5000))
(defn
raw-resolve-template
[n]
(if
(.exists (io/as-file (str "resources/templates/" n)))
n
(str "auto/" n)))
(def resolve-template (memoize raw-resolve-template))
(defmacro compose-exception-reason
"Compose and return a sensible reason message for this `exception`."
([exception intro]
`(str
~intro
(if ~intro ": ")
(join
"\n\tcaused by: "
(reverse
(loop [ex# ~exception result# ()]
(if-not (nil? ex#)
(recur
(.getCause ex#)
(cons (str
(.getName (.getClass ex#))
": "
(.getMessage ex#)) result#))
result#))))))
([exception]
`(compose-exception-reason ~exception nil)))
(defmacro compose-reason-and-log
"Compose a reason message for this `exception`, log it (with its
stacktrace), and return the reason message."
([exception intro]
`(let [reason# (compose-exception-reason ~exception ~intro)]
(clojure.tools.logging/error
reason#
"\n"
(with-out-str
(-> ~exception .printStackTrace)))
reason#))
([exception]
`(compose-reason-and-log ~exception nil)))
(defmacro do-or-log-error
"Evaluate the supplied `form` in a try/catch block. If the
keyword param `:message` is supplied, the value will be used
as the log message; if the keyword param `:error-return` is
supplied, the value will be returned if an exception is caught."
[form & {:keys [message error-return]
:or {message `(str "A failure occurred in "
~(list 'quote form))}}]
`(try
~form
(catch Exception any#
(compose-reason-and-log any# ~message)
~error-return)))
(defmacro do-or-return-reason
"Clojure stacktraces are unreadable. We have to do better; evaluate
this `form` in a try-catch block; return a map. If the evaluation
succeeds, the map will have a key `:result` whose value is the result;
otherwise it will have a key `:error` which will be bound to the most
sensible error message we can construct."
([form intro]
`(try
{:result ~form}
(catch Exception any#
{:error (compose-exception-reason any# ~intro)})))
([form]
`(do-or-return-reason ~form nil)))
(defmacro do-or-log-and-return-reason
"Clojure stacktraces are unreadable. We have to do better; evaluate
this `form` in a try-catch block; return a map. If the evaluation
succeeds, the map will have a key `:result` whose value is the result;
otherwise it will have a key `:error` which will be bound to the most
sensible error message we can construct. Additionally, log the exception"
[form]
`(try
{:result ~form}
(catch Exception any#
{:error (compose-reason-and-log any#)})))
(defmacro do-or-warn
"Evaluate this `form`; if any exception is thrown, show it to the user
via the `*warn*` mechanism."
([form]
`(try
~form
(catch Exception any#
(*warn* (compose-exception-reason any#))
nil)))
([form intro]
`(try
~form
(catch Exception any#
(*warn* (str ~intro ":\n\t" (compose-exception-reason any#)))
nil))))
(defmacro do-or-warn-and-log
"Evaluate this `form`; if any exception is thrown, log the reason and
show it to the user via the `*warn*` mechanism."
([form]
`(try
~form
(catch Exception any#
(*warn* (compose-reason-and-log any#))
nil)))
([form intro]
`(try
~form
(catch Exception any#
(*warn* (compose-reason-and-log any# ~intro ))
nil))))
| 92268 | (ns ^{:doc "Application Description Language support - utility functions likely
to be useful in user-written code."
:author "<NAME>"}
adl-support.core
(:require [clojure.core.memoize :as memo]
[clojure.data.json :as json]
[clojure.java.io :as io]
[clojure.string :refer [split join]]
[clojure.tools.logging]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;
;;;; adl-support.core: functions used by ADL-generated code.
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the MIT-style licence provided; see LICENSE.
;;;;
;;;; This program 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
;;;; License for more details.
;;;;
;;;; Copyright (C) 2018 <NAME>
;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^:dynamic *warn*
"The idea here is to have a function with which to show warnings to the user,
which can be dynamically bound. Any binding should be a function of one
argument, which it should print, log, or otherwise display."
(fn [s] (println s)))
(defn massage-value
"Return a map with one key, this `k` as a keyword, whose value is the binding of
`k` in map `m`, as read by read."
[k m]
(let [v (m k)
vr (if
(string? v)
(try
(json/read-str v)
(catch Exception _ nil)))]
(cond
(nil? v) {}
(= v "") {}
(and
(number? vr)
;; there's a problem that json/read-str will read "07777 888999" as 7777
(re-matches #"^[0-9.]+$" v)) {(keyword k) vr}
true
{(keyword k) v})))
(defn raw-massage-params
"Sending empty strings, or numbers as strings, to the database often isn't
helpful. Massage these `params` and `form-params` to eliminate these problems.
Date and time fields also need massaging."
([request entity]
(let
[params (:params request)
form-params (:form-params request)
p (reduce
merge
{}
(map
#(massage-value % params)
(keys params)))]
(if
(empty? (keys form-params))
p
(reduce
merge
;; do the keyfields first, from params
p
;; then merge in everything from form-params, potentially overriding what
;; we got from params.
(map
#(massage-value % form-params)
(keys form-params))))))
([request]
(raw-massage-params request nil)))
(def massage-params
"Sending empty strings, or numbers as strings, to the database often isn't
helpful. Massage these `params` and `form-params` to eliminate these problems.
We must take key field values out of just params, but we should take all other
values out of form-params - because we need the key to load the form in
the first place, but just accepting values of other params would allow spoofing."
(memo/ttl raw-massage-params {} :ttl/threshold 5000))
(defn
raw-resolve-template
[n]
(if
(.exists (io/as-file (str "resources/templates/" n)))
n
(str "auto/" n)))
(def resolve-template (memoize raw-resolve-template))
(defmacro compose-exception-reason
"Compose and return a sensible reason message for this `exception`."
([exception intro]
`(str
~intro
(if ~intro ": ")
(join
"\n\tcaused by: "
(reverse
(loop [ex# ~exception result# ()]
(if-not (nil? ex#)
(recur
(.getCause ex#)
(cons (str
(.getName (.getClass ex#))
": "
(.getMessage ex#)) result#))
result#))))))
([exception]
`(compose-exception-reason ~exception nil)))
(defmacro compose-reason-and-log
"Compose a reason message for this `exception`, log it (with its
stacktrace), and return the reason message."
([exception intro]
`(let [reason# (compose-exception-reason ~exception ~intro)]
(clojure.tools.logging/error
reason#
"\n"
(with-out-str
(-> ~exception .printStackTrace)))
reason#))
([exception]
`(compose-reason-and-log ~exception nil)))
(defmacro do-or-log-error
"Evaluate the supplied `form` in a try/catch block. If the
keyword param `:message` is supplied, the value will be used
as the log message; if the keyword param `:error-return` is
supplied, the value will be returned if an exception is caught."
[form & {:keys [message error-return]
:or {message `(str "A failure occurred in "
~(list 'quote form))}}]
`(try
~form
(catch Exception any#
(compose-reason-and-log any# ~message)
~error-return)))
(defmacro do-or-return-reason
"Clojure stacktraces are unreadable. We have to do better; evaluate
this `form` in a try-catch block; return a map. If the evaluation
succeeds, the map will have a key `:result` whose value is the result;
otherwise it will have a key `:error` which will be bound to the most
sensible error message we can construct."
([form intro]
`(try
{:result ~form}
(catch Exception any#
{:error (compose-exception-reason any# ~intro)})))
([form]
`(do-or-return-reason ~form nil)))
(defmacro do-or-log-and-return-reason
"Clojure stacktraces are unreadable. We have to do better; evaluate
this `form` in a try-catch block; return a map. If the evaluation
succeeds, the map will have a key `:result` whose value is the result;
otherwise it will have a key `:error` which will be bound to the most
sensible error message we can construct. Additionally, log the exception"
[form]
`(try
{:result ~form}
(catch Exception any#
{:error (compose-reason-and-log any#)})))
(defmacro do-or-warn
"Evaluate this `form`; if any exception is thrown, show it to the user
via the `*warn*` mechanism."
([form]
`(try
~form
(catch Exception any#
(*warn* (compose-exception-reason any#))
nil)))
([form intro]
`(try
~form
(catch Exception any#
(*warn* (str ~intro ":\n\t" (compose-exception-reason any#)))
nil))))
(defmacro do-or-warn-and-log
"Evaluate this `form`; if any exception is thrown, log the reason and
show it to the user via the `*warn*` mechanism."
([form]
`(try
~form
(catch Exception any#
(*warn* (compose-reason-and-log any#))
nil)))
([form intro]
`(try
~form
(catch Exception any#
(*warn* (compose-reason-and-log any# ~intro ))
nil))))
| true | (ns ^{:doc "Application Description Language support - utility functions likely
to be useful in user-written code."
:author "PI:NAME:<NAME>END_PI"}
adl-support.core
(:require [clojure.core.memoize :as memo]
[clojure.data.json :as json]
[clojure.java.io :as io]
[clojure.string :refer [split join]]
[clojure.tools.logging]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;
;;;; adl-support.core: functions used by ADL-generated code.
;;;;
;;;; This program is free software; you can redistribute it and/or
;;;; modify it under the terms of the MIT-style licence provided; see LICENSE.
;;;;
;;;; This program 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
;;;; License for more details.
;;;;
;;;; Copyright (C) 2018 PI:NAME:<NAME>END_PI
;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^:dynamic *warn*
"The idea here is to have a function with which to show warnings to the user,
which can be dynamically bound. Any binding should be a function of one
argument, which it should print, log, or otherwise display."
(fn [s] (println s)))
(defn massage-value
"Return a map with one key, this `k` as a keyword, whose value is the binding of
`k` in map `m`, as read by read."
[k m]
(let [v (m k)
vr (if
(string? v)
(try
(json/read-str v)
(catch Exception _ nil)))]
(cond
(nil? v) {}
(= v "") {}
(and
(number? vr)
;; there's a problem that json/read-str will read "07777 888999" as 7777
(re-matches #"^[0-9.]+$" v)) {(keyword k) vr}
true
{(keyword k) v})))
(defn raw-massage-params
"Sending empty strings, or numbers as strings, to the database often isn't
helpful. Massage these `params` and `form-params` to eliminate these problems.
Date and time fields also need massaging."
([request entity]
(let
[params (:params request)
form-params (:form-params request)
p (reduce
merge
{}
(map
#(massage-value % params)
(keys params)))]
(if
(empty? (keys form-params))
p
(reduce
merge
;; do the keyfields first, from params
p
;; then merge in everything from form-params, potentially overriding what
;; we got from params.
(map
#(massage-value % form-params)
(keys form-params))))))
([request]
(raw-massage-params request nil)))
(def massage-params
"Sending empty strings, or numbers as strings, to the database often isn't
helpful. Massage these `params` and `form-params` to eliminate these problems.
We must take key field values out of just params, but we should take all other
values out of form-params - because we need the key to load the form in
the first place, but just accepting values of other params would allow spoofing."
(memo/ttl raw-massage-params {} :ttl/threshold 5000))
(defn
raw-resolve-template
[n]
(if
(.exists (io/as-file (str "resources/templates/" n)))
n
(str "auto/" n)))
(def resolve-template (memoize raw-resolve-template))
(defmacro compose-exception-reason
"Compose and return a sensible reason message for this `exception`."
([exception intro]
`(str
~intro
(if ~intro ": ")
(join
"\n\tcaused by: "
(reverse
(loop [ex# ~exception result# ()]
(if-not (nil? ex#)
(recur
(.getCause ex#)
(cons (str
(.getName (.getClass ex#))
": "
(.getMessage ex#)) result#))
result#))))))
([exception]
`(compose-exception-reason ~exception nil)))
(defmacro compose-reason-and-log
"Compose a reason message for this `exception`, log it (with its
stacktrace), and return the reason message."
([exception intro]
`(let [reason# (compose-exception-reason ~exception ~intro)]
(clojure.tools.logging/error
reason#
"\n"
(with-out-str
(-> ~exception .printStackTrace)))
reason#))
([exception]
`(compose-reason-and-log ~exception nil)))
(defmacro do-or-log-error
"Evaluate the supplied `form` in a try/catch block. If the
keyword param `:message` is supplied, the value will be used
as the log message; if the keyword param `:error-return` is
supplied, the value will be returned if an exception is caught."
[form & {:keys [message error-return]
:or {message `(str "A failure occurred in "
~(list 'quote form))}}]
`(try
~form
(catch Exception any#
(compose-reason-and-log any# ~message)
~error-return)))
(defmacro do-or-return-reason
"Clojure stacktraces are unreadable. We have to do better; evaluate
this `form` in a try-catch block; return a map. If the evaluation
succeeds, the map will have a key `:result` whose value is the result;
otherwise it will have a key `:error` which will be bound to the most
sensible error message we can construct."
([form intro]
`(try
{:result ~form}
(catch Exception any#
{:error (compose-exception-reason any# ~intro)})))
([form]
`(do-or-return-reason ~form nil)))
(defmacro do-or-log-and-return-reason
"Clojure stacktraces are unreadable. We have to do better; evaluate
this `form` in a try-catch block; return a map. If the evaluation
succeeds, the map will have a key `:result` whose value is the result;
otherwise it will have a key `:error` which will be bound to the most
sensible error message we can construct. Additionally, log the exception"
[form]
`(try
{:result ~form}
(catch Exception any#
{:error (compose-reason-and-log any#)})))
(defmacro do-or-warn
"Evaluate this `form`; if any exception is thrown, show it to the user
via the `*warn*` mechanism."
([form]
`(try
~form
(catch Exception any#
(*warn* (compose-exception-reason any#))
nil)))
([form intro]
`(try
~form
(catch Exception any#
(*warn* (str ~intro ":\n\t" (compose-exception-reason any#)))
nil))))
(defmacro do-or-warn-and-log
"Evaluate this `form`; if any exception is thrown, log the reason and
show it to the user via the `*warn*` mechanism."
([form]
`(try
~form
(catch Exception any#
(*warn* (compose-reason-and-log any#))
nil)))
([form intro]
`(try
~form
(catch Exception any#
(*warn* (compose-reason-and-log any# ~intro ))
nil))))
|
[
{
"context": "r \"docufant\"\n :password \"password\"\n :port 5432})\n\n\n(defn t",
"end": 460,
"score": 0.9995574355125427,
"start": 452,
"tag": "PASSWORD",
"value": "password"
}
] | test/docufant/core_test.clj | xlevus/docufant-clj | 0 | (ns docufant.core-test
(:require [docufant.core :as doc]
[docufant.db :as db]
[docufant.postgres :as pg]
[docufant.operator :as oper]
[clojure.test :as t :refer [deftest testing is]]
[clojure.java.jdbc :as j]))
(def ^:dynamic *db-spec* {:dbtype "postgresql"
:dbname "docufant_test"
:user "docufant"
:password "password"
:port 5432})
(defn tables [f]
;;(db/transaction
(doc/init! *db-spec*
{:type :unique-name :unique true :path [:name]})
(f)
(j/execute! *db-spec* "DROP TABLE docufant CASCADE;")
(j/execute! *db-spec* "DROP TABLE docufant_link CASCADE;")
)
(defn transaction [f]
(j/with-db-transaction [t-con *db-spec*]
(binding [*db-spec* t-con]
(f))
(j/db-set-rollback-only! t-con)))
(t/use-fixtures :once tables)
(t/use-fixtures :each transaction)
(deftest test-mutations
(testing "create!"
(let [inst (doc/create! *db-spec* :test {:a 100})
[type id] (:id inst)]
(is (= :test type))
(is (int? id))
(is (= {:a 100} (dissoc inst :id)))
))
(testing "update!"
(let [inst (doc/create! *db-spec* :test {:a 200})
id (:id inst)]
(doc/update! *db-spec* id {:a 300})
(is (= 300 (:a (doc/get *db-spec* id)))))
))
(deftest test-queries
(testing "equality"
(let [i1 (doc/create! *db-spec* :type1 {:a 1 :name "i1"})
i2 (doc/create! *db-spec* :type1 {:a {:b 2} :name "i2"})
i3 (doc/create! *db-spec* :type1 {:a {:b 2 :c {:z 1 :x 2}} :name "i3"})
i4 (doc/create! *db-spec* :type2 {:a {:b 3 :c {:x 2 :y 1}} :name "i4"})]
(is (= [i1] (doc/select *db-spec* nil (oper/= [:a] 1))))
(is (= [i3 i4] (doc/select *db-spec* nil (oper/= [:a :c :x] 2))))
(is (= [i3] (doc/select *db-spec* :type1 (oper/= [:a :c :x] 2))))
(is (= [i4] (doc/select *db-spec* :type2 (oper/= [:a :c :x] 2))))
))
(testing "inequality"
(let [i1 (doc/create! *db-spec* :ordered {:a 1 :b 3})
i2 (doc/create! *db-spec* :ordered {:a 2 :b 4})
i3 (doc/create! *db-spec* :ordered {:a 3 :b 5 :c {:d 10}})
i4 (doc/create! *db-spec* :ordered {:b 6 :c {:d 5}})]
(is (= [i1] (doc/select *db-spec* :ordered (oper/< [:a] 2))))
(is (= [i3] (doc/select *db-spec* :ordered (oper/> [:a] 2))))
(is (= [i1 i2] (doc/select *db-spec* :ordered (oper/<= [:a] 2))))
(is (= [i2 i3] (doc/select *db-spec* :ordered (oper/>= [:a] 2))))
(is (= [i2 i3] (doc/select *db-spec* :ordered (oper/<> [:a] 1))))
(is (= [i3] (doc/select *db-spec* :ordered
(oper/> [:b] 1)
(oper/> [:c :d] 6))))
(is (= [i1 i2] (doc/select *db-spec* :ordered (oper/> [:b] 1)
:limit 2)))
(is (= [i3 i4] (doc/select *db-spec* :ordered (oper/> [:b] 1)
:limit 2
:offset 2)))
(is (= [i4 i3 i2 i1] (doc/select *db-spec* :ordered (oper/> [:b] 1)
:order-by [[:b] :desc])))
))
(testing "get"
(let [i1 (doc/create! *db-spec* :test {:a 1})
i2 (doc/create! *db-spec* :test {:a 3})]
(is (= i1 (doc/get *db-spec* (:id i1))))
(is (nil? (doc/get *db-spec* [:foo 1])))
)))
(deftest test-links
(testing "abc"
(let [i1 (doc/create! *db-spec* :tparent {:a 1})
i2 (doc/create! *db-spec* :tchild {:a 2})]
(doc/link! *db-spec* :parent i1 i2)
(doc/link! *db-spec* :child i2 i1)
(is (= [i2] (doc/select *db-spec* nil :linked-to [:parent i1])))
(is (= [i1] (doc/select *db-spec* nil :linked-to [:child i2])))
)))
(deftest test-removal
(testing "delete"
(let [i1 (doc/create! *db-spec* :test {:a 1})]
(is (= 1 (doc/delete! *db-spec* i1)))
(is (= nil (doc/get *db-spec* (:id i1))))
(is (= 0 (doc/delete! *db-spec* [:null 92929])))))
(testing "delete linked"
(let [i1 (doc/create! *db-spec* :test {:a 1})
i2 (doc/create! *db-spec* :test {:a 2})]
(doc/link! *db-spec* :linked i1 i2)
(is (= 1 (doc/delete! *db-spec* i1)))
(is (= nil (doc/get *db-spec* (:id i1))))
(is (= 0 (doc/delete! *db-spec* [:null 92929]))))))
| 34208 | (ns docufant.core-test
(:require [docufant.core :as doc]
[docufant.db :as db]
[docufant.postgres :as pg]
[docufant.operator :as oper]
[clojure.test :as t :refer [deftest testing is]]
[clojure.java.jdbc :as j]))
(def ^:dynamic *db-spec* {:dbtype "postgresql"
:dbname "docufant_test"
:user "docufant"
:password "<PASSWORD>"
:port 5432})
(defn tables [f]
;;(db/transaction
(doc/init! *db-spec*
{:type :unique-name :unique true :path [:name]})
(f)
(j/execute! *db-spec* "DROP TABLE docufant CASCADE;")
(j/execute! *db-spec* "DROP TABLE docufant_link CASCADE;")
)
(defn transaction [f]
(j/with-db-transaction [t-con *db-spec*]
(binding [*db-spec* t-con]
(f))
(j/db-set-rollback-only! t-con)))
(t/use-fixtures :once tables)
(t/use-fixtures :each transaction)
(deftest test-mutations
(testing "create!"
(let [inst (doc/create! *db-spec* :test {:a 100})
[type id] (:id inst)]
(is (= :test type))
(is (int? id))
(is (= {:a 100} (dissoc inst :id)))
))
(testing "update!"
(let [inst (doc/create! *db-spec* :test {:a 200})
id (:id inst)]
(doc/update! *db-spec* id {:a 300})
(is (= 300 (:a (doc/get *db-spec* id)))))
))
(deftest test-queries
(testing "equality"
(let [i1 (doc/create! *db-spec* :type1 {:a 1 :name "i1"})
i2 (doc/create! *db-spec* :type1 {:a {:b 2} :name "i2"})
i3 (doc/create! *db-spec* :type1 {:a {:b 2 :c {:z 1 :x 2}} :name "i3"})
i4 (doc/create! *db-spec* :type2 {:a {:b 3 :c {:x 2 :y 1}} :name "i4"})]
(is (= [i1] (doc/select *db-spec* nil (oper/= [:a] 1))))
(is (= [i3 i4] (doc/select *db-spec* nil (oper/= [:a :c :x] 2))))
(is (= [i3] (doc/select *db-spec* :type1 (oper/= [:a :c :x] 2))))
(is (= [i4] (doc/select *db-spec* :type2 (oper/= [:a :c :x] 2))))
))
(testing "inequality"
(let [i1 (doc/create! *db-spec* :ordered {:a 1 :b 3})
i2 (doc/create! *db-spec* :ordered {:a 2 :b 4})
i3 (doc/create! *db-spec* :ordered {:a 3 :b 5 :c {:d 10}})
i4 (doc/create! *db-spec* :ordered {:b 6 :c {:d 5}})]
(is (= [i1] (doc/select *db-spec* :ordered (oper/< [:a] 2))))
(is (= [i3] (doc/select *db-spec* :ordered (oper/> [:a] 2))))
(is (= [i1 i2] (doc/select *db-spec* :ordered (oper/<= [:a] 2))))
(is (= [i2 i3] (doc/select *db-spec* :ordered (oper/>= [:a] 2))))
(is (= [i2 i3] (doc/select *db-spec* :ordered (oper/<> [:a] 1))))
(is (= [i3] (doc/select *db-spec* :ordered
(oper/> [:b] 1)
(oper/> [:c :d] 6))))
(is (= [i1 i2] (doc/select *db-spec* :ordered (oper/> [:b] 1)
:limit 2)))
(is (= [i3 i4] (doc/select *db-spec* :ordered (oper/> [:b] 1)
:limit 2
:offset 2)))
(is (= [i4 i3 i2 i1] (doc/select *db-spec* :ordered (oper/> [:b] 1)
:order-by [[:b] :desc])))
))
(testing "get"
(let [i1 (doc/create! *db-spec* :test {:a 1})
i2 (doc/create! *db-spec* :test {:a 3})]
(is (= i1 (doc/get *db-spec* (:id i1))))
(is (nil? (doc/get *db-spec* [:foo 1])))
)))
(deftest test-links
(testing "abc"
(let [i1 (doc/create! *db-spec* :tparent {:a 1})
i2 (doc/create! *db-spec* :tchild {:a 2})]
(doc/link! *db-spec* :parent i1 i2)
(doc/link! *db-spec* :child i2 i1)
(is (= [i2] (doc/select *db-spec* nil :linked-to [:parent i1])))
(is (= [i1] (doc/select *db-spec* nil :linked-to [:child i2])))
)))
(deftest test-removal
(testing "delete"
(let [i1 (doc/create! *db-spec* :test {:a 1})]
(is (= 1 (doc/delete! *db-spec* i1)))
(is (= nil (doc/get *db-spec* (:id i1))))
(is (= 0 (doc/delete! *db-spec* [:null 92929])))))
(testing "delete linked"
(let [i1 (doc/create! *db-spec* :test {:a 1})
i2 (doc/create! *db-spec* :test {:a 2})]
(doc/link! *db-spec* :linked i1 i2)
(is (= 1 (doc/delete! *db-spec* i1)))
(is (= nil (doc/get *db-spec* (:id i1))))
(is (= 0 (doc/delete! *db-spec* [:null 92929]))))))
| true | (ns docufant.core-test
(:require [docufant.core :as doc]
[docufant.db :as db]
[docufant.postgres :as pg]
[docufant.operator :as oper]
[clojure.test :as t :refer [deftest testing is]]
[clojure.java.jdbc :as j]))
(def ^:dynamic *db-spec* {:dbtype "postgresql"
:dbname "docufant_test"
:user "docufant"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:port 5432})
(defn tables [f]
;;(db/transaction
(doc/init! *db-spec*
{:type :unique-name :unique true :path [:name]})
(f)
(j/execute! *db-spec* "DROP TABLE docufant CASCADE;")
(j/execute! *db-spec* "DROP TABLE docufant_link CASCADE;")
)
(defn transaction [f]
(j/with-db-transaction [t-con *db-spec*]
(binding [*db-spec* t-con]
(f))
(j/db-set-rollback-only! t-con)))
(t/use-fixtures :once tables)
(t/use-fixtures :each transaction)
(deftest test-mutations
(testing "create!"
(let [inst (doc/create! *db-spec* :test {:a 100})
[type id] (:id inst)]
(is (= :test type))
(is (int? id))
(is (= {:a 100} (dissoc inst :id)))
))
(testing "update!"
(let [inst (doc/create! *db-spec* :test {:a 200})
id (:id inst)]
(doc/update! *db-spec* id {:a 300})
(is (= 300 (:a (doc/get *db-spec* id)))))
))
(deftest test-queries
(testing "equality"
(let [i1 (doc/create! *db-spec* :type1 {:a 1 :name "i1"})
i2 (doc/create! *db-spec* :type1 {:a {:b 2} :name "i2"})
i3 (doc/create! *db-spec* :type1 {:a {:b 2 :c {:z 1 :x 2}} :name "i3"})
i4 (doc/create! *db-spec* :type2 {:a {:b 3 :c {:x 2 :y 1}} :name "i4"})]
(is (= [i1] (doc/select *db-spec* nil (oper/= [:a] 1))))
(is (= [i3 i4] (doc/select *db-spec* nil (oper/= [:a :c :x] 2))))
(is (= [i3] (doc/select *db-spec* :type1 (oper/= [:a :c :x] 2))))
(is (= [i4] (doc/select *db-spec* :type2 (oper/= [:a :c :x] 2))))
))
(testing "inequality"
(let [i1 (doc/create! *db-spec* :ordered {:a 1 :b 3})
i2 (doc/create! *db-spec* :ordered {:a 2 :b 4})
i3 (doc/create! *db-spec* :ordered {:a 3 :b 5 :c {:d 10}})
i4 (doc/create! *db-spec* :ordered {:b 6 :c {:d 5}})]
(is (= [i1] (doc/select *db-spec* :ordered (oper/< [:a] 2))))
(is (= [i3] (doc/select *db-spec* :ordered (oper/> [:a] 2))))
(is (= [i1 i2] (doc/select *db-spec* :ordered (oper/<= [:a] 2))))
(is (= [i2 i3] (doc/select *db-spec* :ordered (oper/>= [:a] 2))))
(is (= [i2 i3] (doc/select *db-spec* :ordered (oper/<> [:a] 1))))
(is (= [i3] (doc/select *db-spec* :ordered
(oper/> [:b] 1)
(oper/> [:c :d] 6))))
(is (= [i1 i2] (doc/select *db-spec* :ordered (oper/> [:b] 1)
:limit 2)))
(is (= [i3 i4] (doc/select *db-spec* :ordered (oper/> [:b] 1)
:limit 2
:offset 2)))
(is (= [i4 i3 i2 i1] (doc/select *db-spec* :ordered (oper/> [:b] 1)
:order-by [[:b] :desc])))
))
(testing "get"
(let [i1 (doc/create! *db-spec* :test {:a 1})
i2 (doc/create! *db-spec* :test {:a 3})]
(is (= i1 (doc/get *db-spec* (:id i1))))
(is (nil? (doc/get *db-spec* [:foo 1])))
)))
(deftest test-links
(testing "abc"
(let [i1 (doc/create! *db-spec* :tparent {:a 1})
i2 (doc/create! *db-spec* :tchild {:a 2})]
(doc/link! *db-spec* :parent i1 i2)
(doc/link! *db-spec* :child i2 i1)
(is (= [i2] (doc/select *db-spec* nil :linked-to [:parent i1])))
(is (= [i1] (doc/select *db-spec* nil :linked-to [:child i2])))
)))
(deftest test-removal
(testing "delete"
(let [i1 (doc/create! *db-spec* :test {:a 1})]
(is (= 1 (doc/delete! *db-spec* i1)))
(is (= nil (doc/get *db-spec* (:id i1))))
(is (= 0 (doc/delete! *db-spec* [:null 92929])))))
(testing "delete linked"
(let [i1 (doc/create! *db-spec* :test {:a 1})
i2 (doc/create! *db-spec* :test {:a 2})]
(doc/link! *db-spec* :linked i1 i2)
(is (= 1 (doc/delete! *db-spec* i1)))
(is (= nil (doc/get *db-spec* (:id i1))))
(is (= 0 (doc/delete! *db-spec* [:null 92929]))))))
|
[
{
"context": ";; Copyright (c) 2015-2022 Michael Schaeffer\n;;\n;; Licensed as below.\n;;\n;; Portions Copyright",
"end": 44,
"score": 0.9996418952941895,
"start": 27,
"tag": "NAME",
"value": "Michael Schaeffer"
}
] | src/sql_file/sql_util.clj | mschaef/sql-file | 1 | ;; Copyright (c) 2015-2022 Michael Schaeffer
;;
;; Licensed as below.
;;
;; Portions Copyright (c) 2014 KSM Technology Partners
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; The license is also includes at the root of the project in the file
;; LICENSE.
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; You must not remove this notice, or any other, from this software.
(ns sql-file.sql-util
(:require [clojure.tools.logging :as log]
[clojure.java.jdbc :as jdbc]))
(defn query-all [ db-connection query-spec ]
(log/debug "query-all:" query-spec)
(jdbc/query db-connection query-spec))
(defn query-first [ db-connection query-spec ]
(log/debug "query-first:" query-spec)
(first (jdbc/query db-connection query-spec)))
(defn scalar-result
([ query-result default ]
(or
(let [first-row (first query-result)
row-keys (keys first-row)]
(when (> (count row-keys) 1)
(log/debug "Queries used for query-scalar should only return one field per row."))
(get first-row (first row-keys)))
default))
([ query-result ]
(scalar-result query-result nil)))
(defn query-scalar
([ db-connection query-spec default ]
(log/debug "query-scalar:" query-spec)
(scalar-result (jdbc/query db-connection query-spec) default))
([ db-connection query-spec ]
(query-scalar db-connection query-spec nil)))
| 17128 | ;; Copyright (c) 2015-2022 <NAME>
;;
;; Licensed as below.
;;
;; Portions Copyright (c) 2014 KSM Technology Partners
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; The license is also includes at the root of the project in the file
;; LICENSE.
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; You must not remove this notice, or any other, from this software.
(ns sql-file.sql-util
(:require [clojure.tools.logging :as log]
[clojure.java.jdbc :as jdbc]))
(defn query-all [ db-connection query-spec ]
(log/debug "query-all:" query-spec)
(jdbc/query db-connection query-spec))
(defn query-first [ db-connection query-spec ]
(log/debug "query-first:" query-spec)
(first (jdbc/query db-connection query-spec)))
(defn scalar-result
([ query-result default ]
(or
(let [first-row (first query-result)
row-keys (keys first-row)]
(when (> (count row-keys) 1)
(log/debug "Queries used for query-scalar should only return one field per row."))
(get first-row (first row-keys)))
default))
([ query-result ]
(scalar-result query-result nil)))
(defn query-scalar
([ db-connection query-spec default ]
(log/debug "query-scalar:" query-spec)
(scalar-result (jdbc/query db-connection query-spec) default))
([ db-connection query-spec ]
(query-scalar db-connection query-spec nil)))
| true | ;; Copyright (c) 2015-2022 PI:NAME:<NAME>END_PI
;;
;; Licensed as below.
;;
;; Portions Copyright (c) 2014 KSM Technology Partners
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; The license is also includes at the root of the project in the file
;; LICENSE.
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; You must not remove this notice, or any other, from this software.
(ns sql-file.sql-util
(:require [clojure.tools.logging :as log]
[clojure.java.jdbc :as jdbc]))
(defn query-all [ db-connection query-spec ]
(log/debug "query-all:" query-spec)
(jdbc/query db-connection query-spec))
(defn query-first [ db-connection query-spec ]
(log/debug "query-first:" query-spec)
(first (jdbc/query db-connection query-spec)))
(defn scalar-result
([ query-result default ]
(or
(let [first-row (first query-result)
row-keys (keys first-row)]
(when (> (count row-keys) 1)
(log/debug "Queries used for query-scalar should only return one field per row."))
(get first-row (first row-keys)))
default))
([ query-result ]
(scalar-result query-result nil)))
(defn query-scalar
([ db-connection query-spec default ]
(log/debug "query-scalar:" query-spec)
(scalar-result (jdbc/query db-connection query-spec) default))
([ db-connection query-spec ]
(query-scalar db-connection query-spec nil)))
|
[
{
"context": ")\n\n(deftest case-insensitivity-test\n (let [name \"InT NaMe\"\n type \"iNt\"\n prev-aa {:Name (",
"end": 1979,
"score": 0.6849063634872437,
"start": 1976,
"tag": "NAME",
"value": "InT"
},
{
"context": "(deftest case-insensitivity-test\n (let [name \"InT NaMe\"\n type \"iNt\"\n prev-aa {:Name (str/l",
"end": 1984,
"score": 0.6381257772445679,
"start": 1980,
"tag": "USERNAME",
"value": "NaMe"
}
] | ingest-app/test/cmr/ingest/test/validation/additional_attribute_validation.clj | daniel-zamora/Common-Metadata-Repository | 0 | (ns cmr.ingest.test.validation.additional-attribute-validation
(:require
[clojure.string :as str]
[clojure.test :refer :all]
[cmr.common.util :as util]
[cmr.ingest.validation.additional-attribute-validation :as v]
[cmr.umm-spec.additional-attribute :as aa]))
(deftest aa-range-reduced-test
(util/are2
[prev-params params reduced?]
(let [aa {::aa/parsed-parameter-range-begin (first params)
::aa/parsed-parameter-range-end (last params)}
prev-aa {::aa/parsed-parameter-range-begin (first prev-params)
::aa/parsed-parameter-range-end (last prev-params)}]
(= reduced? (#'v/aa-range-reduced? aa prev-aa)))
"reduced on both ends" [3 9] [4 8] true
"reduced on min with max" [3 9] [4 10] true
"reduced on min no max" [3 9] [4 nil] true
"reduced on max with min" [3 9] [1 8] true
"reduced on max no min"[3 9] [nil 8] true
"same range" [3 9] [3 9] false
"expanded on both ends" [3 9] [2 10] false
"no max" [3 9] [3 nil] false
"no min" [3 9] [nil 9] false
"no range" [3 9] [nil nil] false))
(deftest out-of-range-searches-test
(are
[values expected-search]
(let [[name type begin end] values
msg (format "Collection additional attribute [%s] cannot be changed since there are existing granules outside of the new value range."
name)
expected {:params {"attribute[]" expected-search
"options[attribute][or]" true}
:error-msg msg}
aa {:Name name
:DataType type
:ParameterRangeBegin begin
:ParameterRangeEnd end}]
(= expected (#'v/out-of-range-searches aa)))
["alpha" "INT" 1 5] ["int,alpha,,1" "int,alpha,5,"]
["alpha" "INT" 1 nil] ["int,alpha,,1"]
["alpha" "INT" nil 5] ["int,alpha,5,"]
["alpha" "FLOAT" nil 1.23] ["float,alpha,1.23,"]))
(deftest case-insensitivity-test
(let [name "InT NaMe"
type "iNt"
prev-aa {:Name (str/lower-case name)
:DataType (str/lower-case type)}
aa {:Name name
:DataType type}]
(empty? (#'v/build-aa-deleted-searches [aa] [prev-aa]))
(empty? (#'v/build-aa-type-range-searches [aa] [prev-aa]))))
| 113274 | (ns cmr.ingest.test.validation.additional-attribute-validation
(:require
[clojure.string :as str]
[clojure.test :refer :all]
[cmr.common.util :as util]
[cmr.ingest.validation.additional-attribute-validation :as v]
[cmr.umm-spec.additional-attribute :as aa]))
(deftest aa-range-reduced-test
(util/are2
[prev-params params reduced?]
(let [aa {::aa/parsed-parameter-range-begin (first params)
::aa/parsed-parameter-range-end (last params)}
prev-aa {::aa/parsed-parameter-range-begin (first prev-params)
::aa/parsed-parameter-range-end (last prev-params)}]
(= reduced? (#'v/aa-range-reduced? aa prev-aa)))
"reduced on both ends" [3 9] [4 8] true
"reduced on min with max" [3 9] [4 10] true
"reduced on min no max" [3 9] [4 nil] true
"reduced on max with min" [3 9] [1 8] true
"reduced on max no min"[3 9] [nil 8] true
"same range" [3 9] [3 9] false
"expanded on both ends" [3 9] [2 10] false
"no max" [3 9] [3 nil] false
"no min" [3 9] [nil 9] false
"no range" [3 9] [nil nil] false))
(deftest out-of-range-searches-test
(are
[values expected-search]
(let [[name type begin end] values
msg (format "Collection additional attribute [%s] cannot be changed since there are existing granules outside of the new value range."
name)
expected {:params {"attribute[]" expected-search
"options[attribute][or]" true}
:error-msg msg}
aa {:Name name
:DataType type
:ParameterRangeBegin begin
:ParameterRangeEnd end}]
(= expected (#'v/out-of-range-searches aa)))
["alpha" "INT" 1 5] ["int,alpha,,1" "int,alpha,5,"]
["alpha" "INT" 1 nil] ["int,alpha,,1"]
["alpha" "INT" nil 5] ["int,alpha,5,"]
["alpha" "FLOAT" nil 1.23] ["float,alpha,1.23,"]))
(deftest case-insensitivity-test
(let [name "<NAME> NaMe"
type "iNt"
prev-aa {:Name (str/lower-case name)
:DataType (str/lower-case type)}
aa {:Name name
:DataType type}]
(empty? (#'v/build-aa-deleted-searches [aa] [prev-aa]))
(empty? (#'v/build-aa-type-range-searches [aa] [prev-aa]))))
| true | (ns cmr.ingest.test.validation.additional-attribute-validation
(:require
[clojure.string :as str]
[clojure.test :refer :all]
[cmr.common.util :as util]
[cmr.ingest.validation.additional-attribute-validation :as v]
[cmr.umm-spec.additional-attribute :as aa]))
(deftest aa-range-reduced-test
(util/are2
[prev-params params reduced?]
(let [aa {::aa/parsed-parameter-range-begin (first params)
::aa/parsed-parameter-range-end (last params)}
prev-aa {::aa/parsed-parameter-range-begin (first prev-params)
::aa/parsed-parameter-range-end (last prev-params)}]
(= reduced? (#'v/aa-range-reduced? aa prev-aa)))
"reduced on both ends" [3 9] [4 8] true
"reduced on min with max" [3 9] [4 10] true
"reduced on min no max" [3 9] [4 nil] true
"reduced on max with min" [3 9] [1 8] true
"reduced on max no min"[3 9] [nil 8] true
"same range" [3 9] [3 9] false
"expanded on both ends" [3 9] [2 10] false
"no max" [3 9] [3 nil] false
"no min" [3 9] [nil 9] false
"no range" [3 9] [nil nil] false))
(deftest out-of-range-searches-test
(are
[values expected-search]
(let [[name type begin end] values
msg (format "Collection additional attribute [%s] cannot be changed since there are existing granules outside of the new value range."
name)
expected {:params {"attribute[]" expected-search
"options[attribute][or]" true}
:error-msg msg}
aa {:Name name
:DataType type
:ParameterRangeBegin begin
:ParameterRangeEnd end}]
(= expected (#'v/out-of-range-searches aa)))
["alpha" "INT" 1 5] ["int,alpha,,1" "int,alpha,5,"]
["alpha" "INT" 1 nil] ["int,alpha,,1"]
["alpha" "INT" nil 5] ["int,alpha,5,"]
["alpha" "FLOAT" nil 1.23] ["float,alpha,1.23,"]))
(deftest case-insensitivity-test
(let [name "PI:NAME:<NAME>END_PI NaMe"
type "iNt"
prev-aa {:Name (str/lower-case name)
:DataType (str/lower-case type)}
aa {:Name name
:DataType type}]
(empty? (#'v/build-aa-deleted-searches [aa] [prev-aa]))
(empty? (#'v/build-aa-type-range-searches [aa] [prev-aa]))))
|
[
{
"context": "e.storage.names :as names])\n (:gen-class))\n\n(-> \"Pierre\"\n (names/create)\n :id\n (names/get-by-id)",
"end": 118,
"score": 0.9997817873954773,
"start": 112,
"tag": "NAME",
"value": "Pierre"
},
{
"context": "te)\n :id\n (names/get-by-id))\n(names/create \"Jean\")\n(-> \"Luc\"\n (names/create)\n :id\n (names",
"end": 189,
"score": 0.9997897148132324,
"start": 185,
"tag": "NAME",
"value": "Jean"
},
{
"context": " (names/get-by-id))\n(names/create \"Jean\")\n(-> \"Luc\"\n (names/create)\n :id\n (names/delete))\n(",
"end": 200,
"score": 0.9998445510864258,
"start": 197,
"tag": "NAME",
"value": "Luc"
},
{
"context": "reate)\n :id\n (names/delete))\n(names/create \"Sam\")\n\n(defn -main\n [& args]\n (println \"Names: \" (n",
"end": 267,
"score": 0.9998118281364441,
"start": 264,
"tag": "NAME",
"value": "Sam"
}
] | src/coffee_chat_roulette/core.clj | AGenson/coffee-chat-roulette | 0 | (ns coffee-chat-roulette.core
(:require [coffee-chat-roulette.storage.names :as names])
(:gen-class))
(-> "Pierre"
(names/create)
:id
(names/get-by-id))
(names/create "Jean")
(-> "Luc"
(names/create)
:id
(names/delete))
(names/create "Sam")
(defn -main
[& args]
(println "Names: " (names/get-all))
(println "Size: " (names/size)))
| 70865 | (ns coffee-chat-roulette.core
(:require [coffee-chat-roulette.storage.names :as names])
(:gen-class))
(-> "<NAME>"
(names/create)
:id
(names/get-by-id))
(names/create "<NAME>")
(-> "<NAME>"
(names/create)
:id
(names/delete))
(names/create "<NAME>")
(defn -main
[& args]
(println "Names: " (names/get-all))
(println "Size: " (names/size)))
| true | (ns coffee-chat-roulette.core
(:require [coffee-chat-roulette.storage.names :as names])
(:gen-class))
(-> "PI:NAME:<NAME>END_PI"
(names/create)
:id
(names/get-by-id))
(names/create "PI:NAME:<NAME>END_PI")
(-> "PI:NAME:<NAME>END_PI"
(names/create)
:id
(names/delete))
(names/create "PI:NAME:<NAME>END_PI")
(defn -main
[& args]
(println "Names: " (names/get-all))
(println "Size: " (names/size)))
|
[
{
"context": " (str \"//\" db-host \"/\" db-name)\n :user \"scott\"\n :password \"tiger\"})\n\n (with-connecti",
"end": 476,
"score": 0.9340846538543701,
"start": 471,
"tag": "USERNAME",
"value": "scott"
},
{
"context": "e)\n :user \"scott\"\n :password \"tiger\"})\n\n (with-connection db\n (delete-rows :citie",
"end": 505,
"score": 0.9987268447875977,
"start": 500,
"tag": "PASSWORD",
"value": "tiger"
}
] | mysql/clojure/delete/mysql_delete.clj | ekzemplaro/data_base_language | 3 | ; -----------------------------------------------------------------
;
; mysql_delete.clj
;
; Jul/17/2014
;
; -----------------------------------------------------------------
(use 'clojure.java.jdbc)
;
(println "*** 開始 ***")
(let [db-host "host_mysql"
db-name "city"
id (first *command-line-args*)
]
(println id)
(def db {:classname "org.gjt.mm.mysql.Driver"
:subprotocol "mysql"
:subname (str "//" db-host "/" db-name)
:user "scott"
:password "tiger"})
(with-connection db
(delete-rows :cities ["id=?" id])
))
(println "*** 終了 ***")
; -----------------------------------------------------------------
| 29454 | ; -----------------------------------------------------------------
;
; mysql_delete.clj
;
; Jul/17/2014
;
; -----------------------------------------------------------------
(use 'clojure.java.jdbc)
;
(println "*** 開始 ***")
(let [db-host "host_mysql"
db-name "city"
id (first *command-line-args*)
]
(println id)
(def db {:classname "org.gjt.mm.mysql.Driver"
:subprotocol "mysql"
:subname (str "//" db-host "/" db-name)
:user "scott"
:password "<PASSWORD>"})
(with-connection db
(delete-rows :cities ["id=?" id])
))
(println "*** 終了 ***")
; -----------------------------------------------------------------
| true | ; -----------------------------------------------------------------
;
; mysql_delete.clj
;
; Jul/17/2014
;
; -----------------------------------------------------------------
(use 'clojure.java.jdbc)
;
(println "*** 開始 ***")
(let [db-host "host_mysql"
db-name "city"
id (first *command-line-args*)
]
(println id)
(def db {:classname "org.gjt.mm.mysql.Driver"
:subprotocol "mysql"
:subname (str "//" db-host "/" db-name)
:user "scott"
:password "PI:PASSWORD:<PASSWORD>END_PI"})
(with-connection db
(delete-rows :cities ["id=?" id])
))
(println "*** 終了 ***")
; -----------------------------------------------------------------
|
[
{
"context": "estal when loading with midje testing turned on\n;; Daniel Ciumberica: Why is the log initializes itself when the names",
"end": 1999,
"score": 0.999799370765686,
"start": 1982,
"tag": "NAME",
"value": "Daniel Ciumberica"
}
] | src/clojupyter/log.clj | nighcoder/clojupyter | 2 | (ns clojupyter.log
(:require [clojupyter.kernel.config :as cfg]
[clojure.pprint :as pp]
[clojure.string :as str]
[io.simplect.compose :refer [def- C]]
[taoensso.timbre :as timbre]))
(def ^:dynamic *verbose* false)
(defmacro debug
[& args]
`(timbre/debug ~@args))
(defmacro info
[& args]
`(timbre/info ~@args))
(defmacro error
[& args]
`(timbre/error ~@args))
(defmacro warn
[& args]
`(timbre/warn ~@args))
(defmacro with-level
[level & body]
`(timbre/with-level ~level ~@body))
(defn ppstr
[v]
(with-out-str
(println)
(println ">>>>>>>")
(pp/pprint v)
(println "<<<<<<<<")))
(defonce ^:private ORG-CONFIG timbre/*config*)
(def- fmt-level
(C name str/upper-case first))
(defn- fmt-origin
[?ns-str ?file]
(str/replace (or ?ns-str ?file "?") #"^clojupyter\." "c8r."))
(defn output-fn
([ data] (output-fn nil data))
([opts data]
(let [{:keys [no-stacktrace?]} opts
{:keys [level ?err msg_ ?ns-str ?file hostname_
timestamp_ ?line]} data]
(str "["
(fmt-level level) " "
(force timestamp_) " "
"Clojupyter" "] "
(str (fmt-origin ?ns-str ?file)
(when ?line (str ":" ?line))) " -- "
(force msg_)
(when-not no-stacktrace?
(when-let [err ?err]
(str "\n" (timbre/stacktrace err opts))))))))
(def CONFIG {:timestamp-opts {:pattern "HH:mm:ss.SSS", :locale :jvm-default, :timezone (java.util.TimeZone/getDefault)}
:ns-blacklist ["io.pedestal.*"]
:output-fn output-fn
:level :warn})
(defn- set-clojupyter-config!
[]
(timbre/merge-config! CONFIG))
(defn- reset-config!
[]
(timbre/set-config! ORG-CONFIG))
(defn init!
[]
(set-clojupyter-config!)
(timbre/set-level! (cfg/log-level)))
(init!) ;; avoid spurious debug messages from io.pedestal when loading with midje testing turned on
;; Daniel Ciumberica: Why is the log initializes itself when the namespace is required?
| 7147 | (ns clojupyter.log
(:require [clojupyter.kernel.config :as cfg]
[clojure.pprint :as pp]
[clojure.string :as str]
[io.simplect.compose :refer [def- C]]
[taoensso.timbre :as timbre]))
(def ^:dynamic *verbose* false)
(defmacro debug
[& args]
`(timbre/debug ~@args))
(defmacro info
[& args]
`(timbre/info ~@args))
(defmacro error
[& args]
`(timbre/error ~@args))
(defmacro warn
[& args]
`(timbre/warn ~@args))
(defmacro with-level
[level & body]
`(timbre/with-level ~level ~@body))
(defn ppstr
[v]
(with-out-str
(println)
(println ">>>>>>>")
(pp/pprint v)
(println "<<<<<<<<")))
(defonce ^:private ORG-CONFIG timbre/*config*)
(def- fmt-level
(C name str/upper-case first))
(defn- fmt-origin
[?ns-str ?file]
(str/replace (or ?ns-str ?file "?") #"^clojupyter\." "c8r."))
(defn output-fn
([ data] (output-fn nil data))
([opts data]
(let [{:keys [no-stacktrace?]} opts
{:keys [level ?err msg_ ?ns-str ?file hostname_
timestamp_ ?line]} data]
(str "["
(fmt-level level) " "
(force timestamp_) " "
"Clojupyter" "] "
(str (fmt-origin ?ns-str ?file)
(when ?line (str ":" ?line))) " -- "
(force msg_)
(when-not no-stacktrace?
(when-let [err ?err]
(str "\n" (timbre/stacktrace err opts))))))))
(def CONFIG {:timestamp-opts {:pattern "HH:mm:ss.SSS", :locale :jvm-default, :timezone (java.util.TimeZone/getDefault)}
:ns-blacklist ["io.pedestal.*"]
:output-fn output-fn
:level :warn})
(defn- set-clojupyter-config!
[]
(timbre/merge-config! CONFIG))
(defn- reset-config!
[]
(timbre/set-config! ORG-CONFIG))
(defn init!
[]
(set-clojupyter-config!)
(timbre/set-level! (cfg/log-level)))
(init!) ;; avoid spurious debug messages from io.pedestal when loading with midje testing turned on
;; <NAME>: Why is the log initializes itself when the namespace is required?
| true | (ns clojupyter.log
(:require [clojupyter.kernel.config :as cfg]
[clojure.pprint :as pp]
[clojure.string :as str]
[io.simplect.compose :refer [def- C]]
[taoensso.timbre :as timbre]))
(def ^:dynamic *verbose* false)
(defmacro debug
[& args]
`(timbre/debug ~@args))
(defmacro info
[& args]
`(timbre/info ~@args))
(defmacro error
[& args]
`(timbre/error ~@args))
(defmacro warn
[& args]
`(timbre/warn ~@args))
(defmacro with-level
[level & body]
`(timbre/with-level ~level ~@body))
(defn ppstr
[v]
(with-out-str
(println)
(println ">>>>>>>")
(pp/pprint v)
(println "<<<<<<<<")))
(defonce ^:private ORG-CONFIG timbre/*config*)
(def- fmt-level
(C name str/upper-case first))
(defn- fmt-origin
[?ns-str ?file]
(str/replace (or ?ns-str ?file "?") #"^clojupyter\." "c8r."))
(defn output-fn
([ data] (output-fn nil data))
([opts data]
(let [{:keys [no-stacktrace?]} opts
{:keys [level ?err msg_ ?ns-str ?file hostname_
timestamp_ ?line]} data]
(str "["
(fmt-level level) " "
(force timestamp_) " "
"Clojupyter" "] "
(str (fmt-origin ?ns-str ?file)
(when ?line (str ":" ?line))) " -- "
(force msg_)
(when-not no-stacktrace?
(when-let [err ?err]
(str "\n" (timbre/stacktrace err opts))))))))
(def CONFIG {:timestamp-opts {:pattern "HH:mm:ss.SSS", :locale :jvm-default, :timezone (java.util.TimeZone/getDefault)}
:ns-blacklist ["io.pedestal.*"]
:output-fn output-fn
:level :warn})
(defn- set-clojupyter-config!
[]
(timbre/merge-config! CONFIG))
(defn- reset-config!
[]
(timbre/set-config! ORG-CONFIG))
(defn init!
[]
(set-clojupyter-config!)
(timbre/set-level! (cfg/log-level)))
(init!) ;; avoid spurious debug messages from io.pedestal when loading with midje testing turned on
;; PI:NAME:<NAME>END_PI: Why is the log initializes itself when the namespace is required?
|
[
{
"context": "ode]]\n - [[trace]]\n - [[value]]\"\n\n {:author \"Adam Helinski\"}\n\n (:import (convex.api Convex)\n (con",
"end": 395,
"score": 0.9991087317466736,
"start": 382,
"tag": "NAME",
"value": "Adam Helinski"
}
] | project/net/src/clj/main/convex/client.clj | rosejn/convex.cljc | 30 | (ns convex.client
"Interacting with a peer via the binary protocol.
After creating a client with [[connect]], main interactions are [[query]] and [[transact]].
All IO functions return a future which ultimately resolves to a result received from the peer.
Information from result can be extracted using:
- [[error-code]]
- [[trace]]
- [[value]]"
{:author "Adam Helinski"}
(:import (convex.api Convex)
(convex.core Result)
(convex.core.crypto AKeyPair)
(convex.core.data ACell
AVector
SignedData)
(convex.core.data.prim CVMLong)
(convex.core.lang Symbols)
(convex.core.store Stores)
(convex.core.transactions ATransaction)
(convex.peer Server)
(java.net InetSocketAddress)
(java.util.concurrent CompletableFuture)
(java.util.function Function))
(:refer-clojure :exclude [resolve
sequence])
(:require [convex.sign :as $.sign]))
(set! *warn-on-reflection*
true)
;;;;;;;;;; Lifecycle
(defn close
"Closes the given `client`.
See [[connect]]."
[^Convex connection]
(.close connection)
nil)
(defn connect
"Opens a new client connection to a peer using the binary protocol.
An optional map may be provided:
| Key | Value | Default |
|---|---|---|
| `:convex.server/host` | Peer IP address | \"localhost\" |
| `:convex.server/port` | Peer port | 18888 |
"
(^Convex []
(connect nil))
(^Convex [option+]
(Convex/connect (InetSocketAddress. (or ^String (:convex.server/host option+)
"localhost")
(long (or (:convex.server/port option+)
Server/DEFAULT_PORT)))
nil
nil
(or (:convex.client/db option+)
(Stores/current)))))
(defn connected?
"Returns true if the given `client` is still connected.
Attention. Currently, does not detect severed connections (eg. server shutting down).
See [[close]]."
[^Convex client]
(.isConnected client))
;;;;;;;;;; Networking - Performed directly by the client
(defn peer-status
"Advanced feature. The peer status is a vector of blobs which are hashes to data about the peer.
For instance, blob 4 is the hash of the state. That is how [[state]] works, retrieving the hash
from the peer status and then using [[resolve]]."
^CompletableFuture
[^Convex client]
(.requestStatus client))
(defn resolve
"Given a `hash` (see `convex.cell/hash` in `:project/cvm`), peer looks into its database and returns
the value it finds for that hash.
Returns a future resolving to a result."
(^CompletableFuture [^Convex client hash]
(.acquire client
hash))
(^CompletableFuture [^Convex client hash store]
(.acquire client
hash
store)))
(defn query
"Performs a query, `cell` representing code to execute.
Queries are a dry run: executed only by the peer, without consensus, and any state change is discarded.
They do not incur fees.
Returns a future resolving to a result."
^CompletableFuture
[^Convex client address cell]
(.query client
cell
address))
(defn state
"Requests the currrent network state from the peer.
Returns a future resolving to a result."
^CompletableFuture
[^Convex client]
(.acquireState client))
(defn transact
"Performs a transaction which is one of the following (from `:project/cvm`):
- `convex.cell/call` for an actor call
- `convex.cell/invoke` for executing code
- `convex.cell/transfer` for executing a transfer of Convex Coins
Transaction must be either pre-signed or a key pair must be provided (see `convex.sign` namespace from
`:project/crypto`).
It is important that transactions are created for the account matching the key pair and that the right
sequence number is used. See [[sequence]]."
(^CompletableFuture [^Convex client ^SignedData signed-transaction]
(.transact client
signed-transaction))
(^CompletableFuture [client ^AKeyPair key-pair ^ATransaction transaction]
(transact client
($.sign/signed key-pair
transaction))))
;;;;;;;;;; Results
(defn error-code
"Given a result dereferenced from a future, returns the error code (a cell, typically a CVM keyword).
Returns nil if no error occured."
^ACell
[^Result result]
(.getErrorCode result))
(defn trace
"Given a result dereferenced rfom a future, returns the stacktrace (a CVM vector of CVM strings).
Returns nil if no error occured."
^AVector
[^Result result]
(.getTrace result))
(defn value
"Given a result dereferenced from a future, returns its value (a cell).
In case of error, this will be the error message (typically a CVM string, although not necessarily)."
^ACell
[^Result result]
(.getValue result))
;;;;;;;;;; Networking - Higher-level
(defn sequence
"Uses [[query]] to retrieve the next sequence number required for a transaction.
Eacht account has a sequence number which is incremented on each successful transaction to prevent replay
attacks. Providing a transaction (eg. `convex.cell/invoke` from `:project/cvm`) with a wrong sequence
number will fail."
[^Convex client address]
(.thenApply (query client
address
Symbols/STAR_SEQUENCE)
(reify Function
(apply [_this result]
(if-some [ec (error-code result)]
(throw (ex-info "Unable to fetch next sequence"
{:convex.cell/address address
:convex.error/code ec
:convex.error/trace (trace result)}))
(inc (.longValue ^CVMLong (value result))))))))
| 61363 | (ns convex.client
"Interacting with a peer via the binary protocol.
After creating a client with [[connect]], main interactions are [[query]] and [[transact]].
All IO functions return a future which ultimately resolves to a result received from the peer.
Information from result can be extracted using:
- [[error-code]]
- [[trace]]
- [[value]]"
{:author "<NAME>"}
(:import (convex.api Convex)
(convex.core Result)
(convex.core.crypto AKeyPair)
(convex.core.data ACell
AVector
SignedData)
(convex.core.data.prim CVMLong)
(convex.core.lang Symbols)
(convex.core.store Stores)
(convex.core.transactions ATransaction)
(convex.peer Server)
(java.net InetSocketAddress)
(java.util.concurrent CompletableFuture)
(java.util.function Function))
(:refer-clojure :exclude [resolve
sequence])
(:require [convex.sign :as $.sign]))
(set! *warn-on-reflection*
true)
;;;;;;;;;; Lifecycle
(defn close
"Closes the given `client`.
See [[connect]]."
[^Convex connection]
(.close connection)
nil)
(defn connect
"Opens a new client connection to a peer using the binary protocol.
An optional map may be provided:
| Key | Value | Default |
|---|---|---|
| `:convex.server/host` | Peer IP address | \"localhost\" |
| `:convex.server/port` | Peer port | 18888 |
"
(^Convex []
(connect nil))
(^Convex [option+]
(Convex/connect (InetSocketAddress. (or ^String (:convex.server/host option+)
"localhost")
(long (or (:convex.server/port option+)
Server/DEFAULT_PORT)))
nil
nil
(or (:convex.client/db option+)
(Stores/current)))))
(defn connected?
"Returns true if the given `client` is still connected.
Attention. Currently, does not detect severed connections (eg. server shutting down).
See [[close]]."
[^Convex client]
(.isConnected client))
;;;;;;;;;; Networking - Performed directly by the client
(defn peer-status
"Advanced feature. The peer status is a vector of blobs which are hashes to data about the peer.
For instance, blob 4 is the hash of the state. That is how [[state]] works, retrieving the hash
from the peer status and then using [[resolve]]."
^CompletableFuture
[^Convex client]
(.requestStatus client))
(defn resolve
"Given a `hash` (see `convex.cell/hash` in `:project/cvm`), peer looks into its database and returns
the value it finds for that hash.
Returns a future resolving to a result."
(^CompletableFuture [^Convex client hash]
(.acquire client
hash))
(^CompletableFuture [^Convex client hash store]
(.acquire client
hash
store)))
(defn query
"Performs a query, `cell` representing code to execute.
Queries are a dry run: executed only by the peer, without consensus, and any state change is discarded.
They do not incur fees.
Returns a future resolving to a result."
^CompletableFuture
[^Convex client address cell]
(.query client
cell
address))
(defn state
"Requests the currrent network state from the peer.
Returns a future resolving to a result."
^CompletableFuture
[^Convex client]
(.acquireState client))
(defn transact
"Performs a transaction which is one of the following (from `:project/cvm`):
- `convex.cell/call` for an actor call
- `convex.cell/invoke` for executing code
- `convex.cell/transfer` for executing a transfer of Convex Coins
Transaction must be either pre-signed or a key pair must be provided (see `convex.sign` namespace from
`:project/crypto`).
It is important that transactions are created for the account matching the key pair and that the right
sequence number is used. See [[sequence]]."
(^CompletableFuture [^Convex client ^SignedData signed-transaction]
(.transact client
signed-transaction))
(^CompletableFuture [client ^AKeyPair key-pair ^ATransaction transaction]
(transact client
($.sign/signed key-pair
transaction))))
;;;;;;;;;; Results
(defn error-code
"Given a result dereferenced from a future, returns the error code (a cell, typically a CVM keyword).
Returns nil if no error occured."
^ACell
[^Result result]
(.getErrorCode result))
(defn trace
"Given a result dereferenced rfom a future, returns the stacktrace (a CVM vector of CVM strings).
Returns nil if no error occured."
^AVector
[^Result result]
(.getTrace result))
(defn value
"Given a result dereferenced from a future, returns its value (a cell).
In case of error, this will be the error message (typically a CVM string, although not necessarily)."
^ACell
[^Result result]
(.getValue result))
;;;;;;;;;; Networking - Higher-level
(defn sequence
"Uses [[query]] to retrieve the next sequence number required for a transaction.
Eacht account has a sequence number which is incremented on each successful transaction to prevent replay
attacks. Providing a transaction (eg. `convex.cell/invoke` from `:project/cvm`) with a wrong sequence
number will fail."
[^Convex client address]
(.thenApply (query client
address
Symbols/STAR_SEQUENCE)
(reify Function
(apply [_this result]
(if-some [ec (error-code result)]
(throw (ex-info "Unable to fetch next sequence"
{:convex.cell/address address
:convex.error/code ec
:convex.error/trace (trace result)}))
(inc (.longValue ^CVMLong (value result))))))))
| true | (ns convex.client
"Interacting with a peer via the binary protocol.
After creating a client with [[connect]], main interactions are [[query]] and [[transact]].
All IO functions return a future which ultimately resolves to a result received from the peer.
Information from result can be extracted using:
- [[error-code]]
- [[trace]]
- [[value]]"
{:author "PI:NAME:<NAME>END_PI"}
(:import (convex.api Convex)
(convex.core Result)
(convex.core.crypto AKeyPair)
(convex.core.data ACell
AVector
SignedData)
(convex.core.data.prim CVMLong)
(convex.core.lang Symbols)
(convex.core.store Stores)
(convex.core.transactions ATransaction)
(convex.peer Server)
(java.net InetSocketAddress)
(java.util.concurrent CompletableFuture)
(java.util.function Function))
(:refer-clojure :exclude [resolve
sequence])
(:require [convex.sign :as $.sign]))
(set! *warn-on-reflection*
true)
;;;;;;;;;; Lifecycle
(defn close
"Closes the given `client`.
See [[connect]]."
[^Convex connection]
(.close connection)
nil)
(defn connect
"Opens a new client connection to a peer using the binary protocol.
An optional map may be provided:
| Key | Value | Default |
|---|---|---|
| `:convex.server/host` | Peer IP address | \"localhost\" |
| `:convex.server/port` | Peer port | 18888 |
"
(^Convex []
(connect nil))
(^Convex [option+]
(Convex/connect (InetSocketAddress. (or ^String (:convex.server/host option+)
"localhost")
(long (or (:convex.server/port option+)
Server/DEFAULT_PORT)))
nil
nil
(or (:convex.client/db option+)
(Stores/current)))))
(defn connected?
"Returns true if the given `client` is still connected.
Attention. Currently, does not detect severed connections (eg. server shutting down).
See [[close]]."
[^Convex client]
(.isConnected client))
;;;;;;;;;; Networking - Performed directly by the client
(defn peer-status
"Advanced feature. The peer status is a vector of blobs which are hashes to data about the peer.
For instance, blob 4 is the hash of the state. That is how [[state]] works, retrieving the hash
from the peer status and then using [[resolve]]."
^CompletableFuture
[^Convex client]
(.requestStatus client))
(defn resolve
"Given a `hash` (see `convex.cell/hash` in `:project/cvm`), peer looks into its database and returns
the value it finds for that hash.
Returns a future resolving to a result."
(^CompletableFuture [^Convex client hash]
(.acquire client
hash))
(^CompletableFuture [^Convex client hash store]
(.acquire client
hash
store)))
(defn query
"Performs a query, `cell` representing code to execute.
Queries are a dry run: executed only by the peer, without consensus, and any state change is discarded.
They do not incur fees.
Returns a future resolving to a result."
^CompletableFuture
[^Convex client address cell]
(.query client
cell
address))
(defn state
"Requests the currrent network state from the peer.
Returns a future resolving to a result."
^CompletableFuture
[^Convex client]
(.acquireState client))
(defn transact
"Performs a transaction which is one of the following (from `:project/cvm`):
- `convex.cell/call` for an actor call
- `convex.cell/invoke` for executing code
- `convex.cell/transfer` for executing a transfer of Convex Coins
Transaction must be either pre-signed or a key pair must be provided (see `convex.sign` namespace from
`:project/crypto`).
It is important that transactions are created for the account matching the key pair and that the right
sequence number is used. See [[sequence]]."
(^CompletableFuture [^Convex client ^SignedData signed-transaction]
(.transact client
signed-transaction))
(^CompletableFuture [client ^AKeyPair key-pair ^ATransaction transaction]
(transact client
($.sign/signed key-pair
transaction))))
;;;;;;;;;; Results
(defn error-code
"Given a result dereferenced from a future, returns the error code (a cell, typically a CVM keyword).
Returns nil if no error occured."
^ACell
[^Result result]
(.getErrorCode result))
(defn trace
"Given a result dereferenced rfom a future, returns the stacktrace (a CVM vector of CVM strings).
Returns nil if no error occured."
^AVector
[^Result result]
(.getTrace result))
(defn value
"Given a result dereferenced from a future, returns its value (a cell).
In case of error, this will be the error message (typically a CVM string, although not necessarily)."
^ACell
[^Result result]
(.getValue result))
;;;;;;;;;; Networking - Higher-level
(defn sequence
"Uses [[query]] to retrieve the next sequence number required for a transaction.
Eacht account has a sequence number which is incremented on each successful transaction to prevent replay
attacks. Providing a transaction (eg. `convex.cell/invoke` from `:project/cvm`) with a wrong sequence
number will fail."
[^Convex client address]
(.thenApply (query client
address
Symbols/STAR_SEQUENCE)
(reify Function
(apply [_this result]
(if-some [ec (error-code result)]
(throw (ex-info "Unable to fetch next sequence"
{:convex.cell/address address
:convex.error/code ec
:convex.error/trace (trace result)}))
(inc (.longValue ^CVMLong (value result))))))))
|
[
{
"context": "ue-str\n :user-id \"user1\"\n :format \"applic",
"end": 3923,
"score": 0.968005895614624,
"start": 3918,
"tag": "USERNAME",
"value": "user1"
},
{
"context": " :description \\\"A good tag\\\" :originator-id \\\"user1\\\"}\")\n :revision-d",
"end": 4112,
"score": 0.6140139102935791,
"start": 4111,
"tag": "USERNAME",
"value": "1"
},
{
"context": " tag1-colls [coll1 coll2]\n tag-key \"tag1\"\n tag1 (tags/save-tag\n u",
"end": 38481,
"score": 0.8772122263908386,
"start": 38477,
"tag": "KEY",
"value": "tag1"
}
] | system-int-test/test/cmr/system_int_test/bootstrap/bulk_index_test.clj | sxu123/Common-Metadata-Repository | 0 | (ns cmr.system-int-test.bootstrap.bulk-index-test
"Integration test for CMR bulk indexing."
(:require
[clj-time.coerce :as cr]
[clj-time.core :as t]
[clojure.java.jdbc :as j]
[clojure.test :refer :all]
[cmr.access-control.test.util :as u]
[cmr.common.date-time-parser :as p]
[cmr.common.util :as util :refer [are3]]
[cmr.mock-echo.client.echo-util :as e]
[cmr.oracle.connection :as oracle]
[cmr.system-int-test.data2.collection :as dc]
[cmr.system-int-test.data2.core :as d]
[cmr.system-int-test.data2.granule :as dg]
[cmr.system-int-test.system :as s]
[cmr.system-int-test.utils.bootstrap-util :as bootstrap]
[cmr.system-int-test.utils.dev-system-util :as dev-sys-util]
[cmr.system-int-test.utils.index-util :as index]
[cmr.system-int-test.utils.ingest-util :as ingest]
[cmr.system-int-test.utils.metadata-db-util :as mdb]
[cmr.system-int-test.utils.search-util :as search]
[cmr.system-int-test.utils.tag-util :as tags]
[cmr.transmit.access-control :as ac]
[cmr.transmit.config :as tc]
[cmr.umm.echo10.echo10-core :as echo10]))
(use-fixtures :each (join-fixtures
[(ingest/reset-fixture {"provguid1" "PROV1"})
tags/grant-all-tag-fixture]))
(defn- save-collection
"Saves a collection concept"
([n]
(save-collection n {}))
([n attributes]
(let [unique-str (str "coll" n)
umm (dc/collection {:short-name unique-str :entry-title unique-str})
xml (echo10/umm->echo10-xml umm)
coll (mdb/save-concept (merge
{:concept-type :collection
:format "application/echo10+xml"
:metadata xml
:extra-fields {:short-name unique-str
:entry-title unique-str
:entry-id unique-str
:version-id "v1"}
:revision-date "2000-01-01T10:00:00Z"
:provider-id "PROV1"
:native-id unique-str
:short-name unique-str}
attributes))]
;; Make sure the concept was saved successfully
(is (= 201 (:status coll)))
(merge umm (select-keys coll [:concept-id :revision-id])))))
(defn- save-granule
"Saves a granule concept"
([n collection]
(save-granule n collection {}))
([n collection attributes]
(let [unique-str (str "gran" n)
umm (dg/granule collection {:granule-ur unique-str})
xml (echo10/umm->echo10-xml umm)
gran (mdb/save-concept (merge
{:concept-type :granule
:provider-id "PROV1"
:native-id unique-str
:format "application/echo10+xml"
:metadata xml
:revision-date "2000-01-01T10:00:00Z"
:extra-fields {:parent-collection-id (:concept-id collection)
:parent-entry-title (:entry-title collection)
:granule-ur unique-str}}
attributes))]
;; Make sure the concept was saved successfully
(is (= 201 (:status gran)))
(merge umm (select-keys gran [:concept-id :revision-id])))))
(defn- save-tag
"Saves a tag concept"
([n]
(save-tag n {}))
([n attributes]
(let [unique-str (str "tag" n)
tag (mdb/save-concept (merge
{:concept-type :tag
:native-id unique-str
:user-id "user1"
:format "application/edn"
:metadata (str "{:tag-key \"" unique-str "\" :description \"A good tag\" :originator-id \"user1\"}")
:revision-date "2000-01-01T10:00:00Z"}
attributes))]
;; Make sure the concept was saved successfully
(is (= 201 (:status tag)))
(merge tag (select-keys tag [:concept-id :revision-id])))))
(defn- save-acl
"Saves an acl"
[n attributes target]
(let [unique-str (str "acl" n)
acl (mdb/save-concept (merge
{:concept-type :acl
:provider-id "CMR"
:native-id unique-str
:format "application/edn"
:metadata (pr-str {:group-permissions [{:user-type "guest"
:permissions ["read" "update"]}]
:system-identity {:target target}})
:revision-date "2000-01-01T10:00:00Z"}
attributes))]
;; Make sure the acl was saved successfully
(is (= 201 (:status acl)))
acl))
(defn- save-group
"Saves a group"
([n]
(save-group n {}))
([n attributes]
(let [unique-str (str "group" n)
group (mdb/save-concept (merge
{:concept-type :access-group
:provider-id "CMR"
:native-id unique-str
:format "application/edn"
:metadata "{:name \"Administrators\"
:description \"The group of users that manages the CMR.\"
:members [\"user1\" \"user2\"]}"
:revision-date "2000-01-01T10:00:00Z"}
attributes))]
;; Make sure the group was saved successfully
(is (= 201 (:status group)))
group)))
(defn- delete-concept
"Creates a tombstone for the concept in metadata-db."
[concept]
(let [tombstone (update-in concept [:revision-id] inc)]
(is (= 201 (:status (mdb/tombstone-concept tombstone))))))
(defn- normalize-search-result-item
"Returns a map with just concept-id and revision-id for the given item."
[result-item]
(-> result-item
util/map-keys->kebab-case
(select-keys [:concept-id :revision-id])))
(defn- search-results-match?
"Compare search results to expected results."
[results expected]
(let [search-items (set (map normalize-search-result-item results))
exp-items (set (map #(dissoc % :status) expected))]
(is (= exp-items search-items))))
(defn- get-last-replicated-revision-date
"Helper to get the last replicated revision date from the database."
[db]
(j/with-db-transaction
[conn db]
(->> (j/query conn ["SELECT LAST_REPLICATED_REVISION_DATE FROM REPLICATION_STATUS"])
first
:last_replicated_revision_date
(oracle/oracle-timestamp->str-time conn))))
(deftest index-system-concepts-test
(s/only-with-real-database
;; Disable message publishing so items are not indexed as part of the initial save.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! false))
(let [acl1 (save-acl 1
{:extra-fields {:acl-identity "system:token"
:target-provider-id "PROV1"}}
"TOKEN")
acl2 (save-acl 2
{:extra-fields {:acl-identity "system:group"
:target-provider-id "PROV1"}}
"GROUP")
acl3 (save-acl 3
{:extra-fields {:acl-identity "system:user"
:target-provider-id "PROV1"}}
"USER")
_ (delete-concept acl3)
group1 (save-group 1 {})
group2 (save-group 2 {})
group3 (save-group 3 {})
_ (delete-concept group2)
tag1 (save-tag 1 {})
_ (delete-concept tag1)
;; this tag has no originator-id to test a bug fix for a bug in tag processing related to missing originator-ids
tag2 (save-tag 2 {:metadata "{:tag-key \"tag2\" :description \"A good tag\"}"})
tag3 (save-tag 3 {})]
(bootstrap/bulk-index-system-concepts)
;; Force elastic data to be flushed, not actually waiting for index requests to finish
(index/wait-until-indexed)
;; ACLs
(let [response (ac/search-for-acls (u/conn-context) {} {:token (tc/echo-system-token)})
items (:items response)]
(search-results-match? items [acl1 acl2]))
;; Groups
(let [response (ac/search-for-groups (u/conn-context) {})
;; Need to filter out admin group created by fixture
items (filter #(not (= "mock-admin-group-guid" (:legacy_guid %))) (:items response))]
(search-results-match? items [group1 group3]))
(are3 [expected-tags]
(let [result-tags (update
(tags/search {})
:items
(fn [items]
(map #(select-keys % [:concept-id :revision-id]) items)))]
(tags/assert-tag-search expected-tags result-tags))
"Tags"
[tag2 tag3])
;; Re-enable message publishing.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! true)))))
;; Commented out due to requiring a database link in order to work - this job is only transitional
;; for moving to NGAP so we will remove it once we have fully transitioned.
#_(deftest index-recently-replicated-test
(s/only-with-real-database
;; Disable message publishing so items are not indexed as part of the initial save.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! false))
(let [last-replicated-datetime "3016-01-01T10:00:00Z"
coll-missed-cutoff (save-collection 1 {:revision-date "3016-01-01T09:59:40Z"})
coll-within-buffer (save-collection 2 {:revision-date "3016-01-01T09:59:41Z"})
coll-after-date (save-collection 3 {:revision-date "3016-01-02T00:00:00Z"})
gran-missed-cutoff (save-granule 1 coll-missed-cutoff {:revision-date "3016-01-01T09:59:40Z"})
gran-within-buffer (save-granule 2 coll-within-buffer {:revision-date "3016-01-01T09:59:41Z"})
gran-after-date (save-granule 3 coll-after-date {:revision-date "3016-01-02T00:00:00Z"})
tag-missed-cutoff (save-tag 1 {:revision-date "3016-01-01T09:59:40Z"})
tag-within-buffer (save-tag 2 {:revision-date "3016-01-01T09:59:41Z"})
tag-after-date (save-tag 3 {:revision-date "3016-01-02T00:00:00Z"})
acl-missed-cutoff (save-acl 1
{:revision-date "3016-01-01T09:59:40Z"
:extra-fields {:acl-identity "system:token"
:target-provider-id "PROV1"}}
"TOKEN")
acl-within-buffer (save-acl 2
{:revision-date "3016-01-01T09:59:41Z"
:extra-fields {:acl-identity "system:group"
:target-provider-id "PROV1"}}
"GROUP")
acl-after-date (save-acl 3
{:revision-date "3016-01-02T00:00:00Z"
:extra-fields {:acl-identity "system:user"
:target-provider-id "PROV1"}}
"USER")
group-missed-cutoff (save-group 1 {:revision-date "3016-01-01T09:59:40Z"})
group-within-buffer (save-group 2 {:revision-date "3016-01-01T09:59:41Z"})
group-after-date (save-group 3 {:revision-date "3016-01-02T00:00:00Z"})
db (get-in (s/context) [:system :bootstrap-db])
stmt "UPDATE REPLICATION_STATUS SET LAST_REPLICATED_REVISION_DATE = ?"]
(j/db-do-prepared db stmt [(cr/to-sql-time (p/parse-datetime last-replicated-datetime))])
(bootstrap/index-recently-replicated)
;; Force elastic data to be flushed, not actually waiting for index requests to finish
(index/wait-until-indexed)
(testing "Concepts with revision date within 20 seconds of last replicated date are indexed."
(are3 [concept-type expected]
(d/refs-match? expected (search/find-refs concept-type {}))
"Collections"
:collection [coll-within-buffer coll-after-date]
"Granules"
:granule [gran-within-buffer gran-after-date])
;; ACLs
(let [response (ac/search-for-acls (u/conn-context) {} {:token (tc/echo-system-token)})
items (:items response)]
(search-results-match? items [acl-within-buffer acl-after-date]))
;; Groups
(let [response (ac/search-for-groups (u/conn-context) {})
;; Need to filter out admin group created by fixture
items (filter #(not (= "mock-admin-group-guid" (:legacy_guid %))) (:items response))]
(search-results-match? items [group-within-buffer group-after-date]))
(are3 [expected-tags]
(let [result-tags (update
(tags/search {})
:items
(fn [items]
(map #(select-keys % [:concept-id :revision-id]) items)))]
(tags/assert-tag-search expected-tags result-tags))
"Tags"
[tag-within-buffer tag-after-date])))
(testing "When there are no concepts to index the date is not changed."
(j/db-do-prepared db stmt [(cr/to-sql-time (p/parse-datetime "3016-02-01T10:00:00.000Z"))])
(bootstrap/index-recently-replicated)
(is (= "3016-02-01T10:00:00.000Z" (get-last-replicated-revision-date db))))
(testing "Max revision dates are tracked correctly"
(testing "for provider concepts"
(let [coll (save-collection 1 {:revision-date "3016-02-02T10:59:40Z"})]
(save-granule 1 coll {:revision-date "3016-02-01T11:59:40Z"})
(save-tag 1 {:revision-date "3016-02-01T18:59:40Z"})
(bootstrap/index-recently-replicated))
(is (= "3016-02-02T10:59:40.000Z" (get-last-replicated-revision-date db))))
(testing "for system concepts"
(let [coll (save-collection 1 {:revision-date "3016-02-03T10:59:40Z"})]
(save-granule 1 coll {:revision-date "3016-03-01T11:59:40Z"})
(save-tag 1 {:revision-date "3016-03-01T12:10:47Z"})
(bootstrap/index-recently-replicated))
(is (= "3016-03-01T12:10:47.000Z" (get-last-replicated-revision-date db))))))
;; Re-enable message publishing.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! true)))
(deftest bulk-index-by-concept-id
(s/only-with-real-database
;; Disable message publishing so items are not indexed.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! false))
(let [;; saved but not indexed
coll1 (save-collection 1)
coll2 (save-collection 2 {})
colls (map :concept-id [coll1 coll2])
gran1 (save-granule 1 coll1)
gran2 (save-granule 2 coll2 {})
tag1 (save-tag 1)
tag2 (save-tag 2 {})
acl1 (save-acl 1
{:extra-fields {:acl-identity "system:token"
:target-provider-id "PROV1"}}
"TOKEN")
acl2 (save-acl 2
{:extra-fields {:acl-identity "system:group"
:target-provider-id "PROV1"}}
"GROUP")
group1 (save-group 1)
group2 (save-group 2 {})]
(bootstrap/bulk-index-concepts "PROV1" :collection colls)
(bootstrap/bulk-index-concepts "PROV1" :granule [(:concept-id gran2)])
(bootstrap/bulk-index-concepts "PROV1" :tag [(:concept-id tag1)])
;; Commented out until ACLs and groups are supported in the index by concept-id API
; (bootstrap/bulk-index-concepts "CMR" :access-group [(:concept-id group2)])
; (bootstrap/bulk-index-concepts "CMR" :acl [(:concept-id acl2)])
(index/wait-until-indexed)
(testing "Concepts are indexed."
;; Collections and granules
(are3 [concept-type expected]
(d/refs-match? expected (search/find-refs concept-type {}))
"Collections"
:collection [coll1 coll2]
"Granules"
:granule [gran2])
;; Commented out until ACLs and groups are supported in the index by concept-id API
; ;; ACLs
; (let [response (ac/search-for-acls (u/conn-context) {} {:token (tc/echo-system-token)})
; items (:items response)]
; (search-results-match? items [acl2]))
; ;; ;; Groups
; (let [response (ac/search-for-groups (u/conn-context) {})
; ;; Need to filter out admin group created by fixture
; items (filter #(not (= "mock-admin-group-guid" (:legacy_guid %))) (:items response))]
; (search-results-match? items [group2]))
(are3 [expected-tags]
(let [result-tags (update
(tags/search {})
:items
(fn [items]
(map #(select-keys % [:concept-id :revision-id]) items)))]
(tags/assert-tag-search expected-tags result-tags))
"Tags"
[tag1])))
;; Re-enable message publishing.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! true))))
(deftest bulk-delete-by-concept-id
(s/only-with-real-database
(let [coll1 (save-collection 1)
coll2 (save-collection 2 {})
coll3 (save-collection 3 {})
gran1 (save-granule 1 coll2)
gran2 (save-granule 2 coll2 {})
tag1 (save-tag 1)
tag2 (save-tag 2 {})
acl1 (save-acl 1
{:extra-fields {:acl-identity "system:token"
:target-provider-id "PROV1"}}
"TOKEN")
acl2 (save-acl 2
{:extra-fields {:acl-identity "system:group"
:target-provider-id "PROV1"}}
"GROUP")
group1 (save-group 1)
group2 (save-group 2 {})]
(bootstrap/bulk-delete-concepts "PROV1" :collection (map :concept-id [coll1 coll3]))
(bootstrap/bulk-delete-concepts "PROV1" :granule [(:concept-id gran2)])
(bootstrap/bulk-delete-concepts "PROV1" :tag [(:concept-id tag1)])
;; Commented out until ACLs and groups are supported in the delete by concept-id API
; (bootstrap/bulk-index-concepts "CMR" :access-group [(:concept-id group2)])
; (bootstrap/bulk-index-concepts "CMR" :acl [(:concept-id acl2)])
(index/wait-until-indexed)
(testing "Concepts are deleted"
;; Collections and granules
(are3 [concept-type expected]
(d/refs-match? expected (search/find-refs concept-type {}))
"Collections"
:collection [coll2]
"Granules"
:granule [gran1])
(are3 [expected-tags]
(let [result-tags (update
(tags/search {})
:items
(fn [items]
(map #(select-keys % [:concept-id :revision-id]) items)))]
(tags/assert-tag-search expected-tags result-tags))
"Tags"
[tag2])))))
(deftest bulk-index-after-date-time
(s/only-with-real-database
;; Disable message publishing so items are not indexed.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! false))
(let [;; saved but not indexed
coll1 (save-collection 1)
coll2 (save-collection 2 {:revision-date "3016-01-01T10:00:00Z"})
gran1 (save-granule 1 coll1)
gran2 (save-granule 2 coll2 {:revision-date "3016-01-01T10:00:00Z"})
tag1 (save-tag 1)
tag2 (save-tag 2 {:revision-date "3016-01-01T10:00:00Z"})
acl1 (save-acl 1
{:revision-date "2000-01-01T09:59:40Z"
:extra-fields {:acl-identity "system:token"
:target-provider-id "PROV1"}}
"TOKEN")
acl2 (save-acl 2
{:revision-date "3016-01-01T09:59:41Z"
:extra-fields {:acl-identity "system:group"
:target-provider-id "PROV1"}}
"GROUP")
group1 (save-group 1)
group2 (save-group 2 {:revision-date "3016-01-01T10:00:00Z"})]
(bootstrap/bulk-index-after-date-time "2015-01-01T12:00:00Z")
(index/wait-until-indexed)
(testing "Only concepts after date are indexed."
(are3 [concept-type expected]
(d/refs-match? expected (search/find-refs concept-type {}))
"Collections"
:collection [coll2]
"Granules"
:granule [gran2])
;; ACLs
(let [response (ac/search-for-acls (u/conn-context) {} {:token (tc/echo-system-token)})
items (:items response)]
(search-results-match? items [acl2]))
;; Groups
(let [response (ac/search-for-groups (u/conn-context) {})
;; Need to filter out admin group created by fixture
items (filter #(not (= "mock-admin-group-guid" (:legacy_guid %))) (:items response))]
(search-results-match? items [group2]))
(are3 [expected-tags]
(let [result-tags (update
(tags/search {})
:items
(fn [items]
(map #(select-keys % [:concept-id :revision-id]) items)))]
(tags/assert-tag-search expected-tags result-tags))
"Tags"
[tag2])))
;; Re-enable message publishing.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! true))))
;; This test runs bulk index with some concepts in mdb that are good, and some that are
;; deleted, and some that have not yet been deleted, but have an expired deletion date.
(deftest bulk-index-with-some-deleted
(s/only-with-real-database
;; Disable message publishing so items are not indexed as part of the initial save.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! false))
(let [;; coll1 is a regular collection that is ingested
umm1 (dc/collection {:short-name "coll1" :entry-title "coll1"})
xml1 (echo10/umm->echo10-xml umm1)
coll1 (mdb/save-concept {:concept-type :collection
:format "application/echo10+xml"
:metadata xml1
:extra-fields {:short-name "coll1"
:entry-title "coll1"
:entry-id "coll1"
:version-id "v1"}
:provider-id "PROV1"
:native-id "coll1"
:short-name "coll1"})
umm1 (merge umm1 (select-keys coll1 [:concept-id :revision-id]))
;; coll2 is a regualr collection that is ingested and will be deleted later
coll2 (d/ingest "PROV1" (dc/collection {:short-name "coll2" :entry-title "coll2"}))
;; coll3 is a collection with an expired delete time
umm3 (dc/collection {:short-name "coll3" :entry-title "coll3" :delete-time "2000-01-01T12:00:00Z"})
xml3 (echo10/umm->echo10-xml umm3)
coll3 (mdb/save-concept {:concept-type :collection
:format "application/echo10+xml"
:metadata xml3
:extra-fields {:short-name "coll3"
:entry-title "coll3"
:entry-id "coll3"
:version-id "v1"
:delete-time "2000-01-01T12:00:00Z"}
:provider-id "PROV1"
:native-id "coll3"
:short-name "coll3"})
;; gran1 is a regular granule that is ingested
ummg1 (dg/granule coll1 {:granule-ur "gran1"})
xmlg1 (echo10/umm->echo10-xml ummg1)
gran1 (mdb/save-concept {:concept-type :granule
:provider-id "PROV1"
:native-id "gran1"
:format "application/echo10+xml"
:metadata xmlg1
:extra-fields {:parent-collection-id (:concept-id umm1)
:parent-entry-title "coll1"
:granule-ur "gran1"}})
ummg1 (merge ummg1 (select-keys gran1 [:concept-id :revision-id]))
;; gran2 is a regular granule that is ingested and will be deleted later
ummg2 (dg/granule coll1 {:granule-ur "gran2"})
xmlg2 (echo10/umm->echo10-xml ummg2)
gran2 (mdb/save-concept {:concept-type :granule
:provider-id "PROV1"
:native-id "gran2"
:format "application/echo10+xml"
:metadata xmlg2
:extra-fields {:parent-collection-id (:concept-id umm1)
:parent-entry-title "coll1"
:granule-ur "gran2"}})
ummg2 (merge ummg2 (select-keys gran2 [:concept-id :revision-id]))
;; gran3 is a granule with an expired delete time
ummg3 (dg/granule coll1 {:granule-ur "gran3" :delete-time "2000-01-01T12:00:00Z"})
xmlg3 (echo10/umm->echo10-xml ummg3)
gran3 (mdb/save-concept {:concept-type :granule
:provider-id "PROV1"
:native-id "gran3"
:format "application/echo10+xml"
:metadata xmlg3
:extra-fields {:parent-collection-id (:concept-id umm1)
:parent-entry-title "coll1"
:granule-ur "gran3"}})]
;; Verify that all of the ingest requests completed successfully
(doseq [concept [coll1 coll2 coll3 gran1 gran2 gran3]] (is (= 201 (:status concept))))
;; bulk index all collections and granules
(bootstrap/bulk-index-provider "PROV1")
(index/wait-until-indexed)
(testing "Expired documents are not indexed during bulk indexing"
(are [search concept-type expected]
(d/refs-match? expected (search/find-refs concept-type search))
{:concept-id (:concept-id coll1)} :collection [umm1]
{:concept-id (:concept-id coll2)} :collection [coll2]
{:concept-id (:concept-id coll3)} :collection []
{:concept-id (:concept-id gran1)} :granule [ummg1]
{:concept-id (:concept-id gran2)} :granule [ummg2]
{:concept-id (:concept-id gran3)} :granule []))
(testing "Deleted documents get deleted during bulk indexing"
(let [coll2-tombstone {:concept-id (:concept-id coll2)
:revision-id (inc (:revision-id coll2))}
gran2-tombstone {:concept-id (:concept-id gran2)
:revision-id (inc (:revision-id gran2))}]
;; delete coll2 and gran2 in metadata-db
(mdb/tombstone-concept coll2-tombstone)
(mdb/tombstone-concept gran2-tombstone)
;; bulk index all collections and granules
(bootstrap/bulk-index-provider "PROV1")
(index/wait-until-indexed)
(are [search concept-type expected]
(d/refs-match? expected (search/find-refs concept-type search))
{:concept-id (:concept-id coll1)} :collection [umm1]
{:concept-id (:concept-id coll2)} :collection []
{:concept-id (:concept-id coll3)} :collection []
{:concept-id (:concept-id gran1)} :granule [ummg1]
{:concept-id (:concept-id gran2)} :granule []
{:concept-id (:concept-id gran3)} :granule []))))
;; Re-enable message publishing.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! true))))
;; This test verifies that the bulk indexer can run concurrently with ingest and indexing of items.
;; This test performs the following steps:
;; 1. Saves ten collections in metadata db.
;; 2. Saves three granules for each of those collections in metadata db.
;; 3. Ingests ten granules five times each in a separate thread.
;; 4. Concurrently executes a bulk index operation for the provider.
;; 5. Waits for the bulk indexing and granule ingest to complete.
;; 6. Searches for all of the saved/ingested concepts by concept-id.
;; 7. Verifies that the concepts returned by search have the expected revision ids.
(deftest bulk-index-after-ingest
(s/only-with-real-database
(let [collections (for [x (range 1 11)]
(let [umm (dc/collection {:short-name (str "short-name" x)
:entry-title (str "title" x)})
xml (echo10/umm->echo10-xml umm)
concept-map {:concept-type :collection
:format "application/echo10+xml"
:metadata xml
:extra-fields {:short-name (str "short-name" x)
:entry-title (str "title" x)
:entry-id (str "entry-id" x)
:version-id "v1"}
:provider-id "PROV1"
:native-id (str "coll" x)
:short-name (str "short-name" x)}
{:keys [concept-id revision-id]} (mdb/save-concept concept-map)]
(assoc umm :concept-id concept-id :revision-id revision-id)))
granules1 (mapcat (fn [collection]
(doall
(for [x (range 1 4)]
(let [pid (:concept-id collection)
umm (dg/granule collection)
xml (echo10/umm->echo10-xml umm)
concept-map {:concept-type :granule
:provider-id "PROV1"
:native-id (str "gran-" pid "-" x)
:extra-fields {:parent-collection-id pid
:parent-entry-title
(:entry-title collection)
:granule-ur (str "gran-" pid "-" x)}
:format "application/echo10+xml"
:metadata xml}
{:keys [concept-id revision-id]} (mdb/save-concept concept-map)]
(assoc umm :concept-id concept-id :revision-id revision-id)))))
collections)
;; granules2 and f (the future) are used to ingest ten granules five times each in
;; a separate thread to verify that bulk indexing with concurrent ingest does the right
;; thing.
granules2 (let [collection (first collections)
pid (:concept-id collection)]
(for [x (range 1 11)]
(dg/granule collection {:granule-ur (str "gran2-" pid "-" x)})))
f (future (dotimes [n 5]
(doall (map (fn [gran]
(Thread/sleep 100)
(d/ingest "PROV1" gran))
granules2))))]
(bootstrap/bulk-index-provider "PROV1")
;; force our future to complete
@f
(index/wait-until-indexed)
(testing "retrieval after bulk indexing returns the latest revision."
(doseq [collection collections]
(let [{:keys [concept-id revision-id]} collection
response (search/find-refs :collection {:concept-id concept-id})
es-revision-id (:revision-id (first (:refs response)))]
;; the latest revision should be indexed
(is (= es-revision-id revision-id))))
(doseq [granule granules1]
(let [{:keys [concept-id revision-id]} granule
response (search/find-refs :granule {:concept-id concept-id})
es-revision-id (:revision-id (first (:refs response)))]
(is (= es-revision-id revision-id) (str "Failure for granule " concept-id))))
(doseq [granule (last @f)]
(let [{:keys [concept-id]} granule
response (search/find-refs :granule {:concept-id concept-id})
es-revision-id (:revision-id (first (:refs response)))]
(is (= 5 es-revision-id) (str "Failure for granule " concept-id))))))))
(deftest invalid-provider-bulk-index-validation-test
(s/only-with-real-database
(testing "Validation of a provider supplied in a bulk-index request."
(let [{:keys [status errors]} (bootstrap/bulk-index-provider "NCD4580")]
(is (= [400 ["Provider: [NCD4580] does not exist in the system"]]
[status errors]))))))
(deftest collection-bulk-index-validation-test
(s/only-with-real-database
(let [umm1 (dc/collection {:short-name "coll1" :entry-title "coll1"})
xml1 (echo10/umm->echo10-xml umm1)
coll1 (mdb/save-concept {:concept-type :collection
:format "application/echo10+xml"
:metadata xml1
:extra-fields {:short-name "coll1"
:entry-title "coll1"
:entry-id "coll1"
:version-id "v1"}
:provider-id "PROV1"
:native-id "coll1"
:short-name "coll1"})
umm1 (merge umm1 (select-keys coll1 [:concept-id :revision-id]))
ummg1 (dg/granule coll1 {:granule-ur "gran1"})
xmlg1 (echo10/umm->echo10-xml ummg1)
gran1 (mdb/save-concept {:concept-type :granule
:provider-id "PROV1"
:native-id "gran1"
:format "application/echo10+xml"
:metadata xmlg1
:extra-fields {:parent-collection-id (:concept-id umm1)
:parent-entry-title "coll1"}})
valid-prov-id "PROV1"
valid-coll-id (:concept-id umm1)
invalid-prov-id "NCD4580"
invalid-coll-id "C12-PROV1"
err-msg1 (format "Provider: [%s] does not exist in the system" invalid-prov-id)
err-msg2 (format "Collection [%s] does not exist." invalid-coll-id)
{:keys [status errors] :as succ-stat} (bootstrap/bulk-index-collection
valid-prov-id valid-coll-id)
;; invalid provider and collection
{:keys [status errors] :as fail-stat1} (bootstrap/bulk-index-collection
invalid-prov-id invalid-coll-id)
;; valid provider and invalid collection
{:keys [status errors] :as fail-stat2} (bootstrap/bulk-index-collection
valid-prov-id invalid-coll-id)
;; invalid provider and valid collection
{:keys [status errors] :as fail-stat3} (bootstrap/bulk-index-collection
invalid-prov-id valid-coll-id)]
(testing "Validation of a collection supplied in a bulk-index request."
(are [expected actual] (= expected actual)
[202 nil] [(:status succ-stat) (:errors succ-stat)]
[400 [err-msg1]] [(:status fail-stat1) (:errors fail-stat1)]
[400 [err-msg2]] [(:status fail-stat2) (:errors fail-stat2)]
[400 [err-msg1]] [(:status fail-stat3) (:errors fail-stat3)])))))
;; This test is to verify that bulk index works with tombstoned tag associations
(deftest bulk-index-collections-with-tag-association-test
(s/only-with-real-database
(let [[coll1 coll2] (for [n (range 1 3)]
(d/ingest "PROV1" (dc/collection {:entry-title (str "coll" n)})))
;; Wait until collections are indexed so tags can be associated with them
_ (index/wait-until-indexed)
user1-token (e/login (s/context) "user1")
tag1-colls [coll1 coll2]
tag-key "tag1"
tag1 (tags/save-tag
user1-token
(tags/make-tag {:tag-key tag-key})
tag1-colls)]
(index/wait-until-indexed)
;; disassociate tag1 from coll2 and not send indexing events
(dev-sys-util/eval-in-dev-sys
`(cmr.metadata-db.config/set-publish-messages! false))
(tags/disassociate-by-query user1-token tag-key {:concept_id (:concept-id coll2)})
(dev-sys-util/eval-in-dev-sys
`(cmr.metadata-db.config/set-publish-messages! true))
(bootstrap/bulk-index-provider "PROV1")
(index/wait-until-indexed)
(testing "All tag parameters with XML references"
(is (d/refs-match? [coll1]
(search/find-refs :collection {:tag-key "tag1"})))))))
| 70472 | (ns cmr.system-int-test.bootstrap.bulk-index-test
"Integration test for CMR bulk indexing."
(:require
[clj-time.coerce :as cr]
[clj-time.core :as t]
[clojure.java.jdbc :as j]
[clojure.test :refer :all]
[cmr.access-control.test.util :as u]
[cmr.common.date-time-parser :as p]
[cmr.common.util :as util :refer [are3]]
[cmr.mock-echo.client.echo-util :as e]
[cmr.oracle.connection :as oracle]
[cmr.system-int-test.data2.collection :as dc]
[cmr.system-int-test.data2.core :as d]
[cmr.system-int-test.data2.granule :as dg]
[cmr.system-int-test.system :as s]
[cmr.system-int-test.utils.bootstrap-util :as bootstrap]
[cmr.system-int-test.utils.dev-system-util :as dev-sys-util]
[cmr.system-int-test.utils.index-util :as index]
[cmr.system-int-test.utils.ingest-util :as ingest]
[cmr.system-int-test.utils.metadata-db-util :as mdb]
[cmr.system-int-test.utils.search-util :as search]
[cmr.system-int-test.utils.tag-util :as tags]
[cmr.transmit.access-control :as ac]
[cmr.transmit.config :as tc]
[cmr.umm.echo10.echo10-core :as echo10]))
(use-fixtures :each (join-fixtures
[(ingest/reset-fixture {"provguid1" "PROV1"})
tags/grant-all-tag-fixture]))
(defn- save-collection
"Saves a collection concept"
([n]
(save-collection n {}))
([n attributes]
(let [unique-str (str "coll" n)
umm (dc/collection {:short-name unique-str :entry-title unique-str})
xml (echo10/umm->echo10-xml umm)
coll (mdb/save-concept (merge
{:concept-type :collection
:format "application/echo10+xml"
:metadata xml
:extra-fields {:short-name unique-str
:entry-title unique-str
:entry-id unique-str
:version-id "v1"}
:revision-date "2000-01-01T10:00:00Z"
:provider-id "PROV1"
:native-id unique-str
:short-name unique-str}
attributes))]
;; Make sure the concept was saved successfully
(is (= 201 (:status coll)))
(merge umm (select-keys coll [:concept-id :revision-id])))))
(defn- save-granule
"Saves a granule concept"
([n collection]
(save-granule n collection {}))
([n collection attributes]
(let [unique-str (str "gran" n)
umm (dg/granule collection {:granule-ur unique-str})
xml (echo10/umm->echo10-xml umm)
gran (mdb/save-concept (merge
{:concept-type :granule
:provider-id "PROV1"
:native-id unique-str
:format "application/echo10+xml"
:metadata xml
:revision-date "2000-01-01T10:00:00Z"
:extra-fields {:parent-collection-id (:concept-id collection)
:parent-entry-title (:entry-title collection)
:granule-ur unique-str}}
attributes))]
;; Make sure the concept was saved successfully
(is (= 201 (:status gran)))
(merge umm (select-keys gran [:concept-id :revision-id])))))
(defn- save-tag
"Saves a tag concept"
([n]
(save-tag n {}))
([n attributes]
(let [unique-str (str "tag" n)
tag (mdb/save-concept (merge
{:concept-type :tag
:native-id unique-str
:user-id "user1"
:format "application/edn"
:metadata (str "{:tag-key \"" unique-str "\" :description \"A good tag\" :originator-id \"user1\"}")
:revision-date "2000-01-01T10:00:00Z"}
attributes))]
;; Make sure the concept was saved successfully
(is (= 201 (:status tag)))
(merge tag (select-keys tag [:concept-id :revision-id])))))
(defn- save-acl
"Saves an acl"
[n attributes target]
(let [unique-str (str "acl" n)
acl (mdb/save-concept (merge
{:concept-type :acl
:provider-id "CMR"
:native-id unique-str
:format "application/edn"
:metadata (pr-str {:group-permissions [{:user-type "guest"
:permissions ["read" "update"]}]
:system-identity {:target target}})
:revision-date "2000-01-01T10:00:00Z"}
attributes))]
;; Make sure the acl was saved successfully
(is (= 201 (:status acl)))
acl))
(defn- save-group
"Saves a group"
([n]
(save-group n {}))
([n attributes]
(let [unique-str (str "group" n)
group (mdb/save-concept (merge
{:concept-type :access-group
:provider-id "CMR"
:native-id unique-str
:format "application/edn"
:metadata "{:name \"Administrators\"
:description \"The group of users that manages the CMR.\"
:members [\"user1\" \"user2\"]}"
:revision-date "2000-01-01T10:00:00Z"}
attributes))]
;; Make sure the group was saved successfully
(is (= 201 (:status group)))
group)))
(defn- delete-concept
"Creates a tombstone for the concept in metadata-db."
[concept]
(let [tombstone (update-in concept [:revision-id] inc)]
(is (= 201 (:status (mdb/tombstone-concept tombstone))))))
(defn- normalize-search-result-item
"Returns a map with just concept-id and revision-id for the given item."
[result-item]
(-> result-item
util/map-keys->kebab-case
(select-keys [:concept-id :revision-id])))
(defn- search-results-match?
"Compare search results to expected results."
[results expected]
(let [search-items (set (map normalize-search-result-item results))
exp-items (set (map #(dissoc % :status) expected))]
(is (= exp-items search-items))))
(defn- get-last-replicated-revision-date
"Helper to get the last replicated revision date from the database."
[db]
(j/with-db-transaction
[conn db]
(->> (j/query conn ["SELECT LAST_REPLICATED_REVISION_DATE FROM REPLICATION_STATUS"])
first
:last_replicated_revision_date
(oracle/oracle-timestamp->str-time conn))))
(deftest index-system-concepts-test
(s/only-with-real-database
;; Disable message publishing so items are not indexed as part of the initial save.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! false))
(let [acl1 (save-acl 1
{:extra-fields {:acl-identity "system:token"
:target-provider-id "PROV1"}}
"TOKEN")
acl2 (save-acl 2
{:extra-fields {:acl-identity "system:group"
:target-provider-id "PROV1"}}
"GROUP")
acl3 (save-acl 3
{:extra-fields {:acl-identity "system:user"
:target-provider-id "PROV1"}}
"USER")
_ (delete-concept acl3)
group1 (save-group 1 {})
group2 (save-group 2 {})
group3 (save-group 3 {})
_ (delete-concept group2)
tag1 (save-tag 1 {})
_ (delete-concept tag1)
;; this tag has no originator-id to test a bug fix for a bug in tag processing related to missing originator-ids
tag2 (save-tag 2 {:metadata "{:tag-key \"tag2\" :description \"A good tag\"}"})
tag3 (save-tag 3 {})]
(bootstrap/bulk-index-system-concepts)
;; Force elastic data to be flushed, not actually waiting for index requests to finish
(index/wait-until-indexed)
;; ACLs
(let [response (ac/search-for-acls (u/conn-context) {} {:token (tc/echo-system-token)})
items (:items response)]
(search-results-match? items [acl1 acl2]))
;; Groups
(let [response (ac/search-for-groups (u/conn-context) {})
;; Need to filter out admin group created by fixture
items (filter #(not (= "mock-admin-group-guid" (:legacy_guid %))) (:items response))]
(search-results-match? items [group1 group3]))
(are3 [expected-tags]
(let [result-tags (update
(tags/search {})
:items
(fn [items]
(map #(select-keys % [:concept-id :revision-id]) items)))]
(tags/assert-tag-search expected-tags result-tags))
"Tags"
[tag2 tag3])
;; Re-enable message publishing.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! true)))))
;; Commented out due to requiring a database link in order to work - this job is only transitional
;; for moving to NGAP so we will remove it once we have fully transitioned.
#_(deftest index-recently-replicated-test
(s/only-with-real-database
;; Disable message publishing so items are not indexed as part of the initial save.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! false))
(let [last-replicated-datetime "3016-01-01T10:00:00Z"
coll-missed-cutoff (save-collection 1 {:revision-date "3016-01-01T09:59:40Z"})
coll-within-buffer (save-collection 2 {:revision-date "3016-01-01T09:59:41Z"})
coll-after-date (save-collection 3 {:revision-date "3016-01-02T00:00:00Z"})
gran-missed-cutoff (save-granule 1 coll-missed-cutoff {:revision-date "3016-01-01T09:59:40Z"})
gran-within-buffer (save-granule 2 coll-within-buffer {:revision-date "3016-01-01T09:59:41Z"})
gran-after-date (save-granule 3 coll-after-date {:revision-date "3016-01-02T00:00:00Z"})
tag-missed-cutoff (save-tag 1 {:revision-date "3016-01-01T09:59:40Z"})
tag-within-buffer (save-tag 2 {:revision-date "3016-01-01T09:59:41Z"})
tag-after-date (save-tag 3 {:revision-date "3016-01-02T00:00:00Z"})
acl-missed-cutoff (save-acl 1
{:revision-date "3016-01-01T09:59:40Z"
:extra-fields {:acl-identity "system:token"
:target-provider-id "PROV1"}}
"TOKEN")
acl-within-buffer (save-acl 2
{:revision-date "3016-01-01T09:59:41Z"
:extra-fields {:acl-identity "system:group"
:target-provider-id "PROV1"}}
"GROUP")
acl-after-date (save-acl 3
{:revision-date "3016-01-02T00:00:00Z"
:extra-fields {:acl-identity "system:user"
:target-provider-id "PROV1"}}
"USER")
group-missed-cutoff (save-group 1 {:revision-date "3016-01-01T09:59:40Z"})
group-within-buffer (save-group 2 {:revision-date "3016-01-01T09:59:41Z"})
group-after-date (save-group 3 {:revision-date "3016-01-02T00:00:00Z"})
db (get-in (s/context) [:system :bootstrap-db])
stmt "UPDATE REPLICATION_STATUS SET LAST_REPLICATED_REVISION_DATE = ?"]
(j/db-do-prepared db stmt [(cr/to-sql-time (p/parse-datetime last-replicated-datetime))])
(bootstrap/index-recently-replicated)
;; Force elastic data to be flushed, not actually waiting for index requests to finish
(index/wait-until-indexed)
(testing "Concepts with revision date within 20 seconds of last replicated date are indexed."
(are3 [concept-type expected]
(d/refs-match? expected (search/find-refs concept-type {}))
"Collections"
:collection [coll-within-buffer coll-after-date]
"Granules"
:granule [gran-within-buffer gran-after-date])
;; ACLs
(let [response (ac/search-for-acls (u/conn-context) {} {:token (tc/echo-system-token)})
items (:items response)]
(search-results-match? items [acl-within-buffer acl-after-date]))
;; Groups
(let [response (ac/search-for-groups (u/conn-context) {})
;; Need to filter out admin group created by fixture
items (filter #(not (= "mock-admin-group-guid" (:legacy_guid %))) (:items response))]
(search-results-match? items [group-within-buffer group-after-date]))
(are3 [expected-tags]
(let [result-tags (update
(tags/search {})
:items
(fn [items]
(map #(select-keys % [:concept-id :revision-id]) items)))]
(tags/assert-tag-search expected-tags result-tags))
"Tags"
[tag-within-buffer tag-after-date])))
(testing "When there are no concepts to index the date is not changed."
(j/db-do-prepared db stmt [(cr/to-sql-time (p/parse-datetime "3016-02-01T10:00:00.000Z"))])
(bootstrap/index-recently-replicated)
(is (= "3016-02-01T10:00:00.000Z" (get-last-replicated-revision-date db))))
(testing "Max revision dates are tracked correctly"
(testing "for provider concepts"
(let [coll (save-collection 1 {:revision-date "3016-02-02T10:59:40Z"})]
(save-granule 1 coll {:revision-date "3016-02-01T11:59:40Z"})
(save-tag 1 {:revision-date "3016-02-01T18:59:40Z"})
(bootstrap/index-recently-replicated))
(is (= "3016-02-02T10:59:40.000Z" (get-last-replicated-revision-date db))))
(testing "for system concepts"
(let [coll (save-collection 1 {:revision-date "3016-02-03T10:59:40Z"})]
(save-granule 1 coll {:revision-date "3016-03-01T11:59:40Z"})
(save-tag 1 {:revision-date "3016-03-01T12:10:47Z"})
(bootstrap/index-recently-replicated))
(is (= "3016-03-01T12:10:47.000Z" (get-last-replicated-revision-date db))))))
;; Re-enable message publishing.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! true)))
(deftest bulk-index-by-concept-id
(s/only-with-real-database
;; Disable message publishing so items are not indexed.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! false))
(let [;; saved but not indexed
coll1 (save-collection 1)
coll2 (save-collection 2 {})
colls (map :concept-id [coll1 coll2])
gran1 (save-granule 1 coll1)
gran2 (save-granule 2 coll2 {})
tag1 (save-tag 1)
tag2 (save-tag 2 {})
acl1 (save-acl 1
{:extra-fields {:acl-identity "system:token"
:target-provider-id "PROV1"}}
"TOKEN")
acl2 (save-acl 2
{:extra-fields {:acl-identity "system:group"
:target-provider-id "PROV1"}}
"GROUP")
group1 (save-group 1)
group2 (save-group 2 {})]
(bootstrap/bulk-index-concepts "PROV1" :collection colls)
(bootstrap/bulk-index-concepts "PROV1" :granule [(:concept-id gran2)])
(bootstrap/bulk-index-concepts "PROV1" :tag [(:concept-id tag1)])
;; Commented out until ACLs and groups are supported in the index by concept-id API
; (bootstrap/bulk-index-concepts "CMR" :access-group [(:concept-id group2)])
; (bootstrap/bulk-index-concepts "CMR" :acl [(:concept-id acl2)])
(index/wait-until-indexed)
(testing "Concepts are indexed."
;; Collections and granules
(are3 [concept-type expected]
(d/refs-match? expected (search/find-refs concept-type {}))
"Collections"
:collection [coll1 coll2]
"Granules"
:granule [gran2])
;; Commented out until ACLs and groups are supported in the index by concept-id API
; ;; ACLs
; (let [response (ac/search-for-acls (u/conn-context) {} {:token (tc/echo-system-token)})
; items (:items response)]
; (search-results-match? items [acl2]))
; ;; ;; Groups
; (let [response (ac/search-for-groups (u/conn-context) {})
; ;; Need to filter out admin group created by fixture
; items (filter #(not (= "mock-admin-group-guid" (:legacy_guid %))) (:items response))]
; (search-results-match? items [group2]))
(are3 [expected-tags]
(let [result-tags (update
(tags/search {})
:items
(fn [items]
(map #(select-keys % [:concept-id :revision-id]) items)))]
(tags/assert-tag-search expected-tags result-tags))
"Tags"
[tag1])))
;; Re-enable message publishing.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! true))))
(deftest bulk-delete-by-concept-id
(s/only-with-real-database
(let [coll1 (save-collection 1)
coll2 (save-collection 2 {})
coll3 (save-collection 3 {})
gran1 (save-granule 1 coll2)
gran2 (save-granule 2 coll2 {})
tag1 (save-tag 1)
tag2 (save-tag 2 {})
acl1 (save-acl 1
{:extra-fields {:acl-identity "system:token"
:target-provider-id "PROV1"}}
"TOKEN")
acl2 (save-acl 2
{:extra-fields {:acl-identity "system:group"
:target-provider-id "PROV1"}}
"GROUP")
group1 (save-group 1)
group2 (save-group 2 {})]
(bootstrap/bulk-delete-concepts "PROV1" :collection (map :concept-id [coll1 coll3]))
(bootstrap/bulk-delete-concepts "PROV1" :granule [(:concept-id gran2)])
(bootstrap/bulk-delete-concepts "PROV1" :tag [(:concept-id tag1)])
;; Commented out until ACLs and groups are supported in the delete by concept-id API
; (bootstrap/bulk-index-concepts "CMR" :access-group [(:concept-id group2)])
; (bootstrap/bulk-index-concepts "CMR" :acl [(:concept-id acl2)])
(index/wait-until-indexed)
(testing "Concepts are deleted"
;; Collections and granules
(are3 [concept-type expected]
(d/refs-match? expected (search/find-refs concept-type {}))
"Collections"
:collection [coll2]
"Granules"
:granule [gran1])
(are3 [expected-tags]
(let [result-tags (update
(tags/search {})
:items
(fn [items]
(map #(select-keys % [:concept-id :revision-id]) items)))]
(tags/assert-tag-search expected-tags result-tags))
"Tags"
[tag2])))))
(deftest bulk-index-after-date-time
(s/only-with-real-database
;; Disable message publishing so items are not indexed.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! false))
(let [;; saved but not indexed
coll1 (save-collection 1)
coll2 (save-collection 2 {:revision-date "3016-01-01T10:00:00Z"})
gran1 (save-granule 1 coll1)
gran2 (save-granule 2 coll2 {:revision-date "3016-01-01T10:00:00Z"})
tag1 (save-tag 1)
tag2 (save-tag 2 {:revision-date "3016-01-01T10:00:00Z"})
acl1 (save-acl 1
{:revision-date "2000-01-01T09:59:40Z"
:extra-fields {:acl-identity "system:token"
:target-provider-id "PROV1"}}
"TOKEN")
acl2 (save-acl 2
{:revision-date "3016-01-01T09:59:41Z"
:extra-fields {:acl-identity "system:group"
:target-provider-id "PROV1"}}
"GROUP")
group1 (save-group 1)
group2 (save-group 2 {:revision-date "3016-01-01T10:00:00Z"})]
(bootstrap/bulk-index-after-date-time "2015-01-01T12:00:00Z")
(index/wait-until-indexed)
(testing "Only concepts after date are indexed."
(are3 [concept-type expected]
(d/refs-match? expected (search/find-refs concept-type {}))
"Collections"
:collection [coll2]
"Granules"
:granule [gran2])
;; ACLs
(let [response (ac/search-for-acls (u/conn-context) {} {:token (tc/echo-system-token)})
items (:items response)]
(search-results-match? items [acl2]))
;; Groups
(let [response (ac/search-for-groups (u/conn-context) {})
;; Need to filter out admin group created by fixture
items (filter #(not (= "mock-admin-group-guid" (:legacy_guid %))) (:items response))]
(search-results-match? items [group2]))
(are3 [expected-tags]
(let [result-tags (update
(tags/search {})
:items
(fn [items]
(map #(select-keys % [:concept-id :revision-id]) items)))]
(tags/assert-tag-search expected-tags result-tags))
"Tags"
[tag2])))
;; Re-enable message publishing.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! true))))
;; This test runs bulk index with some concepts in mdb that are good, and some that are
;; deleted, and some that have not yet been deleted, but have an expired deletion date.
(deftest bulk-index-with-some-deleted
(s/only-with-real-database
;; Disable message publishing so items are not indexed as part of the initial save.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! false))
(let [;; coll1 is a regular collection that is ingested
umm1 (dc/collection {:short-name "coll1" :entry-title "coll1"})
xml1 (echo10/umm->echo10-xml umm1)
coll1 (mdb/save-concept {:concept-type :collection
:format "application/echo10+xml"
:metadata xml1
:extra-fields {:short-name "coll1"
:entry-title "coll1"
:entry-id "coll1"
:version-id "v1"}
:provider-id "PROV1"
:native-id "coll1"
:short-name "coll1"})
umm1 (merge umm1 (select-keys coll1 [:concept-id :revision-id]))
;; coll2 is a regualr collection that is ingested and will be deleted later
coll2 (d/ingest "PROV1" (dc/collection {:short-name "coll2" :entry-title "coll2"}))
;; coll3 is a collection with an expired delete time
umm3 (dc/collection {:short-name "coll3" :entry-title "coll3" :delete-time "2000-01-01T12:00:00Z"})
xml3 (echo10/umm->echo10-xml umm3)
coll3 (mdb/save-concept {:concept-type :collection
:format "application/echo10+xml"
:metadata xml3
:extra-fields {:short-name "coll3"
:entry-title "coll3"
:entry-id "coll3"
:version-id "v1"
:delete-time "2000-01-01T12:00:00Z"}
:provider-id "PROV1"
:native-id "coll3"
:short-name "coll3"})
;; gran1 is a regular granule that is ingested
ummg1 (dg/granule coll1 {:granule-ur "gran1"})
xmlg1 (echo10/umm->echo10-xml ummg1)
gran1 (mdb/save-concept {:concept-type :granule
:provider-id "PROV1"
:native-id "gran1"
:format "application/echo10+xml"
:metadata xmlg1
:extra-fields {:parent-collection-id (:concept-id umm1)
:parent-entry-title "coll1"
:granule-ur "gran1"}})
ummg1 (merge ummg1 (select-keys gran1 [:concept-id :revision-id]))
;; gran2 is a regular granule that is ingested and will be deleted later
ummg2 (dg/granule coll1 {:granule-ur "gran2"})
xmlg2 (echo10/umm->echo10-xml ummg2)
gran2 (mdb/save-concept {:concept-type :granule
:provider-id "PROV1"
:native-id "gran2"
:format "application/echo10+xml"
:metadata xmlg2
:extra-fields {:parent-collection-id (:concept-id umm1)
:parent-entry-title "coll1"
:granule-ur "gran2"}})
ummg2 (merge ummg2 (select-keys gran2 [:concept-id :revision-id]))
;; gran3 is a granule with an expired delete time
ummg3 (dg/granule coll1 {:granule-ur "gran3" :delete-time "2000-01-01T12:00:00Z"})
xmlg3 (echo10/umm->echo10-xml ummg3)
gran3 (mdb/save-concept {:concept-type :granule
:provider-id "PROV1"
:native-id "gran3"
:format "application/echo10+xml"
:metadata xmlg3
:extra-fields {:parent-collection-id (:concept-id umm1)
:parent-entry-title "coll1"
:granule-ur "gran3"}})]
;; Verify that all of the ingest requests completed successfully
(doseq [concept [coll1 coll2 coll3 gran1 gran2 gran3]] (is (= 201 (:status concept))))
;; bulk index all collections and granules
(bootstrap/bulk-index-provider "PROV1")
(index/wait-until-indexed)
(testing "Expired documents are not indexed during bulk indexing"
(are [search concept-type expected]
(d/refs-match? expected (search/find-refs concept-type search))
{:concept-id (:concept-id coll1)} :collection [umm1]
{:concept-id (:concept-id coll2)} :collection [coll2]
{:concept-id (:concept-id coll3)} :collection []
{:concept-id (:concept-id gran1)} :granule [ummg1]
{:concept-id (:concept-id gran2)} :granule [ummg2]
{:concept-id (:concept-id gran3)} :granule []))
(testing "Deleted documents get deleted during bulk indexing"
(let [coll2-tombstone {:concept-id (:concept-id coll2)
:revision-id (inc (:revision-id coll2))}
gran2-tombstone {:concept-id (:concept-id gran2)
:revision-id (inc (:revision-id gran2))}]
;; delete coll2 and gran2 in metadata-db
(mdb/tombstone-concept coll2-tombstone)
(mdb/tombstone-concept gran2-tombstone)
;; bulk index all collections and granules
(bootstrap/bulk-index-provider "PROV1")
(index/wait-until-indexed)
(are [search concept-type expected]
(d/refs-match? expected (search/find-refs concept-type search))
{:concept-id (:concept-id coll1)} :collection [umm1]
{:concept-id (:concept-id coll2)} :collection []
{:concept-id (:concept-id coll3)} :collection []
{:concept-id (:concept-id gran1)} :granule [ummg1]
{:concept-id (:concept-id gran2)} :granule []
{:concept-id (:concept-id gran3)} :granule []))))
;; Re-enable message publishing.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! true))))
;; This test verifies that the bulk indexer can run concurrently with ingest and indexing of items.
;; This test performs the following steps:
;; 1. Saves ten collections in metadata db.
;; 2. Saves three granules for each of those collections in metadata db.
;; 3. Ingests ten granules five times each in a separate thread.
;; 4. Concurrently executes a bulk index operation for the provider.
;; 5. Waits for the bulk indexing and granule ingest to complete.
;; 6. Searches for all of the saved/ingested concepts by concept-id.
;; 7. Verifies that the concepts returned by search have the expected revision ids.
(deftest bulk-index-after-ingest
(s/only-with-real-database
(let [collections (for [x (range 1 11)]
(let [umm (dc/collection {:short-name (str "short-name" x)
:entry-title (str "title" x)})
xml (echo10/umm->echo10-xml umm)
concept-map {:concept-type :collection
:format "application/echo10+xml"
:metadata xml
:extra-fields {:short-name (str "short-name" x)
:entry-title (str "title" x)
:entry-id (str "entry-id" x)
:version-id "v1"}
:provider-id "PROV1"
:native-id (str "coll" x)
:short-name (str "short-name" x)}
{:keys [concept-id revision-id]} (mdb/save-concept concept-map)]
(assoc umm :concept-id concept-id :revision-id revision-id)))
granules1 (mapcat (fn [collection]
(doall
(for [x (range 1 4)]
(let [pid (:concept-id collection)
umm (dg/granule collection)
xml (echo10/umm->echo10-xml umm)
concept-map {:concept-type :granule
:provider-id "PROV1"
:native-id (str "gran-" pid "-" x)
:extra-fields {:parent-collection-id pid
:parent-entry-title
(:entry-title collection)
:granule-ur (str "gran-" pid "-" x)}
:format "application/echo10+xml"
:metadata xml}
{:keys [concept-id revision-id]} (mdb/save-concept concept-map)]
(assoc umm :concept-id concept-id :revision-id revision-id)))))
collections)
;; granules2 and f (the future) are used to ingest ten granules five times each in
;; a separate thread to verify that bulk indexing with concurrent ingest does the right
;; thing.
granules2 (let [collection (first collections)
pid (:concept-id collection)]
(for [x (range 1 11)]
(dg/granule collection {:granule-ur (str "gran2-" pid "-" x)})))
f (future (dotimes [n 5]
(doall (map (fn [gran]
(Thread/sleep 100)
(d/ingest "PROV1" gran))
granules2))))]
(bootstrap/bulk-index-provider "PROV1")
;; force our future to complete
@f
(index/wait-until-indexed)
(testing "retrieval after bulk indexing returns the latest revision."
(doseq [collection collections]
(let [{:keys [concept-id revision-id]} collection
response (search/find-refs :collection {:concept-id concept-id})
es-revision-id (:revision-id (first (:refs response)))]
;; the latest revision should be indexed
(is (= es-revision-id revision-id))))
(doseq [granule granules1]
(let [{:keys [concept-id revision-id]} granule
response (search/find-refs :granule {:concept-id concept-id})
es-revision-id (:revision-id (first (:refs response)))]
(is (= es-revision-id revision-id) (str "Failure for granule " concept-id))))
(doseq [granule (last @f)]
(let [{:keys [concept-id]} granule
response (search/find-refs :granule {:concept-id concept-id})
es-revision-id (:revision-id (first (:refs response)))]
(is (= 5 es-revision-id) (str "Failure for granule " concept-id))))))))
(deftest invalid-provider-bulk-index-validation-test
(s/only-with-real-database
(testing "Validation of a provider supplied in a bulk-index request."
(let [{:keys [status errors]} (bootstrap/bulk-index-provider "NCD4580")]
(is (= [400 ["Provider: [NCD4580] does not exist in the system"]]
[status errors]))))))
(deftest collection-bulk-index-validation-test
(s/only-with-real-database
(let [umm1 (dc/collection {:short-name "coll1" :entry-title "coll1"})
xml1 (echo10/umm->echo10-xml umm1)
coll1 (mdb/save-concept {:concept-type :collection
:format "application/echo10+xml"
:metadata xml1
:extra-fields {:short-name "coll1"
:entry-title "coll1"
:entry-id "coll1"
:version-id "v1"}
:provider-id "PROV1"
:native-id "coll1"
:short-name "coll1"})
umm1 (merge umm1 (select-keys coll1 [:concept-id :revision-id]))
ummg1 (dg/granule coll1 {:granule-ur "gran1"})
xmlg1 (echo10/umm->echo10-xml ummg1)
gran1 (mdb/save-concept {:concept-type :granule
:provider-id "PROV1"
:native-id "gran1"
:format "application/echo10+xml"
:metadata xmlg1
:extra-fields {:parent-collection-id (:concept-id umm1)
:parent-entry-title "coll1"}})
valid-prov-id "PROV1"
valid-coll-id (:concept-id umm1)
invalid-prov-id "NCD4580"
invalid-coll-id "C12-PROV1"
err-msg1 (format "Provider: [%s] does not exist in the system" invalid-prov-id)
err-msg2 (format "Collection [%s] does not exist." invalid-coll-id)
{:keys [status errors] :as succ-stat} (bootstrap/bulk-index-collection
valid-prov-id valid-coll-id)
;; invalid provider and collection
{:keys [status errors] :as fail-stat1} (bootstrap/bulk-index-collection
invalid-prov-id invalid-coll-id)
;; valid provider and invalid collection
{:keys [status errors] :as fail-stat2} (bootstrap/bulk-index-collection
valid-prov-id invalid-coll-id)
;; invalid provider and valid collection
{:keys [status errors] :as fail-stat3} (bootstrap/bulk-index-collection
invalid-prov-id valid-coll-id)]
(testing "Validation of a collection supplied in a bulk-index request."
(are [expected actual] (= expected actual)
[202 nil] [(:status succ-stat) (:errors succ-stat)]
[400 [err-msg1]] [(:status fail-stat1) (:errors fail-stat1)]
[400 [err-msg2]] [(:status fail-stat2) (:errors fail-stat2)]
[400 [err-msg1]] [(:status fail-stat3) (:errors fail-stat3)])))))
;; This test is to verify that bulk index works with tombstoned tag associations
(deftest bulk-index-collections-with-tag-association-test
(s/only-with-real-database
(let [[coll1 coll2] (for [n (range 1 3)]
(d/ingest "PROV1" (dc/collection {:entry-title (str "coll" n)})))
;; Wait until collections are indexed so tags can be associated with them
_ (index/wait-until-indexed)
user1-token (e/login (s/context) "user1")
tag1-colls [coll1 coll2]
tag-key "<KEY>"
tag1 (tags/save-tag
user1-token
(tags/make-tag {:tag-key tag-key})
tag1-colls)]
(index/wait-until-indexed)
;; disassociate tag1 from coll2 and not send indexing events
(dev-sys-util/eval-in-dev-sys
`(cmr.metadata-db.config/set-publish-messages! false))
(tags/disassociate-by-query user1-token tag-key {:concept_id (:concept-id coll2)})
(dev-sys-util/eval-in-dev-sys
`(cmr.metadata-db.config/set-publish-messages! true))
(bootstrap/bulk-index-provider "PROV1")
(index/wait-until-indexed)
(testing "All tag parameters with XML references"
(is (d/refs-match? [coll1]
(search/find-refs :collection {:tag-key "tag1"})))))))
| true | (ns cmr.system-int-test.bootstrap.bulk-index-test
"Integration test for CMR bulk indexing."
(:require
[clj-time.coerce :as cr]
[clj-time.core :as t]
[clojure.java.jdbc :as j]
[clojure.test :refer :all]
[cmr.access-control.test.util :as u]
[cmr.common.date-time-parser :as p]
[cmr.common.util :as util :refer [are3]]
[cmr.mock-echo.client.echo-util :as e]
[cmr.oracle.connection :as oracle]
[cmr.system-int-test.data2.collection :as dc]
[cmr.system-int-test.data2.core :as d]
[cmr.system-int-test.data2.granule :as dg]
[cmr.system-int-test.system :as s]
[cmr.system-int-test.utils.bootstrap-util :as bootstrap]
[cmr.system-int-test.utils.dev-system-util :as dev-sys-util]
[cmr.system-int-test.utils.index-util :as index]
[cmr.system-int-test.utils.ingest-util :as ingest]
[cmr.system-int-test.utils.metadata-db-util :as mdb]
[cmr.system-int-test.utils.search-util :as search]
[cmr.system-int-test.utils.tag-util :as tags]
[cmr.transmit.access-control :as ac]
[cmr.transmit.config :as tc]
[cmr.umm.echo10.echo10-core :as echo10]))
(use-fixtures :each (join-fixtures
[(ingest/reset-fixture {"provguid1" "PROV1"})
tags/grant-all-tag-fixture]))
(defn- save-collection
"Saves a collection concept"
([n]
(save-collection n {}))
([n attributes]
(let [unique-str (str "coll" n)
umm (dc/collection {:short-name unique-str :entry-title unique-str})
xml (echo10/umm->echo10-xml umm)
coll (mdb/save-concept (merge
{:concept-type :collection
:format "application/echo10+xml"
:metadata xml
:extra-fields {:short-name unique-str
:entry-title unique-str
:entry-id unique-str
:version-id "v1"}
:revision-date "2000-01-01T10:00:00Z"
:provider-id "PROV1"
:native-id unique-str
:short-name unique-str}
attributes))]
;; Make sure the concept was saved successfully
(is (= 201 (:status coll)))
(merge umm (select-keys coll [:concept-id :revision-id])))))
(defn- save-granule
"Saves a granule concept"
([n collection]
(save-granule n collection {}))
([n collection attributes]
(let [unique-str (str "gran" n)
umm (dg/granule collection {:granule-ur unique-str})
xml (echo10/umm->echo10-xml umm)
gran (mdb/save-concept (merge
{:concept-type :granule
:provider-id "PROV1"
:native-id unique-str
:format "application/echo10+xml"
:metadata xml
:revision-date "2000-01-01T10:00:00Z"
:extra-fields {:parent-collection-id (:concept-id collection)
:parent-entry-title (:entry-title collection)
:granule-ur unique-str}}
attributes))]
;; Make sure the concept was saved successfully
(is (= 201 (:status gran)))
(merge umm (select-keys gran [:concept-id :revision-id])))))
(defn- save-tag
"Saves a tag concept"
([n]
(save-tag n {}))
([n attributes]
(let [unique-str (str "tag" n)
tag (mdb/save-concept (merge
{:concept-type :tag
:native-id unique-str
:user-id "user1"
:format "application/edn"
:metadata (str "{:tag-key \"" unique-str "\" :description \"A good tag\" :originator-id \"user1\"}")
:revision-date "2000-01-01T10:00:00Z"}
attributes))]
;; Make sure the concept was saved successfully
(is (= 201 (:status tag)))
(merge tag (select-keys tag [:concept-id :revision-id])))))
(defn- save-acl
"Saves an acl"
[n attributes target]
(let [unique-str (str "acl" n)
acl (mdb/save-concept (merge
{:concept-type :acl
:provider-id "CMR"
:native-id unique-str
:format "application/edn"
:metadata (pr-str {:group-permissions [{:user-type "guest"
:permissions ["read" "update"]}]
:system-identity {:target target}})
:revision-date "2000-01-01T10:00:00Z"}
attributes))]
;; Make sure the acl was saved successfully
(is (= 201 (:status acl)))
acl))
(defn- save-group
"Saves a group"
([n]
(save-group n {}))
([n attributes]
(let [unique-str (str "group" n)
group (mdb/save-concept (merge
{:concept-type :access-group
:provider-id "CMR"
:native-id unique-str
:format "application/edn"
:metadata "{:name \"Administrators\"
:description \"The group of users that manages the CMR.\"
:members [\"user1\" \"user2\"]}"
:revision-date "2000-01-01T10:00:00Z"}
attributes))]
;; Make sure the group was saved successfully
(is (= 201 (:status group)))
group)))
(defn- delete-concept
"Creates a tombstone for the concept in metadata-db."
[concept]
(let [tombstone (update-in concept [:revision-id] inc)]
(is (= 201 (:status (mdb/tombstone-concept tombstone))))))
(defn- normalize-search-result-item
"Returns a map with just concept-id and revision-id for the given item."
[result-item]
(-> result-item
util/map-keys->kebab-case
(select-keys [:concept-id :revision-id])))
(defn- search-results-match?
"Compare search results to expected results."
[results expected]
(let [search-items (set (map normalize-search-result-item results))
exp-items (set (map #(dissoc % :status) expected))]
(is (= exp-items search-items))))
(defn- get-last-replicated-revision-date
"Helper to get the last replicated revision date from the database."
[db]
(j/with-db-transaction
[conn db]
(->> (j/query conn ["SELECT LAST_REPLICATED_REVISION_DATE FROM REPLICATION_STATUS"])
first
:last_replicated_revision_date
(oracle/oracle-timestamp->str-time conn))))
(deftest index-system-concepts-test
(s/only-with-real-database
;; Disable message publishing so items are not indexed as part of the initial save.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! false))
(let [acl1 (save-acl 1
{:extra-fields {:acl-identity "system:token"
:target-provider-id "PROV1"}}
"TOKEN")
acl2 (save-acl 2
{:extra-fields {:acl-identity "system:group"
:target-provider-id "PROV1"}}
"GROUP")
acl3 (save-acl 3
{:extra-fields {:acl-identity "system:user"
:target-provider-id "PROV1"}}
"USER")
_ (delete-concept acl3)
group1 (save-group 1 {})
group2 (save-group 2 {})
group3 (save-group 3 {})
_ (delete-concept group2)
tag1 (save-tag 1 {})
_ (delete-concept tag1)
;; this tag has no originator-id to test a bug fix for a bug in tag processing related to missing originator-ids
tag2 (save-tag 2 {:metadata "{:tag-key \"tag2\" :description \"A good tag\"}"})
tag3 (save-tag 3 {})]
(bootstrap/bulk-index-system-concepts)
;; Force elastic data to be flushed, not actually waiting for index requests to finish
(index/wait-until-indexed)
;; ACLs
(let [response (ac/search-for-acls (u/conn-context) {} {:token (tc/echo-system-token)})
items (:items response)]
(search-results-match? items [acl1 acl2]))
;; Groups
(let [response (ac/search-for-groups (u/conn-context) {})
;; Need to filter out admin group created by fixture
items (filter #(not (= "mock-admin-group-guid" (:legacy_guid %))) (:items response))]
(search-results-match? items [group1 group3]))
(are3 [expected-tags]
(let [result-tags (update
(tags/search {})
:items
(fn [items]
(map #(select-keys % [:concept-id :revision-id]) items)))]
(tags/assert-tag-search expected-tags result-tags))
"Tags"
[tag2 tag3])
;; Re-enable message publishing.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! true)))))
;; Commented out due to requiring a database link in order to work - this job is only transitional
;; for moving to NGAP so we will remove it once we have fully transitioned.
#_(deftest index-recently-replicated-test
(s/only-with-real-database
;; Disable message publishing so items are not indexed as part of the initial save.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! false))
(let [last-replicated-datetime "3016-01-01T10:00:00Z"
coll-missed-cutoff (save-collection 1 {:revision-date "3016-01-01T09:59:40Z"})
coll-within-buffer (save-collection 2 {:revision-date "3016-01-01T09:59:41Z"})
coll-after-date (save-collection 3 {:revision-date "3016-01-02T00:00:00Z"})
gran-missed-cutoff (save-granule 1 coll-missed-cutoff {:revision-date "3016-01-01T09:59:40Z"})
gran-within-buffer (save-granule 2 coll-within-buffer {:revision-date "3016-01-01T09:59:41Z"})
gran-after-date (save-granule 3 coll-after-date {:revision-date "3016-01-02T00:00:00Z"})
tag-missed-cutoff (save-tag 1 {:revision-date "3016-01-01T09:59:40Z"})
tag-within-buffer (save-tag 2 {:revision-date "3016-01-01T09:59:41Z"})
tag-after-date (save-tag 3 {:revision-date "3016-01-02T00:00:00Z"})
acl-missed-cutoff (save-acl 1
{:revision-date "3016-01-01T09:59:40Z"
:extra-fields {:acl-identity "system:token"
:target-provider-id "PROV1"}}
"TOKEN")
acl-within-buffer (save-acl 2
{:revision-date "3016-01-01T09:59:41Z"
:extra-fields {:acl-identity "system:group"
:target-provider-id "PROV1"}}
"GROUP")
acl-after-date (save-acl 3
{:revision-date "3016-01-02T00:00:00Z"
:extra-fields {:acl-identity "system:user"
:target-provider-id "PROV1"}}
"USER")
group-missed-cutoff (save-group 1 {:revision-date "3016-01-01T09:59:40Z"})
group-within-buffer (save-group 2 {:revision-date "3016-01-01T09:59:41Z"})
group-after-date (save-group 3 {:revision-date "3016-01-02T00:00:00Z"})
db (get-in (s/context) [:system :bootstrap-db])
stmt "UPDATE REPLICATION_STATUS SET LAST_REPLICATED_REVISION_DATE = ?"]
(j/db-do-prepared db stmt [(cr/to-sql-time (p/parse-datetime last-replicated-datetime))])
(bootstrap/index-recently-replicated)
;; Force elastic data to be flushed, not actually waiting for index requests to finish
(index/wait-until-indexed)
(testing "Concepts with revision date within 20 seconds of last replicated date are indexed."
(are3 [concept-type expected]
(d/refs-match? expected (search/find-refs concept-type {}))
"Collections"
:collection [coll-within-buffer coll-after-date]
"Granules"
:granule [gran-within-buffer gran-after-date])
;; ACLs
(let [response (ac/search-for-acls (u/conn-context) {} {:token (tc/echo-system-token)})
items (:items response)]
(search-results-match? items [acl-within-buffer acl-after-date]))
;; Groups
(let [response (ac/search-for-groups (u/conn-context) {})
;; Need to filter out admin group created by fixture
items (filter #(not (= "mock-admin-group-guid" (:legacy_guid %))) (:items response))]
(search-results-match? items [group-within-buffer group-after-date]))
(are3 [expected-tags]
(let [result-tags (update
(tags/search {})
:items
(fn [items]
(map #(select-keys % [:concept-id :revision-id]) items)))]
(tags/assert-tag-search expected-tags result-tags))
"Tags"
[tag-within-buffer tag-after-date])))
(testing "When there are no concepts to index the date is not changed."
(j/db-do-prepared db stmt [(cr/to-sql-time (p/parse-datetime "3016-02-01T10:00:00.000Z"))])
(bootstrap/index-recently-replicated)
(is (= "3016-02-01T10:00:00.000Z" (get-last-replicated-revision-date db))))
(testing "Max revision dates are tracked correctly"
(testing "for provider concepts"
(let [coll (save-collection 1 {:revision-date "3016-02-02T10:59:40Z"})]
(save-granule 1 coll {:revision-date "3016-02-01T11:59:40Z"})
(save-tag 1 {:revision-date "3016-02-01T18:59:40Z"})
(bootstrap/index-recently-replicated))
(is (= "3016-02-02T10:59:40.000Z" (get-last-replicated-revision-date db))))
(testing "for system concepts"
(let [coll (save-collection 1 {:revision-date "3016-02-03T10:59:40Z"})]
(save-granule 1 coll {:revision-date "3016-03-01T11:59:40Z"})
(save-tag 1 {:revision-date "3016-03-01T12:10:47Z"})
(bootstrap/index-recently-replicated))
(is (= "3016-03-01T12:10:47.000Z" (get-last-replicated-revision-date db))))))
;; Re-enable message publishing.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! true)))
(deftest bulk-index-by-concept-id
(s/only-with-real-database
;; Disable message publishing so items are not indexed.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! false))
(let [;; saved but not indexed
coll1 (save-collection 1)
coll2 (save-collection 2 {})
colls (map :concept-id [coll1 coll2])
gran1 (save-granule 1 coll1)
gran2 (save-granule 2 coll2 {})
tag1 (save-tag 1)
tag2 (save-tag 2 {})
acl1 (save-acl 1
{:extra-fields {:acl-identity "system:token"
:target-provider-id "PROV1"}}
"TOKEN")
acl2 (save-acl 2
{:extra-fields {:acl-identity "system:group"
:target-provider-id "PROV1"}}
"GROUP")
group1 (save-group 1)
group2 (save-group 2 {})]
(bootstrap/bulk-index-concepts "PROV1" :collection colls)
(bootstrap/bulk-index-concepts "PROV1" :granule [(:concept-id gran2)])
(bootstrap/bulk-index-concepts "PROV1" :tag [(:concept-id tag1)])
;; Commented out until ACLs and groups are supported in the index by concept-id API
; (bootstrap/bulk-index-concepts "CMR" :access-group [(:concept-id group2)])
; (bootstrap/bulk-index-concepts "CMR" :acl [(:concept-id acl2)])
(index/wait-until-indexed)
(testing "Concepts are indexed."
;; Collections and granules
(are3 [concept-type expected]
(d/refs-match? expected (search/find-refs concept-type {}))
"Collections"
:collection [coll1 coll2]
"Granules"
:granule [gran2])
;; Commented out until ACLs and groups are supported in the index by concept-id API
; ;; ACLs
; (let [response (ac/search-for-acls (u/conn-context) {} {:token (tc/echo-system-token)})
; items (:items response)]
; (search-results-match? items [acl2]))
; ;; ;; Groups
; (let [response (ac/search-for-groups (u/conn-context) {})
; ;; Need to filter out admin group created by fixture
; items (filter #(not (= "mock-admin-group-guid" (:legacy_guid %))) (:items response))]
; (search-results-match? items [group2]))
(are3 [expected-tags]
(let [result-tags (update
(tags/search {})
:items
(fn [items]
(map #(select-keys % [:concept-id :revision-id]) items)))]
(tags/assert-tag-search expected-tags result-tags))
"Tags"
[tag1])))
;; Re-enable message publishing.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! true))))
(deftest bulk-delete-by-concept-id
(s/only-with-real-database
(let [coll1 (save-collection 1)
coll2 (save-collection 2 {})
coll3 (save-collection 3 {})
gran1 (save-granule 1 coll2)
gran2 (save-granule 2 coll2 {})
tag1 (save-tag 1)
tag2 (save-tag 2 {})
acl1 (save-acl 1
{:extra-fields {:acl-identity "system:token"
:target-provider-id "PROV1"}}
"TOKEN")
acl2 (save-acl 2
{:extra-fields {:acl-identity "system:group"
:target-provider-id "PROV1"}}
"GROUP")
group1 (save-group 1)
group2 (save-group 2 {})]
(bootstrap/bulk-delete-concepts "PROV1" :collection (map :concept-id [coll1 coll3]))
(bootstrap/bulk-delete-concepts "PROV1" :granule [(:concept-id gran2)])
(bootstrap/bulk-delete-concepts "PROV1" :tag [(:concept-id tag1)])
;; Commented out until ACLs and groups are supported in the delete by concept-id API
; (bootstrap/bulk-index-concepts "CMR" :access-group [(:concept-id group2)])
; (bootstrap/bulk-index-concepts "CMR" :acl [(:concept-id acl2)])
(index/wait-until-indexed)
(testing "Concepts are deleted"
;; Collections and granules
(are3 [concept-type expected]
(d/refs-match? expected (search/find-refs concept-type {}))
"Collections"
:collection [coll2]
"Granules"
:granule [gran1])
(are3 [expected-tags]
(let [result-tags (update
(tags/search {})
:items
(fn [items]
(map #(select-keys % [:concept-id :revision-id]) items)))]
(tags/assert-tag-search expected-tags result-tags))
"Tags"
[tag2])))))
(deftest bulk-index-after-date-time
(s/only-with-real-database
;; Disable message publishing so items are not indexed.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! false))
(let [;; saved but not indexed
coll1 (save-collection 1)
coll2 (save-collection 2 {:revision-date "3016-01-01T10:00:00Z"})
gran1 (save-granule 1 coll1)
gran2 (save-granule 2 coll2 {:revision-date "3016-01-01T10:00:00Z"})
tag1 (save-tag 1)
tag2 (save-tag 2 {:revision-date "3016-01-01T10:00:00Z"})
acl1 (save-acl 1
{:revision-date "2000-01-01T09:59:40Z"
:extra-fields {:acl-identity "system:token"
:target-provider-id "PROV1"}}
"TOKEN")
acl2 (save-acl 2
{:revision-date "3016-01-01T09:59:41Z"
:extra-fields {:acl-identity "system:group"
:target-provider-id "PROV1"}}
"GROUP")
group1 (save-group 1)
group2 (save-group 2 {:revision-date "3016-01-01T10:00:00Z"})]
(bootstrap/bulk-index-after-date-time "2015-01-01T12:00:00Z")
(index/wait-until-indexed)
(testing "Only concepts after date are indexed."
(are3 [concept-type expected]
(d/refs-match? expected (search/find-refs concept-type {}))
"Collections"
:collection [coll2]
"Granules"
:granule [gran2])
;; ACLs
(let [response (ac/search-for-acls (u/conn-context) {} {:token (tc/echo-system-token)})
items (:items response)]
(search-results-match? items [acl2]))
;; Groups
(let [response (ac/search-for-groups (u/conn-context) {})
;; Need to filter out admin group created by fixture
items (filter #(not (= "mock-admin-group-guid" (:legacy_guid %))) (:items response))]
(search-results-match? items [group2]))
(are3 [expected-tags]
(let [result-tags (update
(tags/search {})
:items
(fn [items]
(map #(select-keys % [:concept-id :revision-id]) items)))]
(tags/assert-tag-search expected-tags result-tags))
"Tags"
[tag2])))
;; Re-enable message publishing.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! true))))
;; This test runs bulk index with some concepts in mdb that are good, and some that are
;; deleted, and some that have not yet been deleted, but have an expired deletion date.
(deftest bulk-index-with-some-deleted
(s/only-with-real-database
;; Disable message publishing so items are not indexed as part of the initial save.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! false))
(let [;; coll1 is a regular collection that is ingested
umm1 (dc/collection {:short-name "coll1" :entry-title "coll1"})
xml1 (echo10/umm->echo10-xml umm1)
coll1 (mdb/save-concept {:concept-type :collection
:format "application/echo10+xml"
:metadata xml1
:extra-fields {:short-name "coll1"
:entry-title "coll1"
:entry-id "coll1"
:version-id "v1"}
:provider-id "PROV1"
:native-id "coll1"
:short-name "coll1"})
umm1 (merge umm1 (select-keys coll1 [:concept-id :revision-id]))
;; coll2 is a regualr collection that is ingested and will be deleted later
coll2 (d/ingest "PROV1" (dc/collection {:short-name "coll2" :entry-title "coll2"}))
;; coll3 is a collection with an expired delete time
umm3 (dc/collection {:short-name "coll3" :entry-title "coll3" :delete-time "2000-01-01T12:00:00Z"})
xml3 (echo10/umm->echo10-xml umm3)
coll3 (mdb/save-concept {:concept-type :collection
:format "application/echo10+xml"
:metadata xml3
:extra-fields {:short-name "coll3"
:entry-title "coll3"
:entry-id "coll3"
:version-id "v1"
:delete-time "2000-01-01T12:00:00Z"}
:provider-id "PROV1"
:native-id "coll3"
:short-name "coll3"})
;; gran1 is a regular granule that is ingested
ummg1 (dg/granule coll1 {:granule-ur "gran1"})
xmlg1 (echo10/umm->echo10-xml ummg1)
gran1 (mdb/save-concept {:concept-type :granule
:provider-id "PROV1"
:native-id "gran1"
:format "application/echo10+xml"
:metadata xmlg1
:extra-fields {:parent-collection-id (:concept-id umm1)
:parent-entry-title "coll1"
:granule-ur "gran1"}})
ummg1 (merge ummg1 (select-keys gran1 [:concept-id :revision-id]))
;; gran2 is a regular granule that is ingested and will be deleted later
ummg2 (dg/granule coll1 {:granule-ur "gran2"})
xmlg2 (echo10/umm->echo10-xml ummg2)
gran2 (mdb/save-concept {:concept-type :granule
:provider-id "PROV1"
:native-id "gran2"
:format "application/echo10+xml"
:metadata xmlg2
:extra-fields {:parent-collection-id (:concept-id umm1)
:parent-entry-title "coll1"
:granule-ur "gran2"}})
ummg2 (merge ummg2 (select-keys gran2 [:concept-id :revision-id]))
;; gran3 is a granule with an expired delete time
ummg3 (dg/granule coll1 {:granule-ur "gran3" :delete-time "2000-01-01T12:00:00Z"})
xmlg3 (echo10/umm->echo10-xml ummg3)
gran3 (mdb/save-concept {:concept-type :granule
:provider-id "PROV1"
:native-id "gran3"
:format "application/echo10+xml"
:metadata xmlg3
:extra-fields {:parent-collection-id (:concept-id umm1)
:parent-entry-title "coll1"
:granule-ur "gran3"}})]
;; Verify that all of the ingest requests completed successfully
(doseq [concept [coll1 coll2 coll3 gran1 gran2 gran3]] (is (= 201 (:status concept))))
;; bulk index all collections and granules
(bootstrap/bulk-index-provider "PROV1")
(index/wait-until-indexed)
(testing "Expired documents are not indexed during bulk indexing"
(are [search concept-type expected]
(d/refs-match? expected (search/find-refs concept-type search))
{:concept-id (:concept-id coll1)} :collection [umm1]
{:concept-id (:concept-id coll2)} :collection [coll2]
{:concept-id (:concept-id coll3)} :collection []
{:concept-id (:concept-id gran1)} :granule [ummg1]
{:concept-id (:concept-id gran2)} :granule [ummg2]
{:concept-id (:concept-id gran3)} :granule []))
(testing "Deleted documents get deleted during bulk indexing"
(let [coll2-tombstone {:concept-id (:concept-id coll2)
:revision-id (inc (:revision-id coll2))}
gran2-tombstone {:concept-id (:concept-id gran2)
:revision-id (inc (:revision-id gran2))}]
;; delete coll2 and gran2 in metadata-db
(mdb/tombstone-concept coll2-tombstone)
(mdb/tombstone-concept gran2-tombstone)
;; bulk index all collections and granules
(bootstrap/bulk-index-provider "PROV1")
(index/wait-until-indexed)
(are [search concept-type expected]
(d/refs-match? expected (search/find-refs concept-type search))
{:concept-id (:concept-id coll1)} :collection [umm1]
{:concept-id (:concept-id coll2)} :collection []
{:concept-id (:concept-id coll3)} :collection []
{:concept-id (:concept-id gran1)} :granule [ummg1]
{:concept-id (:concept-id gran2)} :granule []
{:concept-id (:concept-id gran3)} :granule []))))
;; Re-enable message publishing.
(dev-sys-util/eval-in-dev-sys `(cmr.metadata-db.config/set-publish-messages! true))))
;; This test verifies that the bulk indexer can run concurrently with ingest and indexing of items.
;; This test performs the following steps:
;; 1. Saves ten collections in metadata db.
;; 2. Saves three granules for each of those collections in metadata db.
;; 3. Ingests ten granules five times each in a separate thread.
;; 4. Concurrently executes a bulk index operation for the provider.
;; 5. Waits for the bulk indexing and granule ingest to complete.
;; 6. Searches for all of the saved/ingested concepts by concept-id.
;; 7. Verifies that the concepts returned by search have the expected revision ids.
(deftest bulk-index-after-ingest
(s/only-with-real-database
(let [collections (for [x (range 1 11)]
(let [umm (dc/collection {:short-name (str "short-name" x)
:entry-title (str "title" x)})
xml (echo10/umm->echo10-xml umm)
concept-map {:concept-type :collection
:format "application/echo10+xml"
:metadata xml
:extra-fields {:short-name (str "short-name" x)
:entry-title (str "title" x)
:entry-id (str "entry-id" x)
:version-id "v1"}
:provider-id "PROV1"
:native-id (str "coll" x)
:short-name (str "short-name" x)}
{:keys [concept-id revision-id]} (mdb/save-concept concept-map)]
(assoc umm :concept-id concept-id :revision-id revision-id)))
granules1 (mapcat (fn [collection]
(doall
(for [x (range 1 4)]
(let [pid (:concept-id collection)
umm (dg/granule collection)
xml (echo10/umm->echo10-xml umm)
concept-map {:concept-type :granule
:provider-id "PROV1"
:native-id (str "gran-" pid "-" x)
:extra-fields {:parent-collection-id pid
:parent-entry-title
(:entry-title collection)
:granule-ur (str "gran-" pid "-" x)}
:format "application/echo10+xml"
:metadata xml}
{:keys [concept-id revision-id]} (mdb/save-concept concept-map)]
(assoc umm :concept-id concept-id :revision-id revision-id)))))
collections)
;; granules2 and f (the future) are used to ingest ten granules five times each in
;; a separate thread to verify that bulk indexing with concurrent ingest does the right
;; thing.
granules2 (let [collection (first collections)
pid (:concept-id collection)]
(for [x (range 1 11)]
(dg/granule collection {:granule-ur (str "gran2-" pid "-" x)})))
f (future (dotimes [n 5]
(doall (map (fn [gran]
(Thread/sleep 100)
(d/ingest "PROV1" gran))
granules2))))]
(bootstrap/bulk-index-provider "PROV1")
;; force our future to complete
@f
(index/wait-until-indexed)
(testing "retrieval after bulk indexing returns the latest revision."
(doseq [collection collections]
(let [{:keys [concept-id revision-id]} collection
response (search/find-refs :collection {:concept-id concept-id})
es-revision-id (:revision-id (first (:refs response)))]
;; the latest revision should be indexed
(is (= es-revision-id revision-id))))
(doseq [granule granules1]
(let [{:keys [concept-id revision-id]} granule
response (search/find-refs :granule {:concept-id concept-id})
es-revision-id (:revision-id (first (:refs response)))]
(is (= es-revision-id revision-id) (str "Failure for granule " concept-id))))
(doseq [granule (last @f)]
(let [{:keys [concept-id]} granule
response (search/find-refs :granule {:concept-id concept-id})
es-revision-id (:revision-id (first (:refs response)))]
(is (= 5 es-revision-id) (str "Failure for granule " concept-id))))))))
(deftest invalid-provider-bulk-index-validation-test
(s/only-with-real-database
(testing "Validation of a provider supplied in a bulk-index request."
(let [{:keys [status errors]} (bootstrap/bulk-index-provider "NCD4580")]
(is (= [400 ["Provider: [NCD4580] does not exist in the system"]]
[status errors]))))))
(deftest collection-bulk-index-validation-test
(s/only-with-real-database
(let [umm1 (dc/collection {:short-name "coll1" :entry-title "coll1"})
xml1 (echo10/umm->echo10-xml umm1)
coll1 (mdb/save-concept {:concept-type :collection
:format "application/echo10+xml"
:metadata xml1
:extra-fields {:short-name "coll1"
:entry-title "coll1"
:entry-id "coll1"
:version-id "v1"}
:provider-id "PROV1"
:native-id "coll1"
:short-name "coll1"})
umm1 (merge umm1 (select-keys coll1 [:concept-id :revision-id]))
ummg1 (dg/granule coll1 {:granule-ur "gran1"})
xmlg1 (echo10/umm->echo10-xml ummg1)
gran1 (mdb/save-concept {:concept-type :granule
:provider-id "PROV1"
:native-id "gran1"
:format "application/echo10+xml"
:metadata xmlg1
:extra-fields {:parent-collection-id (:concept-id umm1)
:parent-entry-title "coll1"}})
valid-prov-id "PROV1"
valid-coll-id (:concept-id umm1)
invalid-prov-id "NCD4580"
invalid-coll-id "C12-PROV1"
err-msg1 (format "Provider: [%s] does not exist in the system" invalid-prov-id)
err-msg2 (format "Collection [%s] does not exist." invalid-coll-id)
{:keys [status errors] :as succ-stat} (bootstrap/bulk-index-collection
valid-prov-id valid-coll-id)
;; invalid provider and collection
{:keys [status errors] :as fail-stat1} (bootstrap/bulk-index-collection
invalid-prov-id invalid-coll-id)
;; valid provider and invalid collection
{:keys [status errors] :as fail-stat2} (bootstrap/bulk-index-collection
valid-prov-id invalid-coll-id)
;; invalid provider and valid collection
{:keys [status errors] :as fail-stat3} (bootstrap/bulk-index-collection
invalid-prov-id valid-coll-id)]
(testing "Validation of a collection supplied in a bulk-index request."
(are [expected actual] (= expected actual)
[202 nil] [(:status succ-stat) (:errors succ-stat)]
[400 [err-msg1]] [(:status fail-stat1) (:errors fail-stat1)]
[400 [err-msg2]] [(:status fail-stat2) (:errors fail-stat2)]
[400 [err-msg1]] [(:status fail-stat3) (:errors fail-stat3)])))))
;; This test is to verify that bulk index works with tombstoned tag associations
(deftest bulk-index-collections-with-tag-association-test
(s/only-with-real-database
(let [[coll1 coll2] (for [n (range 1 3)]
(d/ingest "PROV1" (dc/collection {:entry-title (str "coll" n)})))
;; Wait until collections are indexed so tags can be associated with them
_ (index/wait-until-indexed)
user1-token (e/login (s/context) "user1")
tag1-colls [coll1 coll2]
tag-key "PI:KEY:<KEY>END_PI"
tag1 (tags/save-tag
user1-token
(tags/make-tag {:tag-key tag-key})
tag1-colls)]
(index/wait-until-indexed)
;; disassociate tag1 from coll2 and not send indexing events
(dev-sys-util/eval-in-dev-sys
`(cmr.metadata-db.config/set-publish-messages! false))
(tags/disassociate-by-query user1-token tag-key {:concept_id (:concept-id coll2)})
(dev-sys-util/eval-in-dev-sys
`(cmr.metadata-db.config/set-publish-messages! true))
(bootstrap/bulk-index-provider "PROV1")
(index/wait-until-indexed)
(testing "All tag parameters with XML references"
(is (d/refs-match? [coll1]
(search/find-refs :collection {:tag-key "tag1"})))))))
|
[
{
"context": ".boards :as boards]))\n\n(def nubank\n {:name \"Nubank\"\n :page \"https://boards.greenhouse.io/nuba",
"end": 169,
"score": 0.9997988343238831,
"start": 163,
"tag": "NAME",
"value": "Nubank"
},
{
"context": " :enrich identity})\n\n(def paygo\n {:name \"PayGo\"\n :page \"https://paygo.gupy.io/\"\n :path ",
"end": 468,
"score": 0.9997086524963379,
"start": 463,
"tag": "NAME",
"value": "PayGo"
},
{
"context": " \"clojure\")})\n\n(def embraer\n {:name \"Embraer\"\n :page \"https://embraer.gupy.io/\"\n :pat",
"end": 850,
"score": 0.9997897744178772,
"start": 843,
"tag": "NAME",
"value": "Embraer"
},
{
"context": " \"clojure\")})\n\n(def pipo-saude\n {:name \"Pipo Saúde\"\n :page \"https://pipo-saude.breezy.hr/\"\n ",
"end": 1172,
"score": 0.9998375773429871,
"start": 1162,
"tag": "NAME",
"value": "Pipo Saúde"
},
{
"context": "jure? boolean})\n\n(def i80-seguros\n {:name \"180° Seguros\"\n :page \"https://180-seguros.breezy.hr/\"\n ",
"end": 1416,
"score": 0.9994615316390991,
"start": 1404,
"tag": "NAME",
"value": "180° Seguros"
}
] | src/clojure_empregos_brasil/companies.clj | clj-br/vagas | 23 | (ns clojure-empregos-brasil.companies
(:require [clojure.string :as string]
[clojure-empregos-brasil.boards :as boards]))
(def nubank
{:name "Nubank"
:page "https://boards.greenhouse.io/nubank"
:path [:div.opening]
:scrap boards/greenhouse
:engineer? (comp (partial = "60350") :department)
:brazil? (comp (partial = "58102") :office_id)
:clojure? boolean
:enrich identity})
(def paygo
{:name "PayGo"
:page "https://paygo.gupy.io/"
:path [:.job-list :tr]
:scrap (assoc boards/gupy :remote boolean) ;; all PayGo positions are remote
:engineer? #(= (:department %) "Tecnologia")
:brazil? boolean
:clojure? #(string/includes?
(-> % :title string/lower-case)
"clojure")})
(def embraer
{:name "Embraer"
:page "https://embraer.gupy.io/"
:path [:.job-list :tr]
:scrap boards/gupy
:engineer? #(= (:department %) "Inovação")
:brazil? :remote
:clojure? #(string/includes?
(-> % :title string/lower-case)
"clojure")})
(def pipo-saude
{:name "Pipo Saúde"
:page "https://pipo-saude.breezy.hr/"
:path [:li.position]
:scrap boards/breezy
:engineer? #(= (:department %) "Engenharia")
:brazil? boolean
:clojure? boolean})
(def i80-seguros
{:name "180° Seguros"
:page "https://180-seguros.breezy.hr/"
:path [:li.position]
:scrap boards/breezy
:engineer? #(= (:department %) "Tecnologia")
:brazil? boolean
:clojure? boolean})
| 80187 | (ns clojure-empregos-brasil.companies
(:require [clojure.string :as string]
[clojure-empregos-brasil.boards :as boards]))
(def nubank
{:name "<NAME>"
:page "https://boards.greenhouse.io/nubank"
:path [:div.opening]
:scrap boards/greenhouse
:engineer? (comp (partial = "60350") :department)
:brazil? (comp (partial = "58102") :office_id)
:clojure? boolean
:enrich identity})
(def paygo
{:name "<NAME>"
:page "https://paygo.gupy.io/"
:path [:.job-list :tr]
:scrap (assoc boards/gupy :remote boolean) ;; all PayGo positions are remote
:engineer? #(= (:department %) "Tecnologia")
:brazil? boolean
:clojure? #(string/includes?
(-> % :title string/lower-case)
"clojure")})
(def embraer
{:name "<NAME>"
:page "https://embraer.gupy.io/"
:path [:.job-list :tr]
:scrap boards/gupy
:engineer? #(= (:department %) "Inovação")
:brazil? :remote
:clojure? #(string/includes?
(-> % :title string/lower-case)
"clojure")})
(def pipo-saude
{:name "<NAME>"
:page "https://pipo-saude.breezy.hr/"
:path [:li.position]
:scrap boards/breezy
:engineer? #(= (:department %) "Engenharia")
:brazil? boolean
:clojure? boolean})
(def i80-seguros
{:name "<NAME>"
:page "https://180-seguros.breezy.hr/"
:path [:li.position]
:scrap boards/breezy
:engineer? #(= (:department %) "Tecnologia")
:brazil? boolean
:clojure? boolean})
| true | (ns clojure-empregos-brasil.companies
(:require [clojure.string :as string]
[clojure-empregos-brasil.boards :as boards]))
(def nubank
{:name "PI:NAME:<NAME>END_PI"
:page "https://boards.greenhouse.io/nubank"
:path [:div.opening]
:scrap boards/greenhouse
:engineer? (comp (partial = "60350") :department)
:brazil? (comp (partial = "58102") :office_id)
:clojure? boolean
:enrich identity})
(def paygo
{:name "PI:NAME:<NAME>END_PI"
:page "https://paygo.gupy.io/"
:path [:.job-list :tr]
:scrap (assoc boards/gupy :remote boolean) ;; all PayGo positions are remote
:engineer? #(= (:department %) "Tecnologia")
:brazil? boolean
:clojure? #(string/includes?
(-> % :title string/lower-case)
"clojure")})
(def embraer
{:name "PI:NAME:<NAME>END_PI"
:page "https://embraer.gupy.io/"
:path [:.job-list :tr]
:scrap boards/gupy
:engineer? #(= (:department %) "Inovação")
:brazil? :remote
:clojure? #(string/includes?
(-> % :title string/lower-case)
"clojure")})
(def pipo-saude
{:name "PI:NAME:<NAME>END_PI"
:page "https://pipo-saude.breezy.hr/"
:path [:li.position]
:scrap boards/breezy
:engineer? #(= (:department %) "Engenharia")
:brazil? boolean
:clojure? boolean})
(def i80-seguros
{:name "PI:NAME:<NAME>END_PI"
:page "https://180-seguros.breezy.hr/"
:path [:li.position]
:scrap boards/breezy
:engineer? #(= (:department %) "Tecnologia")
:brazil? boolean
:clojure? boolean})
|
[
{
"context": "intln \"was nil\"))\n\n(def null-person {:first-name \"John\" :last-name \"Doe\"})\n(defn fetch-person [people id",
"end": 345,
"score": 0.9998533129692078,
"start": 341,
"tag": "NAME",
"value": "John"
},
{
"context": "\n(def null-person {:first-name \"John\" :last-name \"Doe\"})\n(defn fetch-person [people id]\n (get id peopl",
"end": 362,
"score": 0.9997231364250183,
"start": 359,
"tag": "NAME",
"value": "Doe"
},
{
"context": "ing/capitalize \n (str \"Hello, \"))\n \"Hello, John\")) \n\n(defn build-person [first-name last-name]\n ",
"end": 568,
"score": 0.9994518160820007,
"start": 564,
"tag": "NAME",
"value": "John"
},
{
"context": "irst-name :last-name last-name}\n {:first-name \"John\" :last-name \"Doe\"}))\n",
"end": 721,
"score": 0.999836802482605,
"start": 717,
"tag": "NAME",
"value": "John"
},
{
"context": "me last-name}\n {:first-name \"John\" :last-name \"Doe\"}))\n",
"end": 738,
"score": 0.9997296333312988,
"start": 735,
"tag": "NAME",
"value": "Doe"
}
] | ClojureExamples/src/mbfpp/oo/nullobject/examples.clj | cycle-chen/mbfpp-code | 4 | (ns mbfpp.oo.nullobject.examples
(:require [clojure.string :as string]))
(defn example [x]
(if x
(println "wasn't nil")
(println "was nil")))
(defmulti example-mm (fn [x] (nil? x)))
(defmethod example-mm false [x] (println "wasn't nil"))
(defmethod example-mm true [x] (println "was nil"))
(def null-person {:first-name "John" :last-name "Doe"})
(defn fetch-person [people id]
(get id people null-person))
(defn person-greeting [person]
(if person
(->> (:first-name person)
string/capitalize
(str "Hello, "))
"Hello, John"))
(defn build-person [first-name last-name]
(if (and first-name last-name)
{:first-name first-name :last-name last-name}
{:first-name "John" :last-name "Doe"}))
| 40744 | (ns mbfpp.oo.nullobject.examples
(:require [clojure.string :as string]))
(defn example [x]
(if x
(println "wasn't nil")
(println "was nil")))
(defmulti example-mm (fn [x] (nil? x)))
(defmethod example-mm false [x] (println "wasn't nil"))
(defmethod example-mm true [x] (println "was nil"))
(def null-person {:first-name "<NAME>" :last-name "<NAME>"})
(defn fetch-person [people id]
(get id people null-person))
(defn person-greeting [person]
(if person
(->> (:first-name person)
string/capitalize
(str "Hello, "))
"Hello, <NAME>"))
(defn build-person [first-name last-name]
(if (and first-name last-name)
{:first-name first-name :last-name last-name}
{:first-name "<NAME>" :last-name "<NAME>"}))
| true | (ns mbfpp.oo.nullobject.examples
(:require [clojure.string :as string]))
(defn example [x]
(if x
(println "wasn't nil")
(println "was nil")))
(defmulti example-mm (fn [x] (nil? x)))
(defmethod example-mm false [x] (println "wasn't nil"))
(defmethod example-mm true [x] (println "was nil"))
(def null-person {:first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"})
(defn fetch-person [people id]
(get id people null-person))
(defn person-greeting [person]
(if person
(->> (:first-name person)
string/capitalize
(str "Hello, "))
"Hello, PI:NAME:<NAME>END_PI"))
(defn build-person [first-name last-name]
(if (and first-name last-name)
{:first-name first-name :last-name last-name}
{:first-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"}))
|
[
{
"context": "nfig {:ssl-key \"./test-resources/ssl/private_keys/broker.example.com.pem\"\n :ssl-cert \"./test-resources/",
"end": 1573,
"score": 0.8715385794639587,
"start": 1551,
"tag": "KEY",
"value": "broker.example.com.pem"
},
{
"context": " :message_type \"http://puppetlabs.com/kennylogginsschema\"}))]\n (is (= false (session-ass",
"end": 8154,
"score": 0.7761251926422119,
"start": 8149,
"tag": "USERNAME",
"value": "kenny"
}
] | test/unit/puppetlabs/pcp/broker/core_test.clj | rileynewton/pcp-broker | 6 | (ns puppetlabs.pcp.broker.core-test
(:require [clojure.test :refer :all]
[metrics.core]
[puppetlabs.pcp.testutils :refer [dotestseq]]
[puppetlabs.pcp.broker.shared :refer [Broker]]
[puppetlabs.pcp.broker.core :refer :all]
[puppetlabs.pcp.broker.connection :as connection :refer [Codec]]
[puppetlabs.pcp.broker.websocket :refer [ws->uri ws->common-name]]
[puppetlabs.pcp.broker.message :as message]
[puppetlabs.pcp.broker.shared-test :refer [mock-uri mock-ws->uri make-test-broker]]
[puppetlabs.trapperkeeper.services.webserver.jetty9-core :as jetty9-core]
[puppetlabs.trapperkeeper.services.webserver.jetty9-config :as jetty9-config]
[schema.core :as s]
[slingshot.test])
(:import [puppetlabs.pcp.broker.connection Connection]
[com.puppetlabs.trapperkeeper.services.webserver.jetty9.utils InternalSslContextFactory]))
(s/def identity-codec :- Codec
{:encode identity
:decode identity})
(def dummy-connection
(connection/make-connection :dummy-ws message/v2-codec mock-uri false))
(s/defn make-mock-ssl-context-factory :- InternalSslContextFactory
"Return an instance of the SslContextFactory with only a minimal configuration
of the key & trust stores. If the specified `certificate-chain` is not nil it is
included with the PrivateKey entry in the factory's key store."
[certificate-chain :- (s/maybe s/Str)]
(let [pem-config {:ssl-key "./test-resources/ssl/private_keys/broker.example.com.pem"
:ssl-cert "./test-resources/ssl/certs/broker.example.com.pem"
:ssl-ca-cert "./test-resources/ssl/certs/ca.pem"}
pem-config (if (nil? certificate-chain)
pem-config
(assoc pem-config :ssl-cert-chain certificate-chain))
keystore-config (jetty9-config/pem-ssl-config->keystore-ssl-config pem-config)]
(doto (InternalSslContextFactory.)
(.setKeyStore (:keystore keystore-config))
(.setKeyStorePassword (:key-password keystore-config))
(.setTrustStore (:truststore keystore-config)))))
(s/defn make-mock-webserver-context :- jetty9-core/ServerContext
"Return a mock webserver context including the specfied `ssl-context-factory`."
[ssl-context-factory :- InternalSslContextFactory]
{:server nil
:handlers (org.eclipse.jetty.server.handler.ContextHandlerCollection.)
:state (atom {:mbean-container nil
:overrides-read-by-webserver true
:overrides nil
:endpoints {}
:ssl-context-factory ssl-context-factory})})
(deftest get-webserver-cn-test
(testing "It returns the correct cn"
(let [cn (-> nil
make-mock-ssl-context-factory
make-mock-webserver-context
get-webserver-cn)]
(is (= "broker.example.com" cn))))
(testing "It returns the correct cn from a certificate chain"
(let [cn (-> "./test-resources/ssl/certs/broker-chain.example.com.pem"
make-mock-ssl-context-factory
make-mock-webserver-context
get-webserver-cn)]
(is (= "broker.example.com" cn))))
(testing "It returns nil if anything goes wrong"
(is (nil? (-> (InternalSslContextFactory.)
make-mock-webserver-context
get-webserver-cn)))))
(deftest add-connection-test
(testing "It should add a connection to the connection map"
(with-redefs [ws->uri mock-ws->uri]
(let [broker (make-test-broker)]
(add-connection! broker (connection/make-connection :dummy-ws identity-codec mock-uri false))
(is (s/validate Connection (-> broker :database deref :inventory (get mock-uri))))))))
(deftest remove-connecton-test
(testing "It should remove a connection from the inventory map"
(with-redefs [ws->uri mock-ws->uri]
(let [broker (make-test-broker)
connection (connection/make-connection :dummy-ws identity-codec mock-uri false)]
(swap! (:database broker) update :inventory assoc mock-uri connection)
(is (not= {} (-> broker :database deref :inventory)))
(remove-connection! broker mock-uri)
(is (= {} (-> broker :database deref :inventory)))))))
(deftest expire-connection-test
(testing "It should expire connections in the inventory"
(with-redefs [ws->uri mock-ws->uri]
(let [broker (make-test-broker)
connection (connection/make-connection :dummy-ws identity-codec mock-uri false)]
(add-connection! broker connection)
(expire-ssl-connections broker)
(= true (-> broker :database deref :inventory (get mock-uri) :expired))))))
(deftest close-expired-connection-test
(testing "It should close expired connections in the inventory after :expired-conn-throttle time"
(let [closed (promise)]
(with-redefs [ws->uri mock-ws->uri
puppetlabs.experimental.websockets.client/close! (fn [& args] (deliver closed true))]
(let [broker (assoc (make-test-broker) :expired-conn-throttle 1000)
connection (connection/make-connection :dummy-ws identity-codec mock-uri false)]
(add-connection! broker connection)
(expire-ssl-connections broker)
(future (close-expired-connections! broker))
(Thread/sleep 100)
(is (not (realized? closed)))
(is (true? (deref closed 1000 false))))))))
(deftest make-ring-request-test
(testing "it should return a ring request - one target"
(let [message (message/make-message
{:message_type "example1"
:sender "pcp://example01.example.com/agent"
:target "pcp://example02.example.com/agent"})]
(is (= {:uri "/pcp-broker/send"
:request-method :post
:remote-addr ""
:form-params {}
:query-params {"sender" "pcp://example01.example.com/agent"
"target" "pcp://example02.example.com/agent"
"message_type" "example1"}
:params {"sender" "pcp://example01.example.com/agent"
"target" "pcp://example02.example.com/agent"
"message_type" "example1"}}
(make-ring-request message nil))))))
(defn yes-authorization-check [r] {:authorized true
:message ""
:request r})
(defn no-authorization-check [r] {:authorized false
:message "Danger Zone"
:request r})
(deftest authorized?-test
(let [yes-broker (assoc (make-test-broker) :authorization-check yes-authorization-check)
no-broker (assoc (make-test-broker) :authorization-check no-authorization-check)
message (message/make-message
{:message_type "example1"
:sender "pcp://example01.example.com/agent"
:target "pcp://example02.example.com/agent"})]
(is (= true (authorized? yes-broker message nil)))
(is (= false (authorized? yes-broker (assoc message :message_type "no\u0000good") nil)))
(is (= false (authorized? yes-broker (assoc message :target "pcp://bad/\u0000target") nil)))
(is (= false (authorized? no-broker message nil)))))
(deftest session-association-message?-test
(testing "It returns true when passed a sessions association message"
(let [message (message/make-message
{:target "pcp:///server"
:message_type "http://puppetlabs.com/associate_request"})]
(is (= true (session-association-request? message)))))
(testing "It returns false when passed a message of an unknown type"
(let [message (-> (message/make-message
{:target "pcp:///server"
:message_type "http://puppetlabs.com/kennylogginsschema"}))]
(is (= false (session-association-request? message)))))
(testing "It returns false when passed a message not aimed to the server target"
(let [message (-> (message/make-message
{:target "pcp://other/server"
:message_type "http://puppetlabs.com/associate_request"}))]
(is (= false (session-association-request? message))))))
(deftest process-associate-request!-test
(let [closed (atom (promise))]
(with-redefs [puppetlabs.experimental.websockets.client/close! (fn [& args] (deliver @closed args))
puppetlabs.experimental.websockets.client/send! (constantly false)
puppetlabs.pcp.broker.websocket/ws->client-type (fn [_] "controller")
ws->uri (fn [_] "pcp://localhost/controller")]
(let [message (-> (message/make-message
{:sender "pcp://localhost/controller"
:message_type "http://puppetlabs.com/login_message"}))]
(testing "It should return an associated Connection if there's no reason to deny association"
(reset! closed (promise))
(let [broker (make-test-broker)
connection (connection/make-connection :dummy-ws identity-codec mock-uri false)
_ (add-connection! broker connection)
connection-uri (:uri (process-associate-request! broker message connection))]
(is (not (realized? @closed)))
(is (= "pcp://localhost/controller" connection-uri))))))))
(deftest process-inventory-request-test
(with-redefs [ws->uri mock-ws->uri])
(let [broker (make-test-broker)
message (message/make-message
{:sender "pcp://test.example.com/test"
:data {:query ["pcp://*/*"]}})
connection (connection/make-connection :dummy-ws identity-codec mock-uri false)
accepted (atom nil)]
(with-redefs
[puppetlabs.pcp.broker.shared/deliver-server-message (fn [_ message _]
(reset! accepted message))]
(let [outcome (process-inventory-request broker message connection)]
(is (nil? outcome))
(is (= [] (:uris (:data @accepted))))))))
(deftest process-server-message!-test
(with-redefs [ws->uri mock-ws->uri]
(let [broker (make-test-broker)
message (message/make-message
{:message_type "http://puppetlabs.com/associate_request"})
connection (connection/make-connection :dummy-ws identity-codec mock-uri false)
associate-request (atom nil)]
(with-redefs
[puppetlabs.pcp.broker.core/process-associate-request! (fn [_ message connection]
(reset! associate-request message)
connection)]
(process-server-message! broker message connection)
(is (not= nil @associate-request))))))
(deftest authenticated?-test
(with-redefs [ws->uri mock-ws->uri]
(let [message (message/make-message
{:sender "pcp://lolcathost/agent"})]
(testing "simple match"
(with-redefs [ws->common-name (fn [_] "lolcathost")]
(is (authenticated? message dummy-connection))))
(testing "simple mismatch"
(with-redefs [ws->common-name (fn [_] "remotecat")]
(is (not (authenticated? message dummy-connection)))))
(testing "accidental regex collisions"
(with-redefs [ws->common-name (fn [_] "lol.athost")]
(is (not (authenticated? message dummy-connection))))))))
(defn make-valid-ring-request
[message _]
(let [{:keys [sender target message_type]} message
params {"sender" sender
"target" target
"message_type" message_type}]
{:uri "/pcp-broker/send"
:request-method :post
:remote-addr ""
:form-params {}
:query-params params
:params params}))
(deftest validate-message-test
(with-redefs [ws->uri mock-ws->uri
ws->common-name (fn [_] "localpost")]
(testing "correctly marks not authenticated messages"
(let [broker (make-test-broker)
msg (message/make-message
{:sender "pcp://groceryshop/office"
:message_type "http://puppetlabs.com/associate_request"})
is-association-request true]
(is (= :not-authenticated
(validate-message broker msg dummy-connection is-association-request)))))
(with-redefs [puppetlabs.pcp.broker.core/make-ring-request make-valid-ring-request]
(testing "correctly marks not authorized messages"
(let [no-broker (assoc (make-test-broker) :authorization-check no-authorization-check)
msg (message/make-message
{:sender "pcp://localpost/exploit"
:message_type "http://puppetlabs.com/associate_request"})
is-association-request true]
(is (= :not-authorized
(validate-message no-broker msg dummy-connection is-association-request)))))
(testing "marks multicast messages as unsupported"
(let [yes-broker (assoc (make-test-broker)
:authorization-check yes-authorization-check)
msg (message/make-message
{:sender "pcp://localpost/gbp"
:message_type "http://puppetlabs.com/associate_request"})
is-association-request true]
(with-redefs [puppetlabs.pcp.broker.message/multicast-message? (fn [_] true)]
(is (= :multicast-unsupported
(validate-message yes-broker msg dummy-connection is-association-request))))))
(testing "marks expired messages as to be processed"
(let [yes-broker (assoc (make-test-broker)
:authorization-check yes-authorization-check)
msg (message/make-message
{:sender "pcp://localpost/gbp"
:message_type "http://puppetlabs.com/associate_request"})
is-association-request true]
(is (= :to-be-processed
(validate-message yes-broker msg dummy-connection is-association-request)))))
(testing "correctly marks messages to be processed"
(let [yes-broker (assoc (make-test-broker) :authorization-check yes-authorization-check)
msg (message/make-message
{:sender "pcp://localpost/opera"
:message_type "http://puppetlabs.com/associate_request"})
is-association-request true]
(is (= :to-be-processed
(validate-message yes-broker msg dummy-connection is-association-request))))))))
(deftest process-message-test
(with-redefs [puppetlabs.pcp.broker.core/make-ring-request make-valid-ring-request
puppetlabs.pcp.broker.shared/get-connection (fn [_ _] dummy-connection)
ws->uri mock-ws->uri
ws->common-name (fn [_] "host_a")]
(testing "delivers message in case of expired msg (not associate_session)"
(let [broker (assoc (make-test-broker)
:authorization-check yes-authorization-check)
called-accept-message (atom false)
msg (-> (message/make-message
{:sender "pcp://host_a/entity"
:message_type "some_kinda_love"
:target "pcp://host_b/entity"}))]
(swap! (:database broker) update :inventory assoc "pcp://host_a/entity" dummy-connection)
(with-redefs [puppetlabs.pcp.broker.shared/deliver-message
(fn [_ _ _] (reset! called-accept-message true) nil)]
(let [outcome (process-message! broker (message/v2-encode msg) :dummy-ws)]
(is @called-accept-message)
(is (nil? outcome))))))
(testing "sends an error message and returns nil in case of authentication failure"
(let [broker (make-test-broker)
error-message-description (atom nil)
msg (-> (message/make-message
{:sender "pcp://popgroup/entity"
:message_type "some_kinda_hate"
:target "pcp://gangoffour/entity"}))]
(with-redefs [puppetlabs.pcp.broker.shared/send-error-message
(fn [_ description _] (reset! error-message-description description) nil)]
(let [outcome (process-message! broker (message/v2-encode msg) :dummy-ws)]
(is (= "Message not authenticated." @error-message-description))
(is (nil? outcome))))))
(testing "sends an error message and returns nil in case of authorization failure"
(let [broker (assoc (make-test-broker)
:authorization-check no-authorization-check)
error-message-description (atom nil)
msg (message/make-message
{:sender "pcp://host_a/entity"
:message_type "sexbeat"
:target "pcp://fourtet/entity"})]
(with-redefs [puppetlabs.pcp.broker.shared/send-error-message
(fn [_ description _]
(reset! error-message-description description) nil)]
(let [outcome (process-message! broker (message/v2-encode msg) :dummy-ws)]
(is (= "Message not authorized." @error-message-description))
(is (nil? outcome))))))
(testing "process an authorized message sent to broker"
(let [broker (assoc (make-test-broker)
:authorization-check yes-authorization-check)
processed-server-message (atom false)
msg (message/make-message
{:sender "pcp://host_a/entity"
:message_type "jackonfire"
:target "pcp:///server"})]
(with-redefs [puppetlabs.pcp.broker.core/process-server-message!
(fn [_ _ _] (reset! processed-server-message true) nil)]
(let [outcome (process-message! broker (message/v2-encode msg) :dummy-ws)]
(is @processed-server-message)
(is (nil? outcome))))))
(testing "sends an error message and returns nil in case of a multicast message"
(let [broker (assoc (make-test-broker)
:authorization-check yes-authorization-check)
error-message-description (atom nil)
msg (message/make-message
{:sender "pcp://host_a/entity"
:message_type "ether"
:target "pcp://wire/*"})]
(with-redefs [puppetlabs.pcp.broker.shared/send-error-message
(fn [_ description _] (reset! error-message-description description) nil)]
(let [outcome (process-message! broker (message/v2-encode msg) :dummy-ws)]
(is (= "Multiple recipients no longer supported." @error-message-description))
(is (nil? outcome))))))
(testing "delivers an authorized message"
(let [broker (assoc (make-test-broker)
:authorization-check yes-authorization-check)
accepted-message-for-delivery (atom false)
msg (message/make-message
{:sender "pcp://host_a/entity"
:message_type "ether"
:target "pcp://wire/entity"})]
(with-redefs [puppetlabs.pcp.broker.shared/deliver-message
(fn [_ _ _] (reset! accepted-message-for-delivery true) nil)]
(let [outcome (process-message! broker (message/v2-encode msg) :dummy-ws)]
(is @accepted-message-for-delivery)
(is (nil? outcome))))))))
(deftest codec-roundtrip-test
(with-redefs [puppetlabs.pcp.broker.core/make-ring-request make-valid-ring-request
ws->uri mock-ws->uri
ws->common-name (fn [_] "gangoffour")]
(let [broker (assoc (make-test-broker)
:authorization-check yes-authorization-check)
msg (message/make-message
{:sender "pcp://gangoffour/entity"
:message_type "ether"
:target "pcp://gangoffour/entity"})]
(testing "v1-codec survives roundtrip"
(let [sent-message (atom nil)
connection (connection/make-connection :dummy-ws message/v1-codec mock-uri false)]
(with-redefs [puppetlabs.pcp.broker.shared/get-connection
(fn [_ _] connection)
puppetlabs.experimental.websockets.client/send!
(fn [_ message] (reset! sent-message message))]
(let [outcome (process-message! broker (message/v1-encode msg) :dummy-ws)]
(is (= msg (message/v1-decode @sent-message)))
(is (nil? outcome))))))
(testing "v2-codec survives roundtrip"
(let [sent-message (atom nil)
connection (connection/make-connection :dummy-ws message/v2-codec mock-uri false)]
(with-redefs [puppetlabs.pcp.broker.shared/get-connection
(fn [_ _] connection)
puppetlabs.experimental.websockets.client/send!
(fn [_ message] (reset! sent-message message))]
(let [outcome (process-message! broker (message/v2-encode msg) :dummy-ws)]
(is (= msg (message/v2-decode @sent-message)))
(is (nil? outcome)))))))))
(deftest initiate-controllers-test
(let [is-connecting (promise)]
(with-redefs [puppetlabs.pcp.client/connect (fn [params handlers] (deliver is-connecting true) :client)
ws->uri mock-ws->uri]
(let [broker (assoc (make-test-broker)
:authorization-check yes-authorization-check)
ssl-context-factory (make-mock-ssl-context-factory nil)
_ (.start ssl-context-factory)
ssl-context (.getSslContext ssl-context-factory)
_ (.stop ssl-context-factory)
clients (initiate-controller-connections broker ssl-context ["wss://foo.com/v1"] #{} 100)
client (get clients "pcp://foo.com/server")]
(is (= 1 (count clients)))
(is client)
(is (deref is-connecting 1000 nil)
(is (= :client (:websocket client))
(is (= "pcp://foo.com/server" (:uri client)))))))))
| 56938 | (ns puppetlabs.pcp.broker.core-test
(:require [clojure.test :refer :all]
[metrics.core]
[puppetlabs.pcp.testutils :refer [dotestseq]]
[puppetlabs.pcp.broker.shared :refer [Broker]]
[puppetlabs.pcp.broker.core :refer :all]
[puppetlabs.pcp.broker.connection :as connection :refer [Codec]]
[puppetlabs.pcp.broker.websocket :refer [ws->uri ws->common-name]]
[puppetlabs.pcp.broker.message :as message]
[puppetlabs.pcp.broker.shared-test :refer [mock-uri mock-ws->uri make-test-broker]]
[puppetlabs.trapperkeeper.services.webserver.jetty9-core :as jetty9-core]
[puppetlabs.trapperkeeper.services.webserver.jetty9-config :as jetty9-config]
[schema.core :as s]
[slingshot.test])
(:import [puppetlabs.pcp.broker.connection Connection]
[com.puppetlabs.trapperkeeper.services.webserver.jetty9.utils InternalSslContextFactory]))
(s/def identity-codec :- Codec
{:encode identity
:decode identity})
(def dummy-connection
(connection/make-connection :dummy-ws message/v2-codec mock-uri false))
(s/defn make-mock-ssl-context-factory :- InternalSslContextFactory
"Return an instance of the SslContextFactory with only a minimal configuration
of the key & trust stores. If the specified `certificate-chain` is not nil it is
included with the PrivateKey entry in the factory's key store."
[certificate-chain :- (s/maybe s/Str)]
(let [pem-config {:ssl-key "./test-resources/ssl/private_keys/<KEY>"
:ssl-cert "./test-resources/ssl/certs/broker.example.com.pem"
:ssl-ca-cert "./test-resources/ssl/certs/ca.pem"}
pem-config (if (nil? certificate-chain)
pem-config
(assoc pem-config :ssl-cert-chain certificate-chain))
keystore-config (jetty9-config/pem-ssl-config->keystore-ssl-config pem-config)]
(doto (InternalSslContextFactory.)
(.setKeyStore (:keystore keystore-config))
(.setKeyStorePassword (:key-password keystore-config))
(.setTrustStore (:truststore keystore-config)))))
(s/defn make-mock-webserver-context :- jetty9-core/ServerContext
"Return a mock webserver context including the specfied `ssl-context-factory`."
[ssl-context-factory :- InternalSslContextFactory]
{:server nil
:handlers (org.eclipse.jetty.server.handler.ContextHandlerCollection.)
:state (atom {:mbean-container nil
:overrides-read-by-webserver true
:overrides nil
:endpoints {}
:ssl-context-factory ssl-context-factory})})
(deftest get-webserver-cn-test
(testing "It returns the correct cn"
(let [cn (-> nil
make-mock-ssl-context-factory
make-mock-webserver-context
get-webserver-cn)]
(is (= "broker.example.com" cn))))
(testing "It returns the correct cn from a certificate chain"
(let [cn (-> "./test-resources/ssl/certs/broker-chain.example.com.pem"
make-mock-ssl-context-factory
make-mock-webserver-context
get-webserver-cn)]
(is (= "broker.example.com" cn))))
(testing "It returns nil if anything goes wrong"
(is (nil? (-> (InternalSslContextFactory.)
make-mock-webserver-context
get-webserver-cn)))))
(deftest add-connection-test
(testing "It should add a connection to the connection map"
(with-redefs [ws->uri mock-ws->uri]
(let [broker (make-test-broker)]
(add-connection! broker (connection/make-connection :dummy-ws identity-codec mock-uri false))
(is (s/validate Connection (-> broker :database deref :inventory (get mock-uri))))))))
(deftest remove-connecton-test
(testing "It should remove a connection from the inventory map"
(with-redefs [ws->uri mock-ws->uri]
(let [broker (make-test-broker)
connection (connection/make-connection :dummy-ws identity-codec mock-uri false)]
(swap! (:database broker) update :inventory assoc mock-uri connection)
(is (not= {} (-> broker :database deref :inventory)))
(remove-connection! broker mock-uri)
(is (= {} (-> broker :database deref :inventory)))))))
(deftest expire-connection-test
(testing "It should expire connections in the inventory"
(with-redefs [ws->uri mock-ws->uri]
(let [broker (make-test-broker)
connection (connection/make-connection :dummy-ws identity-codec mock-uri false)]
(add-connection! broker connection)
(expire-ssl-connections broker)
(= true (-> broker :database deref :inventory (get mock-uri) :expired))))))
(deftest close-expired-connection-test
(testing "It should close expired connections in the inventory after :expired-conn-throttle time"
(let [closed (promise)]
(with-redefs [ws->uri mock-ws->uri
puppetlabs.experimental.websockets.client/close! (fn [& args] (deliver closed true))]
(let [broker (assoc (make-test-broker) :expired-conn-throttle 1000)
connection (connection/make-connection :dummy-ws identity-codec mock-uri false)]
(add-connection! broker connection)
(expire-ssl-connections broker)
(future (close-expired-connections! broker))
(Thread/sleep 100)
(is (not (realized? closed)))
(is (true? (deref closed 1000 false))))))))
(deftest make-ring-request-test
(testing "it should return a ring request - one target"
(let [message (message/make-message
{:message_type "example1"
:sender "pcp://example01.example.com/agent"
:target "pcp://example02.example.com/agent"})]
(is (= {:uri "/pcp-broker/send"
:request-method :post
:remote-addr ""
:form-params {}
:query-params {"sender" "pcp://example01.example.com/agent"
"target" "pcp://example02.example.com/agent"
"message_type" "example1"}
:params {"sender" "pcp://example01.example.com/agent"
"target" "pcp://example02.example.com/agent"
"message_type" "example1"}}
(make-ring-request message nil))))))
(defn yes-authorization-check [r] {:authorized true
:message ""
:request r})
(defn no-authorization-check [r] {:authorized false
:message "Danger Zone"
:request r})
(deftest authorized?-test
(let [yes-broker (assoc (make-test-broker) :authorization-check yes-authorization-check)
no-broker (assoc (make-test-broker) :authorization-check no-authorization-check)
message (message/make-message
{:message_type "example1"
:sender "pcp://example01.example.com/agent"
:target "pcp://example02.example.com/agent"})]
(is (= true (authorized? yes-broker message nil)))
(is (= false (authorized? yes-broker (assoc message :message_type "no\u0000good") nil)))
(is (= false (authorized? yes-broker (assoc message :target "pcp://bad/\u0000target") nil)))
(is (= false (authorized? no-broker message nil)))))
(deftest session-association-message?-test
(testing "It returns true when passed a sessions association message"
(let [message (message/make-message
{:target "pcp:///server"
:message_type "http://puppetlabs.com/associate_request"})]
(is (= true (session-association-request? message)))))
(testing "It returns false when passed a message of an unknown type"
(let [message (-> (message/make-message
{:target "pcp:///server"
:message_type "http://puppetlabs.com/kennylogginsschema"}))]
(is (= false (session-association-request? message)))))
(testing "It returns false when passed a message not aimed to the server target"
(let [message (-> (message/make-message
{:target "pcp://other/server"
:message_type "http://puppetlabs.com/associate_request"}))]
(is (= false (session-association-request? message))))))
(deftest process-associate-request!-test
(let [closed (atom (promise))]
(with-redefs [puppetlabs.experimental.websockets.client/close! (fn [& args] (deliver @closed args))
puppetlabs.experimental.websockets.client/send! (constantly false)
puppetlabs.pcp.broker.websocket/ws->client-type (fn [_] "controller")
ws->uri (fn [_] "pcp://localhost/controller")]
(let [message (-> (message/make-message
{:sender "pcp://localhost/controller"
:message_type "http://puppetlabs.com/login_message"}))]
(testing "It should return an associated Connection if there's no reason to deny association"
(reset! closed (promise))
(let [broker (make-test-broker)
connection (connection/make-connection :dummy-ws identity-codec mock-uri false)
_ (add-connection! broker connection)
connection-uri (:uri (process-associate-request! broker message connection))]
(is (not (realized? @closed)))
(is (= "pcp://localhost/controller" connection-uri))))))))
(deftest process-inventory-request-test
(with-redefs [ws->uri mock-ws->uri])
(let [broker (make-test-broker)
message (message/make-message
{:sender "pcp://test.example.com/test"
:data {:query ["pcp://*/*"]}})
connection (connection/make-connection :dummy-ws identity-codec mock-uri false)
accepted (atom nil)]
(with-redefs
[puppetlabs.pcp.broker.shared/deliver-server-message (fn [_ message _]
(reset! accepted message))]
(let [outcome (process-inventory-request broker message connection)]
(is (nil? outcome))
(is (= [] (:uris (:data @accepted))))))))
(deftest process-server-message!-test
(with-redefs [ws->uri mock-ws->uri]
(let [broker (make-test-broker)
message (message/make-message
{:message_type "http://puppetlabs.com/associate_request"})
connection (connection/make-connection :dummy-ws identity-codec mock-uri false)
associate-request (atom nil)]
(with-redefs
[puppetlabs.pcp.broker.core/process-associate-request! (fn [_ message connection]
(reset! associate-request message)
connection)]
(process-server-message! broker message connection)
(is (not= nil @associate-request))))))
(deftest authenticated?-test
(with-redefs [ws->uri mock-ws->uri]
(let [message (message/make-message
{:sender "pcp://lolcathost/agent"})]
(testing "simple match"
(with-redefs [ws->common-name (fn [_] "lolcathost")]
(is (authenticated? message dummy-connection))))
(testing "simple mismatch"
(with-redefs [ws->common-name (fn [_] "remotecat")]
(is (not (authenticated? message dummy-connection)))))
(testing "accidental regex collisions"
(with-redefs [ws->common-name (fn [_] "lol.athost")]
(is (not (authenticated? message dummy-connection))))))))
(defn make-valid-ring-request
[message _]
(let [{:keys [sender target message_type]} message
params {"sender" sender
"target" target
"message_type" message_type}]
{:uri "/pcp-broker/send"
:request-method :post
:remote-addr ""
:form-params {}
:query-params params
:params params}))
(deftest validate-message-test
(with-redefs [ws->uri mock-ws->uri
ws->common-name (fn [_] "localpost")]
(testing "correctly marks not authenticated messages"
(let [broker (make-test-broker)
msg (message/make-message
{:sender "pcp://groceryshop/office"
:message_type "http://puppetlabs.com/associate_request"})
is-association-request true]
(is (= :not-authenticated
(validate-message broker msg dummy-connection is-association-request)))))
(with-redefs [puppetlabs.pcp.broker.core/make-ring-request make-valid-ring-request]
(testing "correctly marks not authorized messages"
(let [no-broker (assoc (make-test-broker) :authorization-check no-authorization-check)
msg (message/make-message
{:sender "pcp://localpost/exploit"
:message_type "http://puppetlabs.com/associate_request"})
is-association-request true]
(is (= :not-authorized
(validate-message no-broker msg dummy-connection is-association-request)))))
(testing "marks multicast messages as unsupported"
(let [yes-broker (assoc (make-test-broker)
:authorization-check yes-authorization-check)
msg (message/make-message
{:sender "pcp://localpost/gbp"
:message_type "http://puppetlabs.com/associate_request"})
is-association-request true]
(with-redefs [puppetlabs.pcp.broker.message/multicast-message? (fn [_] true)]
(is (= :multicast-unsupported
(validate-message yes-broker msg dummy-connection is-association-request))))))
(testing "marks expired messages as to be processed"
(let [yes-broker (assoc (make-test-broker)
:authorization-check yes-authorization-check)
msg (message/make-message
{:sender "pcp://localpost/gbp"
:message_type "http://puppetlabs.com/associate_request"})
is-association-request true]
(is (= :to-be-processed
(validate-message yes-broker msg dummy-connection is-association-request)))))
(testing "correctly marks messages to be processed"
(let [yes-broker (assoc (make-test-broker) :authorization-check yes-authorization-check)
msg (message/make-message
{:sender "pcp://localpost/opera"
:message_type "http://puppetlabs.com/associate_request"})
is-association-request true]
(is (= :to-be-processed
(validate-message yes-broker msg dummy-connection is-association-request))))))))
(deftest process-message-test
(with-redefs [puppetlabs.pcp.broker.core/make-ring-request make-valid-ring-request
puppetlabs.pcp.broker.shared/get-connection (fn [_ _] dummy-connection)
ws->uri mock-ws->uri
ws->common-name (fn [_] "host_a")]
(testing "delivers message in case of expired msg (not associate_session)"
(let [broker (assoc (make-test-broker)
:authorization-check yes-authorization-check)
called-accept-message (atom false)
msg (-> (message/make-message
{:sender "pcp://host_a/entity"
:message_type "some_kinda_love"
:target "pcp://host_b/entity"}))]
(swap! (:database broker) update :inventory assoc "pcp://host_a/entity" dummy-connection)
(with-redefs [puppetlabs.pcp.broker.shared/deliver-message
(fn [_ _ _] (reset! called-accept-message true) nil)]
(let [outcome (process-message! broker (message/v2-encode msg) :dummy-ws)]
(is @called-accept-message)
(is (nil? outcome))))))
(testing "sends an error message and returns nil in case of authentication failure"
(let [broker (make-test-broker)
error-message-description (atom nil)
msg (-> (message/make-message
{:sender "pcp://popgroup/entity"
:message_type "some_kinda_hate"
:target "pcp://gangoffour/entity"}))]
(with-redefs [puppetlabs.pcp.broker.shared/send-error-message
(fn [_ description _] (reset! error-message-description description) nil)]
(let [outcome (process-message! broker (message/v2-encode msg) :dummy-ws)]
(is (= "Message not authenticated." @error-message-description))
(is (nil? outcome))))))
(testing "sends an error message and returns nil in case of authorization failure"
(let [broker (assoc (make-test-broker)
:authorization-check no-authorization-check)
error-message-description (atom nil)
msg (message/make-message
{:sender "pcp://host_a/entity"
:message_type "sexbeat"
:target "pcp://fourtet/entity"})]
(with-redefs [puppetlabs.pcp.broker.shared/send-error-message
(fn [_ description _]
(reset! error-message-description description) nil)]
(let [outcome (process-message! broker (message/v2-encode msg) :dummy-ws)]
(is (= "Message not authorized." @error-message-description))
(is (nil? outcome))))))
(testing "process an authorized message sent to broker"
(let [broker (assoc (make-test-broker)
:authorization-check yes-authorization-check)
processed-server-message (atom false)
msg (message/make-message
{:sender "pcp://host_a/entity"
:message_type "jackonfire"
:target "pcp:///server"})]
(with-redefs [puppetlabs.pcp.broker.core/process-server-message!
(fn [_ _ _] (reset! processed-server-message true) nil)]
(let [outcome (process-message! broker (message/v2-encode msg) :dummy-ws)]
(is @processed-server-message)
(is (nil? outcome))))))
(testing "sends an error message and returns nil in case of a multicast message"
(let [broker (assoc (make-test-broker)
:authorization-check yes-authorization-check)
error-message-description (atom nil)
msg (message/make-message
{:sender "pcp://host_a/entity"
:message_type "ether"
:target "pcp://wire/*"})]
(with-redefs [puppetlabs.pcp.broker.shared/send-error-message
(fn [_ description _] (reset! error-message-description description) nil)]
(let [outcome (process-message! broker (message/v2-encode msg) :dummy-ws)]
(is (= "Multiple recipients no longer supported." @error-message-description))
(is (nil? outcome))))))
(testing "delivers an authorized message"
(let [broker (assoc (make-test-broker)
:authorization-check yes-authorization-check)
accepted-message-for-delivery (atom false)
msg (message/make-message
{:sender "pcp://host_a/entity"
:message_type "ether"
:target "pcp://wire/entity"})]
(with-redefs [puppetlabs.pcp.broker.shared/deliver-message
(fn [_ _ _] (reset! accepted-message-for-delivery true) nil)]
(let [outcome (process-message! broker (message/v2-encode msg) :dummy-ws)]
(is @accepted-message-for-delivery)
(is (nil? outcome))))))))
(deftest codec-roundtrip-test
(with-redefs [puppetlabs.pcp.broker.core/make-ring-request make-valid-ring-request
ws->uri mock-ws->uri
ws->common-name (fn [_] "gangoffour")]
(let [broker (assoc (make-test-broker)
:authorization-check yes-authorization-check)
msg (message/make-message
{:sender "pcp://gangoffour/entity"
:message_type "ether"
:target "pcp://gangoffour/entity"})]
(testing "v1-codec survives roundtrip"
(let [sent-message (atom nil)
connection (connection/make-connection :dummy-ws message/v1-codec mock-uri false)]
(with-redefs [puppetlabs.pcp.broker.shared/get-connection
(fn [_ _] connection)
puppetlabs.experimental.websockets.client/send!
(fn [_ message] (reset! sent-message message))]
(let [outcome (process-message! broker (message/v1-encode msg) :dummy-ws)]
(is (= msg (message/v1-decode @sent-message)))
(is (nil? outcome))))))
(testing "v2-codec survives roundtrip"
(let [sent-message (atom nil)
connection (connection/make-connection :dummy-ws message/v2-codec mock-uri false)]
(with-redefs [puppetlabs.pcp.broker.shared/get-connection
(fn [_ _] connection)
puppetlabs.experimental.websockets.client/send!
(fn [_ message] (reset! sent-message message))]
(let [outcome (process-message! broker (message/v2-encode msg) :dummy-ws)]
(is (= msg (message/v2-decode @sent-message)))
(is (nil? outcome)))))))))
(deftest initiate-controllers-test
(let [is-connecting (promise)]
(with-redefs [puppetlabs.pcp.client/connect (fn [params handlers] (deliver is-connecting true) :client)
ws->uri mock-ws->uri]
(let [broker (assoc (make-test-broker)
:authorization-check yes-authorization-check)
ssl-context-factory (make-mock-ssl-context-factory nil)
_ (.start ssl-context-factory)
ssl-context (.getSslContext ssl-context-factory)
_ (.stop ssl-context-factory)
clients (initiate-controller-connections broker ssl-context ["wss://foo.com/v1"] #{} 100)
client (get clients "pcp://foo.com/server")]
(is (= 1 (count clients)))
(is client)
(is (deref is-connecting 1000 nil)
(is (= :client (:websocket client))
(is (= "pcp://foo.com/server" (:uri client)))))))))
| true | (ns puppetlabs.pcp.broker.core-test
(:require [clojure.test :refer :all]
[metrics.core]
[puppetlabs.pcp.testutils :refer [dotestseq]]
[puppetlabs.pcp.broker.shared :refer [Broker]]
[puppetlabs.pcp.broker.core :refer :all]
[puppetlabs.pcp.broker.connection :as connection :refer [Codec]]
[puppetlabs.pcp.broker.websocket :refer [ws->uri ws->common-name]]
[puppetlabs.pcp.broker.message :as message]
[puppetlabs.pcp.broker.shared-test :refer [mock-uri mock-ws->uri make-test-broker]]
[puppetlabs.trapperkeeper.services.webserver.jetty9-core :as jetty9-core]
[puppetlabs.trapperkeeper.services.webserver.jetty9-config :as jetty9-config]
[schema.core :as s]
[slingshot.test])
(:import [puppetlabs.pcp.broker.connection Connection]
[com.puppetlabs.trapperkeeper.services.webserver.jetty9.utils InternalSslContextFactory]))
(s/def identity-codec :- Codec
{:encode identity
:decode identity})
(def dummy-connection
(connection/make-connection :dummy-ws message/v2-codec mock-uri false))
(s/defn make-mock-ssl-context-factory :- InternalSslContextFactory
"Return an instance of the SslContextFactory with only a minimal configuration
of the key & trust stores. If the specified `certificate-chain` is not nil it is
included with the PrivateKey entry in the factory's key store."
[certificate-chain :- (s/maybe s/Str)]
(let [pem-config {:ssl-key "./test-resources/ssl/private_keys/PI:KEY:<KEY>END_PI"
:ssl-cert "./test-resources/ssl/certs/broker.example.com.pem"
:ssl-ca-cert "./test-resources/ssl/certs/ca.pem"}
pem-config (if (nil? certificate-chain)
pem-config
(assoc pem-config :ssl-cert-chain certificate-chain))
keystore-config (jetty9-config/pem-ssl-config->keystore-ssl-config pem-config)]
(doto (InternalSslContextFactory.)
(.setKeyStore (:keystore keystore-config))
(.setKeyStorePassword (:key-password keystore-config))
(.setTrustStore (:truststore keystore-config)))))
(s/defn make-mock-webserver-context :- jetty9-core/ServerContext
"Return a mock webserver context including the specfied `ssl-context-factory`."
[ssl-context-factory :- InternalSslContextFactory]
{:server nil
:handlers (org.eclipse.jetty.server.handler.ContextHandlerCollection.)
:state (atom {:mbean-container nil
:overrides-read-by-webserver true
:overrides nil
:endpoints {}
:ssl-context-factory ssl-context-factory})})
(deftest get-webserver-cn-test
(testing "It returns the correct cn"
(let [cn (-> nil
make-mock-ssl-context-factory
make-mock-webserver-context
get-webserver-cn)]
(is (= "broker.example.com" cn))))
(testing "It returns the correct cn from a certificate chain"
(let [cn (-> "./test-resources/ssl/certs/broker-chain.example.com.pem"
make-mock-ssl-context-factory
make-mock-webserver-context
get-webserver-cn)]
(is (= "broker.example.com" cn))))
(testing "It returns nil if anything goes wrong"
(is (nil? (-> (InternalSslContextFactory.)
make-mock-webserver-context
get-webserver-cn)))))
(deftest add-connection-test
(testing "It should add a connection to the connection map"
(with-redefs [ws->uri mock-ws->uri]
(let [broker (make-test-broker)]
(add-connection! broker (connection/make-connection :dummy-ws identity-codec mock-uri false))
(is (s/validate Connection (-> broker :database deref :inventory (get mock-uri))))))))
(deftest remove-connecton-test
(testing "It should remove a connection from the inventory map"
(with-redefs [ws->uri mock-ws->uri]
(let [broker (make-test-broker)
connection (connection/make-connection :dummy-ws identity-codec mock-uri false)]
(swap! (:database broker) update :inventory assoc mock-uri connection)
(is (not= {} (-> broker :database deref :inventory)))
(remove-connection! broker mock-uri)
(is (= {} (-> broker :database deref :inventory)))))))
(deftest expire-connection-test
(testing "It should expire connections in the inventory"
(with-redefs [ws->uri mock-ws->uri]
(let [broker (make-test-broker)
connection (connection/make-connection :dummy-ws identity-codec mock-uri false)]
(add-connection! broker connection)
(expire-ssl-connections broker)
(= true (-> broker :database deref :inventory (get mock-uri) :expired))))))
(deftest close-expired-connection-test
(testing "It should close expired connections in the inventory after :expired-conn-throttle time"
(let [closed (promise)]
(with-redefs [ws->uri mock-ws->uri
puppetlabs.experimental.websockets.client/close! (fn [& args] (deliver closed true))]
(let [broker (assoc (make-test-broker) :expired-conn-throttle 1000)
connection (connection/make-connection :dummy-ws identity-codec mock-uri false)]
(add-connection! broker connection)
(expire-ssl-connections broker)
(future (close-expired-connections! broker))
(Thread/sleep 100)
(is (not (realized? closed)))
(is (true? (deref closed 1000 false))))))))
(deftest make-ring-request-test
(testing "it should return a ring request - one target"
(let [message (message/make-message
{:message_type "example1"
:sender "pcp://example01.example.com/agent"
:target "pcp://example02.example.com/agent"})]
(is (= {:uri "/pcp-broker/send"
:request-method :post
:remote-addr ""
:form-params {}
:query-params {"sender" "pcp://example01.example.com/agent"
"target" "pcp://example02.example.com/agent"
"message_type" "example1"}
:params {"sender" "pcp://example01.example.com/agent"
"target" "pcp://example02.example.com/agent"
"message_type" "example1"}}
(make-ring-request message nil))))))
(defn yes-authorization-check [r] {:authorized true
:message ""
:request r})
(defn no-authorization-check [r] {:authorized false
:message "Danger Zone"
:request r})
(deftest authorized?-test
(let [yes-broker (assoc (make-test-broker) :authorization-check yes-authorization-check)
no-broker (assoc (make-test-broker) :authorization-check no-authorization-check)
message (message/make-message
{:message_type "example1"
:sender "pcp://example01.example.com/agent"
:target "pcp://example02.example.com/agent"})]
(is (= true (authorized? yes-broker message nil)))
(is (= false (authorized? yes-broker (assoc message :message_type "no\u0000good") nil)))
(is (= false (authorized? yes-broker (assoc message :target "pcp://bad/\u0000target") nil)))
(is (= false (authorized? no-broker message nil)))))
(deftest session-association-message?-test
(testing "It returns true when passed a sessions association message"
(let [message (message/make-message
{:target "pcp:///server"
:message_type "http://puppetlabs.com/associate_request"})]
(is (= true (session-association-request? message)))))
(testing "It returns false when passed a message of an unknown type"
(let [message (-> (message/make-message
{:target "pcp:///server"
:message_type "http://puppetlabs.com/kennylogginsschema"}))]
(is (= false (session-association-request? message)))))
(testing "It returns false when passed a message not aimed to the server target"
(let [message (-> (message/make-message
{:target "pcp://other/server"
:message_type "http://puppetlabs.com/associate_request"}))]
(is (= false (session-association-request? message))))))
(deftest process-associate-request!-test
(let [closed (atom (promise))]
(with-redefs [puppetlabs.experimental.websockets.client/close! (fn [& args] (deliver @closed args))
puppetlabs.experimental.websockets.client/send! (constantly false)
puppetlabs.pcp.broker.websocket/ws->client-type (fn [_] "controller")
ws->uri (fn [_] "pcp://localhost/controller")]
(let [message (-> (message/make-message
{:sender "pcp://localhost/controller"
:message_type "http://puppetlabs.com/login_message"}))]
(testing "It should return an associated Connection if there's no reason to deny association"
(reset! closed (promise))
(let [broker (make-test-broker)
connection (connection/make-connection :dummy-ws identity-codec mock-uri false)
_ (add-connection! broker connection)
connection-uri (:uri (process-associate-request! broker message connection))]
(is (not (realized? @closed)))
(is (= "pcp://localhost/controller" connection-uri))))))))
(deftest process-inventory-request-test
(with-redefs [ws->uri mock-ws->uri])
(let [broker (make-test-broker)
message (message/make-message
{:sender "pcp://test.example.com/test"
:data {:query ["pcp://*/*"]}})
connection (connection/make-connection :dummy-ws identity-codec mock-uri false)
accepted (atom nil)]
(with-redefs
[puppetlabs.pcp.broker.shared/deliver-server-message (fn [_ message _]
(reset! accepted message))]
(let [outcome (process-inventory-request broker message connection)]
(is (nil? outcome))
(is (= [] (:uris (:data @accepted))))))))
(deftest process-server-message!-test
(with-redefs [ws->uri mock-ws->uri]
(let [broker (make-test-broker)
message (message/make-message
{:message_type "http://puppetlabs.com/associate_request"})
connection (connection/make-connection :dummy-ws identity-codec mock-uri false)
associate-request (atom nil)]
(with-redefs
[puppetlabs.pcp.broker.core/process-associate-request! (fn [_ message connection]
(reset! associate-request message)
connection)]
(process-server-message! broker message connection)
(is (not= nil @associate-request))))))
(deftest authenticated?-test
(with-redefs [ws->uri mock-ws->uri]
(let [message (message/make-message
{:sender "pcp://lolcathost/agent"})]
(testing "simple match"
(with-redefs [ws->common-name (fn [_] "lolcathost")]
(is (authenticated? message dummy-connection))))
(testing "simple mismatch"
(with-redefs [ws->common-name (fn [_] "remotecat")]
(is (not (authenticated? message dummy-connection)))))
(testing "accidental regex collisions"
(with-redefs [ws->common-name (fn [_] "lol.athost")]
(is (not (authenticated? message dummy-connection))))))))
(defn make-valid-ring-request
[message _]
(let [{:keys [sender target message_type]} message
params {"sender" sender
"target" target
"message_type" message_type}]
{:uri "/pcp-broker/send"
:request-method :post
:remote-addr ""
:form-params {}
:query-params params
:params params}))
(deftest validate-message-test
(with-redefs [ws->uri mock-ws->uri
ws->common-name (fn [_] "localpost")]
(testing "correctly marks not authenticated messages"
(let [broker (make-test-broker)
msg (message/make-message
{:sender "pcp://groceryshop/office"
:message_type "http://puppetlabs.com/associate_request"})
is-association-request true]
(is (= :not-authenticated
(validate-message broker msg dummy-connection is-association-request)))))
(with-redefs [puppetlabs.pcp.broker.core/make-ring-request make-valid-ring-request]
(testing "correctly marks not authorized messages"
(let [no-broker (assoc (make-test-broker) :authorization-check no-authorization-check)
msg (message/make-message
{:sender "pcp://localpost/exploit"
:message_type "http://puppetlabs.com/associate_request"})
is-association-request true]
(is (= :not-authorized
(validate-message no-broker msg dummy-connection is-association-request)))))
(testing "marks multicast messages as unsupported"
(let [yes-broker (assoc (make-test-broker)
:authorization-check yes-authorization-check)
msg (message/make-message
{:sender "pcp://localpost/gbp"
:message_type "http://puppetlabs.com/associate_request"})
is-association-request true]
(with-redefs [puppetlabs.pcp.broker.message/multicast-message? (fn [_] true)]
(is (= :multicast-unsupported
(validate-message yes-broker msg dummy-connection is-association-request))))))
(testing "marks expired messages as to be processed"
(let [yes-broker (assoc (make-test-broker)
:authorization-check yes-authorization-check)
msg (message/make-message
{:sender "pcp://localpost/gbp"
:message_type "http://puppetlabs.com/associate_request"})
is-association-request true]
(is (= :to-be-processed
(validate-message yes-broker msg dummy-connection is-association-request)))))
(testing "correctly marks messages to be processed"
(let [yes-broker (assoc (make-test-broker) :authorization-check yes-authorization-check)
msg (message/make-message
{:sender "pcp://localpost/opera"
:message_type "http://puppetlabs.com/associate_request"})
is-association-request true]
(is (= :to-be-processed
(validate-message yes-broker msg dummy-connection is-association-request))))))))
(deftest process-message-test
(with-redefs [puppetlabs.pcp.broker.core/make-ring-request make-valid-ring-request
puppetlabs.pcp.broker.shared/get-connection (fn [_ _] dummy-connection)
ws->uri mock-ws->uri
ws->common-name (fn [_] "host_a")]
(testing "delivers message in case of expired msg (not associate_session)"
(let [broker (assoc (make-test-broker)
:authorization-check yes-authorization-check)
called-accept-message (atom false)
msg (-> (message/make-message
{:sender "pcp://host_a/entity"
:message_type "some_kinda_love"
:target "pcp://host_b/entity"}))]
(swap! (:database broker) update :inventory assoc "pcp://host_a/entity" dummy-connection)
(with-redefs [puppetlabs.pcp.broker.shared/deliver-message
(fn [_ _ _] (reset! called-accept-message true) nil)]
(let [outcome (process-message! broker (message/v2-encode msg) :dummy-ws)]
(is @called-accept-message)
(is (nil? outcome))))))
(testing "sends an error message and returns nil in case of authentication failure"
(let [broker (make-test-broker)
error-message-description (atom nil)
msg (-> (message/make-message
{:sender "pcp://popgroup/entity"
:message_type "some_kinda_hate"
:target "pcp://gangoffour/entity"}))]
(with-redefs [puppetlabs.pcp.broker.shared/send-error-message
(fn [_ description _] (reset! error-message-description description) nil)]
(let [outcome (process-message! broker (message/v2-encode msg) :dummy-ws)]
(is (= "Message not authenticated." @error-message-description))
(is (nil? outcome))))))
(testing "sends an error message and returns nil in case of authorization failure"
(let [broker (assoc (make-test-broker)
:authorization-check no-authorization-check)
error-message-description (atom nil)
msg (message/make-message
{:sender "pcp://host_a/entity"
:message_type "sexbeat"
:target "pcp://fourtet/entity"})]
(with-redefs [puppetlabs.pcp.broker.shared/send-error-message
(fn [_ description _]
(reset! error-message-description description) nil)]
(let [outcome (process-message! broker (message/v2-encode msg) :dummy-ws)]
(is (= "Message not authorized." @error-message-description))
(is (nil? outcome))))))
(testing "process an authorized message sent to broker"
(let [broker (assoc (make-test-broker)
:authorization-check yes-authorization-check)
processed-server-message (atom false)
msg (message/make-message
{:sender "pcp://host_a/entity"
:message_type "jackonfire"
:target "pcp:///server"})]
(with-redefs [puppetlabs.pcp.broker.core/process-server-message!
(fn [_ _ _] (reset! processed-server-message true) nil)]
(let [outcome (process-message! broker (message/v2-encode msg) :dummy-ws)]
(is @processed-server-message)
(is (nil? outcome))))))
(testing "sends an error message and returns nil in case of a multicast message"
(let [broker (assoc (make-test-broker)
:authorization-check yes-authorization-check)
error-message-description (atom nil)
msg (message/make-message
{:sender "pcp://host_a/entity"
:message_type "ether"
:target "pcp://wire/*"})]
(with-redefs [puppetlabs.pcp.broker.shared/send-error-message
(fn [_ description _] (reset! error-message-description description) nil)]
(let [outcome (process-message! broker (message/v2-encode msg) :dummy-ws)]
(is (= "Multiple recipients no longer supported." @error-message-description))
(is (nil? outcome))))))
(testing "delivers an authorized message"
(let [broker (assoc (make-test-broker)
:authorization-check yes-authorization-check)
accepted-message-for-delivery (atom false)
msg (message/make-message
{:sender "pcp://host_a/entity"
:message_type "ether"
:target "pcp://wire/entity"})]
(with-redefs [puppetlabs.pcp.broker.shared/deliver-message
(fn [_ _ _] (reset! accepted-message-for-delivery true) nil)]
(let [outcome (process-message! broker (message/v2-encode msg) :dummy-ws)]
(is @accepted-message-for-delivery)
(is (nil? outcome))))))))
(deftest codec-roundtrip-test
(with-redefs [puppetlabs.pcp.broker.core/make-ring-request make-valid-ring-request
ws->uri mock-ws->uri
ws->common-name (fn [_] "gangoffour")]
(let [broker (assoc (make-test-broker)
:authorization-check yes-authorization-check)
msg (message/make-message
{:sender "pcp://gangoffour/entity"
:message_type "ether"
:target "pcp://gangoffour/entity"})]
(testing "v1-codec survives roundtrip"
(let [sent-message (atom nil)
connection (connection/make-connection :dummy-ws message/v1-codec mock-uri false)]
(with-redefs [puppetlabs.pcp.broker.shared/get-connection
(fn [_ _] connection)
puppetlabs.experimental.websockets.client/send!
(fn [_ message] (reset! sent-message message))]
(let [outcome (process-message! broker (message/v1-encode msg) :dummy-ws)]
(is (= msg (message/v1-decode @sent-message)))
(is (nil? outcome))))))
(testing "v2-codec survives roundtrip"
(let [sent-message (atom nil)
connection (connection/make-connection :dummy-ws message/v2-codec mock-uri false)]
(with-redefs [puppetlabs.pcp.broker.shared/get-connection
(fn [_ _] connection)
puppetlabs.experimental.websockets.client/send!
(fn [_ message] (reset! sent-message message))]
(let [outcome (process-message! broker (message/v2-encode msg) :dummy-ws)]
(is (= msg (message/v2-decode @sent-message)))
(is (nil? outcome)))))))))
(deftest initiate-controllers-test
(let [is-connecting (promise)]
(with-redefs [puppetlabs.pcp.client/connect (fn [params handlers] (deliver is-connecting true) :client)
ws->uri mock-ws->uri]
(let [broker (assoc (make-test-broker)
:authorization-check yes-authorization-check)
ssl-context-factory (make-mock-ssl-context-factory nil)
_ (.start ssl-context-factory)
ssl-context (.getSslContext ssl-context-factory)
_ (.stop ssl-context-factory)
clients (initiate-controller-connections broker ssl-context ["wss://foo.com/v1"] #{} 100)
client (get clients "pcp://foo.com/server")]
(is (= 1 (count clients)))
(is client)
(is (deref is-connecting 1000 nil)
(is (= :client (:websocket client))
(is (= "pcp://foo.com/server" (:uri client)))))))))
|
[
{
"context": "ntegrant.core/halt!)\n;;\n;; Cf. https://github.com/weavejester/integrant.\n\n;; :log/level\n;; --------------------",
"end": 1475,
"score": 0.8369577527046204,
"start": 1464,
"tag": "USERNAME",
"value": "weavejester"
},
{
"context": "---\n;; Send headers with each request:\n;; token \"xyzabc123\"\n;; authorization (str \"Bearer \" token)\n;; us",
"end": 4086,
"score": 0.6080963611602783,
"start": 4079,
"tag": "KEY",
"value": "xyzabc1"
},
{
"context": "Send headers with each request:\n;; token \"xyzabc123\"\n;; authorization (str \"Bearer \" token)\n;; use",
"end": 4087,
"score": 0.5218688249588013,
"start": 4086,
"tag": "PASSWORD",
"value": "2"
},
{
"context": "end headers with each request:\n;; token \"xyzabc123\"\n;; authorization (str \"Bearer \" token)\n;; user",
"end": 4088,
"score": 0.4985102713108063,
"start": 4087,
"tag": "KEY",
"value": "3"
},
{
"context": "thorization (str \"Bearer \" token)\n;; user-agent \"X-Kubelt\"\n;; headers {:headers {:authorization authorizat",
"end": 4154,
"score": 0.8791347742080688,
"start": 4146,
"tag": "USERNAME",
"value": "X-Kubelt"
},
{
"context": " :node/read \"http:///ip4/127.0.0.1/tcp/5001\"\n :no",
"end": 6490,
"score": 0.9992756247520447,
"start": 6481,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " :node/write \"http:///ip4/127.0.0.1/tcp/5001\"}))))))))\n\n(defmethod ig/halt-key! :clie",
"end": 6571,
"score": 0.9994471073150635,
"start": 6562,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | src/main/com/kubelt/lib/init.cljc | kubelt/kubelt | 0 | (ns com.kubelt.lib.init
"SDK system map implementation."
{:copyright "©2022 Proof Zero Inc." :license "Apache 2.0"}
(:require
[integrant.core :as ig]
[taoensso.timbre :as log])
(:require
[com.kubelt.ipfs.client :as ipfs.client]
[com.kubelt.lib.error :as lib.error]
[com.kubelt.lib.integrant :as lib.integrant]
[com.kubelt.lib.jwt :as lib.jwt]
[com.kubelt.lib.promise :as lib.promise]
[com.kubelt.lib.vault :as lib.vault]
[com.kubelt.lib.wallet :as lib.wallet]
[com.kubelt.proto.http :as proto.http])
(:require
#?@(:browser [[com.kubelt.lib.http.browser :as http.browser]]
:node [[com.kubelt.lib.http.node :as http.node]]
:clj [[com.kubelt.lib.http.jvm :as http.jvm]])))
;; System
;; -----------------------------------------------------------------------------
;; For each key in the system map, if a corresponding method is
;; implemented for the ig/init-key multimethod it will be invoked in
;; order to initialize that part of the system. The return value is
;; stored as part of the system configuration map. Initialization is
;; performed recursively, making it possible to have nested subsystems.
;;
;; If methods are defined for the ig/halt-key! multimethod, they are
;; invoked in order to tear down the system in the reverse order in
;; which it was initialized.
;;
;; To begin the system:
;; (integrant.core/init)
;; To stop the system:
;; (integrant.core/halt!)
;;
;; Cf. https://github.com/weavejester/integrant.
;; :log/level
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :log/level [_ log-level]
;; Initialize the logging system.
(when log-level
(log/merge-config! {:min-level log-level}))
log-level)
(defmethod ig/halt-key! :log/level [_ log-level]
(log/debug {:log/msg "halt logging"}))
;; :ipfs.read/scheme
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :ipfs.read/scheme [_ scheme]
scheme)
;; :ipfs.read/host
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :ipfs.read/host [_ host]
host)
;; :ipfs.read/port
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :ipfs.read/port [_ port]
port)
;; :ipfs.write/scheme
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :ipfs.write/scheme [_ scheme]
scheme)
;; :ipfs.write/host
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :ipfs.write/host [_ host]
host)
;; :ipfs.write/port
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :ipfs.write/port [_ port]
port)
;; :p2p/scheme
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :p2p/scheme [_ scheme]
scheme)
;; :p2p/host
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :p2p/host [_ host]
host)
;; :p2p/port
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :p2p/port [_ port]
port)
;; :credential/jwt
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :credential/jwt [_ tokens]
tokens)
;; :client/http
;; -----------------------------------------------------------------------------
;; TODO support custom user agent string.
(defmethod ig/init-key :client/http [_ value]
{:post [(not (nil? %))]}
(log/debug {:log/msg "init HTTP client"})
#?(:browser (http.browser/->HttpClient)
:node (http.node/->HttpClient)
:clj (http.jvm/->HttpClient)))
(defmethod ig/halt-key! :client/http [_ client]
{:pre [(satisfies? proto.http/HttpClient client)]}
(log/debug {:log/msg "halt HTTP client"}))
;; :client/ipfs
;; -----------------------------------------------------------------------------
;; Send headers with each request:
;; token "xyzabc123"
;; authorization (str "Bearer " token)
;; user-agent "X-Kubelt"
;; headers {:headers {:authorization authorization
;; :user-agent user-agent}}
;;
;; Use an http.Agent (node-only) to control client behavior:
;; agent {:agent (.. http Agent.)}
(defmethod ig/init-key :client/ipfs [_ value]
(let [;; Supply the address of the IPFS node(s). Read and write can
;; use different paths if desired, e.g. when you want to read
;; from a local daemon but write to a remote service for
;; pinning.
read-scheme (get-in value [:ipfs/read :http/scheme])
read-host (get-in value [:ipfs/read :http/host])
read-port (get-in value [:ipfs/read :http/port])
write-scheme (get-in value [:ipfs/write :http/scheme])
write-host (get-in value [:ipfs/write :http/host])
write-port (get-in value [:ipfs/write :http/port])
;; Get the platform-specific HTTP client.
http-client (get value :client/http)
make-url (fn [scheme host port]
(str (name read-scheme) "://" read-host ":" read-port))
ipfs-read (make-url read-scheme read-host read-port)
ipfs-write (make-url write-scheme write-host write-port)]
(log/debug {:log/msg "init IPFS client" :ipfs/read ipfs-read :ipfs/write ipfs-write})
;; Create the options object we pass to client creation fn.
#?(:cljs
(let [options {:http/client http-client
:read/scheme read-scheme
:read/host read-host
:read/port read-port
:write/scheme write-scheme
:write/host write-host
:write/port write-port
;; Set a global timeout for *all* requests:
;;:client/timeout 5000
}]
(-> (ipfs.client/init options)
(lib.promise/then (fn [x] (lib.promise/resolved x)))
(lib.promise/catch (fn [e]
(log/fatal ::error e)
(log/fatal ::mocking-ipfs-client "TODO: FIX IN CI")
(lib.promise/resolved
{:com.kubelt/type :kubelt.type/ipfs-client
:http/client :mock
:node/read "http:///ip4/127.0.0.1/tcp/5001"
:node/write "http:///ip4/127.0.0.1/tcp/5001"}))))))))
(defmethod ig/halt-key! :client/ipfs [_ client]
(log/debug {:log/msg "halt IPFS client"}))
;; :client/p2p
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :client/p2p [_ {:keys [http/scheme http/host http/port] :as value}]
;; TODO initialize an RPC client using the given coordinates once
;; local client is fleshed out.
(let [address (str (name scheme) "://" host ":" port)]
(log/debug {:log/msg "init p2p client" :p2p/address address})
value))
(defmethod ig/halt-key! :client/p2p [_ value]
(log/debug {:log/msg "halt p2p client"}))
;; :crypto/session
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :crypto/session [_ {:keys [jwt/tokens]}]
(log/debug {:log/msg "init session"})
;; If any JWTs are provided, parse them and store the decoded result.
(let [tokens (reduce (fn [m [core token]]
(let [decoded (lib.jwt/decode token)]
(assoc m core decoded)))
{}
tokens)]
;; Our session storage map is a "vault".
(lib.vault/vault tokens)))
(defmethod ig/halt-key! :crypto/session [_ session]
(log/debug {:log/msg "halt session"}))
;; :crypto/wallet
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :crypto/wallet [_ wallet]
(log/debug {:log/msg "init wallet"})
(if-not (lib.wallet/valid? wallet)
(throw (ex-info "invalid wallet" wallet))
wallet))
(defmethod ig/halt-key! :crypto/wallet [_ wallet]
(log/debug {:log/msg "halt wallet"}))
;; Public
;; -----------------------------------------------------------------------------
;; NB: the configuration map is validated by the exposed SDK methods.
(defn init
"Initialize the SDK."
[system-config resolve reject]
(if (lib.error/error? system-config)
(reject system-config)
(-> system-config
;; TEMP
(dissoc :client/ipfs)
(lib.integrant/init resolve reject))))
(defn halt!
"Clean-up resources used by the SDK."
[sys-map]
(ig/halt! sys-map))
| 53423 | (ns com.kubelt.lib.init
"SDK system map implementation."
{:copyright "©2022 Proof Zero Inc." :license "Apache 2.0"}
(:require
[integrant.core :as ig]
[taoensso.timbre :as log])
(:require
[com.kubelt.ipfs.client :as ipfs.client]
[com.kubelt.lib.error :as lib.error]
[com.kubelt.lib.integrant :as lib.integrant]
[com.kubelt.lib.jwt :as lib.jwt]
[com.kubelt.lib.promise :as lib.promise]
[com.kubelt.lib.vault :as lib.vault]
[com.kubelt.lib.wallet :as lib.wallet]
[com.kubelt.proto.http :as proto.http])
(:require
#?@(:browser [[com.kubelt.lib.http.browser :as http.browser]]
:node [[com.kubelt.lib.http.node :as http.node]]
:clj [[com.kubelt.lib.http.jvm :as http.jvm]])))
;; System
;; -----------------------------------------------------------------------------
;; For each key in the system map, if a corresponding method is
;; implemented for the ig/init-key multimethod it will be invoked in
;; order to initialize that part of the system. The return value is
;; stored as part of the system configuration map. Initialization is
;; performed recursively, making it possible to have nested subsystems.
;;
;; If methods are defined for the ig/halt-key! multimethod, they are
;; invoked in order to tear down the system in the reverse order in
;; which it was initialized.
;;
;; To begin the system:
;; (integrant.core/init)
;; To stop the system:
;; (integrant.core/halt!)
;;
;; Cf. https://github.com/weavejester/integrant.
;; :log/level
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :log/level [_ log-level]
;; Initialize the logging system.
(when log-level
(log/merge-config! {:min-level log-level}))
log-level)
(defmethod ig/halt-key! :log/level [_ log-level]
(log/debug {:log/msg "halt logging"}))
;; :ipfs.read/scheme
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :ipfs.read/scheme [_ scheme]
scheme)
;; :ipfs.read/host
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :ipfs.read/host [_ host]
host)
;; :ipfs.read/port
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :ipfs.read/port [_ port]
port)
;; :ipfs.write/scheme
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :ipfs.write/scheme [_ scheme]
scheme)
;; :ipfs.write/host
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :ipfs.write/host [_ host]
host)
;; :ipfs.write/port
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :ipfs.write/port [_ port]
port)
;; :p2p/scheme
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :p2p/scheme [_ scheme]
scheme)
;; :p2p/host
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :p2p/host [_ host]
host)
;; :p2p/port
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :p2p/port [_ port]
port)
;; :credential/jwt
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :credential/jwt [_ tokens]
tokens)
;; :client/http
;; -----------------------------------------------------------------------------
;; TODO support custom user agent string.
(defmethod ig/init-key :client/http [_ value]
{:post [(not (nil? %))]}
(log/debug {:log/msg "init HTTP client"})
#?(:browser (http.browser/->HttpClient)
:node (http.node/->HttpClient)
:clj (http.jvm/->HttpClient)))
(defmethod ig/halt-key! :client/http [_ client]
{:pre [(satisfies? proto.http/HttpClient client)]}
(log/debug {:log/msg "halt HTTP client"}))
;; :client/ipfs
;; -----------------------------------------------------------------------------
;; Send headers with each request:
;; token "<KEY> <PASSWORD> <KEY>"
;; authorization (str "Bearer " token)
;; user-agent "X-Kubelt"
;; headers {:headers {:authorization authorization
;; :user-agent user-agent}}
;;
;; Use an http.Agent (node-only) to control client behavior:
;; agent {:agent (.. http Agent.)}
(defmethod ig/init-key :client/ipfs [_ value]
(let [;; Supply the address of the IPFS node(s). Read and write can
;; use different paths if desired, e.g. when you want to read
;; from a local daemon but write to a remote service for
;; pinning.
read-scheme (get-in value [:ipfs/read :http/scheme])
read-host (get-in value [:ipfs/read :http/host])
read-port (get-in value [:ipfs/read :http/port])
write-scheme (get-in value [:ipfs/write :http/scheme])
write-host (get-in value [:ipfs/write :http/host])
write-port (get-in value [:ipfs/write :http/port])
;; Get the platform-specific HTTP client.
http-client (get value :client/http)
make-url (fn [scheme host port]
(str (name read-scheme) "://" read-host ":" read-port))
ipfs-read (make-url read-scheme read-host read-port)
ipfs-write (make-url write-scheme write-host write-port)]
(log/debug {:log/msg "init IPFS client" :ipfs/read ipfs-read :ipfs/write ipfs-write})
;; Create the options object we pass to client creation fn.
#?(:cljs
(let [options {:http/client http-client
:read/scheme read-scheme
:read/host read-host
:read/port read-port
:write/scheme write-scheme
:write/host write-host
:write/port write-port
;; Set a global timeout for *all* requests:
;;:client/timeout 5000
}]
(-> (ipfs.client/init options)
(lib.promise/then (fn [x] (lib.promise/resolved x)))
(lib.promise/catch (fn [e]
(log/fatal ::error e)
(log/fatal ::mocking-ipfs-client "TODO: FIX IN CI")
(lib.promise/resolved
{:com.kubelt/type :kubelt.type/ipfs-client
:http/client :mock
:node/read "http:///ip4/127.0.0.1/tcp/5001"
:node/write "http:///ip4/127.0.0.1/tcp/5001"}))))))))
(defmethod ig/halt-key! :client/ipfs [_ client]
(log/debug {:log/msg "halt IPFS client"}))
;; :client/p2p
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :client/p2p [_ {:keys [http/scheme http/host http/port] :as value}]
;; TODO initialize an RPC client using the given coordinates once
;; local client is fleshed out.
(let [address (str (name scheme) "://" host ":" port)]
(log/debug {:log/msg "init p2p client" :p2p/address address})
value))
(defmethod ig/halt-key! :client/p2p [_ value]
(log/debug {:log/msg "halt p2p client"}))
;; :crypto/session
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :crypto/session [_ {:keys [jwt/tokens]}]
(log/debug {:log/msg "init session"})
;; If any JWTs are provided, parse them and store the decoded result.
(let [tokens (reduce (fn [m [core token]]
(let [decoded (lib.jwt/decode token)]
(assoc m core decoded)))
{}
tokens)]
;; Our session storage map is a "vault".
(lib.vault/vault tokens)))
(defmethod ig/halt-key! :crypto/session [_ session]
(log/debug {:log/msg "halt session"}))
;; :crypto/wallet
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :crypto/wallet [_ wallet]
(log/debug {:log/msg "init wallet"})
(if-not (lib.wallet/valid? wallet)
(throw (ex-info "invalid wallet" wallet))
wallet))
(defmethod ig/halt-key! :crypto/wallet [_ wallet]
(log/debug {:log/msg "halt wallet"}))
;; Public
;; -----------------------------------------------------------------------------
;; NB: the configuration map is validated by the exposed SDK methods.
(defn init
"Initialize the SDK."
[system-config resolve reject]
(if (lib.error/error? system-config)
(reject system-config)
(-> system-config
;; TEMP
(dissoc :client/ipfs)
(lib.integrant/init resolve reject))))
(defn halt!
"Clean-up resources used by the SDK."
[sys-map]
(ig/halt! sys-map))
| true | (ns com.kubelt.lib.init
"SDK system map implementation."
{:copyright "©2022 Proof Zero Inc." :license "Apache 2.0"}
(:require
[integrant.core :as ig]
[taoensso.timbre :as log])
(:require
[com.kubelt.ipfs.client :as ipfs.client]
[com.kubelt.lib.error :as lib.error]
[com.kubelt.lib.integrant :as lib.integrant]
[com.kubelt.lib.jwt :as lib.jwt]
[com.kubelt.lib.promise :as lib.promise]
[com.kubelt.lib.vault :as lib.vault]
[com.kubelt.lib.wallet :as lib.wallet]
[com.kubelt.proto.http :as proto.http])
(:require
#?@(:browser [[com.kubelt.lib.http.browser :as http.browser]]
:node [[com.kubelt.lib.http.node :as http.node]]
:clj [[com.kubelt.lib.http.jvm :as http.jvm]])))
;; System
;; -----------------------------------------------------------------------------
;; For each key in the system map, if a corresponding method is
;; implemented for the ig/init-key multimethod it will be invoked in
;; order to initialize that part of the system. The return value is
;; stored as part of the system configuration map. Initialization is
;; performed recursively, making it possible to have nested subsystems.
;;
;; If methods are defined for the ig/halt-key! multimethod, they are
;; invoked in order to tear down the system in the reverse order in
;; which it was initialized.
;;
;; To begin the system:
;; (integrant.core/init)
;; To stop the system:
;; (integrant.core/halt!)
;;
;; Cf. https://github.com/weavejester/integrant.
;; :log/level
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :log/level [_ log-level]
;; Initialize the logging system.
(when log-level
(log/merge-config! {:min-level log-level}))
log-level)
(defmethod ig/halt-key! :log/level [_ log-level]
(log/debug {:log/msg "halt logging"}))
;; :ipfs.read/scheme
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :ipfs.read/scheme [_ scheme]
scheme)
;; :ipfs.read/host
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :ipfs.read/host [_ host]
host)
;; :ipfs.read/port
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :ipfs.read/port [_ port]
port)
;; :ipfs.write/scheme
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :ipfs.write/scheme [_ scheme]
scheme)
;; :ipfs.write/host
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :ipfs.write/host [_ host]
host)
;; :ipfs.write/port
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :ipfs.write/port [_ port]
port)
;; :p2p/scheme
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :p2p/scheme [_ scheme]
scheme)
;; :p2p/host
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :p2p/host [_ host]
host)
;; :p2p/port
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :p2p/port [_ port]
port)
;; :credential/jwt
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :credential/jwt [_ tokens]
tokens)
;; :client/http
;; -----------------------------------------------------------------------------
;; TODO support custom user agent string.
(defmethod ig/init-key :client/http [_ value]
{:post [(not (nil? %))]}
(log/debug {:log/msg "init HTTP client"})
#?(:browser (http.browser/->HttpClient)
:node (http.node/->HttpClient)
:clj (http.jvm/->HttpClient)))
(defmethod ig/halt-key! :client/http [_ client]
{:pre [(satisfies? proto.http/HttpClient client)]}
(log/debug {:log/msg "halt HTTP client"}))
;; :client/ipfs
;; -----------------------------------------------------------------------------
;; Send headers with each request:
;; token "PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI PI:KEY:<KEY>END_PI"
;; authorization (str "Bearer " token)
;; user-agent "X-Kubelt"
;; headers {:headers {:authorization authorization
;; :user-agent user-agent}}
;;
;; Use an http.Agent (node-only) to control client behavior:
;; agent {:agent (.. http Agent.)}
(defmethod ig/init-key :client/ipfs [_ value]
(let [;; Supply the address of the IPFS node(s). Read and write can
;; use different paths if desired, e.g. when you want to read
;; from a local daemon but write to a remote service for
;; pinning.
read-scheme (get-in value [:ipfs/read :http/scheme])
read-host (get-in value [:ipfs/read :http/host])
read-port (get-in value [:ipfs/read :http/port])
write-scheme (get-in value [:ipfs/write :http/scheme])
write-host (get-in value [:ipfs/write :http/host])
write-port (get-in value [:ipfs/write :http/port])
;; Get the platform-specific HTTP client.
http-client (get value :client/http)
make-url (fn [scheme host port]
(str (name read-scheme) "://" read-host ":" read-port))
ipfs-read (make-url read-scheme read-host read-port)
ipfs-write (make-url write-scheme write-host write-port)]
(log/debug {:log/msg "init IPFS client" :ipfs/read ipfs-read :ipfs/write ipfs-write})
;; Create the options object we pass to client creation fn.
#?(:cljs
(let [options {:http/client http-client
:read/scheme read-scheme
:read/host read-host
:read/port read-port
:write/scheme write-scheme
:write/host write-host
:write/port write-port
;; Set a global timeout for *all* requests:
;;:client/timeout 5000
}]
(-> (ipfs.client/init options)
(lib.promise/then (fn [x] (lib.promise/resolved x)))
(lib.promise/catch (fn [e]
(log/fatal ::error e)
(log/fatal ::mocking-ipfs-client "TODO: FIX IN CI")
(lib.promise/resolved
{:com.kubelt/type :kubelt.type/ipfs-client
:http/client :mock
:node/read "http:///ip4/127.0.0.1/tcp/5001"
:node/write "http:///ip4/127.0.0.1/tcp/5001"}))))))))
(defmethod ig/halt-key! :client/ipfs [_ client]
(log/debug {:log/msg "halt IPFS client"}))
;; :client/p2p
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :client/p2p [_ {:keys [http/scheme http/host http/port] :as value}]
;; TODO initialize an RPC client using the given coordinates once
;; local client is fleshed out.
(let [address (str (name scheme) "://" host ":" port)]
(log/debug {:log/msg "init p2p client" :p2p/address address})
value))
(defmethod ig/halt-key! :client/p2p [_ value]
(log/debug {:log/msg "halt p2p client"}))
;; :crypto/session
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :crypto/session [_ {:keys [jwt/tokens]}]
(log/debug {:log/msg "init session"})
;; If any JWTs are provided, parse them and store the decoded result.
(let [tokens (reduce (fn [m [core token]]
(let [decoded (lib.jwt/decode token)]
(assoc m core decoded)))
{}
tokens)]
;; Our session storage map is a "vault".
(lib.vault/vault tokens)))
(defmethod ig/halt-key! :crypto/session [_ session]
(log/debug {:log/msg "halt session"}))
;; :crypto/wallet
;; -----------------------------------------------------------------------------
(defmethod ig/init-key :crypto/wallet [_ wallet]
(log/debug {:log/msg "init wallet"})
(if-not (lib.wallet/valid? wallet)
(throw (ex-info "invalid wallet" wallet))
wallet))
(defmethod ig/halt-key! :crypto/wallet [_ wallet]
(log/debug {:log/msg "halt wallet"}))
;; Public
;; -----------------------------------------------------------------------------
;; NB: the configuration map is validated by the exposed SDK methods.
(defn init
"Initialize the SDK."
[system-config resolve reject]
(if (lib.error/error? system-config)
(reject system-config)
(-> system-config
;; TEMP
(dissoc :client/ipfs)
(lib.integrant/init resolve reject))))
(defn halt!
"Clean-up resources used by the SDK."
[sys-map]
(ig/halt! sys-map))
|
[
{
"context": "b\n (is (sched/started?))\n (let [jk (j/key \"clojurewerkz.quartzite.test.execution.job2\" \"tests\")\n tk (t/key \"clojurewerk",
"end": 1992,
"score": 0.9911813139915466,
"start": 1950,
"tag": "KEY",
"value": "clojurewerkz.quartzite.test.execution.job2"
},
{
"context": "cution.job2\" \"tests\")\n tk (t/key \"clojurewerkz.quartzite.test.execution.trigger2\" \"tests\")\n job (j/build\n ",
"end": 2077,
"score": 0.9825863242149353,
"start": 2031,
"tag": "KEY",
"value": "clojurewerkz.quartzite.test.execution.trigger2"
},
{
"context": "get-job jk))\n (is (nil? (sched/get-job (j/key \"ab88fsyd7f\" \"k28s8d77s\"))))\n (is (nil? (sched/get-trigger",
"end": 3236,
"score": 0.9980480074882507,
"start": 3226,
"tag": "KEY",
"value": "ab88fsyd7f"
},
{
"context": "77s\"))))\n (is (nil? (sched/get-trigger (t/key \"ab88fsyd7f\"))))\n (is (not (empty? (sched/get-trigger-keys",
"end": 3305,
"score": 0.9975724816322327,
"start": 3295,
"tag": "KEY",
"value": "ab88fsyd7f"
},
{
"context": "s\n (is (sched/started?))\n (let [jk (j/key \"clojurewerkz.quartzite.test.execution.job4\" \"tests\")\n tk (t/key \"clojurewerkz.qu",
"end": 4955,
"score": 0.9760717749595642,
"start": 4913,
"tag": "KEY",
"value": "clojurewerkz.quartzite.test.execution.job4"
},
{
"context": ".execution.job4\" \"tests\")\n tk (t/key \"clojurewerkz.quartzite.test.execution.trigger4\" \"tests\")\n job (j/build\n ",
"end": 5036,
"score": 0.8928095102310181,
"start": 4990,
"tag": "KEY",
"value": "clojurewerkz.quartzite.test.execution.trigger4"
},
{
"context": "g\n (is (sched/started?))\n (let [jk (j/key \"clojurewerkz.quartzite.test.execution.job5\" \"tests.jobs.unscheduling\")\n tk (t/ke",
"end": 6006,
"score": 0.9732764959335327,
"start": 5964,
"tag": "KEY",
"value": "clojurewerkz.quartzite.test.execution.job5"
},
{
"context": "tests.jobs.unscheduling\")\n tk (t/key \"clojurewerkz.quartzite.test.execution.trigger5\" \"tests.jobs.unscheduling\")\n job (j/bu",
"end": 6105,
"score": 0.8218144774436951,
"start": 6059,
"tag": "KEY",
"value": "clojurewerkz.quartzite.test.execution.trigger5"
}
] | src/test/clojure/com/novemberain/quartz_mongodb/test/quartzite_integration_test.clj | Widgetlabs/quartz-mongodb | 1 | (ns com.novemberain.quartz-mongodb.test.quartzite-integration-test
(:use clojure.test
clojurewerkz.quartzite.conversion
[clj-time.core :only [now secs from-now]])
(:require [clojurewerkz.quartzite.scheduler :as sched]
[clojurewerkz.quartzite.jobs :as j]
[clojurewerkz.quartzite.triggers :as t]
[clojurewerkz.quartzite.matchers :as m]
[clojurewerkz.quartzite.schedule.simple :as s]
[clojurewerkz.quartzite.schedule.calendar-interval :as calin])
(:import java.util.concurrent.CountDownLatch
org.quartz.impl.matchers.GroupMatcher))
;; These are integration tests from Quartzite.
;; They do a decent job of exercising most of the underlying store operations
;; so we just reuse it here.
(sched/initialize)
(sched/start)
;;
;; Case 1
;;
(def latch1 (CountDownLatch. 10))
(defrecord JobA []
org.quartz.Job
(execute [this ctx]
(.countDown ^CountDownLatch latch1)))
(deftest test-basic-periodic-execution-with-a-job-defined-using-defrecord
(is (sched/started?))
(let [job (j/build
(j/of-type JobA)
(j/with-identity "clojurewerkz.quartzite.test.execution.job1" "tests"))
trigger (t/build
(t/start-now)
(t/with-schedule (s/schedule
(s/with-repeat-count 10)
(s/with-interval-in-milliseconds 200))))]
(sched/schedule job trigger)
(let [j (sched/get-job (j/key "clojurewerkz.quartzite.test.execution.job1" "tests"))
m (from-job-detail j)]
(is j)
(is (:key m))
(is (nil? (:description m)))
(is (:job-data m)))
(.await ^CountDownLatch latch1)))
;;
;; Case 2
;;
(def counter2 (atom 0))
(j/defjob JobB
[ctx]
(swap! counter2 inc))
(deftest test-unscheduling-of-a-job-defined-using-defjob
(is (sched/started?))
(let [jk (j/key "clojurewerkz.quartzite.test.execution.job2" "tests")
tk (t/key "clojurewerkz.quartzite.test.execution.trigger2" "tests")
job (j/build
(j/of-type JobB)
(j/with-identity "clojurewerkz.quartzite.test.execution.job2" "tests"))
trigger (t/build
(t/start-now)
(t/with-identity "clojurewerkz.quartzite.test.execution.trigger2" "tests")
(t/with-description "just a trigger")
(t/with-schedule (s/schedule
(s/with-repeat-count 10)
(s/with-interval-in-milliseconds 400))))]
(is (not (sched/all-scheduled? jk tk)))
(is (not (sched/scheduled? jk)))
(is (not (sched/scheduled? tk)))
(sched/schedule job trigger)
(is (sched/all-scheduled? jk tk))
(is (sched/scheduled? jk))
(is (sched/scheduled? tk))
(is (not (empty? (sched/get-triggers [tk]))))
(is (not (empty? (sched/get-jobs [jk]))))
(let [t (sched/get-trigger tk)
m (from-trigger t)]
(is t)
(is (:key m))
(is (:description m))
(is (:start-time m))
(is (:next-fire-time m)))
(is (sched/get-job jk))
(is (nil? (sched/get-job (j/key "ab88fsyd7f" "k28s8d77s"))))
(is (nil? (sched/get-trigger (t/key "ab88fsyd7f"))))
(is (not (empty? (sched/get-trigger-keys (m/group-equals "tests")))))
(is (not (empty? (sched/get-matching-triggers (m/group-equals "tests")))))
(is (not (empty? (sched/get-job-keys (m/group-equals "tests")))))
(is (not (empty? (sched/get-matching-jobs (m/group-equals "tests")))))
(Thread/sleep 2000)
(sched/unschedule-job tk)
(is (not (sched/all-scheduled? tk jk)))
(Thread/sleep 2000)
(is (< @counter2 7))))
;;
;; Case 3
;;
(def counter3 (atom 0))
(j/defjob JobC
[ctx]
(swap! counter3 inc))
(deftest test-manual-triggering-of-a-job-defined-using-defjob
(is (sched/started?))
(let [jk (j/key "clojurewerkz.quartzite.test.execution.job3" "tests")
tk (t/key "clojurewerkz.quartzite.test.execution.trigger3" "tests")
job (j/build
(j/of-type JobC)
(j/with-identity "clojurewerkz.quartzite.test.execution.job3" "tests"))
trigger (t/build
(t/start-now)
(t/with-identity "clojurewerkz.quartzite.test.execution.trigger3" "tests")
(t/with-schedule (s/schedule
(s/with-repeat-count 10)
(s/with-interval-in-seconds 2))))]
(sched/schedule job trigger)
(sched/trigger jk)
(Thread/sleep 500)
(is (= 2 @counter3))))
;;
;; Case 4
;;
(def value4 (atom nil))
(j/defjob JobD
[ctx]
(swap! value4 (fn [_]
(from-job-data (.getMergedJobDataMap ctx)))))
(deftest test-job-data-access
(is (sched/started?))
(let [jk (j/key "clojurewerkz.quartzite.test.execution.job4" "tests")
tk (t/key "clojurewerkz.quartzite.test.execution.trigger4" "tests")
job (j/build
(j/of-type JobD)
(j/with-identity "clojurewerkz.quartzite.test.execution.job4" "tests")
(j/using-job-data { "job-key" "job-element" }))
trigger (t/build
(t/start-now)
(t/with-identity "clojurewerkz.quartzite.test.execution.trigger4" "tests")
(t/with-schedule (s/schedule
(s/with-repeat-count 10)
(s/with-interval-in-seconds 2))))]
(sched/schedule job trigger)
(sched/trigger jk)
(Thread/sleep 1000)
(is (= "job-element" (get @value4 "job-key")))))
;;
;; Case 5
;;
(def counter5 (atom 0))
(j/defjob JobE
[ctx]
(let [i (get (from-job-data ctx) "job-key")]
(swap! counter5 + i)))
(deftest test-job-pausing-resuming-and-unscheduling
(is (sched/started?))
(let [jk (j/key "clojurewerkz.quartzite.test.execution.job5" "tests.jobs.unscheduling")
tk (t/key "clojurewerkz.quartzite.test.execution.trigger5" "tests.jobs.unscheduling")
job (j/build
(j/of-type JobE)
(j/with-identity "clojurewerkz.quartzite.test.execution.job5" "tests.triggers.unscheduling")
(j/using-job-data { "job-key" 2 }))
trigger (t/build
(t/start-now)
(t/with-identity "clojurewerkz.quartzite.test.execution.trigger5" "tests.triggers.unscheduling")
(t/with-schedule (s/schedule
(s/with-repeat-count 10)
(s/with-interval-in-seconds 1))))]
(sched/schedule job trigger)
(sched/pause-job jk)
(sched/resume-job jk)
(sched/pause-jobs (GroupMatcher/groupEquals "tests.jobs.unscheduling"))
(sched/resume-jobs (GroupMatcher/groupEquals "tests.jobs.unscheduling"))
(sched/pause-trigger tk)
(sched/resume-trigger tk)
(sched/pause-triggers (GroupMatcher/groupEquals "tests.triggers.unscheduling"))
(sched/resume-triggers (GroupMatcher/groupEquals "tests.triggers.unscheduling"))
(sched/pause-all!)
(sched/resume-all!)
(sched/unschedule-job tk)
(Thread/sleep 300)
(sched/unschedule-jobs [tk])
(sched/delete-job jk)
(sched/delete-jobs [jk])
(Thread/sleep 3000)
;; with start-now policty some executions
;; manages to get through. In part this test is supposed
;; to demonstrate it as much as test unscheduling/pausing functions. MK.
(is (< @counter5 10))))
;;
;; Case 6
;;
(def latch6 (CountDownLatch. 3))
(j/defjob JobF
[ctx]
(.countDown ^CountDownLatch latch6))
(deftest test-basic-periodic-execution-with-calendar-interval-schedule
(is (sched/started?))
(let [job (j/build
(j/of-type JobF)
(j/with-identity "clojurewerkz.quartzite.test.execution.job6" "tests"))
trigger (t/build
(t/start-now)
(t/with-schedule (calin/schedule
(calin/with-interval-in-seconds 2))))]
(sched/schedule job trigger)
(.await ^CountDownLatch latch6)))
;;
;; Case 7
;;
(def counter7 (atom 0))
(j/defjob JobG
[ctx]
(swap! counter7 inc))
(deftest test-double-scheduling
(is (sched/started?))
(let [job (j/build
(j/of-type JobG)
(j/with-identity "clojurewerkz.quartzite.test.execution.job7" "tests"))
trigger (t/build
(t/start-at (-> 2 secs from-now))
(t/with-schedule (calin/schedule
(calin/with-interval-in-seconds 2))))]
(is (sched/schedule job trigger))
;; schedule will raise an exception
(is (thrown?
org.quartz.ObjectAlreadyExistsException
(sched/schedule job trigger)))
;; but maybe-schedule will not
(is (not (sched/maybe-schedule job trigger)))
(is (not (sched/maybe-schedule job trigger)))
(is (not (sched/maybe-schedule job trigger)))
(Thread/sleep 7000)
(is (= 3 @counter7))))
| 100117 | (ns com.novemberain.quartz-mongodb.test.quartzite-integration-test
(:use clojure.test
clojurewerkz.quartzite.conversion
[clj-time.core :only [now secs from-now]])
(:require [clojurewerkz.quartzite.scheduler :as sched]
[clojurewerkz.quartzite.jobs :as j]
[clojurewerkz.quartzite.triggers :as t]
[clojurewerkz.quartzite.matchers :as m]
[clojurewerkz.quartzite.schedule.simple :as s]
[clojurewerkz.quartzite.schedule.calendar-interval :as calin])
(:import java.util.concurrent.CountDownLatch
org.quartz.impl.matchers.GroupMatcher))
;; These are integration tests from Quartzite.
;; They do a decent job of exercising most of the underlying store operations
;; so we just reuse it here.
(sched/initialize)
(sched/start)
;;
;; Case 1
;;
(def latch1 (CountDownLatch. 10))
(defrecord JobA []
org.quartz.Job
(execute [this ctx]
(.countDown ^CountDownLatch latch1)))
(deftest test-basic-periodic-execution-with-a-job-defined-using-defrecord
(is (sched/started?))
(let [job (j/build
(j/of-type JobA)
(j/with-identity "clojurewerkz.quartzite.test.execution.job1" "tests"))
trigger (t/build
(t/start-now)
(t/with-schedule (s/schedule
(s/with-repeat-count 10)
(s/with-interval-in-milliseconds 200))))]
(sched/schedule job trigger)
(let [j (sched/get-job (j/key "clojurewerkz.quartzite.test.execution.job1" "tests"))
m (from-job-detail j)]
(is j)
(is (:key m))
(is (nil? (:description m)))
(is (:job-data m)))
(.await ^CountDownLatch latch1)))
;;
;; Case 2
;;
(def counter2 (atom 0))
(j/defjob JobB
[ctx]
(swap! counter2 inc))
(deftest test-unscheduling-of-a-job-defined-using-defjob
(is (sched/started?))
(let [jk (j/key "<KEY>" "tests")
tk (t/key "<KEY>" "tests")
job (j/build
(j/of-type JobB)
(j/with-identity "clojurewerkz.quartzite.test.execution.job2" "tests"))
trigger (t/build
(t/start-now)
(t/with-identity "clojurewerkz.quartzite.test.execution.trigger2" "tests")
(t/with-description "just a trigger")
(t/with-schedule (s/schedule
(s/with-repeat-count 10)
(s/with-interval-in-milliseconds 400))))]
(is (not (sched/all-scheduled? jk tk)))
(is (not (sched/scheduled? jk)))
(is (not (sched/scheduled? tk)))
(sched/schedule job trigger)
(is (sched/all-scheduled? jk tk))
(is (sched/scheduled? jk))
(is (sched/scheduled? tk))
(is (not (empty? (sched/get-triggers [tk]))))
(is (not (empty? (sched/get-jobs [jk]))))
(let [t (sched/get-trigger tk)
m (from-trigger t)]
(is t)
(is (:key m))
(is (:description m))
(is (:start-time m))
(is (:next-fire-time m)))
(is (sched/get-job jk))
(is (nil? (sched/get-job (j/key "<KEY>" "k28s8d77s"))))
(is (nil? (sched/get-trigger (t/key "<KEY>"))))
(is (not (empty? (sched/get-trigger-keys (m/group-equals "tests")))))
(is (not (empty? (sched/get-matching-triggers (m/group-equals "tests")))))
(is (not (empty? (sched/get-job-keys (m/group-equals "tests")))))
(is (not (empty? (sched/get-matching-jobs (m/group-equals "tests")))))
(Thread/sleep 2000)
(sched/unschedule-job tk)
(is (not (sched/all-scheduled? tk jk)))
(Thread/sleep 2000)
(is (< @counter2 7))))
;;
;; Case 3
;;
(def counter3 (atom 0))
(j/defjob JobC
[ctx]
(swap! counter3 inc))
(deftest test-manual-triggering-of-a-job-defined-using-defjob
(is (sched/started?))
(let [jk (j/key "clojurewerkz.quartzite.test.execution.job3" "tests")
tk (t/key "clojurewerkz.quartzite.test.execution.trigger3" "tests")
job (j/build
(j/of-type JobC)
(j/with-identity "clojurewerkz.quartzite.test.execution.job3" "tests"))
trigger (t/build
(t/start-now)
(t/with-identity "clojurewerkz.quartzite.test.execution.trigger3" "tests")
(t/with-schedule (s/schedule
(s/with-repeat-count 10)
(s/with-interval-in-seconds 2))))]
(sched/schedule job trigger)
(sched/trigger jk)
(Thread/sleep 500)
(is (= 2 @counter3))))
;;
;; Case 4
;;
(def value4 (atom nil))
(j/defjob JobD
[ctx]
(swap! value4 (fn [_]
(from-job-data (.getMergedJobDataMap ctx)))))
(deftest test-job-data-access
(is (sched/started?))
(let [jk (j/key "<KEY>" "tests")
tk (t/key "<KEY>" "tests")
job (j/build
(j/of-type JobD)
(j/with-identity "clojurewerkz.quartzite.test.execution.job4" "tests")
(j/using-job-data { "job-key" "job-element" }))
trigger (t/build
(t/start-now)
(t/with-identity "clojurewerkz.quartzite.test.execution.trigger4" "tests")
(t/with-schedule (s/schedule
(s/with-repeat-count 10)
(s/with-interval-in-seconds 2))))]
(sched/schedule job trigger)
(sched/trigger jk)
(Thread/sleep 1000)
(is (= "job-element" (get @value4 "job-key")))))
;;
;; Case 5
;;
(def counter5 (atom 0))
(j/defjob JobE
[ctx]
(let [i (get (from-job-data ctx) "job-key")]
(swap! counter5 + i)))
(deftest test-job-pausing-resuming-and-unscheduling
(is (sched/started?))
(let [jk (j/key "<KEY>" "tests.jobs.unscheduling")
tk (t/key "<KEY>" "tests.jobs.unscheduling")
job (j/build
(j/of-type JobE)
(j/with-identity "clojurewerkz.quartzite.test.execution.job5" "tests.triggers.unscheduling")
(j/using-job-data { "job-key" 2 }))
trigger (t/build
(t/start-now)
(t/with-identity "clojurewerkz.quartzite.test.execution.trigger5" "tests.triggers.unscheduling")
(t/with-schedule (s/schedule
(s/with-repeat-count 10)
(s/with-interval-in-seconds 1))))]
(sched/schedule job trigger)
(sched/pause-job jk)
(sched/resume-job jk)
(sched/pause-jobs (GroupMatcher/groupEquals "tests.jobs.unscheduling"))
(sched/resume-jobs (GroupMatcher/groupEquals "tests.jobs.unscheduling"))
(sched/pause-trigger tk)
(sched/resume-trigger tk)
(sched/pause-triggers (GroupMatcher/groupEquals "tests.triggers.unscheduling"))
(sched/resume-triggers (GroupMatcher/groupEquals "tests.triggers.unscheduling"))
(sched/pause-all!)
(sched/resume-all!)
(sched/unschedule-job tk)
(Thread/sleep 300)
(sched/unschedule-jobs [tk])
(sched/delete-job jk)
(sched/delete-jobs [jk])
(Thread/sleep 3000)
;; with start-now policty some executions
;; manages to get through. In part this test is supposed
;; to demonstrate it as much as test unscheduling/pausing functions. MK.
(is (< @counter5 10))))
;;
;; Case 6
;;
(def latch6 (CountDownLatch. 3))
(j/defjob JobF
[ctx]
(.countDown ^CountDownLatch latch6))
(deftest test-basic-periodic-execution-with-calendar-interval-schedule
(is (sched/started?))
(let [job (j/build
(j/of-type JobF)
(j/with-identity "clojurewerkz.quartzite.test.execution.job6" "tests"))
trigger (t/build
(t/start-now)
(t/with-schedule (calin/schedule
(calin/with-interval-in-seconds 2))))]
(sched/schedule job trigger)
(.await ^CountDownLatch latch6)))
;;
;; Case 7
;;
(def counter7 (atom 0))
(j/defjob JobG
[ctx]
(swap! counter7 inc))
(deftest test-double-scheduling
(is (sched/started?))
(let [job (j/build
(j/of-type JobG)
(j/with-identity "clojurewerkz.quartzite.test.execution.job7" "tests"))
trigger (t/build
(t/start-at (-> 2 secs from-now))
(t/with-schedule (calin/schedule
(calin/with-interval-in-seconds 2))))]
(is (sched/schedule job trigger))
;; schedule will raise an exception
(is (thrown?
org.quartz.ObjectAlreadyExistsException
(sched/schedule job trigger)))
;; but maybe-schedule will not
(is (not (sched/maybe-schedule job trigger)))
(is (not (sched/maybe-schedule job trigger)))
(is (not (sched/maybe-schedule job trigger)))
(Thread/sleep 7000)
(is (= 3 @counter7))))
| true | (ns com.novemberain.quartz-mongodb.test.quartzite-integration-test
(:use clojure.test
clojurewerkz.quartzite.conversion
[clj-time.core :only [now secs from-now]])
(:require [clojurewerkz.quartzite.scheduler :as sched]
[clojurewerkz.quartzite.jobs :as j]
[clojurewerkz.quartzite.triggers :as t]
[clojurewerkz.quartzite.matchers :as m]
[clojurewerkz.quartzite.schedule.simple :as s]
[clojurewerkz.quartzite.schedule.calendar-interval :as calin])
(:import java.util.concurrent.CountDownLatch
org.quartz.impl.matchers.GroupMatcher))
;; These are integration tests from Quartzite.
;; They do a decent job of exercising most of the underlying store operations
;; so we just reuse it here.
(sched/initialize)
(sched/start)
;;
;; Case 1
;;
(def latch1 (CountDownLatch. 10))
(defrecord JobA []
org.quartz.Job
(execute [this ctx]
(.countDown ^CountDownLatch latch1)))
(deftest test-basic-periodic-execution-with-a-job-defined-using-defrecord
(is (sched/started?))
(let [job (j/build
(j/of-type JobA)
(j/with-identity "clojurewerkz.quartzite.test.execution.job1" "tests"))
trigger (t/build
(t/start-now)
(t/with-schedule (s/schedule
(s/with-repeat-count 10)
(s/with-interval-in-milliseconds 200))))]
(sched/schedule job trigger)
(let [j (sched/get-job (j/key "clojurewerkz.quartzite.test.execution.job1" "tests"))
m (from-job-detail j)]
(is j)
(is (:key m))
(is (nil? (:description m)))
(is (:job-data m)))
(.await ^CountDownLatch latch1)))
;;
;; Case 2
;;
(def counter2 (atom 0))
(j/defjob JobB
[ctx]
(swap! counter2 inc))
(deftest test-unscheduling-of-a-job-defined-using-defjob
(is (sched/started?))
(let [jk (j/key "PI:KEY:<KEY>END_PI" "tests")
tk (t/key "PI:KEY:<KEY>END_PI" "tests")
job (j/build
(j/of-type JobB)
(j/with-identity "clojurewerkz.quartzite.test.execution.job2" "tests"))
trigger (t/build
(t/start-now)
(t/with-identity "clojurewerkz.quartzite.test.execution.trigger2" "tests")
(t/with-description "just a trigger")
(t/with-schedule (s/schedule
(s/with-repeat-count 10)
(s/with-interval-in-milliseconds 400))))]
(is (not (sched/all-scheduled? jk tk)))
(is (not (sched/scheduled? jk)))
(is (not (sched/scheduled? tk)))
(sched/schedule job trigger)
(is (sched/all-scheduled? jk tk))
(is (sched/scheduled? jk))
(is (sched/scheduled? tk))
(is (not (empty? (sched/get-triggers [tk]))))
(is (not (empty? (sched/get-jobs [jk]))))
(let [t (sched/get-trigger tk)
m (from-trigger t)]
(is t)
(is (:key m))
(is (:description m))
(is (:start-time m))
(is (:next-fire-time m)))
(is (sched/get-job jk))
(is (nil? (sched/get-job (j/key "PI:KEY:<KEY>END_PI" "k28s8d77s"))))
(is (nil? (sched/get-trigger (t/key "PI:KEY:<KEY>END_PI"))))
(is (not (empty? (sched/get-trigger-keys (m/group-equals "tests")))))
(is (not (empty? (sched/get-matching-triggers (m/group-equals "tests")))))
(is (not (empty? (sched/get-job-keys (m/group-equals "tests")))))
(is (not (empty? (sched/get-matching-jobs (m/group-equals "tests")))))
(Thread/sleep 2000)
(sched/unschedule-job tk)
(is (not (sched/all-scheduled? tk jk)))
(Thread/sleep 2000)
(is (< @counter2 7))))
;;
;; Case 3
;;
(def counter3 (atom 0))
(j/defjob JobC
[ctx]
(swap! counter3 inc))
(deftest test-manual-triggering-of-a-job-defined-using-defjob
(is (sched/started?))
(let [jk (j/key "clojurewerkz.quartzite.test.execution.job3" "tests")
tk (t/key "clojurewerkz.quartzite.test.execution.trigger3" "tests")
job (j/build
(j/of-type JobC)
(j/with-identity "clojurewerkz.quartzite.test.execution.job3" "tests"))
trigger (t/build
(t/start-now)
(t/with-identity "clojurewerkz.quartzite.test.execution.trigger3" "tests")
(t/with-schedule (s/schedule
(s/with-repeat-count 10)
(s/with-interval-in-seconds 2))))]
(sched/schedule job trigger)
(sched/trigger jk)
(Thread/sleep 500)
(is (= 2 @counter3))))
;;
;; Case 4
;;
(def value4 (atom nil))
(j/defjob JobD
[ctx]
(swap! value4 (fn [_]
(from-job-data (.getMergedJobDataMap ctx)))))
(deftest test-job-data-access
(is (sched/started?))
(let [jk (j/key "PI:KEY:<KEY>END_PI" "tests")
tk (t/key "PI:KEY:<KEY>END_PI" "tests")
job (j/build
(j/of-type JobD)
(j/with-identity "clojurewerkz.quartzite.test.execution.job4" "tests")
(j/using-job-data { "job-key" "job-element" }))
trigger (t/build
(t/start-now)
(t/with-identity "clojurewerkz.quartzite.test.execution.trigger4" "tests")
(t/with-schedule (s/schedule
(s/with-repeat-count 10)
(s/with-interval-in-seconds 2))))]
(sched/schedule job trigger)
(sched/trigger jk)
(Thread/sleep 1000)
(is (= "job-element" (get @value4 "job-key")))))
;;
;; Case 5
;;
(def counter5 (atom 0))
(j/defjob JobE
[ctx]
(let [i (get (from-job-data ctx) "job-key")]
(swap! counter5 + i)))
(deftest test-job-pausing-resuming-and-unscheduling
(is (sched/started?))
(let [jk (j/key "PI:KEY:<KEY>END_PI" "tests.jobs.unscheduling")
tk (t/key "PI:KEY:<KEY>END_PI" "tests.jobs.unscheduling")
job (j/build
(j/of-type JobE)
(j/with-identity "clojurewerkz.quartzite.test.execution.job5" "tests.triggers.unscheduling")
(j/using-job-data { "job-key" 2 }))
trigger (t/build
(t/start-now)
(t/with-identity "clojurewerkz.quartzite.test.execution.trigger5" "tests.triggers.unscheduling")
(t/with-schedule (s/schedule
(s/with-repeat-count 10)
(s/with-interval-in-seconds 1))))]
(sched/schedule job trigger)
(sched/pause-job jk)
(sched/resume-job jk)
(sched/pause-jobs (GroupMatcher/groupEquals "tests.jobs.unscheduling"))
(sched/resume-jobs (GroupMatcher/groupEquals "tests.jobs.unscheduling"))
(sched/pause-trigger tk)
(sched/resume-trigger tk)
(sched/pause-triggers (GroupMatcher/groupEquals "tests.triggers.unscheduling"))
(sched/resume-triggers (GroupMatcher/groupEquals "tests.triggers.unscheduling"))
(sched/pause-all!)
(sched/resume-all!)
(sched/unschedule-job tk)
(Thread/sleep 300)
(sched/unschedule-jobs [tk])
(sched/delete-job jk)
(sched/delete-jobs [jk])
(Thread/sleep 3000)
;; with start-now policty some executions
;; manages to get through. In part this test is supposed
;; to demonstrate it as much as test unscheduling/pausing functions. MK.
(is (< @counter5 10))))
;;
;; Case 6
;;
(def latch6 (CountDownLatch. 3))
(j/defjob JobF
[ctx]
(.countDown ^CountDownLatch latch6))
(deftest test-basic-periodic-execution-with-calendar-interval-schedule
(is (sched/started?))
(let [job (j/build
(j/of-type JobF)
(j/with-identity "clojurewerkz.quartzite.test.execution.job6" "tests"))
trigger (t/build
(t/start-now)
(t/with-schedule (calin/schedule
(calin/with-interval-in-seconds 2))))]
(sched/schedule job trigger)
(.await ^CountDownLatch latch6)))
;;
;; Case 7
;;
(def counter7 (atom 0))
(j/defjob JobG
[ctx]
(swap! counter7 inc))
(deftest test-double-scheduling
(is (sched/started?))
(let [job (j/build
(j/of-type JobG)
(j/with-identity "clojurewerkz.quartzite.test.execution.job7" "tests"))
trigger (t/build
(t/start-at (-> 2 secs from-now))
(t/with-schedule (calin/schedule
(calin/with-interval-in-seconds 2))))]
(is (sched/schedule job trigger))
;; schedule will raise an exception
(is (thrown?
org.quartz.ObjectAlreadyExistsException
(sched/schedule job trigger)))
;; but maybe-schedule will not
(is (not (sched/maybe-schedule job trigger)))
(is (not (sched/maybe-schedule job trigger)))
(is (not (sched/maybe-schedule job trigger)))
(Thread/sleep 7000)
(is (= 3 @counter7))))
|
[
{
"context": "(ns ^{:author \"Kadir Malak\"}\n infixxer.core)\n\n(def ops\n {\"u!\" {:precedence",
"end": 26,
"score": 0.9998180866241455,
"start": 15,
"tag": "NAME",
"value": "Kadir Malak"
}
] | src/infixxer/core.clj | kadirmalak/infixxer | 0 | (ns ^{:author "Kadir Malak"}
infixxer.core)
(def ops
{"u!" {:precedence 13 :alias `not}
"u+" {:precedence 13}
"u-" {:precedence 13}
"/" {:precedence 12}
"*" {:precedence 12}
"**" {:precedence 12 :alias `Math/pow}
"%" {:precedence 12 :alias `mod}
"+" {:precedence 11}
"-" {:precedence 11}
"<" {:precedence 9}
"<=" {:precedence 9}
">" {:precedence 9}
">=" {:precedence 9}
"==" {:precedence 8 :alias `=}
"!=" {:precedence 8 :alias `not=}
"&" {:precedence 7 :alias `bit-and}
"|" {:precedence 5 :alias `bit-or}
"&&" {:precedence 4 :alias `and}
"||" {:precedence 3 :alias `or}
})
(defn remove-at [v i]
(let [len (count v)]
(if (or (< i 0) (>= i len))
v
(into [] (concat (subvec v 0 i)
(subvec v (inc i) len))))))
(defn group-with-next-at [v i]
(let [sub (subvec v i (+ 2 i))]
(-> v
(remove-at (inc i))
(assoc i (apply list sub)))))
(defn tokenize [el]
(cond
(contains? ops (str el)) :op
(contains? ops (str "u" el)) :op
:else :other))
(defn add-unary-parentheses [expr]
(let [tokens (map tokenize expr)
padded (conj tokens :op)
triplets (partition 3 1 padded)
op-op-other? (fn [i el] (if (= el '(:op :op :other)) i))
indices (keep-indexed op-op-other? triplets)]
(if (empty? indices)
{:expr expr :changed false}
(if (and (= 1 (count indices))
(= 2 (count expr)))
{:expr expr :changed false}
; loop in reverse order because size changes at each iteration
(loop [expr (vec expr)
indices (reverse indices)]
(if (empty? indices)
{:expr (apply list expr) :changed true}
(let [i (first indices)
indices (rest indices)
expr (group-with-next-at expr i)]
(recur expr indices))))))))
(defn add-all-unary-parentheses [expr]
(loop [expr expr]
(let [{:keys [expr changed]} (add-unary-parentheses expr)]
(if changed
(recur expr)
expr))))
(defn choose-op [candidates]
(let [table (into [] (map-indexed
(fn [i op]
{:op op
:index i
:precedence (-> ops
(get (str op) {})
(:precedence 0))})
candidates))
max-precedence (apply max (map :precedence table))]
(first (filter
#(= max-precedence (:precedence %))
table))))
(defn add-binary-parentheses [expr]
(let [triplets (map vec (partition 3 2 expr))
n (count triplets)]
(if (< n 2)
{:expr expr :changed false}
(let [candidates (map second triplets)
idx (:index (choose-op candidates))
parts (map-indexed
(fn [i triplet]
(cond
(< i idx) (subvec triplet 0 2) ; [a b]
(= i idx) [(apply list triplet)] ; [(a b c)]
(> i idx) (subvec triplet 1 3))) ; [b c]
triplets)]
{:expr (apply concat parts) :changed true}))))
(defn add-all-binary-parentheses [expr]
(loop [expr expr]
(let [{:keys [expr changed]} (add-binary-parentheses expr)]
(if changed
(recur expr)
expr))))
(defn add-all-parentheses [expr]
(if (seq? expr)
(if (= 'fn* (first expr))
expr
(->> expr
(map add-all-parentheses)
(add-all-unary-parentheses)
(add-all-binary-parentheses)))
expr))
(defn reorder-and-replace [expr]
(let [[x & _] expr]
(if (= 'fn* x)
(nth expr 2) ; just take the body
(condp = (count expr)
1 (let [[x] expr]
(if (seq? x) (reorder-and-replace x) x))
2 (let [[op x] expr
op (-> ops
(get (str "u" op) {})
(:alias op))
x (if (seq? x) (reorder-and-replace x) x)]
(list op x))
3 (let [[x op y] expr
op (-> ops
(get (str op) {})
(:alias op))
x (if (seq? x) (reorder-and-replace x) x)
y (if (seq? y) (reorder-and-replace y) y)]
(list op x y))
(throw (new Exception (str "wrong number of elements: " (count expr))))))))
(defn convert [expr]
(-> expr
(add-all-parentheses)
(reorder-and-replace)))
(defmacro $= [& expr]
(convert expr))
| 97742 | (ns ^{:author "<NAME>"}
infixxer.core)
(def ops
{"u!" {:precedence 13 :alias `not}
"u+" {:precedence 13}
"u-" {:precedence 13}
"/" {:precedence 12}
"*" {:precedence 12}
"**" {:precedence 12 :alias `Math/pow}
"%" {:precedence 12 :alias `mod}
"+" {:precedence 11}
"-" {:precedence 11}
"<" {:precedence 9}
"<=" {:precedence 9}
">" {:precedence 9}
">=" {:precedence 9}
"==" {:precedence 8 :alias `=}
"!=" {:precedence 8 :alias `not=}
"&" {:precedence 7 :alias `bit-and}
"|" {:precedence 5 :alias `bit-or}
"&&" {:precedence 4 :alias `and}
"||" {:precedence 3 :alias `or}
})
(defn remove-at [v i]
(let [len (count v)]
(if (or (< i 0) (>= i len))
v
(into [] (concat (subvec v 0 i)
(subvec v (inc i) len))))))
(defn group-with-next-at [v i]
(let [sub (subvec v i (+ 2 i))]
(-> v
(remove-at (inc i))
(assoc i (apply list sub)))))
(defn tokenize [el]
(cond
(contains? ops (str el)) :op
(contains? ops (str "u" el)) :op
:else :other))
(defn add-unary-parentheses [expr]
(let [tokens (map tokenize expr)
padded (conj tokens :op)
triplets (partition 3 1 padded)
op-op-other? (fn [i el] (if (= el '(:op :op :other)) i))
indices (keep-indexed op-op-other? triplets)]
(if (empty? indices)
{:expr expr :changed false}
(if (and (= 1 (count indices))
(= 2 (count expr)))
{:expr expr :changed false}
; loop in reverse order because size changes at each iteration
(loop [expr (vec expr)
indices (reverse indices)]
(if (empty? indices)
{:expr (apply list expr) :changed true}
(let [i (first indices)
indices (rest indices)
expr (group-with-next-at expr i)]
(recur expr indices))))))))
(defn add-all-unary-parentheses [expr]
(loop [expr expr]
(let [{:keys [expr changed]} (add-unary-parentheses expr)]
(if changed
(recur expr)
expr))))
(defn choose-op [candidates]
(let [table (into [] (map-indexed
(fn [i op]
{:op op
:index i
:precedence (-> ops
(get (str op) {})
(:precedence 0))})
candidates))
max-precedence (apply max (map :precedence table))]
(first (filter
#(= max-precedence (:precedence %))
table))))
(defn add-binary-parentheses [expr]
(let [triplets (map vec (partition 3 2 expr))
n (count triplets)]
(if (< n 2)
{:expr expr :changed false}
(let [candidates (map second triplets)
idx (:index (choose-op candidates))
parts (map-indexed
(fn [i triplet]
(cond
(< i idx) (subvec triplet 0 2) ; [a b]
(= i idx) [(apply list triplet)] ; [(a b c)]
(> i idx) (subvec triplet 1 3))) ; [b c]
triplets)]
{:expr (apply concat parts) :changed true}))))
(defn add-all-binary-parentheses [expr]
(loop [expr expr]
(let [{:keys [expr changed]} (add-binary-parentheses expr)]
(if changed
(recur expr)
expr))))
(defn add-all-parentheses [expr]
(if (seq? expr)
(if (= 'fn* (first expr))
expr
(->> expr
(map add-all-parentheses)
(add-all-unary-parentheses)
(add-all-binary-parentheses)))
expr))
(defn reorder-and-replace [expr]
(let [[x & _] expr]
(if (= 'fn* x)
(nth expr 2) ; just take the body
(condp = (count expr)
1 (let [[x] expr]
(if (seq? x) (reorder-and-replace x) x))
2 (let [[op x] expr
op (-> ops
(get (str "u" op) {})
(:alias op))
x (if (seq? x) (reorder-and-replace x) x)]
(list op x))
3 (let [[x op y] expr
op (-> ops
(get (str op) {})
(:alias op))
x (if (seq? x) (reorder-and-replace x) x)
y (if (seq? y) (reorder-and-replace y) y)]
(list op x y))
(throw (new Exception (str "wrong number of elements: " (count expr))))))))
(defn convert [expr]
(-> expr
(add-all-parentheses)
(reorder-and-replace)))
(defmacro $= [& expr]
(convert expr))
| true | (ns ^{:author "PI:NAME:<NAME>END_PI"}
infixxer.core)
(def ops
{"u!" {:precedence 13 :alias `not}
"u+" {:precedence 13}
"u-" {:precedence 13}
"/" {:precedence 12}
"*" {:precedence 12}
"**" {:precedence 12 :alias `Math/pow}
"%" {:precedence 12 :alias `mod}
"+" {:precedence 11}
"-" {:precedence 11}
"<" {:precedence 9}
"<=" {:precedence 9}
">" {:precedence 9}
">=" {:precedence 9}
"==" {:precedence 8 :alias `=}
"!=" {:precedence 8 :alias `not=}
"&" {:precedence 7 :alias `bit-and}
"|" {:precedence 5 :alias `bit-or}
"&&" {:precedence 4 :alias `and}
"||" {:precedence 3 :alias `or}
})
(defn remove-at [v i]
(let [len (count v)]
(if (or (< i 0) (>= i len))
v
(into [] (concat (subvec v 0 i)
(subvec v (inc i) len))))))
(defn group-with-next-at [v i]
(let [sub (subvec v i (+ 2 i))]
(-> v
(remove-at (inc i))
(assoc i (apply list sub)))))
(defn tokenize [el]
(cond
(contains? ops (str el)) :op
(contains? ops (str "u" el)) :op
:else :other))
(defn add-unary-parentheses [expr]
(let [tokens (map tokenize expr)
padded (conj tokens :op)
triplets (partition 3 1 padded)
op-op-other? (fn [i el] (if (= el '(:op :op :other)) i))
indices (keep-indexed op-op-other? triplets)]
(if (empty? indices)
{:expr expr :changed false}
(if (and (= 1 (count indices))
(= 2 (count expr)))
{:expr expr :changed false}
; loop in reverse order because size changes at each iteration
(loop [expr (vec expr)
indices (reverse indices)]
(if (empty? indices)
{:expr (apply list expr) :changed true}
(let [i (first indices)
indices (rest indices)
expr (group-with-next-at expr i)]
(recur expr indices))))))))
(defn add-all-unary-parentheses [expr]
(loop [expr expr]
(let [{:keys [expr changed]} (add-unary-parentheses expr)]
(if changed
(recur expr)
expr))))
(defn choose-op [candidates]
(let [table (into [] (map-indexed
(fn [i op]
{:op op
:index i
:precedence (-> ops
(get (str op) {})
(:precedence 0))})
candidates))
max-precedence (apply max (map :precedence table))]
(first (filter
#(= max-precedence (:precedence %))
table))))
(defn add-binary-parentheses [expr]
(let [triplets (map vec (partition 3 2 expr))
n (count triplets)]
(if (< n 2)
{:expr expr :changed false}
(let [candidates (map second triplets)
idx (:index (choose-op candidates))
parts (map-indexed
(fn [i triplet]
(cond
(< i idx) (subvec triplet 0 2) ; [a b]
(= i idx) [(apply list triplet)] ; [(a b c)]
(> i idx) (subvec triplet 1 3))) ; [b c]
triplets)]
{:expr (apply concat parts) :changed true}))))
(defn add-all-binary-parentheses [expr]
(loop [expr expr]
(let [{:keys [expr changed]} (add-binary-parentheses expr)]
(if changed
(recur expr)
expr))))
(defn add-all-parentheses [expr]
(if (seq? expr)
(if (= 'fn* (first expr))
expr
(->> expr
(map add-all-parentheses)
(add-all-unary-parentheses)
(add-all-binary-parentheses)))
expr))
(defn reorder-and-replace [expr]
(let [[x & _] expr]
(if (= 'fn* x)
(nth expr 2) ; just take the body
(condp = (count expr)
1 (let [[x] expr]
(if (seq? x) (reorder-and-replace x) x))
2 (let [[op x] expr
op (-> ops
(get (str "u" op) {})
(:alias op))
x (if (seq? x) (reorder-and-replace x) x)]
(list op x))
3 (let [[x op y] expr
op (-> ops
(get (str op) {})
(:alias op))
x (if (seq? x) (reorder-and-replace x) x)
y (if (seq? y) (reorder-and-replace y) y)]
(list op x y))
(throw (new Exception (str "wrong number of elements: " (count expr))))))))
(defn convert [expr]
(-> expr
(add-all-parentheses)
(reorder-and-replace)))
(defmacro $= [& expr]
(convert expr))
|
[
{
"context": " :as jdbc]))\n\n(def config\n {:port 8080\n :bind \"127.0.0.1\"\n :db {:classname \"org.sqlite.JDBC\"\n :su",
"end": 163,
"score": 0.9950847625732422,
"start": 154,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "(find-location-by-name {:name \"Mercure\"})) :name \"Mercury\"})\n (insert-location! {:name \"Paddington\"})\n",
"end": 756,
"score": 0.5761852264404297,
"start": 753,
"tag": "NAME",
"value": "Mer"
},
{
"context": "})) :name \"Mercury\"})\n (insert-location! {:name \"Paddington\"})\n (delete-location! {:id (:id (find-locatio",
"end": 799,
"score": 0.8204615116119385,
"start": 792,
"tag": "NAME",
"value": "Padding"
},
{
"context": "ocation! {:id (:id (find-location-by-name {:name \"Paddington\"}))})\n (find-location-by-name {:name \"Mercure\"})",
"end": 877,
"score": 0.7382157444953918,
"start": 867,
"tag": "NAME",
"value": "Paddington"
}
] | practice/living-clojure/training-plan/src/training_plan/week7/core.clj | tomjkidd/clojure | 1 | (ns training-plan.week7.core
(:require [yesql.core :refer [defqueries]]
[clojure.java.jdbc :as jdbc]))
(def config
{:port 8080
:bind "127.0.0.1"
:db {:classname "org.sqlite.JDBC"
:subprotocol "sqlite"
:subname "data/db.sqlite"}})
(def db-spec
(:db config))
(defqueries "../resources/sqlite-init.sql"
{:connection db-spec})
(defqueries "../resources/sqlite-queryfile.sql"
{:connection db-spec})
(defn test-queries
"TODO: Put this into a unit testable format, these were used in the repl to make sure that the function calls worked through yesql as advertised."
[]
(get-locations)
(insert-location! {:name "Mercure"})
(update-location! {:id (:id (find-location-by-name {:name "Mercure"})) :name "Mercury"})
(insert-location! {:name "Paddington"})
(delete-location! {:id (:id (find-location-by-name {:name "Paddington"}))})
(find-location-by-name {:name "Mercure"})
(get-locations))
| 26763 | (ns training-plan.week7.core
(:require [yesql.core :refer [defqueries]]
[clojure.java.jdbc :as jdbc]))
(def config
{:port 8080
:bind "127.0.0.1"
:db {:classname "org.sqlite.JDBC"
:subprotocol "sqlite"
:subname "data/db.sqlite"}})
(def db-spec
(:db config))
(defqueries "../resources/sqlite-init.sql"
{:connection db-spec})
(defqueries "../resources/sqlite-queryfile.sql"
{:connection db-spec})
(defn test-queries
"TODO: Put this into a unit testable format, these were used in the repl to make sure that the function calls worked through yesql as advertised."
[]
(get-locations)
(insert-location! {:name "Mercure"})
(update-location! {:id (:id (find-location-by-name {:name "Mercure"})) :name "<NAME>cury"})
(insert-location! {:name "<NAME>ton"})
(delete-location! {:id (:id (find-location-by-name {:name "<NAME>"}))})
(find-location-by-name {:name "Mercure"})
(get-locations))
| true | (ns training-plan.week7.core
(:require [yesql.core :refer [defqueries]]
[clojure.java.jdbc :as jdbc]))
(def config
{:port 8080
:bind "127.0.0.1"
:db {:classname "org.sqlite.JDBC"
:subprotocol "sqlite"
:subname "data/db.sqlite"}})
(def db-spec
(:db config))
(defqueries "../resources/sqlite-init.sql"
{:connection db-spec})
(defqueries "../resources/sqlite-queryfile.sql"
{:connection db-spec})
(defn test-queries
"TODO: Put this into a unit testable format, these were used in the repl to make sure that the function calls worked through yesql as advertised."
[]
(get-locations)
(insert-location! {:name "Mercure"})
(update-location! {:id (:id (find-location-by-name {:name "Mercure"})) :name "PI:NAME:<NAME>END_PIcury"})
(insert-location! {:name "PI:NAME:<NAME>END_PIton"})
(delete-location! {:id (:id (find-location-by-name {:name "PI:NAME:<NAME>END_PI"}))})
(find-location-by-name {:name "Mercure"})
(get-locations))
|
[
{
"context": ";; Copyright (c) Metail and Thomas Athorne\n;;\n;; Licensed under the Apa",
"end": 25,
"score": 0.9894534945487976,
"start": 19,
"tag": "NAME",
"value": "Metail"
},
{
"context": ";; Copyright (c) Metail and Thomas Athorne\n;;\n;; Licensed under the Apache License, Versio",
"end": 44,
"score": 0.9998719096183777,
"start": 30,
"tag": "NAME",
"value": "Thomas Athorne"
}
] | src/clj_stan/core.clj | thomasathorne/clj-stan | 14 | ;; Copyright (c) Metail and Thomas Athorne
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns clj-stan.core
(:require [clj-stan.r-dump-format :as r-dump]
[clj-stan.read-output :as output]
[me.raynes.conch :as conch]
[environ.core :refer [env]]
[pandect.algo.sha256 :refer [sha256]]
[clojure.java.io :as io]))
(defn execute
[& args]
(try (apply conch/execute args)
(catch Exception e
(run! println (:err (:proc (.data e))))
(run! println (:out (:proc (.data e))))
(throw e))))
(defprotocol Model
(sample [this data-map] [this data-map params])
(optimize [this data-map] [this data-map params])
(variational [this data-map algorithm] [this data-map algorithm params]))
(defn tmp-dir
[]
(let [d (io/file (str (System/getProperty "java.io.tmpdir") "/"
(System/currentTimeMillis) "-" (rand-int 1000000)))]
(.mkdir d)
d))
(defrecord CompiledModel [executable]
Model
(sample [this data-map] (sample this data-map {}))
(sample [this data-map {:keys [chains chain-length seed]
:or {chains 5 chain-length 2000 seed -1}}]
(let [t (tmp-dir)]
(r-dump/r-dump (str t "/tmp-data.R") data-map)
(let [procs (mapv #(conch/execute executable "sample"
(str "num_samples=" chain-length)
"random" (str "seed=" seed)
"data" (str "file=" t "/tmp-data.R")
"output" (str "file=" t "/output-" % ".csv")
{:background true})
(range chains))]
(mapv deref procs)
(into []
(mapcat #(output/read-stan-output (str t "/output-" % ".csv")))
(range chains)))))
(optimize [this data-map] (optimize this data-map {}))
(optimize [this data-map {:keys [seed] :or {seed -1}}]
(let [t (tmp-dir)]
(r-dump/r-dump (str t "/tmp-data.R") data-map)
(execute executable "optimize"
"random" (str "seed=" seed)
"data" (str "file=" t "/tmp-data.R")
"output" (str "file=" t "/output.csv"))
(first (output/read-stan-output (str t "/output.csv")))))
(variational [this data-map algorithm] (variational this data-map algorithm {}))
(variational [this data-map algorithm {:keys [seed samples] :or {seed -1 samples 1000}}]
(let [t (tmp-dir)]
(r-dump/r-dump (str t "/tmp-data.R") data-map)
(execute executable "variational"
(str "algorithm=" algorithm)
(str "output_samples=" samples)
"random" (str "seed=" seed)
"data" (str "file=" t "/tmp-data.R")
"output" (str "file=" t "/output.csv"))
(let [[mode & samples] (output/read-stan-output (str t "/output.csv"))]
{:mode mode
:samples samples}))))
(defn lib
[path lib-name]
(first (filter (fn [s]
(.startsWith s (str path lib-name "_")))
(map str (.listFiles (io/file path))))))
(defn make
[model]
(let [text (slurp model)
hash (sha256 text)
exe (str "target/clj-stan/_" hash)
_ (io/make-parents exe)]
(when (not (.exists (io/file exe)))
(let [home (or (env :stan-home)
(throw (Exception. "STAN_HOME environment variable is not set.
See `clj-stan` documentation.")))
model-file (str exe ".stan")
hpp-file (str exe ".hpp")
lib-path (str home "/stan/lib/stan_math/lib/")]
(spit model-file text)
(println (format "Compiling %s to C++." model))
(execute (str home "/bin/stanc") model-file (str "--o=" hpp-file))
(println (format "Compiling C++ for %s into executable." model))
(execute "g++"
"-I" home "-I" (str home "/src")
"-isystem" (str home "/stan/src")
"-isystem" (str home "/stan/lib/stan_math/")
"-isystem" (lib lib-path "eigen")
"-isystem" (lib lib-path "boost")
"-isystem" (str (lib lib-path "sundials") "/include")
"-std=c++1y" "-Wall"
"-DEIGEN_NO_DEBUG" "-DBOOST_RESULT_OF_USE_TR1" "-DBOOST_NO_DECLTYPE"
"-DBOOST_DISABLE_ASSERTS" "-DBOOST_PHOENIX_NO_VARIADIC_EXPRESSION"
"-DFUSION_MAX_VECTOR_SIZE=12" "-DNO_FPRINTF_OUTPUT"
"-Wno-unused-function" "-Wno-uninitialized" "-Wno-unused-local-typedefs"
"-pipe" "-O3" "-o" exe (str home "/src/cmdstan/main.cpp")
"-include" hpp-file
(str (lib lib-path "sundials") "/lib/libsundials_nvecserial.a")
(str (lib lib-path "sundials") "/lib/libsundials_cvodes.a")
(str (lib lib-path "sundials") "/lib/libsundials_idas.a"))))
(->CompiledModel exe)))
| 44590 | ;; Copyright (c) <NAME> and <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 clj-stan.core
(:require [clj-stan.r-dump-format :as r-dump]
[clj-stan.read-output :as output]
[me.raynes.conch :as conch]
[environ.core :refer [env]]
[pandect.algo.sha256 :refer [sha256]]
[clojure.java.io :as io]))
(defn execute
[& args]
(try (apply conch/execute args)
(catch Exception e
(run! println (:err (:proc (.data e))))
(run! println (:out (:proc (.data e))))
(throw e))))
(defprotocol Model
(sample [this data-map] [this data-map params])
(optimize [this data-map] [this data-map params])
(variational [this data-map algorithm] [this data-map algorithm params]))
(defn tmp-dir
[]
(let [d (io/file (str (System/getProperty "java.io.tmpdir") "/"
(System/currentTimeMillis) "-" (rand-int 1000000)))]
(.mkdir d)
d))
(defrecord CompiledModel [executable]
Model
(sample [this data-map] (sample this data-map {}))
(sample [this data-map {:keys [chains chain-length seed]
:or {chains 5 chain-length 2000 seed -1}}]
(let [t (tmp-dir)]
(r-dump/r-dump (str t "/tmp-data.R") data-map)
(let [procs (mapv #(conch/execute executable "sample"
(str "num_samples=" chain-length)
"random" (str "seed=" seed)
"data" (str "file=" t "/tmp-data.R")
"output" (str "file=" t "/output-" % ".csv")
{:background true})
(range chains))]
(mapv deref procs)
(into []
(mapcat #(output/read-stan-output (str t "/output-" % ".csv")))
(range chains)))))
(optimize [this data-map] (optimize this data-map {}))
(optimize [this data-map {:keys [seed] :or {seed -1}}]
(let [t (tmp-dir)]
(r-dump/r-dump (str t "/tmp-data.R") data-map)
(execute executable "optimize"
"random" (str "seed=" seed)
"data" (str "file=" t "/tmp-data.R")
"output" (str "file=" t "/output.csv"))
(first (output/read-stan-output (str t "/output.csv")))))
(variational [this data-map algorithm] (variational this data-map algorithm {}))
(variational [this data-map algorithm {:keys [seed samples] :or {seed -1 samples 1000}}]
(let [t (tmp-dir)]
(r-dump/r-dump (str t "/tmp-data.R") data-map)
(execute executable "variational"
(str "algorithm=" algorithm)
(str "output_samples=" samples)
"random" (str "seed=" seed)
"data" (str "file=" t "/tmp-data.R")
"output" (str "file=" t "/output.csv"))
(let [[mode & samples] (output/read-stan-output (str t "/output.csv"))]
{:mode mode
:samples samples}))))
(defn lib
[path lib-name]
(first (filter (fn [s]
(.startsWith s (str path lib-name "_")))
(map str (.listFiles (io/file path))))))
(defn make
[model]
(let [text (slurp model)
hash (sha256 text)
exe (str "target/clj-stan/_" hash)
_ (io/make-parents exe)]
(when (not (.exists (io/file exe)))
(let [home (or (env :stan-home)
(throw (Exception. "STAN_HOME environment variable is not set.
See `clj-stan` documentation.")))
model-file (str exe ".stan")
hpp-file (str exe ".hpp")
lib-path (str home "/stan/lib/stan_math/lib/")]
(spit model-file text)
(println (format "Compiling %s to C++." model))
(execute (str home "/bin/stanc") model-file (str "--o=" hpp-file))
(println (format "Compiling C++ for %s into executable." model))
(execute "g++"
"-I" home "-I" (str home "/src")
"-isystem" (str home "/stan/src")
"-isystem" (str home "/stan/lib/stan_math/")
"-isystem" (lib lib-path "eigen")
"-isystem" (lib lib-path "boost")
"-isystem" (str (lib lib-path "sundials") "/include")
"-std=c++1y" "-Wall"
"-DEIGEN_NO_DEBUG" "-DBOOST_RESULT_OF_USE_TR1" "-DBOOST_NO_DECLTYPE"
"-DBOOST_DISABLE_ASSERTS" "-DBOOST_PHOENIX_NO_VARIADIC_EXPRESSION"
"-DFUSION_MAX_VECTOR_SIZE=12" "-DNO_FPRINTF_OUTPUT"
"-Wno-unused-function" "-Wno-uninitialized" "-Wno-unused-local-typedefs"
"-pipe" "-O3" "-o" exe (str home "/src/cmdstan/main.cpp")
"-include" hpp-file
(str (lib lib-path "sundials") "/lib/libsundials_nvecserial.a")
(str (lib lib-path "sundials") "/lib/libsundials_cvodes.a")
(str (lib lib-path "sundials") "/lib/libsundials_idas.a"))))
(->CompiledModel exe)))
| true | ;; Copyright (c) PI:NAME:<NAME>END_PI and 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 clj-stan.core
(:require [clj-stan.r-dump-format :as r-dump]
[clj-stan.read-output :as output]
[me.raynes.conch :as conch]
[environ.core :refer [env]]
[pandect.algo.sha256 :refer [sha256]]
[clojure.java.io :as io]))
(defn execute
[& args]
(try (apply conch/execute args)
(catch Exception e
(run! println (:err (:proc (.data e))))
(run! println (:out (:proc (.data e))))
(throw e))))
(defprotocol Model
(sample [this data-map] [this data-map params])
(optimize [this data-map] [this data-map params])
(variational [this data-map algorithm] [this data-map algorithm params]))
(defn tmp-dir
[]
(let [d (io/file (str (System/getProperty "java.io.tmpdir") "/"
(System/currentTimeMillis) "-" (rand-int 1000000)))]
(.mkdir d)
d))
(defrecord CompiledModel [executable]
Model
(sample [this data-map] (sample this data-map {}))
(sample [this data-map {:keys [chains chain-length seed]
:or {chains 5 chain-length 2000 seed -1}}]
(let [t (tmp-dir)]
(r-dump/r-dump (str t "/tmp-data.R") data-map)
(let [procs (mapv #(conch/execute executable "sample"
(str "num_samples=" chain-length)
"random" (str "seed=" seed)
"data" (str "file=" t "/tmp-data.R")
"output" (str "file=" t "/output-" % ".csv")
{:background true})
(range chains))]
(mapv deref procs)
(into []
(mapcat #(output/read-stan-output (str t "/output-" % ".csv")))
(range chains)))))
(optimize [this data-map] (optimize this data-map {}))
(optimize [this data-map {:keys [seed] :or {seed -1}}]
(let [t (tmp-dir)]
(r-dump/r-dump (str t "/tmp-data.R") data-map)
(execute executable "optimize"
"random" (str "seed=" seed)
"data" (str "file=" t "/tmp-data.R")
"output" (str "file=" t "/output.csv"))
(first (output/read-stan-output (str t "/output.csv")))))
(variational [this data-map algorithm] (variational this data-map algorithm {}))
(variational [this data-map algorithm {:keys [seed samples] :or {seed -1 samples 1000}}]
(let [t (tmp-dir)]
(r-dump/r-dump (str t "/tmp-data.R") data-map)
(execute executable "variational"
(str "algorithm=" algorithm)
(str "output_samples=" samples)
"random" (str "seed=" seed)
"data" (str "file=" t "/tmp-data.R")
"output" (str "file=" t "/output.csv"))
(let [[mode & samples] (output/read-stan-output (str t "/output.csv"))]
{:mode mode
:samples samples}))))
(defn lib
[path lib-name]
(first (filter (fn [s]
(.startsWith s (str path lib-name "_")))
(map str (.listFiles (io/file path))))))
(defn make
[model]
(let [text (slurp model)
hash (sha256 text)
exe (str "target/clj-stan/_" hash)
_ (io/make-parents exe)]
(when (not (.exists (io/file exe)))
(let [home (or (env :stan-home)
(throw (Exception. "STAN_HOME environment variable is not set.
See `clj-stan` documentation.")))
model-file (str exe ".stan")
hpp-file (str exe ".hpp")
lib-path (str home "/stan/lib/stan_math/lib/")]
(spit model-file text)
(println (format "Compiling %s to C++." model))
(execute (str home "/bin/stanc") model-file (str "--o=" hpp-file))
(println (format "Compiling C++ for %s into executable." model))
(execute "g++"
"-I" home "-I" (str home "/src")
"-isystem" (str home "/stan/src")
"-isystem" (str home "/stan/lib/stan_math/")
"-isystem" (lib lib-path "eigen")
"-isystem" (lib lib-path "boost")
"-isystem" (str (lib lib-path "sundials") "/include")
"-std=c++1y" "-Wall"
"-DEIGEN_NO_DEBUG" "-DBOOST_RESULT_OF_USE_TR1" "-DBOOST_NO_DECLTYPE"
"-DBOOST_DISABLE_ASSERTS" "-DBOOST_PHOENIX_NO_VARIADIC_EXPRESSION"
"-DFUSION_MAX_VECTOR_SIZE=12" "-DNO_FPRINTF_OUTPUT"
"-Wno-unused-function" "-Wno-uninitialized" "-Wno-unused-local-typedefs"
"-pipe" "-O3" "-o" exe (str home "/src/cmdstan/main.cpp")
"-include" hpp-file
(str (lib lib-path "sundials") "/lib/libsundials_nvecserial.a")
(str (lib lib-path "sundials") "/lib/libsundials_cvodes.a")
(str (lib lib-path "sundials") "/lib/libsundials_idas.a"))))
(->CompiledModel exe)))
|
[
{
"context": "er data\n(def users-db\n {1 #:acme.user{:name \"Usuario 1\"\n :email \"user@provider.com\"\n ",
"end": 818,
"score": 0.9218385815620422,
"start": 809,
"tag": "NAME",
"value": "Usuario 1"
},
{
"context": ":name \"Usuario 1\"\n :email \"user@provider.com\"\n :birthday \"1989-10-25\"}\n 2 #:",
"end": 865,
"score": 0.9999149441719055,
"start": 848,
"tag": "EMAIL",
"value": "user@provider.com"
},
{
"context": "irthday \"1989-10-25\"}\n 2 #:acme.user{:name \"Usuario 2\"\n :email \"anuser@provider.com\"",
"end": 945,
"score": 0.9010271430015564,
"start": 936,
"tag": "NAME",
"value": "Usuario 2"
},
{
"context": ":name \"Usuario 2\"\n :email \"anuser@provider.com\"\n :birthday \"1975-09-11\"}})\n\n; pu",
"end": 994,
"score": 0.9999133944511414,
"start": 975,
"tag": "EMAIL",
"value": "anuser@provider.com"
},
{
"context": "`user-db :acme.user/id\n {1 #:acme.user{:name \"Trey Parker\"\n :email \"trey@provider.com\"}\n ",
"end": 2384,
"score": 0.9998871088027954,
"start": 2373,
"tag": "NAME",
"value": "Trey Parker"
},
{
"context": "r{:name \"Trey Parker\"\n :email \"trey@provider.com\"}\n 2 #:acme.user{:name \"Matt Stone\"\n ",
"end": 2430,
"score": 0.9999220967292786,
"start": 2413,
"tag": "EMAIL",
"value": "trey@provider.com"
},
{
"context": "l \"trey@provider.com\"}\n 2 #:acme.user{:name \"Matt Stone\"\n :email \"matt@provider.com\"}})",
"end": 2470,
"score": 0.999866247177124,
"start": 2460,
"tag": "NAME",
"value": "Matt Stone"
},
{
"context": "er{:name \"Matt Stone\"\n :email \"matt@provider.com\"}}))\n\n; avatar slug is a version of email, conver",
"end": 2516,
"score": 0.9999272227287292,
"start": 2499,
"tag": "EMAIL",
"value": "matt@provider.com"
},
{
"context": " reach the same result:\n (->> {:acme.user/email \"other@provider.com\"}\n (psm/smart-map indexes)\n :acme.user/avat",
"end": 3807,
"score": 0.9996699094772339,
"start": 3789,
"tag": "EMAIL",
"value": "other@provider.com"
},
{
"context": "c-table-resolver :user/id\n {1 {:user/email \"user@example.com\"}\n 2 {:user/email \"another@example.com\"\n ",
"end": 5452,
"score": 0.9999221563339233,
"start": 5436,
"tag": "EMAIL",
"value": "user@example.com"
},
{
"context": "email \"user@example.com\"}\n 2 {:user/email \"another@example.com\"\n :user/name \"Sam\"}})\n (pbir/const",
"end": 5498,
"score": 0.9999149441719055,
"start": 5479,
"tag": "EMAIL",
"value": "another@example.com"
},
{
"context": "ail \"another@example.com\"\n :user/name \"Sam\"}})\n (pbir/constantly-resolver :all-users\n ",
"end": 5527,
"score": 0.9992715716362,
"start": 5524,
"tag": "NAME",
"value": "Sam"
},
{
"context": "]}])\n; => {:all-users\n; [{:user/display-name \"user@example.com\"} ; no name, use email\n; {:user/display-name",
"end": 5768,
"score": 0.9999019503593445,
"start": 5752,
"tag": "EMAIL",
"value": "user@example.com"
},
{
"context": " ; no name, use email\n; {:user/display-name \"Sam\"} ; has name (the optional), use it\n; ]}\n\n;; ",
"end": 5823,
"score": 0.9984539747238159,
"start": 5820,
"tag": "NAME",
"value": "Sam"
}
] | clj/ex/study_pathom/pathom01/src/main/pathom05.clj | mertnuhoglu/study | 1 | (ns main.pathom05
(:require
[com.wsscode.pathom3.connect.indexes :as pci]
[com.wsscode.pathom3.connect.operation :as pco]
[com.wsscode.pathom3.interface.eql :as p.eql]
[com.wsscode.pathom3.interface.smart-map :as psm]
[com.wsscode.pathom3.connect.built-in.resolvers :as pbir]
[clojure.string :as str]))
; ex01:
(def user-birthdays
{1 1969
2 1954
3 1986})
; defresolver is the main option to create new resolvers
(pco/defresolver user-birthday [{:keys [acme.user/id]}]
{:acme.user/birth-year (get user-birthdays id)})
(comment
(user-birthday user-birthdays)
;=> #:acme.user{:birth-year nil}
(user-birthday {:acme.user/id 2})
;=> #:acme.user{:birth-year 1954}
,)
;; ex02:
; define a map for indexed access to user data
(def users-db
{1 #:acme.user{:name "Usuario 1"
:email "user@provider.com"
:birthday "1989-10-25"}
2 #:acme.user{:name "Usuario 2"
:email "anuser@provider.com"
:birthday "1975-09-11"}})
; pull stored user info from id
(pco/defresolver user-by-id [{:keys [acme.user/id]}]
{::pco/output
[:acme.user/name
:acme.user/email
:acme.user/birthday]}
(get users-db id))
; extract birth year from birthday
(pco/defresolver birth-year [{:keys [acme.user/birthday]}]
{:acme.user/birth-year (first (str/split birthday #"-"))})
(comment
; process needs an environment configuration
(p.eql/process env
; we can provide some initial data
{:acme.user/id 1}
; then we write an EQL query
[:acme.user/birth-year])
; => {:acme.user/birth-year "1989"}
,)
; ex04: Invoking resolvers
;Like functions, you can call the resolvers directly:
(pco/defresolver extension [{::keys [path]}]
{::path-ext (last (str/split path #"\."))})
(comment
(extension {::path "foo.txt"})
; => {::path-ext "txt"}
,)
;Outside of the test context, you should have little reason to invoke a resolver directly. What sets resolvers apart from regular functions are that it contains data about its requirements and what it provides.
;This allows you to abstract away the operation names and focus only on the attributes.
;To illustrate the difference, let's compare the two approaches, first let's define the resolvers:
(def user-from-id
(pbir/static-table-resolver `user-db :acme.user/id
{1 #:acme.user{:name "Trey Parker"
:email "trey@provider.com"}
2 #:acme.user{:name "Matt Stone"
:email "matt@provider.com"}}))
; avatar slug is a version of email, converting every non letter character into dashes
(pco/defresolver user-avatar-slug [{:acme.user/keys [email]}]
{:acme.user/avatar-slug (str/replace email #"[^a-z0-9A-Z]" "-")})
(pco/defresolver user-avatar-url [{:acme.user/keys [avatar-slug]}]
{:acme.user/avatar-url (str "http://avatar-images-host/for-id/" avatar-slug)})
(comment
;Consider the question: What is the avatar url of the user with id 1?
; opt01: traditional way
(-> {:acme.user/id 1}
(user-from-id)
(user-avatar-slug)
(user-avatar-url)
:acme.user/avatar-url)
; => "http://avatar-images-host/for-id/trey-provider-com"
,)
; opt02: smart map
; first, we build an index for the relations expressed by the resolvers
(def indexes
(pci/register [user-from-id
user-avatar-slug
user-avatar-url]))
(comment
; now instead of reference the functions, we let Pathom figure them out using the indexes
(->> {:acme.user/id 2}
(psm/smart-map indexes)
:acme.user/avatar-url)
; => "http://avatar-images-host/for-id/matt-provider-com"
; to highlight the fact that we disregard the function, other ways where we can change
; the initial data and reach the same result:
(->> {:acme.user/email "other@provider.com"}
(psm/smart-map indexes)
:acme.user/avatar-url)
; => "http://avatar-images-host/for-id/other-provider-com"
(->> {:acme.user/avatar-slug "some-slogan"}
(psm/smart-map indexes)
:acme.user/avatar-url)
; => "http://avatar-images-host/for-id/some-slogan"
,)
;; ex05: Using the indexes
(comment
; index'leri farklı şekillerde oluşturabilirsin:
; create indexes for a single resolver
(def single-registry (pci/register some-resolver))
; creating indexes with a few resolvers
(def many-registry (pci/register [resolver-a resolver-b]))
; define a group of resolvers in a variable
(def some-resolvers [res-a res-b])
; now use in combination with other mixes:
(def more-registry
(pci/register [some-resolvers
[other-group with-more
[deep-nested resolvers]]
and-more]))
; now using indexes as part of registry
(def with-indexes (pci/register [some-resolvers many-registry]))
; all together now
(def env
(pci/register [[resolver-a resolver-b]
some-resolvers
many-registry]))
,)
; The indexes are part of the Pathom environment, for some operations just the indexes are enough.
; When you see indexes or env, consider they expect to have at least the indexes for the resolvers in the map.
;; ex06: Optional inputs
; use pco/?
(pco/defresolver user-display-name
[{:user/keys [email name]}]
{::pco/input [:user/email (pco/? :user/name)]}
{:user/display-name (or name email)})
(def opt-env
(pci/register
[(pbir/static-table-resolver :user/id
{1 {:user/email "user@example.com"}
2 {:user/email "another@example.com"
:user/name "Sam"}})
(pbir/constantly-resolver :all-users
[{:user/id 1}
{:user/id 2}])
user-display-name]))
(p.eql/process opt-env
[{:all-users [:user/display-name]}])
; => {:all-users
; [{:user/display-name "user@example.com"} ; no name, use email
; {:user/display-name "Sam"} ; has name (the optional), use it
; ]}
;; ex07: Nested inputs
; This feature is handy when you need to make data aggregation based on indirect data.
(pco/defresolver top-players
"Return maps with ids for the top players in a given game."
[]
{:game/top-players
[{:player/id 1}
{:player/id 20}
{:player/id 8}
{:player/id 2}]})
(pco/defresolver player-by-id
"Get player by id, in our case just generate some data based on the id."
[{:keys [player/id]}]
{:player/name (str "Player " id)
:player/score (* id 50)})
; Now, for the task: how to make a resolver that computes the average score from the top players?
(pco/defresolver top-players-avg
"Compute the average score for the top players using nested inputs."
[{:keys [game/top-players]}]
; we have to make the nested input explicit
{::pco/input [{:game/top-players [:player/score]}]}
{:game/top-players-avg-score
(let [score-sum (transduce (map :player/score) + 0 top-players)]
(double (/ score-sum (count top-players))))})
(p.eql/process (pci/register [top-players player-by-id top-players-avg])
[:game/top-players-avg-score])
; => #:game{:top-players-avg-score 387.5}
;; ex08: Parameters
(def mock-todos-db
[{::todo-message "Write demo on params"
::todo-done? true}
{::todo-message "Pathom in Rust"
::todo-done? false}])
; opt01: no parameters
; when resolvers have nested data, it's better always to specify it.
(pco/defresolver todos-resolver [env _]
; express nested shape
{::pco/output
[{::todos
[::todo-message
::todo-done?]}]}
{::todos mock-todos-db})
(def env (pci/register todos-resolver))
; list all todos
(p.eql/process env [::todos])
; opt02: with parameters
; add parameter:
; list undone todos:
(p.eql/process env ['(::todos {::todo-done? false})])
; nothing happens. we need to use the parameters to filter the data in the resolver
; opt03: with parameters in the resolver
(def mock-todos-db
[{::todo-message "Write demo on params"
::todo-done? true}
{::todo-message "Pathom in Rust"
::todo-done? false}])
(pco/defresolver todos-resolver [env _]
{::pco/output
[{::todos
[::todo-message
::todo-done?]}]}
{::todos
; pull params and filter
(if-some [done? (get (pco/params env) ::todo-done?)]
(->> mock-todos-db
(filter #(= done? (::todo-done? %))))
mock-todos-db)})
(def env (pci/register todos-resolver))
; list undone todos
(p.eql/process env
'[(::todos {::todo-done? false})])
;=> #:main.pathom05{:todos (#:main.pathom05{:todo-message "Pathom in Rust", :todo-done? false})}
; opt04: use parameters with smart maps. call sm-preload!
(def sm (psm/smart-map env {}))
; preload using EQL params
;(psm/sm-preload! sm '[(::todos {::todo-done? false})])
;(::todos sm) ; => cached filtered li | 22516 | (ns main.pathom05
(:require
[com.wsscode.pathom3.connect.indexes :as pci]
[com.wsscode.pathom3.connect.operation :as pco]
[com.wsscode.pathom3.interface.eql :as p.eql]
[com.wsscode.pathom3.interface.smart-map :as psm]
[com.wsscode.pathom3.connect.built-in.resolvers :as pbir]
[clojure.string :as str]))
; ex01:
(def user-birthdays
{1 1969
2 1954
3 1986})
; defresolver is the main option to create new resolvers
(pco/defresolver user-birthday [{:keys [acme.user/id]}]
{:acme.user/birth-year (get user-birthdays id)})
(comment
(user-birthday user-birthdays)
;=> #:acme.user{:birth-year nil}
(user-birthday {:acme.user/id 2})
;=> #:acme.user{:birth-year 1954}
,)
;; ex02:
; define a map for indexed access to user data
(def users-db
{1 #:acme.user{:name "<NAME>"
:email "<EMAIL>"
:birthday "1989-10-25"}
2 #:acme.user{:name "<NAME>"
:email "<EMAIL>"
:birthday "1975-09-11"}})
; pull stored user info from id
(pco/defresolver user-by-id [{:keys [acme.user/id]}]
{::pco/output
[:acme.user/name
:acme.user/email
:acme.user/birthday]}
(get users-db id))
; extract birth year from birthday
(pco/defresolver birth-year [{:keys [acme.user/birthday]}]
{:acme.user/birth-year (first (str/split birthday #"-"))})
(comment
; process needs an environment configuration
(p.eql/process env
; we can provide some initial data
{:acme.user/id 1}
; then we write an EQL query
[:acme.user/birth-year])
; => {:acme.user/birth-year "1989"}
,)
; ex04: Invoking resolvers
;Like functions, you can call the resolvers directly:
(pco/defresolver extension [{::keys [path]}]
{::path-ext (last (str/split path #"\."))})
(comment
(extension {::path "foo.txt"})
; => {::path-ext "txt"}
,)
;Outside of the test context, you should have little reason to invoke a resolver directly. What sets resolvers apart from regular functions are that it contains data about its requirements and what it provides.
;This allows you to abstract away the operation names and focus only on the attributes.
;To illustrate the difference, let's compare the two approaches, first let's define the resolvers:
(def user-from-id
(pbir/static-table-resolver `user-db :acme.user/id
{1 #:acme.user{:name "<NAME>"
:email "<EMAIL>"}
2 #:acme.user{:name "<NAME>"
:email "<EMAIL>"}}))
; avatar slug is a version of email, converting every non letter character into dashes
(pco/defresolver user-avatar-slug [{:acme.user/keys [email]}]
{:acme.user/avatar-slug (str/replace email #"[^a-z0-9A-Z]" "-")})
(pco/defresolver user-avatar-url [{:acme.user/keys [avatar-slug]}]
{:acme.user/avatar-url (str "http://avatar-images-host/for-id/" avatar-slug)})
(comment
;Consider the question: What is the avatar url of the user with id 1?
; opt01: traditional way
(-> {:acme.user/id 1}
(user-from-id)
(user-avatar-slug)
(user-avatar-url)
:acme.user/avatar-url)
; => "http://avatar-images-host/for-id/trey-provider-com"
,)
; opt02: smart map
; first, we build an index for the relations expressed by the resolvers
(def indexes
(pci/register [user-from-id
user-avatar-slug
user-avatar-url]))
(comment
; now instead of reference the functions, we let Pathom figure them out using the indexes
(->> {:acme.user/id 2}
(psm/smart-map indexes)
:acme.user/avatar-url)
; => "http://avatar-images-host/for-id/matt-provider-com"
; to highlight the fact that we disregard the function, other ways where we can change
; the initial data and reach the same result:
(->> {:acme.user/email "<EMAIL>"}
(psm/smart-map indexes)
:acme.user/avatar-url)
; => "http://avatar-images-host/for-id/other-provider-com"
(->> {:acme.user/avatar-slug "some-slogan"}
(psm/smart-map indexes)
:acme.user/avatar-url)
; => "http://avatar-images-host/for-id/some-slogan"
,)
;; ex05: Using the indexes
(comment
; index'leri farklı şekillerde oluşturabilirsin:
; create indexes for a single resolver
(def single-registry (pci/register some-resolver))
; creating indexes with a few resolvers
(def many-registry (pci/register [resolver-a resolver-b]))
; define a group of resolvers in a variable
(def some-resolvers [res-a res-b])
; now use in combination with other mixes:
(def more-registry
(pci/register [some-resolvers
[other-group with-more
[deep-nested resolvers]]
and-more]))
; now using indexes as part of registry
(def with-indexes (pci/register [some-resolvers many-registry]))
; all together now
(def env
(pci/register [[resolver-a resolver-b]
some-resolvers
many-registry]))
,)
; The indexes are part of the Pathom environment, for some operations just the indexes are enough.
; When you see indexes or env, consider they expect to have at least the indexes for the resolvers in the map.
;; ex06: Optional inputs
; use pco/?
(pco/defresolver user-display-name
[{:user/keys [email name]}]
{::pco/input [:user/email (pco/? :user/name)]}
{:user/display-name (or name email)})
(def opt-env
(pci/register
[(pbir/static-table-resolver :user/id
{1 {:user/email "<EMAIL>"}
2 {:user/email "<EMAIL>"
:user/name "<NAME>"}})
(pbir/constantly-resolver :all-users
[{:user/id 1}
{:user/id 2}])
user-display-name]))
(p.eql/process opt-env
[{:all-users [:user/display-name]}])
; => {:all-users
; [{:user/display-name "<EMAIL>"} ; no name, use email
; {:user/display-name "<NAME>"} ; has name (the optional), use it
; ]}
;; ex07: Nested inputs
; This feature is handy when you need to make data aggregation based on indirect data.
(pco/defresolver top-players
"Return maps with ids for the top players in a given game."
[]
{:game/top-players
[{:player/id 1}
{:player/id 20}
{:player/id 8}
{:player/id 2}]})
(pco/defresolver player-by-id
"Get player by id, in our case just generate some data based on the id."
[{:keys [player/id]}]
{:player/name (str "Player " id)
:player/score (* id 50)})
; Now, for the task: how to make a resolver that computes the average score from the top players?
(pco/defresolver top-players-avg
"Compute the average score for the top players using nested inputs."
[{:keys [game/top-players]}]
; we have to make the nested input explicit
{::pco/input [{:game/top-players [:player/score]}]}
{:game/top-players-avg-score
(let [score-sum (transduce (map :player/score) + 0 top-players)]
(double (/ score-sum (count top-players))))})
(p.eql/process (pci/register [top-players player-by-id top-players-avg])
[:game/top-players-avg-score])
; => #:game{:top-players-avg-score 387.5}
;; ex08: Parameters
(def mock-todos-db
[{::todo-message "Write demo on params"
::todo-done? true}
{::todo-message "Pathom in Rust"
::todo-done? false}])
; opt01: no parameters
; when resolvers have nested data, it's better always to specify it.
(pco/defresolver todos-resolver [env _]
; express nested shape
{::pco/output
[{::todos
[::todo-message
::todo-done?]}]}
{::todos mock-todos-db})
(def env (pci/register todos-resolver))
; list all todos
(p.eql/process env [::todos])
; opt02: with parameters
; add parameter:
; list undone todos:
(p.eql/process env ['(::todos {::todo-done? false})])
; nothing happens. we need to use the parameters to filter the data in the resolver
; opt03: with parameters in the resolver
(def mock-todos-db
[{::todo-message "Write demo on params"
::todo-done? true}
{::todo-message "Pathom in Rust"
::todo-done? false}])
(pco/defresolver todos-resolver [env _]
{::pco/output
[{::todos
[::todo-message
::todo-done?]}]}
{::todos
; pull params and filter
(if-some [done? (get (pco/params env) ::todo-done?)]
(->> mock-todos-db
(filter #(= done? (::todo-done? %))))
mock-todos-db)})
(def env (pci/register todos-resolver))
; list undone todos
(p.eql/process env
'[(::todos {::todo-done? false})])
;=> #:main.pathom05{:todos (#:main.pathom05{:todo-message "Pathom in Rust", :todo-done? false})}
; opt04: use parameters with smart maps. call sm-preload!
(def sm (psm/smart-map env {}))
; preload using EQL params
;(psm/sm-preload! sm '[(::todos {::todo-done? false})])
;(::todos sm) ; => cached filtered li | true | (ns main.pathom05
(:require
[com.wsscode.pathom3.connect.indexes :as pci]
[com.wsscode.pathom3.connect.operation :as pco]
[com.wsscode.pathom3.interface.eql :as p.eql]
[com.wsscode.pathom3.interface.smart-map :as psm]
[com.wsscode.pathom3.connect.built-in.resolvers :as pbir]
[clojure.string :as str]))
; ex01:
(def user-birthdays
{1 1969
2 1954
3 1986})
; defresolver is the main option to create new resolvers
(pco/defresolver user-birthday [{:keys [acme.user/id]}]
{:acme.user/birth-year (get user-birthdays id)})
(comment
(user-birthday user-birthdays)
;=> #:acme.user{:birth-year nil}
(user-birthday {:acme.user/id 2})
;=> #:acme.user{:birth-year 1954}
,)
;; ex02:
; define a map for indexed access to user data
(def users-db
{1 #:acme.user{:name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:birthday "1989-10-25"}
2 #:acme.user{:name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"
:birthday "1975-09-11"}})
; pull stored user info from id
(pco/defresolver user-by-id [{:keys [acme.user/id]}]
{::pco/output
[:acme.user/name
:acme.user/email
:acme.user/birthday]}
(get users-db id))
; extract birth year from birthday
(pco/defresolver birth-year [{:keys [acme.user/birthday]}]
{:acme.user/birth-year (first (str/split birthday #"-"))})
(comment
; process needs an environment configuration
(p.eql/process env
; we can provide some initial data
{:acme.user/id 1}
; then we write an EQL query
[:acme.user/birth-year])
; => {:acme.user/birth-year "1989"}
,)
; ex04: Invoking resolvers
;Like functions, you can call the resolvers directly:
(pco/defresolver extension [{::keys [path]}]
{::path-ext (last (str/split path #"\."))})
(comment
(extension {::path "foo.txt"})
; => {::path-ext "txt"}
,)
;Outside of the test context, you should have little reason to invoke a resolver directly. What sets resolvers apart from regular functions are that it contains data about its requirements and what it provides.
;This allows you to abstract away the operation names and focus only on the attributes.
;To illustrate the difference, let's compare the two approaches, first let's define the resolvers:
(def user-from-id
(pbir/static-table-resolver `user-db :acme.user/id
{1 #:acme.user{:name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"}
2 #:acme.user{:name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"}}))
; avatar slug is a version of email, converting every non letter character into dashes
(pco/defresolver user-avatar-slug [{:acme.user/keys [email]}]
{:acme.user/avatar-slug (str/replace email #"[^a-z0-9A-Z]" "-")})
(pco/defresolver user-avatar-url [{:acme.user/keys [avatar-slug]}]
{:acme.user/avatar-url (str "http://avatar-images-host/for-id/" avatar-slug)})
(comment
;Consider the question: What is the avatar url of the user with id 1?
; opt01: traditional way
(-> {:acme.user/id 1}
(user-from-id)
(user-avatar-slug)
(user-avatar-url)
:acme.user/avatar-url)
; => "http://avatar-images-host/for-id/trey-provider-com"
,)
; opt02: smart map
; first, we build an index for the relations expressed by the resolvers
(def indexes
(pci/register [user-from-id
user-avatar-slug
user-avatar-url]))
(comment
; now instead of reference the functions, we let Pathom figure them out using the indexes
(->> {:acme.user/id 2}
(psm/smart-map indexes)
:acme.user/avatar-url)
; => "http://avatar-images-host/for-id/matt-provider-com"
; to highlight the fact that we disregard the function, other ways where we can change
; the initial data and reach the same result:
(->> {:acme.user/email "PI:EMAIL:<EMAIL>END_PI"}
(psm/smart-map indexes)
:acme.user/avatar-url)
; => "http://avatar-images-host/for-id/other-provider-com"
(->> {:acme.user/avatar-slug "some-slogan"}
(psm/smart-map indexes)
:acme.user/avatar-url)
; => "http://avatar-images-host/for-id/some-slogan"
,)
;; ex05: Using the indexes
(comment
; index'leri farklı şekillerde oluşturabilirsin:
; create indexes for a single resolver
(def single-registry (pci/register some-resolver))
; creating indexes with a few resolvers
(def many-registry (pci/register [resolver-a resolver-b]))
; define a group of resolvers in a variable
(def some-resolvers [res-a res-b])
; now use in combination with other mixes:
(def more-registry
(pci/register [some-resolvers
[other-group with-more
[deep-nested resolvers]]
and-more]))
; now using indexes as part of registry
(def with-indexes (pci/register [some-resolvers many-registry]))
; all together now
(def env
(pci/register [[resolver-a resolver-b]
some-resolvers
many-registry]))
,)
; The indexes are part of the Pathom environment, for some operations just the indexes are enough.
; When you see indexes or env, consider they expect to have at least the indexes for the resolvers in the map.
;; ex06: Optional inputs
; use pco/?
(pco/defresolver user-display-name
[{:user/keys [email name]}]
{::pco/input [:user/email (pco/? :user/name)]}
{:user/display-name (or name email)})
(def opt-env
(pci/register
[(pbir/static-table-resolver :user/id
{1 {:user/email "PI:EMAIL:<EMAIL>END_PI"}
2 {:user/email "PI:EMAIL:<EMAIL>END_PI"
:user/name "PI:NAME:<NAME>END_PI"}})
(pbir/constantly-resolver :all-users
[{:user/id 1}
{:user/id 2}])
user-display-name]))
(p.eql/process opt-env
[{:all-users [:user/display-name]}])
; => {:all-users
; [{:user/display-name "PI:EMAIL:<EMAIL>END_PI"} ; no name, use email
; {:user/display-name "PI:NAME:<NAME>END_PI"} ; has name (the optional), use it
; ]}
;; ex07: Nested inputs
; This feature is handy when you need to make data aggregation based on indirect data.
(pco/defresolver top-players
"Return maps with ids for the top players in a given game."
[]
{:game/top-players
[{:player/id 1}
{:player/id 20}
{:player/id 8}
{:player/id 2}]})
(pco/defresolver player-by-id
"Get player by id, in our case just generate some data based on the id."
[{:keys [player/id]}]
{:player/name (str "Player " id)
:player/score (* id 50)})
; Now, for the task: how to make a resolver that computes the average score from the top players?
(pco/defresolver top-players-avg
"Compute the average score for the top players using nested inputs."
[{:keys [game/top-players]}]
; we have to make the nested input explicit
{::pco/input [{:game/top-players [:player/score]}]}
{:game/top-players-avg-score
(let [score-sum (transduce (map :player/score) + 0 top-players)]
(double (/ score-sum (count top-players))))})
(p.eql/process (pci/register [top-players player-by-id top-players-avg])
[:game/top-players-avg-score])
; => #:game{:top-players-avg-score 387.5}
;; ex08: Parameters
(def mock-todos-db
[{::todo-message "Write demo on params"
::todo-done? true}
{::todo-message "Pathom in Rust"
::todo-done? false}])
; opt01: no parameters
; when resolvers have nested data, it's better always to specify it.
(pco/defresolver todos-resolver [env _]
; express nested shape
{::pco/output
[{::todos
[::todo-message
::todo-done?]}]}
{::todos mock-todos-db})
(def env (pci/register todos-resolver))
; list all todos
(p.eql/process env [::todos])
; opt02: with parameters
; add parameter:
; list undone todos:
(p.eql/process env ['(::todos {::todo-done? false})])
; nothing happens. we need to use the parameters to filter the data in the resolver
; opt03: with parameters in the resolver
(def mock-todos-db
[{::todo-message "Write demo on params"
::todo-done? true}
{::todo-message "Pathom in Rust"
::todo-done? false}])
(pco/defresolver todos-resolver [env _]
{::pco/output
[{::todos
[::todo-message
::todo-done?]}]}
{::todos
; pull params and filter
(if-some [done? (get (pco/params env) ::todo-done?)]
(->> mock-todos-db
(filter #(= done? (::todo-done? %))))
mock-todos-db)})
(def env (pci/register todos-resolver))
; list undone todos
(p.eql/process env
'[(::todos {::todo-done? false})])
;=> #:main.pathom05{:todos (#:main.pathom05{:todo-message "Pathom in Rust", :todo-done? false})}
; opt04: use parameters with smart maps. call sm-preload!
(def sm (psm/smart-map env {}))
; preload using EQL params
;(psm/sm-preload! sm '[(::todos {::todo-done? false})])
;(::todos sm) ; => cached filtered li |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.