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": "t-token resp)]\n (client/post \"https://github.com/sesson\"\n {:form-params {:authenticity_toke",
"end": 445,
"score": 0.999419093132019,
"start": 439,
"tag": "USERNAME",
"value": "sesson"
},
{
"context": "mit \"Sign+in\"\n :login user\n :password pass\n ",
"end": 592,
"score": 0.6777974367141724,
"start": 588,
"tag": "USERNAME",
"value": "user"
},
{
"context": "login user\n :password pass\n :utf8 \"\\u2713\"}}))\n",
"end": 637,
"score": 0.998741626739502,
"start": 633,
"tag": "PASSWORD",
"value": "pass"
},
{
"context": ":password pass\n :utf8 \"\\u2713\"}}))\n\n(defn build-url\n [day]\n (str \"http://adve",
"end": 681,
"score": 0.8776325583457947,
"start": 674,
"tag": "PASSWORD",
"value": "\"\\u2713"
}
] | src/adventofcode2017/util.clj | wtneal/adventofcode2017 | 0 | (ns adventofcode2017.util
(:require [clj-http.client :as client]
[net.cgrand.enlive-html :as html]))
(defn get-token
[resp]
(-> (:body)
(html/snippet)
(html/select [[:input (html/attr= :name "authenticity_token")]])
(get-in [:attrs :value])))
(defn login
[user pass]
(let [resp (client/get "https://adventofcode.com/auth/github")
token (get-token resp)]
(client/post "https://github.com/sesson"
{:form-params {:authenticity_token token
:commit "Sign+in"
:login user
:password pass
:utf8 "\u2713"}}))
(defn build-url
[day]
(str "http://adventofcode.com/2017/day/" day "/input"))
(defn scrape-input
[day]
(client/get (build-url day)))
| 76958 | (ns adventofcode2017.util
(:require [clj-http.client :as client]
[net.cgrand.enlive-html :as html]))
(defn get-token
[resp]
(-> (:body)
(html/snippet)
(html/select [[:input (html/attr= :name "authenticity_token")]])
(get-in [:attrs :value])))
(defn login
[user pass]
(let [resp (client/get "https://adventofcode.com/auth/github")
token (get-token resp)]
(client/post "https://github.com/sesson"
{:form-params {:authenticity_token token
:commit "Sign+in"
:login user
:password <PASSWORD>
:utf8 <PASSWORD>"}}))
(defn build-url
[day]
(str "http://adventofcode.com/2017/day/" day "/input"))
(defn scrape-input
[day]
(client/get (build-url day)))
| true | (ns adventofcode2017.util
(:require [clj-http.client :as client]
[net.cgrand.enlive-html :as html]))
(defn get-token
[resp]
(-> (:body)
(html/snippet)
(html/select [[:input (html/attr= :name "authenticity_token")]])
(get-in [:attrs :value])))
(defn login
[user pass]
(let [resp (client/get "https://adventofcode.com/auth/github")
token (get-token resp)]
(client/post "https://github.com/sesson"
{:form-params {:authenticity_token token
:commit "Sign+in"
:login user
:password PI:PASSWORD:<PASSWORD>END_PI
:utf8 PI:PASSWORD:<PASSWORD>END_PI"}}))
(defn build-url
[day]
(str "http://adventofcode.com/2017/day/" day "/input"))
(defn scrape-input
[day]
(client/get (build-url day)))
|
[
{
"context": ":sim/input-loc \"https://raw.githubusercontent.com/yetanalytics/datasim/DS-102_return_of_colo/dev-resources/input",
"end": 4772,
"score": 0.9502385854721069,
"start": 4760,
"tag": "USERNAME",
"value": "yetanalytics"
},
{
"context": "{:select-agents\n #{\"mbox::mailto:agent_0@example.org\"}\n :strip-ids? nil\n ",
"end": 4919,
"score": 0.9998690485954285,
"start": 4900,
"tag": "EMAIL",
"value": "agent_0@example.org"
},
{
"context": ":sim/input-loc \"https://raw.githubusercontent.com/yetanalytics/datasim/DS-102_return_of_colo/dev-resources/input",
"end": 5337,
"score": 0.8933101892471313,
"start": 5325,
"tag": "USERNAME",
"value": "yetanalytics"
},
{
"context": "gents\n #{\"mbox::mailto:agent_0@example.org\"}\n :strip-ids? nil\n ",
"end": 5504,
"score": 0.9998249411582947,
"start": 5485,
"tag": "EMAIL",
"value": "agent_0@example.org"
}
] | src/onyx/com/yetanalytics/datasim/onyx/sim.clj | yetanalytics/datasim | 12 | (ns com.yetanalytics.datasim.onyx.sim
"Feed datasim seqs into onyx"
(:require [com.yetanalytics.datasim.sim :as sim]
[com.yetanalytics.datasim.input :as input]
[com.yetanalytics.datasim.onyx.util :as u]
[onyx.plugin.protocols :as p]
[clojure.core.async :as a]
[com.yetanalytics.datasim.util.sequence :as su]
[taoensso.timbre :refer [fatal infof debug warnf] :as timbre]))
(defn init-seq
[input
{:keys [select-agents
strip-ids?
remove-refs?
take-n
drop-n
batch-size]
:as args}
task-prefix
]
(lazy-seq
(cond->> (if select-agents
(sim/sim-seq
input
:select-agents select-agents)
(sim/sim-seq
input))
take-n (take take-n)
drop-n (drop (* drop-n batch-size))
strip-ids?
(map
#(dissoc % "id"))
remove-refs?
(remove
#(= "StatementRef"
(get-in % ["object" "objectType"])))
;; chop em up
batch-size
(partition-all batch-size)
batch-size
(map-indexed
(fn [idx statements]
{:task-prefix task-prefix
:chunk-idx (cond-> idx
drop-n (+ (quot drop-n batch-size)))
:range [(-> statements
first
meta
:timestamp-ms)
(-> statements
last
meta
:timestamp-ms)]
:statements (into []
(map
#(with-meta % nil)
statements))})))))
(defn inject-sim-input [_ {input-loc ::input-loc
select-agents ::select-agents
strip-ids? ::strip-ids?
remove-refs? ::remove-refs?
?take-n ::take-n
?drop-n ::drop-n
batch-size ::batch-size
:or {strip-ids? false
remove-refs? false
batch-size 1}
:as lifecycle}]
{:sim/input-loc input-loc
:sim/args {:select-agents select-agents
:strip-ids? strip-ids?
:remove-refs? remove-refs?
:take-n ?take-n
:drop-n ?drop-n
:batch-size batch-size}})
;; Onyx Plugin impl lets us do what we want
(defn plugin
[{:keys [onyx.core/task-map
sim/input-loc
sim/args
onyx.core/task
onyx.core/tenancy-id
onyx.core/job-id] :as event}]
(let [task-prefix (format "%s_%s_%s"
tenancy-id
job-id
(name task))
{?take-n :take-n} args
input (cond-> (input/from-location :input :json
input-loc)
?take-n (u/override-max! ?take-n))
rst (volatile! nil)
completed? (volatile! nil)
offset (volatile! nil)]
(reify
p/Plugin
(start [this event]
this)
(stop [this event]
(vreset! rst nil)
(vreset! completed? nil)
(vreset! offset nil)
this)
p/Checkpointed
(checkpoint [this]
@offset)
(recover! [this _ checkpoint]
(if (nil? checkpoint)
(do
(infof "DATASIM Input starting up...")
(vreset! rst (init-seq
input
args
task-prefix))
(vreset! completed? false)
(vreset! offset 0))
(do
(warnf "DATASIM recovering by dropping %d segments" checkpoint)
(vreset! rst (init-seq
input
(assoc args :drop-n checkpoint)
task-prefix))
(vreset! completed? false)
(vreset! offset checkpoint)))
this)
(checkpointed! [this epoch]) ;; TODO: keep a running log of n segs for replay, clear here
p/BarrierSynchronization
(synced? [this epoch]
true)
(completed? [this]
@completed?)
p/Input
(poll! [this _ timeout-ms]
(if-let [seg (first @rst)]
(do
(vswap! rst rest)
(vswap! offset inc)
seg)
(do (vreset! completed? true)
nil))))))
(def in-calls
{:lifecycle/before-task-start inject-sim-input})
(comment
(clojure.pprint/pprint
(time
(p/poll!
(plugin
{:sim/input-loc "https://raw.githubusercontent.com/yetanalytics/datasim/DS-102_return_of_colo/dev-resources/input/mom.json"
:sim/args {:select-agents
#{"mbox::mailto:agent_0@example.org"}
:strip-ids? nil
:remove-refs? nil
:take-n nil
:drop-n nil
:batch-size nil}
:onyx.core/task :out-0
:onyx.core/tenancy-id "foo"
:onyx.core/job-id (java.util.UUID/randomUUID)})
nil nil
))
)
(let [reader (plugin
{:sim/input-loc "https://raw.githubusercontent.com/yetanalytics/datasim/DS-102_return_of_colo/dev-resources/input/mom.json"
:sim/args {:select-agents
#{"mbox::mailto:agent_0@example.org"}
:strip-ids? nil
:remove-refs? nil
:take-n nil
:drop-n nil
:batch-size nil
}
:onyx.core/task :out-0
:onyx.core/tenancy-id "foo"
:onyx.core/job-id (java.util.UUID/randomUUID)})]
(p/recover! reader nil nil)
(time
(dotimes [n 10000]
(when-not (p/poll! reader nil nil)
(print 'x))
(when (zero? (rem n 1000))
(println 'seg n 'checkpoint (p/checkpoint reader)))))
)
(def i (input/from-location :input :json "dev-resources/input/mom.json"))
(first (init-seq i {:batch-size 10} ""))
)
| 105363 | (ns com.yetanalytics.datasim.onyx.sim
"Feed datasim seqs into onyx"
(:require [com.yetanalytics.datasim.sim :as sim]
[com.yetanalytics.datasim.input :as input]
[com.yetanalytics.datasim.onyx.util :as u]
[onyx.plugin.protocols :as p]
[clojure.core.async :as a]
[com.yetanalytics.datasim.util.sequence :as su]
[taoensso.timbre :refer [fatal infof debug warnf] :as timbre]))
(defn init-seq
[input
{:keys [select-agents
strip-ids?
remove-refs?
take-n
drop-n
batch-size]
:as args}
task-prefix
]
(lazy-seq
(cond->> (if select-agents
(sim/sim-seq
input
:select-agents select-agents)
(sim/sim-seq
input))
take-n (take take-n)
drop-n (drop (* drop-n batch-size))
strip-ids?
(map
#(dissoc % "id"))
remove-refs?
(remove
#(= "StatementRef"
(get-in % ["object" "objectType"])))
;; chop em up
batch-size
(partition-all batch-size)
batch-size
(map-indexed
(fn [idx statements]
{:task-prefix task-prefix
:chunk-idx (cond-> idx
drop-n (+ (quot drop-n batch-size)))
:range [(-> statements
first
meta
:timestamp-ms)
(-> statements
last
meta
:timestamp-ms)]
:statements (into []
(map
#(with-meta % nil)
statements))})))))
(defn inject-sim-input [_ {input-loc ::input-loc
select-agents ::select-agents
strip-ids? ::strip-ids?
remove-refs? ::remove-refs?
?take-n ::take-n
?drop-n ::drop-n
batch-size ::batch-size
:or {strip-ids? false
remove-refs? false
batch-size 1}
:as lifecycle}]
{:sim/input-loc input-loc
:sim/args {:select-agents select-agents
:strip-ids? strip-ids?
:remove-refs? remove-refs?
:take-n ?take-n
:drop-n ?drop-n
:batch-size batch-size}})
;; Onyx Plugin impl lets us do what we want
(defn plugin
[{:keys [onyx.core/task-map
sim/input-loc
sim/args
onyx.core/task
onyx.core/tenancy-id
onyx.core/job-id] :as event}]
(let [task-prefix (format "%s_%s_%s"
tenancy-id
job-id
(name task))
{?take-n :take-n} args
input (cond-> (input/from-location :input :json
input-loc)
?take-n (u/override-max! ?take-n))
rst (volatile! nil)
completed? (volatile! nil)
offset (volatile! nil)]
(reify
p/Plugin
(start [this event]
this)
(stop [this event]
(vreset! rst nil)
(vreset! completed? nil)
(vreset! offset nil)
this)
p/Checkpointed
(checkpoint [this]
@offset)
(recover! [this _ checkpoint]
(if (nil? checkpoint)
(do
(infof "DATASIM Input starting up...")
(vreset! rst (init-seq
input
args
task-prefix))
(vreset! completed? false)
(vreset! offset 0))
(do
(warnf "DATASIM recovering by dropping %d segments" checkpoint)
(vreset! rst (init-seq
input
(assoc args :drop-n checkpoint)
task-prefix))
(vreset! completed? false)
(vreset! offset checkpoint)))
this)
(checkpointed! [this epoch]) ;; TODO: keep a running log of n segs for replay, clear here
p/BarrierSynchronization
(synced? [this epoch]
true)
(completed? [this]
@completed?)
p/Input
(poll! [this _ timeout-ms]
(if-let [seg (first @rst)]
(do
(vswap! rst rest)
(vswap! offset inc)
seg)
(do (vreset! completed? true)
nil))))))
(def in-calls
{:lifecycle/before-task-start inject-sim-input})
(comment
(clojure.pprint/pprint
(time
(p/poll!
(plugin
{:sim/input-loc "https://raw.githubusercontent.com/yetanalytics/datasim/DS-102_return_of_colo/dev-resources/input/mom.json"
:sim/args {:select-agents
#{"mbox::mailto:<EMAIL>"}
:strip-ids? nil
:remove-refs? nil
:take-n nil
:drop-n nil
:batch-size nil}
:onyx.core/task :out-0
:onyx.core/tenancy-id "foo"
:onyx.core/job-id (java.util.UUID/randomUUID)})
nil nil
))
)
(let [reader (plugin
{:sim/input-loc "https://raw.githubusercontent.com/yetanalytics/datasim/DS-102_return_of_colo/dev-resources/input/mom.json"
:sim/args {:select-agents
#{"mbox::mailto:<EMAIL>"}
:strip-ids? nil
:remove-refs? nil
:take-n nil
:drop-n nil
:batch-size nil
}
:onyx.core/task :out-0
:onyx.core/tenancy-id "foo"
:onyx.core/job-id (java.util.UUID/randomUUID)})]
(p/recover! reader nil nil)
(time
(dotimes [n 10000]
(when-not (p/poll! reader nil nil)
(print 'x))
(when (zero? (rem n 1000))
(println 'seg n 'checkpoint (p/checkpoint reader)))))
)
(def i (input/from-location :input :json "dev-resources/input/mom.json"))
(first (init-seq i {:batch-size 10} ""))
)
| true | (ns com.yetanalytics.datasim.onyx.sim
"Feed datasim seqs into onyx"
(:require [com.yetanalytics.datasim.sim :as sim]
[com.yetanalytics.datasim.input :as input]
[com.yetanalytics.datasim.onyx.util :as u]
[onyx.plugin.protocols :as p]
[clojure.core.async :as a]
[com.yetanalytics.datasim.util.sequence :as su]
[taoensso.timbre :refer [fatal infof debug warnf] :as timbre]))
(defn init-seq
[input
{:keys [select-agents
strip-ids?
remove-refs?
take-n
drop-n
batch-size]
:as args}
task-prefix
]
(lazy-seq
(cond->> (if select-agents
(sim/sim-seq
input
:select-agents select-agents)
(sim/sim-seq
input))
take-n (take take-n)
drop-n (drop (* drop-n batch-size))
strip-ids?
(map
#(dissoc % "id"))
remove-refs?
(remove
#(= "StatementRef"
(get-in % ["object" "objectType"])))
;; chop em up
batch-size
(partition-all batch-size)
batch-size
(map-indexed
(fn [idx statements]
{:task-prefix task-prefix
:chunk-idx (cond-> idx
drop-n (+ (quot drop-n batch-size)))
:range [(-> statements
first
meta
:timestamp-ms)
(-> statements
last
meta
:timestamp-ms)]
:statements (into []
(map
#(with-meta % nil)
statements))})))))
(defn inject-sim-input [_ {input-loc ::input-loc
select-agents ::select-agents
strip-ids? ::strip-ids?
remove-refs? ::remove-refs?
?take-n ::take-n
?drop-n ::drop-n
batch-size ::batch-size
:or {strip-ids? false
remove-refs? false
batch-size 1}
:as lifecycle}]
{:sim/input-loc input-loc
:sim/args {:select-agents select-agents
:strip-ids? strip-ids?
:remove-refs? remove-refs?
:take-n ?take-n
:drop-n ?drop-n
:batch-size batch-size}})
;; Onyx Plugin impl lets us do what we want
(defn plugin
[{:keys [onyx.core/task-map
sim/input-loc
sim/args
onyx.core/task
onyx.core/tenancy-id
onyx.core/job-id] :as event}]
(let [task-prefix (format "%s_%s_%s"
tenancy-id
job-id
(name task))
{?take-n :take-n} args
input (cond-> (input/from-location :input :json
input-loc)
?take-n (u/override-max! ?take-n))
rst (volatile! nil)
completed? (volatile! nil)
offset (volatile! nil)]
(reify
p/Plugin
(start [this event]
this)
(stop [this event]
(vreset! rst nil)
(vreset! completed? nil)
(vreset! offset nil)
this)
p/Checkpointed
(checkpoint [this]
@offset)
(recover! [this _ checkpoint]
(if (nil? checkpoint)
(do
(infof "DATASIM Input starting up...")
(vreset! rst (init-seq
input
args
task-prefix))
(vreset! completed? false)
(vreset! offset 0))
(do
(warnf "DATASIM recovering by dropping %d segments" checkpoint)
(vreset! rst (init-seq
input
(assoc args :drop-n checkpoint)
task-prefix))
(vreset! completed? false)
(vreset! offset checkpoint)))
this)
(checkpointed! [this epoch]) ;; TODO: keep a running log of n segs for replay, clear here
p/BarrierSynchronization
(synced? [this epoch]
true)
(completed? [this]
@completed?)
p/Input
(poll! [this _ timeout-ms]
(if-let [seg (first @rst)]
(do
(vswap! rst rest)
(vswap! offset inc)
seg)
(do (vreset! completed? true)
nil))))))
(def in-calls
{:lifecycle/before-task-start inject-sim-input})
(comment
(clojure.pprint/pprint
(time
(p/poll!
(plugin
{:sim/input-loc "https://raw.githubusercontent.com/yetanalytics/datasim/DS-102_return_of_colo/dev-resources/input/mom.json"
:sim/args {:select-agents
#{"mbox::mailto:PI:EMAIL:<EMAIL>END_PI"}
:strip-ids? nil
:remove-refs? nil
:take-n nil
:drop-n nil
:batch-size nil}
:onyx.core/task :out-0
:onyx.core/tenancy-id "foo"
:onyx.core/job-id (java.util.UUID/randomUUID)})
nil nil
))
)
(let [reader (plugin
{:sim/input-loc "https://raw.githubusercontent.com/yetanalytics/datasim/DS-102_return_of_colo/dev-resources/input/mom.json"
:sim/args {:select-agents
#{"mbox::mailto:PI:EMAIL:<EMAIL>END_PI"}
:strip-ids? nil
:remove-refs? nil
:take-n nil
:drop-n nil
:batch-size nil
}
:onyx.core/task :out-0
:onyx.core/tenancy-id "foo"
:onyx.core/job-id (java.util.UUID/randomUUID)})]
(p/recover! reader nil nil)
(time
(dotimes [n 10000]
(when-not (p/poll! reader nil nil)
(print 'x))
(when (zero? (rem n 1000))
(println 'seg n 'checkpoint (p/checkpoint reader)))))
)
(def i (input/from-location :input :json "dev-resources/input/mom.json"))
(first (init-seq i {:batch-size 10} ""))
)
|
[
{
"context": "leSpeed\"\n :min-rotation \"minRotation\"\n :name \"name\"\n :on \"on\"\n :on-destroy \"onDestroy\"\n :parti",
"end": 3382,
"score": 0.7594870328903198,
"start": 3378,
"tag": "NAME",
"value": "name"
}
] | src/phzr/impl/accessors/particles/arcade/emitter.cljs | dparis/phzr | 120 | (ns phzr.impl.accessors.particles.arcade.emitter)
(def emitter-get-properties
{:alive "alive"
:alpha "alpha"
:alpha-data "alphaData"
:angle "angle"
:angular-drag "angularDrag"
:area "area"
:auto-alpha "autoAlpha"
:auto-scale "autoScale"
:blend-mode "blendMode"
:bottom "bottom"
:bounce "bounce"
:cache-as-bitmap "cacheAsBitmap"
:camera-offset "cameraOffset"
:children "children"
:class-type "classType"
:cursor "cursor"
:cursor-index "cursorIndex"
:emit-x "emitX"
:emit-y "emitY"
:enable-body "enableBody"
:enable-body-debug "enableBodyDebug"
:exists "exists"
:filter-area "filterArea"
:filters "filters"
:fixed-to-camera "fixedToCamera"
:frequency "frequency"
:gravity "gravity"
:hash "hash"
:height "height"
:hit-area "hitArea"
:ignore-destroy "ignoreDestroy"
:left "left"
:length "length"
:lifespan "lifespan"
:mask "mask"
:max-particle-alpha "maxParticleAlpha"
:max-particle-scale "maxParticleScale"
:max-particle-speed "maxParticleSpeed"
:max-particles "maxParticles"
:max-rotation "maxRotation"
:min-particle-alpha "minParticleAlpha"
:min-particle-scale "minParticleScale"
:min-particle-speed "minParticleSpeed"
:min-rotation "minRotation"
:name "name"
:on "on"
:on-destroy "onDestroy"
:parent "parent"
:particle-anchor "particleAnchor"
:particle-bring-to-top "particleBringToTop"
:particle-class "particleClass"
:particle-drag "particleDrag"
:particle-send-to-back "particleSendToBack"
:pending-destroy "pendingDestroy"
:physics-body-type "physicsBodyType"
:physics-sort-direction "physicsSortDirection"
:physics-type "physicsType"
:pivot "pivot"
:position "position"
:renderable "renderable"
:right "right"
:rotation "rotation"
:scale "scale"
:scale-data "scaleData"
:stage "stage"
:top "top"
:total "total"
:transform-callback "transformCallback"
:transform-callback-context "transformCallbackContext"
:visible "visible"
:width "width"
:world-alpha "worldAlpha"
:world-position "worldPosition"
:world-rotation "worldRotation"
:world-scale "worldScale"
:world-visible "worldVisible"
:x "x"
:y "y"
:z "z"})
(def emitter-set-properties
{:alive "alive"
:alpha "alpha"
:alpha-data "alphaData"
:angle "angle"
:angular-drag "angularDrag"
:area "area"
:auto-alpha "autoAlpha"
:auto-scale "autoScale"
:blend-mode "blendMode"
:bounce "bounce"
:cache-as-bitmap "cacheAsBitmap"
:camera-offset "cameraOffset"
:class-type "classType"
:cursor "cursor"
:emit-x "emitX"
:emit-y "emitY"
:enable-body "enableBody"
:enable-body-debug "enableBodyDebug"
:exists "exists"
:filter-area "filterArea"
:filters "filters"
:fixed-to-camera "fixedToCamera"
:frequency "frequency"
:gravity "gravity"
:hash "hash"
:height "height"
:hit-area "hitArea"
:ignore-destroy "ignoreDestroy"
:lifespan "lifespan"
:mask "mask"
:max-particle-alpha "maxParticleAlpha"
:max-particle-scale "maxParticleScale"
:max-particle-speed "maxParticleSpeed"
:max-particles "maxParticles"
:max-rotation "maxRotation"
:min-particle-alpha "minParticleAlpha"
:min-particle-scale "minParticleScale"
:min-particle-speed "minParticleSpeed"
:min-rotation "minRotation"
:name "name"
:on "on"
:on-destroy "onDestroy"
:particle-anchor "particleAnchor"
:particle-bring-to-top "particleBringToTop"
:particle-class "particleClass"
:particle-drag "particleDrag"
:particle-send-to-back "particleSendToBack"
:pending-destroy "pendingDestroy"
:physics-body-type "physicsBodyType"
:physics-sort-direction "physicsSortDirection"
:pivot "pivot"
:position "position"
:renderable "renderable"
:rotation "rotation"
:scale "scale"
:scale-data "scaleData"
:transform-callback "transformCallback"
:transform-callback-context "transformCallbackContext"
:visible "visible"
:width "width"
:world-visible "worldVisible"
:x "x"
:y "y"
:z "z"}) | 64440 | (ns phzr.impl.accessors.particles.arcade.emitter)
(def emitter-get-properties
{:alive "alive"
:alpha "alpha"
:alpha-data "alphaData"
:angle "angle"
:angular-drag "angularDrag"
:area "area"
:auto-alpha "autoAlpha"
:auto-scale "autoScale"
:blend-mode "blendMode"
:bottom "bottom"
:bounce "bounce"
:cache-as-bitmap "cacheAsBitmap"
:camera-offset "cameraOffset"
:children "children"
:class-type "classType"
:cursor "cursor"
:cursor-index "cursorIndex"
:emit-x "emitX"
:emit-y "emitY"
:enable-body "enableBody"
:enable-body-debug "enableBodyDebug"
:exists "exists"
:filter-area "filterArea"
:filters "filters"
:fixed-to-camera "fixedToCamera"
:frequency "frequency"
:gravity "gravity"
:hash "hash"
:height "height"
:hit-area "hitArea"
:ignore-destroy "ignoreDestroy"
:left "left"
:length "length"
:lifespan "lifespan"
:mask "mask"
:max-particle-alpha "maxParticleAlpha"
:max-particle-scale "maxParticleScale"
:max-particle-speed "maxParticleSpeed"
:max-particles "maxParticles"
:max-rotation "maxRotation"
:min-particle-alpha "minParticleAlpha"
:min-particle-scale "minParticleScale"
:min-particle-speed "minParticleSpeed"
:min-rotation "minRotation"
:name "name"
:on "on"
:on-destroy "onDestroy"
:parent "parent"
:particle-anchor "particleAnchor"
:particle-bring-to-top "particleBringToTop"
:particle-class "particleClass"
:particle-drag "particleDrag"
:particle-send-to-back "particleSendToBack"
:pending-destroy "pendingDestroy"
:physics-body-type "physicsBodyType"
:physics-sort-direction "physicsSortDirection"
:physics-type "physicsType"
:pivot "pivot"
:position "position"
:renderable "renderable"
:right "right"
:rotation "rotation"
:scale "scale"
:scale-data "scaleData"
:stage "stage"
:top "top"
:total "total"
:transform-callback "transformCallback"
:transform-callback-context "transformCallbackContext"
:visible "visible"
:width "width"
:world-alpha "worldAlpha"
:world-position "worldPosition"
:world-rotation "worldRotation"
:world-scale "worldScale"
:world-visible "worldVisible"
:x "x"
:y "y"
:z "z"})
(def emitter-set-properties
{:alive "alive"
:alpha "alpha"
:alpha-data "alphaData"
:angle "angle"
:angular-drag "angularDrag"
:area "area"
:auto-alpha "autoAlpha"
:auto-scale "autoScale"
:blend-mode "blendMode"
:bounce "bounce"
:cache-as-bitmap "cacheAsBitmap"
:camera-offset "cameraOffset"
:class-type "classType"
:cursor "cursor"
:emit-x "emitX"
:emit-y "emitY"
:enable-body "enableBody"
:enable-body-debug "enableBodyDebug"
:exists "exists"
:filter-area "filterArea"
:filters "filters"
:fixed-to-camera "fixedToCamera"
:frequency "frequency"
:gravity "gravity"
:hash "hash"
:height "height"
:hit-area "hitArea"
:ignore-destroy "ignoreDestroy"
:lifespan "lifespan"
:mask "mask"
:max-particle-alpha "maxParticleAlpha"
:max-particle-scale "maxParticleScale"
:max-particle-speed "maxParticleSpeed"
:max-particles "maxParticles"
:max-rotation "maxRotation"
:min-particle-alpha "minParticleAlpha"
:min-particle-scale "minParticleScale"
:min-particle-speed "minParticleSpeed"
:min-rotation "minRotation"
:name "<NAME>"
:on "on"
:on-destroy "onDestroy"
:particle-anchor "particleAnchor"
:particle-bring-to-top "particleBringToTop"
:particle-class "particleClass"
:particle-drag "particleDrag"
:particle-send-to-back "particleSendToBack"
:pending-destroy "pendingDestroy"
:physics-body-type "physicsBodyType"
:physics-sort-direction "physicsSortDirection"
:pivot "pivot"
:position "position"
:renderable "renderable"
:rotation "rotation"
:scale "scale"
:scale-data "scaleData"
:transform-callback "transformCallback"
:transform-callback-context "transformCallbackContext"
:visible "visible"
:width "width"
:world-visible "worldVisible"
:x "x"
:y "y"
:z "z"}) | true | (ns phzr.impl.accessors.particles.arcade.emitter)
(def emitter-get-properties
{:alive "alive"
:alpha "alpha"
:alpha-data "alphaData"
:angle "angle"
:angular-drag "angularDrag"
:area "area"
:auto-alpha "autoAlpha"
:auto-scale "autoScale"
:blend-mode "blendMode"
:bottom "bottom"
:bounce "bounce"
:cache-as-bitmap "cacheAsBitmap"
:camera-offset "cameraOffset"
:children "children"
:class-type "classType"
:cursor "cursor"
:cursor-index "cursorIndex"
:emit-x "emitX"
:emit-y "emitY"
:enable-body "enableBody"
:enable-body-debug "enableBodyDebug"
:exists "exists"
:filter-area "filterArea"
:filters "filters"
:fixed-to-camera "fixedToCamera"
:frequency "frequency"
:gravity "gravity"
:hash "hash"
:height "height"
:hit-area "hitArea"
:ignore-destroy "ignoreDestroy"
:left "left"
:length "length"
:lifespan "lifespan"
:mask "mask"
:max-particle-alpha "maxParticleAlpha"
:max-particle-scale "maxParticleScale"
:max-particle-speed "maxParticleSpeed"
:max-particles "maxParticles"
:max-rotation "maxRotation"
:min-particle-alpha "minParticleAlpha"
:min-particle-scale "minParticleScale"
:min-particle-speed "minParticleSpeed"
:min-rotation "minRotation"
:name "name"
:on "on"
:on-destroy "onDestroy"
:parent "parent"
:particle-anchor "particleAnchor"
:particle-bring-to-top "particleBringToTop"
:particle-class "particleClass"
:particle-drag "particleDrag"
:particle-send-to-back "particleSendToBack"
:pending-destroy "pendingDestroy"
:physics-body-type "physicsBodyType"
:physics-sort-direction "physicsSortDirection"
:physics-type "physicsType"
:pivot "pivot"
:position "position"
:renderable "renderable"
:right "right"
:rotation "rotation"
:scale "scale"
:scale-data "scaleData"
:stage "stage"
:top "top"
:total "total"
:transform-callback "transformCallback"
:transform-callback-context "transformCallbackContext"
:visible "visible"
:width "width"
:world-alpha "worldAlpha"
:world-position "worldPosition"
:world-rotation "worldRotation"
:world-scale "worldScale"
:world-visible "worldVisible"
:x "x"
:y "y"
:z "z"})
(def emitter-set-properties
{:alive "alive"
:alpha "alpha"
:alpha-data "alphaData"
:angle "angle"
:angular-drag "angularDrag"
:area "area"
:auto-alpha "autoAlpha"
:auto-scale "autoScale"
:blend-mode "blendMode"
:bounce "bounce"
:cache-as-bitmap "cacheAsBitmap"
:camera-offset "cameraOffset"
:class-type "classType"
:cursor "cursor"
:emit-x "emitX"
:emit-y "emitY"
:enable-body "enableBody"
:enable-body-debug "enableBodyDebug"
:exists "exists"
:filter-area "filterArea"
:filters "filters"
:fixed-to-camera "fixedToCamera"
:frequency "frequency"
:gravity "gravity"
:hash "hash"
:height "height"
:hit-area "hitArea"
:ignore-destroy "ignoreDestroy"
:lifespan "lifespan"
:mask "mask"
:max-particle-alpha "maxParticleAlpha"
:max-particle-scale "maxParticleScale"
:max-particle-speed "maxParticleSpeed"
:max-particles "maxParticles"
:max-rotation "maxRotation"
:min-particle-alpha "minParticleAlpha"
:min-particle-scale "minParticleScale"
:min-particle-speed "minParticleSpeed"
:min-rotation "minRotation"
:name "PI:NAME:<NAME>END_PI"
:on "on"
:on-destroy "onDestroy"
:particle-anchor "particleAnchor"
:particle-bring-to-top "particleBringToTop"
:particle-class "particleClass"
:particle-drag "particleDrag"
:particle-send-to-back "particleSendToBack"
:pending-destroy "pendingDestroy"
:physics-body-type "physicsBodyType"
:physics-sort-direction "physicsSortDirection"
:pivot "pivot"
:position "position"
:renderable "renderable"
:rotation "rotation"
:scale "scale"
:scale-data "scaleData"
:transform-callback "transformCallback"
:transform-callback-context "transformCallbackContext"
:visible "visible"
:width "width"
:world-visible "worldVisible"
:x "x"
:y "y"
:z "z"}) |
[
{
"context": "is (= {:event :followed\n :handle \"@doofus\"\n :name \"Doofus\"}\n ",
"end": 4960,
"score": 0.9992132186889648,
"start": 4952,
"tag": "USERNAME",
"value": "\"@doofus"
},
{
"context": " :handle \"@doofus\"\n :name \"Doofus\"}\n (try-match* \"F @doofus Doofus\"",
"end": 4995,
"score": 0.8378555774688721,
"start": 4989,
"tag": "NAME",
"value": "Doofus"
}
] | akar-core/test/akar/patterns_test.clj | missingfaktor/akar | 194 | (ns akar.patterns-test
(:require [akar.patterns :refer :all]
[akar.primitives :refer :all]
[akar.combinators :refer :all]
[clojure.test :refer :all]
[akar.test-support :refer :all])
(:import [clojure.lang Keyword]
[akar.test_support Add Sub Num Node]))
(deftest patterns-test
(testing "basic patterns"
(testing "!any"
(is (= :success
(match* :random-value (clauses*
!any (fn [] :success))))))
(testing "!pfail"
(is (= clause-not-applied
(try-match* :some-value (clauses*
!fail (fn [] :success))))))
(testing "!var"
(is (= :some-value
(match* :some-value (clauses*
!bind (fn [x] x))))))
(testing "!pred"
(let [!even (!pred even?)
!odd (!pred odd?)
block (clauses*
!even (fn [] :even)
!odd (fn [] :odd))]
(is (= :odd
(match* 9 block)))
(is (= :even
(match* 8 block)))))
(testing "!constant"
(let [block (clauses*
(!constant 4) (fn [] :fier)
(!constant 5) (fn [] :fünf))]
(is (= :fier
(match* 4 block)))
(is (= :fünf
(match* 5 block)))))
(testing "!some and !nil"
(let [block (clauses*
!some (fn [] :some)
!nil (fn [] :nil))]
(is (= :some
(match* 21 block)))
(is (= :nil
(match* nil block))))))
(testing "collection patterns"
(let [block (clauses*
!empty (fn [] :empty)
!cons (fn [hd tl] {:hd hd :tl tl})
!any (fn [] :not-sequential))]
(testing "!empty"
(is (= :empty
(match* [] block))))
(testing "!cons"
(is (= {:hd 3 :tl [4 5]}
(match* [3 4 5] block))))
(testing "non-sequential data fallthrough for both !empty and !cons"
(is (= :not-sequential
(match* :some-random-data block)))))
(let [block (clauses*
(!further-many !seq [!bind !any !bind]) (fn [a b] [a b]))]
(testing "!seq"
(is (= [2 4]
(match* [2 3 4] block)))))
(let [block (clauses*
(!and (!key "k") (!optional-key :l) (!optional-key :m)) (fn [a b c] [a b c])
!any (fn [] :stuff))]
(testing "!key and !optional-key, with regular maps"
(is (= [:x :y nil]
(match* {"k" :x :l :y} block)))
(is (= :stuff
(match* [] block)))))
(let [block (clauses*
(!key :tag) (fn [tag] tag)
(!optional-key :contents) (fn [contents] contents))]
(testing "!key and !optional-key, with records"
(is (= "i"
(match* (->Node "i" "k") block)))
(is (= "c"
(match* (->Node nil "c") block)))
(is (= nil
(match* (->Node nil nil) block)))))
(let [some-map {"XBD" 112}
block (clauses*
(!look-in some-map) (fn [v] v)
!any (fn [] :not-registered))]
(testing "!look-in"
(is (= 112
(match* "XBD" block)))
(is (= :not-registered
(match* "XKD" block)))))
(let [block (clauses*
(!further (!variant :add) [(!constant 0) !bind]) (fn [y] [:num y])
(!further (!variant :sub) [!bind (!constant 0)]) (fn [x] [:num x])
(!at (!variant :num)) (fn [node _] node))]
(testing "!variant"
(is (= [:num 3]
(match* [:add 0 3] block)))
(is (= [:num 5]
(match* [:sub 5 0] block)))
(is (= [:num 11]
(match* [:num 11] block)))))
(let [block (clauses*
(!further (!record Add) [(!constant 0) !bind]) (fn [y] (->Num y))
(!further (!record Sub) [!bind (!constant 0)]) (fn [x] (->Num x))
(!at (!record Num)) (fn [node _] node))]
(testing "!variant"
(is (= (->Num 3)
(match* (->Add 0 3) block)))
(is (= (->Num 5)
(match* (->Sub 5 0) block)))
(is (= (->Num 11)
(match* (->Num 11) block))))))
(testing "string patterns"
(testing "!regex"
(let [block (clauses*
(!regex #"^F (.*) (.*)$") (fn [handle name]
{:event :followed
:handle handle
:name name})
!any (fn [] :bad-event))]
(testing "captures values from a string that matches regex"
(is (= {:event :followed
:handle "@doofus"
:name "Doofus"}
(try-match* "F @doofus Doofus" block))))
(testing "doesn't match invalid strings"
(is (= :bad-event
(try-match* "F X" block))))
(testing "doesn't match non-strings"
(is (= :bad-event
(try-match* :not-even-a-string block)))))
(let [block (clauses*
(!regex #"^F [0-9]{1}$") (fn [] :match)
!any (fn [] :no-match))]
(testing "matches a string against a regex that captures nothing"
(is (= :match
(try-match* "F 7" block))))
(testing "doesn't match invalid srings"
(is (= :no-match
(try-match* "F 11" block)))))))
(testing "type-casing patterns"
(testing "!tag"
(let [block (clauses*
(!tag :some-tag) (fn [] :yes))]
(is (= :yes
(try-match* {:tag :some-tag} block)))))
(testing "!type"
(let [block (clauses*
(!and (!type :card) !bind) (fn [card] (:details card)))]
(is (= "Details"
(try-match* (with-meta {:details "Details"} {:type :card}) block)))))
(testing "!type - for class"
(let [block (clauses*
(!type String) (fn [] :string)
(!type Keyword) (fn [] :keyword)
(!type Exception) (fn [] :exception))]
(is (= :string
(try-match* "SomeString" block)))
(is (= :keyword
(try-match* :some-keyword block)))
(is (= :exception
(try-match* (RuntimeException.) block)))
(is (= clause-not-applied
(try-match* 4 block)))))))
| 30838 | (ns akar.patterns-test
(:require [akar.patterns :refer :all]
[akar.primitives :refer :all]
[akar.combinators :refer :all]
[clojure.test :refer :all]
[akar.test-support :refer :all])
(:import [clojure.lang Keyword]
[akar.test_support Add Sub Num Node]))
(deftest patterns-test
(testing "basic patterns"
(testing "!any"
(is (= :success
(match* :random-value (clauses*
!any (fn [] :success))))))
(testing "!pfail"
(is (= clause-not-applied
(try-match* :some-value (clauses*
!fail (fn [] :success))))))
(testing "!var"
(is (= :some-value
(match* :some-value (clauses*
!bind (fn [x] x))))))
(testing "!pred"
(let [!even (!pred even?)
!odd (!pred odd?)
block (clauses*
!even (fn [] :even)
!odd (fn [] :odd))]
(is (= :odd
(match* 9 block)))
(is (= :even
(match* 8 block)))))
(testing "!constant"
(let [block (clauses*
(!constant 4) (fn [] :fier)
(!constant 5) (fn [] :fünf))]
(is (= :fier
(match* 4 block)))
(is (= :fünf
(match* 5 block)))))
(testing "!some and !nil"
(let [block (clauses*
!some (fn [] :some)
!nil (fn [] :nil))]
(is (= :some
(match* 21 block)))
(is (= :nil
(match* nil block))))))
(testing "collection patterns"
(let [block (clauses*
!empty (fn [] :empty)
!cons (fn [hd tl] {:hd hd :tl tl})
!any (fn [] :not-sequential))]
(testing "!empty"
(is (= :empty
(match* [] block))))
(testing "!cons"
(is (= {:hd 3 :tl [4 5]}
(match* [3 4 5] block))))
(testing "non-sequential data fallthrough for both !empty and !cons"
(is (= :not-sequential
(match* :some-random-data block)))))
(let [block (clauses*
(!further-many !seq [!bind !any !bind]) (fn [a b] [a b]))]
(testing "!seq"
(is (= [2 4]
(match* [2 3 4] block)))))
(let [block (clauses*
(!and (!key "k") (!optional-key :l) (!optional-key :m)) (fn [a b c] [a b c])
!any (fn [] :stuff))]
(testing "!key and !optional-key, with regular maps"
(is (= [:x :y nil]
(match* {"k" :x :l :y} block)))
(is (= :stuff
(match* [] block)))))
(let [block (clauses*
(!key :tag) (fn [tag] tag)
(!optional-key :contents) (fn [contents] contents))]
(testing "!key and !optional-key, with records"
(is (= "i"
(match* (->Node "i" "k") block)))
(is (= "c"
(match* (->Node nil "c") block)))
(is (= nil
(match* (->Node nil nil) block)))))
(let [some-map {"XBD" 112}
block (clauses*
(!look-in some-map) (fn [v] v)
!any (fn [] :not-registered))]
(testing "!look-in"
(is (= 112
(match* "XBD" block)))
(is (= :not-registered
(match* "XKD" block)))))
(let [block (clauses*
(!further (!variant :add) [(!constant 0) !bind]) (fn [y] [:num y])
(!further (!variant :sub) [!bind (!constant 0)]) (fn [x] [:num x])
(!at (!variant :num)) (fn [node _] node))]
(testing "!variant"
(is (= [:num 3]
(match* [:add 0 3] block)))
(is (= [:num 5]
(match* [:sub 5 0] block)))
(is (= [:num 11]
(match* [:num 11] block)))))
(let [block (clauses*
(!further (!record Add) [(!constant 0) !bind]) (fn [y] (->Num y))
(!further (!record Sub) [!bind (!constant 0)]) (fn [x] (->Num x))
(!at (!record Num)) (fn [node _] node))]
(testing "!variant"
(is (= (->Num 3)
(match* (->Add 0 3) block)))
(is (= (->Num 5)
(match* (->Sub 5 0) block)))
(is (= (->Num 11)
(match* (->Num 11) block))))))
(testing "string patterns"
(testing "!regex"
(let [block (clauses*
(!regex #"^F (.*) (.*)$") (fn [handle name]
{:event :followed
:handle handle
:name name})
!any (fn [] :bad-event))]
(testing "captures values from a string that matches regex"
(is (= {:event :followed
:handle "@doofus"
:name "<NAME>"}
(try-match* "F @doofus Doofus" block))))
(testing "doesn't match invalid strings"
(is (= :bad-event
(try-match* "F X" block))))
(testing "doesn't match non-strings"
(is (= :bad-event
(try-match* :not-even-a-string block)))))
(let [block (clauses*
(!regex #"^F [0-9]{1}$") (fn [] :match)
!any (fn [] :no-match))]
(testing "matches a string against a regex that captures nothing"
(is (= :match
(try-match* "F 7" block))))
(testing "doesn't match invalid srings"
(is (= :no-match
(try-match* "F 11" block)))))))
(testing "type-casing patterns"
(testing "!tag"
(let [block (clauses*
(!tag :some-tag) (fn [] :yes))]
(is (= :yes
(try-match* {:tag :some-tag} block)))))
(testing "!type"
(let [block (clauses*
(!and (!type :card) !bind) (fn [card] (:details card)))]
(is (= "Details"
(try-match* (with-meta {:details "Details"} {:type :card}) block)))))
(testing "!type - for class"
(let [block (clauses*
(!type String) (fn [] :string)
(!type Keyword) (fn [] :keyword)
(!type Exception) (fn [] :exception))]
(is (= :string
(try-match* "SomeString" block)))
(is (= :keyword
(try-match* :some-keyword block)))
(is (= :exception
(try-match* (RuntimeException.) block)))
(is (= clause-not-applied
(try-match* 4 block)))))))
| true | (ns akar.patterns-test
(:require [akar.patterns :refer :all]
[akar.primitives :refer :all]
[akar.combinators :refer :all]
[clojure.test :refer :all]
[akar.test-support :refer :all])
(:import [clojure.lang Keyword]
[akar.test_support Add Sub Num Node]))
(deftest patterns-test
(testing "basic patterns"
(testing "!any"
(is (= :success
(match* :random-value (clauses*
!any (fn [] :success))))))
(testing "!pfail"
(is (= clause-not-applied
(try-match* :some-value (clauses*
!fail (fn [] :success))))))
(testing "!var"
(is (= :some-value
(match* :some-value (clauses*
!bind (fn [x] x))))))
(testing "!pred"
(let [!even (!pred even?)
!odd (!pred odd?)
block (clauses*
!even (fn [] :even)
!odd (fn [] :odd))]
(is (= :odd
(match* 9 block)))
(is (= :even
(match* 8 block)))))
(testing "!constant"
(let [block (clauses*
(!constant 4) (fn [] :fier)
(!constant 5) (fn [] :fünf))]
(is (= :fier
(match* 4 block)))
(is (= :fünf
(match* 5 block)))))
(testing "!some and !nil"
(let [block (clauses*
!some (fn [] :some)
!nil (fn [] :nil))]
(is (= :some
(match* 21 block)))
(is (= :nil
(match* nil block))))))
(testing "collection patterns"
(let [block (clauses*
!empty (fn [] :empty)
!cons (fn [hd tl] {:hd hd :tl tl})
!any (fn [] :not-sequential))]
(testing "!empty"
(is (= :empty
(match* [] block))))
(testing "!cons"
(is (= {:hd 3 :tl [4 5]}
(match* [3 4 5] block))))
(testing "non-sequential data fallthrough for both !empty and !cons"
(is (= :not-sequential
(match* :some-random-data block)))))
(let [block (clauses*
(!further-many !seq [!bind !any !bind]) (fn [a b] [a b]))]
(testing "!seq"
(is (= [2 4]
(match* [2 3 4] block)))))
(let [block (clauses*
(!and (!key "k") (!optional-key :l) (!optional-key :m)) (fn [a b c] [a b c])
!any (fn [] :stuff))]
(testing "!key and !optional-key, with regular maps"
(is (= [:x :y nil]
(match* {"k" :x :l :y} block)))
(is (= :stuff
(match* [] block)))))
(let [block (clauses*
(!key :tag) (fn [tag] tag)
(!optional-key :contents) (fn [contents] contents))]
(testing "!key and !optional-key, with records"
(is (= "i"
(match* (->Node "i" "k") block)))
(is (= "c"
(match* (->Node nil "c") block)))
(is (= nil
(match* (->Node nil nil) block)))))
(let [some-map {"XBD" 112}
block (clauses*
(!look-in some-map) (fn [v] v)
!any (fn [] :not-registered))]
(testing "!look-in"
(is (= 112
(match* "XBD" block)))
(is (= :not-registered
(match* "XKD" block)))))
(let [block (clauses*
(!further (!variant :add) [(!constant 0) !bind]) (fn [y] [:num y])
(!further (!variant :sub) [!bind (!constant 0)]) (fn [x] [:num x])
(!at (!variant :num)) (fn [node _] node))]
(testing "!variant"
(is (= [:num 3]
(match* [:add 0 3] block)))
(is (= [:num 5]
(match* [:sub 5 0] block)))
(is (= [:num 11]
(match* [:num 11] block)))))
(let [block (clauses*
(!further (!record Add) [(!constant 0) !bind]) (fn [y] (->Num y))
(!further (!record Sub) [!bind (!constant 0)]) (fn [x] (->Num x))
(!at (!record Num)) (fn [node _] node))]
(testing "!variant"
(is (= (->Num 3)
(match* (->Add 0 3) block)))
(is (= (->Num 5)
(match* (->Sub 5 0) block)))
(is (= (->Num 11)
(match* (->Num 11) block))))))
(testing "string patterns"
(testing "!regex"
(let [block (clauses*
(!regex #"^F (.*) (.*)$") (fn [handle name]
{:event :followed
:handle handle
:name name})
!any (fn [] :bad-event))]
(testing "captures values from a string that matches regex"
(is (= {:event :followed
:handle "@doofus"
:name "PI:NAME:<NAME>END_PI"}
(try-match* "F @doofus Doofus" block))))
(testing "doesn't match invalid strings"
(is (= :bad-event
(try-match* "F X" block))))
(testing "doesn't match non-strings"
(is (= :bad-event
(try-match* :not-even-a-string block)))))
(let [block (clauses*
(!regex #"^F [0-9]{1}$") (fn [] :match)
!any (fn [] :no-match))]
(testing "matches a string against a regex that captures nothing"
(is (= :match
(try-match* "F 7" block))))
(testing "doesn't match invalid srings"
(is (= :no-match
(try-match* "F 11" block)))))))
(testing "type-casing patterns"
(testing "!tag"
(let [block (clauses*
(!tag :some-tag) (fn [] :yes))]
(is (= :yes
(try-match* {:tag :some-tag} block)))))
(testing "!type"
(let [block (clauses*
(!and (!type :card) !bind) (fn [card] (:details card)))]
(is (= "Details"
(try-match* (with-meta {:details "Details"} {:type :card}) block)))))
(testing "!type - for class"
(let [block (clauses*
(!type String) (fn [] :string)
(!type Keyword) (fn [] :keyword)
(!type Exception) (fn [] :exception))]
(is (= :string
(try-match* "SomeString" block)))
(is (= :keyword
(try-match* :some-keyword block)))
(is (= :exception
(try-match* (RuntimeException.) block)))
(is (= clause-not-applied
(try-match* 4 block)))))))
|
[
{
"context": ";;\n;;\n;; Copyright 2013 Netflix, Inc.\n;;\n;; Licensed under the Apache Lic",
"end": 28,
"score": 0.7669497132301331,
"start": 25,
"tag": "NAME",
"value": "Net"
}
] | src/test/clojure/pigpen/functional/join_test.clj | magomimmo/PigPen | 1 | ;;
;;
;; Copyright 2013 Netflix, Inc.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;;
(ns pigpen.functional.join-test
(:use clojure.test)
(:require [pigpen.extensions.test :refer [test-diff]]
[pigpen.core :as pig]
[pigpen.fold :as fold]))
(deftest test-group-by
(let [data (pig/return [{:a 1 :b 2}
{:a 1 :b 3}
{:a 2 :b 4}])
command (pig/group-by :a data)]
(test-diff
(set (pig/dump command))
'#{[1 ({:a 1, :b 2} {:a 1, :b 3})]
[2 ({:a 2, :b 4})]})))
(deftest test-into
(let [data (pig/return [2 4 6])
command (pig/into [] data)]
(test-diff
(pig/dump command)
'[[2 4 6]])))
(deftest test-reduce
(testing "conj"
(let [data (pig/return [2 4 6])
command (pig/reduce conj [] data)]
(test-diff
(pig/dump command)
'[[2 4 6]])))
(testing "+"
(let [data (pig/return [2 4 6])
command (pig/reduce + data)]
(test-diff
(pig/dump command)
'[12]))))
(deftest test-fold
(let [data (pig/return [{:k :foo, :v 1}
{:k :foo, :v 2}
{:k :foo, :v 3}
{:k :bar, :v 4}
{:k :bar, :v 5}])]
(testing "inline sum"
(let [command (->> data
(pig/group-by :k
{:fold (fold/fold-fn +
(fn [acc value]
(+ acc (:v value))))}))]
(is (= (set (pig/dump command))
'#{[:foo 6]
[:bar 9]}))))
(testing "inline count"
(let [command (->> data
(pig/group-by :k
{:fold (fold/fold-fn (fn ([] 0)
([a b] (+ a b)))
(fn [acc _] (inc acc)))}))]
(is (= (set (pig/dump command))
'#{[:bar 2]
[:foo 3]}))))
(testing "using fold/count"
(let [command (->> data
(pig/group-by :k
{:fold (fold/count)}))]
(is (= (set (pig/dump command))
'#{[:bar 2]
[:foo 3]})))))
(testing "dual fold co-group"
(let [data0 (pig/return [{:k :foo, :a 1}
{:k :foo, :a 2}
{:k :foo, :a 3}
{:k :bar, :a 4}
{:k :bar, :a 5}])
data1 (pig/return [{:k :foo, :b 1}
{:k :foo, :b 2}
{:k :bar, :b 3}
{:k :bar, :b 4}
{:k :bar, :b 5}])
command (pig/cogroup [(data0 :on :k, :required true, :fold (->> (fold/map :a) (fold/sum)))
(data1 :on :k, :required true, :fold (->> (fold/map :b) (fold/sum)))]
vector)]
(is (= (set (pig/dump command))
'#{[:foo 6 3]
[:bar 9 12]}))))
(testing "fold all sum"
(let [data (pig/return [1 2 3 4])
command (pig/fold + data)]
(is (= (pig/dump command)
'[10]))))
(testing "fold all count"
(let [data (pig/return [1 2 3 4])
command (pig/fold (fold/count) data)]
(is (= (pig/dump command)
'[4])))))
(deftest test-cogroup
(let [data1 (pig/return [{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}
{:k :l, :v 9}
{:k :l, :v 11}])
data2 (pig/return [{:k nil, :v 2}
{:k nil, :v 4}
{:k :i, :v 6}
{:k :i, :v 8}
{:k :r, :v 10}
{:k :r, :v 12}])]
(testing "inner"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :by :k :type :required)
(data2 :by :k :type :required)]
vector)))
'#{[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]}))
(testing "left outer"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :required)
(data2 :on :k :type :optional)]
vector)))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] nil]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:l [{:k :l, :v 9} {:k :l, :v 11}] nil]}))
(testing "right outer"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :optional)
(data2 :on :k :type :required)]
vector)))
'#{[nil nil [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:r nil [{:k :r, :v 10} {:k :r, :v 12}]]}))
(testing "full outer"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :optional)
(data2 :on :k :type :optional)]
vector)))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] nil]
[nil nil [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:l [{:k :l, :v 9} {:k :l, :v 11}] nil]
[:r nil [{:k :r, :v 10} {:k :r, :v 12}]]}))
(testing "inner join nils"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :required)
(data2 :on :k :type :required)]
vector
{:join-nils true})))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]}))
(testing "left outer join nils"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :required)
(data2 :on :k :type :optional)]
vector
{:join-nils true})))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:l [{:k :l, :v 9} {:k :l, :v 11}] nil]}))
(testing "right outer join nils"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :optional)
(data2 :on :k :type :required)]
vector
{:join-nils true})))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:r nil [{:k :r, :v 10} {:k :r, :v 12}]]}))
(testing "full outer join nils"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :optional)
(data2 :on :k :type :optional)]
vector
{:join-nils true})))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:l [{:k :l, :v 9} {:k :l, :v 11}] nil]
[:r nil [{:k :r, :v 10} {:k :r, :v 12}]]}))
(testing "self cogroup"
(let [data (pig/return [0 1 2])
command (pig/cogroup [(data)
(data)]
vector)]
(is (= (pig/dump command)
'[[2 (2) (2)] [0 (0) (0)] [1 (1) (1)]]))))
(testing "self cogroup with fold"
(let [data (pig/return [0 1 2])
command (pig/cogroup [(data :fold (fold/count))
(data :fold (fold/count))]
vector)]
(is (= (pig/dump command)
'[[2 1 1] [0 1 1] [1 1 1]]))))))
(deftest test-join
(let [data1 (pig/return [{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}
{:k :l, :v 9}
{:k :l, :v 11}])
data2 (pig/return [{:k nil, :v 2}
{:k nil, :v 4}
{:k :i, :v 6}
{:k :i, :v 8}
{:k :r, :v 10}
{:k :r, :v 12}])]
(testing "inner join - implicit :required"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k)
(data2 :on :k)]
vector)))
'#{[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]}))
(testing "inner"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :required)
(data2 :on :k :type :required)]
vector)))
'#{[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]}))
(testing "left outer"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :required)
(data2 :on :k :type :optional)]
vector)))
'#{[{:k nil, :v 1} nil]
[{:k nil, :v 3} nil]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[{:k :l, :v 9} nil]
[{:k :l, :v 11} nil]}))
(testing "right outer"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :optional)
(data2 :on :k :type :required)]
vector)))
'#{[nil {:k nil, :v 2}]
[nil {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[nil {:k :r, :v 10}]
[nil {:k :r, :v 12}]}))
(testing "full outer"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :optional)
(data2 :on :k :type :optional)]
vector)))
'#{[{:k nil, :v 1} nil]
[{:k nil, :v 3} nil]
[nil {:k nil, :v 2}]
[nil {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[{:k :l, :v 9} nil]
[{:k :l, :v 11} nil]
[nil {:k :r, :v 10}]
[nil {:k :r, :v 12}]}))
(testing "inner join nils"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :required)
(data2 :on :k :type :required)]
vector
{:join-nils true})))
'#{[{:k nil, :v 1} {:k nil, :v 2}]
[{:k nil, :v 3} {:k nil, :v 2}]
[{:k nil, :v 1} {:k nil, :v 4}]
[{:k nil, :v 3} {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]}))
(testing "left outer join nils"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :required)
(data2 :on :k :type :optional)]
vector
{:join-nils true})))
'#{[{:k nil, :v 1} {:k nil, :v 2}]
[{:k nil, :v 3} {:k nil, :v 2}]
[{:k nil, :v 1} {:k nil, :v 4}]
[{:k nil, :v 3} {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[{:k :l, :v 9} nil]
[{:k :l, :v 11} nil]}))
(testing "right outer join nils"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :optional)
(data2 :on :k :type :required)]
vector
{:join-nils true})))
'#{[{:k nil, :v 1} {:k nil, :v 2}]
[{:k nil, :v 3} {:k nil, :v 2}]
[{:k nil, :v 1} {:k nil, :v 4}]
[{:k nil, :v 3} {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[nil {:k :r, :v 10}]
[nil {:k :r, :v 12}]}))
(testing "full outer join nils"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :optional)
(data2 :on :k :type :optional)]
vector
{:join-nils true})))
'#{[{:k nil, :v 1} {:k nil, :v 2}]
[{:k nil, :v 3} {:k nil, :v 2}]
[{:k nil, :v 1} {:k nil, :v 4}]
[{:k nil, :v 3} {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[{:k :l, :v 9} nil]
[{:k :l, :v 11} nil]
[nil {:k :r, :v 10}]
[nil {:k :r, :v 12}]}))
(testing "self join"
(let [data (pig/return [0 1 2])
command (pig/join [(data)
(data)]
vector)]
(is (= (pig/dump command)
[[2 2] [0 0] [1 1]]))))
(testing "key-selector defaults to identity"
(let [data1 (pig/return [1 2])
data2 (pig/return [2 3])
command (pig/join [(data1)
(data2)]
vector)]
(test-diff
(set (pig/dump command))
'#{[2 2]})))))
(deftest test-filter-by
(let [data (pig/return [{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}
{:k :l, :v 9}
{:k :l, :v 11}])]
(testing "Normal"
(let [keys (pig/return [:i])]
(test-diff
(set (pig/dump (pig/filter-by :k keys data)))
'#{{:k :i, :v 5}
{:k :i, :v 7}})))
(testing "Nil keys"
(let [keys (pig/return [:i nil])]
(test-diff
(set (pig/dump (pig/filter-by :k keys data)))
'#{{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}})))
(testing "Duplicate keys"
(let [keys (pig/return [:i :i])]
(test-diff
(pig/dump (pig/filter-by :k keys data))
'[{:k :i, :v 5}
{:k :i, :v 7}
{:k :i, :v 5}
{:k :i, :v 7}])))))
(deftest test-remove-by
(let [data (pig/return [{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}
{:k :l, :v 9}
{:k :l, :v 11}])]
(testing "Normal"
(let [keys (pig/return [:i])]
(test-diff
(set (pig/dump (pig/remove-by :k keys data)))
'#{{:k nil, :v 1}
{:k nil, :v 3}
{:k :l, :v 9}
{:k :l, :v 11}})))
(testing "Nil keys"
(let [keys (pig/return [:i nil])]
(test-diff
(set (pig/dump (pig/remove-by :k keys data)))
'#{{:k :l, :v 9}
{:k :l, :v 11}})))
(testing "Duplicate keys"
(let [keys (pig/return [:i :i])]
(test-diff
(set (pig/dump (pig/remove-by :k keys data)))
'#{{:k nil, :v 1}
{:k nil, :v 3}
{:k :l, :v 9}
{:k :l, :v 11}})))))
| 5608 | ;;
;;
;; Copyright 2013 <NAME>flix, Inc.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;;
(ns pigpen.functional.join-test
(:use clojure.test)
(:require [pigpen.extensions.test :refer [test-diff]]
[pigpen.core :as pig]
[pigpen.fold :as fold]))
(deftest test-group-by
(let [data (pig/return [{:a 1 :b 2}
{:a 1 :b 3}
{:a 2 :b 4}])
command (pig/group-by :a data)]
(test-diff
(set (pig/dump command))
'#{[1 ({:a 1, :b 2} {:a 1, :b 3})]
[2 ({:a 2, :b 4})]})))
(deftest test-into
(let [data (pig/return [2 4 6])
command (pig/into [] data)]
(test-diff
(pig/dump command)
'[[2 4 6]])))
(deftest test-reduce
(testing "conj"
(let [data (pig/return [2 4 6])
command (pig/reduce conj [] data)]
(test-diff
(pig/dump command)
'[[2 4 6]])))
(testing "+"
(let [data (pig/return [2 4 6])
command (pig/reduce + data)]
(test-diff
(pig/dump command)
'[12]))))
(deftest test-fold
(let [data (pig/return [{:k :foo, :v 1}
{:k :foo, :v 2}
{:k :foo, :v 3}
{:k :bar, :v 4}
{:k :bar, :v 5}])]
(testing "inline sum"
(let [command (->> data
(pig/group-by :k
{:fold (fold/fold-fn +
(fn [acc value]
(+ acc (:v value))))}))]
(is (= (set (pig/dump command))
'#{[:foo 6]
[:bar 9]}))))
(testing "inline count"
(let [command (->> data
(pig/group-by :k
{:fold (fold/fold-fn (fn ([] 0)
([a b] (+ a b)))
(fn [acc _] (inc acc)))}))]
(is (= (set (pig/dump command))
'#{[:bar 2]
[:foo 3]}))))
(testing "using fold/count"
(let [command (->> data
(pig/group-by :k
{:fold (fold/count)}))]
(is (= (set (pig/dump command))
'#{[:bar 2]
[:foo 3]})))))
(testing "dual fold co-group"
(let [data0 (pig/return [{:k :foo, :a 1}
{:k :foo, :a 2}
{:k :foo, :a 3}
{:k :bar, :a 4}
{:k :bar, :a 5}])
data1 (pig/return [{:k :foo, :b 1}
{:k :foo, :b 2}
{:k :bar, :b 3}
{:k :bar, :b 4}
{:k :bar, :b 5}])
command (pig/cogroup [(data0 :on :k, :required true, :fold (->> (fold/map :a) (fold/sum)))
(data1 :on :k, :required true, :fold (->> (fold/map :b) (fold/sum)))]
vector)]
(is (= (set (pig/dump command))
'#{[:foo 6 3]
[:bar 9 12]}))))
(testing "fold all sum"
(let [data (pig/return [1 2 3 4])
command (pig/fold + data)]
(is (= (pig/dump command)
'[10]))))
(testing "fold all count"
(let [data (pig/return [1 2 3 4])
command (pig/fold (fold/count) data)]
(is (= (pig/dump command)
'[4])))))
(deftest test-cogroup
(let [data1 (pig/return [{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}
{:k :l, :v 9}
{:k :l, :v 11}])
data2 (pig/return [{:k nil, :v 2}
{:k nil, :v 4}
{:k :i, :v 6}
{:k :i, :v 8}
{:k :r, :v 10}
{:k :r, :v 12}])]
(testing "inner"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :by :k :type :required)
(data2 :by :k :type :required)]
vector)))
'#{[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]}))
(testing "left outer"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :required)
(data2 :on :k :type :optional)]
vector)))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] nil]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:l [{:k :l, :v 9} {:k :l, :v 11}] nil]}))
(testing "right outer"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :optional)
(data2 :on :k :type :required)]
vector)))
'#{[nil nil [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:r nil [{:k :r, :v 10} {:k :r, :v 12}]]}))
(testing "full outer"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :optional)
(data2 :on :k :type :optional)]
vector)))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] nil]
[nil nil [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:l [{:k :l, :v 9} {:k :l, :v 11}] nil]
[:r nil [{:k :r, :v 10} {:k :r, :v 12}]]}))
(testing "inner join nils"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :required)
(data2 :on :k :type :required)]
vector
{:join-nils true})))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]}))
(testing "left outer join nils"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :required)
(data2 :on :k :type :optional)]
vector
{:join-nils true})))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:l [{:k :l, :v 9} {:k :l, :v 11}] nil]}))
(testing "right outer join nils"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :optional)
(data2 :on :k :type :required)]
vector
{:join-nils true})))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:r nil [{:k :r, :v 10} {:k :r, :v 12}]]}))
(testing "full outer join nils"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :optional)
(data2 :on :k :type :optional)]
vector
{:join-nils true})))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:l [{:k :l, :v 9} {:k :l, :v 11}] nil]
[:r nil [{:k :r, :v 10} {:k :r, :v 12}]]}))
(testing "self cogroup"
(let [data (pig/return [0 1 2])
command (pig/cogroup [(data)
(data)]
vector)]
(is (= (pig/dump command)
'[[2 (2) (2)] [0 (0) (0)] [1 (1) (1)]]))))
(testing "self cogroup with fold"
(let [data (pig/return [0 1 2])
command (pig/cogroup [(data :fold (fold/count))
(data :fold (fold/count))]
vector)]
(is (= (pig/dump command)
'[[2 1 1] [0 1 1] [1 1 1]]))))))
(deftest test-join
(let [data1 (pig/return [{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}
{:k :l, :v 9}
{:k :l, :v 11}])
data2 (pig/return [{:k nil, :v 2}
{:k nil, :v 4}
{:k :i, :v 6}
{:k :i, :v 8}
{:k :r, :v 10}
{:k :r, :v 12}])]
(testing "inner join - implicit :required"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k)
(data2 :on :k)]
vector)))
'#{[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]}))
(testing "inner"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :required)
(data2 :on :k :type :required)]
vector)))
'#{[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]}))
(testing "left outer"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :required)
(data2 :on :k :type :optional)]
vector)))
'#{[{:k nil, :v 1} nil]
[{:k nil, :v 3} nil]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[{:k :l, :v 9} nil]
[{:k :l, :v 11} nil]}))
(testing "right outer"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :optional)
(data2 :on :k :type :required)]
vector)))
'#{[nil {:k nil, :v 2}]
[nil {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[nil {:k :r, :v 10}]
[nil {:k :r, :v 12}]}))
(testing "full outer"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :optional)
(data2 :on :k :type :optional)]
vector)))
'#{[{:k nil, :v 1} nil]
[{:k nil, :v 3} nil]
[nil {:k nil, :v 2}]
[nil {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[{:k :l, :v 9} nil]
[{:k :l, :v 11} nil]
[nil {:k :r, :v 10}]
[nil {:k :r, :v 12}]}))
(testing "inner join nils"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :required)
(data2 :on :k :type :required)]
vector
{:join-nils true})))
'#{[{:k nil, :v 1} {:k nil, :v 2}]
[{:k nil, :v 3} {:k nil, :v 2}]
[{:k nil, :v 1} {:k nil, :v 4}]
[{:k nil, :v 3} {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]}))
(testing "left outer join nils"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :required)
(data2 :on :k :type :optional)]
vector
{:join-nils true})))
'#{[{:k nil, :v 1} {:k nil, :v 2}]
[{:k nil, :v 3} {:k nil, :v 2}]
[{:k nil, :v 1} {:k nil, :v 4}]
[{:k nil, :v 3} {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[{:k :l, :v 9} nil]
[{:k :l, :v 11} nil]}))
(testing "right outer join nils"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :optional)
(data2 :on :k :type :required)]
vector
{:join-nils true})))
'#{[{:k nil, :v 1} {:k nil, :v 2}]
[{:k nil, :v 3} {:k nil, :v 2}]
[{:k nil, :v 1} {:k nil, :v 4}]
[{:k nil, :v 3} {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[nil {:k :r, :v 10}]
[nil {:k :r, :v 12}]}))
(testing "full outer join nils"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :optional)
(data2 :on :k :type :optional)]
vector
{:join-nils true})))
'#{[{:k nil, :v 1} {:k nil, :v 2}]
[{:k nil, :v 3} {:k nil, :v 2}]
[{:k nil, :v 1} {:k nil, :v 4}]
[{:k nil, :v 3} {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[{:k :l, :v 9} nil]
[{:k :l, :v 11} nil]
[nil {:k :r, :v 10}]
[nil {:k :r, :v 12}]}))
(testing "self join"
(let [data (pig/return [0 1 2])
command (pig/join [(data)
(data)]
vector)]
(is (= (pig/dump command)
[[2 2] [0 0] [1 1]]))))
(testing "key-selector defaults to identity"
(let [data1 (pig/return [1 2])
data2 (pig/return [2 3])
command (pig/join [(data1)
(data2)]
vector)]
(test-diff
(set (pig/dump command))
'#{[2 2]})))))
(deftest test-filter-by
(let [data (pig/return [{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}
{:k :l, :v 9}
{:k :l, :v 11}])]
(testing "Normal"
(let [keys (pig/return [:i])]
(test-diff
(set (pig/dump (pig/filter-by :k keys data)))
'#{{:k :i, :v 5}
{:k :i, :v 7}})))
(testing "Nil keys"
(let [keys (pig/return [:i nil])]
(test-diff
(set (pig/dump (pig/filter-by :k keys data)))
'#{{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}})))
(testing "Duplicate keys"
(let [keys (pig/return [:i :i])]
(test-diff
(pig/dump (pig/filter-by :k keys data))
'[{:k :i, :v 5}
{:k :i, :v 7}
{:k :i, :v 5}
{:k :i, :v 7}])))))
(deftest test-remove-by
(let [data (pig/return [{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}
{:k :l, :v 9}
{:k :l, :v 11}])]
(testing "Normal"
(let [keys (pig/return [:i])]
(test-diff
(set (pig/dump (pig/remove-by :k keys data)))
'#{{:k nil, :v 1}
{:k nil, :v 3}
{:k :l, :v 9}
{:k :l, :v 11}})))
(testing "Nil keys"
(let [keys (pig/return [:i nil])]
(test-diff
(set (pig/dump (pig/remove-by :k keys data)))
'#{{:k :l, :v 9}
{:k :l, :v 11}})))
(testing "Duplicate keys"
(let [keys (pig/return [:i :i])]
(test-diff
(set (pig/dump (pig/remove-by :k keys data)))
'#{{:k nil, :v 1}
{:k nil, :v 3}
{:k :l, :v 9}
{:k :l, :v 11}})))))
| true | ;;
;;
;; Copyright 2013 PI:NAME:<NAME>END_PIflix, Inc.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;;
(ns pigpen.functional.join-test
(:use clojure.test)
(:require [pigpen.extensions.test :refer [test-diff]]
[pigpen.core :as pig]
[pigpen.fold :as fold]))
(deftest test-group-by
(let [data (pig/return [{:a 1 :b 2}
{:a 1 :b 3}
{:a 2 :b 4}])
command (pig/group-by :a data)]
(test-diff
(set (pig/dump command))
'#{[1 ({:a 1, :b 2} {:a 1, :b 3})]
[2 ({:a 2, :b 4})]})))
(deftest test-into
(let [data (pig/return [2 4 6])
command (pig/into [] data)]
(test-diff
(pig/dump command)
'[[2 4 6]])))
(deftest test-reduce
(testing "conj"
(let [data (pig/return [2 4 6])
command (pig/reduce conj [] data)]
(test-diff
(pig/dump command)
'[[2 4 6]])))
(testing "+"
(let [data (pig/return [2 4 6])
command (pig/reduce + data)]
(test-diff
(pig/dump command)
'[12]))))
(deftest test-fold
(let [data (pig/return [{:k :foo, :v 1}
{:k :foo, :v 2}
{:k :foo, :v 3}
{:k :bar, :v 4}
{:k :bar, :v 5}])]
(testing "inline sum"
(let [command (->> data
(pig/group-by :k
{:fold (fold/fold-fn +
(fn [acc value]
(+ acc (:v value))))}))]
(is (= (set (pig/dump command))
'#{[:foo 6]
[:bar 9]}))))
(testing "inline count"
(let [command (->> data
(pig/group-by :k
{:fold (fold/fold-fn (fn ([] 0)
([a b] (+ a b)))
(fn [acc _] (inc acc)))}))]
(is (= (set (pig/dump command))
'#{[:bar 2]
[:foo 3]}))))
(testing "using fold/count"
(let [command (->> data
(pig/group-by :k
{:fold (fold/count)}))]
(is (= (set (pig/dump command))
'#{[:bar 2]
[:foo 3]})))))
(testing "dual fold co-group"
(let [data0 (pig/return [{:k :foo, :a 1}
{:k :foo, :a 2}
{:k :foo, :a 3}
{:k :bar, :a 4}
{:k :bar, :a 5}])
data1 (pig/return [{:k :foo, :b 1}
{:k :foo, :b 2}
{:k :bar, :b 3}
{:k :bar, :b 4}
{:k :bar, :b 5}])
command (pig/cogroup [(data0 :on :k, :required true, :fold (->> (fold/map :a) (fold/sum)))
(data1 :on :k, :required true, :fold (->> (fold/map :b) (fold/sum)))]
vector)]
(is (= (set (pig/dump command))
'#{[:foo 6 3]
[:bar 9 12]}))))
(testing "fold all sum"
(let [data (pig/return [1 2 3 4])
command (pig/fold + data)]
(is (= (pig/dump command)
'[10]))))
(testing "fold all count"
(let [data (pig/return [1 2 3 4])
command (pig/fold (fold/count) data)]
(is (= (pig/dump command)
'[4])))))
(deftest test-cogroup
(let [data1 (pig/return [{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}
{:k :l, :v 9}
{:k :l, :v 11}])
data2 (pig/return [{:k nil, :v 2}
{:k nil, :v 4}
{:k :i, :v 6}
{:k :i, :v 8}
{:k :r, :v 10}
{:k :r, :v 12}])]
(testing "inner"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :by :k :type :required)
(data2 :by :k :type :required)]
vector)))
'#{[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]}))
(testing "left outer"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :required)
(data2 :on :k :type :optional)]
vector)))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] nil]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:l [{:k :l, :v 9} {:k :l, :v 11}] nil]}))
(testing "right outer"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :optional)
(data2 :on :k :type :required)]
vector)))
'#{[nil nil [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:r nil [{:k :r, :v 10} {:k :r, :v 12}]]}))
(testing "full outer"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :optional)
(data2 :on :k :type :optional)]
vector)))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] nil]
[nil nil [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:l [{:k :l, :v 9} {:k :l, :v 11}] nil]
[:r nil [{:k :r, :v 10} {:k :r, :v 12}]]}))
(testing "inner join nils"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :required)
(data2 :on :k :type :required)]
vector
{:join-nils true})))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]}))
(testing "left outer join nils"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :required)
(data2 :on :k :type :optional)]
vector
{:join-nils true})))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:l [{:k :l, :v 9} {:k :l, :v 11}] nil]}))
(testing "right outer join nils"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :optional)
(data2 :on :k :type :required)]
vector
{:join-nils true})))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:r nil [{:k :r, :v 10} {:k :r, :v 12}]]}))
(testing "full outer join nils"
(test-diff
(set (pig/dump (pig/cogroup [(data1 :on :k :type :optional)
(data2 :on :k :type :optional)]
vector
{:join-nils true})))
'#{[nil [{:k nil, :v 1} {:k nil, :v 3}] [{:k nil, :v 2} {:k nil, :v 4}]]
[:i [{:k :i, :v 5} {:k :i, :v 7}] [{:k :i, :v 6} {:k :i, :v 8}]]
[:l [{:k :l, :v 9} {:k :l, :v 11}] nil]
[:r nil [{:k :r, :v 10} {:k :r, :v 12}]]}))
(testing "self cogroup"
(let [data (pig/return [0 1 2])
command (pig/cogroup [(data)
(data)]
vector)]
(is (= (pig/dump command)
'[[2 (2) (2)] [0 (0) (0)] [1 (1) (1)]]))))
(testing "self cogroup with fold"
(let [data (pig/return [0 1 2])
command (pig/cogroup [(data :fold (fold/count))
(data :fold (fold/count))]
vector)]
(is (= (pig/dump command)
'[[2 1 1] [0 1 1] [1 1 1]]))))))
(deftest test-join
(let [data1 (pig/return [{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}
{:k :l, :v 9}
{:k :l, :v 11}])
data2 (pig/return [{:k nil, :v 2}
{:k nil, :v 4}
{:k :i, :v 6}
{:k :i, :v 8}
{:k :r, :v 10}
{:k :r, :v 12}])]
(testing "inner join - implicit :required"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k)
(data2 :on :k)]
vector)))
'#{[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]}))
(testing "inner"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :required)
(data2 :on :k :type :required)]
vector)))
'#{[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]}))
(testing "left outer"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :required)
(data2 :on :k :type :optional)]
vector)))
'#{[{:k nil, :v 1} nil]
[{:k nil, :v 3} nil]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[{:k :l, :v 9} nil]
[{:k :l, :v 11} nil]}))
(testing "right outer"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :optional)
(data2 :on :k :type :required)]
vector)))
'#{[nil {:k nil, :v 2}]
[nil {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[nil {:k :r, :v 10}]
[nil {:k :r, :v 12}]}))
(testing "full outer"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :optional)
(data2 :on :k :type :optional)]
vector)))
'#{[{:k nil, :v 1} nil]
[{:k nil, :v 3} nil]
[nil {:k nil, :v 2}]
[nil {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[{:k :l, :v 9} nil]
[{:k :l, :v 11} nil]
[nil {:k :r, :v 10}]
[nil {:k :r, :v 12}]}))
(testing "inner join nils"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :required)
(data2 :on :k :type :required)]
vector
{:join-nils true})))
'#{[{:k nil, :v 1} {:k nil, :v 2}]
[{:k nil, :v 3} {:k nil, :v 2}]
[{:k nil, :v 1} {:k nil, :v 4}]
[{:k nil, :v 3} {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]}))
(testing "left outer join nils"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :required)
(data2 :on :k :type :optional)]
vector
{:join-nils true})))
'#{[{:k nil, :v 1} {:k nil, :v 2}]
[{:k nil, :v 3} {:k nil, :v 2}]
[{:k nil, :v 1} {:k nil, :v 4}]
[{:k nil, :v 3} {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[{:k :l, :v 9} nil]
[{:k :l, :v 11} nil]}))
(testing "right outer join nils"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :optional)
(data2 :on :k :type :required)]
vector
{:join-nils true})))
'#{[{:k nil, :v 1} {:k nil, :v 2}]
[{:k nil, :v 3} {:k nil, :v 2}]
[{:k nil, :v 1} {:k nil, :v 4}]
[{:k nil, :v 3} {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[nil {:k :r, :v 10}]
[nil {:k :r, :v 12}]}))
(testing "full outer join nils"
(test-diff
(set (pig/dump (pig/join [(data1 :on :k :type :optional)
(data2 :on :k :type :optional)]
vector
{:join-nils true})))
'#{[{:k nil, :v 1} {:k nil, :v 2}]
[{:k nil, :v 3} {:k nil, :v 2}]
[{:k nil, :v 1} {:k nil, :v 4}]
[{:k nil, :v 3} {:k nil, :v 4}]
[{:k :i, :v 5} {:k :i, :v 6}]
[{:k :i, :v 5} {:k :i, :v 8}]
[{:k :i, :v 7} {:k :i, :v 6}]
[{:k :i, :v 7} {:k :i, :v 8}]
[{:k :l, :v 9} nil]
[{:k :l, :v 11} nil]
[nil {:k :r, :v 10}]
[nil {:k :r, :v 12}]}))
(testing "self join"
(let [data (pig/return [0 1 2])
command (pig/join [(data)
(data)]
vector)]
(is (= (pig/dump command)
[[2 2] [0 0] [1 1]]))))
(testing "key-selector defaults to identity"
(let [data1 (pig/return [1 2])
data2 (pig/return [2 3])
command (pig/join [(data1)
(data2)]
vector)]
(test-diff
(set (pig/dump command))
'#{[2 2]})))))
(deftest test-filter-by
(let [data (pig/return [{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}
{:k :l, :v 9}
{:k :l, :v 11}])]
(testing "Normal"
(let [keys (pig/return [:i])]
(test-diff
(set (pig/dump (pig/filter-by :k keys data)))
'#{{:k :i, :v 5}
{:k :i, :v 7}})))
(testing "Nil keys"
(let [keys (pig/return [:i nil])]
(test-diff
(set (pig/dump (pig/filter-by :k keys data)))
'#{{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}})))
(testing "Duplicate keys"
(let [keys (pig/return [:i :i])]
(test-diff
(pig/dump (pig/filter-by :k keys data))
'[{:k :i, :v 5}
{:k :i, :v 7}
{:k :i, :v 5}
{:k :i, :v 7}])))))
(deftest test-remove-by
(let [data (pig/return [{:k nil, :v 1}
{:k nil, :v 3}
{:k :i, :v 5}
{:k :i, :v 7}
{:k :l, :v 9}
{:k :l, :v 11}])]
(testing "Normal"
(let [keys (pig/return [:i])]
(test-diff
(set (pig/dump (pig/remove-by :k keys data)))
'#{{:k nil, :v 1}
{:k nil, :v 3}
{:k :l, :v 9}
{:k :l, :v 11}})))
(testing "Nil keys"
(let [keys (pig/return [:i nil])]
(test-diff
(set (pig/dump (pig/remove-by :k keys data)))
'#{{:k :l, :v 9}
{:k :l, :v 11}})))
(testing "Duplicate keys"
(let [keys (pig/return [:i :i])]
(test-diff
(set (pig/dump (pig/remove-by :k keys data)))
'#{{:k nil, :v 1}
{:k nil, :v 3}
{:k :l, :v 9}
{:k :l, :v 11}})))))
|
[
{
"context": "irect back\r\n to the login page.\"\r\n [{{username \"user-name\" password \"password\"} :multipart-params\r\n sess",
"end": 622,
"score": 0.9996725916862488,
"start": 613,
"tag": "USERNAME",
"value": "user-name"
},
{
"context": "login page.\"\r\n [{{username \"user-name\" password \"password\"} :multipart-params\r\n session ",
"end": 642,
"score": 0.9977691173553467,
"start": 634,
"tag": "PASSWORD",
"value": "password"
}
] | src/clj/cwiki/routes/login.clj | clartaq/cwiki | 3 | ;;;
;;; Routes for login, logout, etc.
;;;
(ns cwiki.routes.login
(:require [compojure.core :refer :all]
[cwiki.models.wiki-db :as db]
[cwiki.layouts.login :as login-layout]
[cwiki.util.req-info :as ri]
[ring.util.response :refer [redirect]]))
(defn get-login
"Gather user credentials for login."
[req]
(login-layout/login-page))
(defn post-login
"Check that the user name and password match credentials in the database.
If so, add the identity to the current session, otherwise redirect back
to the login page."
[{{username "user-name" password "password"} :multipart-params
session :session :as req}]
(if-let [user (db/get-user-by-username-and-password username password)]
; If authenticated
(let [identity (dissoc user :user_password)
new-session (assoc (redirect "/")
:session (assoc session :identity identity))]
(ri/save-session-info new-session)
new-session)
; Otherwise
(redirect "/login")))
(defn get-logout
"Ask the user to verify that they want to log out."
[req]
(login-layout/view-logout-page req))
(defn post-logout
"Log out the current user."
[{session :session}]
(let [new-session (assoc (redirect "/login")
:session (dissoc session :identity))]
(ri/save-session-info new-session)
new-session))
(defroutes login-routes
(GET "/login" [] get-login)
(POST "/login" [] post-login)
(GET "/logout" [] get-logout)
(POST "/logout" [] post-logout))
| 97629 | ;;;
;;; Routes for login, logout, etc.
;;;
(ns cwiki.routes.login
(:require [compojure.core :refer :all]
[cwiki.models.wiki-db :as db]
[cwiki.layouts.login :as login-layout]
[cwiki.util.req-info :as ri]
[ring.util.response :refer [redirect]]))
(defn get-login
"Gather user credentials for login."
[req]
(login-layout/login-page))
(defn post-login
"Check that the user name and password match credentials in the database.
If so, add the identity to the current session, otherwise redirect back
to the login page."
[{{username "user-name" password "<PASSWORD>"} :multipart-params
session :session :as req}]
(if-let [user (db/get-user-by-username-and-password username password)]
; If authenticated
(let [identity (dissoc user :user_password)
new-session (assoc (redirect "/")
:session (assoc session :identity identity))]
(ri/save-session-info new-session)
new-session)
; Otherwise
(redirect "/login")))
(defn get-logout
"Ask the user to verify that they want to log out."
[req]
(login-layout/view-logout-page req))
(defn post-logout
"Log out the current user."
[{session :session}]
(let [new-session (assoc (redirect "/login")
:session (dissoc session :identity))]
(ri/save-session-info new-session)
new-session))
(defroutes login-routes
(GET "/login" [] get-login)
(POST "/login" [] post-login)
(GET "/logout" [] get-logout)
(POST "/logout" [] post-logout))
| true | ;;;
;;; Routes for login, logout, etc.
;;;
(ns cwiki.routes.login
(:require [compojure.core :refer :all]
[cwiki.models.wiki-db :as db]
[cwiki.layouts.login :as login-layout]
[cwiki.util.req-info :as ri]
[ring.util.response :refer [redirect]]))
(defn get-login
"Gather user credentials for login."
[req]
(login-layout/login-page))
(defn post-login
"Check that the user name and password match credentials in the database.
If so, add the identity to the current session, otherwise redirect back
to the login page."
[{{username "user-name" password "PI:PASSWORD:<PASSWORD>END_PI"} :multipart-params
session :session :as req}]
(if-let [user (db/get-user-by-username-and-password username password)]
; If authenticated
(let [identity (dissoc user :user_password)
new-session (assoc (redirect "/")
:session (assoc session :identity identity))]
(ri/save-session-info new-session)
new-session)
; Otherwise
(redirect "/login")))
(defn get-logout
"Ask the user to verify that they want to log out."
[req]
(login-layout/view-logout-page req))
(defn post-logout
"Log out the current user."
[{session :session}]
(let [new-session (assoc (redirect "/login")
:session (dissoc session :identity))]
(ri/save-session-info new-session)
new-session))
(defroutes login-routes
(GET "/login" [] get-login)
(POST "/login" [] post-login)
(GET "/logout" [] get-logout)
(POST "/logout" [] post-logout))
|
[
{
"context": "hronosConnection\n {:url url\n :user user\n :password password}))\n",
"end": 705,
"score": 0.992661714553833,
"start": 701,
"tag": "USERNAME",
"value": "user"
},
{
"context": " {:url url\n :user user\n :password password}))\n",
"end": 729,
"score": 0.9932609796524048,
"start": 721,
"tag": "PASSWORD",
"value": "password"
}
] | src/de/otto/machroput/chronos/connection.clj | otto-de/machroput | 7 | (ns de.otto.machroput.chronos.connection
(:require
[de.otto.machroput.utils.http-utils :refer :all]
[clojure.data.json :as json]))
(defn has-parent-dependency? [json]
(not (nil? (:parents json))))
(defprotocol ChronosApi
(create-new-app [self json]))
(defrecord ChronosConnection [url user password ]
ChronosApi
(create-new-app [self json]
(let [json-str (json/write-str json)]
(if (has-parent-dependency? json)
(a-json-request self POST "/scheduler/dependency" json-str)
(a-json-request self POST "/scheduler/iso8601" json-str)))))
(defn new-chronos-connection [{:keys [url user password]} ]
(map->ChronosConnection
{:url url
:user user
:password password}))
| 113803 | (ns de.otto.machroput.chronos.connection
(:require
[de.otto.machroput.utils.http-utils :refer :all]
[clojure.data.json :as json]))
(defn has-parent-dependency? [json]
(not (nil? (:parents json))))
(defprotocol ChronosApi
(create-new-app [self json]))
(defrecord ChronosConnection [url user password ]
ChronosApi
(create-new-app [self json]
(let [json-str (json/write-str json)]
(if (has-parent-dependency? json)
(a-json-request self POST "/scheduler/dependency" json-str)
(a-json-request self POST "/scheduler/iso8601" json-str)))))
(defn new-chronos-connection [{:keys [url user password]} ]
(map->ChronosConnection
{:url url
:user user
:password <PASSWORD>}))
| true | (ns de.otto.machroput.chronos.connection
(:require
[de.otto.machroput.utils.http-utils :refer :all]
[clojure.data.json :as json]))
(defn has-parent-dependency? [json]
(not (nil? (:parents json))))
(defprotocol ChronosApi
(create-new-app [self json]))
(defrecord ChronosConnection [url user password ]
ChronosApi
(create-new-app [self json]
(let [json-str (json/write-str json)]
(if (has-parent-dependency? json)
(a-json-request self POST "/scheduler/dependency" json-str)
(a-json-request self POST "/scheduler/iso8601" json-str)))))
(defn new-chronos-connection [{:keys [url user password]} ]
(map->ChronosConnection
{:url url
:user user
:password PI:PASSWORD:<PASSWORD>END_PI}))
|
[
{
"context": "21-riemann-by-stream/\n\n(def email (mailer {:from \"me@mcorbin.fr\"\n :host \"mail.foo.com\"\n ",
"end": 398,
"score": 0.9999185800552368,
"start": 385,
"tag": "EMAIL",
"value": "me@mcorbin.fr"
},
{
"context": " :user \"foo\"\n :password \"bar\"}))\n",
"end": 507,
"score": 0.9994214773178101,
"start": 504,
"tag": "PASSWORD",
"value": "bar"
}
] | mycorp/output/email.clj | mcorbin/riemann-configuration-example | 1 | (ns mycorp.output.email
"send email"
(:require [riemann.config :refer :all]
[riemann.streams :refer :all]
[riemann.test :refer :all]
[riemann.email :refer :all]
[clojure.tools.logging :refer :all]))
;; this stream can be used to send email
;; cf http://localhost:3000/posts/2017-05-21-riemann-by-stream/
(def email (mailer {:from "me@mcorbin.fr"
:host "mail.foo.com"
:user "foo"
:password "bar"}))
| 110159 | (ns mycorp.output.email
"send email"
(:require [riemann.config :refer :all]
[riemann.streams :refer :all]
[riemann.test :refer :all]
[riemann.email :refer :all]
[clojure.tools.logging :refer :all]))
;; this stream can be used to send email
;; cf http://localhost:3000/posts/2017-05-21-riemann-by-stream/
(def email (mailer {:from "<EMAIL>"
:host "mail.foo.com"
:user "foo"
:password "<PASSWORD>"}))
| true | (ns mycorp.output.email
"send email"
(:require [riemann.config :refer :all]
[riemann.streams :refer :all]
[riemann.test :refer :all]
[riemann.email :refer :all]
[clojure.tools.logging :refer :all]))
;; this stream can be used to send email
;; cf http://localhost:3000/posts/2017-05-21-riemann-by-stream/
(def email (mailer {:from "PI:EMAIL:<EMAIL>END_PI"
:host "mail.foo.com"
:user "foo"
:password "PI:PASSWORD:<PASSWORD>END_PI"}))
|
[
{
"context": "-number port\n :database-name db\n :username username\n :password password}))\n\n(defstate db\n :start",
"end": 577,
"score": 0.9955787658691406,
"start": 569,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ase-name db\n :username username\n :password password}))\n\n(defstate db\n :start (let [{database-url :da",
"end": 601,
"score": 0.998691201210022,
"start": 593,
"tag": "PASSWORD",
"value": "password"
}
] | src/rocket_link/db.clj | Seryiza/rocket-link | 2 | (ns rocket-link.db
(:require [mount.core :refer [defstate]]
[hikari-cp.core :as cp]
[rocket-link.config :refer [config]]
[clojure.string :as str]))
(defn url->opts [database-url]
(let [uri (java.net.URI. database-url)
path (.getPath uri)
host (.getHost uri)
port (.getPort uri)
[_ db] (re-find #"\/(.+)" path)
[username password] (str/split (.getUserInfo uri) #"\:")]
{:adapter "postgresql"
:server-name host
:port-number port
:database-name db
:username username
:password password}))
(defstate db
:start (let [{database-url :database-url} config
pool-opts (url->opts database-url)
datasource (cp/make-datasource pool-opts)]
{:datasource datasource})
:stop (-> db :datasource cp/close-datasource))
| 108641 | (ns rocket-link.db
(:require [mount.core :refer [defstate]]
[hikari-cp.core :as cp]
[rocket-link.config :refer [config]]
[clojure.string :as str]))
(defn url->opts [database-url]
(let [uri (java.net.URI. database-url)
path (.getPath uri)
host (.getHost uri)
port (.getPort uri)
[_ db] (re-find #"\/(.+)" path)
[username password] (str/split (.getUserInfo uri) #"\:")]
{:adapter "postgresql"
:server-name host
:port-number port
:database-name db
:username username
:password <PASSWORD>}))
(defstate db
:start (let [{database-url :database-url} config
pool-opts (url->opts database-url)
datasource (cp/make-datasource pool-opts)]
{:datasource datasource})
:stop (-> db :datasource cp/close-datasource))
| true | (ns rocket-link.db
(:require [mount.core :refer [defstate]]
[hikari-cp.core :as cp]
[rocket-link.config :refer [config]]
[clojure.string :as str]))
(defn url->opts [database-url]
(let [uri (java.net.URI. database-url)
path (.getPath uri)
host (.getHost uri)
port (.getPort uri)
[_ db] (re-find #"\/(.+)" path)
[username password] (str/split (.getUserInfo uri) #"\:")]
{:adapter "postgresql"
:server-name host
:port-number port
:database-name db
:username username
:password PI:PASSWORD:<PASSWORD>END_PI}))
(defstate db
:start (let [{database-url :database-url} config
pool-opts (url->opts database-url)
datasource (cp/make-datasource pool-opts)]
{:datasource datasource})
:stop (-> db :datasource cp/close-datasource))
|
[
{
"context": "s metadata)}]\n [:meta {:name \"author\", :content \"Nurullah Akkaya\"}]\n [:link {:rel \"icon\", \n\t :href \"/images/favi",
"end": 368,
"score": 0.9998831152915955,
"start": 353,
"tag": "NAME",
"value": "Nurullah Akkaya"
},
{
"context": "py; 2018\" \n [:a {:href \"http://nakkaya.com\"} \" Nurullah Akkaya\"]]]]\n ;;\n ;;\n (if (= (:type metadata) :post) \n",
"end": 3247,
"score": 0.9998891949653625,
"start": 3232,
"tag": "NAME",
"value": "Nurullah Akkaya"
}
] | resources/templates/default.clj | nakkaya/nakkaya.com | 29 | ;;(doctype :xhtml-transitional)
[:html
{:xmlns "http://www.w3.org/1999/xhtml", :lang "en", :xml:lang "en"}
[:head
[:meta
{:http-equiv "content-type", :content "text/html; charset=UTF-8"}]
[:meta {:name "description", :content (:description metadata)}]
[:meta {:name "keywords", :content (:tags metadata)}]
[:meta {:name "author", :content "Nurullah Akkaya"}]
[:link {:rel "icon",
:href "/images/favicon.ico" :type "image/x-icon"}]
[:link {:rel "shortcut icon",
:href "/images/favicon.ico" :type "image/x-icon"}]
[:link {:rel "stylesheet", :type "text/css", :href "/default.css"}]
[:link
{:rel "alternate", :type "application/rss+xml",
:title (:site-title (static.config/config)), :href "/rss-feed"}]
(if (= (:type metadata) :post)
[:link {:rel "canonical"
:href (str "http://nakkaya.com" (:url metadata))}])
[:script {:src "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML",
:type "text/javascript"}]
[:title (:title metadata)]]
[:body
[:div
{:id "wrap"}
[:div
{:id "header"}
[:h1
[:a
{:href "/"}
"nakkaya"
[:span {:class "fade-small"} "dot"]
[:span {:class "fade"} "com"]]]
[:div
{:class "pages"}
[:a {:href "/", :class "page"} "Home"] " | "
[:a {:href "/projects.html", :class "page"} "Projects"] " | "
[:a {:href "/archives.html", :class "page"} "Archives"] " | "
[:a {:href "/tags/", :class "page"} "Tags"] " | "
[:a {:href "/contact.html", :class "page" :rel "author"} "About"]
[:form {:method "get"
:action "http://www.google.com/search" :id "searchform"}
[:div
[:input {:type "text" :name "q" :class "box" :id "s"}]
[:input {:type "hidden" :name "sitesearch"
:value "nakkaya.com"}]]]]]
[:div
{:id "content"}
[:div
{:id "post"}
(if (or (= (:type metadata) :post)
(= (:type metadata) :site))
[:h2 {:class "page-title"} (:title metadata)])
content
(if (= (:type metadata) :post)
(reduce
(fn[h v]
(conj h [:a {:href (str "/tags/#" v)} (str v " ")]))
[:div {:class "post-tags"} "Tags: "]
(.split (:tags metadata) " ")))]
(if (= (:type metadata) :post)
[:div
{:id "related"}
[:h3 {:class "random-posts"} "Random Posts"]
[:ul
{:class "posts"}
(map
#(let [f %
url (static.core/post-url f)
[metadata _] (static.io/read-doc f)
date (static.core/parse-date
"yyyy-MM-dd" "dd MMM yyyy"
(re-find #"\d*-\d*-\d*" (str f)))]
[:li [:span date] [:a {:href url} (:title metadata)]])
(take 5 (shuffle (static.io/list-files :posts))))]])
[:div {:id "disqus"}
(if (= (:type metadata) :post)
"<div id=\"disqus_thread\"></div><script type=\"text/javascript\" src=\"//disqus.com/forums/nakkaya/embed.js\"></script><noscript><a href=\"//disqus.com/forums/nakkaya/?url=ref\">View the discussion thread.</a></noscript><a href=\"//disqus.com\" class=\"dsq-brlink\">blog comments powered by <span class=\"logo-disqus\">Disqus</span></a>")]]
[:div
{:id "footer"}
[:a {:href "/rss-feed"} " RSS Feed"]
[:p "© 2018"
[:a {:href "http://nakkaya.com"} " Nurullah Akkaya"]]]]
;;
;;
(if (= (:type metadata) :post)
"<script type=\"text/javascript\">
//<![CDATA[
(function() {
var links = document.getElementsByTagName('a');
var query = '?';
for(var i = 0; i < links.length; i++) {
if(links[i].href.indexOf('#disqus_thread') >= 0) {
query += 'url' + i + '=' + encodeURIComponent(links[i].href) + '&';
}
}
document.write('<script charset=\"utf-8\" type=\"text/javascript\" src=\"//disqus.com/forums/nakkaya/get_num_replies.js' + query + '\"></' + 'script>');
})();
//]]>
</script>")]]
| 68244 | ;;(doctype :xhtml-transitional)
[:html
{:xmlns "http://www.w3.org/1999/xhtml", :lang "en", :xml:lang "en"}
[:head
[:meta
{:http-equiv "content-type", :content "text/html; charset=UTF-8"}]
[:meta {:name "description", :content (:description metadata)}]
[:meta {:name "keywords", :content (:tags metadata)}]
[:meta {:name "author", :content "<NAME>"}]
[:link {:rel "icon",
:href "/images/favicon.ico" :type "image/x-icon"}]
[:link {:rel "shortcut icon",
:href "/images/favicon.ico" :type "image/x-icon"}]
[:link {:rel "stylesheet", :type "text/css", :href "/default.css"}]
[:link
{:rel "alternate", :type "application/rss+xml",
:title (:site-title (static.config/config)), :href "/rss-feed"}]
(if (= (:type metadata) :post)
[:link {:rel "canonical"
:href (str "http://nakkaya.com" (:url metadata))}])
[:script {:src "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML",
:type "text/javascript"}]
[:title (:title metadata)]]
[:body
[:div
{:id "wrap"}
[:div
{:id "header"}
[:h1
[:a
{:href "/"}
"nakkaya"
[:span {:class "fade-small"} "dot"]
[:span {:class "fade"} "com"]]]
[:div
{:class "pages"}
[:a {:href "/", :class "page"} "Home"] " | "
[:a {:href "/projects.html", :class "page"} "Projects"] " | "
[:a {:href "/archives.html", :class "page"} "Archives"] " | "
[:a {:href "/tags/", :class "page"} "Tags"] " | "
[:a {:href "/contact.html", :class "page" :rel "author"} "About"]
[:form {:method "get"
:action "http://www.google.com/search" :id "searchform"}
[:div
[:input {:type "text" :name "q" :class "box" :id "s"}]
[:input {:type "hidden" :name "sitesearch"
:value "nakkaya.com"}]]]]]
[:div
{:id "content"}
[:div
{:id "post"}
(if (or (= (:type metadata) :post)
(= (:type metadata) :site))
[:h2 {:class "page-title"} (:title metadata)])
content
(if (= (:type metadata) :post)
(reduce
(fn[h v]
(conj h [:a {:href (str "/tags/#" v)} (str v " ")]))
[:div {:class "post-tags"} "Tags: "]
(.split (:tags metadata) " ")))]
(if (= (:type metadata) :post)
[:div
{:id "related"}
[:h3 {:class "random-posts"} "Random Posts"]
[:ul
{:class "posts"}
(map
#(let [f %
url (static.core/post-url f)
[metadata _] (static.io/read-doc f)
date (static.core/parse-date
"yyyy-MM-dd" "dd MMM yyyy"
(re-find #"\d*-\d*-\d*" (str f)))]
[:li [:span date] [:a {:href url} (:title metadata)]])
(take 5 (shuffle (static.io/list-files :posts))))]])
[:div {:id "disqus"}
(if (= (:type metadata) :post)
"<div id=\"disqus_thread\"></div><script type=\"text/javascript\" src=\"//disqus.com/forums/nakkaya/embed.js\"></script><noscript><a href=\"//disqus.com/forums/nakkaya/?url=ref\">View the discussion thread.</a></noscript><a href=\"//disqus.com\" class=\"dsq-brlink\">blog comments powered by <span class=\"logo-disqus\">Disqus</span></a>")]]
[:div
{:id "footer"}
[:a {:href "/rss-feed"} " RSS Feed"]
[:p "© 2018"
[:a {:href "http://nakkaya.com"} " <NAME>"]]]]
;;
;;
(if (= (:type metadata) :post)
"<script type=\"text/javascript\">
//<![CDATA[
(function() {
var links = document.getElementsByTagName('a');
var query = '?';
for(var i = 0; i < links.length; i++) {
if(links[i].href.indexOf('#disqus_thread') >= 0) {
query += 'url' + i + '=' + encodeURIComponent(links[i].href) + '&';
}
}
document.write('<script charset=\"utf-8\" type=\"text/javascript\" src=\"//disqus.com/forums/nakkaya/get_num_replies.js' + query + '\"></' + 'script>');
})();
//]]>
</script>")]]
| true | ;;(doctype :xhtml-transitional)
[:html
{:xmlns "http://www.w3.org/1999/xhtml", :lang "en", :xml:lang "en"}
[:head
[:meta
{:http-equiv "content-type", :content "text/html; charset=UTF-8"}]
[:meta {:name "description", :content (:description metadata)}]
[:meta {:name "keywords", :content (:tags metadata)}]
[:meta {:name "author", :content "PI:NAME:<NAME>END_PI"}]
[:link {:rel "icon",
:href "/images/favicon.ico" :type "image/x-icon"}]
[:link {:rel "shortcut icon",
:href "/images/favicon.ico" :type "image/x-icon"}]
[:link {:rel "stylesheet", :type "text/css", :href "/default.css"}]
[:link
{:rel "alternate", :type "application/rss+xml",
:title (:site-title (static.config/config)), :href "/rss-feed"}]
(if (= (:type metadata) :post)
[:link {:rel "canonical"
:href (str "http://nakkaya.com" (:url metadata))}])
[:script {:src "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML",
:type "text/javascript"}]
[:title (:title metadata)]]
[:body
[:div
{:id "wrap"}
[:div
{:id "header"}
[:h1
[:a
{:href "/"}
"nakkaya"
[:span {:class "fade-small"} "dot"]
[:span {:class "fade"} "com"]]]
[:div
{:class "pages"}
[:a {:href "/", :class "page"} "Home"] " | "
[:a {:href "/projects.html", :class "page"} "Projects"] " | "
[:a {:href "/archives.html", :class "page"} "Archives"] " | "
[:a {:href "/tags/", :class "page"} "Tags"] " | "
[:a {:href "/contact.html", :class "page" :rel "author"} "About"]
[:form {:method "get"
:action "http://www.google.com/search" :id "searchform"}
[:div
[:input {:type "text" :name "q" :class "box" :id "s"}]
[:input {:type "hidden" :name "sitesearch"
:value "nakkaya.com"}]]]]]
[:div
{:id "content"}
[:div
{:id "post"}
(if (or (= (:type metadata) :post)
(= (:type metadata) :site))
[:h2 {:class "page-title"} (:title metadata)])
content
(if (= (:type metadata) :post)
(reduce
(fn[h v]
(conj h [:a {:href (str "/tags/#" v)} (str v " ")]))
[:div {:class "post-tags"} "Tags: "]
(.split (:tags metadata) " ")))]
(if (= (:type metadata) :post)
[:div
{:id "related"}
[:h3 {:class "random-posts"} "Random Posts"]
[:ul
{:class "posts"}
(map
#(let [f %
url (static.core/post-url f)
[metadata _] (static.io/read-doc f)
date (static.core/parse-date
"yyyy-MM-dd" "dd MMM yyyy"
(re-find #"\d*-\d*-\d*" (str f)))]
[:li [:span date] [:a {:href url} (:title metadata)]])
(take 5 (shuffle (static.io/list-files :posts))))]])
[:div {:id "disqus"}
(if (= (:type metadata) :post)
"<div id=\"disqus_thread\"></div><script type=\"text/javascript\" src=\"//disqus.com/forums/nakkaya/embed.js\"></script><noscript><a href=\"//disqus.com/forums/nakkaya/?url=ref\">View the discussion thread.</a></noscript><a href=\"//disqus.com\" class=\"dsq-brlink\">blog comments powered by <span class=\"logo-disqus\">Disqus</span></a>")]]
[:div
{:id "footer"}
[:a {:href "/rss-feed"} " RSS Feed"]
[:p "© 2018"
[:a {:href "http://nakkaya.com"} " PI:NAME:<NAME>END_PI"]]]]
;;
;;
(if (= (:type metadata) :post)
"<script type=\"text/javascript\">
//<![CDATA[
(function() {
var links = document.getElementsByTagName('a');
var query = '?';
for(var i = 0; i < links.length; i++) {
if(links[i].href.indexOf('#disqus_thread') >= 0) {
query += 'url' + i + '=' + encodeURIComponent(links[i].href) + '&';
}
}
document.write('<script charset=\"utf-8\" type=\"text/javascript\" src=\"//disqus.com/forums/nakkaya/get_num_replies.js' + query + '\"></' + 'script>');
})();
//]]>
</script>")]]
|
[
{
"context": "[[eval]] which does\n all the job.\"\n\n {:author \"Adam Helinski\"}\n\n (:import (convex.core Block\n ",
"end": 1352,
"score": 0.9989499449729919,
"start": 1339,
"tag": "NAME",
"value": "Adam Helinski"
}
] | project/cvm/src/clj/main/convex/cvm.clj | rosejn/convex.cljc | 30 | (ns convex.cvm
"Code execution in the CVM, altering state, and gaining insights.
Central entities of this namespaces are contextes and they can be created using [[ctx]].
All other functions revolve around them. While the design of a context is mostly immutable, whenever an altering function
is applied (eg. [[juice-set]]) or code is handled in any way (eg. [[eval]]), old context must be discarded and only returned
one should be used.
Cheap copies can be created using [[fork]].
Actions involving code (eg. [[compile]], [[exec]], ...) return a new context which holds either a [[result]] or an [[exception]].
Those actions always consume [[juice]].
Given that a \"cell\" is the term reserved for CVM data and objects, execution consists of following steps:
| Step | Function | Does |
|---|---|---|
| 1 | [[expand]] | `cell` -> `canonical cell`, applies macros |
| 2 | [[compile]] | `canonical cell` -> `op`, preparing executable code |
| 3 | [[exec]] | Executes compiled code |
Any cell can be applied safely to those functions, worse that can happen is nothing (eg. providing an already compiled cell to
[[compile]]).
If fine-grained control is not needed and if source is not compiled anyways, a simpler alternative is to use [[eval]] which does
all the job."
{:author "Adam Helinski"}
(:import (convex.core Block
State)
(convex.core.data ABlobMap
AccountKey
AccountStatus
ACell
Address
AHashMap)
(convex.core.data.prim CVMLong)
(convex.core.init Init)
(convex.core.lang AFn
AOp
Context)
(convex.core.lang.impl ErrorValue))
(:refer-clojure :exclude [compile
def
eval
key
time])
(:require [convex.cell :as $.cell]))
(set! *warn-on-reflection*
true)
(declare juice-set
state-set)
;;;;;;;;;; Creating a new context
(defn ctx
"Creates a \"fake\" context. Ideal for testing and repl'ing around.
An optional map of options may be provided:
| Key | Value | Default |
|---|---|---|
| `:convex.cvm/address` | Address of the executing account | Reserved address (an actor) |
| `:convex.cvm/state` | Genesis state | Initial state with Convex actors and libraries |
| `:convex.peer/key | Account key for the initial peer (see [[convex.cell/account-key]]) | Fake key, all 0's |"
(^Context []
(ctx nil))
(^Context [option+]
(Context/createFake (or (:convex.cvm/state option+)
(Init/createState [(or (:convex.peer/key option+)
($.cell/key ($.cell/blob (byte-array 32))))]))
(or (:convex.cvm/address option+)
Init/RESERVED_ADDRESS))))
(defn fork
"Duplicates the given [[ctx]] (very cheap).
Any operation on the returned copy has no impact on the original context.
Attention, forking a `ctx` looses any attached [[result]] or [[exception]]."
^Context
[^Context ctx]
(.fork ctx))
(defn fork-to
"Like [[fork]] but switches the executing account.
Note: CVM log is lost."
^Context
[^Context ctx address]
(.forkWithAddress ctx
address))
;;;;;;;;;; Querying context properties
(defn- -wrap-address
;; Wraps `x` in an Address object if it is not already.
^Address
[x]
(cond->
x
(number? x)
$.cell/address))
(defn account
"Returns the account for the given `address` (or the address associated with `ctx`)."
(^AccountStatus [^Context ctx]
(.getAccountStatus ctx))
(^AccountStatus [^Context ctx address]
(.getAccountStatus ctx
(-wrap-address address))))
(defn address
"Returns the executing address of the given `ctx`."
^Address
[^Context ctx]
(.getAddress ctx))
(defn env
"Returns the environment of the executing account attached to `ctx`."
(^AHashMap [^Context ctx]
(.getEnvironment ctx))
(^AHashMap [ctx address]
(.getEnvironment (account ctx
address))))
(defn exception
"The CVM enters in exceptional state in case of error or particular patterns such as
halting or doing a rollback.
Returns the current exception or nil if `ctx` is not in such a state meaning that [[result]]
can be safely used.
An exception code can be provided as a filter, meaning that even if an exception occured, this
functions will return nil unless that exception has the given `code`.
Also see [[code-std*]] for easily retrieving an official error code. Note that in practice, unlike the CVM
itself or any of the core function, a user Convex function can return anything as a code."
([^Context ctx]
(when (.isExceptional ctx)
(.getExceptional ctx)))
([^ACell code ^Context ctx]
(when (.isExceptional ctx)
(let [e (.getExceptional ctx)]
(when (= (.getCode e)
code)
e)))))
(defn exception?
"Returns true if the given `ctx` is in an exceptional state.
See [[exception]]."
([^Context ctx]
(.isExceptional ctx))
([^ACell code ^Context ctx]
(if (.isExceptional ctx)
(= code
(.getCode (.getExceptional ctx)))
false)))
(defn juice
"Returns the remaining amount of juice available for the executing account.
Also see [[juice-set]]."
[^Context ctx]
(.getJuice ctx))
(defn key
"Returns the key of the given `address` (or the address associated with `ctx`)."
(^AccountKey [ctx]
(.getAccountKey (account ctx)))
(^AccountKey [ctx address]
(.getAccountKey (account ctx
address))))
(defn log
"Returns the log of `ctx` (a CVM vector of size 2 vectors containing a logging address
and a logged value)."
^ABlobMap
[^Context ctx]
(.getLog ctx))
(defn result
"Extracts the result (eg. after expansion, compilation, execution, ...) wrapped in a `ctx`.
Throws if the `ctx` is in an exceptional state. See [[exception]]."
[^Context ctx]
(.getResult ctx))
(defn state
"Returns the whole CVM state associated with `ctx`.
Also see [[state-set]]."
^State
[^Context ctx]
(.getState ctx))
(defn time
"Returns the current timestamp (Unix epoch in milliseconds as CVM long) assigned to the state in the given `ctx`.
Also see [[timestamp-set]]."
^CVMLong
[^Context ctx]
(-> ctx
state
.getTimeStamp))
;;;;;;;;;; Modifying context properties
(defn account-create
"Creates an new account, with a `key` (user) or without (actor).
See [[convex.cell/key]].
Address is attached as a result in the returned context."
(^Context [^Context ctx]
(.createAccount ctx
nil))
(^Context [^Context ctx key]
(.createAccount ctx
key)))
(defn def
"Like calling `(def sym value)` in Convex Lisp, either in the current address of the given one.
Argument is a map of `CVM symbol` -> `CVM value`."
(^Context [ctx sym->value]
(convex.cvm/def ctx
(address ctx)
sym->value))
(^Context [^Context ctx addr sym->value]
(let [s (state ctx)
a (.getAccount s
addr)]
(if a
(state-set ctx
(.putAccount s
addr
(.withEnvironment a
(reduce (fn [^AHashMap env [^ACell sym ^ACell value]]
(.assoc env
sym
value))
(.getEnvironment a)
sym->value))))
ctx))))
(defn deploy
"Deploys the given `code` as an actor.
Returns a context that is either [[exception]]al or has the address of the successfully created actor
attached as a [[result]]."
^Context
[^Context ctx code]
(.deployActor ctx
code))
(defn exception-clear
"Removes the currently attached exception from the given `ctx`."
^Context
[^Context ctx]
(.withException ctx
nil))
(defn juice-preserve
"Executes `(f ctx)`, `f` being a function `ctx` -> `ctx`.
The returned `ctx` will have the same amount of juice as the original."
^Context
[ctx f]
(let [juice- (juice ctx)]
(.withJuice ^Context (f ctx)
juice-)))
(defn juice-refill
"Refills juice to maximum.
Also see [[juice-set]]."
^Context
[^Context ctx]
(juice-set ctx
Long/MAX_VALUE))
(defn juice-set
"Sets the juice of the given `ctx` to the requested `amount`.
Also see [[juice]], [[juice-refill]]."
^Context
[^Context ctx amount]
(.withJuice ctx
amount))
(defn key-set
"Sets `key` on the address curently associated with `ctx`."
^Context
[^Context ctx ^AccountKey key]
(.setAccountKey ctx
key))
(defn result-set
"Attaches the given `result` to `ctx`, as if it was the result of a transaction."
^Context
[^Context ctx ^ACell result]
(.withResult ctx
result))
(defn state-set
"Replaces the CVM state in the `ctx` with the given one.
See [[state]]."
^Context
[^Context ctx ^State state]
(.withState ctx
state))
(defn time-advance
"Advances the timestamp in the state of `ctx` by `millis` milliseconds.
Does not do anything if `millis` is < 0.
See [[time]]."
^Context
[^Context ctx millis]
(state-set ctx
(-> ctx
state
(.applyBlock (Block/create (long (+ (.longValue (time ctx))
millis))
($.cell/key ($.cell/blob (byte-array 32)))
($.cell/vector [])))
.getState)))
(defn undef
"Like calling `(undef sym)` in Convex Lisp, either in the current account or the given one, repeatedly
on any CVM symbol in `sym+`."
(^Context [ctx sym+]
(undef ctx
(address ctx)
sym+))
(^Context [^Context ctx addr sym+]
(let [s (state ctx)
a (.getAccount s
addr)]
(if a
(state-set ctx
(.putAccount s
addr
(.withEnvironment a
(reduce (fn [^AHashMap env ^ACell sym]
(.dissoc env
sym))
(.getEnvironment a)
sym+))))
ctx))))
;;;;;;;;;; Phase 1 & 2 - Expanding Convex objects and compiling into operations
(defn expand
"Expands `cell` into a `canonical cell` by applying macros.
Fetched using [[result]] if not given.
Returns a new `ctx` with a [[result]] ready for [[compile]] or an [[exception]] in case
of failure."
(^Context [ctx]
(expand ctx
(result ctx)))
(^Context [^Context ctx object]
(.expand ctx
object)))
(defn compile
"Compiles the `canonical-cell` into executable code.
Fetched using [[result]] if not given.
Returns a new `ctx` with a [[result]] ready for [[exec]] or an [[exception]] in case of
failure."
(^Context [ctx]
(compile ctx
(result ctx)))
(^Context [^Context ctx canonical-cell]
(.compile ctx
canonical-cell)))
(defn expand-compile
"Chains [[expand]] and [[compile]] in a slightly more efficient fashion than calling both separately."
(^Context [ctx]
(expand-compile ctx
(result ctx)))
(^Context [^Context ctx object]
(.expandCompile ctx
object)))
;;;;;;;;;; Pahse 3 - Executing compiled code
(defn exec
"Executes compiled code.
Usually run after [[compile]].
Returns a new `ctx` with a [[result]] or an [[exception]] in case of failure."
(^Context [ctx]
(exec ctx
(result ctx)))
(^Context [^Context ctx ^AOp op]
(.run ctx
op)))
;;;
(defn eval
"Evaluates the given `cell`, going efficiently through [[expand]], [[compile]], and [[exec]].
Works with any kind of `cell` and is sufficient when there is no need for fine-grained control.
An important difference with the aforementioned cycle is that the cell passes through `*lang*`, a function
possibly set by the user for intercepting a cell (eg. modifying the cell and evaluating explicitley).
Returns a new `ctx` with a [[result]] or an [[exception]] in case of failure."
(^Context [ctx]
(eval ctx
(result ctx)))
(^Context [^Context ctx ^ACell cell]
(.run ctx
cell)))
;;;;;;;;;; Functions
(defmacro arg+*
"See [[invoke]]."
[& arg+]
(let [sym-arr (gensym)]
`(let [~sym-arr ^"[Lconvex.core.data.ACell;" (make-array ACell
~(count arg+))]
~@(map (fn [i arg]
`(aset ~sym-arr
~i
~arg))
(range)
arg+)
~sym-arr)))
(defn invoke
"Invokes the given CVM `f`unction using the given `ctx`.
`arg+` is a Java array of CVM objects. See [[arg+*]] for easily and efficiently creating one.
Returns a new `ctx` with a [[result]] or an [[exception]] in case of failure."
^Context
[^Context ctx ^AFn f arg+]
(let [ctx-2 (.invoke ctx
f
arg+)
ex (exception ctx-2)]
(if ex
(if (instance? ErrorValue
ex)
ctx-2
(exception-clear ctx-2))
ctx-2)))
| 74829 | (ns convex.cvm
"Code execution in the CVM, altering state, and gaining insights.
Central entities of this namespaces are contextes and they can be created using [[ctx]].
All other functions revolve around them. While the design of a context is mostly immutable, whenever an altering function
is applied (eg. [[juice-set]]) or code is handled in any way (eg. [[eval]]), old context must be discarded and only returned
one should be used.
Cheap copies can be created using [[fork]].
Actions involving code (eg. [[compile]], [[exec]], ...) return a new context which holds either a [[result]] or an [[exception]].
Those actions always consume [[juice]].
Given that a \"cell\" is the term reserved for CVM data and objects, execution consists of following steps:
| Step | Function | Does |
|---|---|---|
| 1 | [[expand]] | `cell` -> `canonical cell`, applies macros |
| 2 | [[compile]] | `canonical cell` -> `op`, preparing executable code |
| 3 | [[exec]] | Executes compiled code |
Any cell can be applied safely to those functions, worse that can happen is nothing (eg. providing an already compiled cell to
[[compile]]).
If fine-grained control is not needed and if source is not compiled anyways, a simpler alternative is to use [[eval]] which does
all the job."
{:author "<NAME>"}
(:import (convex.core Block
State)
(convex.core.data ABlobMap
AccountKey
AccountStatus
ACell
Address
AHashMap)
(convex.core.data.prim CVMLong)
(convex.core.init Init)
(convex.core.lang AFn
AOp
Context)
(convex.core.lang.impl ErrorValue))
(:refer-clojure :exclude [compile
def
eval
key
time])
(:require [convex.cell :as $.cell]))
(set! *warn-on-reflection*
true)
(declare juice-set
state-set)
;;;;;;;;;; Creating a new context
(defn ctx
"Creates a \"fake\" context. Ideal for testing and repl'ing around.
An optional map of options may be provided:
| Key | Value | Default |
|---|---|---|
| `:convex.cvm/address` | Address of the executing account | Reserved address (an actor) |
| `:convex.cvm/state` | Genesis state | Initial state with Convex actors and libraries |
| `:convex.peer/key | Account key for the initial peer (see [[convex.cell/account-key]]) | Fake key, all 0's |"
(^Context []
(ctx nil))
(^Context [option+]
(Context/createFake (or (:convex.cvm/state option+)
(Init/createState [(or (:convex.peer/key option+)
($.cell/key ($.cell/blob (byte-array 32))))]))
(or (:convex.cvm/address option+)
Init/RESERVED_ADDRESS))))
(defn fork
"Duplicates the given [[ctx]] (very cheap).
Any operation on the returned copy has no impact on the original context.
Attention, forking a `ctx` looses any attached [[result]] or [[exception]]."
^Context
[^Context ctx]
(.fork ctx))
(defn fork-to
"Like [[fork]] but switches the executing account.
Note: CVM log is lost."
^Context
[^Context ctx address]
(.forkWithAddress ctx
address))
;;;;;;;;;; Querying context properties
(defn- -wrap-address
;; Wraps `x` in an Address object if it is not already.
^Address
[x]
(cond->
x
(number? x)
$.cell/address))
(defn account
"Returns the account for the given `address` (or the address associated with `ctx`)."
(^AccountStatus [^Context ctx]
(.getAccountStatus ctx))
(^AccountStatus [^Context ctx address]
(.getAccountStatus ctx
(-wrap-address address))))
(defn address
"Returns the executing address of the given `ctx`."
^Address
[^Context ctx]
(.getAddress ctx))
(defn env
"Returns the environment of the executing account attached to `ctx`."
(^AHashMap [^Context ctx]
(.getEnvironment ctx))
(^AHashMap [ctx address]
(.getEnvironment (account ctx
address))))
(defn exception
"The CVM enters in exceptional state in case of error or particular patterns such as
halting or doing a rollback.
Returns the current exception or nil if `ctx` is not in such a state meaning that [[result]]
can be safely used.
An exception code can be provided as a filter, meaning that even if an exception occured, this
functions will return nil unless that exception has the given `code`.
Also see [[code-std*]] for easily retrieving an official error code. Note that in practice, unlike the CVM
itself or any of the core function, a user Convex function can return anything as a code."
([^Context ctx]
(when (.isExceptional ctx)
(.getExceptional ctx)))
([^ACell code ^Context ctx]
(when (.isExceptional ctx)
(let [e (.getExceptional ctx)]
(when (= (.getCode e)
code)
e)))))
(defn exception?
"Returns true if the given `ctx` is in an exceptional state.
See [[exception]]."
([^Context ctx]
(.isExceptional ctx))
([^ACell code ^Context ctx]
(if (.isExceptional ctx)
(= code
(.getCode (.getExceptional ctx)))
false)))
(defn juice
"Returns the remaining amount of juice available for the executing account.
Also see [[juice-set]]."
[^Context ctx]
(.getJuice ctx))
(defn key
"Returns the key of the given `address` (or the address associated with `ctx`)."
(^AccountKey [ctx]
(.getAccountKey (account ctx)))
(^AccountKey [ctx address]
(.getAccountKey (account ctx
address))))
(defn log
"Returns the log of `ctx` (a CVM vector of size 2 vectors containing a logging address
and a logged value)."
^ABlobMap
[^Context ctx]
(.getLog ctx))
(defn result
"Extracts the result (eg. after expansion, compilation, execution, ...) wrapped in a `ctx`.
Throws if the `ctx` is in an exceptional state. See [[exception]]."
[^Context ctx]
(.getResult ctx))
(defn state
"Returns the whole CVM state associated with `ctx`.
Also see [[state-set]]."
^State
[^Context ctx]
(.getState ctx))
(defn time
"Returns the current timestamp (Unix epoch in milliseconds as CVM long) assigned to the state in the given `ctx`.
Also see [[timestamp-set]]."
^CVMLong
[^Context ctx]
(-> ctx
state
.getTimeStamp))
;;;;;;;;;; Modifying context properties
(defn account-create
"Creates an new account, with a `key` (user) or without (actor).
See [[convex.cell/key]].
Address is attached as a result in the returned context."
(^Context [^Context ctx]
(.createAccount ctx
nil))
(^Context [^Context ctx key]
(.createAccount ctx
key)))
(defn def
"Like calling `(def sym value)` in Convex Lisp, either in the current address of the given one.
Argument is a map of `CVM symbol` -> `CVM value`."
(^Context [ctx sym->value]
(convex.cvm/def ctx
(address ctx)
sym->value))
(^Context [^Context ctx addr sym->value]
(let [s (state ctx)
a (.getAccount s
addr)]
(if a
(state-set ctx
(.putAccount s
addr
(.withEnvironment a
(reduce (fn [^AHashMap env [^ACell sym ^ACell value]]
(.assoc env
sym
value))
(.getEnvironment a)
sym->value))))
ctx))))
(defn deploy
"Deploys the given `code` as an actor.
Returns a context that is either [[exception]]al or has the address of the successfully created actor
attached as a [[result]]."
^Context
[^Context ctx code]
(.deployActor ctx
code))
(defn exception-clear
"Removes the currently attached exception from the given `ctx`."
^Context
[^Context ctx]
(.withException ctx
nil))
(defn juice-preserve
"Executes `(f ctx)`, `f` being a function `ctx` -> `ctx`.
The returned `ctx` will have the same amount of juice as the original."
^Context
[ctx f]
(let [juice- (juice ctx)]
(.withJuice ^Context (f ctx)
juice-)))
(defn juice-refill
"Refills juice to maximum.
Also see [[juice-set]]."
^Context
[^Context ctx]
(juice-set ctx
Long/MAX_VALUE))
(defn juice-set
"Sets the juice of the given `ctx` to the requested `amount`.
Also see [[juice]], [[juice-refill]]."
^Context
[^Context ctx amount]
(.withJuice ctx
amount))
(defn key-set
"Sets `key` on the address curently associated with `ctx`."
^Context
[^Context ctx ^AccountKey key]
(.setAccountKey ctx
key))
(defn result-set
"Attaches the given `result` to `ctx`, as if it was the result of a transaction."
^Context
[^Context ctx ^ACell result]
(.withResult ctx
result))
(defn state-set
"Replaces the CVM state in the `ctx` with the given one.
See [[state]]."
^Context
[^Context ctx ^State state]
(.withState ctx
state))
(defn time-advance
"Advances the timestamp in the state of `ctx` by `millis` milliseconds.
Does not do anything if `millis` is < 0.
See [[time]]."
^Context
[^Context ctx millis]
(state-set ctx
(-> ctx
state
(.applyBlock (Block/create (long (+ (.longValue (time ctx))
millis))
($.cell/key ($.cell/blob (byte-array 32)))
($.cell/vector [])))
.getState)))
(defn undef
"Like calling `(undef sym)` in Convex Lisp, either in the current account or the given one, repeatedly
on any CVM symbol in `sym+`."
(^Context [ctx sym+]
(undef ctx
(address ctx)
sym+))
(^Context [^Context ctx addr sym+]
(let [s (state ctx)
a (.getAccount s
addr)]
(if a
(state-set ctx
(.putAccount s
addr
(.withEnvironment a
(reduce (fn [^AHashMap env ^ACell sym]
(.dissoc env
sym))
(.getEnvironment a)
sym+))))
ctx))))
;;;;;;;;;; Phase 1 & 2 - Expanding Convex objects and compiling into operations
(defn expand
"Expands `cell` into a `canonical cell` by applying macros.
Fetched using [[result]] if not given.
Returns a new `ctx` with a [[result]] ready for [[compile]] or an [[exception]] in case
of failure."
(^Context [ctx]
(expand ctx
(result ctx)))
(^Context [^Context ctx object]
(.expand ctx
object)))
(defn compile
"Compiles the `canonical-cell` into executable code.
Fetched using [[result]] if not given.
Returns a new `ctx` with a [[result]] ready for [[exec]] or an [[exception]] in case of
failure."
(^Context [ctx]
(compile ctx
(result ctx)))
(^Context [^Context ctx canonical-cell]
(.compile ctx
canonical-cell)))
(defn expand-compile
"Chains [[expand]] and [[compile]] in a slightly more efficient fashion than calling both separately."
(^Context [ctx]
(expand-compile ctx
(result ctx)))
(^Context [^Context ctx object]
(.expandCompile ctx
object)))
;;;;;;;;;; Pahse 3 - Executing compiled code
(defn exec
"Executes compiled code.
Usually run after [[compile]].
Returns a new `ctx` with a [[result]] or an [[exception]] in case of failure."
(^Context [ctx]
(exec ctx
(result ctx)))
(^Context [^Context ctx ^AOp op]
(.run ctx
op)))
;;;
(defn eval
"Evaluates the given `cell`, going efficiently through [[expand]], [[compile]], and [[exec]].
Works with any kind of `cell` and is sufficient when there is no need for fine-grained control.
An important difference with the aforementioned cycle is that the cell passes through `*lang*`, a function
possibly set by the user for intercepting a cell (eg. modifying the cell and evaluating explicitley).
Returns a new `ctx` with a [[result]] or an [[exception]] in case of failure."
(^Context [ctx]
(eval ctx
(result ctx)))
(^Context [^Context ctx ^ACell cell]
(.run ctx
cell)))
;;;;;;;;;; Functions
(defmacro arg+*
"See [[invoke]]."
[& arg+]
(let [sym-arr (gensym)]
`(let [~sym-arr ^"[Lconvex.core.data.ACell;" (make-array ACell
~(count arg+))]
~@(map (fn [i arg]
`(aset ~sym-arr
~i
~arg))
(range)
arg+)
~sym-arr)))
(defn invoke
"Invokes the given CVM `f`unction using the given `ctx`.
`arg+` is a Java array of CVM objects. See [[arg+*]] for easily and efficiently creating one.
Returns a new `ctx` with a [[result]] or an [[exception]] in case of failure."
^Context
[^Context ctx ^AFn f arg+]
(let [ctx-2 (.invoke ctx
f
arg+)
ex (exception ctx-2)]
(if ex
(if (instance? ErrorValue
ex)
ctx-2
(exception-clear ctx-2))
ctx-2)))
| true | (ns convex.cvm
"Code execution in the CVM, altering state, and gaining insights.
Central entities of this namespaces are contextes and they can be created using [[ctx]].
All other functions revolve around them. While the design of a context is mostly immutable, whenever an altering function
is applied (eg. [[juice-set]]) or code is handled in any way (eg. [[eval]]), old context must be discarded and only returned
one should be used.
Cheap copies can be created using [[fork]].
Actions involving code (eg. [[compile]], [[exec]], ...) return a new context which holds either a [[result]] or an [[exception]].
Those actions always consume [[juice]].
Given that a \"cell\" is the term reserved for CVM data and objects, execution consists of following steps:
| Step | Function | Does |
|---|---|---|
| 1 | [[expand]] | `cell` -> `canonical cell`, applies macros |
| 2 | [[compile]] | `canonical cell` -> `op`, preparing executable code |
| 3 | [[exec]] | Executes compiled code |
Any cell can be applied safely to those functions, worse that can happen is nothing (eg. providing an already compiled cell to
[[compile]]).
If fine-grained control is not needed and if source is not compiled anyways, a simpler alternative is to use [[eval]] which does
all the job."
{:author "PI:NAME:<NAME>END_PI"}
(:import (convex.core Block
State)
(convex.core.data ABlobMap
AccountKey
AccountStatus
ACell
Address
AHashMap)
(convex.core.data.prim CVMLong)
(convex.core.init Init)
(convex.core.lang AFn
AOp
Context)
(convex.core.lang.impl ErrorValue))
(:refer-clojure :exclude [compile
def
eval
key
time])
(:require [convex.cell :as $.cell]))
(set! *warn-on-reflection*
true)
(declare juice-set
state-set)
;;;;;;;;;; Creating a new context
(defn ctx
"Creates a \"fake\" context. Ideal for testing and repl'ing around.
An optional map of options may be provided:
| Key | Value | Default |
|---|---|---|
| `:convex.cvm/address` | Address of the executing account | Reserved address (an actor) |
| `:convex.cvm/state` | Genesis state | Initial state with Convex actors and libraries |
| `:convex.peer/key | Account key for the initial peer (see [[convex.cell/account-key]]) | Fake key, all 0's |"
(^Context []
(ctx nil))
(^Context [option+]
(Context/createFake (or (:convex.cvm/state option+)
(Init/createState [(or (:convex.peer/key option+)
($.cell/key ($.cell/blob (byte-array 32))))]))
(or (:convex.cvm/address option+)
Init/RESERVED_ADDRESS))))
(defn fork
"Duplicates the given [[ctx]] (very cheap).
Any operation on the returned copy has no impact on the original context.
Attention, forking a `ctx` looses any attached [[result]] or [[exception]]."
^Context
[^Context ctx]
(.fork ctx))
(defn fork-to
"Like [[fork]] but switches the executing account.
Note: CVM log is lost."
^Context
[^Context ctx address]
(.forkWithAddress ctx
address))
;;;;;;;;;; Querying context properties
(defn- -wrap-address
;; Wraps `x` in an Address object if it is not already.
^Address
[x]
(cond->
x
(number? x)
$.cell/address))
(defn account
"Returns the account for the given `address` (or the address associated with `ctx`)."
(^AccountStatus [^Context ctx]
(.getAccountStatus ctx))
(^AccountStatus [^Context ctx address]
(.getAccountStatus ctx
(-wrap-address address))))
(defn address
"Returns the executing address of the given `ctx`."
^Address
[^Context ctx]
(.getAddress ctx))
(defn env
"Returns the environment of the executing account attached to `ctx`."
(^AHashMap [^Context ctx]
(.getEnvironment ctx))
(^AHashMap [ctx address]
(.getEnvironment (account ctx
address))))
(defn exception
"The CVM enters in exceptional state in case of error or particular patterns such as
halting or doing a rollback.
Returns the current exception or nil if `ctx` is not in such a state meaning that [[result]]
can be safely used.
An exception code can be provided as a filter, meaning that even if an exception occured, this
functions will return nil unless that exception has the given `code`.
Also see [[code-std*]] for easily retrieving an official error code. Note that in practice, unlike the CVM
itself or any of the core function, a user Convex function can return anything as a code."
([^Context ctx]
(when (.isExceptional ctx)
(.getExceptional ctx)))
([^ACell code ^Context ctx]
(when (.isExceptional ctx)
(let [e (.getExceptional ctx)]
(when (= (.getCode e)
code)
e)))))
(defn exception?
"Returns true if the given `ctx` is in an exceptional state.
See [[exception]]."
([^Context ctx]
(.isExceptional ctx))
([^ACell code ^Context ctx]
(if (.isExceptional ctx)
(= code
(.getCode (.getExceptional ctx)))
false)))
(defn juice
"Returns the remaining amount of juice available for the executing account.
Also see [[juice-set]]."
[^Context ctx]
(.getJuice ctx))
(defn key
"Returns the key of the given `address` (or the address associated with `ctx`)."
(^AccountKey [ctx]
(.getAccountKey (account ctx)))
(^AccountKey [ctx address]
(.getAccountKey (account ctx
address))))
(defn log
"Returns the log of `ctx` (a CVM vector of size 2 vectors containing a logging address
and a logged value)."
^ABlobMap
[^Context ctx]
(.getLog ctx))
(defn result
"Extracts the result (eg. after expansion, compilation, execution, ...) wrapped in a `ctx`.
Throws if the `ctx` is in an exceptional state. See [[exception]]."
[^Context ctx]
(.getResult ctx))
(defn state
"Returns the whole CVM state associated with `ctx`.
Also see [[state-set]]."
^State
[^Context ctx]
(.getState ctx))
(defn time
"Returns the current timestamp (Unix epoch in milliseconds as CVM long) assigned to the state in the given `ctx`.
Also see [[timestamp-set]]."
^CVMLong
[^Context ctx]
(-> ctx
state
.getTimeStamp))
;;;;;;;;;; Modifying context properties
(defn account-create
"Creates an new account, with a `key` (user) or without (actor).
See [[convex.cell/key]].
Address is attached as a result in the returned context."
(^Context [^Context ctx]
(.createAccount ctx
nil))
(^Context [^Context ctx key]
(.createAccount ctx
key)))
(defn def
"Like calling `(def sym value)` in Convex Lisp, either in the current address of the given one.
Argument is a map of `CVM symbol` -> `CVM value`."
(^Context [ctx sym->value]
(convex.cvm/def ctx
(address ctx)
sym->value))
(^Context [^Context ctx addr sym->value]
(let [s (state ctx)
a (.getAccount s
addr)]
(if a
(state-set ctx
(.putAccount s
addr
(.withEnvironment a
(reduce (fn [^AHashMap env [^ACell sym ^ACell value]]
(.assoc env
sym
value))
(.getEnvironment a)
sym->value))))
ctx))))
(defn deploy
"Deploys the given `code` as an actor.
Returns a context that is either [[exception]]al or has the address of the successfully created actor
attached as a [[result]]."
^Context
[^Context ctx code]
(.deployActor ctx
code))
(defn exception-clear
"Removes the currently attached exception from the given `ctx`."
^Context
[^Context ctx]
(.withException ctx
nil))
(defn juice-preserve
"Executes `(f ctx)`, `f` being a function `ctx` -> `ctx`.
The returned `ctx` will have the same amount of juice as the original."
^Context
[ctx f]
(let [juice- (juice ctx)]
(.withJuice ^Context (f ctx)
juice-)))
(defn juice-refill
"Refills juice to maximum.
Also see [[juice-set]]."
^Context
[^Context ctx]
(juice-set ctx
Long/MAX_VALUE))
(defn juice-set
"Sets the juice of the given `ctx` to the requested `amount`.
Also see [[juice]], [[juice-refill]]."
^Context
[^Context ctx amount]
(.withJuice ctx
amount))
(defn key-set
"Sets `key` on the address curently associated with `ctx`."
^Context
[^Context ctx ^AccountKey key]
(.setAccountKey ctx
key))
(defn result-set
"Attaches the given `result` to `ctx`, as if it was the result of a transaction."
^Context
[^Context ctx ^ACell result]
(.withResult ctx
result))
(defn state-set
"Replaces the CVM state in the `ctx` with the given one.
See [[state]]."
^Context
[^Context ctx ^State state]
(.withState ctx
state))
(defn time-advance
"Advances the timestamp in the state of `ctx` by `millis` milliseconds.
Does not do anything if `millis` is < 0.
See [[time]]."
^Context
[^Context ctx millis]
(state-set ctx
(-> ctx
state
(.applyBlock (Block/create (long (+ (.longValue (time ctx))
millis))
($.cell/key ($.cell/blob (byte-array 32)))
($.cell/vector [])))
.getState)))
(defn undef
"Like calling `(undef sym)` in Convex Lisp, either in the current account or the given one, repeatedly
on any CVM symbol in `sym+`."
(^Context [ctx sym+]
(undef ctx
(address ctx)
sym+))
(^Context [^Context ctx addr sym+]
(let [s (state ctx)
a (.getAccount s
addr)]
(if a
(state-set ctx
(.putAccount s
addr
(.withEnvironment a
(reduce (fn [^AHashMap env ^ACell sym]
(.dissoc env
sym))
(.getEnvironment a)
sym+))))
ctx))))
;;;;;;;;;; Phase 1 & 2 - Expanding Convex objects and compiling into operations
(defn expand
"Expands `cell` into a `canonical cell` by applying macros.
Fetched using [[result]] if not given.
Returns a new `ctx` with a [[result]] ready for [[compile]] or an [[exception]] in case
of failure."
(^Context [ctx]
(expand ctx
(result ctx)))
(^Context [^Context ctx object]
(.expand ctx
object)))
(defn compile
"Compiles the `canonical-cell` into executable code.
Fetched using [[result]] if not given.
Returns a new `ctx` with a [[result]] ready for [[exec]] or an [[exception]] in case of
failure."
(^Context [ctx]
(compile ctx
(result ctx)))
(^Context [^Context ctx canonical-cell]
(.compile ctx
canonical-cell)))
(defn expand-compile
"Chains [[expand]] and [[compile]] in a slightly more efficient fashion than calling both separately."
(^Context [ctx]
(expand-compile ctx
(result ctx)))
(^Context [^Context ctx object]
(.expandCompile ctx
object)))
;;;;;;;;;; Pahse 3 - Executing compiled code
(defn exec
"Executes compiled code.
Usually run after [[compile]].
Returns a new `ctx` with a [[result]] or an [[exception]] in case of failure."
(^Context [ctx]
(exec ctx
(result ctx)))
(^Context [^Context ctx ^AOp op]
(.run ctx
op)))
;;;
(defn eval
"Evaluates the given `cell`, going efficiently through [[expand]], [[compile]], and [[exec]].
Works with any kind of `cell` and is sufficient when there is no need for fine-grained control.
An important difference with the aforementioned cycle is that the cell passes through `*lang*`, a function
possibly set by the user for intercepting a cell (eg. modifying the cell and evaluating explicitley).
Returns a new `ctx` with a [[result]] or an [[exception]] in case of failure."
(^Context [ctx]
(eval ctx
(result ctx)))
(^Context [^Context ctx ^ACell cell]
(.run ctx
cell)))
;;;;;;;;;; Functions
(defmacro arg+*
"See [[invoke]]."
[& arg+]
(let [sym-arr (gensym)]
`(let [~sym-arr ^"[Lconvex.core.data.ACell;" (make-array ACell
~(count arg+))]
~@(map (fn [i arg]
`(aset ~sym-arr
~i
~arg))
(range)
arg+)
~sym-arr)))
(defn invoke
"Invokes the given CVM `f`unction using the given `ctx`.
`arg+` is a Java array of CVM objects. See [[arg+*]] for easily and efficiently creating one.
Returns a new `ctx` with a [[result]] or an [[exception]] in case of failure."
^Context
[^Context ctx ^AFn f arg+]
(let [ctx-2 (.invoke ctx
f
arg+)
ex (exception ctx-2)]
(if ex
(if (instance? ErrorValue
ex)
ctx-2
(exception-clear ctx-2))
ctx-2)))
|
End of preview. Expand
in Dataset Viewer.
- Downloads last month
- 0