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": ";; Copyright (c) 2015-2016 Andrey Antukh <niwi@niwi.nz>\n;; All rights reserved.\n;;\n;; Redi",
"end": 40,
"score": 0.9998809695243835,
"start": 27,
"tag": "NAME",
"value": "Andrey Antukh"
},
{
"context": ";; Copyright (c) 2015-2016 Andrey Antukh <niwi@niwi.nz>\n;; All rights reserved.\n;;\n;; Redistribution and",
"end": 54,
"score": 0.999933123588562,
"start": 42,
"tag": "EMAIL",
"value": "niwi@niwi.nz"
}
] | src/clojure/catacumba/impl/context.clj | source-c/catacumba | 212 | ;; Copyright (c) 2015-2016 Andrey Antukh <niwi@niwi.nz>
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;;
;; * Redistributions of source code must retain the above copyright notice, this
;; list of conditions and the following disclaimer.
;;
;; * Redistributions in binary form must reproduce the above copyright notice,
;; this list of conditions and the following disclaimer in the documentation
;; and/or other materials provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(ns catacumba.impl.context
"Functions and helpers for work in a clojure
way with ratpack types."
(:require [catacumba.impl.helpers :as hp]
[catacumba.impl.registry :as reg]
[promesa.core :as p])
(:import catacumba.impl.DelegatedContext
catacumba.impl.ContextHolder
ratpack.handling.Handler
ratpack.handling.Context
ratpack.handling.RequestOutcome
ratpack.form.Form
ratpack.parse.Parse
ratpack.http.Request
ratpack.http.Response
ratpack.http.Headers
ratpack.http.TypedData
ratpack.http.MutableHeaders
ratpack.util.MultiValueMap
ratpack.server.PublicAddress
ratpack.registry.Registry
io.netty.handler.codec.http.cookie.Cookie
java.util.Optional))
;; --- Helpers
(defn- assoc-conj!
{:internal true :no-doc true}
[the-map key val]
(assoc! the-map key
(if-let [cur (get the-map key)]
(if (vector? cur)
(conj cur val)
[cur val])
val)))
(defn get-response*
{:internal true}
[context]
(cond
(instance? Response context) context
(instance? Context context) (.getResponse context)
(map? context) (:catacumba/response context)
:else (throw (ex-info "Invalid arguments2" {}))))
(defn get-context*
{:internal true}
[context]
(cond
(instance? Context context) context
(map? context) (:catacumba/context context)
:else (throw (ex-info "Invalid arguments1" {}))))
(defn get-request*
{:internal true}
[context]
(cond
(instance? Request context) context
(instance? Context context) (.getRequest context)
(map? context) (:catacumba/request context)
:else (throw (ex-info "Invalid arguments3" {}))))
;; --- Public Api
(defn get-context-params
"Get the current context params.
The current params can be passed to the next
handler using the `delegate` function. Is a simple
way to communicate the handlers chain."
{:internal true :no-doc true}
[context]
(let [^Context ctx (get-context* context)
^DelegatedContext dctx (reg/maybe-get ctx DelegatedContext)]
(when dctx
(.-data dctx))))
(defn delegate
"Delegate handling to the next handler in line.
This function accept an additiona parameter for
pass context parameters to the next handlers, and
that can be obtained with `context-params`
function.
Returns an instance of DelegatedContext."
([] (DelegatedContext. nil))
([data] (DelegatedContext. data)))
(defn delegated-context?
"Check if the provided value is a DelegatedContext instance."
[v]
(instance? DelegatedContext v))
(defn public-address
"Get the current public address as URI instance.
The default implementation uses a variety of strategies to
attempt to provide the desired result most of the time.
Information used includes:
- Configured public address URI (optional)
- X-Forwarded-Host header (if included in request)
- X-Forwarded-Proto or X-Forwarded-Ssl headers (if included in request)
- Absolute request URI (if included in request)
- Host header (if included in request)
- Service's bind address and scheme (http vs. https)"
[context]
(let [^Context ctx (get-context* context)
^PublicAddress addr (.get ctx PublicAddress)]
(.get addr ctx)))
(defn on-close
"Register a callback in the context that will be called
when the connection with the client is closed."
[context callback]
(let [^Context ctx (:catacumba/context context)]
(.onClose ctx (hp/fn->action callback))))
(defn before-send
"Register a callback in the context that will be called
just before send the response to the client. Is a useful
hook for set some additional cookies, headers or similar
response transformations."
[context callback]
(let [^Response response (:catacumba/response context)]
(.beforeSend response (hp/fn->action callback))))
;; Implementation notes:
;; Reflection is used for access to private field of Form instance
;; because ratpack does not allows an other way for iter over
;; all parameters (including files) in an uniform way.
(defn- extract-files
[^Form form]
(let [field (.. form getClass (getDeclaredField "files"))]
(.setAccessible field true)
(.get field form)))
(defn get-query-params
"Parse query params from request and return a
maybe multivalue map."
[context]
(let [^Request request (get-request* context)
^MultiValueMap params (.getQueryParams request)]
(persistent!
(reduce (fn [acc key]
(let [values (.getAll params key)]
(reduce #(assoc-conj! %1 (keyword key) %2) acc values)))
(transient {})
(.keySet params)))))
(defn get-route-params
"Return a hash-map with parameters extracted from
routing patterns."
[context]
(let [^Context ctx (get-context* context)]
(into {} hp/keywordice-keys-t (.getAllPathTokens ctx))))
(defn headers->map
{:internal true :no-doc true}
[^MultiValueMap headers keywordize]
(persistent!
(reduce (fn [acc ^String key]
(let [values (.getAll headers key)
key (if keywordize
(keyword (.toLowerCase key))
(.toLowerCase key))]
(reduce #(assoc-conj! %1 key %2) acc values)))
(transient {})
(.keySet headers))))
(defn get-headers
([context] (get-headers context true))
([context keywordize?]
(let [^Request request (get-request* context)
^Headers headers (.getHeaders request)]
(headers->map (.asMultiValueMap headers) keywordize?))))
(defn set-headers!
[context headers]
(let [^Response response (get-response* context)
^MutableHeaders headersmap (.getHeaders response)]
(loop [headers headers]
(when-let [[key vals] (first headers)]
(.set headersmap (name key) vals)
(recur (rest headers))))))
(defn- cookie->map
[^Cookie cookie]
{:path (.path cookie)
:value (.value cookie)
:domain (.domain cookie)
:http-only (.isHttpOnly cookie)
:secure (.isSecure cookie)
:max-age (.maxAge cookie)})
(defn get-cookies
"Get the incoming cookies."
[context]
(let [^Request request (get-request* context)]
(persistent!
(reduce (fn [acc ^Cookie cookie]
(let [name (keyword (.name cookie))]
(assoc! acc name (cookie->map cookie))))
(transient {})
(into [] (.getCookies request))))))
(defn set-status!
"Set the response http status."
[context status]
(let [^Response response (get-response* context)]
(.status response (int status))))
(defn set-cookies!
"Set the outgoing cookies.
(set-cookies! ctx {:cookiename {:value \"value\"}})
As well as setting the value of the cookie,
you can also set additional attributes:
- `:domain` - restrict the cookie to a specific domain
- `:path` - restrict the cookie to a specific path
- `:secure` - restrict the cookie to HTTPS URLs if true
- `:http-only` - restrict the cookie to HTTP if true
(not accessible via e.g. JavaScript)
- `:max-age` - the number of seconds until the cookie expires
As you can observe is almost identical hash map structure
as used in the ring especification."
[context cookies]
;; TODO: remove nesed blocks using properly the reduce.
(let [^Response response (get-response* context)]
(loop [cookies (into [] cookies)]
(when-let [[cookiename cookiedata] (first cookies)]
(let [cookie (.cookie response (name cookiename) "")]
(reduce (fn [_ [k v]]
(case k
:path (.setPath cookie v)
:domain (.setDomain cookie v)
:secure (.setSecure cookie v)
:http-only (.setHttpOnly cookie v)
:max-age (.setMaxAge cookie v)
:value (.setValue cookie v)))
nil
(into [] cookiedata))
(recur (rest cookies)))))))
(defn- parse-form-files
[^MultiValueMap files result-map]
(persistent!
(reduce
(fn [acc key]
(let [values (.getAll files key)]
(reduce #(assoc-conj! %1 (keyword key) %2) acc values)))
(transient result-map)
(.keySet files))))
(defn- parse-form-fields
[^Form form result-map]
(persistent!
(reduce
(fn [acc the-key]
(let [values (.getAll form the-key)]
(reduce #(assoc-conj! %1 (keyword the-key) %2) acc values)))
(transient result-map)
(.keySet form))))
(defn get-formdata*
{:internal true}
[^Context ctx ^TypedData body]
(let [^Form form (.parse ctx body (Parse/of Form))
^MultiValueMap files (.files form)]
(->> {}
(parse-form-files files)
(parse-form-fields form))))
(declare get-body!)
(defn get-formdata
[{:keys [body] :as context}]
(let [ctx (get-context* context)]
(if body
(p/resolved (get-formdata* ctx body))
(->> (get-body! ctx)
(p/map #(get-formdata* ctx %))))))
(defn resolve-file
"Resolve file using the current filesystem binding
configuration. The path will be resolved as relative
to the filesystem binding root."
[context ^String path]
(let [^Context ctx (:catacumba/context context)]
(.file ctx path)))
(defn get-body!
"Reads asynchronously the body from context. This
function return a promise (CompletableFuture instance).
NOTE: it can only be done once, consider using specialized
body parsing handlers instead of this. This function
should be considered low-level."
[context]
(p/promise
(fn [resolve reject]
(let [^Request request (get-request* context)]
(-> (.getBody request)
(hp/on-error reject)
(hp/then resolve))))))
;; --- Implementation
(defn build-context
{:internal true}
[^Context ctx]
(let [^Request request (.getRequest ctx)
^Response response (.getResponse ctx)]
{:catacumba/context ctx
:catacumba/request request
:catacumba/response response
:path (str "/" (.getPath request))
:query (.getQuery request)
:method (keyword (.. request getMethod getName toLowerCase))
:query-params (get-query-params request)
:cookies (get-cookies request)
:headers (get-headers request true)}))
(defn create-context
{:internal true}
[^Context ctx]
(let [^Request req (get-request* ctx)
^ContextHolder holder (reg/maybe-get req ContextHolder)]
(if holder
(merge (.-data ^ContextHolder holder)
{:route-params (get-route-params ctx)}
(get-context-params ctx))
(let [context (build-context ctx)
holder (ContextHolder. context)]
(reg/add! req holder)
(merge context
{:route-params (get-route-params ctx)}
(get-context-params ctx))))))
| 122533 | ;; Copyright (c) 2015-2016 <NAME> <<EMAIL>>
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;;
;; * Redistributions of source code must retain the above copyright notice, this
;; list of conditions and the following disclaimer.
;;
;; * Redistributions in binary form must reproduce the above copyright notice,
;; this list of conditions and the following disclaimer in the documentation
;; and/or other materials provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(ns catacumba.impl.context
"Functions and helpers for work in a clojure
way with ratpack types."
(:require [catacumba.impl.helpers :as hp]
[catacumba.impl.registry :as reg]
[promesa.core :as p])
(:import catacumba.impl.DelegatedContext
catacumba.impl.ContextHolder
ratpack.handling.Handler
ratpack.handling.Context
ratpack.handling.RequestOutcome
ratpack.form.Form
ratpack.parse.Parse
ratpack.http.Request
ratpack.http.Response
ratpack.http.Headers
ratpack.http.TypedData
ratpack.http.MutableHeaders
ratpack.util.MultiValueMap
ratpack.server.PublicAddress
ratpack.registry.Registry
io.netty.handler.codec.http.cookie.Cookie
java.util.Optional))
;; --- Helpers
(defn- assoc-conj!
{:internal true :no-doc true}
[the-map key val]
(assoc! the-map key
(if-let [cur (get the-map key)]
(if (vector? cur)
(conj cur val)
[cur val])
val)))
(defn get-response*
{:internal true}
[context]
(cond
(instance? Response context) context
(instance? Context context) (.getResponse context)
(map? context) (:catacumba/response context)
:else (throw (ex-info "Invalid arguments2" {}))))
(defn get-context*
{:internal true}
[context]
(cond
(instance? Context context) context
(map? context) (:catacumba/context context)
:else (throw (ex-info "Invalid arguments1" {}))))
(defn get-request*
{:internal true}
[context]
(cond
(instance? Request context) context
(instance? Context context) (.getRequest context)
(map? context) (:catacumba/request context)
:else (throw (ex-info "Invalid arguments3" {}))))
;; --- Public Api
(defn get-context-params
"Get the current context params.
The current params can be passed to the next
handler using the `delegate` function. Is a simple
way to communicate the handlers chain."
{:internal true :no-doc true}
[context]
(let [^Context ctx (get-context* context)
^DelegatedContext dctx (reg/maybe-get ctx DelegatedContext)]
(when dctx
(.-data dctx))))
(defn delegate
"Delegate handling to the next handler in line.
This function accept an additiona parameter for
pass context parameters to the next handlers, and
that can be obtained with `context-params`
function.
Returns an instance of DelegatedContext."
([] (DelegatedContext. nil))
([data] (DelegatedContext. data)))
(defn delegated-context?
"Check if the provided value is a DelegatedContext instance."
[v]
(instance? DelegatedContext v))
(defn public-address
"Get the current public address as URI instance.
The default implementation uses a variety of strategies to
attempt to provide the desired result most of the time.
Information used includes:
- Configured public address URI (optional)
- X-Forwarded-Host header (if included in request)
- X-Forwarded-Proto or X-Forwarded-Ssl headers (if included in request)
- Absolute request URI (if included in request)
- Host header (if included in request)
- Service's bind address and scheme (http vs. https)"
[context]
(let [^Context ctx (get-context* context)
^PublicAddress addr (.get ctx PublicAddress)]
(.get addr ctx)))
(defn on-close
"Register a callback in the context that will be called
when the connection with the client is closed."
[context callback]
(let [^Context ctx (:catacumba/context context)]
(.onClose ctx (hp/fn->action callback))))
(defn before-send
"Register a callback in the context that will be called
just before send the response to the client. Is a useful
hook for set some additional cookies, headers or similar
response transformations."
[context callback]
(let [^Response response (:catacumba/response context)]
(.beforeSend response (hp/fn->action callback))))
;; Implementation notes:
;; Reflection is used for access to private field of Form instance
;; because ratpack does not allows an other way for iter over
;; all parameters (including files) in an uniform way.
(defn- extract-files
[^Form form]
(let [field (.. form getClass (getDeclaredField "files"))]
(.setAccessible field true)
(.get field form)))
(defn get-query-params
"Parse query params from request and return a
maybe multivalue map."
[context]
(let [^Request request (get-request* context)
^MultiValueMap params (.getQueryParams request)]
(persistent!
(reduce (fn [acc key]
(let [values (.getAll params key)]
(reduce #(assoc-conj! %1 (keyword key) %2) acc values)))
(transient {})
(.keySet params)))))
(defn get-route-params
"Return a hash-map with parameters extracted from
routing patterns."
[context]
(let [^Context ctx (get-context* context)]
(into {} hp/keywordice-keys-t (.getAllPathTokens ctx))))
(defn headers->map
{:internal true :no-doc true}
[^MultiValueMap headers keywordize]
(persistent!
(reduce (fn [acc ^String key]
(let [values (.getAll headers key)
key (if keywordize
(keyword (.toLowerCase key))
(.toLowerCase key))]
(reduce #(assoc-conj! %1 key %2) acc values)))
(transient {})
(.keySet headers))))
(defn get-headers
([context] (get-headers context true))
([context keywordize?]
(let [^Request request (get-request* context)
^Headers headers (.getHeaders request)]
(headers->map (.asMultiValueMap headers) keywordize?))))
(defn set-headers!
[context headers]
(let [^Response response (get-response* context)
^MutableHeaders headersmap (.getHeaders response)]
(loop [headers headers]
(when-let [[key vals] (first headers)]
(.set headersmap (name key) vals)
(recur (rest headers))))))
(defn- cookie->map
[^Cookie cookie]
{:path (.path cookie)
:value (.value cookie)
:domain (.domain cookie)
:http-only (.isHttpOnly cookie)
:secure (.isSecure cookie)
:max-age (.maxAge cookie)})
(defn get-cookies
"Get the incoming cookies."
[context]
(let [^Request request (get-request* context)]
(persistent!
(reduce (fn [acc ^Cookie cookie]
(let [name (keyword (.name cookie))]
(assoc! acc name (cookie->map cookie))))
(transient {})
(into [] (.getCookies request))))))
(defn set-status!
"Set the response http status."
[context status]
(let [^Response response (get-response* context)]
(.status response (int status))))
(defn set-cookies!
"Set the outgoing cookies.
(set-cookies! ctx {:cookiename {:value \"value\"}})
As well as setting the value of the cookie,
you can also set additional attributes:
- `:domain` - restrict the cookie to a specific domain
- `:path` - restrict the cookie to a specific path
- `:secure` - restrict the cookie to HTTPS URLs if true
- `:http-only` - restrict the cookie to HTTP if true
(not accessible via e.g. JavaScript)
- `:max-age` - the number of seconds until the cookie expires
As you can observe is almost identical hash map structure
as used in the ring especification."
[context cookies]
;; TODO: remove nesed blocks using properly the reduce.
(let [^Response response (get-response* context)]
(loop [cookies (into [] cookies)]
(when-let [[cookiename cookiedata] (first cookies)]
(let [cookie (.cookie response (name cookiename) "")]
(reduce (fn [_ [k v]]
(case k
:path (.setPath cookie v)
:domain (.setDomain cookie v)
:secure (.setSecure cookie v)
:http-only (.setHttpOnly cookie v)
:max-age (.setMaxAge cookie v)
:value (.setValue cookie v)))
nil
(into [] cookiedata))
(recur (rest cookies)))))))
(defn- parse-form-files
[^MultiValueMap files result-map]
(persistent!
(reduce
(fn [acc key]
(let [values (.getAll files key)]
(reduce #(assoc-conj! %1 (keyword key) %2) acc values)))
(transient result-map)
(.keySet files))))
(defn- parse-form-fields
[^Form form result-map]
(persistent!
(reduce
(fn [acc the-key]
(let [values (.getAll form the-key)]
(reduce #(assoc-conj! %1 (keyword the-key) %2) acc values)))
(transient result-map)
(.keySet form))))
(defn get-formdata*
{:internal true}
[^Context ctx ^TypedData body]
(let [^Form form (.parse ctx body (Parse/of Form))
^MultiValueMap files (.files form)]
(->> {}
(parse-form-files files)
(parse-form-fields form))))
(declare get-body!)
(defn get-formdata
[{:keys [body] :as context}]
(let [ctx (get-context* context)]
(if body
(p/resolved (get-formdata* ctx body))
(->> (get-body! ctx)
(p/map #(get-formdata* ctx %))))))
(defn resolve-file
"Resolve file using the current filesystem binding
configuration. The path will be resolved as relative
to the filesystem binding root."
[context ^String path]
(let [^Context ctx (:catacumba/context context)]
(.file ctx path)))
(defn get-body!
"Reads asynchronously the body from context. This
function return a promise (CompletableFuture instance).
NOTE: it can only be done once, consider using specialized
body parsing handlers instead of this. This function
should be considered low-level."
[context]
(p/promise
(fn [resolve reject]
(let [^Request request (get-request* context)]
(-> (.getBody request)
(hp/on-error reject)
(hp/then resolve))))))
;; --- Implementation
(defn build-context
{:internal true}
[^Context ctx]
(let [^Request request (.getRequest ctx)
^Response response (.getResponse ctx)]
{:catacumba/context ctx
:catacumba/request request
:catacumba/response response
:path (str "/" (.getPath request))
:query (.getQuery request)
:method (keyword (.. request getMethod getName toLowerCase))
:query-params (get-query-params request)
:cookies (get-cookies request)
:headers (get-headers request true)}))
(defn create-context
{:internal true}
[^Context ctx]
(let [^Request req (get-request* ctx)
^ContextHolder holder (reg/maybe-get req ContextHolder)]
(if holder
(merge (.-data ^ContextHolder holder)
{:route-params (get-route-params ctx)}
(get-context-params ctx))
(let [context (build-context ctx)
holder (ContextHolder. context)]
(reg/add! req holder)
(merge context
{:route-params (get-route-params ctx)}
(get-context-params ctx))))))
| true | ;; Copyright (c) 2015-2016 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
;; All rights reserved.
;;
;; Redistribution and use in source and binary forms, with or without
;; modification, are permitted provided that the following conditions are met:
;;
;; * Redistributions of source code must retain the above copyright notice, this
;; list of conditions and the following disclaimer.
;;
;; * Redistributions in binary form must reproduce the above copyright notice,
;; this list of conditions and the following disclaimer in the documentation
;; and/or other materials provided with the distribution.
;;
;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
;; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
;; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
;; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
(ns catacumba.impl.context
"Functions and helpers for work in a clojure
way with ratpack types."
(:require [catacumba.impl.helpers :as hp]
[catacumba.impl.registry :as reg]
[promesa.core :as p])
(:import catacumba.impl.DelegatedContext
catacumba.impl.ContextHolder
ratpack.handling.Handler
ratpack.handling.Context
ratpack.handling.RequestOutcome
ratpack.form.Form
ratpack.parse.Parse
ratpack.http.Request
ratpack.http.Response
ratpack.http.Headers
ratpack.http.TypedData
ratpack.http.MutableHeaders
ratpack.util.MultiValueMap
ratpack.server.PublicAddress
ratpack.registry.Registry
io.netty.handler.codec.http.cookie.Cookie
java.util.Optional))
;; --- Helpers
(defn- assoc-conj!
{:internal true :no-doc true}
[the-map key val]
(assoc! the-map key
(if-let [cur (get the-map key)]
(if (vector? cur)
(conj cur val)
[cur val])
val)))
(defn get-response*
{:internal true}
[context]
(cond
(instance? Response context) context
(instance? Context context) (.getResponse context)
(map? context) (:catacumba/response context)
:else (throw (ex-info "Invalid arguments2" {}))))
(defn get-context*
{:internal true}
[context]
(cond
(instance? Context context) context
(map? context) (:catacumba/context context)
:else (throw (ex-info "Invalid arguments1" {}))))
(defn get-request*
{:internal true}
[context]
(cond
(instance? Request context) context
(instance? Context context) (.getRequest context)
(map? context) (:catacumba/request context)
:else (throw (ex-info "Invalid arguments3" {}))))
;; --- Public Api
(defn get-context-params
"Get the current context params.
The current params can be passed to the next
handler using the `delegate` function. Is a simple
way to communicate the handlers chain."
{:internal true :no-doc true}
[context]
(let [^Context ctx (get-context* context)
^DelegatedContext dctx (reg/maybe-get ctx DelegatedContext)]
(when dctx
(.-data dctx))))
(defn delegate
"Delegate handling to the next handler in line.
This function accept an additiona parameter for
pass context parameters to the next handlers, and
that can be obtained with `context-params`
function.
Returns an instance of DelegatedContext."
([] (DelegatedContext. nil))
([data] (DelegatedContext. data)))
(defn delegated-context?
"Check if the provided value is a DelegatedContext instance."
[v]
(instance? DelegatedContext v))
(defn public-address
"Get the current public address as URI instance.
The default implementation uses a variety of strategies to
attempt to provide the desired result most of the time.
Information used includes:
- Configured public address URI (optional)
- X-Forwarded-Host header (if included in request)
- X-Forwarded-Proto or X-Forwarded-Ssl headers (if included in request)
- Absolute request URI (if included in request)
- Host header (if included in request)
- Service's bind address and scheme (http vs. https)"
[context]
(let [^Context ctx (get-context* context)
^PublicAddress addr (.get ctx PublicAddress)]
(.get addr ctx)))
(defn on-close
"Register a callback in the context that will be called
when the connection with the client is closed."
[context callback]
(let [^Context ctx (:catacumba/context context)]
(.onClose ctx (hp/fn->action callback))))
(defn before-send
"Register a callback in the context that will be called
just before send the response to the client. Is a useful
hook for set some additional cookies, headers or similar
response transformations."
[context callback]
(let [^Response response (:catacumba/response context)]
(.beforeSend response (hp/fn->action callback))))
;; Implementation notes:
;; Reflection is used for access to private field of Form instance
;; because ratpack does not allows an other way for iter over
;; all parameters (including files) in an uniform way.
(defn- extract-files
[^Form form]
(let [field (.. form getClass (getDeclaredField "files"))]
(.setAccessible field true)
(.get field form)))
(defn get-query-params
"Parse query params from request and return a
maybe multivalue map."
[context]
(let [^Request request (get-request* context)
^MultiValueMap params (.getQueryParams request)]
(persistent!
(reduce (fn [acc key]
(let [values (.getAll params key)]
(reduce #(assoc-conj! %1 (keyword key) %2) acc values)))
(transient {})
(.keySet params)))))
(defn get-route-params
"Return a hash-map with parameters extracted from
routing patterns."
[context]
(let [^Context ctx (get-context* context)]
(into {} hp/keywordice-keys-t (.getAllPathTokens ctx))))
(defn headers->map
{:internal true :no-doc true}
[^MultiValueMap headers keywordize]
(persistent!
(reduce (fn [acc ^String key]
(let [values (.getAll headers key)
key (if keywordize
(keyword (.toLowerCase key))
(.toLowerCase key))]
(reduce #(assoc-conj! %1 key %2) acc values)))
(transient {})
(.keySet headers))))
(defn get-headers
([context] (get-headers context true))
([context keywordize?]
(let [^Request request (get-request* context)
^Headers headers (.getHeaders request)]
(headers->map (.asMultiValueMap headers) keywordize?))))
(defn set-headers!
[context headers]
(let [^Response response (get-response* context)
^MutableHeaders headersmap (.getHeaders response)]
(loop [headers headers]
(when-let [[key vals] (first headers)]
(.set headersmap (name key) vals)
(recur (rest headers))))))
(defn- cookie->map
[^Cookie cookie]
{:path (.path cookie)
:value (.value cookie)
:domain (.domain cookie)
:http-only (.isHttpOnly cookie)
:secure (.isSecure cookie)
:max-age (.maxAge cookie)})
(defn get-cookies
"Get the incoming cookies."
[context]
(let [^Request request (get-request* context)]
(persistent!
(reduce (fn [acc ^Cookie cookie]
(let [name (keyword (.name cookie))]
(assoc! acc name (cookie->map cookie))))
(transient {})
(into [] (.getCookies request))))))
(defn set-status!
"Set the response http status."
[context status]
(let [^Response response (get-response* context)]
(.status response (int status))))
(defn set-cookies!
"Set the outgoing cookies.
(set-cookies! ctx {:cookiename {:value \"value\"}})
As well as setting the value of the cookie,
you can also set additional attributes:
- `:domain` - restrict the cookie to a specific domain
- `:path` - restrict the cookie to a specific path
- `:secure` - restrict the cookie to HTTPS URLs if true
- `:http-only` - restrict the cookie to HTTP if true
(not accessible via e.g. JavaScript)
- `:max-age` - the number of seconds until the cookie expires
As you can observe is almost identical hash map structure
as used in the ring especification."
[context cookies]
;; TODO: remove nesed blocks using properly the reduce.
(let [^Response response (get-response* context)]
(loop [cookies (into [] cookies)]
(when-let [[cookiename cookiedata] (first cookies)]
(let [cookie (.cookie response (name cookiename) "")]
(reduce (fn [_ [k v]]
(case k
:path (.setPath cookie v)
:domain (.setDomain cookie v)
:secure (.setSecure cookie v)
:http-only (.setHttpOnly cookie v)
:max-age (.setMaxAge cookie v)
:value (.setValue cookie v)))
nil
(into [] cookiedata))
(recur (rest cookies)))))))
(defn- parse-form-files
[^MultiValueMap files result-map]
(persistent!
(reduce
(fn [acc key]
(let [values (.getAll files key)]
(reduce #(assoc-conj! %1 (keyword key) %2) acc values)))
(transient result-map)
(.keySet files))))
(defn- parse-form-fields
[^Form form result-map]
(persistent!
(reduce
(fn [acc the-key]
(let [values (.getAll form the-key)]
(reduce #(assoc-conj! %1 (keyword the-key) %2) acc values)))
(transient result-map)
(.keySet form))))
(defn get-formdata*
{:internal true}
[^Context ctx ^TypedData body]
(let [^Form form (.parse ctx body (Parse/of Form))
^MultiValueMap files (.files form)]
(->> {}
(parse-form-files files)
(parse-form-fields form))))
(declare get-body!)
(defn get-formdata
[{:keys [body] :as context}]
(let [ctx (get-context* context)]
(if body
(p/resolved (get-formdata* ctx body))
(->> (get-body! ctx)
(p/map #(get-formdata* ctx %))))))
(defn resolve-file
"Resolve file using the current filesystem binding
configuration. The path will be resolved as relative
to the filesystem binding root."
[context ^String path]
(let [^Context ctx (:catacumba/context context)]
(.file ctx path)))
(defn get-body!
"Reads asynchronously the body from context. This
function return a promise (CompletableFuture instance).
NOTE: it can only be done once, consider using specialized
body parsing handlers instead of this. This function
should be considered low-level."
[context]
(p/promise
(fn [resolve reject]
(let [^Request request (get-request* context)]
(-> (.getBody request)
(hp/on-error reject)
(hp/then resolve))))))
;; --- Implementation
(defn build-context
{:internal true}
[^Context ctx]
(let [^Request request (.getRequest ctx)
^Response response (.getResponse ctx)]
{:catacumba/context ctx
:catacumba/request request
:catacumba/response response
:path (str "/" (.getPath request))
:query (.getQuery request)
:method (keyword (.. request getMethod getName toLowerCase))
:query-params (get-query-params request)
:cookies (get-cookies request)
:headers (get-headers request true)}))
(defn create-context
{:internal true}
[^Context ctx]
(let [^Request req (get-request* ctx)
^ContextHolder holder (reg/maybe-get req ContextHolder)]
(if holder
(merge (.-data ^ContextHolder holder)
{:route-params (get-route-params ctx)}
(get-context-params ctx))
(let [context (build-context ctx)
holder (ContextHolder. context)]
(reg/add! req holder)
(merge context
{:route-params (get-route-params ctx)}
(get-context-params ctx))))))
|
[
{
"context": "ohnny\n :movie/title \"Johnny\"\n :movie/genre :thri",
"end": 4510,
"score": 0.9968536496162415,
"start": 4504,
"tag": "NAME",
"value": "Johnny"
},
{
"context": "x-data [[:db/retract 79164837199949 :movie/title \"Commando David\"]\n [:db/add 791648371",
"end": 4875,
"score": 0.9950572848320007,
"start": 4861,
"tag": "NAME",
"value": "Commando David"
},
{
"context": " [:db/add 79164837199949 :movie/title \"Commando\"]]})\n )\n\n(comment ;; Commando\n (let [pull-query-1",
"end": 4953,
"score": 0.9457970857620239,
"start": 4945,
"tag": "NAME",
"value": "Commando"
}
] | src/datomic/client_api_tutorial.clj | michelemendel/datomic-playground | 0 | (ns datomic.client-api-tutorial
(:require [datomic.client.api :as d]
[clojure.pprint :as pp]))
(defn reset-test-db
"Reset test database"
[cfg db-name schema ident-genres test-data]
(let [client (d/client cfg)
_ (d/delete-database client {:db-name db-name})
_ (d/create-database client {:db-name db-name})
conn (d/connect client {:db-name db-name})
schema-tx (d/transact conn {:tx-data schema})
ident-genres-tx (d/transact conn {:tx-data ident-genres})
test-data-tx (d/transact conn {:tx-data test-data})]
{:test-data-tx test-data-tx :client client :conn conn}))
(defn init-test-db
"Initialize test database"
[cfg db-name]
(let [client (d/client cfg)
conn (d/connect client {:db-name db-name})]
{:test-data-tx nil :client client :conn conn}))
(def system "datomic-tutorial")
(def db-name "movies")
(def cfg {:server-type :dev-local
:system system})
(def movie-schema [{:db/ident :movie/uid
:db/valueType :db.type/keyword
:db/cardinality :db.cardinality/one
:db/unique :db.unique/identity
:db/doc "A UID"}
{:db/ident :movie/title
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db/doc "The title of the movie"}
{:db/ident :movie/genre
:db/valueType :db.type/ref
:db/cardinality :db.cardinality/one
:db/doc "The genre of the movie"}
{:db/ident :movie/release-year
:db/valueType :db.type/long
:db/cardinality :db.cardinality/one
:db/doc "The year the movie was released in theaters"}])
;; Assertion - a single atomic fact
(defn make-idents [x] (mapv #(hash-map :db/ident %) x))
(def ident-genres (make-idents [:action :adventure :thriller :punk-dystopia]))
(def test-data [{:movie/uid :the-goonies
:movie/title "The Goonies"
:movie/genre :action
:movie/release-year 1985}
{:movie/uid :commando
:movie/title "Commando"
:movie/genre :thriller
:movie/release-year 1985}
{:movie/uid :repo_man
:movie/title "Repo Man"
:movie/genre :punk-dystopia
:movie/release-year 1984}])
;;Initialize or reset database when evaluating this namespace
;;(def db-conf (reset-test-db cfg db-name movie-schema ident-genres test-data))
(def db-conf (init-test-db cfg db-name))
;; List Databases in a System
(defn list-dbs [db-conf] (pp/pprint (d/list-databases (:client db-conf) {})))
;;(list-dbs db-conf)
;; Create a Database
(defn create-db [db-conf] (d/create-database (:client db-conf) {:db-name db-name}))
;; Delete a Database
(defn delete-db [db-conf] (d/delete-database (:client db-conf) {:db-name db-name}))
;;(delete-db db-conf)
;;(create-db db-conf)
;;(def client (:client db-conf))
(def conn (:conn db-conf))
;; Queries
(def titles '{:find [?e ?v] :where [[?e :movie/title ?v]]})
(def genres '{:find [?e ?v] :where [[?e :movie/genre ?id]
[?id :db/ident ?v]]})
(def years '{:find [?e ?v] :where [[?e :movie/release-year ?v]]})
(def all-data '{:find [?e ?uid ?title ?genre ?year]
:in [$]
:where [[?e :movie/uid ?uid]
[?e :movie/title ?title]
[?e :movie/genre ?genre-id]
[?e :movie/release-year ?year]
[?genre-id :db/ident ?genre]]})
(def get-movie-by-title '{:find [?e ?title ?genre ?year]
:in [$ ?title]
:where [[?e :movie/title ?title]
[?e :movie/genre ?genre-id]
[?e :movie/release-year ?year]
[?genre-id :db/ident ?genre]]})
(def get-movie-id-by-title '[:find ?e
:in $ ?title
:where [?e :movie/title ?title]])
;; Playground
(-> db-conf :test-data-tx :tempids)
(-> db-conf :test-data-tx :tempids)
(:test-data-tx db-conf)
(comment
;;(d/transact conn {:tx-data movie-schema})
;;(d/transact conn {:tx-data test-data})
(d/transact conn {:tx-data [{:movie/uid :johnny
:movie/title "Johnny"
:movie/genre :thriller
:movie/release-year 1984}]})
;;(d/transact conn {:tx-data [[:db/retract 87960930222160 :movie/genre ""]]})
;;(d/transact conn {:tx-data [[:db/retractEntity [:movie/uid :johnny]]]})
;; Rename
(d/transact conn {:tx-data [[:db/retract 79164837199949 :movie/title "Commando David"]
[:db/add 79164837199949 :movie/title "Commando"]]})
)
(comment ;; Commando
(let [pull-query-1 [:movie/title {:movie/genre [:db/ident]}]
pull-query-2 [:movie/title :movie/genre]]
(pp/pprint (d/pull (d/db conn) pull-query-1 (ffirst (d/q get-movie-id-by-title (d/db conn) "Commando"))))
;; Since :movie/uid is unique
(pp/pprint (d/pull (d/db conn) pull-query-2 [:movie/uid :commando]))))
(comment
(do
;;(println "Titles") (pp/pprint (d/q {:query titles :args [(d/db conn)]}))
;;(println "Years") (pp/pprint (d/q {:query years :args [(d/db conn)]}))
;;(println "Genres") (pp/pprint (d/q {:query genres :args [(d/db conn)]}))
(println "Commando") (pp/pprint (d/q get-movie-by-title (d/db conn) "Commando"))
;;(println "All data") (pp/pprint (d/q {:query all-data :args [(d/db conn)]}))
))
;; Raw index
(comment
(d/datoms (d/db conn) {:index :eavt})
(d/datoms (d/db conn) {:index :aevt})
(d/datoms (d/db conn) {:index :avet})
(d/datoms (d/db conn) {:index :vaet})
(pp/pprint (d/datoms (d/db conn) {:index :eavt :components [:movie/title]}))
(pp/pprint (d/datoms (d/db conn) {:index :aevt :components [:movie/title]}))
(pp/pprint (d/datoms (d/db conn) {:index :avet :components [:movie/title]}))
(pp/pprint (d/datoms (d/db conn) {:index :vaet :components [:movie/title]}))
)
| 61257 | (ns datomic.client-api-tutorial
(:require [datomic.client.api :as d]
[clojure.pprint :as pp]))
(defn reset-test-db
"Reset test database"
[cfg db-name schema ident-genres test-data]
(let [client (d/client cfg)
_ (d/delete-database client {:db-name db-name})
_ (d/create-database client {:db-name db-name})
conn (d/connect client {:db-name db-name})
schema-tx (d/transact conn {:tx-data schema})
ident-genres-tx (d/transact conn {:tx-data ident-genres})
test-data-tx (d/transact conn {:tx-data test-data})]
{:test-data-tx test-data-tx :client client :conn conn}))
(defn init-test-db
"Initialize test database"
[cfg db-name]
(let [client (d/client cfg)
conn (d/connect client {:db-name db-name})]
{:test-data-tx nil :client client :conn conn}))
(def system "datomic-tutorial")
(def db-name "movies")
(def cfg {:server-type :dev-local
:system system})
(def movie-schema [{:db/ident :movie/uid
:db/valueType :db.type/keyword
:db/cardinality :db.cardinality/one
:db/unique :db.unique/identity
:db/doc "A UID"}
{:db/ident :movie/title
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db/doc "The title of the movie"}
{:db/ident :movie/genre
:db/valueType :db.type/ref
:db/cardinality :db.cardinality/one
:db/doc "The genre of the movie"}
{:db/ident :movie/release-year
:db/valueType :db.type/long
:db/cardinality :db.cardinality/one
:db/doc "The year the movie was released in theaters"}])
;; Assertion - a single atomic fact
(defn make-idents [x] (mapv #(hash-map :db/ident %) x))
(def ident-genres (make-idents [:action :adventure :thriller :punk-dystopia]))
(def test-data [{:movie/uid :the-goonies
:movie/title "The Goonies"
:movie/genre :action
:movie/release-year 1985}
{:movie/uid :commando
:movie/title "Commando"
:movie/genre :thriller
:movie/release-year 1985}
{:movie/uid :repo_man
:movie/title "Repo Man"
:movie/genre :punk-dystopia
:movie/release-year 1984}])
;;Initialize or reset database when evaluating this namespace
;;(def db-conf (reset-test-db cfg db-name movie-schema ident-genres test-data))
(def db-conf (init-test-db cfg db-name))
;; List Databases in a System
(defn list-dbs [db-conf] (pp/pprint (d/list-databases (:client db-conf) {})))
;;(list-dbs db-conf)
;; Create a Database
(defn create-db [db-conf] (d/create-database (:client db-conf) {:db-name db-name}))
;; Delete a Database
(defn delete-db [db-conf] (d/delete-database (:client db-conf) {:db-name db-name}))
;;(delete-db db-conf)
;;(create-db db-conf)
;;(def client (:client db-conf))
(def conn (:conn db-conf))
;; Queries
(def titles '{:find [?e ?v] :where [[?e :movie/title ?v]]})
(def genres '{:find [?e ?v] :where [[?e :movie/genre ?id]
[?id :db/ident ?v]]})
(def years '{:find [?e ?v] :where [[?e :movie/release-year ?v]]})
(def all-data '{:find [?e ?uid ?title ?genre ?year]
:in [$]
:where [[?e :movie/uid ?uid]
[?e :movie/title ?title]
[?e :movie/genre ?genre-id]
[?e :movie/release-year ?year]
[?genre-id :db/ident ?genre]]})
(def get-movie-by-title '{:find [?e ?title ?genre ?year]
:in [$ ?title]
:where [[?e :movie/title ?title]
[?e :movie/genre ?genre-id]
[?e :movie/release-year ?year]
[?genre-id :db/ident ?genre]]})
(def get-movie-id-by-title '[:find ?e
:in $ ?title
:where [?e :movie/title ?title]])
;; Playground
(-> db-conf :test-data-tx :tempids)
(-> db-conf :test-data-tx :tempids)
(:test-data-tx db-conf)
(comment
;;(d/transact conn {:tx-data movie-schema})
;;(d/transact conn {:tx-data test-data})
(d/transact conn {:tx-data [{:movie/uid :johnny
:movie/title "<NAME>"
:movie/genre :thriller
:movie/release-year 1984}]})
;;(d/transact conn {:tx-data [[:db/retract 87960930222160 :movie/genre ""]]})
;;(d/transact conn {:tx-data [[:db/retractEntity [:movie/uid :johnny]]]})
;; Rename
(d/transact conn {:tx-data [[:db/retract 79164837199949 :movie/title "<NAME>"]
[:db/add 79164837199949 :movie/title "<NAME>"]]})
)
(comment ;; Commando
(let [pull-query-1 [:movie/title {:movie/genre [:db/ident]}]
pull-query-2 [:movie/title :movie/genre]]
(pp/pprint (d/pull (d/db conn) pull-query-1 (ffirst (d/q get-movie-id-by-title (d/db conn) "Commando"))))
;; Since :movie/uid is unique
(pp/pprint (d/pull (d/db conn) pull-query-2 [:movie/uid :commando]))))
(comment
(do
;;(println "Titles") (pp/pprint (d/q {:query titles :args [(d/db conn)]}))
;;(println "Years") (pp/pprint (d/q {:query years :args [(d/db conn)]}))
;;(println "Genres") (pp/pprint (d/q {:query genres :args [(d/db conn)]}))
(println "Commando") (pp/pprint (d/q get-movie-by-title (d/db conn) "Commando"))
;;(println "All data") (pp/pprint (d/q {:query all-data :args [(d/db conn)]}))
))
;; Raw index
(comment
(d/datoms (d/db conn) {:index :eavt})
(d/datoms (d/db conn) {:index :aevt})
(d/datoms (d/db conn) {:index :avet})
(d/datoms (d/db conn) {:index :vaet})
(pp/pprint (d/datoms (d/db conn) {:index :eavt :components [:movie/title]}))
(pp/pprint (d/datoms (d/db conn) {:index :aevt :components [:movie/title]}))
(pp/pprint (d/datoms (d/db conn) {:index :avet :components [:movie/title]}))
(pp/pprint (d/datoms (d/db conn) {:index :vaet :components [:movie/title]}))
)
| true | (ns datomic.client-api-tutorial
(:require [datomic.client.api :as d]
[clojure.pprint :as pp]))
(defn reset-test-db
"Reset test database"
[cfg db-name schema ident-genres test-data]
(let [client (d/client cfg)
_ (d/delete-database client {:db-name db-name})
_ (d/create-database client {:db-name db-name})
conn (d/connect client {:db-name db-name})
schema-tx (d/transact conn {:tx-data schema})
ident-genres-tx (d/transact conn {:tx-data ident-genres})
test-data-tx (d/transact conn {:tx-data test-data})]
{:test-data-tx test-data-tx :client client :conn conn}))
(defn init-test-db
"Initialize test database"
[cfg db-name]
(let [client (d/client cfg)
conn (d/connect client {:db-name db-name})]
{:test-data-tx nil :client client :conn conn}))
(def system "datomic-tutorial")
(def db-name "movies")
(def cfg {:server-type :dev-local
:system system})
(def movie-schema [{:db/ident :movie/uid
:db/valueType :db.type/keyword
:db/cardinality :db.cardinality/one
:db/unique :db.unique/identity
:db/doc "A UID"}
{:db/ident :movie/title
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db/doc "The title of the movie"}
{:db/ident :movie/genre
:db/valueType :db.type/ref
:db/cardinality :db.cardinality/one
:db/doc "The genre of the movie"}
{:db/ident :movie/release-year
:db/valueType :db.type/long
:db/cardinality :db.cardinality/one
:db/doc "The year the movie was released in theaters"}])
;; Assertion - a single atomic fact
(defn make-idents [x] (mapv #(hash-map :db/ident %) x))
(def ident-genres (make-idents [:action :adventure :thriller :punk-dystopia]))
(def test-data [{:movie/uid :the-goonies
:movie/title "The Goonies"
:movie/genre :action
:movie/release-year 1985}
{:movie/uid :commando
:movie/title "Commando"
:movie/genre :thriller
:movie/release-year 1985}
{:movie/uid :repo_man
:movie/title "Repo Man"
:movie/genre :punk-dystopia
:movie/release-year 1984}])
;;Initialize or reset database when evaluating this namespace
;;(def db-conf (reset-test-db cfg db-name movie-schema ident-genres test-data))
(def db-conf (init-test-db cfg db-name))
;; List Databases in a System
(defn list-dbs [db-conf] (pp/pprint (d/list-databases (:client db-conf) {})))
;;(list-dbs db-conf)
;; Create a Database
(defn create-db [db-conf] (d/create-database (:client db-conf) {:db-name db-name}))
;; Delete a Database
(defn delete-db [db-conf] (d/delete-database (:client db-conf) {:db-name db-name}))
;;(delete-db db-conf)
;;(create-db db-conf)
;;(def client (:client db-conf))
(def conn (:conn db-conf))
;; Queries
(def titles '{:find [?e ?v] :where [[?e :movie/title ?v]]})
(def genres '{:find [?e ?v] :where [[?e :movie/genre ?id]
[?id :db/ident ?v]]})
(def years '{:find [?e ?v] :where [[?e :movie/release-year ?v]]})
(def all-data '{:find [?e ?uid ?title ?genre ?year]
:in [$]
:where [[?e :movie/uid ?uid]
[?e :movie/title ?title]
[?e :movie/genre ?genre-id]
[?e :movie/release-year ?year]
[?genre-id :db/ident ?genre]]})
(def get-movie-by-title '{:find [?e ?title ?genre ?year]
:in [$ ?title]
:where [[?e :movie/title ?title]
[?e :movie/genre ?genre-id]
[?e :movie/release-year ?year]
[?genre-id :db/ident ?genre]]})
(def get-movie-id-by-title '[:find ?e
:in $ ?title
:where [?e :movie/title ?title]])
;; Playground
(-> db-conf :test-data-tx :tempids)
(-> db-conf :test-data-tx :tempids)
(:test-data-tx db-conf)
(comment
;;(d/transact conn {:tx-data movie-schema})
;;(d/transact conn {:tx-data test-data})
(d/transact conn {:tx-data [{:movie/uid :johnny
:movie/title "PI:NAME:<NAME>END_PI"
:movie/genre :thriller
:movie/release-year 1984}]})
;;(d/transact conn {:tx-data [[:db/retract 87960930222160 :movie/genre ""]]})
;;(d/transact conn {:tx-data [[:db/retractEntity [:movie/uid :johnny]]]})
;; Rename
(d/transact conn {:tx-data [[:db/retract 79164837199949 :movie/title "PI:NAME:<NAME>END_PI"]
[:db/add 79164837199949 :movie/title "PI:NAME:<NAME>END_PI"]]})
)
(comment ;; Commando
(let [pull-query-1 [:movie/title {:movie/genre [:db/ident]}]
pull-query-2 [:movie/title :movie/genre]]
(pp/pprint (d/pull (d/db conn) pull-query-1 (ffirst (d/q get-movie-id-by-title (d/db conn) "Commando"))))
;; Since :movie/uid is unique
(pp/pprint (d/pull (d/db conn) pull-query-2 [:movie/uid :commando]))))
(comment
(do
;;(println "Titles") (pp/pprint (d/q {:query titles :args [(d/db conn)]}))
;;(println "Years") (pp/pprint (d/q {:query years :args [(d/db conn)]}))
;;(println "Genres") (pp/pprint (d/q {:query genres :args [(d/db conn)]}))
(println "Commando") (pp/pprint (d/q get-movie-by-title (d/db conn) "Commando"))
;;(println "All data") (pp/pprint (d/q {:query all-data :args [(d/db conn)]}))
))
;; Raw index
(comment
(d/datoms (d/db conn) {:index :eavt})
(d/datoms (d/db conn) {:index :aevt})
(d/datoms (d/db conn) {:index :avet})
(d/datoms (d/db conn) {:index :vaet})
(pp/pprint (d/datoms (d/db conn) {:index :eavt :components [:movie/title]}))
(pp/pprint (d/datoms (d/db conn) {:index :aevt :components [:movie/title]}))
(pp/pprint (d/datoms (d/db conn) {:index :avet :components [:movie/title]}))
(pp/pprint (d/datoms (d/db conn) {:index :vaet :components [:movie/title]}))
)
|
[
{
"context": "518c-6d3e-4e75-87f1-ff08bdc933be\"\n :user/email \"user@test.com\"\n :user/password \"123456\"\n :user/created-at (",
"end": 319,
"score": 0.999921441078186,
"start": 306,
"tag": "EMAIL",
"value": "user@test.com"
},
{
"context": " :user/email \"user@test.com\"\n :user/password \"123456\"\n :user/created-at (java.util.Date. 14956360544",
"end": 346,
"score": 0.9994571805000305,
"start": 340,
"tag": "PASSWORD",
"value": "123456"
},
{
"context": "g \"valid changesets\"\n (let [user {:user/email \"test@user.com\" :user/password \"123456\"}]\n (is (-> user cha",
"end": 745,
"score": 0.9999203681945801,
"start": 732,
"tag": "EMAIL",
"value": "test@user.com"
},
{
"context": "user {:user/email \"test@user.com\" :user/password \"123456\"}]\n (is (-> user changeset+errors nil?)))))\n",
"end": 769,
"score": 0.9994296431541443,
"start": 763,
"tag": "PASSWORD",
"value": "123456"
},
{
"context": "esting \"invalid email\"\n (let [user {:user/email \"@user.com\" :user/password \"123456\"}]\n (is (-> ",
"end": 908,
"score": 0.6439329981803894,
"start": 908,
"tag": "USERNAME",
"value": ""
},
{
"context": "ing \"invalid email\"\n (let [user {:user/email \"@user.com\" :user/password \"123456\"}]\n (is (-> user cha",
"end": 919,
"score": 0.5203340649604797,
"start": 911,
"tag": "EMAIL",
"value": "user.com"
},
{
"context": "et [user {:user/email \"@user.com\" :user/password \"123456\"}]\n (is (-> user changeset+errors :user/emai",
"end": 943,
"score": 0.9994330406188965,
"start": 937,
"tag": "PASSWORD",
"value": "123456"
},
{
"context": "g \"invalid password\"\n (let [user {:user/email \"test@user.com\" :user/password \"...\"}]\n (is (-> user change",
"end": 1078,
"score": 0.9999200701713562,
"start": 1065,
"tag": "EMAIL",
"value": "test@user.com"
},
{
"context": " strings to changeset\"\n (let [params {\"email\" \"test@user.com\" \"password\" \"123456\"}]\n (is (-> params (cast",
"end": 1465,
"score": 0.9999259114265442,
"start": 1452,
"tag": "EMAIL",
"value": "test@user.com"
},
{
"context": "(let [params {\"email\" \"test@user.com\" \"password\" \"123456\"}]\n (is (-> params (cast+errors :user) n",
"end": 1481,
"score": 0.9994346499443054,
"start": 1479,
"tag": "PASSWORD",
"value": "12"
},
{
"context": "+errors :user) nil?)))\n (let [params {\"email\" \"test@user\" \"password\" \"123456\"}]\n (is (-> params ",
"end": 1569,
"score": 0.45197799801826477,
"start": 1565,
"tag": "USERNAME",
"value": "test"
},
{
"context": "rs :user) nil?)))\n (let [params {\"email\" \"test@user\" \"password\" \"123456\"}]\n (is (-> params (cast",
"end": 1574,
"score": 0.39682337641716003,
"start": 1570,
"tag": "EMAIL",
"value": "user"
},
{
"context": " (let [params {\"email\" \"test@user\" \"password\" \"123456\"}]\n (is (-> params (cast+errors :user) :user",
"end": 1594,
"score": 0.9994399547576904,
"start": 1588,
"tag": "PASSWORD",
"value": "123456"
},
{
"context": ") :user/email some?)))\n (let [params {\"email\" \"test@user.com\" \"password\" \"...\"}]\n (is (-> params (cast+er",
"end": 1700,
"score": 0.9999018907546997,
"start": 1687,
"tag": "EMAIL",
"value": "test@user.com"
},
{
"context": "rmatting to changeset\"\n (let [params {\"email\" \"test@user.com\" :password \"123456\"}]\n (is (-> params (cast+",
"end": 1899,
"score": 0.9998741149902344,
"start": 1886,
"tag": "EMAIL",
"value": "test@user.com"
},
{
"context": " (let [params {\"email\" \"test@user.com\" :password \"123456\"}]\n (is (-> params (cast+errors :user) nil?)",
"end": 1918,
"score": 0.999457597732544,
"start": 1912,
"tag": "PASSWORD",
"value": "123456"
},
{
"context": "rs :user) nil?)))\n (let [params {\"email\" \"test@user\" \"password\" \"123456\"}]\n (is (-> params (cast",
"end": 2007,
"score": 0.41450485587120056,
"start": 2003,
"tag": "USERNAME",
"value": "user"
},
{
"context": " (let [params {\"email\" \"test@user\" \"password\" \"123456\"}]\n (is (-> params (cast+errors :user) :user",
"end": 2027,
"score": 0.9994180202484131,
"start": 2021,
"tag": "PASSWORD",
"value": "123456"
},
{
"context": ") :user/email some?)))\n (let [params {\"email\" \"test@user.com\" \"password\" \"...\"}]\n (is (-> params (cast+er",
"end": 2133,
"score": 0.9998923540115356,
"start": 2120,
"tag": "EMAIL",
"value": "test@user.com"
},
{
"context": "-user\n (changeset/create {:user/email \"foo@bar.baz\"})\n :changeset/errors\n nil?",
"end": 2671,
"score": 0.9980388879776001,
"start": 2660,
"tag": "EMAIL",
"value": "foo@bar.baz"
},
{
"context": " :changeset/errors\n nil?))\n (is (= \"foo@bar.baz\"\n (-> existing-user\n (changes",
"end": 2747,
"score": 0.999303936958313,
"start": 2736,
"tag": "EMAIL",
"value": "foo@bar.baz"
},
{
"context": "user\n (changeset/create {:user/email \"foo@bar.baz\"})\n :changeset/result\n :u",
"end": 2832,
"score": 0.999001681804657,
"start": 2821,
"tag": "EMAIL",
"value": "foo@bar.baz"
},
{
"context": "user\n (changeset/create {:user/email \"foo@bar.baz\"})\n :changeset/result\n :u",
"end": 2998,
"score": 0.9981096386909485,
"start": 2987,
"tag": "EMAIL",
"value": "foo@bar.baz"
},
{
"context": " (changeset/create {:user/password-confirmation \"987654\"})\n :changeset/result\n ",
"end": 3518,
"score": 0.9984521865844727,
"start": 3512,
"tag": "PASSWORD",
"value": "987654"
},
{
"context": "n\n nil?))\n (is (-> {:user/email \"test@user.com\"\n :user/password \"987654\"\n ",
"end": 3659,
"score": 0.9999150037765503,
"start": 3646,
"tag": "EMAIL",
"value": "test@user.com"
},
{
"context": "mail \"test@user.com\"\n :user/password \"987654\"\n :user/password-confirmation \"987654",
"end": 3696,
"score": 0.9994924068450928,
"start": 3690,
"tag": "PASSWORD",
"value": "987654"
},
{
"context": "987654\"\n :user/password-confirmation \"987654\"}\n (changeset/create)\n :cha",
"end": 3746,
"score": 0.9993346333503723,
"start": 3740,
"tag": "PASSWORD",
"value": "987654"
},
{
"context": "firmation validator\"\n (let [user {:user/email \"user@test.com\"\n :user/password \"123456\"\n ",
"end": 3984,
"score": 0.9999071359634399,
"start": 3971,
"tag": "EMAIL",
"value": "user@test.com"
},
{
"context": "l \"user@test.com\"\n :user/password \"123456\"\n :user/password-confirmation \"123",
"end": 4024,
"score": 0.9994752407073975,
"start": 4018,
"tag": "PASSWORD",
"value": "123456"
},
{
"context": "456\"\n :user/password-confirmation \"123456\"}]\n (is (-> user\n (changeset/cr",
"end": 4077,
"score": 0.9994864463806152,
"start": 4071,
"tag": "PASSWORD",
"value": "123456"
},
{
"context": " (is (-> (assoc user :user/password-confirmation \"123456+7\")\n (changeset/create [:user/password",
"end": 4274,
"score": 0.9994898438453674,
"start": 4266,
"tag": "PASSWORD",
"value": "123456+7"
},
{
"context": "with invalid fields\"\n (let [user {:user/email \"user@test.com\"\n :user/password \"1234\"\n ",
"end": 4540,
"score": 0.9999030828475952,
"start": 4527,
"tag": "EMAIL",
"value": "user@test.com"
},
{
"context": "l \"user@test.com\"\n :user/password \"1234\"\n :user/password-confirmation \"123",
"end": 4578,
"score": 0.9994803667068481,
"start": 4574,
"tag": "PASSWORD",
"value": "1234"
},
{
"context": "234\"\n :user/password-confirmation \"1234\"}]\n (is (-> user\n (changeset/cr",
"end": 4629,
"score": 0.9994872212409973,
"start": 4625,
"tag": "PASSWORD",
"value": "1234"
},
{
"context": " new email to existing user\"\n (let [new-email \"bar@baz.bar\"\n changeset\n (-> {:user/email \"",
"end": 4870,
"score": 0.9995234608650208,
"start": 4859,
"tag": "EMAIL",
"value": "bar@baz.bar"
},
{
"context": "{:user/email \"foo\"\n :user/password \"123456\"}\n (changeset/assoc\n :",
"end": 4962,
"score": 0.9994856715202332,
"start": 4956,
"tag": "PASSWORD",
"value": "123456"
},
{
"context": "dd a new email to changeset\"\n (let [new-email \"bar@baz.bar\"\n changeset (-> {:user/email \"foo\" :user",
"end": 5301,
"score": 0.9995988607406616,
"start": 5290,
"tag": "EMAIL",
"value": "bar@baz.bar"
},
{
"context": " changeset (-> {:user/email \"foo\" :user/password \"123456\"}\n (changeset/create)\n ",
"end": 5368,
"score": 0.9992009997367859,
"start": 5362,
"tag": "PASSWORD",
"value": "123456"
}
] | test/gungnir/changeset_test.clj | ikitommi/gungnir | 142 | (ns gungnir.changeset-test
(:require
[clojure.test :refer :all]
[gungnir.changeset :as changeset]
[gungnir.test.util :as util]))
(use-fixtures :once util/once-fixture)
(use-fixtures :each util/each-fixture)
(def existing-user
{:user/id "e52c518c-6d3e-4e75-87f1-ff08bdc933be"
:user/email "user@test.com"
:user/password "123456"
:user/created-at (java.util.Date. 1495636054438)
:user/updated-at (java.util.Date. 1495636054438)})
(defn- cast+errors [params model]
(-> params (changeset/cast model) changeset/create :changeset/errors))
(defn- changeset+errors [params]
(-> params changeset/create :changeset/errors))
(deftest valid-user-tests
(testing "valid changesets"
(let [user {:user/email "test@user.com" :user/password "123456"}]
(is (-> user changeset+errors nil?)))))
(deftest invalid-valid-user-tests
(testing "invalid email"
(let [user {:user/email "@user.com" :user/password "123456"}]
(is (-> user changeset+errors :user/email some?))))
(testing "invalid password"
(let [user {:user/email "test@user.com" :user/password "..."}]
(is (-> user changeset+errors :user/password some?))))
(testing "invalid email and password"
(let [user {:user/email "test@user" :user/password "..."}]
(is (= #{:user/email :user/password} (-> user changeset+errors keys set))))))
(deftest casting-to-changeset
(testing "casting strings to changeset"
(let [params {"email" "test@user.com" "password" "123456"}]
(is (-> params (cast+errors :user) nil?)))
(let [params {"email" "test@user" "password" "123456"}]
(is (-> params (cast+errors :user) :user/email some?)))
(let [params {"email" "test@user.com" "password" "..."}]
(is (-> params (cast+errors :user) :user/password some?))))
(testing "casting strings and keywords with formatting to changeset"
(let [params {"email" "test@user.com" :password "123456"}]
(is (-> params (cast+errors :user) nil?)))
(let [params {"email" "test@user" "password" "123456"}]
(is (-> params (cast+errors :user) :user/email some?)))
(let [params {"email" "test@user.com" "password" "..."}]
(is (-> params (cast+errors :user) :user/password some?))))
(testing "casting with dash in name"
(let [params {"content" "some content"}]
(is (-> params (changeset/cast :with-dash) seq some?))))
(testing "casting with underscore in name"
(let [params {"content" "some content"}]
(is (-> params (changeset/cast :with_underscore) seq some?)))))
(deftest test-diffing-changeset
(testing "updating email"
(is (-> existing-user
(changeset/create {:user/email "foo@bar.baz"})
:changeset/errors
nil?))
(is (= "foo@bar.baz"
(-> existing-user
(changeset/create {:user/email "foo@bar.baz"})
:changeset/result
:user/email)))
(is (= "123456"
(-> existing-user
(changeset/create {:user/email "foo@bar.baz"})
:changeset/result
:user/password)))))
(deftest test-auto-property
(testing "auto should not be in result"
(is (= (java.util.Date. 1495636054438)
(-> existing-user
(changeset/create {:user/created-at (java.util.Date. 123)})
:changeset/result
:user/created-at)))))
(deftest test-virtual-property
(testing "virtual should not be in result"
(is (-> existing-user
(changeset/create {:user/password-confirmation "987654"})
:changeset/result
:user/password-confirmation
nil?))
(is (-> {:user/email "test@user.com"
:user/password "987654"
:user/password-confirmation "987654"}
(changeset/create)
:changeset/result
:user/password-confirmation
nil?))))
(deftest test-validators
(testing "password confirmation validator"
(let [user {:user/email "user@test.com"
:user/password "123456"
:user/password-confirmation "123456"}]
(is (-> user
(changeset/create [:user/password-match?])
:changeset/errors
nil?))
(is (-> (assoc user :user/password-confirmation "123456+7")
(changeset/create [:user/password-match?])
:changeset/errors
:user/password-confirmation
some?))))
(testing "password confirmation validator with invalid fields"
(let [user {:user/email "user@test.com"
:user/password "1234"
:user/password-confirmation "1234"}]
(is (-> user
(changeset/create [:user/password-match?])
:changeset/errors
some?)))))
(deftest assoc-changeset
(testing "add a new email to existing user"
(let [new-email "bar@baz.bar"
changeset
(-> {:user/email "foo"
:user/password "123456"}
(changeset/assoc
:user/email new-email))]
(is (nil? (:changeset/errors changeset)))
(is (= new-email (-> changeset :changeset/params :user/email)))
(is (= new-email (-> changeset :changeset/result :user/email)))))
(testing "add a new email to changeset"
(let [new-email "bar@baz.bar"
changeset (-> {:user/email "foo" :user/password "123456"}
(changeset/create)
(changeset/assoc :user/email new-email))]
(is (nil? (:changeset/errors changeset)))
(is (= new-email (-> changeset :changeset/params :user/email)))
(is (= new-email (-> changeset :changeset/result :user/email))))))
(deftest update-changeset
(let [comment
{:comment/id (java.util.UUID/randomUUID)
:comment/content ""
:comment/user-id (java.util.UUID/randomUUID)
:comment/post-id (java.util.UUID/randomUUID)
:comment/rating 999}]
(testing "incrementing rating on comment"
(let [changeset (changeset/update comment :comment/rating inc)]
(is (nil? (:changeset/errors changeset)))
(is (= 1000 (-> changeset :changeset/params :comment/rating)))
(is (= 1000 (-> changeset :changeset/result :comment/rating)))))
(testing "incrementing rating on comment"
(let [changeset (changeset/update (changeset/create comment) :comment/rating inc)]
(is (nil? (:changeset/errors changeset)))
(is (= 1000 (-> changeset :changeset/params :comment/rating)))
(is (= 1000 (-> changeset :changeset/result :comment/rating)))))))
(deftest merge-changeset
(let [comment
{:comment/id (java.util.UUID/randomUUID)
:comment/content ""
:comment/user-id (java.util.UUID/randomUUID)
:comment/post-id (java.util.UUID/randomUUID)
:comment/rating 999}]
(testing "merge rating on comment"
(let [changeset (changeset/merge comment {:comment/rating 1000})]
(is (nil? (:changeset/errors changeset)))
(is (= 1000 (-> changeset :changeset/params :comment/rating)))
(is (= 1000 (-> changeset :changeset/result :comment/rating)))))
(testing "merge rating on comment"
(let [changeset (changeset/merge (changeset/create comment) {:comment/rating 1000})]
(is (nil? (:changeset/errors changeset)))
(is (= 1000 (-> changeset :changeset/params :comment/rating)))
(is (= 1000 (-> changeset :changeset/result :comment/rating)))))))
| 47272 | (ns gungnir.changeset-test
(:require
[clojure.test :refer :all]
[gungnir.changeset :as changeset]
[gungnir.test.util :as util]))
(use-fixtures :once util/once-fixture)
(use-fixtures :each util/each-fixture)
(def existing-user
{:user/id "e52c518c-6d3e-4e75-87f1-ff08bdc933be"
:user/email "<EMAIL>"
:user/password "<PASSWORD>"
:user/created-at (java.util.Date. 1495636054438)
:user/updated-at (java.util.Date. 1495636054438)})
(defn- cast+errors [params model]
(-> params (changeset/cast model) changeset/create :changeset/errors))
(defn- changeset+errors [params]
(-> params changeset/create :changeset/errors))
(deftest valid-user-tests
(testing "valid changesets"
(let [user {:user/email "<EMAIL>" :user/password "<PASSWORD>"}]
(is (-> user changeset+errors nil?)))))
(deftest invalid-valid-user-tests
(testing "invalid email"
(let [user {:user/email "@<EMAIL>" :user/password "<PASSWORD>"}]
(is (-> user changeset+errors :user/email some?))))
(testing "invalid password"
(let [user {:user/email "<EMAIL>" :user/password "..."}]
(is (-> user changeset+errors :user/password some?))))
(testing "invalid email and password"
(let [user {:user/email "test@user" :user/password "..."}]
(is (= #{:user/email :user/password} (-> user changeset+errors keys set))))))
(deftest casting-to-changeset
(testing "casting strings to changeset"
(let [params {"email" "<EMAIL>" "password" "<PASSWORD>3456"}]
(is (-> params (cast+errors :user) nil?)))
(let [params {"email" "test@<EMAIL>" "password" "<PASSWORD>"}]
(is (-> params (cast+errors :user) :user/email some?)))
(let [params {"email" "<EMAIL>" "password" "..."}]
(is (-> params (cast+errors :user) :user/password some?))))
(testing "casting strings and keywords with formatting to changeset"
(let [params {"email" "<EMAIL>" :password "<PASSWORD>"}]
(is (-> params (cast+errors :user) nil?)))
(let [params {"email" "test@user" "password" "<PASSWORD>"}]
(is (-> params (cast+errors :user) :user/email some?)))
(let [params {"email" "<EMAIL>" "password" "..."}]
(is (-> params (cast+errors :user) :user/password some?))))
(testing "casting with dash in name"
(let [params {"content" "some content"}]
(is (-> params (changeset/cast :with-dash) seq some?))))
(testing "casting with underscore in name"
(let [params {"content" "some content"}]
(is (-> params (changeset/cast :with_underscore) seq some?)))))
(deftest test-diffing-changeset
(testing "updating email"
(is (-> existing-user
(changeset/create {:user/email "<EMAIL>"})
:changeset/errors
nil?))
(is (= "<EMAIL>"
(-> existing-user
(changeset/create {:user/email "<EMAIL>"})
:changeset/result
:user/email)))
(is (= "123456"
(-> existing-user
(changeset/create {:user/email "<EMAIL>"})
:changeset/result
:user/password)))))
(deftest test-auto-property
(testing "auto should not be in result"
(is (= (java.util.Date. 1495636054438)
(-> existing-user
(changeset/create {:user/created-at (java.util.Date. 123)})
:changeset/result
:user/created-at)))))
(deftest test-virtual-property
(testing "virtual should not be in result"
(is (-> existing-user
(changeset/create {:user/password-confirmation "<PASSWORD>"})
:changeset/result
:user/password-confirmation
nil?))
(is (-> {:user/email "<EMAIL>"
:user/password "<PASSWORD>"
:user/password-confirmation "<PASSWORD>"}
(changeset/create)
:changeset/result
:user/password-confirmation
nil?))))
(deftest test-validators
(testing "password confirmation validator"
(let [user {:user/email "<EMAIL>"
:user/password "<PASSWORD>"
:user/password-confirmation "<PASSWORD>"}]
(is (-> user
(changeset/create [:user/password-match?])
:changeset/errors
nil?))
(is (-> (assoc user :user/password-confirmation "<PASSWORD>")
(changeset/create [:user/password-match?])
:changeset/errors
:user/password-confirmation
some?))))
(testing "password confirmation validator with invalid fields"
(let [user {:user/email "<EMAIL>"
:user/password "<PASSWORD>"
:user/password-confirmation "<PASSWORD>"}]
(is (-> user
(changeset/create [:user/password-match?])
:changeset/errors
some?)))))
(deftest assoc-changeset
(testing "add a new email to existing user"
(let [new-email "<EMAIL>"
changeset
(-> {:user/email "foo"
:user/password "<PASSWORD>"}
(changeset/assoc
:user/email new-email))]
(is (nil? (:changeset/errors changeset)))
(is (= new-email (-> changeset :changeset/params :user/email)))
(is (= new-email (-> changeset :changeset/result :user/email)))))
(testing "add a new email to changeset"
(let [new-email "<EMAIL>"
changeset (-> {:user/email "foo" :user/password "<PASSWORD>"}
(changeset/create)
(changeset/assoc :user/email new-email))]
(is (nil? (:changeset/errors changeset)))
(is (= new-email (-> changeset :changeset/params :user/email)))
(is (= new-email (-> changeset :changeset/result :user/email))))))
(deftest update-changeset
(let [comment
{:comment/id (java.util.UUID/randomUUID)
:comment/content ""
:comment/user-id (java.util.UUID/randomUUID)
:comment/post-id (java.util.UUID/randomUUID)
:comment/rating 999}]
(testing "incrementing rating on comment"
(let [changeset (changeset/update comment :comment/rating inc)]
(is (nil? (:changeset/errors changeset)))
(is (= 1000 (-> changeset :changeset/params :comment/rating)))
(is (= 1000 (-> changeset :changeset/result :comment/rating)))))
(testing "incrementing rating on comment"
(let [changeset (changeset/update (changeset/create comment) :comment/rating inc)]
(is (nil? (:changeset/errors changeset)))
(is (= 1000 (-> changeset :changeset/params :comment/rating)))
(is (= 1000 (-> changeset :changeset/result :comment/rating)))))))
(deftest merge-changeset
(let [comment
{:comment/id (java.util.UUID/randomUUID)
:comment/content ""
:comment/user-id (java.util.UUID/randomUUID)
:comment/post-id (java.util.UUID/randomUUID)
:comment/rating 999}]
(testing "merge rating on comment"
(let [changeset (changeset/merge comment {:comment/rating 1000})]
(is (nil? (:changeset/errors changeset)))
(is (= 1000 (-> changeset :changeset/params :comment/rating)))
(is (= 1000 (-> changeset :changeset/result :comment/rating)))))
(testing "merge rating on comment"
(let [changeset (changeset/merge (changeset/create comment) {:comment/rating 1000})]
(is (nil? (:changeset/errors changeset)))
(is (= 1000 (-> changeset :changeset/params :comment/rating)))
(is (= 1000 (-> changeset :changeset/result :comment/rating)))))))
| true | (ns gungnir.changeset-test
(:require
[clojure.test :refer :all]
[gungnir.changeset :as changeset]
[gungnir.test.util :as util]))
(use-fixtures :once util/once-fixture)
(use-fixtures :each util/each-fixture)
(def existing-user
{:user/id "e52c518c-6d3e-4e75-87f1-ff08bdc933be"
:user/email "PI:EMAIL:<EMAIL>END_PI"
:user/password "PI:PASSWORD:<PASSWORD>END_PI"
:user/created-at (java.util.Date. 1495636054438)
:user/updated-at (java.util.Date. 1495636054438)})
(defn- cast+errors [params model]
(-> params (changeset/cast model) changeset/create :changeset/errors))
(defn- changeset+errors [params]
(-> params changeset/create :changeset/errors))
(deftest valid-user-tests
(testing "valid changesets"
(let [user {:user/email "PI:EMAIL:<EMAIL>END_PI" :user/password "PI:PASSWORD:<PASSWORD>END_PI"}]
(is (-> user changeset+errors nil?)))))
(deftest invalid-valid-user-tests
(testing "invalid email"
(let [user {:user/email "@PI:EMAIL:<EMAIL>END_PI" :user/password "PI:PASSWORD:<PASSWORD>END_PI"}]
(is (-> user changeset+errors :user/email some?))))
(testing "invalid password"
(let [user {:user/email "PI:EMAIL:<EMAIL>END_PI" :user/password "..."}]
(is (-> user changeset+errors :user/password some?))))
(testing "invalid email and password"
(let [user {:user/email "test@user" :user/password "..."}]
(is (= #{:user/email :user/password} (-> user changeset+errors keys set))))))
(deftest casting-to-changeset
(testing "casting strings to changeset"
(let [params {"email" "PI:EMAIL:<EMAIL>END_PI" "password" "PI:PASSWORD:<PASSWORD>END_PI3456"}]
(is (-> params (cast+errors :user) nil?)))
(let [params {"email" "test@PI:EMAIL:<EMAIL>END_PI" "password" "PI:PASSWORD:<PASSWORD>END_PI"}]
(is (-> params (cast+errors :user) :user/email some?)))
(let [params {"email" "PI:EMAIL:<EMAIL>END_PI" "password" "..."}]
(is (-> params (cast+errors :user) :user/password some?))))
(testing "casting strings and keywords with formatting to changeset"
(let [params {"email" "PI:EMAIL:<EMAIL>END_PI" :password "PI:PASSWORD:<PASSWORD>END_PI"}]
(is (-> params (cast+errors :user) nil?)))
(let [params {"email" "test@user" "password" "PI:PASSWORD:<PASSWORD>END_PI"}]
(is (-> params (cast+errors :user) :user/email some?)))
(let [params {"email" "PI:EMAIL:<EMAIL>END_PI" "password" "..."}]
(is (-> params (cast+errors :user) :user/password some?))))
(testing "casting with dash in name"
(let [params {"content" "some content"}]
(is (-> params (changeset/cast :with-dash) seq some?))))
(testing "casting with underscore in name"
(let [params {"content" "some content"}]
(is (-> params (changeset/cast :with_underscore) seq some?)))))
(deftest test-diffing-changeset
(testing "updating email"
(is (-> existing-user
(changeset/create {:user/email "PI:EMAIL:<EMAIL>END_PI"})
:changeset/errors
nil?))
(is (= "PI:EMAIL:<EMAIL>END_PI"
(-> existing-user
(changeset/create {:user/email "PI:EMAIL:<EMAIL>END_PI"})
:changeset/result
:user/email)))
(is (= "123456"
(-> existing-user
(changeset/create {:user/email "PI:EMAIL:<EMAIL>END_PI"})
:changeset/result
:user/password)))))
(deftest test-auto-property
(testing "auto should not be in result"
(is (= (java.util.Date. 1495636054438)
(-> existing-user
(changeset/create {:user/created-at (java.util.Date. 123)})
:changeset/result
:user/created-at)))))
(deftest test-virtual-property
(testing "virtual should not be in result"
(is (-> existing-user
(changeset/create {:user/password-confirmation "PI:PASSWORD:<PASSWORD>END_PI"})
:changeset/result
:user/password-confirmation
nil?))
(is (-> {:user/email "PI:EMAIL:<EMAIL>END_PI"
:user/password "PI:PASSWORD:<PASSWORD>END_PI"
:user/password-confirmation "PI:PASSWORD:<PASSWORD>END_PI"}
(changeset/create)
:changeset/result
:user/password-confirmation
nil?))))
(deftest test-validators
(testing "password confirmation validator"
(let [user {:user/email "PI:EMAIL:<EMAIL>END_PI"
:user/password "PI:PASSWORD:<PASSWORD>END_PI"
:user/password-confirmation "PI:PASSWORD:<PASSWORD>END_PI"}]
(is (-> user
(changeset/create [:user/password-match?])
:changeset/errors
nil?))
(is (-> (assoc user :user/password-confirmation "PI:PASSWORD:<PASSWORD>END_PI")
(changeset/create [:user/password-match?])
:changeset/errors
:user/password-confirmation
some?))))
(testing "password confirmation validator with invalid fields"
(let [user {:user/email "PI:EMAIL:<EMAIL>END_PI"
:user/password "PI:PASSWORD:<PASSWORD>END_PI"
:user/password-confirmation "PI:PASSWORD:<PASSWORD>END_PI"}]
(is (-> user
(changeset/create [:user/password-match?])
:changeset/errors
some?)))))
(deftest assoc-changeset
(testing "add a new email to existing user"
(let [new-email "PI:EMAIL:<EMAIL>END_PI"
changeset
(-> {:user/email "foo"
:user/password "PI:PASSWORD:<PASSWORD>END_PI"}
(changeset/assoc
:user/email new-email))]
(is (nil? (:changeset/errors changeset)))
(is (= new-email (-> changeset :changeset/params :user/email)))
(is (= new-email (-> changeset :changeset/result :user/email)))))
(testing "add a new email to changeset"
(let [new-email "PI:EMAIL:<EMAIL>END_PI"
changeset (-> {:user/email "foo" :user/password "PI:PASSWORD:<PASSWORD>END_PI"}
(changeset/create)
(changeset/assoc :user/email new-email))]
(is (nil? (:changeset/errors changeset)))
(is (= new-email (-> changeset :changeset/params :user/email)))
(is (= new-email (-> changeset :changeset/result :user/email))))))
(deftest update-changeset
(let [comment
{:comment/id (java.util.UUID/randomUUID)
:comment/content ""
:comment/user-id (java.util.UUID/randomUUID)
:comment/post-id (java.util.UUID/randomUUID)
:comment/rating 999}]
(testing "incrementing rating on comment"
(let [changeset (changeset/update comment :comment/rating inc)]
(is (nil? (:changeset/errors changeset)))
(is (= 1000 (-> changeset :changeset/params :comment/rating)))
(is (= 1000 (-> changeset :changeset/result :comment/rating)))))
(testing "incrementing rating on comment"
(let [changeset (changeset/update (changeset/create comment) :comment/rating inc)]
(is (nil? (:changeset/errors changeset)))
(is (= 1000 (-> changeset :changeset/params :comment/rating)))
(is (= 1000 (-> changeset :changeset/result :comment/rating)))))))
(deftest merge-changeset
(let [comment
{:comment/id (java.util.UUID/randomUUID)
:comment/content ""
:comment/user-id (java.util.UUID/randomUUID)
:comment/post-id (java.util.UUID/randomUUID)
:comment/rating 999}]
(testing "merge rating on comment"
(let [changeset (changeset/merge comment {:comment/rating 1000})]
(is (nil? (:changeset/errors changeset)))
(is (= 1000 (-> changeset :changeset/params :comment/rating)))
(is (= 1000 (-> changeset :changeset/result :comment/rating)))))
(testing "merge rating on comment"
(let [changeset (changeset/merge (changeset/create comment) {:comment/rating 1000})]
(is (nil? (:changeset/errors changeset)))
(is (= 1000 (-> changeset :changeset/params :comment/rating)))
(is (= 1000 (-> changeset :changeset/result :comment/rating)))))))
|
[
{
"context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"wahpenayo at gmail dot com\" \n :date \"2018-04-16\"\n ",
"end": 60,
"score": 0.6935787200927734,
"start": 54,
"tag": "USERNAME",
"value": "wahpen"
},
{
"context": "hecked-math* :warn-on-boxed)\n(ns ^{:author \"wahpenayo at gmail dot com\" \n :date \"2018-04-16\"\n ",
"end": 63,
"score": 0.4386337995529175,
"start": 60,
"tag": "EMAIL",
"value": "ayo"
}
] | src/main/clojure/zana/stats/statistics.clj | wahpenayo/zana | 2 | (set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "wahpenayo at gmail dot com"
:date "2018-04-16"
:doc "Stats that don't have an obvious home." }
zana.stats.statistics
(:refer-clojure :exclude [min max])
(:require [zana.geometry.r1 :as r1]
[zana.geometry.z1 :as z1]
[zana.collections.generic :as g]
[zana.stats.accumulators :as accumulators])
(:import [java.util List Map]
[clojure.lang IFn IFn$OD IFn$OL]
[org.apache.commons.math3.stat.descriptive
DescriptiveStatistics]
[zana.java.functions IFnODWithMeta]
[zana.java.math Statistics]
[zana.java.prob ApproximatelyEqual]))
;;----------------------------------------------------------------
;; TODO: handle relative and absolute equality epsilons
;; TODO: move somewhere else?
(defn float-approximately==
([^double ulps ^double x ^double y]
(let [x (float x)
y (float y)
delta (* (float ulps)
(Math/ulp
(float (+ 1.0 (Math/abs x) (Math/abs y)))))]
(<= (Math/abs (float (- x y))) delta)))
([^double x ^double y]
(float-approximately== 1.0 x y)))
;;----------------------------------------------------------------
;; TODO: move somewhere else?
(defn approximately<=
([^double ulps ^double x ^double y]
(let [delta (* ulps
(Math/ulp (+ 1.0 (Math/abs x) (Math/abs y))))]
(<= (- x y) delta)))
([^double x ^double y]
(approximately<= 1.0 x y)))
(defn approximately==
([^double ulps ^double x ^double y]
(let [delta (* ulps
(Math/ulp (+ 1.0 (Math/abs x) (Math/abs y))))]
(<= (Math/abs (- x y)) delta)))
([^double x ^double y] (approximately== 1.0 x y)))
(defn approximately>=
([^double ulps ^double x ^double y]
(let [delta (* ulps
(Math/ulp (+ 1.0 (Math/abs x) (Math/abs y))))]
(<= (- y x) delta)))
([^double x ^double y]
(approximately<= 1.0 x y)))
(defn approximatelyEqual
([^ApproximatelyEqual x ^ApproximatelyEqual y]
(.approximatelyEqual x y))
([^ApproximatelyEqual x ^ApproximatelyEqual y & more]
(and (approximatelyEqual x y)
(apply approximatelyEqual y (first more) (rest more)))))
(defn doubles-approximately==
([^double ulps ^doubles s0 ^doubles s1]
(and (== (alength s0) (alength s1))
(let [n (int (alength s0))]
(loop [i (int 0)]
(if (< i n)
(let [z0 (aget s0 i)
z1 (aget s1 i)]
(if-not (approximately== ulps z0 z1)
false
(recur (inc i))))
true)))))
([^doubles s0 ^doubles s1]
(doubles-approximately== 1.0 s0 s1)))
(defn lists-approximately==
([^double ulps ^List s0 ^List s1]
(and (== (.size s0) (.size s1))
(let [i0 (.iterator s0)
i1 (.iterator s1)]
(loop []
(if (.hasNext i0)
(let [z0 (double (.next i0))
z1 (double (.next i1))]
(if-not (approximately== ulps z0 z1)
false
(recur)))
true)))))
([^List s0 ^List s1]
(lists-approximately== 1.0 s0 s1)))
(defn maps-approximately==
([^double ulps ^Map m0 ^Map m1]
(and (= (.keySet m0) (.keySet m1))
(let [it (.iterator (.keySet m0))]
(loop []
(if (.hasNext it)
(let [k (.next it)
z0 (double (.get m0 k))
z1 (double (.get m1 k))]
(if-not (approximately== ulps z0 z1)
false
(recur)))
true)))))
([^Map m0 ^Map m1]
(maps-approximately== 1.0 m0 m1)))
;;----------------------------------------------------------------
;; TODO: move to function namespace
(defn numerical?
"Does <code>f</code> return primitive <code>double</code> or <code>long</code>
values? <br>
Does <code>f</code> return a number for every element of <code>data</code>?"
([^IFn f]
(or (instance? IFn$OD f)
(instance? IFn$OL f)))
([^IFn f ^Iterable data]
(try
(or (numerical? f)
(g/every? #(number? (f %)) data))
(catch Throwable t
(throw
(RuntimeException.
(print-str "numerical?" f (class data) (g/count data))
t))))))
;;----------------------------------------------------------------
;; TODO: move to function namespace
(defn constantly-0d
"An instance of <code>IFn$OD</code> that returns a primitve
<code>double</code> 0.0, regardless of input."
(^double [] 0.0)
(^double [arg] 0.0))
(defn constantly-1d
"An instance of <code>IFn$OD</code> that returns a primitve
<code>double</code> 1.0, regardless of input."
(^double [] 1.0)
(^double [arg] 1.0))
;;----------------------------------------------------------------
(defn- singular-longs? [^IFn$OL z ^Iterable data]
(let [it (g/iterator data)]
(if (.hasNext it)
(let [z0 (.invokePrim z (.next it))]
(loop []
(if (.hasNext it)
(let [z1 (.invokePrim z (.next it))]
(if (== z0 z1)
(recur)
false))
true)))
true)))
(defn- singular-doubles? [^IFn$OD z ^Iterable data]
(let [it (g/iterator data)
delta (Math/ulp (double 1.0))]
(if-not (.hasNext it)
true
;; get the 1st non-NaN, if any
(let [z0 (double
(loop []
(if (.hasNext it)
(let [di (.next it)
zi (.invokePrim z di)]
(if (Double/isNaN zi)
(recur)
zi))
Double/NaN)))]
;; if all NaN, then .hasNext is false
;; TODO: should this be a relative difference test?
(loop []
(if (.hasNext it)
(let [d1 (.next it)
z1 (.invokePrim z d1)]
(if (> (Math/abs (- z0 z1)) delta)
false
;; else z1 is NaN and/or different from z0
(recur)))
true))))))
(defn- singular-objects? [^IFn z ^Iterable data]
(if (nil? data)
true
(let [it (.iterator data)]
(if-not (.hasNext it)
true
;; get the 1st non-nil, if any
(let [z0 (loop []
(when (.hasNext it)
(let [zi (z (.next it))]
(if (nil? zi) ;; false is not nil == missing
(recur)
zi))))]
;; if all nil, then no more
(loop []
(if (.hasNext it)
(let [z1 (z (.next it))]
(if (or (nil? z1) (= z0 z1))
(recur)
false))
true)))))))
;;----------------------------------------------------------------
(defn singular?
"Is there more than one distinct value in <code>a</code> or in the values of
<code>z</code> mapped over <code>data</code>."
([^doubles a] (zana.java.arrays.Arrays/isSingular a))
([^IFn z ^Iterable data]
(cond (instance? IFn$OD z) (singular-doubles? z data)
(instance? IFn$OL z) (singular-longs? z data)
:else (singular-objects? z data))))
;;----------------------------------------------------------------
;; a mess of functions computing bounds of various kinds.
;; TODO: rationalize this, maybe move some to a geometry package.
;; TODO: minmax, bounds, bounding-box, range are all variations on the same thing
;;----------------------------------------------------------------
;; TODO: handle any Comparable, accept comparator function
;; TODO: compare speed to Java implementation.
;; TODO: move to zana/tu.geometry?
(defn- bounds-slow
(^zana.java.geometry.r1.Interval [^IFn f
^Iterable data
^double min0
^double max0]
(assert (not (g/empty? data)))
(let [it (.iterator data)]
(loop [xmin min0
xmax max0]
(if (.hasNext it)
(let [x (double (f (.next it)))]
(if (Double/isNaN x)
(recur xmin xmax)
(if (>= x xmin)
(if (<= x xmax)
(recur xmin xmax)
(recur xmin x))
(if (<= x xmax)
(recur x xmax)
(recur x x)))))
(r1/interval xmin (Math/nextUp xmax)))))))
;;----------------------------------------------------------------
(defn- bounds-fast
(^zana.java.geometry.r1.Interval [^IFn$OD f
^Iterable data
^double min0
^double max0]
(assert (not (g/empty? data)))
(let [^IFn$OD f (if (instance? IFnODWithMeta f)
(.functionOD ^IFnODWithMeta f)
f)
it (.iterator data)]
(loop [xmin min0
xmax max0]
(if (.hasNext it)
(let [x (.invokePrim f (.next it))]
(if (Double/isNaN x)
(recur xmin xmax)
(if (>= x xmin)
(if (<= x xmax)
(recur xmin xmax)
(recur xmin x))
(if (<= x xmax)
(recur x xmax)
(recur x x)))))
(r1/interval xmin (Math/nextUp xmax)))))))
;;----------------------------------------------------------------
(defn bounds
(^zana.java.geometry.r1.Interval [^Iterable data
^double min0
^double max0]
(when-not (g/empty? data)
(let [it (.iterator data)]
(loop [xmin min0
xmax max0]
(if (.hasNext it)
(let [x (double (.next it))]
(if (Double/isNaN x)
(recur xmin xmax)
(if (>= x xmin)
(if (<= x xmax)
(recur xmin xmax)
(recur xmin x))
(if (<= x xmax)
(recur x xmax)
(recur x x)))))
(r1/interval xmin (Math/nextUp xmax)))))))
(^zana.java.geometry.r1.Interval [^Iterable data]
(bounds data Double/POSITIVE_INFINITY Double/NEGATIVE_INFINITY))
(^zana.java.geometry.r1.Interval [^IFn f
^Iterable data
^double min0
^double max0]
(when-not (g/empty? data)
(let [it (.iterator data)]
(if (instance? IFn$OD f)
(bounds-fast f data min0 max0)
(bounds-slow f data min0 max0)))))
(^zana.java.geometry.r1.Interval [^IFn f
^Iterable data]
(bounds f data Double/POSITIVE_INFINITY Double/NEGATIVE_INFINITY)))
;;----------------------------------------------------------------
(defn- bounding-box-slow
(^java.awt.geom.Rectangle2D$Double [^IFn xf
^IFn yf
^Iterable data]
(let [it (.iterator data)]
(loop [xmin Double/POSITIVE_INFINITY
xmax Double/NEGATIVE_INFINITY
ymin Double/POSITIVE_INFINITY
ymax Double/NEGATIVE_INFINITY]
(if (.hasNext it)
(let [i (.next it)
_ (assert i "no datum")
x (xf i)
_ (assert x (str "x:" xf " " i))
y (yf i)
_ (assert y (str "y:" yf " " i))
x (double x)
y (double y)
;; this will ignore NaNs
xmin (if (< x xmin) x xmin)
xmax (if (> x xmax) x xmax)
ymin (if (< y ymin) y ymin)
ymax (if (> y ymax) y ymax)]
(recur xmin xmax ymin ymax))
(java.awt.geom.Rectangle2D$Double.
xmin ymin (- xmax xmin) (- ymax ymin)))))))
;;----------------------------------------------------------------
(defn- bounding-box-fast
(^java.awt.geom.Rectangle2D$Double [^IFn$OD xf
^IFn$OD yf
^Iterable data]
(let [^IFn$OD xf (if (instance? IFnODWithMeta xf)
(.functionOD ^IFnODWithMeta xf)
xf)
^IFn$OD yf (if (instance? IFnODWithMeta yf)
(.functionOD ^IFnODWithMeta yf)
yf)
it (.iterator data)]
(loop [xmin Double/POSITIVE_INFINITY
xmax Double/NEGATIVE_INFINITY
ymin Double/POSITIVE_INFINITY
ymax Double/NEGATIVE_INFINITY]
(if (.hasNext it)
(let [i (.next it)
x (.invokePrim xf i)
y (.invokePrim yf i)
;; this will ignore NaNs
xmin (if (< x xmin) x xmin)
xmax (if (> x xmax) x xmax)
ymin (if (< y ymin) y ymin)
ymax (if (> y ymax) y ymax)]
(recur xmin xmax ymin ymax))
(java.awt.geom.Rectangle2D$Double.
xmin ymin (- xmax xmin) (- ymax ymin)))))))
;;----------------------------------------------------------------
(defn bounding-box
(^java.awt.geom.Rectangle2D$Double [^IFn xf
^IFn yf
^Iterable data]
(if (and (instance? IFn$OD xf)
(instance? IFn$OD yf))
(bounding-box-fast xf yf data)
;;(Statistics/bounds xf yf data)
(bounding-box-slow xf yf data))))
;;----------------------------------------------------------------
(defn symmetric-bounds
^java.awt.geom.Rectangle2D$Double [^IFn$OD xf
^IFn$OD yf
^Iterable data]
(Statistics/symmetricBounds xf yf data))
;;----------------------------------------------------------------
(defn- minmax-long [^IFn$OL z ^Iterable data]
(assert (not (g/empty? data)))
(let [i (g/iterator data)
zz (.invokePrim z (.next i))]
(loop [z0 zz
z1 zz]
(if (.hasNext i)
(let [zi (.invokePrim z (.next i))]
(cond (< zi z0) (recur zi z1)
(> zi z1) (recur z0 zi)
:else (recur z0 z1)))
[z0 z1]))))
(defn- minmax-double [^IFn$OD z ^Iterable data]
(assert (not (g/empty? data)))
(let [i (g/iterator data)
zz (.invokePrim z (.next i))]
(loop [z0 zz
z1 zz]
(if (.hasNext i)
(let [zi (.invokePrim z (.next i))]
(cond (< zi z0) (recur zi z1)
(> zi z1) (recur z0 zi)
:else (recur z0 z1)))
[z0 z1]))))
(defn- minmax-comparable [^IFn z ^Iterable data]
(assert (not (g/empty? data)))
(let [i (g/iterator data)
^Comparable zz (z (.next i))]
(loop [^Comparable z0 zz
^Comparable z1 zz]
(if (.hasNext i)
(let [^Comparable zi (z (.next i))]
(cond (< (.compareTo zi z0) (int 0)) (recur zi z1)
(> (.compareTo zi z1) (int 0)) (recur z0 zi)
:else (recur z0 z1)))
[z0 z1]))))
(defn minmax
"Return a 2-element vector containing the minimum and maximum values
of <code>z</code> over <code>data</code>. The values of <code>z</code>
need to be <code>Comparable</code>, or primitive numbers."
([z data]
(cond (instance? IFn$OL z) (minmax-long z data)
(instance? IFn$OD z) (minmax-double z data)
(instance? IFn z) (minmax-comparable z data)
:else (throw
(IllegalArgumentException.
(print-str "can't find the minmax values of " (class z)))))))
;;----------------------------------------------------------------
(defn fast-min ^double [^IFn$OD f ^Iterable data]
(let [it (.iterator data)]
(loop [xmin Double/POSITIVE_INFINITY]
(if (.hasNext it)
(let [x (.invokePrim f (.next it))]
(if (Double/isNaN x)
(recur xmin)
(if (>= x xmin)
(recur xmin)
(recur x))))
xmin))))
;;----------------------------------------------------------------
(defn min
(^double [^IFn f ^Iterable data]
(if (instance? IFn$OD f)
(fast-min f data)
(let [it (.iterator data)]
(loop [xmin Double/POSITIVE_INFINITY]
(if (.hasNext it)
(let [x (double (f (.next it)))]
(if (Double/isNaN x)
(recur xmin)
(if (>= x xmin)
(recur xmin)
(recur x))))
xmin)))))
(^double [^Iterable data]
(let [it (.iterator data)]
(loop [xmin Double/POSITIVE_INFINITY]
(if (.hasNext it)
(let [x (double (.next it))]
(if (Double/isNaN x)
(recur xmin)
(if (>= x xmin)
(recur xmin)
(recur x))))
xmin)))))
;;----------------------------------------------------------------
;; return Double/NEGATIVE_INFINITY for empty datasets
(defn fast-max ^double [^IFn$OD f ^Iterable data]
(let [it (.iterator data)]
(loop [xmax Double/NEGATIVE_INFINITY]
(if (.hasNext it)
(let [x (.invokePrim f (.next it))]
(if (Double/isNaN x)
(recur xmax)
(if (<= x xmax)
(recur xmax)
(recur x))))
xmax))))
;;----------------------------------------------------------------
;; return Double/NEGATIVE_INFINITY for empty datasets
(defn max
(^double [^IFn f ^Iterable data]
(if (instance? IFn$OD f)
(fast-max f data)
(let [it (.iterator data)]
(loop [xmax Double/NEGATIVE_INFINITY]
(if (.hasNext it)
(let [x (double (f (.next it)))]
(if (Double/isNaN x)
(recur xmax)
(if (<= x xmax)
(recur xmax)
(recur x))))
xmax)))))
(^double [^Iterable data]
(let [it (.iterator data)]
(loop [xmax Double/NEGATIVE_INFINITY]
(if (.hasNext it)
(let [x (double (.next it))]
(if (Double/isNaN x)
(recur xmax)
(if (<= x xmax)
(recur xmax)
(recur x))))
xmax)))))
;;----------------------------------------------------------------
(defn quantiles
"Return a vector of the quantiles of the doubles in
<code>zs</code>, or the doubles resulting from mapping
<code>z</code> over <code>data</code>.
Return quantiles corresponding to the <code>ps</code>, which
must be numbers between 0.0 and 1.0 (both ends inclusive)."
([zs ps]
(let [^doubles zs (into-array Double/TYPE zs)
ds (DescriptiveStatistics. zs)]
(mapv (fn ^double [^double p]
;; TODO: better 'equality' test?
(cond (== 0.0 p) (.getMin ds)
(== 1.0 p) (.getMax ds)
:else (.getPercentile ds (* 100.0 p))))
ps)))
([z data ps] (quantiles (g/map-to-doubles z data) ps)))
;;----------------------------------------------------------------
;; TODO: Kahan summation; use accumulators?
(defn sum
"Compute the sum of the elements of an array, or of the
values of a function mapped over a data set."
(^double [^doubles zs]
(let [n (alength zs)]
(loop [sum 0.0
i 0]
(if (< i n)
(recur (+ sum (aget zs i)) (inc i))
sum))))
(^double [^IFn z ^Iterable data]
(cond
(instance? IFn$OD z)
(let [^IFn$OD z z
it (g/iterator data)]
(loop [sum (double 0.0)]
(if (.hasNext it)
(recur (+ sum (.invokePrim z (.next it))))
sum)))
(instance? IFn$OL z)
(let [^IFn$OL z z
it (g/iterator data)]
(loop [sum (long 0)]
(if (.hasNext it)
(recur (+ sum (.invokePrim z (.next it))))
(double sum))))
:else
(let [it (g/iterator data)]
(loop [sum (double 0.0)]
(if (.hasNext it)
(recur (+ sum (double (z (.next it)))))
(double sum)))))))
;;----------------------------------------------------------------
(defn mean
"Compute the mean of the elements of an array, or of the
values of a function mapped over a data set."
(^double [^doubles zs] (/ (sum zs) (alength zs)))
(^double [^IFn z ^Iterable data]
(/ (sum z data) (g/count data))))
;;----------------------------------------------------------------
;; TODO: Kahan summation
(defn l1-norm
"Compute the sum of absolute value of the elements of an array,
or of the values of a function mapped over a data set."
(^double [^doubles zs]
(let [n (alength zs)]
(loop [sum 0.0
i 0]
(if (< i n)
(recur (+ sum (Math/abs (aget zs i))) (inc i))
sum))))
(^double [^IFn$OD z ^Iterable data]
(let [it (g/iterator data)]
(loop [sum 0.0]
(if (.hasNext it)
(recur (+ sum (Math/abs (.invokePrim z (.next it)))))
sum)))))
;;----------------------------------------------------------------
;; TODO: Kahan summation
(defn l1-distance
"Compute the sum of absolute differences between 2 arrays, or
between the values of 2 functions mapped over a data set."
(^double [^doubles z0 ^doubles z1]
(let [n (alength z0)]
(assert (== n (alength z1)))
(loop [sum 0.0
i 0]
(if (< i n)
(recur (+ sum (Math/abs (- (aget z0 i) (aget z1 i))))
(inc i))
sum))))
; (^double [^IFn$OD z0 ^IFn$OD z1 ^Iterable data]
; (let [it (g/iterator data)]
; (loop [sum 0.0]
; (if (.hasNext it)
; (let [datum (.next it)]
; (recur (+ sum (Math/abs
; (- (.invokePrim z0 datum)
; (.invokePrim z1 datum))))))
; sum)))))
(^double [^IFn$OD z0 ^IFn$OD z1 ^Iterable data]
(let [absolute-residual (fn absolute-residual ^double [datum]
(Math/abs (- (.invokePrim z0 datum)
(.invokePrim z1 datum))))]
(l1-norm (g/pmap-doubles absolute-residual data)))))
;;----------------------------------------------------------------
(defn mean-absolute-difference
"Compute the mean absolute difference between the elements of 2
arrays, or between the values of 2 functions mapped over a data
set."
(^double [^doubles z0 ^doubles z1]
(/ (l1-distance z0 z1) (alength z0)))
(^double [^IFn$OD z0 ^IFn$OD z1 ^Iterable data]
(/ (l1-distance z0 z1 data) (g/count data))))
;;----------------------------------------------------------------
(defn qr-cost
"Compute the sum of usual quantile regression costs:
<code>(if (<= 0 dz) (* p dz) (* (- p 1) dz))</code>,
where <code>dz == (- z0 z1)</code>."
(^double [^double p
^doubles z0
^doubles z1]
(let [n (alength z0)
p- (- p 1.0)]
(assert (== n (alength z1)))
(loop [sum 0.0
i 0]
(if (< i n)
(let [dz (- (aget z0 i) (aget z1 i))
ds (if (<= 0.0 dz) (* p dz) (* p- dz))]
(recur (+ sum ds) (inc i)))
(* 2.0 sum)))))
(^double [^double p
^IFn$OD z0
^IFn$OD z1
^Iterable data]
(let [p- (- p 1.0)
it (.iterator data)]
(loop [sum 0.0]
(if (.hasNext it)
(let [datum (.next it)
dz (- (.invokePrim z0 datum)
(.invokePrim z1 datum))
ds (if (<= 0.0 dz) (* p dz) (* p- dz))]
(recur (+ sum ds)))
(* 2.0 sum))))))
;;----------------------------------------------------------------
(defn mean-qr-cost
"Compute the mean of usual quantile regression costs:
<code>(if (<= 0 dz) (* p dz) (* (- p 1) dz))</code>,
where <code>dz == (- z0 z1)</code>."
(^double [^double p ^doubles z0 ^doubles z1]
(/ (qr-cost p z0 z1) (alength z0)))
(^double [^double p ^IFn$OD z0 ^IFn$OD z1 ^Iterable data]
(/ (qr-cost p z0 z1 data) (g/count data))))
;;----------------------------------------------------------------
(defn rq-cost
"Compute the sum of a better (?) scaling of the usual quantile
regression costs:
<code>(if (<= 0 dz) (/ dz (- 1.0 p)) (/ (- dz) p))</code>,
where <code>dz == (- z0 z1)</code>."
(^double [^double p
^doubles z0
^doubles z1]
(let [n (alength z0)
p- (- p)
p+ (- 1.0 p)]
(assert (== n (alength z1)))
(loop [sum 0.0
i 0]
(if (< i n)
(let [dz (- (aget z0 i) (aget z1 i))
ds (if (<= 0.0 dz) (/ dz p+) (/ dz p-))]
(recur (+ sum ds) (inc i)))
(* 0.5 sum)))))
(^double [^double p
^IFn$OD z0
^IFn$OD z1
^Iterable data]
(let [p- (- p)
p+ (- 1.0 p)
it (.iterator data)]
(loop [sum 0.0]
(if (.hasNext it)
(let [datum (.next it)
dz (- (.invokePrim z0 datum)
(.invokePrim z1 datum))
ds (if (<= 0.0 dz) (/ dz p+) (/ dz p-))]
(recur (+ sum ds)))
(* 0.5 sum))))))
;;----------------------------------------------------------------
(defn mean-rq-cost
"Compute the mean of alternate quantile regression costs:
<code>(if (<= 0 dz) (/ dz (- 1 p)) (/ (- dz) p)</code>,
where <code>dz == (- z0 z1)</code>."
(^double [^double p ^doubles z0 ^doubles z1]
(/ (rq-cost p z0 z1) (alength z0)))
(^double [^double p ^IFn$OD z0 ^IFn$OD z1 ^Iterable data]
(/ (rq-cost p z0 z1 data) (g/count data))))
;;----------------------------------------------------------------
;; TODO: more accurate summation
(defn l2-norm
"Compute the sum of squares of the elements of an array, or of the values
of a function mapped over a data set."
(^double [^doubles zs]
(let [n (alength zs)]
(loop [sum 0.0
i 0]
(if (< i n)
(let [zi (aget zs i)]
(recur (+ sum (* zi zi)) (inc i)))
sum))))
(^double [^IFn$OD z ^Iterable data]
(let [it (g/iterator data)]
(loop [sum 0.0]
(if (.hasNext it)
(let [zi (.invokePrim z (.next it))]
(recur (+ sum (* zi zi))))
sum)))))
;;----------------------------------------------------------------
;; TODO: more accurate summation. g/reduce-double
(defn l2-distance
"Compute the L1 distance between 2 arrays, or between the values of
2 functions mapped over a data set."
(^double [^doubles z0 ^doubles z1]
(let [n (alength z0)]
(assert (== n (alength z1)))
(loop [sum 0.0
i 0]
(if (< i n)
(let [dz (- (aget z0 i) (aget z1 i))]
(recur (+ sum (* dz dz)) (inc i)))
sum))))
(^double [^IFn$OD z0 ^IFn$OD z1 ^Iterable data]
(let [n (g/count data)
it (g/iterator data)]
(loop [sum 0.0]
(if (.hasNext it)
(let [datum (.next it)
dz (- (.invokePrim z0 datum) (.invokePrim z1 datum))]
(recur (+ sum (* dz dz))))
sum)))))
;;----------------------------------------------------------------
(defn rms-difference
"Return the square root of the [[l2-distance]]."
(^double [^doubles z0 ^doubles z1]
(Math/sqrt (/ (l2-distance z0 z1) (alength z0))))
(^double [^IFn$OD z0 ^IFn$OD z1 ^Iterable data]
(Math/sqrt (/ (l2-distance z0 z1 data) (g/count data)))))
;;----------------------------------------------------------------
| 109277 | (set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "wahpen<EMAIL> at gmail dot com"
:date "2018-04-16"
:doc "Stats that don't have an obvious home." }
zana.stats.statistics
(:refer-clojure :exclude [min max])
(:require [zana.geometry.r1 :as r1]
[zana.geometry.z1 :as z1]
[zana.collections.generic :as g]
[zana.stats.accumulators :as accumulators])
(:import [java.util List Map]
[clojure.lang IFn IFn$OD IFn$OL]
[org.apache.commons.math3.stat.descriptive
DescriptiveStatistics]
[zana.java.functions IFnODWithMeta]
[zana.java.math Statistics]
[zana.java.prob ApproximatelyEqual]))
;;----------------------------------------------------------------
;; TODO: handle relative and absolute equality epsilons
;; TODO: move somewhere else?
(defn float-approximately==
([^double ulps ^double x ^double y]
(let [x (float x)
y (float y)
delta (* (float ulps)
(Math/ulp
(float (+ 1.0 (Math/abs x) (Math/abs y)))))]
(<= (Math/abs (float (- x y))) delta)))
([^double x ^double y]
(float-approximately== 1.0 x y)))
;;----------------------------------------------------------------
;; TODO: move somewhere else?
(defn approximately<=
([^double ulps ^double x ^double y]
(let [delta (* ulps
(Math/ulp (+ 1.0 (Math/abs x) (Math/abs y))))]
(<= (- x y) delta)))
([^double x ^double y]
(approximately<= 1.0 x y)))
(defn approximately==
([^double ulps ^double x ^double y]
(let [delta (* ulps
(Math/ulp (+ 1.0 (Math/abs x) (Math/abs y))))]
(<= (Math/abs (- x y)) delta)))
([^double x ^double y] (approximately== 1.0 x y)))
(defn approximately>=
([^double ulps ^double x ^double y]
(let [delta (* ulps
(Math/ulp (+ 1.0 (Math/abs x) (Math/abs y))))]
(<= (- y x) delta)))
([^double x ^double y]
(approximately<= 1.0 x y)))
(defn approximatelyEqual
([^ApproximatelyEqual x ^ApproximatelyEqual y]
(.approximatelyEqual x y))
([^ApproximatelyEqual x ^ApproximatelyEqual y & more]
(and (approximatelyEqual x y)
(apply approximatelyEqual y (first more) (rest more)))))
(defn doubles-approximately==
([^double ulps ^doubles s0 ^doubles s1]
(and (== (alength s0) (alength s1))
(let [n (int (alength s0))]
(loop [i (int 0)]
(if (< i n)
(let [z0 (aget s0 i)
z1 (aget s1 i)]
(if-not (approximately== ulps z0 z1)
false
(recur (inc i))))
true)))))
([^doubles s0 ^doubles s1]
(doubles-approximately== 1.0 s0 s1)))
(defn lists-approximately==
([^double ulps ^List s0 ^List s1]
(and (== (.size s0) (.size s1))
(let [i0 (.iterator s0)
i1 (.iterator s1)]
(loop []
(if (.hasNext i0)
(let [z0 (double (.next i0))
z1 (double (.next i1))]
(if-not (approximately== ulps z0 z1)
false
(recur)))
true)))))
([^List s0 ^List s1]
(lists-approximately== 1.0 s0 s1)))
(defn maps-approximately==
([^double ulps ^Map m0 ^Map m1]
(and (= (.keySet m0) (.keySet m1))
(let [it (.iterator (.keySet m0))]
(loop []
(if (.hasNext it)
(let [k (.next it)
z0 (double (.get m0 k))
z1 (double (.get m1 k))]
(if-not (approximately== ulps z0 z1)
false
(recur)))
true)))))
([^Map m0 ^Map m1]
(maps-approximately== 1.0 m0 m1)))
;;----------------------------------------------------------------
;; TODO: move to function namespace
(defn numerical?
"Does <code>f</code> return primitive <code>double</code> or <code>long</code>
values? <br>
Does <code>f</code> return a number for every element of <code>data</code>?"
([^IFn f]
(or (instance? IFn$OD f)
(instance? IFn$OL f)))
([^IFn f ^Iterable data]
(try
(or (numerical? f)
(g/every? #(number? (f %)) data))
(catch Throwable t
(throw
(RuntimeException.
(print-str "numerical?" f (class data) (g/count data))
t))))))
;;----------------------------------------------------------------
;; TODO: move to function namespace
(defn constantly-0d
"An instance of <code>IFn$OD</code> that returns a primitve
<code>double</code> 0.0, regardless of input."
(^double [] 0.0)
(^double [arg] 0.0))
(defn constantly-1d
"An instance of <code>IFn$OD</code> that returns a primitve
<code>double</code> 1.0, regardless of input."
(^double [] 1.0)
(^double [arg] 1.0))
;;----------------------------------------------------------------
(defn- singular-longs? [^IFn$OL z ^Iterable data]
(let [it (g/iterator data)]
(if (.hasNext it)
(let [z0 (.invokePrim z (.next it))]
(loop []
(if (.hasNext it)
(let [z1 (.invokePrim z (.next it))]
(if (== z0 z1)
(recur)
false))
true)))
true)))
(defn- singular-doubles? [^IFn$OD z ^Iterable data]
(let [it (g/iterator data)
delta (Math/ulp (double 1.0))]
(if-not (.hasNext it)
true
;; get the 1st non-NaN, if any
(let [z0 (double
(loop []
(if (.hasNext it)
(let [di (.next it)
zi (.invokePrim z di)]
(if (Double/isNaN zi)
(recur)
zi))
Double/NaN)))]
;; if all NaN, then .hasNext is false
;; TODO: should this be a relative difference test?
(loop []
(if (.hasNext it)
(let [d1 (.next it)
z1 (.invokePrim z d1)]
(if (> (Math/abs (- z0 z1)) delta)
false
;; else z1 is NaN and/or different from z0
(recur)))
true))))))
(defn- singular-objects? [^IFn z ^Iterable data]
(if (nil? data)
true
(let [it (.iterator data)]
(if-not (.hasNext it)
true
;; get the 1st non-nil, if any
(let [z0 (loop []
(when (.hasNext it)
(let [zi (z (.next it))]
(if (nil? zi) ;; false is not nil == missing
(recur)
zi))))]
;; if all nil, then no more
(loop []
(if (.hasNext it)
(let [z1 (z (.next it))]
(if (or (nil? z1) (= z0 z1))
(recur)
false))
true)))))))
;;----------------------------------------------------------------
(defn singular?
"Is there more than one distinct value in <code>a</code> or in the values of
<code>z</code> mapped over <code>data</code>."
([^doubles a] (zana.java.arrays.Arrays/isSingular a))
([^IFn z ^Iterable data]
(cond (instance? IFn$OD z) (singular-doubles? z data)
(instance? IFn$OL z) (singular-longs? z data)
:else (singular-objects? z data))))
;;----------------------------------------------------------------
;; a mess of functions computing bounds of various kinds.
;; TODO: rationalize this, maybe move some to a geometry package.
;; TODO: minmax, bounds, bounding-box, range are all variations on the same thing
;;----------------------------------------------------------------
;; TODO: handle any Comparable, accept comparator function
;; TODO: compare speed to Java implementation.
;; TODO: move to zana/tu.geometry?
(defn- bounds-slow
(^zana.java.geometry.r1.Interval [^IFn f
^Iterable data
^double min0
^double max0]
(assert (not (g/empty? data)))
(let [it (.iterator data)]
(loop [xmin min0
xmax max0]
(if (.hasNext it)
(let [x (double (f (.next it)))]
(if (Double/isNaN x)
(recur xmin xmax)
(if (>= x xmin)
(if (<= x xmax)
(recur xmin xmax)
(recur xmin x))
(if (<= x xmax)
(recur x xmax)
(recur x x)))))
(r1/interval xmin (Math/nextUp xmax)))))))
;;----------------------------------------------------------------
(defn- bounds-fast
(^zana.java.geometry.r1.Interval [^IFn$OD f
^Iterable data
^double min0
^double max0]
(assert (not (g/empty? data)))
(let [^IFn$OD f (if (instance? IFnODWithMeta f)
(.functionOD ^IFnODWithMeta f)
f)
it (.iterator data)]
(loop [xmin min0
xmax max0]
(if (.hasNext it)
(let [x (.invokePrim f (.next it))]
(if (Double/isNaN x)
(recur xmin xmax)
(if (>= x xmin)
(if (<= x xmax)
(recur xmin xmax)
(recur xmin x))
(if (<= x xmax)
(recur x xmax)
(recur x x)))))
(r1/interval xmin (Math/nextUp xmax)))))))
;;----------------------------------------------------------------
(defn bounds
(^zana.java.geometry.r1.Interval [^Iterable data
^double min0
^double max0]
(when-not (g/empty? data)
(let [it (.iterator data)]
(loop [xmin min0
xmax max0]
(if (.hasNext it)
(let [x (double (.next it))]
(if (Double/isNaN x)
(recur xmin xmax)
(if (>= x xmin)
(if (<= x xmax)
(recur xmin xmax)
(recur xmin x))
(if (<= x xmax)
(recur x xmax)
(recur x x)))))
(r1/interval xmin (Math/nextUp xmax)))))))
(^zana.java.geometry.r1.Interval [^Iterable data]
(bounds data Double/POSITIVE_INFINITY Double/NEGATIVE_INFINITY))
(^zana.java.geometry.r1.Interval [^IFn f
^Iterable data
^double min0
^double max0]
(when-not (g/empty? data)
(let [it (.iterator data)]
(if (instance? IFn$OD f)
(bounds-fast f data min0 max0)
(bounds-slow f data min0 max0)))))
(^zana.java.geometry.r1.Interval [^IFn f
^Iterable data]
(bounds f data Double/POSITIVE_INFINITY Double/NEGATIVE_INFINITY)))
;;----------------------------------------------------------------
(defn- bounding-box-slow
(^java.awt.geom.Rectangle2D$Double [^IFn xf
^IFn yf
^Iterable data]
(let [it (.iterator data)]
(loop [xmin Double/POSITIVE_INFINITY
xmax Double/NEGATIVE_INFINITY
ymin Double/POSITIVE_INFINITY
ymax Double/NEGATIVE_INFINITY]
(if (.hasNext it)
(let [i (.next it)
_ (assert i "no datum")
x (xf i)
_ (assert x (str "x:" xf " " i))
y (yf i)
_ (assert y (str "y:" yf " " i))
x (double x)
y (double y)
;; this will ignore NaNs
xmin (if (< x xmin) x xmin)
xmax (if (> x xmax) x xmax)
ymin (if (< y ymin) y ymin)
ymax (if (> y ymax) y ymax)]
(recur xmin xmax ymin ymax))
(java.awt.geom.Rectangle2D$Double.
xmin ymin (- xmax xmin) (- ymax ymin)))))))
;;----------------------------------------------------------------
(defn- bounding-box-fast
(^java.awt.geom.Rectangle2D$Double [^IFn$OD xf
^IFn$OD yf
^Iterable data]
(let [^IFn$OD xf (if (instance? IFnODWithMeta xf)
(.functionOD ^IFnODWithMeta xf)
xf)
^IFn$OD yf (if (instance? IFnODWithMeta yf)
(.functionOD ^IFnODWithMeta yf)
yf)
it (.iterator data)]
(loop [xmin Double/POSITIVE_INFINITY
xmax Double/NEGATIVE_INFINITY
ymin Double/POSITIVE_INFINITY
ymax Double/NEGATIVE_INFINITY]
(if (.hasNext it)
(let [i (.next it)
x (.invokePrim xf i)
y (.invokePrim yf i)
;; this will ignore NaNs
xmin (if (< x xmin) x xmin)
xmax (if (> x xmax) x xmax)
ymin (if (< y ymin) y ymin)
ymax (if (> y ymax) y ymax)]
(recur xmin xmax ymin ymax))
(java.awt.geom.Rectangle2D$Double.
xmin ymin (- xmax xmin) (- ymax ymin)))))))
;;----------------------------------------------------------------
(defn bounding-box
(^java.awt.geom.Rectangle2D$Double [^IFn xf
^IFn yf
^Iterable data]
(if (and (instance? IFn$OD xf)
(instance? IFn$OD yf))
(bounding-box-fast xf yf data)
;;(Statistics/bounds xf yf data)
(bounding-box-slow xf yf data))))
;;----------------------------------------------------------------
(defn symmetric-bounds
^java.awt.geom.Rectangle2D$Double [^IFn$OD xf
^IFn$OD yf
^Iterable data]
(Statistics/symmetricBounds xf yf data))
;;----------------------------------------------------------------
(defn- minmax-long [^IFn$OL z ^Iterable data]
(assert (not (g/empty? data)))
(let [i (g/iterator data)
zz (.invokePrim z (.next i))]
(loop [z0 zz
z1 zz]
(if (.hasNext i)
(let [zi (.invokePrim z (.next i))]
(cond (< zi z0) (recur zi z1)
(> zi z1) (recur z0 zi)
:else (recur z0 z1)))
[z0 z1]))))
(defn- minmax-double [^IFn$OD z ^Iterable data]
(assert (not (g/empty? data)))
(let [i (g/iterator data)
zz (.invokePrim z (.next i))]
(loop [z0 zz
z1 zz]
(if (.hasNext i)
(let [zi (.invokePrim z (.next i))]
(cond (< zi z0) (recur zi z1)
(> zi z1) (recur z0 zi)
:else (recur z0 z1)))
[z0 z1]))))
(defn- minmax-comparable [^IFn z ^Iterable data]
(assert (not (g/empty? data)))
(let [i (g/iterator data)
^Comparable zz (z (.next i))]
(loop [^Comparable z0 zz
^Comparable z1 zz]
(if (.hasNext i)
(let [^Comparable zi (z (.next i))]
(cond (< (.compareTo zi z0) (int 0)) (recur zi z1)
(> (.compareTo zi z1) (int 0)) (recur z0 zi)
:else (recur z0 z1)))
[z0 z1]))))
(defn minmax
"Return a 2-element vector containing the minimum and maximum values
of <code>z</code> over <code>data</code>. The values of <code>z</code>
need to be <code>Comparable</code>, or primitive numbers."
([z data]
(cond (instance? IFn$OL z) (minmax-long z data)
(instance? IFn$OD z) (minmax-double z data)
(instance? IFn z) (minmax-comparable z data)
:else (throw
(IllegalArgumentException.
(print-str "can't find the minmax values of " (class z)))))))
;;----------------------------------------------------------------
(defn fast-min ^double [^IFn$OD f ^Iterable data]
(let [it (.iterator data)]
(loop [xmin Double/POSITIVE_INFINITY]
(if (.hasNext it)
(let [x (.invokePrim f (.next it))]
(if (Double/isNaN x)
(recur xmin)
(if (>= x xmin)
(recur xmin)
(recur x))))
xmin))))
;;----------------------------------------------------------------
(defn min
(^double [^IFn f ^Iterable data]
(if (instance? IFn$OD f)
(fast-min f data)
(let [it (.iterator data)]
(loop [xmin Double/POSITIVE_INFINITY]
(if (.hasNext it)
(let [x (double (f (.next it)))]
(if (Double/isNaN x)
(recur xmin)
(if (>= x xmin)
(recur xmin)
(recur x))))
xmin)))))
(^double [^Iterable data]
(let [it (.iterator data)]
(loop [xmin Double/POSITIVE_INFINITY]
(if (.hasNext it)
(let [x (double (.next it))]
(if (Double/isNaN x)
(recur xmin)
(if (>= x xmin)
(recur xmin)
(recur x))))
xmin)))))
;;----------------------------------------------------------------
;; return Double/NEGATIVE_INFINITY for empty datasets
(defn fast-max ^double [^IFn$OD f ^Iterable data]
(let [it (.iterator data)]
(loop [xmax Double/NEGATIVE_INFINITY]
(if (.hasNext it)
(let [x (.invokePrim f (.next it))]
(if (Double/isNaN x)
(recur xmax)
(if (<= x xmax)
(recur xmax)
(recur x))))
xmax))))
;;----------------------------------------------------------------
;; return Double/NEGATIVE_INFINITY for empty datasets
(defn max
(^double [^IFn f ^Iterable data]
(if (instance? IFn$OD f)
(fast-max f data)
(let [it (.iterator data)]
(loop [xmax Double/NEGATIVE_INFINITY]
(if (.hasNext it)
(let [x (double (f (.next it)))]
(if (Double/isNaN x)
(recur xmax)
(if (<= x xmax)
(recur xmax)
(recur x))))
xmax)))))
(^double [^Iterable data]
(let [it (.iterator data)]
(loop [xmax Double/NEGATIVE_INFINITY]
(if (.hasNext it)
(let [x (double (.next it))]
(if (Double/isNaN x)
(recur xmax)
(if (<= x xmax)
(recur xmax)
(recur x))))
xmax)))))
;;----------------------------------------------------------------
(defn quantiles
"Return a vector of the quantiles of the doubles in
<code>zs</code>, or the doubles resulting from mapping
<code>z</code> over <code>data</code>.
Return quantiles corresponding to the <code>ps</code>, which
must be numbers between 0.0 and 1.0 (both ends inclusive)."
([zs ps]
(let [^doubles zs (into-array Double/TYPE zs)
ds (DescriptiveStatistics. zs)]
(mapv (fn ^double [^double p]
;; TODO: better 'equality' test?
(cond (== 0.0 p) (.getMin ds)
(== 1.0 p) (.getMax ds)
:else (.getPercentile ds (* 100.0 p))))
ps)))
([z data ps] (quantiles (g/map-to-doubles z data) ps)))
;;----------------------------------------------------------------
;; TODO: Kahan summation; use accumulators?
(defn sum
"Compute the sum of the elements of an array, or of the
values of a function mapped over a data set."
(^double [^doubles zs]
(let [n (alength zs)]
(loop [sum 0.0
i 0]
(if (< i n)
(recur (+ sum (aget zs i)) (inc i))
sum))))
(^double [^IFn z ^Iterable data]
(cond
(instance? IFn$OD z)
(let [^IFn$OD z z
it (g/iterator data)]
(loop [sum (double 0.0)]
(if (.hasNext it)
(recur (+ sum (.invokePrim z (.next it))))
sum)))
(instance? IFn$OL z)
(let [^IFn$OL z z
it (g/iterator data)]
(loop [sum (long 0)]
(if (.hasNext it)
(recur (+ sum (.invokePrim z (.next it))))
(double sum))))
:else
(let [it (g/iterator data)]
(loop [sum (double 0.0)]
(if (.hasNext it)
(recur (+ sum (double (z (.next it)))))
(double sum)))))))
;;----------------------------------------------------------------
(defn mean
"Compute the mean of the elements of an array, or of the
values of a function mapped over a data set."
(^double [^doubles zs] (/ (sum zs) (alength zs)))
(^double [^IFn z ^Iterable data]
(/ (sum z data) (g/count data))))
;;----------------------------------------------------------------
;; TODO: Kahan summation
(defn l1-norm
"Compute the sum of absolute value of the elements of an array,
or of the values of a function mapped over a data set."
(^double [^doubles zs]
(let [n (alength zs)]
(loop [sum 0.0
i 0]
(if (< i n)
(recur (+ sum (Math/abs (aget zs i))) (inc i))
sum))))
(^double [^IFn$OD z ^Iterable data]
(let [it (g/iterator data)]
(loop [sum 0.0]
(if (.hasNext it)
(recur (+ sum (Math/abs (.invokePrim z (.next it)))))
sum)))))
;;----------------------------------------------------------------
;; TODO: Kahan summation
(defn l1-distance
"Compute the sum of absolute differences between 2 arrays, or
between the values of 2 functions mapped over a data set."
(^double [^doubles z0 ^doubles z1]
(let [n (alength z0)]
(assert (== n (alength z1)))
(loop [sum 0.0
i 0]
(if (< i n)
(recur (+ sum (Math/abs (- (aget z0 i) (aget z1 i))))
(inc i))
sum))))
; (^double [^IFn$OD z0 ^IFn$OD z1 ^Iterable data]
; (let [it (g/iterator data)]
; (loop [sum 0.0]
; (if (.hasNext it)
; (let [datum (.next it)]
; (recur (+ sum (Math/abs
; (- (.invokePrim z0 datum)
; (.invokePrim z1 datum))))))
; sum)))))
(^double [^IFn$OD z0 ^IFn$OD z1 ^Iterable data]
(let [absolute-residual (fn absolute-residual ^double [datum]
(Math/abs (- (.invokePrim z0 datum)
(.invokePrim z1 datum))))]
(l1-norm (g/pmap-doubles absolute-residual data)))))
;;----------------------------------------------------------------
(defn mean-absolute-difference
"Compute the mean absolute difference between the elements of 2
arrays, or between the values of 2 functions mapped over a data
set."
(^double [^doubles z0 ^doubles z1]
(/ (l1-distance z0 z1) (alength z0)))
(^double [^IFn$OD z0 ^IFn$OD z1 ^Iterable data]
(/ (l1-distance z0 z1 data) (g/count data))))
;;----------------------------------------------------------------
(defn qr-cost
"Compute the sum of usual quantile regression costs:
<code>(if (<= 0 dz) (* p dz) (* (- p 1) dz))</code>,
where <code>dz == (- z0 z1)</code>."
(^double [^double p
^doubles z0
^doubles z1]
(let [n (alength z0)
p- (- p 1.0)]
(assert (== n (alength z1)))
(loop [sum 0.0
i 0]
(if (< i n)
(let [dz (- (aget z0 i) (aget z1 i))
ds (if (<= 0.0 dz) (* p dz) (* p- dz))]
(recur (+ sum ds) (inc i)))
(* 2.0 sum)))))
(^double [^double p
^IFn$OD z0
^IFn$OD z1
^Iterable data]
(let [p- (- p 1.0)
it (.iterator data)]
(loop [sum 0.0]
(if (.hasNext it)
(let [datum (.next it)
dz (- (.invokePrim z0 datum)
(.invokePrim z1 datum))
ds (if (<= 0.0 dz) (* p dz) (* p- dz))]
(recur (+ sum ds)))
(* 2.0 sum))))))
;;----------------------------------------------------------------
(defn mean-qr-cost
"Compute the mean of usual quantile regression costs:
<code>(if (<= 0 dz) (* p dz) (* (- p 1) dz))</code>,
where <code>dz == (- z0 z1)</code>."
(^double [^double p ^doubles z0 ^doubles z1]
(/ (qr-cost p z0 z1) (alength z0)))
(^double [^double p ^IFn$OD z0 ^IFn$OD z1 ^Iterable data]
(/ (qr-cost p z0 z1 data) (g/count data))))
;;----------------------------------------------------------------
(defn rq-cost
"Compute the sum of a better (?) scaling of the usual quantile
regression costs:
<code>(if (<= 0 dz) (/ dz (- 1.0 p)) (/ (- dz) p))</code>,
where <code>dz == (- z0 z1)</code>."
(^double [^double p
^doubles z0
^doubles z1]
(let [n (alength z0)
p- (- p)
p+ (- 1.0 p)]
(assert (== n (alength z1)))
(loop [sum 0.0
i 0]
(if (< i n)
(let [dz (- (aget z0 i) (aget z1 i))
ds (if (<= 0.0 dz) (/ dz p+) (/ dz p-))]
(recur (+ sum ds) (inc i)))
(* 0.5 sum)))))
(^double [^double p
^IFn$OD z0
^IFn$OD z1
^Iterable data]
(let [p- (- p)
p+ (- 1.0 p)
it (.iterator data)]
(loop [sum 0.0]
(if (.hasNext it)
(let [datum (.next it)
dz (- (.invokePrim z0 datum)
(.invokePrim z1 datum))
ds (if (<= 0.0 dz) (/ dz p+) (/ dz p-))]
(recur (+ sum ds)))
(* 0.5 sum))))))
;;----------------------------------------------------------------
(defn mean-rq-cost
"Compute the mean of alternate quantile regression costs:
<code>(if (<= 0 dz) (/ dz (- 1 p)) (/ (- dz) p)</code>,
where <code>dz == (- z0 z1)</code>."
(^double [^double p ^doubles z0 ^doubles z1]
(/ (rq-cost p z0 z1) (alength z0)))
(^double [^double p ^IFn$OD z0 ^IFn$OD z1 ^Iterable data]
(/ (rq-cost p z0 z1 data) (g/count data))))
;;----------------------------------------------------------------
;; TODO: more accurate summation
(defn l2-norm
"Compute the sum of squares of the elements of an array, or of the values
of a function mapped over a data set."
(^double [^doubles zs]
(let [n (alength zs)]
(loop [sum 0.0
i 0]
(if (< i n)
(let [zi (aget zs i)]
(recur (+ sum (* zi zi)) (inc i)))
sum))))
(^double [^IFn$OD z ^Iterable data]
(let [it (g/iterator data)]
(loop [sum 0.0]
(if (.hasNext it)
(let [zi (.invokePrim z (.next it))]
(recur (+ sum (* zi zi))))
sum)))))
;;----------------------------------------------------------------
;; TODO: more accurate summation. g/reduce-double
(defn l2-distance
"Compute the L1 distance between 2 arrays, or between the values of
2 functions mapped over a data set."
(^double [^doubles z0 ^doubles z1]
(let [n (alength z0)]
(assert (== n (alength z1)))
(loop [sum 0.0
i 0]
(if (< i n)
(let [dz (- (aget z0 i) (aget z1 i))]
(recur (+ sum (* dz dz)) (inc i)))
sum))))
(^double [^IFn$OD z0 ^IFn$OD z1 ^Iterable data]
(let [n (g/count data)
it (g/iterator data)]
(loop [sum 0.0]
(if (.hasNext it)
(let [datum (.next it)
dz (- (.invokePrim z0 datum) (.invokePrim z1 datum))]
(recur (+ sum (* dz dz))))
sum)))))
;;----------------------------------------------------------------
(defn rms-difference
"Return the square root of the [[l2-distance]]."
(^double [^doubles z0 ^doubles z1]
(Math/sqrt (/ (l2-distance z0 z1) (alength z0))))
(^double [^IFn$OD z0 ^IFn$OD z1 ^Iterable data]
(Math/sqrt (/ (l2-distance z0 z1 data) (g/count data)))))
;;----------------------------------------------------------------
| true | (set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "wahpenPI:EMAIL:<EMAIL>END_PI at gmail dot com"
:date "2018-04-16"
:doc "Stats that don't have an obvious home." }
zana.stats.statistics
(:refer-clojure :exclude [min max])
(:require [zana.geometry.r1 :as r1]
[zana.geometry.z1 :as z1]
[zana.collections.generic :as g]
[zana.stats.accumulators :as accumulators])
(:import [java.util List Map]
[clojure.lang IFn IFn$OD IFn$OL]
[org.apache.commons.math3.stat.descriptive
DescriptiveStatistics]
[zana.java.functions IFnODWithMeta]
[zana.java.math Statistics]
[zana.java.prob ApproximatelyEqual]))
;;----------------------------------------------------------------
;; TODO: handle relative and absolute equality epsilons
;; TODO: move somewhere else?
(defn float-approximately==
([^double ulps ^double x ^double y]
(let [x (float x)
y (float y)
delta (* (float ulps)
(Math/ulp
(float (+ 1.0 (Math/abs x) (Math/abs y)))))]
(<= (Math/abs (float (- x y))) delta)))
([^double x ^double y]
(float-approximately== 1.0 x y)))
;;----------------------------------------------------------------
;; TODO: move somewhere else?
(defn approximately<=
([^double ulps ^double x ^double y]
(let [delta (* ulps
(Math/ulp (+ 1.0 (Math/abs x) (Math/abs y))))]
(<= (- x y) delta)))
([^double x ^double y]
(approximately<= 1.0 x y)))
(defn approximately==
([^double ulps ^double x ^double y]
(let [delta (* ulps
(Math/ulp (+ 1.0 (Math/abs x) (Math/abs y))))]
(<= (Math/abs (- x y)) delta)))
([^double x ^double y] (approximately== 1.0 x y)))
(defn approximately>=
([^double ulps ^double x ^double y]
(let [delta (* ulps
(Math/ulp (+ 1.0 (Math/abs x) (Math/abs y))))]
(<= (- y x) delta)))
([^double x ^double y]
(approximately<= 1.0 x y)))
(defn approximatelyEqual
([^ApproximatelyEqual x ^ApproximatelyEqual y]
(.approximatelyEqual x y))
([^ApproximatelyEqual x ^ApproximatelyEqual y & more]
(and (approximatelyEqual x y)
(apply approximatelyEqual y (first more) (rest more)))))
(defn doubles-approximately==
([^double ulps ^doubles s0 ^doubles s1]
(and (== (alength s0) (alength s1))
(let [n (int (alength s0))]
(loop [i (int 0)]
(if (< i n)
(let [z0 (aget s0 i)
z1 (aget s1 i)]
(if-not (approximately== ulps z0 z1)
false
(recur (inc i))))
true)))))
([^doubles s0 ^doubles s1]
(doubles-approximately== 1.0 s0 s1)))
(defn lists-approximately==
([^double ulps ^List s0 ^List s1]
(and (== (.size s0) (.size s1))
(let [i0 (.iterator s0)
i1 (.iterator s1)]
(loop []
(if (.hasNext i0)
(let [z0 (double (.next i0))
z1 (double (.next i1))]
(if-not (approximately== ulps z0 z1)
false
(recur)))
true)))))
([^List s0 ^List s1]
(lists-approximately== 1.0 s0 s1)))
(defn maps-approximately==
([^double ulps ^Map m0 ^Map m1]
(and (= (.keySet m0) (.keySet m1))
(let [it (.iterator (.keySet m0))]
(loop []
(if (.hasNext it)
(let [k (.next it)
z0 (double (.get m0 k))
z1 (double (.get m1 k))]
(if-not (approximately== ulps z0 z1)
false
(recur)))
true)))))
([^Map m0 ^Map m1]
(maps-approximately== 1.0 m0 m1)))
;;----------------------------------------------------------------
;; TODO: move to function namespace
(defn numerical?
"Does <code>f</code> return primitive <code>double</code> or <code>long</code>
values? <br>
Does <code>f</code> return a number for every element of <code>data</code>?"
([^IFn f]
(or (instance? IFn$OD f)
(instance? IFn$OL f)))
([^IFn f ^Iterable data]
(try
(or (numerical? f)
(g/every? #(number? (f %)) data))
(catch Throwable t
(throw
(RuntimeException.
(print-str "numerical?" f (class data) (g/count data))
t))))))
;;----------------------------------------------------------------
;; TODO: move to function namespace
(defn constantly-0d
"An instance of <code>IFn$OD</code> that returns a primitve
<code>double</code> 0.0, regardless of input."
(^double [] 0.0)
(^double [arg] 0.0))
(defn constantly-1d
"An instance of <code>IFn$OD</code> that returns a primitve
<code>double</code> 1.0, regardless of input."
(^double [] 1.0)
(^double [arg] 1.0))
;;----------------------------------------------------------------
(defn- singular-longs? [^IFn$OL z ^Iterable data]
(let [it (g/iterator data)]
(if (.hasNext it)
(let [z0 (.invokePrim z (.next it))]
(loop []
(if (.hasNext it)
(let [z1 (.invokePrim z (.next it))]
(if (== z0 z1)
(recur)
false))
true)))
true)))
(defn- singular-doubles? [^IFn$OD z ^Iterable data]
(let [it (g/iterator data)
delta (Math/ulp (double 1.0))]
(if-not (.hasNext it)
true
;; get the 1st non-NaN, if any
(let [z0 (double
(loop []
(if (.hasNext it)
(let [di (.next it)
zi (.invokePrim z di)]
(if (Double/isNaN zi)
(recur)
zi))
Double/NaN)))]
;; if all NaN, then .hasNext is false
;; TODO: should this be a relative difference test?
(loop []
(if (.hasNext it)
(let [d1 (.next it)
z1 (.invokePrim z d1)]
(if (> (Math/abs (- z0 z1)) delta)
false
;; else z1 is NaN and/or different from z0
(recur)))
true))))))
(defn- singular-objects? [^IFn z ^Iterable data]
(if (nil? data)
true
(let [it (.iterator data)]
(if-not (.hasNext it)
true
;; get the 1st non-nil, if any
(let [z0 (loop []
(when (.hasNext it)
(let [zi (z (.next it))]
(if (nil? zi) ;; false is not nil == missing
(recur)
zi))))]
;; if all nil, then no more
(loop []
(if (.hasNext it)
(let [z1 (z (.next it))]
(if (or (nil? z1) (= z0 z1))
(recur)
false))
true)))))))
;;----------------------------------------------------------------
(defn singular?
"Is there more than one distinct value in <code>a</code> or in the values of
<code>z</code> mapped over <code>data</code>."
([^doubles a] (zana.java.arrays.Arrays/isSingular a))
([^IFn z ^Iterable data]
(cond (instance? IFn$OD z) (singular-doubles? z data)
(instance? IFn$OL z) (singular-longs? z data)
:else (singular-objects? z data))))
;;----------------------------------------------------------------
;; a mess of functions computing bounds of various kinds.
;; TODO: rationalize this, maybe move some to a geometry package.
;; TODO: minmax, bounds, bounding-box, range are all variations on the same thing
;;----------------------------------------------------------------
;; TODO: handle any Comparable, accept comparator function
;; TODO: compare speed to Java implementation.
;; TODO: move to zana/tu.geometry?
(defn- bounds-slow
(^zana.java.geometry.r1.Interval [^IFn f
^Iterable data
^double min0
^double max0]
(assert (not (g/empty? data)))
(let [it (.iterator data)]
(loop [xmin min0
xmax max0]
(if (.hasNext it)
(let [x (double (f (.next it)))]
(if (Double/isNaN x)
(recur xmin xmax)
(if (>= x xmin)
(if (<= x xmax)
(recur xmin xmax)
(recur xmin x))
(if (<= x xmax)
(recur x xmax)
(recur x x)))))
(r1/interval xmin (Math/nextUp xmax)))))))
;;----------------------------------------------------------------
(defn- bounds-fast
(^zana.java.geometry.r1.Interval [^IFn$OD f
^Iterable data
^double min0
^double max0]
(assert (not (g/empty? data)))
(let [^IFn$OD f (if (instance? IFnODWithMeta f)
(.functionOD ^IFnODWithMeta f)
f)
it (.iterator data)]
(loop [xmin min0
xmax max0]
(if (.hasNext it)
(let [x (.invokePrim f (.next it))]
(if (Double/isNaN x)
(recur xmin xmax)
(if (>= x xmin)
(if (<= x xmax)
(recur xmin xmax)
(recur xmin x))
(if (<= x xmax)
(recur x xmax)
(recur x x)))))
(r1/interval xmin (Math/nextUp xmax)))))))
;;----------------------------------------------------------------
(defn bounds
(^zana.java.geometry.r1.Interval [^Iterable data
^double min0
^double max0]
(when-not (g/empty? data)
(let [it (.iterator data)]
(loop [xmin min0
xmax max0]
(if (.hasNext it)
(let [x (double (.next it))]
(if (Double/isNaN x)
(recur xmin xmax)
(if (>= x xmin)
(if (<= x xmax)
(recur xmin xmax)
(recur xmin x))
(if (<= x xmax)
(recur x xmax)
(recur x x)))))
(r1/interval xmin (Math/nextUp xmax)))))))
(^zana.java.geometry.r1.Interval [^Iterable data]
(bounds data Double/POSITIVE_INFINITY Double/NEGATIVE_INFINITY))
(^zana.java.geometry.r1.Interval [^IFn f
^Iterable data
^double min0
^double max0]
(when-not (g/empty? data)
(let [it (.iterator data)]
(if (instance? IFn$OD f)
(bounds-fast f data min0 max0)
(bounds-slow f data min0 max0)))))
(^zana.java.geometry.r1.Interval [^IFn f
^Iterable data]
(bounds f data Double/POSITIVE_INFINITY Double/NEGATIVE_INFINITY)))
;;----------------------------------------------------------------
(defn- bounding-box-slow
(^java.awt.geom.Rectangle2D$Double [^IFn xf
^IFn yf
^Iterable data]
(let [it (.iterator data)]
(loop [xmin Double/POSITIVE_INFINITY
xmax Double/NEGATIVE_INFINITY
ymin Double/POSITIVE_INFINITY
ymax Double/NEGATIVE_INFINITY]
(if (.hasNext it)
(let [i (.next it)
_ (assert i "no datum")
x (xf i)
_ (assert x (str "x:" xf " " i))
y (yf i)
_ (assert y (str "y:" yf " " i))
x (double x)
y (double y)
;; this will ignore NaNs
xmin (if (< x xmin) x xmin)
xmax (if (> x xmax) x xmax)
ymin (if (< y ymin) y ymin)
ymax (if (> y ymax) y ymax)]
(recur xmin xmax ymin ymax))
(java.awt.geom.Rectangle2D$Double.
xmin ymin (- xmax xmin) (- ymax ymin)))))))
;;----------------------------------------------------------------
(defn- bounding-box-fast
(^java.awt.geom.Rectangle2D$Double [^IFn$OD xf
^IFn$OD yf
^Iterable data]
(let [^IFn$OD xf (if (instance? IFnODWithMeta xf)
(.functionOD ^IFnODWithMeta xf)
xf)
^IFn$OD yf (if (instance? IFnODWithMeta yf)
(.functionOD ^IFnODWithMeta yf)
yf)
it (.iterator data)]
(loop [xmin Double/POSITIVE_INFINITY
xmax Double/NEGATIVE_INFINITY
ymin Double/POSITIVE_INFINITY
ymax Double/NEGATIVE_INFINITY]
(if (.hasNext it)
(let [i (.next it)
x (.invokePrim xf i)
y (.invokePrim yf i)
;; this will ignore NaNs
xmin (if (< x xmin) x xmin)
xmax (if (> x xmax) x xmax)
ymin (if (< y ymin) y ymin)
ymax (if (> y ymax) y ymax)]
(recur xmin xmax ymin ymax))
(java.awt.geom.Rectangle2D$Double.
xmin ymin (- xmax xmin) (- ymax ymin)))))))
;;----------------------------------------------------------------
(defn bounding-box
(^java.awt.geom.Rectangle2D$Double [^IFn xf
^IFn yf
^Iterable data]
(if (and (instance? IFn$OD xf)
(instance? IFn$OD yf))
(bounding-box-fast xf yf data)
;;(Statistics/bounds xf yf data)
(bounding-box-slow xf yf data))))
;;----------------------------------------------------------------
(defn symmetric-bounds
^java.awt.geom.Rectangle2D$Double [^IFn$OD xf
^IFn$OD yf
^Iterable data]
(Statistics/symmetricBounds xf yf data))
;;----------------------------------------------------------------
(defn- minmax-long [^IFn$OL z ^Iterable data]
(assert (not (g/empty? data)))
(let [i (g/iterator data)
zz (.invokePrim z (.next i))]
(loop [z0 zz
z1 zz]
(if (.hasNext i)
(let [zi (.invokePrim z (.next i))]
(cond (< zi z0) (recur zi z1)
(> zi z1) (recur z0 zi)
:else (recur z0 z1)))
[z0 z1]))))
(defn- minmax-double [^IFn$OD z ^Iterable data]
(assert (not (g/empty? data)))
(let [i (g/iterator data)
zz (.invokePrim z (.next i))]
(loop [z0 zz
z1 zz]
(if (.hasNext i)
(let [zi (.invokePrim z (.next i))]
(cond (< zi z0) (recur zi z1)
(> zi z1) (recur z0 zi)
:else (recur z0 z1)))
[z0 z1]))))
(defn- minmax-comparable [^IFn z ^Iterable data]
(assert (not (g/empty? data)))
(let [i (g/iterator data)
^Comparable zz (z (.next i))]
(loop [^Comparable z0 zz
^Comparable z1 zz]
(if (.hasNext i)
(let [^Comparable zi (z (.next i))]
(cond (< (.compareTo zi z0) (int 0)) (recur zi z1)
(> (.compareTo zi z1) (int 0)) (recur z0 zi)
:else (recur z0 z1)))
[z0 z1]))))
(defn minmax
"Return a 2-element vector containing the minimum and maximum values
of <code>z</code> over <code>data</code>. The values of <code>z</code>
need to be <code>Comparable</code>, or primitive numbers."
([z data]
(cond (instance? IFn$OL z) (minmax-long z data)
(instance? IFn$OD z) (minmax-double z data)
(instance? IFn z) (minmax-comparable z data)
:else (throw
(IllegalArgumentException.
(print-str "can't find the minmax values of " (class z)))))))
;;----------------------------------------------------------------
(defn fast-min ^double [^IFn$OD f ^Iterable data]
(let [it (.iterator data)]
(loop [xmin Double/POSITIVE_INFINITY]
(if (.hasNext it)
(let [x (.invokePrim f (.next it))]
(if (Double/isNaN x)
(recur xmin)
(if (>= x xmin)
(recur xmin)
(recur x))))
xmin))))
;;----------------------------------------------------------------
(defn min
(^double [^IFn f ^Iterable data]
(if (instance? IFn$OD f)
(fast-min f data)
(let [it (.iterator data)]
(loop [xmin Double/POSITIVE_INFINITY]
(if (.hasNext it)
(let [x (double (f (.next it)))]
(if (Double/isNaN x)
(recur xmin)
(if (>= x xmin)
(recur xmin)
(recur x))))
xmin)))))
(^double [^Iterable data]
(let [it (.iterator data)]
(loop [xmin Double/POSITIVE_INFINITY]
(if (.hasNext it)
(let [x (double (.next it))]
(if (Double/isNaN x)
(recur xmin)
(if (>= x xmin)
(recur xmin)
(recur x))))
xmin)))))
;;----------------------------------------------------------------
;; return Double/NEGATIVE_INFINITY for empty datasets
(defn fast-max ^double [^IFn$OD f ^Iterable data]
(let [it (.iterator data)]
(loop [xmax Double/NEGATIVE_INFINITY]
(if (.hasNext it)
(let [x (.invokePrim f (.next it))]
(if (Double/isNaN x)
(recur xmax)
(if (<= x xmax)
(recur xmax)
(recur x))))
xmax))))
;;----------------------------------------------------------------
;; return Double/NEGATIVE_INFINITY for empty datasets
(defn max
(^double [^IFn f ^Iterable data]
(if (instance? IFn$OD f)
(fast-max f data)
(let [it (.iterator data)]
(loop [xmax Double/NEGATIVE_INFINITY]
(if (.hasNext it)
(let [x (double (f (.next it)))]
(if (Double/isNaN x)
(recur xmax)
(if (<= x xmax)
(recur xmax)
(recur x))))
xmax)))))
(^double [^Iterable data]
(let [it (.iterator data)]
(loop [xmax Double/NEGATIVE_INFINITY]
(if (.hasNext it)
(let [x (double (.next it))]
(if (Double/isNaN x)
(recur xmax)
(if (<= x xmax)
(recur xmax)
(recur x))))
xmax)))))
;;----------------------------------------------------------------
(defn quantiles
"Return a vector of the quantiles of the doubles in
<code>zs</code>, or the doubles resulting from mapping
<code>z</code> over <code>data</code>.
Return quantiles corresponding to the <code>ps</code>, which
must be numbers between 0.0 and 1.0 (both ends inclusive)."
([zs ps]
(let [^doubles zs (into-array Double/TYPE zs)
ds (DescriptiveStatistics. zs)]
(mapv (fn ^double [^double p]
;; TODO: better 'equality' test?
(cond (== 0.0 p) (.getMin ds)
(== 1.0 p) (.getMax ds)
:else (.getPercentile ds (* 100.0 p))))
ps)))
([z data ps] (quantiles (g/map-to-doubles z data) ps)))
;;----------------------------------------------------------------
;; TODO: Kahan summation; use accumulators?
(defn sum
"Compute the sum of the elements of an array, or of the
values of a function mapped over a data set."
(^double [^doubles zs]
(let [n (alength zs)]
(loop [sum 0.0
i 0]
(if (< i n)
(recur (+ sum (aget zs i)) (inc i))
sum))))
(^double [^IFn z ^Iterable data]
(cond
(instance? IFn$OD z)
(let [^IFn$OD z z
it (g/iterator data)]
(loop [sum (double 0.0)]
(if (.hasNext it)
(recur (+ sum (.invokePrim z (.next it))))
sum)))
(instance? IFn$OL z)
(let [^IFn$OL z z
it (g/iterator data)]
(loop [sum (long 0)]
(if (.hasNext it)
(recur (+ sum (.invokePrim z (.next it))))
(double sum))))
:else
(let [it (g/iterator data)]
(loop [sum (double 0.0)]
(if (.hasNext it)
(recur (+ sum (double (z (.next it)))))
(double sum)))))))
;;----------------------------------------------------------------
(defn mean
"Compute the mean of the elements of an array, or of the
values of a function mapped over a data set."
(^double [^doubles zs] (/ (sum zs) (alength zs)))
(^double [^IFn z ^Iterable data]
(/ (sum z data) (g/count data))))
;;----------------------------------------------------------------
;; TODO: Kahan summation
(defn l1-norm
"Compute the sum of absolute value of the elements of an array,
or of the values of a function mapped over a data set."
(^double [^doubles zs]
(let [n (alength zs)]
(loop [sum 0.0
i 0]
(if (< i n)
(recur (+ sum (Math/abs (aget zs i))) (inc i))
sum))))
(^double [^IFn$OD z ^Iterable data]
(let [it (g/iterator data)]
(loop [sum 0.0]
(if (.hasNext it)
(recur (+ sum (Math/abs (.invokePrim z (.next it)))))
sum)))))
;;----------------------------------------------------------------
;; TODO: Kahan summation
(defn l1-distance
"Compute the sum of absolute differences between 2 arrays, or
between the values of 2 functions mapped over a data set."
(^double [^doubles z0 ^doubles z1]
(let [n (alength z0)]
(assert (== n (alength z1)))
(loop [sum 0.0
i 0]
(if (< i n)
(recur (+ sum (Math/abs (- (aget z0 i) (aget z1 i))))
(inc i))
sum))))
; (^double [^IFn$OD z0 ^IFn$OD z1 ^Iterable data]
; (let [it (g/iterator data)]
; (loop [sum 0.0]
; (if (.hasNext it)
; (let [datum (.next it)]
; (recur (+ sum (Math/abs
; (- (.invokePrim z0 datum)
; (.invokePrim z1 datum))))))
; sum)))))
(^double [^IFn$OD z0 ^IFn$OD z1 ^Iterable data]
(let [absolute-residual (fn absolute-residual ^double [datum]
(Math/abs (- (.invokePrim z0 datum)
(.invokePrim z1 datum))))]
(l1-norm (g/pmap-doubles absolute-residual data)))))
;;----------------------------------------------------------------
(defn mean-absolute-difference
"Compute the mean absolute difference between the elements of 2
arrays, or between the values of 2 functions mapped over a data
set."
(^double [^doubles z0 ^doubles z1]
(/ (l1-distance z0 z1) (alength z0)))
(^double [^IFn$OD z0 ^IFn$OD z1 ^Iterable data]
(/ (l1-distance z0 z1 data) (g/count data))))
;;----------------------------------------------------------------
(defn qr-cost
"Compute the sum of usual quantile regression costs:
<code>(if (<= 0 dz) (* p dz) (* (- p 1) dz))</code>,
where <code>dz == (- z0 z1)</code>."
(^double [^double p
^doubles z0
^doubles z1]
(let [n (alength z0)
p- (- p 1.0)]
(assert (== n (alength z1)))
(loop [sum 0.0
i 0]
(if (< i n)
(let [dz (- (aget z0 i) (aget z1 i))
ds (if (<= 0.0 dz) (* p dz) (* p- dz))]
(recur (+ sum ds) (inc i)))
(* 2.0 sum)))))
(^double [^double p
^IFn$OD z0
^IFn$OD z1
^Iterable data]
(let [p- (- p 1.0)
it (.iterator data)]
(loop [sum 0.0]
(if (.hasNext it)
(let [datum (.next it)
dz (- (.invokePrim z0 datum)
(.invokePrim z1 datum))
ds (if (<= 0.0 dz) (* p dz) (* p- dz))]
(recur (+ sum ds)))
(* 2.0 sum))))))
;;----------------------------------------------------------------
(defn mean-qr-cost
"Compute the mean of usual quantile regression costs:
<code>(if (<= 0 dz) (* p dz) (* (- p 1) dz))</code>,
where <code>dz == (- z0 z1)</code>."
(^double [^double p ^doubles z0 ^doubles z1]
(/ (qr-cost p z0 z1) (alength z0)))
(^double [^double p ^IFn$OD z0 ^IFn$OD z1 ^Iterable data]
(/ (qr-cost p z0 z1 data) (g/count data))))
;;----------------------------------------------------------------
(defn rq-cost
"Compute the sum of a better (?) scaling of the usual quantile
regression costs:
<code>(if (<= 0 dz) (/ dz (- 1.0 p)) (/ (- dz) p))</code>,
where <code>dz == (- z0 z1)</code>."
(^double [^double p
^doubles z0
^doubles z1]
(let [n (alength z0)
p- (- p)
p+ (- 1.0 p)]
(assert (== n (alength z1)))
(loop [sum 0.0
i 0]
(if (< i n)
(let [dz (- (aget z0 i) (aget z1 i))
ds (if (<= 0.0 dz) (/ dz p+) (/ dz p-))]
(recur (+ sum ds) (inc i)))
(* 0.5 sum)))))
(^double [^double p
^IFn$OD z0
^IFn$OD z1
^Iterable data]
(let [p- (- p)
p+ (- 1.0 p)
it (.iterator data)]
(loop [sum 0.0]
(if (.hasNext it)
(let [datum (.next it)
dz (- (.invokePrim z0 datum)
(.invokePrim z1 datum))
ds (if (<= 0.0 dz) (/ dz p+) (/ dz p-))]
(recur (+ sum ds)))
(* 0.5 sum))))))
;;----------------------------------------------------------------
(defn mean-rq-cost
"Compute the mean of alternate quantile regression costs:
<code>(if (<= 0 dz) (/ dz (- 1 p)) (/ (- dz) p)</code>,
where <code>dz == (- z0 z1)</code>."
(^double [^double p ^doubles z0 ^doubles z1]
(/ (rq-cost p z0 z1) (alength z0)))
(^double [^double p ^IFn$OD z0 ^IFn$OD z1 ^Iterable data]
(/ (rq-cost p z0 z1 data) (g/count data))))
;;----------------------------------------------------------------
;; TODO: more accurate summation
(defn l2-norm
"Compute the sum of squares of the elements of an array, or of the values
of a function mapped over a data set."
(^double [^doubles zs]
(let [n (alength zs)]
(loop [sum 0.0
i 0]
(if (< i n)
(let [zi (aget zs i)]
(recur (+ sum (* zi zi)) (inc i)))
sum))))
(^double [^IFn$OD z ^Iterable data]
(let [it (g/iterator data)]
(loop [sum 0.0]
(if (.hasNext it)
(let [zi (.invokePrim z (.next it))]
(recur (+ sum (* zi zi))))
sum)))))
;;----------------------------------------------------------------
;; TODO: more accurate summation. g/reduce-double
(defn l2-distance
"Compute the L1 distance between 2 arrays, or between the values of
2 functions mapped over a data set."
(^double [^doubles z0 ^doubles z1]
(let [n (alength z0)]
(assert (== n (alength z1)))
(loop [sum 0.0
i 0]
(if (< i n)
(let [dz (- (aget z0 i) (aget z1 i))]
(recur (+ sum (* dz dz)) (inc i)))
sum))))
(^double [^IFn$OD z0 ^IFn$OD z1 ^Iterable data]
(let [n (g/count data)
it (g/iterator data)]
(loop [sum 0.0]
(if (.hasNext it)
(let [datum (.next it)
dz (- (.invokePrim z0 datum) (.invokePrim z1 datum))]
(recur (+ sum (* dz dz))))
sum)))))
;;----------------------------------------------------------------
(defn rms-difference
"Return the square root of the [[l2-distance]]."
(^double [^doubles z0 ^doubles z1]
(Math/sqrt (/ (l2-distance z0 z1) (alength z0))))
(^double [^IFn$OD z0 ^IFn$OD z1 ^Iterable data]
(Math/sqrt (/ (l2-distance z0 z1 data) (g/count data)))))
;;----------------------------------------------------------------
|
[
{
"context": "(ns irf.vector)\n\n;vector.cljs\n;by Kolja Wilcke in June 2017\n\n(defrecord Vector [x y])\n(def v ->V",
"end": 46,
"score": 0.999875545501709,
"start": 34,
"tag": "NAME",
"value": "Kolja Wilcke"
}
] | src/irf/vector.cljs | kolja/instant-rocket-fuel-cljs | 0 | (ns irf.vector)
;vector.cljs
;by Kolja Wilcke in June 2017
(defrecord Vector [x y])
(def v ->Vector)
(defn sqr [x] (js/Math.pow x 2))
(def abs js/Math.abs)
(def atan2 js/Math.atan2)
(def pi (.-PI js/Math))
(def tau (+ pi pi))
(def v0 (->Vector 0 0)) ;; null-vektor
(defn quadrant [{:keys [x y]}]
"which quadrant does a vector point to"
(case [(pos? x) (pos? y)]
[true true] 1
[true false] 2
[false false] 3
[false true] 4))
(defmulti almost= #(cond (number? %) :number
(instance? irf.vector/Vector %) :vector))
(defmethod almost= :number
[& args]
"approximate equality for numbers"
(let [mx (apply max args)
mn (apply min args)
e (/ (max (abs mn) (abs mx)) 1e10)]
(< (- mx mn) e)))
(defmethod almost= :vector
[& args]
"approximate equality for vectors"
(and (apply almost= (map :x args))
(apply almost= (map :y args))))
(defn add [& args]
"Add Vectors"
(reduce (fn [{x :x y :y} {acc-x :x acc-y :y}]
(->Vector (+ x acc-x)
(+ y acc-y)))
args))
(defn subtract [{ax :x ay :y} & args]
"Subtract Vectors"
(let [{bx :x by :y} (apply add args)]
(->Vector (- ax bx)
(- ay by))))
(defn mult [{:keys [x y]} n]
"multiply the vector with a Number"
(->Vector (* n x)
(* n y)))
(defn div [{:keys [x y]} n]
"divide the vector with a Number"
(->Vector (/ x n)
(/ y n)))
(defn length-squared [{:keys [x y]}]
"return the length squared (for optimisation)"
(+ (sqr x)
(sqr y)))
(defn length [a]
"returns the length of the vector (Betrag)"
(.sqrt js/Math (length-squared a)))
(defn norm [a]
"returns the normalized vector (Length = 1)"
(if (= a v0)
a
(div a (length a))))
(defn dot [{ax :x ay :y} {bx :x by :y}]
"calculate the dot product or scalar product of two vectors"
(+ (* ax bx)
(* ay by)))
(defn collinear? [& args]
"determines if the given vectors are collinear"
(let [without-null (remove #(= % v0) args)] ;; Null-Vectors are collinear with everything. Just ignore them.
(apply almost= (map (fn [{:keys [x y]}] (/ x y)) without-null))))
(defn angle [{ax :x ay :y} {bx :x by :y}]
"angle between two vectors in clockwise direction"
(let [angle (- (atan2 ay ax)
(atan2 by bx))]
(+ angle (cond (< angle (- pi)) tau
(> angle pi) (- tau)
:else 0))))
; Vector/Kreuzprodukt only exists for 3d Space by definition
(defn project [a b]
"returns the component parallel to a given vector"
(let [u (norm b)]
(mult u (dot a u))))
(defn intersection [pa {ax :x ay :y} pb b]
"Calculates the intersection point of two lines
defined by vectors a and b and their position vectors (pa and pb)."
(let [{cx :x cy :y} (subtract pb pa)
{-bx :x -by :y :as -b} (mult b -1)
m (/ ay ax)
mu (/ (- cy (* m cx))
(- -by (* m -bx)))]
(subtract pb (mult -b mu))))
(defn intersect? [pa a pb b]
"return the intersection point (truthy) if the point lies on both a and b otherwise nil"
(let [x (intersection pa a pb b)
pa->x (subtract x pa)
pb->x (subtract x pb)]
(if (and (< (length-squared pa->x)
(length-squared a))
(= (quadrant pa->x) (quadrant a))
(< (length-squared pb->x)
(length-squared b))
(= (quadrant pb->x) (quadrant b)))
x
nil)))
| 118395 | (ns irf.vector)
;vector.cljs
;by <NAME> in June 2017
(defrecord Vector [x y])
(def v ->Vector)
(defn sqr [x] (js/Math.pow x 2))
(def abs js/Math.abs)
(def atan2 js/Math.atan2)
(def pi (.-PI js/Math))
(def tau (+ pi pi))
(def v0 (->Vector 0 0)) ;; null-vektor
(defn quadrant [{:keys [x y]}]
"which quadrant does a vector point to"
(case [(pos? x) (pos? y)]
[true true] 1
[true false] 2
[false false] 3
[false true] 4))
(defmulti almost= #(cond (number? %) :number
(instance? irf.vector/Vector %) :vector))
(defmethod almost= :number
[& args]
"approximate equality for numbers"
(let [mx (apply max args)
mn (apply min args)
e (/ (max (abs mn) (abs mx)) 1e10)]
(< (- mx mn) e)))
(defmethod almost= :vector
[& args]
"approximate equality for vectors"
(and (apply almost= (map :x args))
(apply almost= (map :y args))))
(defn add [& args]
"Add Vectors"
(reduce (fn [{x :x y :y} {acc-x :x acc-y :y}]
(->Vector (+ x acc-x)
(+ y acc-y)))
args))
(defn subtract [{ax :x ay :y} & args]
"Subtract Vectors"
(let [{bx :x by :y} (apply add args)]
(->Vector (- ax bx)
(- ay by))))
(defn mult [{:keys [x y]} n]
"multiply the vector with a Number"
(->Vector (* n x)
(* n y)))
(defn div [{:keys [x y]} n]
"divide the vector with a Number"
(->Vector (/ x n)
(/ y n)))
(defn length-squared [{:keys [x y]}]
"return the length squared (for optimisation)"
(+ (sqr x)
(sqr y)))
(defn length [a]
"returns the length of the vector (Betrag)"
(.sqrt js/Math (length-squared a)))
(defn norm [a]
"returns the normalized vector (Length = 1)"
(if (= a v0)
a
(div a (length a))))
(defn dot [{ax :x ay :y} {bx :x by :y}]
"calculate the dot product or scalar product of two vectors"
(+ (* ax bx)
(* ay by)))
(defn collinear? [& args]
"determines if the given vectors are collinear"
(let [without-null (remove #(= % v0) args)] ;; Null-Vectors are collinear with everything. Just ignore them.
(apply almost= (map (fn [{:keys [x y]}] (/ x y)) without-null))))
(defn angle [{ax :x ay :y} {bx :x by :y}]
"angle between two vectors in clockwise direction"
(let [angle (- (atan2 ay ax)
(atan2 by bx))]
(+ angle (cond (< angle (- pi)) tau
(> angle pi) (- tau)
:else 0))))
; Vector/Kreuzprodukt only exists for 3d Space by definition
(defn project [a b]
"returns the component parallel to a given vector"
(let [u (norm b)]
(mult u (dot a u))))
(defn intersection [pa {ax :x ay :y} pb b]
"Calculates the intersection point of two lines
defined by vectors a and b and their position vectors (pa and pb)."
(let [{cx :x cy :y} (subtract pb pa)
{-bx :x -by :y :as -b} (mult b -1)
m (/ ay ax)
mu (/ (- cy (* m cx))
(- -by (* m -bx)))]
(subtract pb (mult -b mu))))
(defn intersect? [pa a pb b]
"return the intersection point (truthy) if the point lies on both a and b otherwise nil"
(let [x (intersection pa a pb b)
pa->x (subtract x pa)
pb->x (subtract x pb)]
(if (and (< (length-squared pa->x)
(length-squared a))
(= (quadrant pa->x) (quadrant a))
(< (length-squared pb->x)
(length-squared b))
(= (quadrant pb->x) (quadrant b)))
x
nil)))
| true | (ns irf.vector)
;vector.cljs
;by PI:NAME:<NAME>END_PI in June 2017
(defrecord Vector [x y])
(def v ->Vector)
(defn sqr [x] (js/Math.pow x 2))
(def abs js/Math.abs)
(def atan2 js/Math.atan2)
(def pi (.-PI js/Math))
(def tau (+ pi pi))
(def v0 (->Vector 0 0)) ;; null-vektor
(defn quadrant [{:keys [x y]}]
"which quadrant does a vector point to"
(case [(pos? x) (pos? y)]
[true true] 1
[true false] 2
[false false] 3
[false true] 4))
(defmulti almost= #(cond (number? %) :number
(instance? irf.vector/Vector %) :vector))
(defmethod almost= :number
[& args]
"approximate equality for numbers"
(let [mx (apply max args)
mn (apply min args)
e (/ (max (abs mn) (abs mx)) 1e10)]
(< (- mx mn) e)))
(defmethod almost= :vector
[& args]
"approximate equality for vectors"
(and (apply almost= (map :x args))
(apply almost= (map :y args))))
(defn add [& args]
"Add Vectors"
(reduce (fn [{x :x y :y} {acc-x :x acc-y :y}]
(->Vector (+ x acc-x)
(+ y acc-y)))
args))
(defn subtract [{ax :x ay :y} & args]
"Subtract Vectors"
(let [{bx :x by :y} (apply add args)]
(->Vector (- ax bx)
(- ay by))))
(defn mult [{:keys [x y]} n]
"multiply the vector with a Number"
(->Vector (* n x)
(* n y)))
(defn div [{:keys [x y]} n]
"divide the vector with a Number"
(->Vector (/ x n)
(/ y n)))
(defn length-squared [{:keys [x y]}]
"return the length squared (for optimisation)"
(+ (sqr x)
(sqr y)))
(defn length [a]
"returns the length of the vector (Betrag)"
(.sqrt js/Math (length-squared a)))
(defn norm [a]
"returns the normalized vector (Length = 1)"
(if (= a v0)
a
(div a (length a))))
(defn dot [{ax :x ay :y} {bx :x by :y}]
"calculate the dot product or scalar product of two vectors"
(+ (* ax bx)
(* ay by)))
(defn collinear? [& args]
"determines if the given vectors are collinear"
(let [without-null (remove #(= % v0) args)] ;; Null-Vectors are collinear with everything. Just ignore them.
(apply almost= (map (fn [{:keys [x y]}] (/ x y)) without-null))))
(defn angle [{ax :x ay :y} {bx :x by :y}]
"angle between two vectors in clockwise direction"
(let [angle (- (atan2 ay ax)
(atan2 by bx))]
(+ angle (cond (< angle (- pi)) tau
(> angle pi) (- tau)
:else 0))))
; Vector/Kreuzprodukt only exists for 3d Space by definition
(defn project [a b]
"returns the component parallel to a given vector"
(let [u (norm b)]
(mult u (dot a u))))
(defn intersection [pa {ax :x ay :y} pb b]
"Calculates the intersection point of two lines
defined by vectors a and b and their position vectors (pa and pb)."
(let [{cx :x cy :y} (subtract pb pa)
{-bx :x -by :y :as -b} (mult b -1)
m (/ ay ax)
mu (/ (- cy (* m cx))
(- -by (* m -bx)))]
(subtract pb (mult -b mu))))
(defn intersect? [pa a pb b]
"return the intersection point (truthy) if the point lies on both a and b otherwise nil"
(let [x (intersection pa a pb b)
pa->x (subtract x pa)
pb->x (subtract x pb)]
(if (and (< (length-squared pa->x)
(length-squared a))
(= (quadrant pa->x) (quadrant a))
(< (length-squared pb->x)
(length-squared b))
(= (quadrant pb->x) (quadrant b)))
x
nil)))
|
[
{
"context": "for learning artificial neural networks?\")\r\n (a \"Ryszard Tadeusiewicz: Odkrywanie właściwości sieci neuronowych\")\r\n (m",
"end": 477,
"score": 0.9998593330383301,
"start": 457,
"tag": "NAME",
"value": "Ryszard Tadeusiewicz"
},
{
"context": "Odkrywanie właściwości sieci neuronowych\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: ",
"end": 549,
"score": 0.9998596906661987,
"start": 529,
"tag": "NAME",
"value": "Ryszard Tadeusiewicz"
},
{
"context": "i sieci neuronowych\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właśc",
"end": 565,
"score": 0.9998329877853394,
"start": 551,
"tag": "NAME",
"value": "Tomasz Gąciarz"
},
{
"context": "ych\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neur",
"end": 582,
"score": 0.9998294711112976,
"start": 567,
"tag": "NAME",
"value": "Barbara Borowik"
},
{
"context": "ard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neuronowych\"))\r\n\n(q",
"end": 597,
"score": 0.9998418688774109,
"start": 584,
"tag": "NAME",
"value": "Bartosz Leper"
},
{
"context": "ut vs. very complicated, different kinds\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: ",
"end": 3041,
"score": 0.9998599886894226,
"start": 3021,
"tag": "NAME",
"value": "Ryszard Tadeusiewicz"
},
{
"context": "ed, different kinds\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właśc",
"end": 3057,
"score": 0.9998534917831421,
"start": 3043,
"tag": "NAME",
"value": "Tomasz Gąciarz"
},
{
"context": "nds\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neur",
"end": 3074,
"score": 0.9998601078987122,
"start": 3059,
"tag": "NAME",
"value": "Barbara Borowik"
},
{
"context": "ard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neuronowych, ch.1.4",
"end": 3089,
"score": 0.9998683929443359,
"start": 3076,
"tag": "NAME",
"value": "Bartosz Leper"
},
{
"context": "\")\n (a \"each with each and zero weights\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: ",
"end": 3345,
"score": 0.9998735189437866,
"start": 3325,
"tag": "NAME",
"value": "Ryszard Tadeusiewicz"
},
{
"context": "ch and zero weights\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właśc",
"end": 3361,
"score": 0.9998621940612793,
"start": 3347,
"tag": "NAME",
"value": "Tomasz Gąciarz"
},
{
"context": "hts\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neur",
"end": 3378,
"score": 0.9998353719711304,
"start": 3363,
"tag": "NAME",
"value": "Barbara Borowik"
},
{
"context": "ard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neuronowych, ch.1.4",
"end": 3393,
"score": 0.9996089935302734,
"start": 3380,
"tag": "NAME",
"value": "Bartosz Leper"
},
{
"context": "l\")\n (a \"usually as specialized devices\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: ",
"end": 3748,
"score": 0.9998818635940552,
"start": 3728,
"tag": "NAME",
"value": "Ryszard Tadeusiewicz"
},
{
"context": "specialized devices\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właśc",
"end": 3764,
"score": 0.9998617172241211,
"start": 3750,
"tag": "NAME",
"value": "Tomasz Gąciarz"
},
{
"context": "ces\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neur",
"end": 3781,
"score": 0.9998489618301392,
"start": 3766,
"tag": "NAME",
"value": "Barbara Borowik"
},
{
"context": "ard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neuronowych, ch.1.9",
"end": 3796,
"score": 0.9996533393859863,
"start": 3783,
"tag": "NAME",
"value": "Bartosz Leper"
},
{
"context": "ki/Connectionism\n\n(qam\r\n (q \"\")\r\n (a \"\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: ",
"end": 5676,
"score": 0.9998769760131836,
"start": 5656,
"tag": "NAME",
"value": "Ryszard Tadeusiewicz"
},
{
"context": "m\r\n (q \"\")\r\n (a \"\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właśc",
"end": 5692,
"score": 0.9998501539230347,
"start": 5678,
"tag": "NAME",
"value": "Tomasz Gąciarz"
},
{
"context": "a \"\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neur",
"end": 5709,
"score": 0.9998568296432495,
"start": 5694,
"tag": "NAME",
"value": "Barbara Borowik"
},
{
"context": "ard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neuronowych\"))\r\n\n(q",
"end": 5724,
"score": 0.9989224672317505,
"start": 5711,
"tag": "NAME",
"value": "Bartosz Leper"
},
{
"context": " neuronowych\"))\r\n\n(qam\r\n (q \"\")\r\n (a \"\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: ",
"end": 5824,
"score": 0.9998723864555359,
"start": 5804,
"tag": "NAME",
"value": "Ryszard Tadeusiewicz"
},
{
"context": "m\r\n (q \"\")\r\n (a \"\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właśc",
"end": 5840,
"score": 0.999838650226593,
"start": 5826,
"tag": "NAME",
"value": "Tomasz Gąciarz"
},
{
"context": "a \"\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neur",
"end": 5857,
"score": 0.9998679161071777,
"start": 5842,
"tag": "NAME",
"value": "Barbara Borowik"
},
{
"context": "ard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neuronowych\"))\r\n\n(q",
"end": 5872,
"score": 0.9991340637207031,
"start": 5859,
"tag": "NAME",
"value": "Bartosz Leper"
},
{
"context": " neuronowych\"))\r\n\n(qam\r\n (q \"\")\r\n (a \"\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: ",
"end": 5972,
"score": 0.9998730421066284,
"start": 5952,
"tag": "NAME",
"value": "Ryszard Tadeusiewicz"
},
{
"context": "m\r\n (q \"\")\r\n (a \"\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właśc",
"end": 5988,
"score": 0.9998462796211243,
"start": 5974,
"tag": "NAME",
"value": "Tomasz Gąciarz"
},
{
"context": "a \"\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neur",
"end": 6005,
"score": 0.9998648762702942,
"start": 5990,
"tag": "NAME",
"value": "Barbara Borowik"
},
{
"context": "ard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neuronowych\"))\r\n\n(q",
"end": 6020,
"score": 0.9990324974060059,
"start": 6007,
"tag": "NAME",
"value": "Bartosz Leper"
},
{
"context": " neuronowych\"))\r\n\n(qam\r\n (q \"\")\r\n (a \"\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: ",
"end": 6120,
"score": 0.999873161315918,
"start": 6100,
"tag": "NAME",
"value": "Ryszard Tadeusiewicz"
},
{
"context": "m\r\n (q \"\")\r\n (a \"\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właśc",
"end": 6136,
"score": 0.9998646378517151,
"start": 6122,
"tag": "NAME",
"value": "Tomasz Gąciarz"
},
{
"context": "a \"\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neur",
"end": 6153,
"score": 0.9998553991317749,
"start": 6138,
"tag": "NAME",
"value": "Barbara Borowik"
},
{
"context": "ard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neuronowych\"))\r\n\n(q",
"end": 6168,
"score": 0.9992842674255371,
"start": 6155,
"tag": "NAME",
"value": "Bartosz Leper"
},
{
"context": " neuronowych\"))\r\n\n(qam\r\n (q \"\")\r\n (a \"\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: ",
"end": 6268,
"score": 0.9998751878738403,
"start": 6248,
"tag": "NAME",
"value": "Ryszard Tadeusiewicz"
},
{
"context": "m\r\n (q \"\")\r\n (a \"\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właśc",
"end": 6284,
"score": 0.9998564720153809,
"start": 6270,
"tag": "NAME",
"value": "Tomasz Gąciarz"
},
{
"context": "a \"\")\r\n (m \"Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neur",
"end": 6301,
"score": 0.9998553991317749,
"start": 6286,
"tag": "NAME",
"value": "Barbara Borowik"
},
{
"context": "ard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neuronowych\"))\r\n",
"end": 6316,
"score": 0.9939446449279785,
"start": 6303,
"tag": "NAME",
"value": "Bartosz Leper"
}
] | src/test/clojure/pl/tomaszgigiel/quizzes/packs/ann/01_ann_test.clj | tomaszgigiel/quizzes | 1 | (ns pl.tomaszgigiel.quizzes.packs.ann.01-ann-test
(:require [clojure.test :as tst])
(:require [pl.tomaszgigiel.quizzes.test-config :as test-config])
(:require [pl.tomaszgigiel.quizzes.quiz :refer [qam q a at m]])
(:require [pl.tomaszgigiel.utils.misc :as misc]))
(tst/use-fixtures :once test-config/once-fixture)
(tst/use-fixtures :each test-config/each-fixture)
(qam
(q "What is the best book for learning artificial neural networks?")
(a "Ryszard Tadeusiewicz: Odkrywanie właściwości sieci neuronowych")
(m "Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neuronowych"))
(qam
(q "What are artificial neural networks?")
(a "artificial neural networks or connectionist systems")
(a "computing systems inspired by the biological neural networks that constitute animal brains")
(m "https://en.wikipedia.org/wiki/Artificial_neural_network"))
(qam
(q "What does ANN stand for?")
(a "Artificial neural networks")
(m "https://en.wikipedia.org/wiki/Artificial_neural_network"))
(qam
(q "What are the advantages of artificial neural network?")
(a "ability to learn to perform tasks by considering examples, generally without being programmed with task-specific rules")
(m "https://en.wikipedia.org/wiki/Artificial_neural_network"))
(qam
(q "How are artificial neural networks built?")
(a "a collection of connected units")
(a "constructed from 3 type of layers: input layer, hidden layers, output layer")
(a "elementary unit is an artificial neuron")
(m "https://en.wikipedia.org/wiki/Artificial_neural_network"))
(qam
(q "What is learning in ANN?")
(a "the adaptation of the network to better handle a task by considering sample observations")
(m "https://en.wikipedia.org/wiki/Artificial_neural_network"))
(qam
(q "What does learning in ANN involve?")
(a "Learning ANN involves adjusting the weights (and optional thresholds) of the network to improve the accuracy of the result.")
(m "https://en.wikipedia.org/wiki/Artificial_neural_network"))
(qam
(q "What is an artificial neuron?")
(a "a mathematical function conceived as a model of a biological neuron")
(m "https://en.wikipedia.org/wiki/Artificial_neuron"))
(qam
(q "How are artificial (a real biological) neurons built?")
(a "a body in which computations are performed (soma)")
(a "a number of input channels (dendrites)")
(a "one output channel (a single axon)")
(m "https://en.wikipedia.org/wiki/Artificial_neuron"))
(qam
(q "How to model an artificial neuron?")
(a "(activation-function (reduce + (map * (conj inputs bias) (conj weights 1))))")
(m "https://en.wikipedia.org/wiki/Artificial_neuron"))
(qam
(q "Compare ann vs. brain")
(a "simplified structure: homogeneous, each with each vs. different ways of connecting in different places")
(a "simplified neuron: very simple, inputs, weights, activation function, output vs. very complicated, different kinds")
(m "Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neuronowych, ch.1.4"))
(qam
(q "Characterise heterogeneous neural networks")
(a "they learn faster then homogeneous")
(a "but how to design them?")
(a "each with each and zero weights")
(m "Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neuronowych, ch.1.4"))
(qam
(q "List the uses of artificial neural networks, but not in the field of artificial intelligence")
(a "massive parallel processing")
(a "the artificial neurons that make up the network perform calculations in parallel")
(a "usually as specialized devices")
(m "Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neuronowych, ch.1.9"))
; Every input has a weight associated with it; the larger the weight, the more impact the corresponding input channel has on the output.
; A neuron also has a bias, which, for convenience, can be considered as an additional input to the neuron, x0, that is equal to 1 and has the weight identical to the value of the bias, w0 = b.
; what is perceptron
; https://www.quora.com/What-does-weight-mean-in-terms-of-neural-networks
; Weights near zero means changing this input will not change the output. Negative weights mean increasing this input will decrease the output. A weight decides how much influence the input will have on the output.
; https://hackernoon.com/everything-you-need-to-know-about-neural-networks-8988c3ee4491
; https://towardsdatascience.com/the-differences-between-artificial-and-biological-neural-networks-a8b46db828b7
; https://towardsdatascience.com/deep-learning-versus-biological-neurons-floating-point-numbers-spikes-and-neurotransmitters-6eebfa3390e9
; https://miro.medium.com/max/1400/1*T4ARzySpEQvEnr_9pc78pg.jpeg
; https://en.wikipedia.org/wiki/Artificial_neuron
; An artificial neuron has a body in which computations are performed, and a number of input channels and one output channel, similar to a real biological neuron.
; https://www.sciencedirect.com/topics/earth-and-planetary-sciences/artificial-neural-network
; https://en.wikipedia.org/wiki/Biological_neuron_model
; https://en.wikipedia.org/wiki/Artificial_neuron
; https://en.wikipedia.org/wiki/Neuron
; https://en.wikipedia.org/wiki/Artificial_neural_network
; How do Artificial Neural Networks learn?
; bias
; positive weight
; negative weight
; https://en.wikipedia.org/wiki/Mathematics_of_artificial_neural_networks
; https://en.wikipedia.org/wiki/Connectionism
(qam
(q "")
(a "")
(m "Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neuronowych"))
(qam
(q "")
(a "")
(m "Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neuronowych"))
(qam
(q "")
(a "")
(m "Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neuronowych"))
(qam
(q "")
(a "")
(m "Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neuronowych"))
(qam
(q "")
(a "")
(m "Ryszard Tadeusiewicz, Tomasz Gąciarz, Barbara Borowik, Bartosz Leper: Odkrywanie właściwości sieci neuronowych"))
| 16300 | (ns pl.tomaszgigiel.quizzes.packs.ann.01-ann-test
(:require [clojure.test :as tst])
(:require [pl.tomaszgigiel.quizzes.test-config :as test-config])
(:require [pl.tomaszgigiel.quizzes.quiz :refer [qam q a at m]])
(:require [pl.tomaszgigiel.utils.misc :as misc]))
(tst/use-fixtures :once test-config/once-fixture)
(tst/use-fixtures :each test-config/each-fixture)
(qam
(q "What is the best book for learning artificial neural networks?")
(a "<NAME>: Odkrywanie właściwości sieci neuronowych")
(m "<NAME>, <NAME>, <NAME>, <NAME>: Odkrywanie właściwości sieci neuronowych"))
(qam
(q "What are artificial neural networks?")
(a "artificial neural networks or connectionist systems")
(a "computing systems inspired by the biological neural networks that constitute animal brains")
(m "https://en.wikipedia.org/wiki/Artificial_neural_network"))
(qam
(q "What does ANN stand for?")
(a "Artificial neural networks")
(m "https://en.wikipedia.org/wiki/Artificial_neural_network"))
(qam
(q "What are the advantages of artificial neural network?")
(a "ability to learn to perform tasks by considering examples, generally without being programmed with task-specific rules")
(m "https://en.wikipedia.org/wiki/Artificial_neural_network"))
(qam
(q "How are artificial neural networks built?")
(a "a collection of connected units")
(a "constructed from 3 type of layers: input layer, hidden layers, output layer")
(a "elementary unit is an artificial neuron")
(m "https://en.wikipedia.org/wiki/Artificial_neural_network"))
(qam
(q "What is learning in ANN?")
(a "the adaptation of the network to better handle a task by considering sample observations")
(m "https://en.wikipedia.org/wiki/Artificial_neural_network"))
(qam
(q "What does learning in ANN involve?")
(a "Learning ANN involves adjusting the weights (and optional thresholds) of the network to improve the accuracy of the result.")
(m "https://en.wikipedia.org/wiki/Artificial_neural_network"))
(qam
(q "What is an artificial neuron?")
(a "a mathematical function conceived as a model of a biological neuron")
(m "https://en.wikipedia.org/wiki/Artificial_neuron"))
(qam
(q "How are artificial (a real biological) neurons built?")
(a "a body in which computations are performed (soma)")
(a "a number of input channels (dendrites)")
(a "one output channel (a single axon)")
(m "https://en.wikipedia.org/wiki/Artificial_neuron"))
(qam
(q "How to model an artificial neuron?")
(a "(activation-function (reduce + (map * (conj inputs bias) (conj weights 1))))")
(m "https://en.wikipedia.org/wiki/Artificial_neuron"))
(qam
(q "Compare ann vs. brain")
(a "simplified structure: homogeneous, each with each vs. different ways of connecting in different places")
(a "simplified neuron: very simple, inputs, weights, activation function, output vs. very complicated, different kinds")
(m "<NAME>, <NAME>, <NAME>, <NAME>: Odkrywanie właściwości sieci neuronowych, ch.1.4"))
(qam
(q "Characterise heterogeneous neural networks")
(a "they learn faster then homogeneous")
(a "but how to design them?")
(a "each with each and zero weights")
(m "<NAME>, <NAME>, <NAME>, <NAME>: Odkrywanie właściwości sieci neuronowych, ch.1.4"))
(qam
(q "List the uses of artificial neural networks, but not in the field of artificial intelligence")
(a "massive parallel processing")
(a "the artificial neurons that make up the network perform calculations in parallel")
(a "usually as specialized devices")
(m "<NAME>, <NAME>, <NAME>, <NAME>: Odkrywanie właściwości sieci neuronowych, ch.1.9"))
; Every input has a weight associated with it; the larger the weight, the more impact the corresponding input channel has on the output.
; A neuron also has a bias, which, for convenience, can be considered as an additional input to the neuron, x0, that is equal to 1 and has the weight identical to the value of the bias, w0 = b.
; what is perceptron
; https://www.quora.com/What-does-weight-mean-in-terms-of-neural-networks
; Weights near zero means changing this input will not change the output. Negative weights mean increasing this input will decrease the output. A weight decides how much influence the input will have on the output.
; https://hackernoon.com/everything-you-need-to-know-about-neural-networks-8988c3ee4491
; https://towardsdatascience.com/the-differences-between-artificial-and-biological-neural-networks-a8b46db828b7
; https://towardsdatascience.com/deep-learning-versus-biological-neurons-floating-point-numbers-spikes-and-neurotransmitters-6eebfa3390e9
; https://miro.medium.com/max/1400/1*T4ARzySpEQvEnr_9pc78pg.jpeg
; https://en.wikipedia.org/wiki/Artificial_neuron
; An artificial neuron has a body in which computations are performed, and a number of input channels and one output channel, similar to a real biological neuron.
; https://www.sciencedirect.com/topics/earth-and-planetary-sciences/artificial-neural-network
; https://en.wikipedia.org/wiki/Biological_neuron_model
; https://en.wikipedia.org/wiki/Artificial_neuron
; https://en.wikipedia.org/wiki/Neuron
; https://en.wikipedia.org/wiki/Artificial_neural_network
; How do Artificial Neural Networks learn?
; bias
; positive weight
; negative weight
; https://en.wikipedia.org/wiki/Mathematics_of_artificial_neural_networks
; https://en.wikipedia.org/wiki/Connectionism
(qam
(q "")
(a "")
(m "<NAME>, <NAME>, <NAME>, <NAME>: Odkrywanie właściwości sieci neuronowych"))
(qam
(q "")
(a "")
(m "<NAME>, <NAME>, <NAME>, <NAME>: Odkrywanie właściwości sieci neuronowych"))
(qam
(q "")
(a "")
(m "<NAME>, <NAME>, <NAME>, <NAME>: Odkrywanie właściwości sieci neuronowych"))
(qam
(q "")
(a "")
(m "<NAME>, <NAME>, <NAME>, <NAME>: Odkrywanie właściwości sieci neuronowych"))
(qam
(q "")
(a "")
(m "<NAME>, <NAME>, <NAME>, <NAME>: Odkrywanie właściwości sieci neuronowych"))
| true | (ns pl.tomaszgigiel.quizzes.packs.ann.01-ann-test
(:require [clojure.test :as tst])
(:require [pl.tomaszgigiel.quizzes.test-config :as test-config])
(:require [pl.tomaszgigiel.quizzes.quiz :refer [qam q a at m]])
(:require [pl.tomaszgigiel.utils.misc :as misc]))
(tst/use-fixtures :once test-config/once-fixture)
(tst/use-fixtures :each test-config/each-fixture)
(qam
(q "What is the best book for learning artificial neural networks?")
(a "PI:NAME:<NAME>END_PI: Odkrywanie właściwości sieci neuronowych")
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: Odkrywanie właściwości sieci neuronowych"))
(qam
(q "What are artificial neural networks?")
(a "artificial neural networks or connectionist systems")
(a "computing systems inspired by the biological neural networks that constitute animal brains")
(m "https://en.wikipedia.org/wiki/Artificial_neural_network"))
(qam
(q "What does ANN stand for?")
(a "Artificial neural networks")
(m "https://en.wikipedia.org/wiki/Artificial_neural_network"))
(qam
(q "What are the advantages of artificial neural network?")
(a "ability to learn to perform tasks by considering examples, generally without being programmed with task-specific rules")
(m "https://en.wikipedia.org/wiki/Artificial_neural_network"))
(qam
(q "How are artificial neural networks built?")
(a "a collection of connected units")
(a "constructed from 3 type of layers: input layer, hidden layers, output layer")
(a "elementary unit is an artificial neuron")
(m "https://en.wikipedia.org/wiki/Artificial_neural_network"))
(qam
(q "What is learning in ANN?")
(a "the adaptation of the network to better handle a task by considering sample observations")
(m "https://en.wikipedia.org/wiki/Artificial_neural_network"))
(qam
(q "What does learning in ANN involve?")
(a "Learning ANN involves adjusting the weights (and optional thresholds) of the network to improve the accuracy of the result.")
(m "https://en.wikipedia.org/wiki/Artificial_neural_network"))
(qam
(q "What is an artificial neuron?")
(a "a mathematical function conceived as a model of a biological neuron")
(m "https://en.wikipedia.org/wiki/Artificial_neuron"))
(qam
(q "How are artificial (a real biological) neurons built?")
(a "a body in which computations are performed (soma)")
(a "a number of input channels (dendrites)")
(a "one output channel (a single axon)")
(m "https://en.wikipedia.org/wiki/Artificial_neuron"))
(qam
(q "How to model an artificial neuron?")
(a "(activation-function (reduce + (map * (conj inputs bias) (conj weights 1))))")
(m "https://en.wikipedia.org/wiki/Artificial_neuron"))
(qam
(q "Compare ann vs. brain")
(a "simplified structure: homogeneous, each with each vs. different ways of connecting in different places")
(a "simplified neuron: very simple, inputs, weights, activation function, output vs. very complicated, different kinds")
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: Odkrywanie właściwości sieci neuronowych, ch.1.4"))
(qam
(q "Characterise heterogeneous neural networks")
(a "they learn faster then homogeneous")
(a "but how to design them?")
(a "each with each and zero weights")
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: Odkrywanie właściwości sieci neuronowych, ch.1.4"))
(qam
(q "List the uses of artificial neural networks, but not in the field of artificial intelligence")
(a "massive parallel processing")
(a "the artificial neurons that make up the network perform calculations in parallel")
(a "usually as specialized devices")
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: Odkrywanie właściwości sieci neuronowych, ch.1.9"))
; Every input has a weight associated with it; the larger the weight, the more impact the corresponding input channel has on the output.
; A neuron also has a bias, which, for convenience, can be considered as an additional input to the neuron, x0, that is equal to 1 and has the weight identical to the value of the bias, w0 = b.
; what is perceptron
; https://www.quora.com/What-does-weight-mean-in-terms-of-neural-networks
; Weights near zero means changing this input will not change the output. Negative weights mean increasing this input will decrease the output. A weight decides how much influence the input will have on the output.
; https://hackernoon.com/everything-you-need-to-know-about-neural-networks-8988c3ee4491
; https://towardsdatascience.com/the-differences-between-artificial-and-biological-neural-networks-a8b46db828b7
; https://towardsdatascience.com/deep-learning-versus-biological-neurons-floating-point-numbers-spikes-and-neurotransmitters-6eebfa3390e9
; https://miro.medium.com/max/1400/1*T4ARzySpEQvEnr_9pc78pg.jpeg
; https://en.wikipedia.org/wiki/Artificial_neuron
; An artificial neuron has a body in which computations are performed, and a number of input channels and one output channel, similar to a real biological neuron.
; https://www.sciencedirect.com/topics/earth-and-planetary-sciences/artificial-neural-network
; https://en.wikipedia.org/wiki/Biological_neuron_model
; https://en.wikipedia.org/wiki/Artificial_neuron
; https://en.wikipedia.org/wiki/Neuron
; https://en.wikipedia.org/wiki/Artificial_neural_network
; How do Artificial Neural Networks learn?
; bias
; positive weight
; negative weight
; https://en.wikipedia.org/wiki/Mathematics_of_artificial_neural_networks
; https://en.wikipedia.org/wiki/Connectionism
(qam
(q "")
(a "")
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: Odkrywanie właściwości sieci neuronowych"))
(qam
(q "")
(a "")
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: Odkrywanie właściwości sieci neuronowych"))
(qam
(q "")
(a "")
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: Odkrywanie właściwości sieci neuronowych"))
(qam
(q "")
(a "")
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: Odkrywanie właściwości sieci neuronowych"))
(qam
(q "")
(a "")
(m "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI: Odkrywanie właściwości sieci neuronowych"))
|
[
{
"context": "(ns ^{:author \"Leeor Engel\"}\nchapter-2.chapter-2-q5\n (:require [data-struct",
"end": 26,
"score": 0.9998970031738281,
"start": 15,
"tag": "NAME",
"value": "Leeor Engel"
}
] | Clojure/src/chapter_2/chapter_2_q5.clj | Kiandr/crackingcodinginterview | 0 | (ns ^{:author "Leeor Engel"}
chapter-2.chapter-2-q5
(:require [data-structures.linked-list :refer :all]))
(defn- next-sum
([n1 n2]
(next-sum n1 n2 0))
([n1 n2 carry-over]
(let [n1-data (if (nil? n1) 0 n1)
n2-data (if (nil? n2) 0 n2)]
(+ n1-data n2-data carry-over))))
(defn- get-high-digit [sum]
(let [remainder (mod sum 10)]
(/ (- sum remainder) 10)))
;;
;; Solution 1
;;
(defn- map-all [f c1 c2]
"like 3-arity map, but continues to consume until all are exhausted. nil's are passed for exhausted lists."
(lazy-seq
(let [s1 (seq c1) s2 (seq c2)]
(when (or s1 s2)
(cons (f (first s1) (first s2))
(map-all f (rest s1) (rest s2)))))))
(defn sum-lists [l1 l2]
(let [steps (reductions (fn [[sum-list carry-over] [digit-1 digit-2]]
(let [sum (next-sum digit-1 digit-2 carry-over)
remainder (mod sum 10)]
[(conj sum-list remainder) (get-high-digit sum)]))
['() 0]
(map-all vector l1 l2))
sum-list (map first (map first (rest steps)))
[_ carry-over] (last steps)]
(if (pos? carry-over)
(cons carry-over sum-list)
sum-list)))
;;;;
;; Follow Up - Solution 1: pad and recurse add
;;;;
(defn- zero-pad-left [l length to-len]
(let [num-to-pad (- to-len length)]
(concat (repeat num-to-pad 0) l)))
(defn sum-lists-forward [l1 l2]
(let [l1-len (count l1) l2-len (count l2)
max-len (max l1-len l2-len)
normalized-l1 (zero-pad-left l1 l1-len max-len)
normalized-l2 (zero-pad-left l2 l2-len max-len)
steps (reductions (fn [[sum-list carry-over] [digit-1 digit-2]]
(let [sum (next-sum digit-1 digit-2)
low-digit (mod sum 10)
high-digit (get-high-digit sum)
sum-with-carry (+ carry-over high-digit)
new-sum-list (if (pos? sum-with-carry)
(conj sum-list sum-with-carry)
sum-list)]
[new-sum-list low-digit]))
['() 0]
(map vector normalized-l1 normalized-l2))
digits-no-carry-over (map first (rest steps))
sum-list (filter some? (map first digits-no-carry-over))
[_ carry-over] (last steps)]
(if (pos? carry-over)
(concat sum-list (list carry-over))
sum-list)))
;;;;
;; Follow Up - Solution 2: string concatenation and conversion to/from integers
;;;;
(defn- num-list-as-str [l] (apply str l))
(defn sum-lists-forward-concat [l1 l2]
(let [num-1 (Integer/parseInt (num-list-as-str l1))
num-2 (Integer/parseInt (num-list-as-str l2))
sum (+ num-1 num-2)]
(apply create-linked-list (vector (map #(Integer/parseInt (str %)) (str sum))))))
| 106089 | (ns ^{:author "<NAME>"}
chapter-2.chapter-2-q5
(:require [data-structures.linked-list :refer :all]))
(defn- next-sum
([n1 n2]
(next-sum n1 n2 0))
([n1 n2 carry-over]
(let [n1-data (if (nil? n1) 0 n1)
n2-data (if (nil? n2) 0 n2)]
(+ n1-data n2-data carry-over))))
(defn- get-high-digit [sum]
(let [remainder (mod sum 10)]
(/ (- sum remainder) 10)))
;;
;; Solution 1
;;
(defn- map-all [f c1 c2]
"like 3-arity map, but continues to consume until all are exhausted. nil's are passed for exhausted lists."
(lazy-seq
(let [s1 (seq c1) s2 (seq c2)]
(when (or s1 s2)
(cons (f (first s1) (first s2))
(map-all f (rest s1) (rest s2)))))))
(defn sum-lists [l1 l2]
(let [steps (reductions (fn [[sum-list carry-over] [digit-1 digit-2]]
(let [sum (next-sum digit-1 digit-2 carry-over)
remainder (mod sum 10)]
[(conj sum-list remainder) (get-high-digit sum)]))
['() 0]
(map-all vector l1 l2))
sum-list (map first (map first (rest steps)))
[_ carry-over] (last steps)]
(if (pos? carry-over)
(cons carry-over sum-list)
sum-list)))
;;;;
;; Follow Up - Solution 1: pad and recurse add
;;;;
(defn- zero-pad-left [l length to-len]
(let [num-to-pad (- to-len length)]
(concat (repeat num-to-pad 0) l)))
(defn sum-lists-forward [l1 l2]
(let [l1-len (count l1) l2-len (count l2)
max-len (max l1-len l2-len)
normalized-l1 (zero-pad-left l1 l1-len max-len)
normalized-l2 (zero-pad-left l2 l2-len max-len)
steps (reductions (fn [[sum-list carry-over] [digit-1 digit-2]]
(let [sum (next-sum digit-1 digit-2)
low-digit (mod sum 10)
high-digit (get-high-digit sum)
sum-with-carry (+ carry-over high-digit)
new-sum-list (if (pos? sum-with-carry)
(conj sum-list sum-with-carry)
sum-list)]
[new-sum-list low-digit]))
['() 0]
(map vector normalized-l1 normalized-l2))
digits-no-carry-over (map first (rest steps))
sum-list (filter some? (map first digits-no-carry-over))
[_ carry-over] (last steps)]
(if (pos? carry-over)
(concat sum-list (list carry-over))
sum-list)))
;;;;
;; Follow Up - Solution 2: string concatenation and conversion to/from integers
;;;;
(defn- num-list-as-str [l] (apply str l))
(defn sum-lists-forward-concat [l1 l2]
(let [num-1 (Integer/parseInt (num-list-as-str l1))
num-2 (Integer/parseInt (num-list-as-str l2))
sum (+ num-1 num-2)]
(apply create-linked-list (vector (map #(Integer/parseInt (str %)) (str sum))))))
| true | (ns ^{:author "PI:NAME:<NAME>END_PI"}
chapter-2.chapter-2-q5
(:require [data-structures.linked-list :refer :all]))
(defn- next-sum
([n1 n2]
(next-sum n1 n2 0))
([n1 n2 carry-over]
(let [n1-data (if (nil? n1) 0 n1)
n2-data (if (nil? n2) 0 n2)]
(+ n1-data n2-data carry-over))))
(defn- get-high-digit [sum]
(let [remainder (mod sum 10)]
(/ (- sum remainder) 10)))
;;
;; Solution 1
;;
(defn- map-all [f c1 c2]
"like 3-arity map, but continues to consume until all are exhausted. nil's are passed for exhausted lists."
(lazy-seq
(let [s1 (seq c1) s2 (seq c2)]
(when (or s1 s2)
(cons (f (first s1) (first s2))
(map-all f (rest s1) (rest s2)))))))
(defn sum-lists [l1 l2]
(let [steps (reductions (fn [[sum-list carry-over] [digit-1 digit-2]]
(let [sum (next-sum digit-1 digit-2 carry-over)
remainder (mod sum 10)]
[(conj sum-list remainder) (get-high-digit sum)]))
['() 0]
(map-all vector l1 l2))
sum-list (map first (map first (rest steps)))
[_ carry-over] (last steps)]
(if (pos? carry-over)
(cons carry-over sum-list)
sum-list)))
;;;;
;; Follow Up - Solution 1: pad and recurse add
;;;;
(defn- zero-pad-left [l length to-len]
(let [num-to-pad (- to-len length)]
(concat (repeat num-to-pad 0) l)))
(defn sum-lists-forward [l1 l2]
(let [l1-len (count l1) l2-len (count l2)
max-len (max l1-len l2-len)
normalized-l1 (zero-pad-left l1 l1-len max-len)
normalized-l2 (zero-pad-left l2 l2-len max-len)
steps (reductions (fn [[sum-list carry-over] [digit-1 digit-2]]
(let [sum (next-sum digit-1 digit-2)
low-digit (mod sum 10)
high-digit (get-high-digit sum)
sum-with-carry (+ carry-over high-digit)
new-sum-list (if (pos? sum-with-carry)
(conj sum-list sum-with-carry)
sum-list)]
[new-sum-list low-digit]))
['() 0]
(map vector normalized-l1 normalized-l2))
digits-no-carry-over (map first (rest steps))
sum-list (filter some? (map first digits-no-carry-over))
[_ carry-over] (last steps)]
(if (pos? carry-over)
(concat sum-list (list carry-over))
sum-list)))
;;;;
;; Follow Up - Solution 2: string concatenation and conversion to/from integers
;;;;
(defn- num-list-as-str [l] (apply str l))
(defn sum-lists-forward-concat [l1 l2]
(let [num-1 (Integer/parseInt (num-list-as-str l1))
num-2 (Integer/parseInt (num-list-as-str l2))
sum (+ num-1 num-2)]
(apply create-linked-list (vector (map #(Integer/parseInt (str %)) (str sum))))))
|
[
{
"context": "app-state\n (rc/atom\n {:contacts \n [{:first \"Ben\" :last \"Bitdiddle\" :email \"benb@mit.edu\"}\n {:",
"end": 420,
"score": 0.9998175501823425,
"start": 417,
"tag": "NAME",
"value": "Ben"
},
{
"context": "(rc/atom\n {:contacts \n [{:first \"Ben\" :last \"Bitdiddle\" :email \"benb@mit.edu\"}\n {:first \"Alyssa\" :mi",
"end": 438,
"score": 0.9990151524543762,
"start": 429,
"tag": "NAME",
"value": "Bitdiddle"
},
{
"context": "cts \n [{:first \"Ben\" :last \"Bitdiddle\" :email \"benb@mit.edu\"}\n {:first \"Alyssa\" :middle-initial \"P\" :last",
"end": 460,
"score": 0.999928891658783,
"start": 448,
"tag": "EMAIL",
"value": "benb@mit.edu"
},
{
"context": " \"Bitdiddle\" :email \"benb@mit.edu\"}\n {:first \"Alyssa\" :middle-initial \"P\" :last \"Hacker\" :email \"aphac",
"end": 483,
"score": 0.9996535181999207,
"start": 477,
"tag": "NAME",
"value": "Alyssa"
},
{
"context": "\n {:first \"Alyssa\" :middle-initial \"P\" :last \"Hacker\" :email \"aphacker@mit.edu\"}\n {:first \"Eval\" :",
"end": 518,
"score": 0.9989795684814453,
"start": 512,
"tag": "NAME",
"value": "Hacker"
},
{
"context": "lyssa\" :middle-initial \"P\" :last \"Hacker\" :email \"aphacker@mit.edu\"}\n {:first \"Eval\" :middle \"Lu\" :last \"Ator\" :",
"end": 544,
"score": 0.9999256134033203,
"start": 528,
"tag": "EMAIL",
"value": "aphacker@mit.edu"
},
{
"context": "\"Hacker\" :email \"aphacker@mit.edu\"}\n {:first \"Eval\" :middle \"Lu\" :last \"Ator\" :email \"eval@mit.edu\"}",
"end": 565,
"score": 0.9984233379364014,
"start": 561,
"tag": "NAME",
"value": "Eval"
},
{
"context": "mit.edu\"}\n {:first \"Eval\" :middle \"Lu\" :last \"Ator\" :email \"eval@mit.edu\"}\n {:first \"Louis\" :las",
"end": 591,
"score": 0.9680824279785156,
"start": 587,
"tag": "NAME",
"value": "Ator"
},
{
"context": " {:first \"Eval\" :middle \"Lu\" :last \"Ator\" :email \"eval@mit.edu\"}\n {:first \"Louis\" :last \"Reasoner\" :email \"p",
"end": 613,
"score": 0.9999186396598816,
"start": 601,
"tag": "EMAIL",
"value": "eval@mit.edu"
},
{
"context": ":last \"Ator\" :email \"eval@mit.edu\"}\n {:first \"Louis\" :last \"Reasoner\" :email \"prolog@mit.edu\"}\n {",
"end": 635,
"score": 0.9996417164802551,
"start": 630,
"tag": "NAME",
"value": "Louis"
},
{
"context": "email \"eval@mit.edu\"}\n {:first \"Louis\" :last \"Reasoner\" :email \"prolog@mit.edu\"}\n {:first \"Cy\" :midd",
"end": 652,
"score": 0.9936841726303101,
"start": 644,
"tag": "NAME",
"value": "Reasoner"
},
{
"context": "u\"}\n {:first \"Louis\" :last \"Reasoner\" :email \"prolog@mit.edu\"}\n {:first \"Cy\" :middle-initial \"D\" :last \"Ef",
"end": 676,
"score": 0.999920666217804,
"start": 662,
"tag": "EMAIL",
"value": "prolog@mit.edu"
},
{
"context": "\"Reasoner\" :email \"prolog@mit.edu\"}\n {:first \"Cy\" :middle-initial \"D\" :last \"Effect\" :email \"bugs@",
"end": 695,
"score": 0.9994744658470154,
"start": 693,
"tag": "NAME",
"value": "Cy"
},
{
"context": "olog@mit.edu\"}\n {:first \"Cy\" :middle-initial \"D\" :last \"Effect\" :email \"bugs@mit.edu\"}\n {:fir",
"end": 715,
"score": 0.6997922658920288,
"start": 714,
"tag": "NAME",
"value": "D"
},
{
"context": "du\"}\n {:first \"Cy\" :middle-initial \"D\" :last \"Effect\" :email \"bugs@mit.edu\"}\n {:first \"Lem\" :middl",
"end": 730,
"score": 0.9760984182357788,
"start": 724,
"tag": "NAME",
"value": "Effect"
},
{
"context": "t \"Cy\" :middle-initial \"D\" :last \"Effect\" :email \"bugs@mit.edu\"}\n {:first \"Lem\" :middle-initial \"E\" :last \"T",
"end": 752,
"score": 0.9999200701713562,
"start": 740,
"tag": "EMAIL",
"value": "bugs@mit.edu"
},
{
"context": "ast \"Effect\" :email \"bugs@mit.edu\"}\n {:first \"Lem\" :middle-initial \"E\" :last \"Tweakit\" :email \"more",
"end": 772,
"score": 0.999213457107544,
"start": 769,
"tag": "NAME",
"value": "Lem"
},
{
"context": "u\"}\n {:first \"Lem\" :middle-initial \"E\" :last \"Tweakit\" :email \"morebugs@mit.edu\"}]}))\n\n\n(defn middle-na",
"end": 808,
"score": 0.9984148144721985,
"start": 801,
"tag": "NAME",
"value": "Tweakit"
},
{
"context": "\"Lem\" :middle-initial \"E\" :last \"Tweakit\" :email \"morebugs@mit.edu\"}]}))\n\n\n(defn middle-name [{:keys [middle middle-",
"end": 834,
"score": 0.9999197125434875,
"start": 818,
"tag": "EMAIL",
"value": "morebugs@mit.edu"
},
{
"context": "input {:type \"text\"\n :placeholder \"Contact Name\"\n :value @value\n :o",
"end": 2551,
"score": 0.9697761535644531,
"start": 2539,
"tag": "NAME",
"value": "Contact Name"
}
] | src/reagent_tutorial/core.cljs | mrwizard82d1/reagent-tutorial | 0 | (ns reagent-tutorial.core
(:require [reagent.core :as rc :refer [atom]]
[goog.crypt :as crypt]
[goog.crypt.base64 :as base64]
[clojure.string :as str]))
(enable-console-print!)
(println "Edits to this text should show up in your developer console.")
;; define your app data so that it doesn't get over-written on reload
(def app-state
(rc/atom
{:contacts
[{:first "Ben" :last "Bitdiddle" :email "benb@mit.edu"}
{:first "Alyssa" :middle-initial "P" :last "Hacker" :email "aphacker@mit.edu"}
{:first "Eval" :middle "Lu" :last "Ator" :email "eval@mit.edu"}
{:first "Louis" :last "Reasoner" :email "prolog@mit.edu"}
{:first "Cy" :middle-initial "D" :last "Effect" :email "bugs@mit.edu"}
{:first "Lem" :middle-initial "E" :last "Tweakit" :email "morebugs@mit.edu"}]}))
(defn middle-name [{:keys [middle middle-initial]}]
(cond
middle middle
middle-initial (str middle-initial ".")))
(defn display-name [{:keys [first, last] :as contact}]
(str last ", " first " " (middle-name contact)))
(defn parse-contact [contact-as-text]
(let [[first middle last] (str/split contact-as-text #"\s+")]
(cond
(every? nil? [first middle last])
nil
(and (nil? middle) (nil? last))
{:first first}
(nil? last)
{:first first :last middle}
(str/ends-with? middle ".")
{:first first :middle-initial (str/replace middle "." "") :last last}
:else
{:first first :middle middle :last last})))
(defn remove-contact! [c]
(println "Remove contact" c)
(swap! app-state update-in [:contacts] (fn [contacts]
(vec (remove #(= c %) contacts)))))
(defn add-contact! [c]
(println "Add contact" c)
(swap! app-state update-in [:contacts] (fn [contacts]
(conj contacts c))))
(defn gen-key-map [c]
"Generate a key map for a contact used to identify the contact in the application state."
(let [hasher (crypt/Sha256.)]
(.update hasher (display-name c))
{:key (base64/encodeByteArray (.digest hasher))}))
(defn contact [c]
"Returns the component presenting a single contact."
(with-meta (vector :li
[:span (display-name c)]
[:button
{:on-click #(remove-contact! c)}
"Delete"]) (gen-key-map c)))
(defn new-contact []
(let [value (rc/atom "")]
(fn []
[:div
[:input {:type "text"
:placeholder "Contact Name"
:value @value
:on-change #(reset! value (-> % .-target .-value))}]
[:button {:on-click #(when-let [c (parse-contact @value)]
(add-contact! c)
(reset! value ""))}
"Add"]])))
(defn contacts []
[:div
[:h2 "Contact List"]
[:ul
(map contact (:contacts @app-state))]
[new-contact]])
(rc/render-component [contacts]
(. js/document (getElementById "contacts")))
(defn on-js-reload []
;; optionally touch your app-state to force rerendering depending on
;; your application
;; (swap! app-state update-in [:__figwheel_counter] inc)
)
| 22908 | (ns reagent-tutorial.core
(:require [reagent.core :as rc :refer [atom]]
[goog.crypt :as crypt]
[goog.crypt.base64 :as base64]
[clojure.string :as str]))
(enable-console-print!)
(println "Edits to this text should show up in your developer console.")
;; define your app data so that it doesn't get over-written on reload
(def app-state
(rc/atom
{:contacts
[{:first "<NAME>" :last "<NAME>" :email "<EMAIL>"}
{:first "<NAME>" :middle-initial "P" :last "<NAME>" :email "<EMAIL>"}
{:first "<NAME>" :middle "Lu" :last "<NAME>" :email "<EMAIL>"}
{:first "<NAME>" :last "<NAME>" :email "<EMAIL>"}
{:first "<NAME>" :middle-initial "<NAME>" :last "<NAME>" :email "<EMAIL>"}
{:first "<NAME>" :middle-initial "E" :last "<NAME>" :email "<EMAIL>"}]}))
(defn middle-name [{:keys [middle middle-initial]}]
(cond
middle middle
middle-initial (str middle-initial ".")))
(defn display-name [{:keys [first, last] :as contact}]
(str last ", " first " " (middle-name contact)))
(defn parse-contact [contact-as-text]
(let [[first middle last] (str/split contact-as-text #"\s+")]
(cond
(every? nil? [first middle last])
nil
(and (nil? middle) (nil? last))
{:first first}
(nil? last)
{:first first :last middle}
(str/ends-with? middle ".")
{:first first :middle-initial (str/replace middle "." "") :last last}
:else
{:first first :middle middle :last last})))
(defn remove-contact! [c]
(println "Remove contact" c)
(swap! app-state update-in [:contacts] (fn [contacts]
(vec (remove #(= c %) contacts)))))
(defn add-contact! [c]
(println "Add contact" c)
(swap! app-state update-in [:contacts] (fn [contacts]
(conj contacts c))))
(defn gen-key-map [c]
"Generate a key map for a contact used to identify the contact in the application state."
(let [hasher (crypt/Sha256.)]
(.update hasher (display-name c))
{:key (base64/encodeByteArray (.digest hasher))}))
(defn contact [c]
"Returns the component presenting a single contact."
(with-meta (vector :li
[:span (display-name c)]
[:button
{:on-click #(remove-contact! c)}
"Delete"]) (gen-key-map c)))
(defn new-contact []
(let [value (rc/atom "")]
(fn []
[:div
[:input {:type "text"
:placeholder "<NAME>"
:value @value
:on-change #(reset! value (-> % .-target .-value))}]
[:button {:on-click #(when-let [c (parse-contact @value)]
(add-contact! c)
(reset! value ""))}
"Add"]])))
(defn contacts []
[:div
[:h2 "Contact List"]
[:ul
(map contact (:contacts @app-state))]
[new-contact]])
(rc/render-component [contacts]
(. js/document (getElementById "contacts")))
(defn on-js-reload []
;; optionally touch your app-state to force rerendering depending on
;; your application
;; (swap! app-state update-in [:__figwheel_counter] inc)
)
| true | (ns reagent-tutorial.core
(:require [reagent.core :as rc :refer [atom]]
[goog.crypt :as crypt]
[goog.crypt.base64 :as base64]
[clojure.string :as str]))
(enable-console-print!)
(println "Edits to this text should show up in your developer console.")
;; define your app data so that it doesn't get over-written on reload
(def app-state
(rc/atom
{:contacts
[{:first "PI:NAME:<NAME>END_PI" :last "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}
{:first "PI:NAME:<NAME>END_PI" :middle-initial "P" :last "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}
{:first "PI:NAME:<NAME>END_PI" :middle "Lu" :last "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}
{:first "PI:NAME:<NAME>END_PI" :last "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}
{:first "PI:NAME:<NAME>END_PI" :middle-initial "PI:NAME:<NAME>END_PI" :last "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}
{:first "PI:NAME:<NAME>END_PI" :middle-initial "E" :last "PI:NAME:<NAME>END_PI" :email "PI:EMAIL:<EMAIL>END_PI"}]}))
(defn middle-name [{:keys [middle middle-initial]}]
(cond
middle middle
middle-initial (str middle-initial ".")))
(defn display-name [{:keys [first, last] :as contact}]
(str last ", " first " " (middle-name contact)))
(defn parse-contact [contact-as-text]
(let [[first middle last] (str/split contact-as-text #"\s+")]
(cond
(every? nil? [first middle last])
nil
(and (nil? middle) (nil? last))
{:first first}
(nil? last)
{:first first :last middle}
(str/ends-with? middle ".")
{:first first :middle-initial (str/replace middle "." "") :last last}
:else
{:first first :middle middle :last last})))
(defn remove-contact! [c]
(println "Remove contact" c)
(swap! app-state update-in [:contacts] (fn [contacts]
(vec (remove #(= c %) contacts)))))
(defn add-contact! [c]
(println "Add contact" c)
(swap! app-state update-in [:contacts] (fn [contacts]
(conj contacts c))))
(defn gen-key-map [c]
"Generate a key map for a contact used to identify the contact in the application state."
(let [hasher (crypt/Sha256.)]
(.update hasher (display-name c))
{:key (base64/encodeByteArray (.digest hasher))}))
(defn contact [c]
"Returns the component presenting a single contact."
(with-meta (vector :li
[:span (display-name c)]
[:button
{:on-click #(remove-contact! c)}
"Delete"]) (gen-key-map c)))
(defn new-contact []
(let [value (rc/atom "")]
(fn []
[:div
[:input {:type "text"
:placeholder "PI:NAME:<NAME>END_PI"
:value @value
:on-change #(reset! value (-> % .-target .-value))}]
[:button {:on-click #(when-let [c (parse-contact @value)]
(add-contact! c)
(reset! value ""))}
"Add"]])))
(defn contacts []
[:div
[:h2 "Contact List"]
[:ul
(map contact (:contacts @app-state))]
[new-contact]])
(rc/render-component [contacts]
(. js/document (getElementById "contacts")))
(defn on-js-reload []
;; optionally touch your app-state to force rerendering depending on
;; your application
;; (swap! app-state update-in [:__figwheel_counter] inc)
)
|
[
{
"context": "! *unchecked-math* :warn-on-boxed)\n(ns ^{:author \"palisades dot lakes at gmail dot com\"\n :date \"2017-12-06\"\n :doc \"Unit tests ",
"end": 123,
"score": 0.9323030114173889,
"start": 87,
"tag": "EMAIL",
"value": "palisades dot lakes at gmail dot com"
}
] | src/test/clojure/zana/test/prob/measure.clj | wahpenayo/zana | 2 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "palisades dot lakes at gmail dot com"
:date "2017-12-06"
:doc "Unit tests for zana.prob.measure."}
zana.test.prob.measure
(:require [clojure.string :as s]
[clojure.java.io :as io]
[clojure.test :as test]
[zana.prob.measure :as zpm]
[zana.api :as z])
(:import [java.util Arrays]
[zana.java.prob WEPDF]))
;; mvn -Dtest=zana.test.prob.measure clojure:test
;; TODO: randomized data for larger tests
;;----------------------------------------------------------------
(def nss (str *ns*))
(defn setup [tests]
(def z0 (float-array
[1.0 2.0 3.0 1.0 3.0 5.0 4.0 1.0 5.0]))
(def ^double n0 (double (alength ^floats z0)))
(def w0 (float-array n0 1.0))
(def z1 (float-array [1.0 2.0 3.0 4.0 5.0]))
(def w1 (float-array [3.0 1.0 2.0 1.0 2.0]))
(def pdf0 (z/make-wepdf z0 w0))
(def pdf1 (z/make-wepdf z0))
(def pdf2 (WEPDF/average [pdf0 pdf1]))
(def pdf3 (WEPDF/average [pdf0 pdf1 pdf2]))
(def pdf4 (WEPDF/average
[(z/make-wepdf (float-array [1.0 2.0 3.0]))
(z/make-wepdf (float-array [1.0 3.0 5.0]))
(z/make-wepdf (float-array [4.0 1.0 5.0]))]))
(def cdf5 (z/make-wecdf z0 w0))
(def cdf6 (z/make-wecdf z0))
(def cdf7 (z/wepdf-to-wecdf pdf1))
(def pdf8 (z/wecdf-to-wepdf cdf6))
(def rpms [pdf0 pdf1 pdf2 pdf3 pdf4 cdf5 cdf6 cdf7 pdf8])
(tests))
(test/use-fixtures :once setup)
;;----------------------------------------------------------------
(test/deftest make
(test/is (z/approximatelyEqual pdf0 pdf1 pdf2 pdf3 pdf4 pdf8)
#_(str "\n0 " pdf0 "\n1 " pdf1
"\n2 " pdf2 "\n3 " pdf3
"\n4 " pdf4 "\n5 " pdf8
))
(test/is (z/approximatelyEqual cdf5 cdf6 cdf7)
#_(str "\n" cdf5 "\n" cdf6 "\n" cdf7)))
;;----------------------------------------------------------------
(defn- serialization-test [rpm i]
(let [tokens (s/split nss #"\.")
folder (apply io/file "tst" tokens)
filename (str (.getSimpleName (class rpm)) i)
#_(println filename)
edn-file (io/file folder (str filename ".edn.gz"))
_ (io/make-parents edn-file)
_ (z/write-edn rpm edn-file)
;;_ (taiga/pprint-model model pretty-file)
edn-rpm (z/read-edn edn-file)]
(test/is (= rpm edn-rpm))))
(test/deftest serialization
(z/mapc serialization-test rpms (range (count rpms))))
;;----------------------------------------------------------------
;; TODO: better sum algorithm in cdf to get rid of z/approximately==
(test/deftest quantile
(let [n0 (double n0)]
(doseq [rpm rpms]
#_(dotimes [i 5]
(let [zi (aget z1 i)
wi (aget w1 i)
pi (z/cdf rpm zi)]
(println i zi wi pi (z/quantile rpm pi))))
(test/is (== Double/NEGATIVE_INFINITY
(z/quantile rpm (float 0.0))))
(test/is (== 1.0 (z/quantile rpm (float (/ 1.0 n0)))))
(test/is (== 1.0 (z/quantile rpm (float (/ 2.0 n0)))))
(test/is (== 1.0 (z/quantile rpm (/ 3.0 n0)))
(print-str (/ 3.0 n0) (class rpm) rpm))
(test/is (== 2.0 (z/quantile rpm (float (/ 3.5 n0)))))
(test/is (== 2.0 (z/quantile rpm (float (/ 4.0 n0)))))
(test/is (== 3.0 (z/quantile rpm (float (/ 5.0 n0)))))
(test/is (== 3.0 (z/quantile rpm (float (/ 6.0 n0)))))
(test/is (== 4.0 (z/quantile rpm (float (/ 6.5 n0)))))
(test/is (== 4.0 (z/quantile rpm (float (/ 7.0 n0)))))
(test/is (== 5.0 (z/quantile rpm (float (/ 8.0 n0)))))
(test/is (== 5.0 (z/quantile rpm (float (/ 9.0 n0)))))
(test/is (== 5.0 (z/quantile rpm (float 1.0)))))))
;;----------------------------------------------------------------
;; TODO: better sum algorithm in cdf to get rid of z/approximately==
(test/deftest pointmass
(let [n0 (double n0)]
(doseq [rpm rpms]
#_(println rpm)
(test/is (== 0.0 (z/pointmass rpm -1.0)))
(test/is (== 0.0 (z/pointmass rpm 0.0)))
(test/is (z/float-approximately==
(float (/ 3.0 n0))
(float (z/pointmass rpm 1.0))))
(test/is (== 0.0 (z/pointmass rpm 1.5)))
(test/is (z/float-approximately==
(float (/ 1.0 n0))
(float (z/pointmass rpm 2.0))))
(test/is (z/float-approximately==
(float (/ 2.0 n0))
(float (z/pointmass rpm 3.0))))
(test/is (z/float-approximately==
(float (/ 1.0 n0))
(float (z/pointmass rpm 4.0))))
(test/is (z/float-approximately==
(float (/ 2.0 n0))
(float (z/pointmass rpm 5.0))))
(test/is (== 0.0 (z/pointmass rpm 6.0))))))
;;----------------------------------------------------------------
;; TODO: better sum algorithm in cdf to get rid of z/approximately==
(test/deftest cdf
(let [n0 (double n0)]
(doseq [rpm rpms]
(test/is (== 0.0 (z/cdf rpm -1.0)))
(test/is (== 0.0 (z/cdf rpm 0.0)))
(test/is (z/float-approximately==
(float (/ 3.0 n0))
(float (z/cdf rpm 1.0))))
(test/is (z/float-approximately==
(float (/ 3.0 n0) )
(float (z/cdf rpm 1.5))))
(test/is (z/float-approximately==
(float (/ 4.0 n0) )
(float (z/cdf rpm 2.0))))
(test/is (z/float-approximately==
(float (/ 6.0 n0) )
(float (z/cdf rpm 3.0))))
(test/is (z/float-approximately==
(float (/ 7.0 n0) )
(float (z/cdf rpm 4.0))))
(test/is (z/float-approximately==
(float (/ 9.0 n0) )
(float (z/cdf rpm 5.0))))
(test/is (z/float-approximately==
(float (/ 9.0 n0) )
(float (z/cdf rpm 6.0)))))))
;;----------------------------------------------------------------
| 119293 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "<EMAIL>"
:date "2017-12-06"
:doc "Unit tests for zana.prob.measure."}
zana.test.prob.measure
(:require [clojure.string :as s]
[clojure.java.io :as io]
[clojure.test :as test]
[zana.prob.measure :as zpm]
[zana.api :as z])
(:import [java.util Arrays]
[zana.java.prob WEPDF]))
;; mvn -Dtest=zana.test.prob.measure clojure:test
;; TODO: randomized data for larger tests
;;----------------------------------------------------------------
(def nss (str *ns*))
(defn setup [tests]
(def z0 (float-array
[1.0 2.0 3.0 1.0 3.0 5.0 4.0 1.0 5.0]))
(def ^double n0 (double (alength ^floats z0)))
(def w0 (float-array n0 1.0))
(def z1 (float-array [1.0 2.0 3.0 4.0 5.0]))
(def w1 (float-array [3.0 1.0 2.0 1.0 2.0]))
(def pdf0 (z/make-wepdf z0 w0))
(def pdf1 (z/make-wepdf z0))
(def pdf2 (WEPDF/average [pdf0 pdf1]))
(def pdf3 (WEPDF/average [pdf0 pdf1 pdf2]))
(def pdf4 (WEPDF/average
[(z/make-wepdf (float-array [1.0 2.0 3.0]))
(z/make-wepdf (float-array [1.0 3.0 5.0]))
(z/make-wepdf (float-array [4.0 1.0 5.0]))]))
(def cdf5 (z/make-wecdf z0 w0))
(def cdf6 (z/make-wecdf z0))
(def cdf7 (z/wepdf-to-wecdf pdf1))
(def pdf8 (z/wecdf-to-wepdf cdf6))
(def rpms [pdf0 pdf1 pdf2 pdf3 pdf4 cdf5 cdf6 cdf7 pdf8])
(tests))
(test/use-fixtures :once setup)
;;----------------------------------------------------------------
(test/deftest make
(test/is (z/approximatelyEqual pdf0 pdf1 pdf2 pdf3 pdf4 pdf8)
#_(str "\n0 " pdf0 "\n1 " pdf1
"\n2 " pdf2 "\n3 " pdf3
"\n4 " pdf4 "\n5 " pdf8
))
(test/is (z/approximatelyEqual cdf5 cdf6 cdf7)
#_(str "\n" cdf5 "\n" cdf6 "\n" cdf7)))
;;----------------------------------------------------------------
(defn- serialization-test [rpm i]
(let [tokens (s/split nss #"\.")
folder (apply io/file "tst" tokens)
filename (str (.getSimpleName (class rpm)) i)
#_(println filename)
edn-file (io/file folder (str filename ".edn.gz"))
_ (io/make-parents edn-file)
_ (z/write-edn rpm edn-file)
;;_ (taiga/pprint-model model pretty-file)
edn-rpm (z/read-edn edn-file)]
(test/is (= rpm edn-rpm))))
(test/deftest serialization
(z/mapc serialization-test rpms (range (count rpms))))
;;----------------------------------------------------------------
;; TODO: better sum algorithm in cdf to get rid of z/approximately==
(test/deftest quantile
(let [n0 (double n0)]
(doseq [rpm rpms]
#_(dotimes [i 5]
(let [zi (aget z1 i)
wi (aget w1 i)
pi (z/cdf rpm zi)]
(println i zi wi pi (z/quantile rpm pi))))
(test/is (== Double/NEGATIVE_INFINITY
(z/quantile rpm (float 0.0))))
(test/is (== 1.0 (z/quantile rpm (float (/ 1.0 n0)))))
(test/is (== 1.0 (z/quantile rpm (float (/ 2.0 n0)))))
(test/is (== 1.0 (z/quantile rpm (/ 3.0 n0)))
(print-str (/ 3.0 n0) (class rpm) rpm))
(test/is (== 2.0 (z/quantile rpm (float (/ 3.5 n0)))))
(test/is (== 2.0 (z/quantile rpm (float (/ 4.0 n0)))))
(test/is (== 3.0 (z/quantile rpm (float (/ 5.0 n0)))))
(test/is (== 3.0 (z/quantile rpm (float (/ 6.0 n0)))))
(test/is (== 4.0 (z/quantile rpm (float (/ 6.5 n0)))))
(test/is (== 4.0 (z/quantile rpm (float (/ 7.0 n0)))))
(test/is (== 5.0 (z/quantile rpm (float (/ 8.0 n0)))))
(test/is (== 5.0 (z/quantile rpm (float (/ 9.0 n0)))))
(test/is (== 5.0 (z/quantile rpm (float 1.0)))))))
;;----------------------------------------------------------------
;; TODO: better sum algorithm in cdf to get rid of z/approximately==
(test/deftest pointmass
(let [n0 (double n0)]
(doseq [rpm rpms]
#_(println rpm)
(test/is (== 0.0 (z/pointmass rpm -1.0)))
(test/is (== 0.0 (z/pointmass rpm 0.0)))
(test/is (z/float-approximately==
(float (/ 3.0 n0))
(float (z/pointmass rpm 1.0))))
(test/is (== 0.0 (z/pointmass rpm 1.5)))
(test/is (z/float-approximately==
(float (/ 1.0 n0))
(float (z/pointmass rpm 2.0))))
(test/is (z/float-approximately==
(float (/ 2.0 n0))
(float (z/pointmass rpm 3.0))))
(test/is (z/float-approximately==
(float (/ 1.0 n0))
(float (z/pointmass rpm 4.0))))
(test/is (z/float-approximately==
(float (/ 2.0 n0))
(float (z/pointmass rpm 5.0))))
(test/is (== 0.0 (z/pointmass rpm 6.0))))))
;;----------------------------------------------------------------
;; TODO: better sum algorithm in cdf to get rid of z/approximately==
(test/deftest cdf
(let [n0 (double n0)]
(doseq [rpm rpms]
(test/is (== 0.0 (z/cdf rpm -1.0)))
(test/is (== 0.0 (z/cdf rpm 0.0)))
(test/is (z/float-approximately==
(float (/ 3.0 n0))
(float (z/cdf rpm 1.0))))
(test/is (z/float-approximately==
(float (/ 3.0 n0) )
(float (z/cdf rpm 1.5))))
(test/is (z/float-approximately==
(float (/ 4.0 n0) )
(float (z/cdf rpm 2.0))))
(test/is (z/float-approximately==
(float (/ 6.0 n0) )
(float (z/cdf rpm 3.0))))
(test/is (z/float-approximately==
(float (/ 7.0 n0) )
(float (z/cdf rpm 4.0))))
(test/is (z/float-approximately==
(float (/ 9.0 n0) )
(float (z/cdf rpm 5.0))))
(test/is (z/float-approximately==
(float (/ 9.0 n0) )
(float (z/cdf rpm 6.0)))))))
;;----------------------------------------------------------------
| true | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(ns ^{:author "PI:EMAIL:<EMAIL>END_PI"
:date "2017-12-06"
:doc "Unit tests for zana.prob.measure."}
zana.test.prob.measure
(:require [clojure.string :as s]
[clojure.java.io :as io]
[clojure.test :as test]
[zana.prob.measure :as zpm]
[zana.api :as z])
(:import [java.util Arrays]
[zana.java.prob WEPDF]))
;; mvn -Dtest=zana.test.prob.measure clojure:test
;; TODO: randomized data for larger tests
;;----------------------------------------------------------------
(def nss (str *ns*))
(defn setup [tests]
(def z0 (float-array
[1.0 2.0 3.0 1.0 3.0 5.0 4.0 1.0 5.0]))
(def ^double n0 (double (alength ^floats z0)))
(def w0 (float-array n0 1.0))
(def z1 (float-array [1.0 2.0 3.0 4.0 5.0]))
(def w1 (float-array [3.0 1.0 2.0 1.0 2.0]))
(def pdf0 (z/make-wepdf z0 w0))
(def pdf1 (z/make-wepdf z0))
(def pdf2 (WEPDF/average [pdf0 pdf1]))
(def pdf3 (WEPDF/average [pdf0 pdf1 pdf2]))
(def pdf4 (WEPDF/average
[(z/make-wepdf (float-array [1.0 2.0 3.0]))
(z/make-wepdf (float-array [1.0 3.0 5.0]))
(z/make-wepdf (float-array [4.0 1.0 5.0]))]))
(def cdf5 (z/make-wecdf z0 w0))
(def cdf6 (z/make-wecdf z0))
(def cdf7 (z/wepdf-to-wecdf pdf1))
(def pdf8 (z/wecdf-to-wepdf cdf6))
(def rpms [pdf0 pdf1 pdf2 pdf3 pdf4 cdf5 cdf6 cdf7 pdf8])
(tests))
(test/use-fixtures :once setup)
;;----------------------------------------------------------------
(test/deftest make
(test/is (z/approximatelyEqual pdf0 pdf1 pdf2 pdf3 pdf4 pdf8)
#_(str "\n0 " pdf0 "\n1 " pdf1
"\n2 " pdf2 "\n3 " pdf3
"\n4 " pdf4 "\n5 " pdf8
))
(test/is (z/approximatelyEqual cdf5 cdf6 cdf7)
#_(str "\n" cdf5 "\n" cdf6 "\n" cdf7)))
;;----------------------------------------------------------------
(defn- serialization-test [rpm i]
(let [tokens (s/split nss #"\.")
folder (apply io/file "tst" tokens)
filename (str (.getSimpleName (class rpm)) i)
#_(println filename)
edn-file (io/file folder (str filename ".edn.gz"))
_ (io/make-parents edn-file)
_ (z/write-edn rpm edn-file)
;;_ (taiga/pprint-model model pretty-file)
edn-rpm (z/read-edn edn-file)]
(test/is (= rpm edn-rpm))))
(test/deftest serialization
(z/mapc serialization-test rpms (range (count rpms))))
;;----------------------------------------------------------------
;; TODO: better sum algorithm in cdf to get rid of z/approximately==
(test/deftest quantile
(let [n0 (double n0)]
(doseq [rpm rpms]
#_(dotimes [i 5]
(let [zi (aget z1 i)
wi (aget w1 i)
pi (z/cdf rpm zi)]
(println i zi wi pi (z/quantile rpm pi))))
(test/is (== Double/NEGATIVE_INFINITY
(z/quantile rpm (float 0.0))))
(test/is (== 1.0 (z/quantile rpm (float (/ 1.0 n0)))))
(test/is (== 1.0 (z/quantile rpm (float (/ 2.0 n0)))))
(test/is (== 1.0 (z/quantile rpm (/ 3.0 n0)))
(print-str (/ 3.0 n0) (class rpm) rpm))
(test/is (== 2.0 (z/quantile rpm (float (/ 3.5 n0)))))
(test/is (== 2.0 (z/quantile rpm (float (/ 4.0 n0)))))
(test/is (== 3.0 (z/quantile rpm (float (/ 5.0 n0)))))
(test/is (== 3.0 (z/quantile rpm (float (/ 6.0 n0)))))
(test/is (== 4.0 (z/quantile rpm (float (/ 6.5 n0)))))
(test/is (== 4.0 (z/quantile rpm (float (/ 7.0 n0)))))
(test/is (== 5.0 (z/quantile rpm (float (/ 8.0 n0)))))
(test/is (== 5.0 (z/quantile rpm (float (/ 9.0 n0)))))
(test/is (== 5.0 (z/quantile rpm (float 1.0)))))))
;;----------------------------------------------------------------
;; TODO: better sum algorithm in cdf to get rid of z/approximately==
(test/deftest pointmass
(let [n0 (double n0)]
(doseq [rpm rpms]
#_(println rpm)
(test/is (== 0.0 (z/pointmass rpm -1.0)))
(test/is (== 0.0 (z/pointmass rpm 0.0)))
(test/is (z/float-approximately==
(float (/ 3.0 n0))
(float (z/pointmass rpm 1.0))))
(test/is (== 0.0 (z/pointmass rpm 1.5)))
(test/is (z/float-approximately==
(float (/ 1.0 n0))
(float (z/pointmass rpm 2.0))))
(test/is (z/float-approximately==
(float (/ 2.0 n0))
(float (z/pointmass rpm 3.0))))
(test/is (z/float-approximately==
(float (/ 1.0 n0))
(float (z/pointmass rpm 4.0))))
(test/is (z/float-approximately==
(float (/ 2.0 n0))
(float (z/pointmass rpm 5.0))))
(test/is (== 0.0 (z/pointmass rpm 6.0))))))
;;----------------------------------------------------------------
;; TODO: better sum algorithm in cdf to get rid of z/approximately==
(test/deftest cdf
(let [n0 (double n0)]
(doseq [rpm rpms]
(test/is (== 0.0 (z/cdf rpm -1.0)))
(test/is (== 0.0 (z/cdf rpm 0.0)))
(test/is (z/float-approximately==
(float (/ 3.0 n0))
(float (z/cdf rpm 1.0))))
(test/is (z/float-approximately==
(float (/ 3.0 n0) )
(float (z/cdf rpm 1.5))))
(test/is (z/float-approximately==
(float (/ 4.0 n0) )
(float (z/cdf rpm 2.0))))
(test/is (z/float-approximately==
(float (/ 6.0 n0) )
(float (z/cdf rpm 3.0))))
(test/is (z/float-approximately==
(float (/ 7.0 n0) )
(float (z/cdf rpm 4.0))))
(test/is (z/float-approximately==
(float (/ 9.0 n0) )
(float (z/cdf rpm 5.0))))
(test/is (z/float-approximately==
(float (/ 9.0 n0) )
(float (z/cdf rpm 6.0)))))))
;;----------------------------------------------------------------
|
[
{
"context": " {:Value \"nsidc@nsidc.org\",\n ",
"end": 2252,
"score": 0.9999035596847534,
"start": 2237,
"tag": "EMAIL",
"value": "nsidc@nsidc.org"
},
{
"context": " {:Value \"nsidc@nsidc.org\",\n ",
"end": 3500,
"score": 0.9999265670776367,
"start": 3485,
"tag": "EMAIL",
"value": "nsidc@nsidc.org"
}
] | umm-spec-lib/test/cmr/umm_spec/test/xml_to_umm_mappings/iso19115_2/data_contact.clj | daniel-zamora/Common-Metadata-Repository | 294 | (ns cmr.umm-spec.test.xml-to-umm-mappings.iso19115-2.data-contact
(:require
[clojure.java.io :as io]
[clojure.test :refer :all]
[cmr.umm-spec.xml-to-umm-mappings.iso19115-2.data-contact :as data-contact]))
(def contact-related-urls-example-result
'({:NonDataCenterAffiliation nil,
:Roles ["User Services"],
:GroupName "National Snow and Ice Data Center",
:ContactInformation {:ContactMechanisms (),
:ServiceHours nil,
:Addresses [{:City "Boulder",
:StateProvince "Colorado",
:Country "USA",
:StreetAddresses (),
:PostalCode nil}],
:RelatedUrls ({:URLContentType "DataContactURL",
:Description nil,
:Type "HOME PAGE",
:URL "http://nsidc.org"}),
:ContactInstruction nil}}
{:NonDataCenterAffiliation nil,
:Roles ["User Services"],
:GroupName "National Snow and Ice Data Center2",
:ContactInformation {:ContactMechanisms (),
:ServiceHours nil,
:Addresses [{:City "Boulder",
:StateProvince "Colorado",
:Country "USA",
:StreetAddresses (),
:PostalCode nil}],
:RelatedUrls (),
:ContactInstruction nil}}))
(def data-center-contact-related-urls-example-result
'({:ShortName "NASA National Snow and Ice Data Center Distributed Active Archive Center",
:ContactPersons nil,
:Roles ["ARCHIVER"],
:LongName nil,
:ContactInformation {:ContactMechanisms ({:Value "1 303 492 6199 x",
:Type "Telephone"}
{:Value "1 303 492 2468 x",
:Type "Fax"}
{:Value "nsidc@nsidc.org",
:Type "Email"}),
:ServiceHours nil,
:Addresses [{:City "Boulder",
:StateProvince "CO",
:Country "USA",
:StreetAddresses (),
:PostalCode "80309-0449"}],
:RelatedUrls ({:URLContentType "DataCenterURL",
:Description nil,
:Type "HOME PAGE",
:URL "http://nsidc.org/daac/index.html"}),
:ContactInstruction nil}}
{:ShortName "NASA National Snow and Ice Data Center Distributed Active Archive Center2",
:ContactPersons nil,
:Roles ["ARCHIVER"],
:LongName nil,
:ContactInformation {:ContactMechanisms ({:Value "1 303 492 6199 x",
:Type "Telephone"}
{:Value "1 303 492 2468 x",
:Type "Fax"}
{:Value "nsidc@nsidc.org",
:Type "Email"}),
:ServiceHours nil,
:Addresses [{:City "Boulder",
:StateProvince "CO",
:Country "USA",
:StreetAddresses (),
:PostalCode "80309-0449"}],
:RelatedUrls (),
:ContactInstruction nil}}))
(deftest parse-data-contact-related-urls-test
(testing "Test if the URL doesn't exist for parsing contact data, then don't include it. If it
does exist then include it."
(let [metadata (slurp (io/resource "example-data/iso19115/ISOExample-contactRelatedURLs.xml"))
sanitize? true]
(is (= (:ContactGroups (data-contact/parse-contacts metadata sanitize?))
contact-related-urls-example-result))
(is (= (:DataCenters (data-contact/parse-contacts metadata sanitize?))
data-center-contact-related-urls-example-result)))))
| 67043 | (ns cmr.umm-spec.test.xml-to-umm-mappings.iso19115-2.data-contact
(:require
[clojure.java.io :as io]
[clojure.test :refer :all]
[cmr.umm-spec.xml-to-umm-mappings.iso19115-2.data-contact :as data-contact]))
(def contact-related-urls-example-result
'({:NonDataCenterAffiliation nil,
:Roles ["User Services"],
:GroupName "National Snow and Ice Data Center",
:ContactInformation {:ContactMechanisms (),
:ServiceHours nil,
:Addresses [{:City "Boulder",
:StateProvince "Colorado",
:Country "USA",
:StreetAddresses (),
:PostalCode nil}],
:RelatedUrls ({:URLContentType "DataContactURL",
:Description nil,
:Type "HOME PAGE",
:URL "http://nsidc.org"}),
:ContactInstruction nil}}
{:NonDataCenterAffiliation nil,
:Roles ["User Services"],
:GroupName "National Snow and Ice Data Center2",
:ContactInformation {:ContactMechanisms (),
:ServiceHours nil,
:Addresses [{:City "Boulder",
:StateProvince "Colorado",
:Country "USA",
:StreetAddresses (),
:PostalCode nil}],
:RelatedUrls (),
:ContactInstruction nil}}))
(def data-center-contact-related-urls-example-result
'({:ShortName "NASA National Snow and Ice Data Center Distributed Active Archive Center",
:ContactPersons nil,
:Roles ["ARCHIVER"],
:LongName nil,
:ContactInformation {:ContactMechanisms ({:Value "1 303 492 6199 x",
:Type "Telephone"}
{:Value "1 303 492 2468 x",
:Type "Fax"}
{:Value "<EMAIL>",
:Type "Email"}),
:ServiceHours nil,
:Addresses [{:City "Boulder",
:StateProvince "CO",
:Country "USA",
:StreetAddresses (),
:PostalCode "80309-0449"}],
:RelatedUrls ({:URLContentType "DataCenterURL",
:Description nil,
:Type "HOME PAGE",
:URL "http://nsidc.org/daac/index.html"}),
:ContactInstruction nil}}
{:ShortName "NASA National Snow and Ice Data Center Distributed Active Archive Center2",
:ContactPersons nil,
:Roles ["ARCHIVER"],
:LongName nil,
:ContactInformation {:ContactMechanisms ({:Value "1 303 492 6199 x",
:Type "Telephone"}
{:Value "1 303 492 2468 x",
:Type "Fax"}
{:Value "<EMAIL>",
:Type "Email"}),
:ServiceHours nil,
:Addresses [{:City "Boulder",
:StateProvince "CO",
:Country "USA",
:StreetAddresses (),
:PostalCode "80309-0449"}],
:RelatedUrls (),
:ContactInstruction nil}}))
(deftest parse-data-contact-related-urls-test
(testing "Test if the URL doesn't exist for parsing contact data, then don't include it. If it
does exist then include it."
(let [metadata (slurp (io/resource "example-data/iso19115/ISOExample-contactRelatedURLs.xml"))
sanitize? true]
(is (= (:ContactGroups (data-contact/parse-contacts metadata sanitize?))
contact-related-urls-example-result))
(is (= (:DataCenters (data-contact/parse-contacts metadata sanitize?))
data-center-contact-related-urls-example-result)))))
| true | (ns cmr.umm-spec.test.xml-to-umm-mappings.iso19115-2.data-contact
(:require
[clojure.java.io :as io]
[clojure.test :refer :all]
[cmr.umm-spec.xml-to-umm-mappings.iso19115-2.data-contact :as data-contact]))
(def contact-related-urls-example-result
'({:NonDataCenterAffiliation nil,
:Roles ["User Services"],
:GroupName "National Snow and Ice Data Center",
:ContactInformation {:ContactMechanisms (),
:ServiceHours nil,
:Addresses [{:City "Boulder",
:StateProvince "Colorado",
:Country "USA",
:StreetAddresses (),
:PostalCode nil}],
:RelatedUrls ({:URLContentType "DataContactURL",
:Description nil,
:Type "HOME PAGE",
:URL "http://nsidc.org"}),
:ContactInstruction nil}}
{:NonDataCenterAffiliation nil,
:Roles ["User Services"],
:GroupName "National Snow and Ice Data Center2",
:ContactInformation {:ContactMechanisms (),
:ServiceHours nil,
:Addresses [{:City "Boulder",
:StateProvince "Colorado",
:Country "USA",
:StreetAddresses (),
:PostalCode nil}],
:RelatedUrls (),
:ContactInstruction nil}}))
(def data-center-contact-related-urls-example-result
'({:ShortName "NASA National Snow and Ice Data Center Distributed Active Archive Center",
:ContactPersons nil,
:Roles ["ARCHIVER"],
:LongName nil,
:ContactInformation {:ContactMechanisms ({:Value "1 303 492 6199 x",
:Type "Telephone"}
{:Value "1 303 492 2468 x",
:Type "Fax"}
{:Value "PI:EMAIL:<EMAIL>END_PI",
:Type "Email"}),
:ServiceHours nil,
:Addresses [{:City "Boulder",
:StateProvince "CO",
:Country "USA",
:StreetAddresses (),
:PostalCode "80309-0449"}],
:RelatedUrls ({:URLContentType "DataCenterURL",
:Description nil,
:Type "HOME PAGE",
:URL "http://nsidc.org/daac/index.html"}),
:ContactInstruction nil}}
{:ShortName "NASA National Snow and Ice Data Center Distributed Active Archive Center2",
:ContactPersons nil,
:Roles ["ARCHIVER"],
:LongName nil,
:ContactInformation {:ContactMechanisms ({:Value "1 303 492 6199 x",
:Type "Telephone"}
{:Value "1 303 492 2468 x",
:Type "Fax"}
{:Value "PI:EMAIL:<EMAIL>END_PI",
:Type "Email"}),
:ServiceHours nil,
:Addresses [{:City "Boulder",
:StateProvince "CO",
:Country "USA",
:StreetAddresses (),
:PostalCode "80309-0449"}],
:RelatedUrls (),
:ContactInstruction nil}}))
(deftest parse-data-contact-related-urls-test
(testing "Test if the URL doesn't exist for parsing contact data, then don't include it. If it
does exist then include it."
(let [metadata (slurp (io/resource "example-data/iso19115/ISOExample-contactRelatedURLs.xml"))
sanitize? true]
(is (= (:ContactGroups (data-contact/parse-contacts metadata sanitize?))
contact-related-urls-example-result))
(is (= (:DataCenters (data-contact/parse-contacts metadata sanitize?))
data-center-contact-related-urls-example-result)))))
|
[
{
"context": "erson_id 1234567\n :person_name \"John Doe\"\n :image {:url \"http://focus.on/m",
"end": 2743,
"score": 0.9998283386230469,
"start": 2735,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "//corporate.com/me.png\"}\n :person_short_name \"John\"})\n\n (def cleanup ",
"end": 2894,
"score": 0.9998396039009094,
"start": 2890,
"tag": "NAME",
"value": "John"
},
{
"context": "_id\n ;orig = { :person_id 1234567, :person_name \"John Doe\", :image { :url \"http://focus.on/me.jpg\", :previe",
"end": 3439,
"score": 0.9998243451118469,
"start": 3431,
"tag": "NAME",
"value": "John Doe"
},
{
"context": "tp://corporate.com/me.png\" }, :person_short_name \"John\"}\n ;f = clojure.core$str@63ebeb1f\n\n (transform ",
"end": 3548,
"score": 0.9998438358306885,
"start": 3544,
"tag": "NAME",
"value": "John"
}
] | clj/ex/study_clojure/ex06/src/debug_functions.clj | mertnuhoglu/study | 1 | (ns debug-functions)
; Good methods:
; hashp for tracing <url:file:///~/projects/study/clj/ex/study_clojure/ex06/src/debug_functions.clj#r=g11988>
; cider debugging example <url:file:///~/projects/study/clj/ex/study_clojure/ex06/src/debug_functions.clj#r=g11970>
(comment
; hashp for tracing id=g11988
; [Clojure observability and debugging tools](http://www.futurile.net/2020/05/16/clojure-observability-and-debugging-tools/)
(require 'hashp.core)
(take 3 (repeat #p (+ 1 2)))
; (out) #p[debug-functions/eval15048:44] (+ 1 2) => 3
;;=> (3 3 3)
(inc #p (* 2 #p (+ 3 #p (* 4 5))))
; eval (current-form): (inc #p (* 2 #p (+ 3 #p (* 4 5))))
; (out) #p[debug-functions/eval15053:48] (* 4 5) => 20
; (out) #p[debug-functions/eval15053:48] (+ 3 (* 4 5)) => 23
; (out) #p[debug-functions/eval15053:48] (* 2 (+ 3 (* 4 5))) => 46
;;=> 47
; ref_ex: `~/projects/csl-book-examples/Creatingandmanipulatingfunctions/Higherorderfunctions/fnil/6.clj`
,)
(comment
; clj-inspector for tracing
(require 'inspector.core)
; (err) Execution error (FileNotFoundException) at debug-functions/eval8159 (REPL:31).
(take 3 (repeat #p (+ 1 2)))
; (out) #p[debug-functions/eval15048:44] (+ 1 2) => 3
;;=> (3 3 3)
(inc #p (* 2 #p (+ 3 #p (* 4 5))))
,)
(comment
; @mine: Use hashp instead of dotrace
; #p allows to mark what you want to trace precisely
(require '[clojure.tools.trace :refer [trace, dotrace]])
(trace (* 2 3))
(defn ^:dynamic fib[n] (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2)))))
(trace [fib] (fib 3))
#_(ns-publics 'clojure.tools.trace)
(dotrace [fib] (fib 3))
; (out) TRACE t8378: (fib 3)
; (out) TRACE t8379: | (fib 2)
; (out) TRACE t8380: | | (fib 1)
; (out) TRACE t8380: | | => 1
; (out) TRACE t8381: | | (fib 0)
; (out) TRACE t8381: | | => 0
; (out) TRACE t8379: | => 1
; (out) TRACE t8382: | (fib 1)
; (out) TRACE t8382: | => 1
; (out) TRACE t8378: => 2
; ref_ex: `~/projects/csl-book-examples/Creatingandmanipulatingfunctions/Higherorderfunctions/fnil/6.clj`
,)
(comment
(require 'spyscope.core)
(take 20 (repeat #spy/p (+ 1 2 3)))
; (out) 6
;=> (6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6)
(take 20 (repeat (+ 1 2 3)))
;=> (6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6)
#_(take 20 (repeat #spy/d (+ 1 2 3)))
,)
(comment
; cider debugging example id=g11970
; [Cider Debugger - YouTube](https://www.youtube.com/watch?v=jHCch3-Yuac)
; 01: put break point here: `,db`
(defn pythagoras [x y]
(let [x2 (* x 2)
y2 (* y 2)]
(Math/sqrt (+ x2 y2))))
; 02: run this function: `,ef`
(pythagoras 3 4)
; example 2:
(def sample-person
{:person_id 1234567
:person_name "John Doe"
:image {:url "http://focus.on/me.jpg"
:preview "http://corporate.com/me.png"}
:person_short_name "John"})
(def cleanup ; <1>
{:person_id [:id str]
:person_name [:name (memfn toLowerCase)]
:image [:avatar :url]})
(defn transform [orig mapping]
(apply merge
(map (fn [[k [k' f]]] {k' (f (k orig))}) ; <2>
mapping)))
; debugger: locals:
;k' = :id
;mapping = { :person_id [ :id clojure.core$str@63ebeb1f ], :person_name [ :name user$fn__7845@3cbba7c8 ], :image [ :avatar :url]}
;k = :person_id
;orig = { :person_id 1234567, :person_name "John Doe", :image { :url "http://focus.on/me.jpg", :preview "http://corporate.com/me.png" }, :person_short_name "John"}
;f = clojure.core$str@63ebeb1f
(transform sample-person cleanup)
; ex03:
; `,db`
(defn debugtest2 [a]
(+ 1 a))
(debugtest2 3)
; note: `#break`
(defn debugtest3 [a]
#break
(+ 1 a))
(debugtest3 3)
; note: `#dbg`
(defn debugtest4 [a]
#dbg
(+ 1 a))
(debugtest4 3)
; `M-x cider-browse-instrumented-defs`
;=> debug-functions
;=> debugtest2
,)
| 125066 | (ns debug-functions)
; Good methods:
; hashp for tracing <url:file:///~/projects/study/clj/ex/study_clojure/ex06/src/debug_functions.clj#r=g11988>
; cider debugging example <url:file:///~/projects/study/clj/ex/study_clojure/ex06/src/debug_functions.clj#r=g11970>
(comment
; hashp for tracing id=g11988
; [Clojure observability and debugging tools](http://www.futurile.net/2020/05/16/clojure-observability-and-debugging-tools/)
(require 'hashp.core)
(take 3 (repeat #p (+ 1 2)))
; (out) #p[debug-functions/eval15048:44] (+ 1 2) => 3
;;=> (3 3 3)
(inc #p (* 2 #p (+ 3 #p (* 4 5))))
; eval (current-form): (inc #p (* 2 #p (+ 3 #p (* 4 5))))
; (out) #p[debug-functions/eval15053:48] (* 4 5) => 20
; (out) #p[debug-functions/eval15053:48] (+ 3 (* 4 5)) => 23
; (out) #p[debug-functions/eval15053:48] (* 2 (+ 3 (* 4 5))) => 46
;;=> 47
; ref_ex: `~/projects/csl-book-examples/Creatingandmanipulatingfunctions/Higherorderfunctions/fnil/6.clj`
,)
(comment
; clj-inspector for tracing
(require 'inspector.core)
; (err) Execution error (FileNotFoundException) at debug-functions/eval8159 (REPL:31).
(take 3 (repeat #p (+ 1 2)))
; (out) #p[debug-functions/eval15048:44] (+ 1 2) => 3
;;=> (3 3 3)
(inc #p (* 2 #p (+ 3 #p (* 4 5))))
,)
(comment
; @mine: Use hashp instead of dotrace
; #p allows to mark what you want to trace precisely
(require '[clojure.tools.trace :refer [trace, dotrace]])
(trace (* 2 3))
(defn ^:dynamic fib[n] (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2)))))
(trace [fib] (fib 3))
#_(ns-publics 'clojure.tools.trace)
(dotrace [fib] (fib 3))
; (out) TRACE t8378: (fib 3)
; (out) TRACE t8379: | (fib 2)
; (out) TRACE t8380: | | (fib 1)
; (out) TRACE t8380: | | => 1
; (out) TRACE t8381: | | (fib 0)
; (out) TRACE t8381: | | => 0
; (out) TRACE t8379: | => 1
; (out) TRACE t8382: | (fib 1)
; (out) TRACE t8382: | => 1
; (out) TRACE t8378: => 2
; ref_ex: `~/projects/csl-book-examples/Creatingandmanipulatingfunctions/Higherorderfunctions/fnil/6.clj`
,)
(comment
(require 'spyscope.core)
(take 20 (repeat #spy/p (+ 1 2 3)))
; (out) 6
;=> (6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6)
(take 20 (repeat (+ 1 2 3)))
;=> (6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6)
#_(take 20 (repeat #spy/d (+ 1 2 3)))
,)
(comment
; cider debugging example id=g11970
; [Cider Debugger - YouTube](https://www.youtube.com/watch?v=jHCch3-Yuac)
; 01: put break point here: `,db`
(defn pythagoras [x y]
(let [x2 (* x 2)
y2 (* y 2)]
(Math/sqrt (+ x2 y2))))
; 02: run this function: `,ef`
(pythagoras 3 4)
; example 2:
(def sample-person
{:person_id 1234567
:person_name "<NAME>"
:image {:url "http://focus.on/me.jpg"
:preview "http://corporate.com/me.png"}
:person_short_name "<NAME>"})
(def cleanup ; <1>
{:person_id [:id str]
:person_name [:name (memfn toLowerCase)]
:image [:avatar :url]})
(defn transform [orig mapping]
(apply merge
(map (fn [[k [k' f]]] {k' (f (k orig))}) ; <2>
mapping)))
; debugger: locals:
;k' = :id
;mapping = { :person_id [ :id clojure.core$str@63ebeb1f ], :person_name [ :name user$fn__7845@3cbba7c8 ], :image [ :avatar :url]}
;k = :person_id
;orig = { :person_id 1234567, :person_name "<NAME>", :image { :url "http://focus.on/me.jpg", :preview "http://corporate.com/me.png" }, :person_short_name "<NAME>"}
;f = clojure.core$str@63ebeb1f
(transform sample-person cleanup)
; ex03:
; `,db`
(defn debugtest2 [a]
(+ 1 a))
(debugtest2 3)
; note: `#break`
(defn debugtest3 [a]
#break
(+ 1 a))
(debugtest3 3)
; note: `#dbg`
(defn debugtest4 [a]
#dbg
(+ 1 a))
(debugtest4 3)
; `M-x cider-browse-instrumented-defs`
;=> debug-functions
;=> debugtest2
,)
| true | (ns debug-functions)
; Good methods:
; hashp for tracing <url:file:///~/projects/study/clj/ex/study_clojure/ex06/src/debug_functions.clj#r=g11988>
; cider debugging example <url:file:///~/projects/study/clj/ex/study_clojure/ex06/src/debug_functions.clj#r=g11970>
(comment
; hashp for tracing id=g11988
; [Clojure observability and debugging tools](http://www.futurile.net/2020/05/16/clojure-observability-and-debugging-tools/)
(require 'hashp.core)
(take 3 (repeat #p (+ 1 2)))
; (out) #p[debug-functions/eval15048:44] (+ 1 2) => 3
;;=> (3 3 3)
(inc #p (* 2 #p (+ 3 #p (* 4 5))))
; eval (current-form): (inc #p (* 2 #p (+ 3 #p (* 4 5))))
; (out) #p[debug-functions/eval15053:48] (* 4 5) => 20
; (out) #p[debug-functions/eval15053:48] (+ 3 (* 4 5)) => 23
; (out) #p[debug-functions/eval15053:48] (* 2 (+ 3 (* 4 5))) => 46
;;=> 47
; ref_ex: `~/projects/csl-book-examples/Creatingandmanipulatingfunctions/Higherorderfunctions/fnil/6.clj`
,)
(comment
; clj-inspector for tracing
(require 'inspector.core)
; (err) Execution error (FileNotFoundException) at debug-functions/eval8159 (REPL:31).
(take 3 (repeat #p (+ 1 2)))
; (out) #p[debug-functions/eval15048:44] (+ 1 2) => 3
;;=> (3 3 3)
(inc #p (* 2 #p (+ 3 #p (* 4 5))))
,)
(comment
; @mine: Use hashp instead of dotrace
; #p allows to mark what you want to trace precisely
(require '[clojure.tools.trace :refer [trace, dotrace]])
(trace (* 2 3))
(defn ^:dynamic fib[n] (if (< n 2) n (+ (fib (- n 1)) (fib (- n 2)))))
(trace [fib] (fib 3))
#_(ns-publics 'clojure.tools.trace)
(dotrace [fib] (fib 3))
; (out) TRACE t8378: (fib 3)
; (out) TRACE t8379: | (fib 2)
; (out) TRACE t8380: | | (fib 1)
; (out) TRACE t8380: | | => 1
; (out) TRACE t8381: | | (fib 0)
; (out) TRACE t8381: | | => 0
; (out) TRACE t8379: | => 1
; (out) TRACE t8382: | (fib 1)
; (out) TRACE t8382: | => 1
; (out) TRACE t8378: => 2
; ref_ex: `~/projects/csl-book-examples/Creatingandmanipulatingfunctions/Higherorderfunctions/fnil/6.clj`
,)
(comment
(require 'spyscope.core)
(take 20 (repeat #spy/p (+ 1 2 3)))
; (out) 6
;=> (6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6)
(take 20 (repeat (+ 1 2 3)))
;=> (6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6)
#_(take 20 (repeat #spy/d (+ 1 2 3)))
,)
(comment
; cider debugging example id=g11970
; [Cider Debugger - YouTube](https://www.youtube.com/watch?v=jHCch3-Yuac)
; 01: put break point here: `,db`
(defn pythagoras [x y]
(let [x2 (* x 2)
y2 (* y 2)]
(Math/sqrt (+ x2 y2))))
; 02: run this function: `,ef`
(pythagoras 3 4)
; example 2:
(def sample-person
{:person_id 1234567
:person_name "PI:NAME:<NAME>END_PI"
:image {:url "http://focus.on/me.jpg"
:preview "http://corporate.com/me.png"}
:person_short_name "PI:NAME:<NAME>END_PI"})
(def cleanup ; <1>
{:person_id [:id str]
:person_name [:name (memfn toLowerCase)]
:image [:avatar :url]})
(defn transform [orig mapping]
(apply merge
(map (fn [[k [k' f]]] {k' (f (k orig))}) ; <2>
mapping)))
; debugger: locals:
;k' = :id
;mapping = { :person_id [ :id clojure.core$str@63ebeb1f ], :person_name [ :name user$fn__7845@3cbba7c8 ], :image [ :avatar :url]}
;k = :person_id
;orig = { :person_id 1234567, :person_name "PI:NAME:<NAME>END_PI", :image { :url "http://focus.on/me.jpg", :preview "http://corporate.com/me.png" }, :person_short_name "PI:NAME:<NAME>END_PI"}
;f = clojure.core$str@63ebeb1f
(transform sample-person cleanup)
; ex03:
; `,db`
(defn debugtest2 [a]
(+ 1 a))
(debugtest2 3)
; note: `#break`
(defn debugtest3 [a]
#break
(+ 1 a))
(debugtest3 3)
; note: `#dbg`
(defn debugtest4 [a]
#dbg
(+ 1 a))
(debugtest4 3)
; `M-x cider-browse-instrumented-defs`
;=> debug-functions
;=> debugtest2
,)
|
[
{
"context": "re until end of turn.\"}]}))\n\n(defmethod fix-card \"Callow Jushi\"\n [card]\n (-> card\n (update-in [:rulelist]",
"end": 2428,
"score": 0.7823058366775513,
"start": 2416,
"tag": "NAME",
"value": "Callow Jushi"
},
{
"context": "st] (partial take 2))\n (assoc :multi {:name \"Jaraku the Interloper\"\n :typelist [\"Legendary\" \"Cre",
"end": 2546,
"score": 0.7529523372650146,
"start": 2525,
"tag": "NAME",
"value": "Jaraku the Interloper"
},
{
"context": "controller pays {2}.\"}]})))\n\n(defmethod fix-card \"Hired Muscle\"\n [card]\n (-> card\n (update-in [:ru",
"end": 2891,
"score": 0.6863653063774109,
"start": 2886,
"tag": "NAME",
"value": "Hired"
},
{
"context": "ler pays {2}.\"}]})))\n\n(defmethod fix-card \"Hired Muscle\"\n [card]\n (-> card\n (update-in [:ruleli",
"end": 2895,
"score": 0.5459756851196289,
"start": 2893,
"tag": "NAME",
"value": "us"
},
{
"context": "st] (partial take 2))\n (assoc :multi {:name \"Scarmaker\"\n :typelist [\"Legendary\" \"Cre",
"end": 3004,
"score": 0.7907169461250305,
"start": 2995,
"tag": "NAME",
"value": "Scarmaker"
}
] | src/loa/cleanup/card_adjustment.clj | karmag/loa | 4 | (ns loa.cleanup.card-adjustment)
;;--------------------------------------------------
;; internal
(defmulti fix-card :name)
(defmethod fix-card :default [card] card)
(defmethod fix-card "Forest" [card] (dissoc card :rulelist))
(defmethod fix-card "Island" [card] (dissoc card :rulelist))
(defmethod fix-card "Mountain" [card] (dissoc card :rulelist))
(defmethod fix-card "Plains" [card] (dissoc card :rulelist))
(defmethod fix-card "Swamp" [card] (dissoc card :rulelist))
(defmethod fix-card "Snow-Covered Forest" [card] (dissoc card :rulelist))
(defmethod fix-card "Snow-Covered Island" [card] (dissoc card :rulelist))
(defmethod fix-card "Snow-Covered Mountain" [card] (dissoc card :rulelist))
(defmethod fix-card "Snow-Covered Plains" [card] (dissoc card :rulelist))
(defmethod fix-card "Snow-Covered Swamp" [card] (dissoc card :rulelist))
(defmethod fix-card "Master of the Wild Hunt Avatar"
[card]
(update-in card [:rulelist]
(fn [[rule & _]]
[(update-in rule [:text]
#(.replace % "green Rhino" "Rhino"))])))
(defmethod fix-card "Homura, Human Ascendant"
[card]
(-> card
(update-in [:multi] dissoc :pow :tgh :cost)
(assoc-in [:multi :rulelist]
[{:number 1
:text "Creatures you control get +2/+2 and have flying and \"{R}: This creature gets +1/+0 until end of turn.\""}])))
(defmethod fix-card "Soltari Guerrillas"
[card]
(assoc-in card [:cost] "{2}{R}{W}"))
(defmethod fix-card "Budoka Pupil"
[card]
(assoc-in card
[:multi]
{:name "Ichiga, Who Topples Oaks"
:typelist ["Legendary" "Creature" "Spirit"]
:pow "4"
:tgh "3"
:rulelist [{:number 1
:text "Trample"}
{:number 2
:text "Remove a ki counter from Ichiga, Who Topples Oaks: Target creature gets +2/+2 until end of turn."}]}))
(defmethod fix-card "Cunning Bandit"
[card]
(assoc-in card
[:multi]
{:name "Azamuki, Treachery Incarnate"
:typelist ["Legendary" "Creature" "Spirit"]
:pow "5"
:tgh "2"
:rulelist [{:number 1
:text "Remove a ki counter from Azamuki, Treachery Incarnate: Gain control of target creature until end of turn."}]}))
(defmethod fix-card "Callow Jushi"
[card]
(-> card
(update-in [:rulelist] (partial take 2))
(assoc :multi {:name "Jaraku the Interloper"
:typelist ["Legendary" "Creature" "Spirit"]
:pow "3"
:tgh "4"
:rulelist [{:number 1
:text "Remove a ki counter from Jaraku the Interloper: Counter target spell unless its controller pays {2}."}]})))
(defmethod fix-card "Hired Muscle"
[card]
(-> card
(update-in [:rulelist] (partial take 2))
(assoc :multi {:name "Scarmaker"
:typelist ["Legendary" "Creature" "Spirit"]
:pow "4"
:tgh "4"
:rulelist [{:number 1
:text "Remove a ki counter from Scarmaker: Target creature gains fear until end of turn."
:reminder "It can't be blocked except by artifact creatures and/or black creatures."}]})))
;;--------------------------------------------------
;; interface
(defn fix [card]
(fix-card card))
| 23785 | (ns loa.cleanup.card-adjustment)
;;--------------------------------------------------
;; internal
(defmulti fix-card :name)
(defmethod fix-card :default [card] card)
(defmethod fix-card "Forest" [card] (dissoc card :rulelist))
(defmethod fix-card "Island" [card] (dissoc card :rulelist))
(defmethod fix-card "Mountain" [card] (dissoc card :rulelist))
(defmethod fix-card "Plains" [card] (dissoc card :rulelist))
(defmethod fix-card "Swamp" [card] (dissoc card :rulelist))
(defmethod fix-card "Snow-Covered Forest" [card] (dissoc card :rulelist))
(defmethod fix-card "Snow-Covered Island" [card] (dissoc card :rulelist))
(defmethod fix-card "Snow-Covered Mountain" [card] (dissoc card :rulelist))
(defmethod fix-card "Snow-Covered Plains" [card] (dissoc card :rulelist))
(defmethod fix-card "Snow-Covered Swamp" [card] (dissoc card :rulelist))
(defmethod fix-card "Master of the Wild Hunt Avatar"
[card]
(update-in card [:rulelist]
(fn [[rule & _]]
[(update-in rule [:text]
#(.replace % "green Rhino" "Rhino"))])))
(defmethod fix-card "Homura, Human Ascendant"
[card]
(-> card
(update-in [:multi] dissoc :pow :tgh :cost)
(assoc-in [:multi :rulelist]
[{:number 1
:text "Creatures you control get +2/+2 and have flying and \"{R}: This creature gets +1/+0 until end of turn.\""}])))
(defmethod fix-card "Soltari Guerrillas"
[card]
(assoc-in card [:cost] "{2}{R}{W}"))
(defmethod fix-card "Budoka Pupil"
[card]
(assoc-in card
[:multi]
{:name "Ichiga, Who Topples Oaks"
:typelist ["Legendary" "Creature" "Spirit"]
:pow "4"
:tgh "3"
:rulelist [{:number 1
:text "Trample"}
{:number 2
:text "Remove a ki counter from Ichiga, Who Topples Oaks: Target creature gets +2/+2 until end of turn."}]}))
(defmethod fix-card "Cunning Bandit"
[card]
(assoc-in card
[:multi]
{:name "Azamuki, Treachery Incarnate"
:typelist ["Legendary" "Creature" "Spirit"]
:pow "5"
:tgh "2"
:rulelist [{:number 1
:text "Remove a ki counter from Azamuki, Treachery Incarnate: Gain control of target creature until end of turn."}]}))
(defmethod fix-card "<NAME>"
[card]
(-> card
(update-in [:rulelist] (partial take 2))
(assoc :multi {:name "<NAME>"
:typelist ["Legendary" "Creature" "Spirit"]
:pow "3"
:tgh "4"
:rulelist [{:number 1
:text "Remove a ki counter from Jaraku the Interloper: Counter target spell unless its controller pays {2}."}]})))
(defmethod fix-card "<NAME> M<NAME>cle"
[card]
(-> card
(update-in [:rulelist] (partial take 2))
(assoc :multi {:name "<NAME>"
:typelist ["Legendary" "Creature" "Spirit"]
:pow "4"
:tgh "4"
:rulelist [{:number 1
:text "Remove a ki counter from Scarmaker: Target creature gains fear until end of turn."
:reminder "It can't be blocked except by artifact creatures and/or black creatures."}]})))
;;--------------------------------------------------
;; interface
(defn fix [card]
(fix-card card))
| true | (ns loa.cleanup.card-adjustment)
;;--------------------------------------------------
;; internal
(defmulti fix-card :name)
(defmethod fix-card :default [card] card)
(defmethod fix-card "Forest" [card] (dissoc card :rulelist))
(defmethod fix-card "Island" [card] (dissoc card :rulelist))
(defmethod fix-card "Mountain" [card] (dissoc card :rulelist))
(defmethod fix-card "Plains" [card] (dissoc card :rulelist))
(defmethod fix-card "Swamp" [card] (dissoc card :rulelist))
(defmethod fix-card "Snow-Covered Forest" [card] (dissoc card :rulelist))
(defmethod fix-card "Snow-Covered Island" [card] (dissoc card :rulelist))
(defmethod fix-card "Snow-Covered Mountain" [card] (dissoc card :rulelist))
(defmethod fix-card "Snow-Covered Plains" [card] (dissoc card :rulelist))
(defmethod fix-card "Snow-Covered Swamp" [card] (dissoc card :rulelist))
(defmethod fix-card "Master of the Wild Hunt Avatar"
[card]
(update-in card [:rulelist]
(fn [[rule & _]]
[(update-in rule [:text]
#(.replace % "green Rhino" "Rhino"))])))
(defmethod fix-card "Homura, Human Ascendant"
[card]
(-> card
(update-in [:multi] dissoc :pow :tgh :cost)
(assoc-in [:multi :rulelist]
[{:number 1
:text "Creatures you control get +2/+2 and have flying and \"{R}: This creature gets +1/+0 until end of turn.\""}])))
(defmethod fix-card "Soltari Guerrillas"
[card]
(assoc-in card [:cost] "{2}{R}{W}"))
(defmethod fix-card "Budoka Pupil"
[card]
(assoc-in card
[:multi]
{:name "Ichiga, Who Topples Oaks"
:typelist ["Legendary" "Creature" "Spirit"]
:pow "4"
:tgh "3"
:rulelist [{:number 1
:text "Trample"}
{:number 2
:text "Remove a ki counter from Ichiga, Who Topples Oaks: Target creature gets +2/+2 until end of turn."}]}))
(defmethod fix-card "Cunning Bandit"
[card]
(assoc-in card
[:multi]
{:name "Azamuki, Treachery Incarnate"
:typelist ["Legendary" "Creature" "Spirit"]
:pow "5"
:tgh "2"
:rulelist [{:number 1
:text "Remove a ki counter from Azamuki, Treachery Incarnate: Gain control of target creature until end of turn."}]}))
(defmethod fix-card "PI:NAME:<NAME>END_PI"
[card]
(-> card
(update-in [:rulelist] (partial take 2))
(assoc :multi {:name "PI:NAME:<NAME>END_PI"
:typelist ["Legendary" "Creature" "Spirit"]
:pow "3"
:tgh "4"
:rulelist [{:number 1
:text "Remove a ki counter from Jaraku the Interloper: Counter target spell unless its controller pays {2}."}]})))
(defmethod fix-card "PI:NAME:<NAME>END_PI MPI:NAME:<NAME>END_PIcle"
[card]
(-> card
(update-in [:rulelist] (partial take 2))
(assoc :multi {:name "PI:NAME:<NAME>END_PI"
:typelist ["Legendary" "Creature" "Spirit"]
:pow "4"
:tgh "4"
:rulelist [{:number 1
:text "Remove a ki counter from Scarmaker: Target creature gains fear until end of turn."
:reminder "It can't be blocked except by artifact creatures and/or black creatures."}]})))
;;--------------------------------------------------
;; interface
(defn fix [card]
(fix-card card))
|
[
{
"context": "iple callers.\n Uses tools from the Marth lab and Erik Garrison to realign and recall given a\n set of possible ",
"end": 172,
"score": 0.9999061822891235,
"start": 159,
"tag": "NAME",
"value": "Erik Garrison"
}
] | src/bcbio/variation/ensemble/realign.clj | roryk/bcbio.variation.recall | 1 | (ns bcbio.variation.ensemble.realign
"Realignment based Ensemble calling approaches using inputs from multiple callers.
Uses tools from the Marth lab and Erik Garrison to realign and recall given a
set of possible variants in a genomic region."
(:require [bcbio.run.fsp :as fsp]
[bcbio.run.itx :as itx]
[bcbio.variation.ensemble.prep :as eprep]
[bcbio.variation.recall.merge :as merge]
[bcbio.variation.recall.square :as square]
[bcbio.variation.recall.vcfutils :as vcfutils]
[clojure.java.io :as io]
[clojure.string :as string]
[me.raynes.fs :as fs]))
(defmulti realign-and-call
(fn [& args]
(keyword (get (last args) :caller :freebayes))))
;; TODO: Incorporate verifyBamID and --contamination-estimates
(defmethod realign-and-call :freebayes
^{:doc "Perform realignment with glia and calling with freebayes in a region of interest."}
[region union-vcf bam-file ref-file work-dir config]
(let [out-file (str (io/file work-dir (str "recall-" (eprep/region->safestr region) ".vcf")))]
(itx/run-cmd out-file
"samtools view -bu ~{bam-file} ~{(eprep/region->samstr region)} | "
"glia -Rr -w 1000 -S 200 -Q 200 -G 4 -f ~{ref-file} -v ~{union-vcf} | "
"freebayes -f ~{ref-file} --variant-input ~{union-vcf} "
"--min-mapping-quality 1 --min-base-quality 3 --stdin | "
;"vcffilter -f 'DP > 4' -f 'QUAL > 20.0' -t PASS -F QualDepthFilter | "
"vcfallelicprimitives -t MNP > ~{out-file}")
out-file))
(defmethod realign-and-call :platypus
^{:doc "Perform realignment and recalling with platypus"}
[region union-vcf bam-file ref-file work-dir config]
(let [out-file (str (io/file work-dir (str "recall-" (eprep/region->safestr region) ".vcf.gz")))
filters ["FR[*] <= 0.5 && TC < 4 && %QUAL < 20",
"FR[*] <= 0.5 && TC < 13 && %QUAL < 10",
"FR[*] > 0.5 && TC < 4 && %QUAL < 20"]
filter_str (string/join " | " (map #(format "bcftools filter -e '%s' 2> /dev/null" %) filters))]
(when (itx/needs-run? out-file)
(itx/run-cmd out-file
"platypus callVariants --bamFiles=~{bam-file} --regions=~{(eprep/region->samstr region)} "
"--hapScoreThreshold 10 --scThreshold 0.99 --filteredReadsFrac 0.9 "
"--rmsmqThreshold 20 --qdThreshold 0 --abThreshold 0.00001 --minVarFreq 0.0 "
"--refFile=~{ref-file} --source=~{union-vcf} --assemble=1 "
"--logFileName /dev/null --verbosity=1 --output - "
"sed 's/\\tQ20\\t/\\tPASS\\t/' | "
"vt normalize -r ~{ref-file} -q - 2> /dev/null | vcfuniqalleles | "
"~{filter_str} | bgzip -c > ~{out-file}"))
(eprep/bgzip-index-vcf out-file :remove-orig? true)))
(defn by-region
"Realign and recall variants in a defined genomic region."
[sample region vcf-files bam-file ref-file dirs e-dir config]
(let [out-file (str (io/file e-dir (format "%s-%s.vcf.gz" sample (eprep/region->safestr region))))
work-dir (str (.getParentFile (io/file out-file)))
prep-dir (fsp/safe-mkdir (io/file work-dir (format "recall-%s-prep" (eprep/region->safestr region))))
union-dir (fsp/safe-mkdir (io/file work-dir "union"))
prep-inputs (map-indexed
(fn [i x]
(let [out-file (str (io/file prep-dir
(format "%s-%s-%s.vcf.gz"
sample (eprep/region->safestr region) i)))]
(square/subset-sample-region x sample region out-file)))
vcf-files)
union-vcf (eprep/create-union :gatk prep-inputs ref-file region union-dir)]
(realign-and-call region union-vcf bam-file ref-file work-dir config)))
(defn by-region-multi
"Realign and recall variants in a region, handling multiple sample inputs."
[vcf-files bam-files region ref-file dirs out-file config]
(let [region-e-dir (fsp/safe-mkdir (io/file (:ensemble dirs) (get region :chrom "nochrom")
(eprep/region->safestr region)))
region-merge-dir (fsp/safe-mkdir (str region-e-dir "-merge"))
final-vcfs (->> vcf-files
(mapcat #(for [s (vcfutils/get-samples %)] [s %]))
(group-by first)
(map (fn [[sample s-vcfs]]
(by-region sample region (map second s-vcfs) (get bam-files sample)
ref-file dirs region-e-dir config))))]
(merge/region-merge :gatk final-vcfs region ref-file region-merge-dir out-file)))
(defn ensemble-vcfs
"Combine VCF files with squaring off by recalling at uncalled variant positions."
[orig-vcf-files bam-files ref-file out-file config]
(let [dirs {:ensemble (fsp/safe-mkdir (io/file (fs/parent out-file) "ensemble"))
:inprep (fsp/safe-mkdir (io/file (fs/parent out-file) "inprep"))}
bam-map (square/sample-to-bam-map bam-files ref-file (:inprep dirs))]
(merge/prep-by-region (fn [vcf-files region merge-dir]
(by-region-multi vcf-files bam-map region ref-file
(assoc dirs :merge merge-dir) out-file config))
orig-vcf-files ref-file out-file config)))
| 64344 | (ns bcbio.variation.ensemble.realign
"Realignment based Ensemble calling approaches using inputs from multiple callers.
Uses tools from the Marth lab and <NAME> to realign and recall given a
set of possible variants in a genomic region."
(:require [bcbio.run.fsp :as fsp]
[bcbio.run.itx :as itx]
[bcbio.variation.ensemble.prep :as eprep]
[bcbio.variation.recall.merge :as merge]
[bcbio.variation.recall.square :as square]
[bcbio.variation.recall.vcfutils :as vcfutils]
[clojure.java.io :as io]
[clojure.string :as string]
[me.raynes.fs :as fs]))
(defmulti realign-and-call
(fn [& args]
(keyword (get (last args) :caller :freebayes))))
;; TODO: Incorporate verifyBamID and --contamination-estimates
(defmethod realign-and-call :freebayes
^{:doc "Perform realignment with glia and calling with freebayes in a region of interest."}
[region union-vcf bam-file ref-file work-dir config]
(let [out-file (str (io/file work-dir (str "recall-" (eprep/region->safestr region) ".vcf")))]
(itx/run-cmd out-file
"samtools view -bu ~{bam-file} ~{(eprep/region->samstr region)} | "
"glia -Rr -w 1000 -S 200 -Q 200 -G 4 -f ~{ref-file} -v ~{union-vcf} | "
"freebayes -f ~{ref-file} --variant-input ~{union-vcf} "
"--min-mapping-quality 1 --min-base-quality 3 --stdin | "
;"vcffilter -f 'DP > 4' -f 'QUAL > 20.0' -t PASS -F QualDepthFilter | "
"vcfallelicprimitives -t MNP > ~{out-file}")
out-file))
(defmethod realign-and-call :platypus
^{:doc "Perform realignment and recalling with platypus"}
[region union-vcf bam-file ref-file work-dir config]
(let [out-file (str (io/file work-dir (str "recall-" (eprep/region->safestr region) ".vcf.gz")))
filters ["FR[*] <= 0.5 && TC < 4 && %QUAL < 20",
"FR[*] <= 0.5 && TC < 13 && %QUAL < 10",
"FR[*] > 0.5 && TC < 4 && %QUAL < 20"]
filter_str (string/join " | " (map #(format "bcftools filter -e '%s' 2> /dev/null" %) filters))]
(when (itx/needs-run? out-file)
(itx/run-cmd out-file
"platypus callVariants --bamFiles=~{bam-file} --regions=~{(eprep/region->samstr region)} "
"--hapScoreThreshold 10 --scThreshold 0.99 --filteredReadsFrac 0.9 "
"--rmsmqThreshold 20 --qdThreshold 0 --abThreshold 0.00001 --minVarFreq 0.0 "
"--refFile=~{ref-file} --source=~{union-vcf} --assemble=1 "
"--logFileName /dev/null --verbosity=1 --output - "
"sed 's/\\tQ20\\t/\\tPASS\\t/' | "
"vt normalize -r ~{ref-file} -q - 2> /dev/null | vcfuniqalleles | "
"~{filter_str} | bgzip -c > ~{out-file}"))
(eprep/bgzip-index-vcf out-file :remove-orig? true)))
(defn by-region
"Realign and recall variants in a defined genomic region."
[sample region vcf-files bam-file ref-file dirs e-dir config]
(let [out-file (str (io/file e-dir (format "%s-%s.vcf.gz" sample (eprep/region->safestr region))))
work-dir (str (.getParentFile (io/file out-file)))
prep-dir (fsp/safe-mkdir (io/file work-dir (format "recall-%s-prep" (eprep/region->safestr region))))
union-dir (fsp/safe-mkdir (io/file work-dir "union"))
prep-inputs (map-indexed
(fn [i x]
(let [out-file (str (io/file prep-dir
(format "%s-%s-%s.vcf.gz"
sample (eprep/region->safestr region) i)))]
(square/subset-sample-region x sample region out-file)))
vcf-files)
union-vcf (eprep/create-union :gatk prep-inputs ref-file region union-dir)]
(realign-and-call region union-vcf bam-file ref-file work-dir config)))
(defn by-region-multi
"Realign and recall variants in a region, handling multiple sample inputs."
[vcf-files bam-files region ref-file dirs out-file config]
(let [region-e-dir (fsp/safe-mkdir (io/file (:ensemble dirs) (get region :chrom "nochrom")
(eprep/region->safestr region)))
region-merge-dir (fsp/safe-mkdir (str region-e-dir "-merge"))
final-vcfs (->> vcf-files
(mapcat #(for [s (vcfutils/get-samples %)] [s %]))
(group-by first)
(map (fn [[sample s-vcfs]]
(by-region sample region (map second s-vcfs) (get bam-files sample)
ref-file dirs region-e-dir config))))]
(merge/region-merge :gatk final-vcfs region ref-file region-merge-dir out-file)))
(defn ensemble-vcfs
"Combine VCF files with squaring off by recalling at uncalled variant positions."
[orig-vcf-files bam-files ref-file out-file config]
(let [dirs {:ensemble (fsp/safe-mkdir (io/file (fs/parent out-file) "ensemble"))
:inprep (fsp/safe-mkdir (io/file (fs/parent out-file) "inprep"))}
bam-map (square/sample-to-bam-map bam-files ref-file (:inprep dirs))]
(merge/prep-by-region (fn [vcf-files region merge-dir]
(by-region-multi vcf-files bam-map region ref-file
(assoc dirs :merge merge-dir) out-file config))
orig-vcf-files ref-file out-file config)))
| true | (ns bcbio.variation.ensemble.realign
"Realignment based Ensemble calling approaches using inputs from multiple callers.
Uses tools from the Marth lab and PI:NAME:<NAME>END_PI to realign and recall given a
set of possible variants in a genomic region."
(:require [bcbio.run.fsp :as fsp]
[bcbio.run.itx :as itx]
[bcbio.variation.ensemble.prep :as eprep]
[bcbio.variation.recall.merge :as merge]
[bcbio.variation.recall.square :as square]
[bcbio.variation.recall.vcfutils :as vcfutils]
[clojure.java.io :as io]
[clojure.string :as string]
[me.raynes.fs :as fs]))
(defmulti realign-and-call
(fn [& args]
(keyword (get (last args) :caller :freebayes))))
;; TODO: Incorporate verifyBamID and --contamination-estimates
(defmethod realign-and-call :freebayes
^{:doc "Perform realignment with glia and calling with freebayes in a region of interest."}
[region union-vcf bam-file ref-file work-dir config]
(let [out-file (str (io/file work-dir (str "recall-" (eprep/region->safestr region) ".vcf")))]
(itx/run-cmd out-file
"samtools view -bu ~{bam-file} ~{(eprep/region->samstr region)} | "
"glia -Rr -w 1000 -S 200 -Q 200 -G 4 -f ~{ref-file} -v ~{union-vcf} | "
"freebayes -f ~{ref-file} --variant-input ~{union-vcf} "
"--min-mapping-quality 1 --min-base-quality 3 --stdin | "
;"vcffilter -f 'DP > 4' -f 'QUAL > 20.0' -t PASS -F QualDepthFilter | "
"vcfallelicprimitives -t MNP > ~{out-file}")
out-file))
(defmethod realign-and-call :platypus
^{:doc "Perform realignment and recalling with platypus"}
[region union-vcf bam-file ref-file work-dir config]
(let [out-file (str (io/file work-dir (str "recall-" (eprep/region->safestr region) ".vcf.gz")))
filters ["FR[*] <= 0.5 && TC < 4 && %QUAL < 20",
"FR[*] <= 0.5 && TC < 13 && %QUAL < 10",
"FR[*] > 0.5 && TC < 4 && %QUAL < 20"]
filter_str (string/join " | " (map #(format "bcftools filter -e '%s' 2> /dev/null" %) filters))]
(when (itx/needs-run? out-file)
(itx/run-cmd out-file
"platypus callVariants --bamFiles=~{bam-file} --regions=~{(eprep/region->samstr region)} "
"--hapScoreThreshold 10 --scThreshold 0.99 --filteredReadsFrac 0.9 "
"--rmsmqThreshold 20 --qdThreshold 0 --abThreshold 0.00001 --minVarFreq 0.0 "
"--refFile=~{ref-file} --source=~{union-vcf} --assemble=1 "
"--logFileName /dev/null --verbosity=1 --output - "
"sed 's/\\tQ20\\t/\\tPASS\\t/' | "
"vt normalize -r ~{ref-file} -q - 2> /dev/null | vcfuniqalleles | "
"~{filter_str} | bgzip -c > ~{out-file}"))
(eprep/bgzip-index-vcf out-file :remove-orig? true)))
(defn by-region
"Realign and recall variants in a defined genomic region."
[sample region vcf-files bam-file ref-file dirs e-dir config]
(let [out-file (str (io/file e-dir (format "%s-%s.vcf.gz" sample (eprep/region->safestr region))))
work-dir (str (.getParentFile (io/file out-file)))
prep-dir (fsp/safe-mkdir (io/file work-dir (format "recall-%s-prep" (eprep/region->safestr region))))
union-dir (fsp/safe-mkdir (io/file work-dir "union"))
prep-inputs (map-indexed
(fn [i x]
(let [out-file (str (io/file prep-dir
(format "%s-%s-%s.vcf.gz"
sample (eprep/region->safestr region) i)))]
(square/subset-sample-region x sample region out-file)))
vcf-files)
union-vcf (eprep/create-union :gatk prep-inputs ref-file region union-dir)]
(realign-and-call region union-vcf bam-file ref-file work-dir config)))
(defn by-region-multi
"Realign and recall variants in a region, handling multiple sample inputs."
[vcf-files bam-files region ref-file dirs out-file config]
(let [region-e-dir (fsp/safe-mkdir (io/file (:ensemble dirs) (get region :chrom "nochrom")
(eprep/region->safestr region)))
region-merge-dir (fsp/safe-mkdir (str region-e-dir "-merge"))
final-vcfs (->> vcf-files
(mapcat #(for [s (vcfutils/get-samples %)] [s %]))
(group-by first)
(map (fn [[sample s-vcfs]]
(by-region sample region (map second s-vcfs) (get bam-files sample)
ref-file dirs region-e-dir config))))]
(merge/region-merge :gatk final-vcfs region ref-file region-merge-dir out-file)))
(defn ensemble-vcfs
"Combine VCF files with squaring off by recalling at uncalled variant positions."
[orig-vcf-files bam-files ref-file out-file config]
(let [dirs {:ensemble (fsp/safe-mkdir (io/file (fs/parent out-file) "ensemble"))
:inprep (fsp/safe-mkdir (io/file (fs/parent out-file) "inprep"))}
bam-map (square/sample-to-bam-map bam-files ref-file (:inprep dirs))]
(merge/prep-by-region (fn [vcf-files region merge-dir]
(by-region-multi vcf-files bam-map region ref-file
(assoc dirs :merge merge-dir) out-file config))
orig-vcf-files ref-file out-file config)))
|
[
{
"context": "-str (pprint status))]])])))\n\n(defn post [{:keys [name author message timestamp avatar id]\n ",
"end": 7438,
"score": 0.7092654705047607,
"start": 7434,
"tag": "NAME",
"value": "name"
},
{
"context": " (pprint status))]])])))\n\n(defn post [{:keys [name author message timestamp avatar id]\n :as pos",
"end": 7445,
"score": 0.597665548324585,
"start": 7439,
"tag": "NAME",
"value": "author"
}
] | src/cljs/guestbook/views/post.cljs | trevorjamesmartin/guestbook | 0 | (ns guestbook.views.post
(:require
[re-frame.core :as rf]
[reagent.core :as r]
[cljs.pprint :refer [pprint]]
[guestbook.messages :as msg]
[reagent.dom :as dom]))
(defn clear-post-keys [db]
(dissoc db ::error ::post))
(rf/reg-event-fx
::fetch-replies
(fn [{:keys [db]} [_ post-id]]
{:db (assoc-in db [::replies-status post-id] :loading)
:ajax/get {:url (str "/api/message/" post-id "/replies")
:success-path [:replies]
:success-event [::add-replies post-id]
:error-event [::set-replies-error post-id]}}))
(rf/reg-event-db
::add-replies
(fn [db [_ post-id replies]]
(-> db
(update ::posts (fnil into {}) (map (juxt :id identity)) replies)
(assoc-in [::replies post-id] (map :id replies))
(assoc-in [::replies-status post-id] :success))))
(rf/reg-event-db
::set-replies-error
(fn [db [_ post-id response]]
(-> db
(assoc-in [::replies-status post-id] response))))
(rf/reg-event-db
::clear-replies
(fn [db _]
(dissoc db ::posts ::replies ::replies-status)))
(rf/reg-sub
::posts
(fn [db _]
(assoc
(::posts db)
(::id (::post db))
(::post db))))
(rf/reg-sub
::reply
:<- [::posts]
(fn [posts [_ id]]
(get posts id)))
(rf/reg-sub
::replies-map
(fn [db _]
(::replies db)))
(rf/reg-sub
::replies-for-post
:<- [::replies-map]
(fn [replies [_ id]]
(get replies id)))
(rf/reg-sub
::replies-status-map
(fn [db _]
(::replies-status db)))
(rf/reg-sub
::replies-status
:<- [::replies-status-map]
(fn [statuses [_ id]]
(get statuses id)))
(rf/reg-event-fx
::fetch-post
(fn [{:keys [db]} [_ post-id]]
{:db (clear-post-keys db)
:ajax/get {:url (str "/api/message/" post-id)
:success-path [:message]
:success-event [::set-post]
:error-event [::set-post-error]}}))
(rf/reg-event-db
::set-post
(fn [db [_ post]]
(assoc db ::post post)))
(rf/reg-event-db
::set-post-error
(fn [db [_ response]]
(assoc db :error response)))
(rf/reg-event-db
::clear-post
(fn [db _]
(clear-post-keys db)))
(rf/reg-sub
::post
(fn [db _]
(::post db nil)))
(rf/reg-sub
::error
(fn [db _]
(::error db)))
(rf/reg-sub
::loading?
:<- [::post]
:<- [::error]
(fn [[post error] _]
(and (empty? post) (empty? error))))
(rf/reg-sub
::reply-count
(fn [[_ id] _]
(rf/subscribe [::reply id]))
(fn [post _]
(:reply_count post)))
(rf/reg-sub
::has-replies?
(fn [[_ id] _]
(rf/subscribe [::reply-count id]))
(fn [c _]
(not= c 0)))
(rf/reg-sub
::replies-to-load
(fn [[_ id] _]
[(rf/subscribe [::reply-count id]) (rf/subscribe [::replies-for-post id])])
(fn [[c replies] _]
(- c (count replies))))
(rf/reg-event-db
::expand-post
(fn [db [_ id]]
(update db ::expanded-posts (fnil conj #{}) id)))
(rf/reg-event-db
::collapse-post
(fn [db [_ id]]
(update db ::expanded-posts (fnil disj #{}) id)))
(rf/reg-event-db
::collapse-all
(fn [db [_ id]]
(dissoc db ::expanded-posts)))
(rf/reg-sub
::post-expanded?
(fn [db [_ id]]
(contains? (::expanded-posts db) id)))
(rf/reg-event-db
::add-message
(fn [db [_ post-id {:keys [root_id messages]}]]
(if (= post-id root_id)
(let [parent-id (:id (second messages))]
(if (= parent-id post-id)
(update-in db [::post :reply_count] inc)
(update db ::posts
#(if (contains? % parent-id)
(update-in % [parent-id :reply_count] inc)
%))))
db)))
(rf/reg-event-fx
::fetch-parents
(fn [{:keys [db]} [_ post-id]]
{:ajax/get {:url (str "/api/message/" post-id "/parents")
:success-path [:parents]
:success-event [::add-parents post-id]}}))
(defn add-post-to-db [db {:keys [id parent] :as post}]
(-> db
(assoc-in [::posts id] post)
(update-in [::replies parent]
#(if (some (partial = id) %)
%
(conj % id)))
(assoc-in [::replies-status id] :success)
(update ::expanded-posts (fnil conj #{}) id)))
(rf/reg-event-db
::add-parents
(fn [db [_ post-id parents]]
(reduce add-post-to-db db parents)))
(def post-controllers
[{:parameters {:path [:post]}
:start (fn [{{:keys [post]} :path}]
(rf/dispatch [:ws/set-message-add-handler [::add-message post]])
(rf/dispatch [::fetch-post post])
(rf/dispatch [::fetch-replies post]))
:stop (fn [_]
(rf/dispatch [:ws/set-message-add-handler nil])
(rf/dispatch [::collapse-all])
(rf/dispatch [::clear-post])
(rf/dispatch [::clear-replies]))}
{:parameters {:query [:reply]}
:start (fn [{{:keys [reply]} :query}]
(when reply
(rf/dispatch [::set-scroll-to reply])
(rf/dispatch [::fetch-parents reply])))
:stop (fn [_]
(rf/dispatch [::set-scroll-to nil]))
}
])
(defn loading-bar []
[:progress.progress.is-dark {:max 100} "30%"])
(rf/reg-event-db
::set-scroll-to
(fn [db [_ id]]
(if (nil? id)
(dissoc db ::scroll-to-post)
(assoc db ::scroll-to-post id))))
(rf/reg-sub
::scroll?
(fn [db [_ id]]
(= id (::scroll-to-post db))))
(defn reply [post-id]
(r/create-class
{:component-did-mount
(fn [this]
(when @(rf/subscribe [::scroll? post-id])
(rf/dispatch [::set-scroll-to nil])
(.scrollIntoView (dom/dom-node this))))
:reagent-render
(fn [_]
[msg/message
@(rf/subscribe [::reply post-id])
{:include-link? false}])}))
(defn expand-control [post-id]
(let [expanded? @(rf/subscribe [::post-expanded? post-id])
reply-count @(rf/subscribe [::reply-count post-id])
replies-to-load @(rf/subscribe [::replies-to-load post-id])
loaded? (= replies-to-load 0)
status @(rf/subscribe [::replies-status post-id])]
[:div.field.has-addons
[:p.control>span.button.is-static reply-count " replies"]
[:p.control>button.button
{:on-click (fn []
(if expanded?
(rf/dispatch [::collapse-post post-id])
(do
(when-not loaded?
(rf/dispatch [::fetch-replies post-id]))
(rf/dispatch [::expand-post post-id]))))
:disabled (= status :loading)}
(str (if expanded? "-" "+"))]
(when expanded?
[:p.control>button.button
{:on-click #(rf/dispatch [::fetch-replies post-id])
:disabled (= status :loading)}
(if loaded?
"↻"
(str "Load " replies-to-load " New Replies"))])]))
(defn reply-tree [post-id]
(when @(rf/subscribe [::has-replies? post-id])
(let [status @(rf/subscribe [::replies-status post-id])]
[:<>
[expand-control post-id]
(case status
nil nil
:success
(when @(rf/subscribe [::post-expanded? post-id])
[:div
{:style {:border-left "1px dotted blue"
:padding-left "10px"}}
(doall
(for [id @(rf/subscribe [::replies-for-post post-id])]
^{:key id}
[:<>
[reply id]
[reply-tree id]]))])
:loading [loading-bar]
;; ELSE
[:div
[:h3 "Error"]
[:pre (with-out-str (pprint status))]])])))
(defn post [{:keys [name author message timestamp avatar id]
:as post-content}]
[:div.content
[:button.button.is-info.is-outlined.is-fullwidth
{:on-click #(.back js/window.history)}
"Back to Feed"]
[:h3.title.is-3 "Post by " name
"<" [:a {:href (str "/user/" author)} (str "@" author)]
">"]
[:h4.subtitle.is-4 "Posted at " (.toLocaleString timestamp)]
[msg/message post-content {:include-link? false}]
[reply-tree id]])
(defn post-page [_]
(let [post-content @(rf/subscribe [::post])
{status :status
{:keys [message]} :response
:as error} @(rf/subscribe [::error])]
(cond
@(rf/subscribe [::loading?])
[:div.content
[:p "Loading Message..."]
[loading-bar]]
(seq error)
(case status
404
[:div.content
[:p (or message "Post Not Found.")]
[:pre (with-out-str (pprint error))]]
403
[:div.content
[:p (or message "You are not allowed to visit this post.")]
[:pre (with-out-str (pprint error))]]
500
[:div
[:p (or message "Unknown Error.")]
[:pre (with-out-str (pprint error))]])
(seq post-content)
[post post-content])))
| 59547 | (ns guestbook.views.post
(:require
[re-frame.core :as rf]
[reagent.core :as r]
[cljs.pprint :refer [pprint]]
[guestbook.messages :as msg]
[reagent.dom :as dom]))
(defn clear-post-keys [db]
(dissoc db ::error ::post))
(rf/reg-event-fx
::fetch-replies
(fn [{:keys [db]} [_ post-id]]
{:db (assoc-in db [::replies-status post-id] :loading)
:ajax/get {:url (str "/api/message/" post-id "/replies")
:success-path [:replies]
:success-event [::add-replies post-id]
:error-event [::set-replies-error post-id]}}))
(rf/reg-event-db
::add-replies
(fn [db [_ post-id replies]]
(-> db
(update ::posts (fnil into {}) (map (juxt :id identity)) replies)
(assoc-in [::replies post-id] (map :id replies))
(assoc-in [::replies-status post-id] :success))))
(rf/reg-event-db
::set-replies-error
(fn [db [_ post-id response]]
(-> db
(assoc-in [::replies-status post-id] response))))
(rf/reg-event-db
::clear-replies
(fn [db _]
(dissoc db ::posts ::replies ::replies-status)))
(rf/reg-sub
::posts
(fn [db _]
(assoc
(::posts db)
(::id (::post db))
(::post db))))
(rf/reg-sub
::reply
:<- [::posts]
(fn [posts [_ id]]
(get posts id)))
(rf/reg-sub
::replies-map
(fn [db _]
(::replies db)))
(rf/reg-sub
::replies-for-post
:<- [::replies-map]
(fn [replies [_ id]]
(get replies id)))
(rf/reg-sub
::replies-status-map
(fn [db _]
(::replies-status db)))
(rf/reg-sub
::replies-status
:<- [::replies-status-map]
(fn [statuses [_ id]]
(get statuses id)))
(rf/reg-event-fx
::fetch-post
(fn [{:keys [db]} [_ post-id]]
{:db (clear-post-keys db)
:ajax/get {:url (str "/api/message/" post-id)
:success-path [:message]
:success-event [::set-post]
:error-event [::set-post-error]}}))
(rf/reg-event-db
::set-post
(fn [db [_ post]]
(assoc db ::post post)))
(rf/reg-event-db
::set-post-error
(fn [db [_ response]]
(assoc db :error response)))
(rf/reg-event-db
::clear-post
(fn [db _]
(clear-post-keys db)))
(rf/reg-sub
::post
(fn [db _]
(::post db nil)))
(rf/reg-sub
::error
(fn [db _]
(::error db)))
(rf/reg-sub
::loading?
:<- [::post]
:<- [::error]
(fn [[post error] _]
(and (empty? post) (empty? error))))
(rf/reg-sub
::reply-count
(fn [[_ id] _]
(rf/subscribe [::reply id]))
(fn [post _]
(:reply_count post)))
(rf/reg-sub
::has-replies?
(fn [[_ id] _]
(rf/subscribe [::reply-count id]))
(fn [c _]
(not= c 0)))
(rf/reg-sub
::replies-to-load
(fn [[_ id] _]
[(rf/subscribe [::reply-count id]) (rf/subscribe [::replies-for-post id])])
(fn [[c replies] _]
(- c (count replies))))
(rf/reg-event-db
::expand-post
(fn [db [_ id]]
(update db ::expanded-posts (fnil conj #{}) id)))
(rf/reg-event-db
::collapse-post
(fn [db [_ id]]
(update db ::expanded-posts (fnil disj #{}) id)))
(rf/reg-event-db
::collapse-all
(fn [db [_ id]]
(dissoc db ::expanded-posts)))
(rf/reg-sub
::post-expanded?
(fn [db [_ id]]
(contains? (::expanded-posts db) id)))
(rf/reg-event-db
::add-message
(fn [db [_ post-id {:keys [root_id messages]}]]
(if (= post-id root_id)
(let [parent-id (:id (second messages))]
(if (= parent-id post-id)
(update-in db [::post :reply_count] inc)
(update db ::posts
#(if (contains? % parent-id)
(update-in % [parent-id :reply_count] inc)
%))))
db)))
(rf/reg-event-fx
::fetch-parents
(fn [{:keys [db]} [_ post-id]]
{:ajax/get {:url (str "/api/message/" post-id "/parents")
:success-path [:parents]
:success-event [::add-parents post-id]}}))
(defn add-post-to-db [db {:keys [id parent] :as post}]
(-> db
(assoc-in [::posts id] post)
(update-in [::replies parent]
#(if (some (partial = id) %)
%
(conj % id)))
(assoc-in [::replies-status id] :success)
(update ::expanded-posts (fnil conj #{}) id)))
(rf/reg-event-db
::add-parents
(fn [db [_ post-id parents]]
(reduce add-post-to-db db parents)))
(def post-controllers
[{:parameters {:path [:post]}
:start (fn [{{:keys [post]} :path}]
(rf/dispatch [:ws/set-message-add-handler [::add-message post]])
(rf/dispatch [::fetch-post post])
(rf/dispatch [::fetch-replies post]))
:stop (fn [_]
(rf/dispatch [:ws/set-message-add-handler nil])
(rf/dispatch [::collapse-all])
(rf/dispatch [::clear-post])
(rf/dispatch [::clear-replies]))}
{:parameters {:query [:reply]}
:start (fn [{{:keys [reply]} :query}]
(when reply
(rf/dispatch [::set-scroll-to reply])
(rf/dispatch [::fetch-parents reply])))
:stop (fn [_]
(rf/dispatch [::set-scroll-to nil]))
}
])
(defn loading-bar []
[:progress.progress.is-dark {:max 100} "30%"])
(rf/reg-event-db
::set-scroll-to
(fn [db [_ id]]
(if (nil? id)
(dissoc db ::scroll-to-post)
(assoc db ::scroll-to-post id))))
(rf/reg-sub
::scroll?
(fn [db [_ id]]
(= id (::scroll-to-post db))))
(defn reply [post-id]
(r/create-class
{:component-did-mount
(fn [this]
(when @(rf/subscribe [::scroll? post-id])
(rf/dispatch [::set-scroll-to nil])
(.scrollIntoView (dom/dom-node this))))
:reagent-render
(fn [_]
[msg/message
@(rf/subscribe [::reply post-id])
{:include-link? false}])}))
(defn expand-control [post-id]
(let [expanded? @(rf/subscribe [::post-expanded? post-id])
reply-count @(rf/subscribe [::reply-count post-id])
replies-to-load @(rf/subscribe [::replies-to-load post-id])
loaded? (= replies-to-load 0)
status @(rf/subscribe [::replies-status post-id])]
[:div.field.has-addons
[:p.control>span.button.is-static reply-count " replies"]
[:p.control>button.button
{:on-click (fn []
(if expanded?
(rf/dispatch [::collapse-post post-id])
(do
(when-not loaded?
(rf/dispatch [::fetch-replies post-id]))
(rf/dispatch [::expand-post post-id]))))
:disabled (= status :loading)}
(str (if expanded? "-" "+"))]
(when expanded?
[:p.control>button.button
{:on-click #(rf/dispatch [::fetch-replies post-id])
:disabled (= status :loading)}
(if loaded?
"↻"
(str "Load " replies-to-load " New Replies"))])]))
(defn reply-tree [post-id]
(when @(rf/subscribe [::has-replies? post-id])
(let [status @(rf/subscribe [::replies-status post-id])]
[:<>
[expand-control post-id]
(case status
nil nil
:success
(when @(rf/subscribe [::post-expanded? post-id])
[:div
{:style {:border-left "1px dotted blue"
:padding-left "10px"}}
(doall
(for [id @(rf/subscribe [::replies-for-post post-id])]
^{:key id}
[:<>
[reply id]
[reply-tree id]]))])
:loading [loading-bar]
;; ELSE
[:div
[:h3 "Error"]
[:pre (with-out-str (pprint status))]])])))
(defn post [{:keys [<NAME> <NAME> message timestamp avatar id]
:as post-content}]
[:div.content
[:button.button.is-info.is-outlined.is-fullwidth
{:on-click #(.back js/window.history)}
"Back to Feed"]
[:h3.title.is-3 "Post by " name
"<" [:a {:href (str "/user/" author)} (str "@" author)]
">"]
[:h4.subtitle.is-4 "Posted at " (.toLocaleString timestamp)]
[msg/message post-content {:include-link? false}]
[reply-tree id]])
(defn post-page [_]
(let [post-content @(rf/subscribe [::post])
{status :status
{:keys [message]} :response
:as error} @(rf/subscribe [::error])]
(cond
@(rf/subscribe [::loading?])
[:div.content
[:p "Loading Message..."]
[loading-bar]]
(seq error)
(case status
404
[:div.content
[:p (or message "Post Not Found.")]
[:pre (with-out-str (pprint error))]]
403
[:div.content
[:p (or message "You are not allowed to visit this post.")]
[:pre (with-out-str (pprint error))]]
500
[:div
[:p (or message "Unknown Error.")]
[:pre (with-out-str (pprint error))]])
(seq post-content)
[post post-content])))
| true | (ns guestbook.views.post
(:require
[re-frame.core :as rf]
[reagent.core :as r]
[cljs.pprint :refer [pprint]]
[guestbook.messages :as msg]
[reagent.dom :as dom]))
(defn clear-post-keys [db]
(dissoc db ::error ::post))
(rf/reg-event-fx
::fetch-replies
(fn [{:keys [db]} [_ post-id]]
{:db (assoc-in db [::replies-status post-id] :loading)
:ajax/get {:url (str "/api/message/" post-id "/replies")
:success-path [:replies]
:success-event [::add-replies post-id]
:error-event [::set-replies-error post-id]}}))
(rf/reg-event-db
::add-replies
(fn [db [_ post-id replies]]
(-> db
(update ::posts (fnil into {}) (map (juxt :id identity)) replies)
(assoc-in [::replies post-id] (map :id replies))
(assoc-in [::replies-status post-id] :success))))
(rf/reg-event-db
::set-replies-error
(fn [db [_ post-id response]]
(-> db
(assoc-in [::replies-status post-id] response))))
(rf/reg-event-db
::clear-replies
(fn [db _]
(dissoc db ::posts ::replies ::replies-status)))
(rf/reg-sub
::posts
(fn [db _]
(assoc
(::posts db)
(::id (::post db))
(::post db))))
(rf/reg-sub
::reply
:<- [::posts]
(fn [posts [_ id]]
(get posts id)))
(rf/reg-sub
::replies-map
(fn [db _]
(::replies db)))
(rf/reg-sub
::replies-for-post
:<- [::replies-map]
(fn [replies [_ id]]
(get replies id)))
(rf/reg-sub
::replies-status-map
(fn [db _]
(::replies-status db)))
(rf/reg-sub
::replies-status
:<- [::replies-status-map]
(fn [statuses [_ id]]
(get statuses id)))
(rf/reg-event-fx
::fetch-post
(fn [{:keys [db]} [_ post-id]]
{:db (clear-post-keys db)
:ajax/get {:url (str "/api/message/" post-id)
:success-path [:message]
:success-event [::set-post]
:error-event [::set-post-error]}}))
(rf/reg-event-db
::set-post
(fn [db [_ post]]
(assoc db ::post post)))
(rf/reg-event-db
::set-post-error
(fn [db [_ response]]
(assoc db :error response)))
(rf/reg-event-db
::clear-post
(fn [db _]
(clear-post-keys db)))
(rf/reg-sub
::post
(fn [db _]
(::post db nil)))
(rf/reg-sub
::error
(fn [db _]
(::error db)))
(rf/reg-sub
::loading?
:<- [::post]
:<- [::error]
(fn [[post error] _]
(and (empty? post) (empty? error))))
(rf/reg-sub
::reply-count
(fn [[_ id] _]
(rf/subscribe [::reply id]))
(fn [post _]
(:reply_count post)))
(rf/reg-sub
::has-replies?
(fn [[_ id] _]
(rf/subscribe [::reply-count id]))
(fn [c _]
(not= c 0)))
(rf/reg-sub
::replies-to-load
(fn [[_ id] _]
[(rf/subscribe [::reply-count id]) (rf/subscribe [::replies-for-post id])])
(fn [[c replies] _]
(- c (count replies))))
(rf/reg-event-db
::expand-post
(fn [db [_ id]]
(update db ::expanded-posts (fnil conj #{}) id)))
(rf/reg-event-db
::collapse-post
(fn [db [_ id]]
(update db ::expanded-posts (fnil disj #{}) id)))
(rf/reg-event-db
::collapse-all
(fn [db [_ id]]
(dissoc db ::expanded-posts)))
(rf/reg-sub
::post-expanded?
(fn [db [_ id]]
(contains? (::expanded-posts db) id)))
(rf/reg-event-db
::add-message
(fn [db [_ post-id {:keys [root_id messages]}]]
(if (= post-id root_id)
(let [parent-id (:id (second messages))]
(if (= parent-id post-id)
(update-in db [::post :reply_count] inc)
(update db ::posts
#(if (contains? % parent-id)
(update-in % [parent-id :reply_count] inc)
%))))
db)))
(rf/reg-event-fx
::fetch-parents
(fn [{:keys [db]} [_ post-id]]
{:ajax/get {:url (str "/api/message/" post-id "/parents")
:success-path [:parents]
:success-event [::add-parents post-id]}}))
(defn add-post-to-db [db {:keys [id parent] :as post}]
(-> db
(assoc-in [::posts id] post)
(update-in [::replies parent]
#(if (some (partial = id) %)
%
(conj % id)))
(assoc-in [::replies-status id] :success)
(update ::expanded-posts (fnil conj #{}) id)))
(rf/reg-event-db
::add-parents
(fn [db [_ post-id parents]]
(reduce add-post-to-db db parents)))
(def post-controllers
[{:parameters {:path [:post]}
:start (fn [{{:keys [post]} :path}]
(rf/dispatch [:ws/set-message-add-handler [::add-message post]])
(rf/dispatch [::fetch-post post])
(rf/dispatch [::fetch-replies post]))
:stop (fn [_]
(rf/dispatch [:ws/set-message-add-handler nil])
(rf/dispatch [::collapse-all])
(rf/dispatch [::clear-post])
(rf/dispatch [::clear-replies]))}
{:parameters {:query [:reply]}
:start (fn [{{:keys [reply]} :query}]
(when reply
(rf/dispatch [::set-scroll-to reply])
(rf/dispatch [::fetch-parents reply])))
:stop (fn [_]
(rf/dispatch [::set-scroll-to nil]))
}
])
(defn loading-bar []
[:progress.progress.is-dark {:max 100} "30%"])
(rf/reg-event-db
::set-scroll-to
(fn [db [_ id]]
(if (nil? id)
(dissoc db ::scroll-to-post)
(assoc db ::scroll-to-post id))))
(rf/reg-sub
::scroll?
(fn [db [_ id]]
(= id (::scroll-to-post db))))
(defn reply [post-id]
(r/create-class
{:component-did-mount
(fn [this]
(when @(rf/subscribe [::scroll? post-id])
(rf/dispatch [::set-scroll-to nil])
(.scrollIntoView (dom/dom-node this))))
:reagent-render
(fn [_]
[msg/message
@(rf/subscribe [::reply post-id])
{:include-link? false}])}))
(defn expand-control [post-id]
(let [expanded? @(rf/subscribe [::post-expanded? post-id])
reply-count @(rf/subscribe [::reply-count post-id])
replies-to-load @(rf/subscribe [::replies-to-load post-id])
loaded? (= replies-to-load 0)
status @(rf/subscribe [::replies-status post-id])]
[:div.field.has-addons
[:p.control>span.button.is-static reply-count " replies"]
[:p.control>button.button
{:on-click (fn []
(if expanded?
(rf/dispatch [::collapse-post post-id])
(do
(when-not loaded?
(rf/dispatch [::fetch-replies post-id]))
(rf/dispatch [::expand-post post-id]))))
:disabled (= status :loading)}
(str (if expanded? "-" "+"))]
(when expanded?
[:p.control>button.button
{:on-click #(rf/dispatch [::fetch-replies post-id])
:disabled (= status :loading)}
(if loaded?
"↻"
(str "Load " replies-to-load " New Replies"))])]))
(defn reply-tree [post-id]
(when @(rf/subscribe [::has-replies? post-id])
(let [status @(rf/subscribe [::replies-status post-id])]
[:<>
[expand-control post-id]
(case status
nil nil
:success
(when @(rf/subscribe [::post-expanded? post-id])
[:div
{:style {:border-left "1px dotted blue"
:padding-left "10px"}}
(doall
(for [id @(rf/subscribe [::replies-for-post post-id])]
^{:key id}
[:<>
[reply id]
[reply-tree id]]))])
:loading [loading-bar]
;; ELSE
[:div
[:h3 "Error"]
[:pre (with-out-str (pprint status))]])])))
(defn post [{:keys [PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI message timestamp avatar id]
:as post-content}]
[:div.content
[:button.button.is-info.is-outlined.is-fullwidth
{:on-click #(.back js/window.history)}
"Back to Feed"]
[:h3.title.is-3 "Post by " name
"<" [:a {:href (str "/user/" author)} (str "@" author)]
">"]
[:h4.subtitle.is-4 "Posted at " (.toLocaleString timestamp)]
[msg/message post-content {:include-link? false}]
[reply-tree id]])
(defn post-page [_]
(let [post-content @(rf/subscribe [::post])
{status :status
{:keys [message]} :response
:as error} @(rf/subscribe [::error])]
(cond
@(rf/subscribe [::loading?])
[:div.content
[:p "Loading Message..."]
[loading-bar]]
(seq error)
(case status
404
[:div.content
[:p (or message "Post Not Found.")]
[:pre (with-out-str (pprint error))]]
403
[:div.content
[:p (or message "You are not allowed to visit this post.")]
[:pre (with-out-str (pprint error))]]
500
[:div
[:p (or message "Unknown Error.")]
[:pre (with-out-str (pprint error))]])
(seq post-content)
[post post-content])))
|
[
{
"context": "evoimistelu\" \"telinevoimisteli\"\n \"Triathlon\" \"ui, pyöräili ja juoksi\"\n ",
"end": 3422,
"score": 0.9056956171989441,
"start": 3413,
"tag": "NAME",
"value": "Triathlon"
}
] | src/ontrail/nlp.clj | jrosti/ontrail | 1 | (ns ontrail.nlp
(:import [org.tartarus.snowball.ext finnishStemmer]))
(defn stem [word]
(if (and word (> (count word) 0))
(let [stemmer (finnishStemmer.)]
(.setCurrent stemmer word)
(.stem stemmer)
(.getCurrent stemmer))
""))
(def verb-map {"Beach volley" "pelasi biitsiä"
"Crossfit" "crossfittasi"
"Cyclocross" "cyclocrossaili"
"Crosstrainer" "tyllerövispilöi"
"Frisbeegolf" "frisbeegolffasi"
"Golf" "golffasi"
"Hieronta" "oli hierottavana"
"Hiihto" "hiihti"
"Jalkapallo" "jalkapalloili"
"Jooga" "joogasi"
"Jumppa" "jumppasi"
"Juoksu" "juoksi"
"Jääkiekko" "jääkiekkoili"
"Kahvakuula" "nosti kuulaa"
"Kamppailulaji" "kamppaili"
"Kaukalopallo" "kaukalopalloili"
"Kickbike" "kikkaili"
"Kiipeily" "kiipeili"
"Koripallo" "koripalloili"
"Kuntopiiri" "teki kuntopiiriä"
"Kuntosali" "kävi kuntosalilla"
"Kuntopyörä" "kuntopyöräili"
"Kävely" "käveli"
"Laskettelu" "lasketteli"
"Lentopallo" "lentopalloili"
"Leuanveto" "veti leukoja"
"Luistelu" "luisteli"
"Luisteluhiihto" "luisteluhiihti"
"Lumikenkäily" "lumikenkäili"
"Lumilautailu" "lumilautaili"
"Maantiepyöräily" "maantiepyöräili"
"Maastojuoksu" "juoksi maastossa"
"Maastopyöräily" "pyöräili maastossa"
"Melonta" "meloi"
"Muu laji" "teki jotain muuta"
"Muu merkintä" "merkitsi jotain muuta"
"Nyrkkeily" "nyrkkeili"
"Perinteinen hiihto" "hiihti"
"Pilates" "harrasti pilatesta"
"Pumppi" "pumppasi"
"Potkukelkkailu" "potkukelkkaili"
"Pyöräily" "pyöräili"
"Ratsastus" "ratsasti"
"Ringette" "pelasi ringetteä"
"Rogaining" "rogasi"
"Rullahiihto" "rullahiihti"
"Rullaluistelu" "rullaluisteli"
"Sairaus" "sairasti"
"Sauvakävely" "sauvakäveli"
"Seikkailu-urheilu" "seikkaili"
"Sisäsoutu" "sisäsouti"
"Soutu" "souti"
"Spinning" "spinnasi"
"Squash" "pelasi squashia"
"Sulkapallo" "pelasi sulista"
"Suunnistus" "suunnisti"
"Sähly" "pelasi sählyä"
"Salibandy" "pelasi salibandya"
"Tanssi" "tanssi"
"Tapahtuma" "loi tapahtuman"
"Tennis" "pelasi tennistä"
"Telinevoimistelu" "telinevoimisteli"
"Triathlon" "ui, pyöräili ja juoksi"
"Uinti" "ui"
"Vaellus" "vaelsi"
"Venyttely" "venytteli"
"Voimaharjoittelu" "voimaili"
"Vesijuoksu" "vesijuoksi"
"Yleisurheilu" "yleisurheili"})
(def sports (sort (keys verb-map)))
(defn get-verb [sport-id]
(if (string? sport-id)
(let [verb (verb-map sport-id)]
(if (= nil verb)
(str "harrasti lajia " (.toLowerCase sport-id))
verb))
"nil-sport-id"))
(def stop-words
#{"ja" "ei" "oli" "mutta" "on" "kun"
"että"
"niin"
"se"
"sitten"
"ihan"
"vähän"
"nyt"
"jälkeen"
"vielä"
"kyllä"
"taas"
"kanssa"
"en"
"jo"
"nbsp"
"vaan"
"aika"
"tuli"
"kuin"
"hyvä"
"ollut"
"sen"
"joten"
"vaikka"
"km"
"olla"
"meni"
"ennen"
"tänään"
"sitä"
"hyvin"
"ole"
"jos"
"no"
"siinä"
"koko"
"kuitenkin"
"eli"
"tuntui"
"siis"
"olin"
"paljon"
"myös"
"tai"
"oikein"
"piti"
"vain"
"olisi"
"joka"
"aikaa"
"ehkä"
"mitään"
"eikä"
"siitä"
"voi"
"mennä"
"noin"
"tämä"
"10"
"mä"
"pitää"
"ne"
"aina"
"mitä"
"mun"
"muuten"
"tosi"
"sain"
"olen"
"alkoi"
"tuo"
"siellä"
"varmaan"
"mukaan"
"näin"
"kiva"
"lähdin"
"ettei"
"kai"
"jopa"}
)
| 41568 | (ns ontrail.nlp
(:import [org.tartarus.snowball.ext finnishStemmer]))
(defn stem [word]
(if (and word (> (count word) 0))
(let [stemmer (finnishStemmer.)]
(.setCurrent stemmer word)
(.stem stemmer)
(.getCurrent stemmer))
""))
(def verb-map {"Beach volley" "pelasi biitsiä"
"Crossfit" "crossfittasi"
"Cyclocross" "cyclocrossaili"
"Crosstrainer" "tyllerövispilöi"
"Frisbeegolf" "frisbeegolffasi"
"Golf" "golffasi"
"Hieronta" "oli hierottavana"
"Hiihto" "hiihti"
"Jalkapallo" "jalkapalloili"
"Jooga" "joogasi"
"Jumppa" "jumppasi"
"Juoksu" "juoksi"
"Jääkiekko" "jääkiekkoili"
"Kahvakuula" "nosti kuulaa"
"Kamppailulaji" "kamppaili"
"Kaukalopallo" "kaukalopalloili"
"Kickbike" "kikkaili"
"Kiipeily" "kiipeili"
"Koripallo" "koripalloili"
"Kuntopiiri" "teki kuntopiiriä"
"Kuntosali" "kävi kuntosalilla"
"Kuntopyörä" "kuntopyöräili"
"Kävely" "käveli"
"Laskettelu" "lasketteli"
"Lentopallo" "lentopalloili"
"Leuanveto" "veti leukoja"
"Luistelu" "luisteli"
"Luisteluhiihto" "luisteluhiihti"
"Lumikenkäily" "lumikenkäili"
"Lumilautailu" "lumilautaili"
"Maantiepyöräily" "maantiepyöräili"
"Maastojuoksu" "juoksi maastossa"
"Maastopyöräily" "pyöräili maastossa"
"Melonta" "meloi"
"Muu laji" "teki jotain muuta"
"Muu merkintä" "merkitsi jotain muuta"
"Nyrkkeily" "nyrkkeili"
"Perinteinen hiihto" "hiihti"
"Pilates" "harrasti pilatesta"
"Pumppi" "pumppasi"
"Potkukelkkailu" "potkukelkkaili"
"Pyöräily" "pyöräili"
"Ratsastus" "ratsasti"
"Ringette" "pelasi ringetteä"
"Rogaining" "rogasi"
"Rullahiihto" "rullahiihti"
"Rullaluistelu" "rullaluisteli"
"Sairaus" "sairasti"
"Sauvakävely" "sauvakäveli"
"Seikkailu-urheilu" "seikkaili"
"Sisäsoutu" "sisäsouti"
"Soutu" "souti"
"Spinning" "spinnasi"
"Squash" "pelasi squashia"
"Sulkapallo" "pelasi sulista"
"Suunnistus" "suunnisti"
"Sähly" "pelasi sählyä"
"Salibandy" "pelasi salibandya"
"Tanssi" "tanssi"
"Tapahtuma" "loi tapahtuman"
"Tennis" "pelasi tennistä"
"Telinevoimistelu" "telinevoimisteli"
"<NAME>" "ui, pyöräili ja juoksi"
"Uinti" "ui"
"Vaellus" "vaelsi"
"Venyttely" "venytteli"
"Voimaharjoittelu" "voimaili"
"Vesijuoksu" "vesijuoksi"
"Yleisurheilu" "yleisurheili"})
(def sports (sort (keys verb-map)))
(defn get-verb [sport-id]
(if (string? sport-id)
(let [verb (verb-map sport-id)]
(if (= nil verb)
(str "harrasti lajia " (.toLowerCase sport-id))
verb))
"nil-sport-id"))
(def stop-words
#{"ja" "ei" "oli" "mutta" "on" "kun"
"että"
"niin"
"se"
"sitten"
"ihan"
"vähän"
"nyt"
"jälkeen"
"vielä"
"kyllä"
"taas"
"kanssa"
"en"
"jo"
"nbsp"
"vaan"
"aika"
"tuli"
"kuin"
"hyvä"
"ollut"
"sen"
"joten"
"vaikka"
"km"
"olla"
"meni"
"ennen"
"tänään"
"sitä"
"hyvin"
"ole"
"jos"
"no"
"siinä"
"koko"
"kuitenkin"
"eli"
"tuntui"
"siis"
"olin"
"paljon"
"myös"
"tai"
"oikein"
"piti"
"vain"
"olisi"
"joka"
"aikaa"
"ehkä"
"mitään"
"eikä"
"siitä"
"voi"
"mennä"
"noin"
"tämä"
"10"
"mä"
"pitää"
"ne"
"aina"
"mitä"
"mun"
"muuten"
"tosi"
"sain"
"olen"
"alkoi"
"tuo"
"siellä"
"varmaan"
"mukaan"
"näin"
"kiva"
"lähdin"
"ettei"
"kai"
"jopa"}
)
| true | (ns ontrail.nlp
(:import [org.tartarus.snowball.ext finnishStemmer]))
(defn stem [word]
(if (and word (> (count word) 0))
(let [stemmer (finnishStemmer.)]
(.setCurrent stemmer word)
(.stem stemmer)
(.getCurrent stemmer))
""))
(def verb-map {"Beach volley" "pelasi biitsiä"
"Crossfit" "crossfittasi"
"Cyclocross" "cyclocrossaili"
"Crosstrainer" "tyllerövispilöi"
"Frisbeegolf" "frisbeegolffasi"
"Golf" "golffasi"
"Hieronta" "oli hierottavana"
"Hiihto" "hiihti"
"Jalkapallo" "jalkapalloili"
"Jooga" "joogasi"
"Jumppa" "jumppasi"
"Juoksu" "juoksi"
"Jääkiekko" "jääkiekkoili"
"Kahvakuula" "nosti kuulaa"
"Kamppailulaji" "kamppaili"
"Kaukalopallo" "kaukalopalloili"
"Kickbike" "kikkaili"
"Kiipeily" "kiipeili"
"Koripallo" "koripalloili"
"Kuntopiiri" "teki kuntopiiriä"
"Kuntosali" "kävi kuntosalilla"
"Kuntopyörä" "kuntopyöräili"
"Kävely" "käveli"
"Laskettelu" "lasketteli"
"Lentopallo" "lentopalloili"
"Leuanveto" "veti leukoja"
"Luistelu" "luisteli"
"Luisteluhiihto" "luisteluhiihti"
"Lumikenkäily" "lumikenkäili"
"Lumilautailu" "lumilautaili"
"Maantiepyöräily" "maantiepyöräili"
"Maastojuoksu" "juoksi maastossa"
"Maastopyöräily" "pyöräili maastossa"
"Melonta" "meloi"
"Muu laji" "teki jotain muuta"
"Muu merkintä" "merkitsi jotain muuta"
"Nyrkkeily" "nyrkkeili"
"Perinteinen hiihto" "hiihti"
"Pilates" "harrasti pilatesta"
"Pumppi" "pumppasi"
"Potkukelkkailu" "potkukelkkaili"
"Pyöräily" "pyöräili"
"Ratsastus" "ratsasti"
"Ringette" "pelasi ringetteä"
"Rogaining" "rogasi"
"Rullahiihto" "rullahiihti"
"Rullaluistelu" "rullaluisteli"
"Sairaus" "sairasti"
"Sauvakävely" "sauvakäveli"
"Seikkailu-urheilu" "seikkaili"
"Sisäsoutu" "sisäsouti"
"Soutu" "souti"
"Spinning" "spinnasi"
"Squash" "pelasi squashia"
"Sulkapallo" "pelasi sulista"
"Suunnistus" "suunnisti"
"Sähly" "pelasi sählyä"
"Salibandy" "pelasi salibandya"
"Tanssi" "tanssi"
"Tapahtuma" "loi tapahtuman"
"Tennis" "pelasi tennistä"
"Telinevoimistelu" "telinevoimisteli"
"PI:NAME:<NAME>END_PI" "ui, pyöräili ja juoksi"
"Uinti" "ui"
"Vaellus" "vaelsi"
"Venyttely" "venytteli"
"Voimaharjoittelu" "voimaili"
"Vesijuoksu" "vesijuoksi"
"Yleisurheilu" "yleisurheili"})
(def sports (sort (keys verb-map)))
(defn get-verb [sport-id]
(if (string? sport-id)
(let [verb (verb-map sport-id)]
(if (= nil verb)
(str "harrasti lajia " (.toLowerCase sport-id))
verb))
"nil-sport-id"))
(def stop-words
#{"ja" "ei" "oli" "mutta" "on" "kun"
"että"
"niin"
"se"
"sitten"
"ihan"
"vähän"
"nyt"
"jälkeen"
"vielä"
"kyllä"
"taas"
"kanssa"
"en"
"jo"
"nbsp"
"vaan"
"aika"
"tuli"
"kuin"
"hyvä"
"ollut"
"sen"
"joten"
"vaikka"
"km"
"olla"
"meni"
"ennen"
"tänään"
"sitä"
"hyvin"
"ole"
"jos"
"no"
"siinä"
"koko"
"kuitenkin"
"eli"
"tuntui"
"siis"
"olin"
"paljon"
"myös"
"tai"
"oikein"
"piti"
"vain"
"olisi"
"joka"
"aikaa"
"ehkä"
"mitään"
"eikä"
"siitä"
"voi"
"mennä"
"noin"
"tämä"
"10"
"mä"
"pitää"
"ne"
"aina"
"mitä"
"mun"
"muuten"
"tosi"
"sain"
"olen"
"alkoi"
"tuo"
"siellä"
"varmaan"
"mukaan"
"näin"
"kiva"
"lähdin"
"ettei"
"kai"
"jopa"}
)
|
[
{
"context": "; -------------------------\n\n(def p (read-string \"0xffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff\"))\n\n(def g 2)\n\n\n(defn test-establish-keys\n [alic",
"end": 681,
"score": 0.9239537715911865,
"start": 295,
"tag": "KEY",
"value": "0xffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"
},
{
"context": " @alice)\n (sut/get-attacker-peer-state (:id @alice) :aes-key))\n (= (:aes-key @bob)\n (sut/get-",
"end": 994,
"score": 0.9821727871894836,
"start": 989,
"tag": "NAME",
"value": "alice"
},
{
"context": " :msg)\n forged-msg)\n (= (:msg @alice)\n (sut/get-attacker-peer-state (:id @a",
"end": 1768,
"score": 0.7439454793930054,
"start": 1763,
"tag": "NAME",
"value": "alice"
},
{
"context": "e)\n (sut/get-attacker-peer-state (:id @alice) :msg)\n msg-to-send))))\n\n\n;; ---------",
"end": 1822,
"score": 0.5722880363464355,
"start": 1817,
"tag": "NAME",
"value": "alice"
}
] | test/set5/dh_negotiated_groups_test.clj | milapsheth/Crypto-Challenges | 3 | (ns set5.dh-negotiated-groups-test
(:require [set5.dh-negotiated-groups :as sut]
[clojure.test :refer :all]
[set5.dh-mitm-attack :as dh]
[util.random :as rand]))
;; -------------------------
;; Utilities
;; -------------------------
(def p (read-string "0xffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"))
(def g 2)
(defn test-establish-keys
[alice bob]
(dh/establish-keys alice bob p g)
(and
(= (:aes-key @alice)
(:aes-key @bob))))
(defn test-attacked-establish-keys
[alice bob]
(dh/establish-keys alice bob p g)
(and
(= (:aes-key @alice)
(sut/get-attacker-peer-state (:id @alice) :aes-key))
(= (:aes-key @bob)
(sut/get-attacker-peer-state (:id @bob) :aes-key))))
(defn check-registered-public-key
[peer]
(= (:public-key @peer)
(sut/get-attacker-peer-state (:id @peer) :remote-public-key)))
(defn test-normal-msg-send
[alice bob]
(let [msg (rand/byte-lst (rand/rand-num 50 100))]
(dh/send-msg alice bob msg)
(= (:msg @alice)
(:msg @bob))))
(defn test-attacked-msg
[alice bob]
(let [forged-msg (rand/byte-lst (rand/rand-num 20 50))
msg-to-send (rand/byte-lst (rand/rand-num 20 50))]
(sut/dh-negotiated-group :msg forged-msg)
(dh/send-msg alice bob msg-to-send)
(and (= (:msg @bob)
(sut/get-attacker-peer-state (:id @bob) :msg)
forged-msg)
(= (:msg @alice)
(sut/get-attacker-peer-state (:id @alice) :msg)
msg-to-send))))
;; -------------------------
;; Tests
;; -------------------------
(deftest normal-message-test
(testing "Failed normal message communication"
(let [alice (dh/create-peer)
bob (dh/create-peer)]
(dotimes [n 2]
(is (test-establish-keys (if (even? n) alice bob)
(if (even? n) bob alice)))
(dotimes [n 4]
(is (test-normal-msg-send (if (even? n) alice bob)
(if (even? n) bob alice))))))))
(deftest dh-negotiated-group-test
(testing "Failed to break communication"
(doseq [g [1 p (dec p)]]
(let [alice (dh/create-peer)
bob (dh/create-peer)]
(sut/dh-negotiated-group)
(sut/dh-negotiated-group :g g)
(is (test-attacked-establish-keys alice bob))
(is (check-registered-public-key alice))
(is (check-registered-public-key bob))
(dotimes [n 4]
(is (test-attacked-msg (if (even? n) alice bob)
(if (even? n) bob alice))))
(reset! dh/channel identity)))))
| 56719 | (ns set5.dh-negotiated-groups-test
(:require [set5.dh-negotiated-groups :as sut]
[clojure.test :refer :all]
[set5.dh-mitm-attack :as dh]
[util.random :as rand]))
;; -------------------------
;; Utilities
;; -------------------------
(def p (read-string "<KEY>"))
(def g 2)
(defn test-establish-keys
[alice bob]
(dh/establish-keys alice bob p g)
(and
(= (:aes-key @alice)
(:aes-key @bob))))
(defn test-attacked-establish-keys
[alice bob]
(dh/establish-keys alice bob p g)
(and
(= (:aes-key @alice)
(sut/get-attacker-peer-state (:id @<NAME>) :aes-key))
(= (:aes-key @bob)
(sut/get-attacker-peer-state (:id @bob) :aes-key))))
(defn check-registered-public-key
[peer]
(= (:public-key @peer)
(sut/get-attacker-peer-state (:id @peer) :remote-public-key)))
(defn test-normal-msg-send
[alice bob]
(let [msg (rand/byte-lst (rand/rand-num 50 100))]
(dh/send-msg alice bob msg)
(= (:msg @alice)
(:msg @bob))))
(defn test-attacked-msg
[alice bob]
(let [forged-msg (rand/byte-lst (rand/rand-num 20 50))
msg-to-send (rand/byte-lst (rand/rand-num 20 50))]
(sut/dh-negotiated-group :msg forged-msg)
(dh/send-msg alice bob msg-to-send)
(and (= (:msg @bob)
(sut/get-attacker-peer-state (:id @bob) :msg)
forged-msg)
(= (:msg @<NAME>)
(sut/get-attacker-peer-state (:id @<NAME>) :msg)
msg-to-send))))
;; -------------------------
;; Tests
;; -------------------------
(deftest normal-message-test
(testing "Failed normal message communication"
(let [alice (dh/create-peer)
bob (dh/create-peer)]
(dotimes [n 2]
(is (test-establish-keys (if (even? n) alice bob)
(if (even? n) bob alice)))
(dotimes [n 4]
(is (test-normal-msg-send (if (even? n) alice bob)
(if (even? n) bob alice))))))))
(deftest dh-negotiated-group-test
(testing "Failed to break communication"
(doseq [g [1 p (dec p)]]
(let [alice (dh/create-peer)
bob (dh/create-peer)]
(sut/dh-negotiated-group)
(sut/dh-negotiated-group :g g)
(is (test-attacked-establish-keys alice bob))
(is (check-registered-public-key alice))
(is (check-registered-public-key bob))
(dotimes [n 4]
(is (test-attacked-msg (if (even? n) alice bob)
(if (even? n) bob alice))))
(reset! dh/channel identity)))))
| true | (ns set5.dh-negotiated-groups-test
(:require [set5.dh-negotiated-groups :as sut]
[clojure.test :refer :all]
[set5.dh-mitm-attack :as dh]
[util.random :as rand]))
;; -------------------------
;; Utilities
;; -------------------------
(def p (read-string "PI:KEY:<KEY>END_PI"))
(def g 2)
(defn test-establish-keys
[alice bob]
(dh/establish-keys alice bob p g)
(and
(= (:aes-key @alice)
(:aes-key @bob))))
(defn test-attacked-establish-keys
[alice bob]
(dh/establish-keys alice bob p g)
(and
(= (:aes-key @alice)
(sut/get-attacker-peer-state (:id @PI:NAME:<NAME>END_PI) :aes-key))
(= (:aes-key @bob)
(sut/get-attacker-peer-state (:id @bob) :aes-key))))
(defn check-registered-public-key
[peer]
(= (:public-key @peer)
(sut/get-attacker-peer-state (:id @peer) :remote-public-key)))
(defn test-normal-msg-send
[alice bob]
(let [msg (rand/byte-lst (rand/rand-num 50 100))]
(dh/send-msg alice bob msg)
(= (:msg @alice)
(:msg @bob))))
(defn test-attacked-msg
[alice bob]
(let [forged-msg (rand/byte-lst (rand/rand-num 20 50))
msg-to-send (rand/byte-lst (rand/rand-num 20 50))]
(sut/dh-negotiated-group :msg forged-msg)
(dh/send-msg alice bob msg-to-send)
(and (= (:msg @bob)
(sut/get-attacker-peer-state (:id @bob) :msg)
forged-msg)
(= (:msg @PI:NAME:<NAME>END_PI)
(sut/get-attacker-peer-state (:id @PI:NAME:<NAME>END_PI) :msg)
msg-to-send))))
;; -------------------------
;; Tests
;; -------------------------
(deftest normal-message-test
(testing "Failed normal message communication"
(let [alice (dh/create-peer)
bob (dh/create-peer)]
(dotimes [n 2]
(is (test-establish-keys (if (even? n) alice bob)
(if (even? n) bob alice)))
(dotimes [n 4]
(is (test-normal-msg-send (if (even? n) alice bob)
(if (even? n) bob alice))))))))
(deftest dh-negotiated-group-test
(testing "Failed to break communication"
(doseq [g [1 p (dec p)]]
(let [alice (dh/create-peer)
bob (dh/create-peer)]
(sut/dh-negotiated-group)
(sut/dh-negotiated-group :g g)
(is (test-attacked-establish-keys alice bob))
(is (check-registered-public-key alice))
(is (check-registered-public-key bob))
(dotimes [n 4]
(is (test-attacked-msg (if (even? n) alice bob)
(if (even? n) bob alice))))
(reset! dh/channel identity)))))
|
[
{
"context": ";;\n;; Author:: Adam Jacob (<adam@opscode.com>)\n;; Copyright:: Copyright (c)",
"end": 25,
"score": 0.999845027923584,
"start": 15,
"tag": "NAME",
"value": "Adam Jacob"
},
{
"context": ";;\n;; Author:: Adam Jacob (<adam@opscode.com>)\n;; Copyright:: Copyright (c) 2011 Opscode, Inc.",
"end": 44,
"score": 0.9999296069145203,
"start": 28,
"tag": "EMAIL",
"value": "adam@opscode.com"
}
] | config/software/runit.clj | racker/omnibus | 2 | ;;
;; Author:: Adam Jacob (<adam@opscode.com>)
;; Copyright:: Copyright (c) 2011 Opscode, Inc.
;; License:: Apache License, Version 2.0
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(software "runit"
:source "runit-2.1.1"
:steps [
{:command "sed" :args ["-i" "-e" "s:^char *varservice =\"/service/\";$:char *varservice =\"/opt/opscode/service/\";:" "src/sv.c"]}
{:command "sed" :args ["-i" "-e" "s:/service:/opt/opscode/service:" "etc/2"]}
{:command "sed" :args ["-i" "-e" "s!^PATH=/command:/usr/local/bin:/usr/local/sbin:/bin:/sbin:/usr/bin:/usr/sbin:/usr/X11R6/bin$!PATH=/opt/opscode/bin:/opt/opscode/embedded/bin:/usr/local/bin:/usr/local/sbin:/bin:/sbin:/usr/bin:/usr/sbin!" "etc/2"]}
{:command "sed" :args ["-i" "-e" "s:-static::" "src/Makefile"]}
{:command "sh" :args ["-c" "cd src && make"]}
{:command "sh" :args ["-c" "cd src && make check"]}
{:command "cp" :args ["src/chpst" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["src/runit" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["src/runit-init" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["src/runsv" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["src/runsvchdir" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["src/runsvdir" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["src/sv" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["src/svlogd" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["src/utmpset" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["etc/2" "/opt/opscode/embedded/bin/runsvdir-start"]}
{:command "mkdir" :args ["-p" "/opt/opscode/service"]}
{:command "mkdir" :args ["-p" "/opt/opscode/sv"]}
{:command "mkdir" :args ["-p" "/opt/opscode/init"]}
])
| 11875 | ;;
;; Author:: <NAME> (<<EMAIL>>)
;; Copyright:: Copyright (c) 2011 Opscode, Inc.
;; License:: Apache License, Version 2.0
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(software "runit"
:source "runit-2.1.1"
:steps [
{:command "sed" :args ["-i" "-e" "s:^char *varservice =\"/service/\";$:char *varservice =\"/opt/opscode/service/\";:" "src/sv.c"]}
{:command "sed" :args ["-i" "-e" "s:/service:/opt/opscode/service:" "etc/2"]}
{:command "sed" :args ["-i" "-e" "s!^PATH=/command:/usr/local/bin:/usr/local/sbin:/bin:/sbin:/usr/bin:/usr/sbin:/usr/X11R6/bin$!PATH=/opt/opscode/bin:/opt/opscode/embedded/bin:/usr/local/bin:/usr/local/sbin:/bin:/sbin:/usr/bin:/usr/sbin!" "etc/2"]}
{:command "sed" :args ["-i" "-e" "s:-static::" "src/Makefile"]}
{:command "sh" :args ["-c" "cd src && make"]}
{:command "sh" :args ["-c" "cd src && make check"]}
{:command "cp" :args ["src/chpst" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["src/runit" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["src/runit-init" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["src/runsv" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["src/runsvchdir" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["src/runsvdir" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["src/sv" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["src/svlogd" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["src/utmpset" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["etc/2" "/opt/opscode/embedded/bin/runsvdir-start"]}
{:command "mkdir" :args ["-p" "/opt/opscode/service"]}
{:command "mkdir" :args ["-p" "/opt/opscode/sv"]}
{:command "mkdir" :args ["-p" "/opt/opscode/init"]}
])
| true | ;;
;; Author:: PI:NAME:<NAME>END_PI (<PI:EMAIL:<EMAIL>END_PI>)
;; Copyright:: Copyright (c) 2011 Opscode, Inc.
;; License:: Apache License, Version 2.0
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
(software "runit"
:source "runit-2.1.1"
:steps [
{:command "sed" :args ["-i" "-e" "s:^char *varservice =\"/service/\";$:char *varservice =\"/opt/opscode/service/\";:" "src/sv.c"]}
{:command "sed" :args ["-i" "-e" "s:/service:/opt/opscode/service:" "etc/2"]}
{:command "sed" :args ["-i" "-e" "s!^PATH=/command:/usr/local/bin:/usr/local/sbin:/bin:/sbin:/usr/bin:/usr/sbin:/usr/X11R6/bin$!PATH=/opt/opscode/bin:/opt/opscode/embedded/bin:/usr/local/bin:/usr/local/sbin:/bin:/sbin:/usr/bin:/usr/sbin!" "etc/2"]}
{:command "sed" :args ["-i" "-e" "s:-static::" "src/Makefile"]}
{:command "sh" :args ["-c" "cd src && make"]}
{:command "sh" :args ["-c" "cd src && make check"]}
{:command "cp" :args ["src/chpst" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["src/runit" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["src/runit-init" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["src/runsv" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["src/runsvchdir" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["src/runsvdir" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["src/sv" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["src/svlogd" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["src/utmpset" "/opt/opscode/embedded/bin"]}
{:command "cp" :args ["etc/2" "/opt/opscode/embedded/bin/runsvdir-start"]}
{:command "mkdir" :args ["-p" "/opt/opscode/service"]}
{:command "mkdir" :args ["-p" "/opt/opscode/sv"]}
{:command "mkdir" :args ["-p" "/opt/opscode/init"]}
])
|
[
{
"context": "ame\n :password password})\n (run-pipeline (read-channel (take* 1 (util/",
"end": 2014,
"score": 0.9987081289291382,
"start": 2006,
"tag": "PASSWORD",
"value": "password"
}
] | src/crawl.clj | flodiebold/crawl-clj | 1 | (ns crawl
(:use [lamina.core :exclude (close)])
(:require [aleph.http.websocket :as ws]
[cheshire.core :as json]
[clojure.string :as s]
[crawl.compression :as compression]
[crawl.util :as util]
crawl.lobby
crawl.game))
(defn- wrap-decompression
[ch]
(let [inflater (compression/make-inflater)]
(splice
(map* (partial compression/inflate-to-string inflater) ch)
ch)))
(defn- wrap-json
[ch]
(let [ch* (channel)
keyword-munger (fn [k] (keyword (s/replace k "_" "-")))]
(join (map* json/generate-string ch*) ch)
(splice (map* #(json/parse-string % keyword-munger) ch) ch*)))
(defn- respond-to-pings
[conn]
(receive-all (filter* (util/match-msg #"ping") (tap (:incoming conn)))
(fn [ping]
(enqueue (:outgoing conn) {:msg "pong"})))
conn)
(defn- wrap-connection
[ch]
(let [incoming-ch (channel* :grounded? true :permanent? true)]
(siphon ch incoming-ch)
{:incoming incoming-ch :outgoing ch}))
(defn connect
"Connects to a DCSS server at the given domain and port.
Returns a map representing the connection."
[domain port]
(let [client (ws/websocket-client {:scheme "ws" :server-name domain
:server-port port
:uri "/socket"})]
(run-pipeline client
wrap-decompression
wrap-json
wrap-connection
respond-to-pings
crawl.lobby/handle-lobby-info)))
(defn login
"Logs in at the connection with the credentials (:username and :password).
Returns a result channel containing either the logged-in username, or nil
in case of failure."
[connection credentials]
(let [{username :username password :password} credentials]
(enqueue (:outgoing connection) {:msg "login"
:username username
:password password})
(run-pipeline (read-channel (take* 1 (util/get-msgs connection #"login_.*")))
(fn [msg]
(case (:msg msg)
"login_fail" nil
"login_success" (:username msg))))))
(defn close
"Closes the DCSS connection."
[connection]
(lamina.core/close (:outgoing connection)))
(defn start-game
"Starts the game with the given id."
[connection game-id]
(enqueue (:outgoing connection) {:msg "play"
:game_id game-id})
(crawl.game/game-states connection))
(defn watch-player
[connection username]
"Watches the player with the given username."
(enqueue (:outgoing connection) {:msg "watch"
:username username})
(crawl.game/game-states connection))
(defn- connect-and
[domain port credentials then & args]
(run-pipeline
(connect domain port)
(fn [conn]
(run-pipeline
(if credentials
(login conn credentials)
(success-result true))
(fn [result]
(when result
(let [ch (apply then conn args)
ch* (splice ch (:outgoing conn))]
(on-closed ch* (fn [] (close conn)))
ch*)))))))
(defn connect-and-start
"Connects, logs in and starts a game, returning a channel of game states."
[domain port credentials game-id]
(connect-and domain port credentials start-game game-id))
(defn connect-and-watch
[domain port username]
(connect-and domain port nil watch-player username))
| 124293 | (ns crawl
(:use [lamina.core :exclude (close)])
(:require [aleph.http.websocket :as ws]
[cheshire.core :as json]
[clojure.string :as s]
[crawl.compression :as compression]
[crawl.util :as util]
crawl.lobby
crawl.game))
(defn- wrap-decompression
[ch]
(let [inflater (compression/make-inflater)]
(splice
(map* (partial compression/inflate-to-string inflater) ch)
ch)))
(defn- wrap-json
[ch]
(let [ch* (channel)
keyword-munger (fn [k] (keyword (s/replace k "_" "-")))]
(join (map* json/generate-string ch*) ch)
(splice (map* #(json/parse-string % keyword-munger) ch) ch*)))
(defn- respond-to-pings
[conn]
(receive-all (filter* (util/match-msg #"ping") (tap (:incoming conn)))
(fn [ping]
(enqueue (:outgoing conn) {:msg "pong"})))
conn)
(defn- wrap-connection
[ch]
(let [incoming-ch (channel* :grounded? true :permanent? true)]
(siphon ch incoming-ch)
{:incoming incoming-ch :outgoing ch}))
(defn connect
"Connects to a DCSS server at the given domain and port.
Returns a map representing the connection."
[domain port]
(let [client (ws/websocket-client {:scheme "ws" :server-name domain
:server-port port
:uri "/socket"})]
(run-pipeline client
wrap-decompression
wrap-json
wrap-connection
respond-to-pings
crawl.lobby/handle-lobby-info)))
(defn login
"Logs in at the connection with the credentials (:username and :password).
Returns a result channel containing either the logged-in username, or nil
in case of failure."
[connection credentials]
(let [{username :username password :password} credentials]
(enqueue (:outgoing connection) {:msg "login"
:username username
:password <PASSWORD>})
(run-pipeline (read-channel (take* 1 (util/get-msgs connection #"login_.*")))
(fn [msg]
(case (:msg msg)
"login_fail" nil
"login_success" (:username msg))))))
(defn close
"Closes the DCSS connection."
[connection]
(lamina.core/close (:outgoing connection)))
(defn start-game
"Starts the game with the given id."
[connection game-id]
(enqueue (:outgoing connection) {:msg "play"
:game_id game-id})
(crawl.game/game-states connection))
(defn watch-player
[connection username]
"Watches the player with the given username."
(enqueue (:outgoing connection) {:msg "watch"
:username username})
(crawl.game/game-states connection))
(defn- connect-and
[domain port credentials then & args]
(run-pipeline
(connect domain port)
(fn [conn]
(run-pipeline
(if credentials
(login conn credentials)
(success-result true))
(fn [result]
(when result
(let [ch (apply then conn args)
ch* (splice ch (:outgoing conn))]
(on-closed ch* (fn [] (close conn)))
ch*)))))))
(defn connect-and-start
"Connects, logs in and starts a game, returning a channel of game states."
[domain port credentials game-id]
(connect-and domain port credentials start-game game-id))
(defn connect-and-watch
[domain port username]
(connect-and domain port nil watch-player username))
| true | (ns crawl
(:use [lamina.core :exclude (close)])
(:require [aleph.http.websocket :as ws]
[cheshire.core :as json]
[clojure.string :as s]
[crawl.compression :as compression]
[crawl.util :as util]
crawl.lobby
crawl.game))
(defn- wrap-decompression
[ch]
(let [inflater (compression/make-inflater)]
(splice
(map* (partial compression/inflate-to-string inflater) ch)
ch)))
(defn- wrap-json
[ch]
(let [ch* (channel)
keyword-munger (fn [k] (keyword (s/replace k "_" "-")))]
(join (map* json/generate-string ch*) ch)
(splice (map* #(json/parse-string % keyword-munger) ch) ch*)))
(defn- respond-to-pings
[conn]
(receive-all (filter* (util/match-msg #"ping") (tap (:incoming conn)))
(fn [ping]
(enqueue (:outgoing conn) {:msg "pong"})))
conn)
(defn- wrap-connection
[ch]
(let [incoming-ch (channel* :grounded? true :permanent? true)]
(siphon ch incoming-ch)
{:incoming incoming-ch :outgoing ch}))
(defn connect
"Connects to a DCSS server at the given domain and port.
Returns a map representing the connection."
[domain port]
(let [client (ws/websocket-client {:scheme "ws" :server-name domain
:server-port port
:uri "/socket"})]
(run-pipeline client
wrap-decompression
wrap-json
wrap-connection
respond-to-pings
crawl.lobby/handle-lobby-info)))
(defn login
"Logs in at the connection with the credentials (:username and :password).
Returns a result channel containing either the logged-in username, or nil
in case of failure."
[connection credentials]
(let [{username :username password :password} credentials]
(enqueue (:outgoing connection) {:msg "login"
:username username
:password PI:PASSWORD:<PASSWORD>END_PI})
(run-pipeline (read-channel (take* 1 (util/get-msgs connection #"login_.*")))
(fn [msg]
(case (:msg msg)
"login_fail" nil
"login_success" (:username msg))))))
(defn close
"Closes the DCSS connection."
[connection]
(lamina.core/close (:outgoing connection)))
(defn start-game
"Starts the game with the given id."
[connection game-id]
(enqueue (:outgoing connection) {:msg "play"
:game_id game-id})
(crawl.game/game-states connection))
(defn watch-player
[connection username]
"Watches the player with the given username."
(enqueue (:outgoing connection) {:msg "watch"
:username username})
(crawl.game/game-states connection))
(defn- connect-and
[domain port credentials then & args]
(run-pipeline
(connect domain port)
(fn [conn]
(run-pipeline
(if credentials
(login conn credentials)
(success-result true))
(fn [result]
(when result
(let [ch (apply then conn args)
ch* (splice ch (:outgoing conn))]
(on-closed ch* (fn [] (close conn)))
ch*)))))))
(defn connect-and-start
"Connects, logs in and starts a game, returning a channel of game states."
[domain port credentials game-id]
(connect-and domain port credentials start-game game-id))
(defn connect-and-watch
[domain port username]
(connect-and domain port nil watch-player username))
|
[
{
"context": "urce.org/licenses/MIT\"}\n :url \"http://github.com/cloxp/cloxp-projects\"\n :dependencies [[org.clojure/clo",
"end": 237,
"score": 0.623374342918396,
"start": 232,
"tag": "USERNAME",
"value": "cloxp"
},
{
"context": " :aot [rksm.system-files.jar.File]\n :scm {:url \"git@github.com:cloxp/system-files.git\"}\n :deploy-repositories [",
"end": 773,
"score": 0.8080922961235046,
"start": 759,
"tag": "EMAIL",
"value": "git@github.com"
},
{
"context": "\n :pom-addition [:developers [:developer [:name \"Robert Krahn\"]]])\n",
"end": 954,
"score": 0.9997882843017578,
"start": 942,
"tag": "NAME",
"value": "Robert Krahn"
}
] | project.clj | rksm/clj-system-files | 1 | (defproject org.rksm/system-files "0.2.1-SNAPSHOT"
:description "Accessing clojure classpath data and system files."
:license {:name "MIT License"
:url "http://opensource.org/licenses/MIT"}
:url "http://github.com/cloxp/cloxp-projects"
:dependencies [[org.clojure/clojure "1.10.1"]
[org.clojure/tools.namespace "0.3.0"]
[org.clojure/java.classpath "0.3.0"]
[org.tcrawley/dynapath "1.0.0"]
[com.cemerick/pomegranate "1.1.0"]]
:profiles {:dev {:source-paths ["test-resources/dummy-2-test.jar"]}}
:source-paths ["src/main/clojure"]
:test-paths ["src/test/clojure"]
:test-selectors {:default (fn [m] (do (:test m)))}
:aot [rksm.system-files.jar.File]
:scm {:url "git@github.com:cloxp/system-files.git"}
:deploy-repositories [["releases" :clojars]
["snapshots" :clojars]]
:pom-addition [:developers [:developer [:name "Robert Krahn"]]])
| 98007 | (defproject org.rksm/system-files "0.2.1-SNAPSHOT"
:description "Accessing clojure classpath data and system files."
:license {:name "MIT License"
:url "http://opensource.org/licenses/MIT"}
:url "http://github.com/cloxp/cloxp-projects"
:dependencies [[org.clojure/clojure "1.10.1"]
[org.clojure/tools.namespace "0.3.0"]
[org.clojure/java.classpath "0.3.0"]
[org.tcrawley/dynapath "1.0.0"]
[com.cemerick/pomegranate "1.1.0"]]
:profiles {:dev {:source-paths ["test-resources/dummy-2-test.jar"]}}
:source-paths ["src/main/clojure"]
:test-paths ["src/test/clojure"]
:test-selectors {:default (fn [m] (do (:test m)))}
:aot [rksm.system-files.jar.File]
:scm {:url "<EMAIL>:cloxp/system-files.git"}
:deploy-repositories [["releases" :clojars]
["snapshots" :clojars]]
:pom-addition [:developers [:developer [:name "<NAME>"]]])
| true | (defproject org.rksm/system-files "0.2.1-SNAPSHOT"
:description "Accessing clojure classpath data and system files."
:license {:name "MIT License"
:url "http://opensource.org/licenses/MIT"}
:url "http://github.com/cloxp/cloxp-projects"
:dependencies [[org.clojure/clojure "1.10.1"]
[org.clojure/tools.namespace "0.3.0"]
[org.clojure/java.classpath "0.3.0"]
[org.tcrawley/dynapath "1.0.0"]
[com.cemerick/pomegranate "1.1.0"]]
:profiles {:dev {:source-paths ["test-resources/dummy-2-test.jar"]}}
:source-paths ["src/main/clojure"]
:test-paths ["src/test/clojure"]
:test-selectors {:default (fn [m] (do (:test m)))}
:aot [rksm.system-files.jar.File]
:scm {:url "PI:EMAIL:<EMAIL>END_PI:cloxp/system-files.git"}
:deploy-repositories [["releases" :clojars]
["snapshots" :clojars]]
:pom-addition [:developers [:developer [:name "PI:NAME:<NAME>END_PI"]]])
|
[
{
"context": ":host host :port port :username username :password password})\n this (assoc this :conn conn)]\n (",
"end": 9779,
"score": 0.5057497620582581,
"start": 9771,
"tag": "PASSWORD",
"value": "password"
}
] | message-queue-lib/src/cmr/message_queue/queue/rabbit_mq.clj | sxu123/Common-Metadata-Repository | 0 | (ns cmr.message-queue.queue.rabbit-mq
"Implements index-queue functionality using rabbit mq"
(:gen-class)
(:require [cmr.common.lifecycle :as lifecycle]
[cmr.common.log :as log :refer (debug info warn error)]
[cmr.common.mime-types :as mt]
[cmr.message-queue.config :as config]
[cmr.common.services.errors :as errors]
[cmr.message-queue.services.queue :as queue]
[langohr.core :as rmq]
[langohr.channel :as lch]
[langohr.queue :as lq]
[langohr.consumers :as lc]
[langohr.confirm :as lcf]
[langohr.basic :as lb]
[langohr.exchange :as le]
[clj-http.client :as client]
[cheshire.core :as json]
[cmr.common.services.health-helper :as hh]
[cmr.common.dev.record-pretty-printer :as record-pretty-printer])
(:import java.io.IOException))
(defmacro with-channel
"Opens and binds a channel to the given name from a connection, executes the body and then closes the channel.
Example:
(with-channel
[chan conn]
(lq/status chan \"my-queue\"))"
[bindings & body]
(when (not= 2 (count bindings))
(throw (Exception. "Expected a single pair of bindings of a channel symbol and a connection")))
(let [[channel-name connection-name] bindings]
`(let [~channel-name (lch/open ~connection-name)]
(try
~@body
(finally
(lch/close ~channel-name))))))
(defn wait-queue-name
"Returns the name of the wait queue associated with the given queue name and retry-count"
[queue-name retry-count]
(str queue-name "_wait_" retry-count))
(defn- wait-queue-ttl
"Returns the Time-To-Live (TTL) in milliseconds for the nth (1 based) wait queue"
[n]
(* 1000 (nth (config/rabbit-mq-ttls) (dec n))))
(def ^:const default-exchange-name "")
(defn- attempt-retry
"Retry a message if it has not already exceeded the allowable retries"
[queue-broker ch queue-name msg delivery-tag resp]
(let [retry-count (get msg :retry-count 0)]
(if (queue/retry-limit-met? msg (count (config/rabbit-mq-ttls)))
(do
;; give up
;; Splunk alert "Indexing from message queue failed and all retries exhausted" dependent on this log message
(warn "Max retries exceeded for processing message:" (pr-str msg) "on queue:" queue-name)
(lb/nack ch delivery-tag false false))
(let [msg (assoc msg :retry-count (inc retry-count))
wait-q (wait-queue-name queue-name (inc retry-count))
ttl (wait-queue-ttl (inc retry-count))]
(info "Message" (pr-str msg) "re-queued with response:" (pr-str (:message resp)))
(info (format "Retrying with retry-count =%d on queue %s with ttl = %d"
(inc retry-count)
wait-q
ttl))
(queue/publish-to-queue queue-broker wait-q msg)
(lb/ack ch delivery-tag)))))
(defn- message-handler
"Processes a given message and determines what to do based on the response code returned. Send an
ack if the message completed successfully. Put the message on a wait queue if the response
indicates it needs to be retried. Nack the message if the response is marked as failed."
[queue-broker queue-name client-handler ch metadata ^bytes payload]
(let [{:keys [delivery-tag]} metadata
msg (json/parse-string (String. payload) true)]
(try
(client-handler msg)
(lb/ack ch delivery-tag)
(catch Throwable e
(error e "Message processing failed for message" (pr-str msg))
(attempt-retry queue-broker ch queue-name msg delivery-tag
{:message (.getMessage e)})))))
(defn- start-consumer
"Starts a message consumer in a separate thread.
'queue-broker' is a record that implements
both the Queue and Lifecycle protocols for interacting with a message queue.
'queue-name' is the identifier of the queue to use to receive messages and should correpsond to
the identifier used to create the queue with the create-queue function.
'client-handler' is a function that takes a single parameter (the message) and attempts to
process it. If a function throws an exception it will be retried."
[queue-broker queue-name client-handler]
(let [conn (:conn queue-broker)
;; don't want this channel to close automatically, so no with-channel here
sub-ch (lch/open conn)
handler (partial message-handler queue-broker queue-name client-handler)]
;; By default, RabbitMQ uses a round-robin approach to send messages to listeners. This can
;; lead to stalls as workers wait for other workers to complete. Setting QoS (prefetch) to 1
;; prevents this.
(lb/qos sub-ch 1)
(lc/subscribe sub-ch queue-name handler {:auto-ack false})))
(defn purge-queue
"Remove all messages from a queue and the associated wait queues"
[broker queue-name]
(let [conn (:conn broker)]
(with-channel [ch conn]
(info "Purging all messages from queue" queue-name)
(lq/purge ch queue-name)
(doseq [wait-queue-num (range 1 (inc (count (config/rabbit-mq-ttls))))
:let [ttl (wait-queue-ttl wait-queue-num)
wq (wait-queue-name queue-name wait-queue-num)]]
(debug "Purging messages from wait queue" wq)
(lq/purge ch wq)))))
(defn delete-queue
"Remove a queue from the RabbitMQ server/cluster"
[broker queue-name]
(let [conn (:conn broker)]
(with-channel [ch conn]
(lq/delete ch queue-name)
(doseq [wait-queue-num (range 1 (inc (count (config/rabbit-mq-ttls))))
:let [ttl (wait-queue-ttl wait-queue-num)
wq (wait-queue-name queue-name wait-queue-num)]]
(lq/delete ch wq)))))
(defn health-fn
"Check that the queue is up and responding"
[queue-broker]
(try
(let [{:keys [host admin-port username password]} queue-broker
{:keys [status body]} (client/request
{:url (format "http://%s:%s/api/aliveness-test/%s"
host admin-port
"%2f")
:method :get
:throw-exceptions false
:basic-auth [username password]})]
(if (= status 200)
(let [rmq-status (-> body (json/decode true) :status)]
(if (= rmq-status "ok")
{:ok? true}
{:ok? false :problem rmq-status}))
{:ok? false :problem body}))
(catch Exception e
{:ok? false :problem (.getMessage e)})))
(defn- publish
"Publishes a message to the given exchange/queue combination. When publishing to a queue set the
exchange name to an empty string and the routing-key to the queue name."
[queue-broker exchange-name routing-key msg]
(let [payload (json/generate-string msg)
metadata {:content-type mt/json :persistent true}]
(with-channel
[pub-ch (:conn queue-broker)]
;; put channel into confirmation mode
(lcf/select pub-ch)
;; publish the message
(lb/publish pub-ch exchange-name routing-key payload metadata)
;; block until the confirm arrives or return false if queue nacks the message
(lcf/wait-for-confirms pub-ch))))
(defn- create-queue
[broker queue-name]
(let [{:keys [conn]} broker]
(with-channel
[ch conn]
;; create the queue
;; see http://reference.clojurerabbitmq.info/langohr.queue.html
(info "Creating queue" queue-name)
(lq/declare ch queue-name {:exclusive false :auto-delete false :durable true})
;; create wait queues to use with the primary queue
(info "Creating wait queues")
(doseq [wait-queue-num (range 1 (inc (count (config/rabbit-mq-ttls))))
:let [ttl (wait-queue-ttl wait-queue-num)
wq (wait-queue-name queue-name wait-queue-num)]]
(lq/declare ch
wq
{:exclusive false
:auto-delete false
:durable true
:arguments {"x-dead-letter-exchange" default-exchange-name
"x-dead-letter-routing-key" queue-name
"x-message-ttl" ttl}})))))
(defn- create-exchange
[broker exchange-name]
(let [{:keys [conn]} broker]
(with-channel
[ch conn]
(info "Creating exchange" exchange-name)
(le/declare ch exchange-name "fanout" {:durable true}))))
(defn- bind-queue-to-exchange
[broker queue-name exchange-name]
(let [{:keys [conn]} broker]
(with-channel
[ch conn]
(info "Binding queue" queue-name "to exchange" exchange-name)
(lq/bind ch queue-name exchange-name))))
(defrecord RabbitMQBroker
[
;; RabbitMQ server host
host
;; RabbitMQ server port for queueing requests
port
;; RabbitMQ server port for admin requests (http)
admin-port
;; RabbitMQ user name
username
;; RabbitMQ password
password
;; Connection to the message queue
conn
;; Queues that should be created on startup
persistent-queues
;; Exchanges that should be created on startup
persistent-exchanges
;; A map of queue name to a sequence of exchange names that the queue should be bound to.
bindings]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
lifecycle/Lifecycle
(start
[this system]
(info "Starting RabbitMQ connection")
(let [conn (rmq/connect {:host host :port port :username username :password password})
this (assoc this :conn conn)]
(info "RabbitMQ connection opened")
(doseq [queue-name persistent-queues]
(create-queue this queue-name))
(doseq [exchange-name persistent-exchanges]
(create-exchange this exchange-name))
(doseq [[queue-name exchange-names] bindings
exchange-name exchange-names]
(bind-queue-to-exchange this queue-name exchange-name))
this))
(stop
[this system]
;; Close the connection. This will close all channels as well.
(when (:conn this) (rmq/close (:conn this)))
(assoc this :conn nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
queue/Queue
(publish-to-queue
[this queue-name msg]
(publish this default-exchange-name queue-name msg))
(get-queues-bound-to-exchange
[this exchange-name]
(for [[q es] bindings
e es
:when (= e exchange-name)]
q))
(publish-to-exchange
[this exchange-name msg]
(publish this exchange-name "" msg))
(subscribe
[this queue-name handler]
(start-consumer this queue-name handler))
(reset
[this]
(info "Resetting RabbitMQ")
(doseq [queue-name persistent-queues]
(purge-queue this queue-name)))
(health
[this]
(let [timeout-ms (* 1000 (+ 2 (hh/health-check-timeout-seconds)))]
(hh/get-health #(health-fn this) timeout-ms))))
(record-pretty-printer/enable-record-pretty-printing RabbitMQBroker)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn create-queue-broker
"Create a RabbitMQBroker with the given parameters. See RabbitMQBroker comments for information"
[{:keys [host port admin-port username password
queues exchanges queues-to-exchanges]}]
(->RabbitMQBroker host port admin-port username password nil
queues exchanges queues-to-exchanges))
| 71776 | (ns cmr.message-queue.queue.rabbit-mq
"Implements index-queue functionality using rabbit mq"
(:gen-class)
(:require [cmr.common.lifecycle :as lifecycle]
[cmr.common.log :as log :refer (debug info warn error)]
[cmr.common.mime-types :as mt]
[cmr.message-queue.config :as config]
[cmr.common.services.errors :as errors]
[cmr.message-queue.services.queue :as queue]
[langohr.core :as rmq]
[langohr.channel :as lch]
[langohr.queue :as lq]
[langohr.consumers :as lc]
[langohr.confirm :as lcf]
[langohr.basic :as lb]
[langohr.exchange :as le]
[clj-http.client :as client]
[cheshire.core :as json]
[cmr.common.services.health-helper :as hh]
[cmr.common.dev.record-pretty-printer :as record-pretty-printer])
(:import java.io.IOException))
(defmacro with-channel
"Opens and binds a channel to the given name from a connection, executes the body and then closes the channel.
Example:
(with-channel
[chan conn]
(lq/status chan \"my-queue\"))"
[bindings & body]
(when (not= 2 (count bindings))
(throw (Exception. "Expected a single pair of bindings of a channel symbol and a connection")))
(let [[channel-name connection-name] bindings]
`(let [~channel-name (lch/open ~connection-name)]
(try
~@body
(finally
(lch/close ~channel-name))))))
(defn wait-queue-name
"Returns the name of the wait queue associated with the given queue name and retry-count"
[queue-name retry-count]
(str queue-name "_wait_" retry-count))
(defn- wait-queue-ttl
"Returns the Time-To-Live (TTL) in milliseconds for the nth (1 based) wait queue"
[n]
(* 1000 (nth (config/rabbit-mq-ttls) (dec n))))
(def ^:const default-exchange-name "")
(defn- attempt-retry
"Retry a message if it has not already exceeded the allowable retries"
[queue-broker ch queue-name msg delivery-tag resp]
(let [retry-count (get msg :retry-count 0)]
(if (queue/retry-limit-met? msg (count (config/rabbit-mq-ttls)))
(do
;; give up
;; Splunk alert "Indexing from message queue failed and all retries exhausted" dependent on this log message
(warn "Max retries exceeded for processing message:" (pr-str msg) "on queue:" queue-name)
(lb/nack ch delivery-tag false false))
(let [msg (assoc msg :retry-count (inc retry-count))
wait-q (wait-queue-name queue-name (inc retry-count))
ttl (wait-queue-ttl (inc retry-count))]
(info "Message" (pr-str msg) "re-queued with response:" (pr-str (:message resp)))
(info (format "Retrying with retry-count =%d on queue %s with ttl = %d"
(inc retry-count)
wait-q
ttl))
(queue/publish-to-queue queue-broker wait-q msg)
(lb/ack ch delivery-tag)))))
(defn- message-handler
"Processes a given message and determines what to do based on the response code returned. Send an
ack if the message completed successfully. Put the message on a wait queue if the response
indicates it needs to be retried. Nack the message if the response is marked as failed."
[queue-broker queue-name client-handler ch metadata ^bytes payload]
(let [{:keys [delivery-tag]} metadata
msg (json/parse-string (String. payload) true)]
(try
(client-handler msg)
(lb/ack ch delivery-tag)
(catch Throwable e
(error e "Message processing failed for message" (pr-str msg))
(attempt-retry queue-broker ch queue-name msg delivery-tag
{:message (.getMessage e)})))))
(defn- start-consumer
"Starts a message consumer in a separate thread.
'queue-broker' is a record that implements
both the Queue and Lifecycle protocols for interacting with a message queue.
'queue-name' is the identifier of the queue to use to receive messages and should correpsond to
the identifier used to create the queue with the create-queue function.
'client-handler' is a function that takes a single parameter (the message) and attempts to
process it. If a function throws an exception it will be retried."
[queue-broker queue-name client-handler]
(let [conn (:conn queue-broker)
;; don't want this channel to close automatically, so no with-channel here
sub-ch (lch/open conn)
handler (partial message-handler queue-broker queue-name client-handler)]
;; By default, RabbitMQ uses a round-robin approach to send messages to listeners. This can
;; lead to stalls as workers wait for other workers to complete. Setting QoS (prefetch) to 1
;; prevents this.
(lb/qos sub-ch 1)
(lc/subscribe sub-ch queue-name handler {:auto-ack false})))
(defn purge-queue
"Remove all messages from a queue and the associated wait queues"
[broker queue-name]
(let [conn (:conn broker)]
(with-channel [ch conn]
(info "Purging all messages from queue" queue-name)
(lq/purge ch queue-name)
(doseq [wait-queue-num (range 1 (inc (count (config/rabbit-mq-ttls))))
:let [ttl (wait-queue-ttl wait-queue-num)
wq (wait-queue-name queue-name wait-queue-num)]]
(debug "Purging messages from wait queue" wq)
(lq/purge ch wq)))))
(defn delete-queue
"Remove a queue from the RabbitMQ server/cluster"
[broker queue-name]
(let [conn (:conn broker)]
(with-channel [ch conn]
(lq/delete ch queue-name)
(doseq [wait-queue-num (range 1 (inc (count (config/rabbit-mq-ttls))))
:let [ttl (wait-queue-ttl wait-queue-num)
wq (wait-queue-name queue-name wait-queue-num)]]
(lq/delete ch wq)))))
(defn health-fn
"Check that the queue is up and responding"
[queue-broker]
(try
(let [{:keys [host admin-port username password]} queue-broker
{:keys [status body]} (client/request
{:url (format "http://%s:%s/api/aliveness-test/%s"
host admin-port
"%2f")
:method :get
:throw-exceptions false
:basic-auth [username password]})]
(if (= status 200)
(let [rmq-status (-> body (json/decode true) :status)]
(if (= rmq-status "ok")
{:ok? true}
{:ok? false :problem rmq-status}))
{:ok? false :problem body}))
(catch Exception e
{:ok? false :problem (.getMessage e)})))
(defn- publish
"Publishes a message to the given exchange/queue combination. When publishing to a queue set the
exchange name to an empty string and the routing-key to the queue name."
[queue-broker exchange-name routing-key msg]
(let [payload (json/generate-string msg)
metadata {:content-type mt/json :persistent true}]
(with-channel
[pub-ch (:conn queue-broker)]
;; put channel into confirmation mode
(lcf/select pub-ch)
;; publish the message
(lb/publish pub-ch exchange-name routing-key payload metadata)
;; block until the confirm arrives or return false if queue nacks the message
(lcf/wait-for-confirms pub-ch))))
(defn- create-queue
[broker queue-name]
(let [{:keys [conn]} broker]
(with-channel
[ch conn]
;; create the queue
;; see http://reference.clojurerabbitmq.info/langohr.queue.html
(info "Creating queue" queue-name)
(lq/declare ch queue-name {:exclusive false :auto-delete false :durable true})
;; create wait queues to use with the primary queue
(info "Creating wait queues")
(doseq [wait-queue-num (range 1 (inc (count (config/rabbit-mq-ttls))))
:let [ttl (wait-queue-ttl wait-queue-num)
wq (wait-queue-name queue-name wait-queue-num)]]
(lq/declare ch
wq
{:exclusive false
:auto-delete false
:durable true
:arguments {"x-dead-letter-exchange" default-exchange-name
"x-dead-letter-routing-key" queue-name
"x-message-ttl" ttl}})))))
(defn- create-exchange
[broker exchange-name]
(let [{:keys [conn]} broker]
(with-channel
[ch conn]
(info "Creating exchange" exchange-name)
(le/declare ch exchange-name "fanout" {:durable true}))))
(defn- bind-queue-to-exchange
[broker queue-name exchange-name]
(let [{:keys [conn]} broker]
(with-channel
[ch conn]
(info "Binding queue" queue-name "to exchange" exchange-name)
(lq/bind ch queue-name exchange-name))))
(defrecord RabbitMQBroker
[
;; RabbitMQ server host
host
;; RabbitMQ server port for queueing requests
port
;; RabbitMQ server port for admin requests (http)
admin-port
;; RabbitMQ user name
username
;; RabbitMQ password
password
;; Connection to the message queue
conn
;; Queues that should be created on startup
persistent-queues
;; Exchanges that should be created on startup
persistent-exchanges
;; A map of queue name to a sequence of exchange names that the queue should be bound to.
bindings]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
lifecycle/Lifecycle
(start
[this system]
(info "Starting RabbitMQ connection")
(let [conn (rmq/connect {:host host :port port :username username :password <PASSWORD>})
this (assoc this :conn conn)]
(info "RabbitMQ connection opened")
(doseq [queue-name persistent-queues]
(create-queue this queue-name))
(doseq [exchange-name persistent-exchanges]
(create-exchange this exchange-name))
(doseq [[queue-name exchange-names] bindings
exchange-name exchange-names]
(bind-queue-to-exchange this queue-name exchange-name))
this))
(stop
[this system]
;; Close the connection. This will close all channels as well.
(when (:conn this) (rmq/close (:conn this)))
(assoc this :conn nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
queue/Queue
(publish-to-queue
[this queue-name msg]
(publish this default-exchange-name queue-name msg))
(get-queues-bound-to-exchange
[this exchange-name]
(for [[q es] bindings
e es
:when (= e exchange-name)]
q))
(publish-to-exchange
[this exchange-name msg]
(publish this exchange-name "" msg))
(subscribe
[this queue-name handler]
(start-consumer this queue-name handler))
(reset
[this]
(info "Resetting RabbitMQ")
(doseq [queue-name persistent-queues]
(purge-queue this queue-name)))
(health
[this]
(let [timeout-ms (* 1000 (+ 2 (hh/health-check-timeout-seconds)))]
(hh/get-health #(health-fn this) timeout-ms))))
(record-pretty-printer/enable-record-pretty-printing RabbitMQBroker)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn create-queue-broker
"Create a RabbitMQBroker with the given parameters. See RabbitMQBroker comments for information"
[{:keys [host port admin-port username password
queues exchanges queues-to-exchanges]}]
(->RabbitMQBroker host port admin-port username password nil
queues exchanges queues-to-exchanges))
| true | (ns cmr.message-queue.queue.rabbit-mq
"Implements index-queue functionality using rabbit mq"
(:gen-class)
(:require [cmr.common.lifecycle :as lifecycle]
[cmr.common.log :as log :refer (debug info warn error)]
[cmr.common.mime-types :as mt]
[cmr.message-queue.config :as config]
[cmr.common.services.errors :as errors]
[cmr.message-queue.services.queue :as queue]
[langohr.core :as rmq]
[langohr.channel :as lch]
[langohr.queue :as lq]
[langohr.consumers :as lc]
[langohr.confirm :as lcf]
[langohr.basic :as lb]
[langohr.exchange :as le]
[clj-http.client :as client]
[cheshire.core :as json]
[cmr.common.services.health-helper :as hh]
[cmr.common.dev.record-pretty-printer :as record-pretty-printer])
(:import java.io.IOException))
(defmacro with-channel
"Opens and binds a channel to the given name from a connection, executes the body and then closes the channel.
Example:
(with-channel
[chan conn]
(lq/status chan \"my-queue\"))"
[bindings & body]
(when (not= 2 (count bindings))
(throw (Exception. "Expected a single pair of bindings of a channel symbol and a connection")))
(let [[channel-name connection-name] bindings]
`(let [~channel-name (lch/open ~connection-name)]
(try
~@body
(finally
(lch/close ~channel-name))))))
(defn wait-queue-name
"Returns the name of the wait queue associated with the given queue name and retry-count"
[queue-name retry-count]
(str queue-name "_wait_" retry-count))
(defn- wait-queue-ttl
"Returns the Time-To-Live (TTL) in milliseconds for the nth (1 based) wait queue"
[n]
(* 1000 (nth (config/rabbit-mq-ttls) (dec n))))
(def ^:const default-exchange-name "")
(defn- attempt-retry
"Retry a message if it has not already exceeded the allowable retries"
[queue-broker ch queue-name msg delivery-tag resp]
(let [retry-count (get msg :retry-count 0)]
(if (queue/retry-limit-met? msg (count (config/rabbit-mq-ttls)))
(do
;; give up
;; Splunk alert "Indexing from message queue failed and all retries exhausted" dependent on this log message
(warn "Max retries exceeded for processing message:" (pr-str msg) "on queue:" queue-name)
(lb/nack ch delivery-tag false false))
(let [msg (assoc msg :retry-count (inc retry-count))
wait-q (wait-queue-name queue-name (inc retry-count))
ttl (wait-queue-ttl (inc retry-count))]
(info "Message" (pr-str msg) "re-queued with response:" (pr-str (:message resp)))
(info (format "Retrying with retry-count =%d on queue %s with ttl = %d"
(inc retry-count)
wait-q
ttl))
(queue/publish-to-queue queue-broker wait-q msg)
(lb/ack ch delivery-tag)))))
(defn- message-handler
"Processes a given message and determines what to do based on the response code returned. Send an
ack if the message completed successfully. Put the message on a wait queue if the response
indicates it needs to be retried. Nack the message if the response is marked as failed."
[queue-broker queue-name client-handler ch metadata ^bytes payload]
(let [{:keys [delivery-tag]} metadata
msg (json/parse-string (String. payload) true)]
(try
(client-handler msg)
(lb/ack ch delivery-tag)
(catch Throwable e
(error e "Message processing failed for message" (pr-str msg))
(attempt-retry queue-broker ch queue-name msg delivery-tag
{:message (.getMessage e)})))))
(defn- start-consumer
"Starts a message consumer in a separate thread.
'queue-broker' is a record that implements
both the Queue and Lifecycle protocols for interacting with a message queue.
'queue-name' is the identifier of the queue to use to receive messages and should correpsond to
the identifier used to create the queue with the create-queue function.
'client-handler' is a function that takes a single parameter (the message) and attempts to
process it. If a function throws an exception it will be retried."
[queue-broker queue-name client-handler]
(let [conn (:conn queue-broker)
;; don't want this channel to close automatically, so no with-channel here
sub-ch (lch/open conn)
handler (partial message-handler queue-broker queue-name client-handler)]
;; By default, RabbitMQ uses a round-robin approach to send messages to listeners. This can
;; lead to stalls as workers wait for other workers to complete. Setting QoS (prefetch) to 1
;; prevents this.
(lb/qos sub-ch 1)
(lc/subscribe sub-ch queue-name handler {:auto-ack false})))
(defn purge-queue
"Remove all messages from a queue and the associated wait queues"
[broker queue-name]
(let [conn (:conn broker)]
(with-channel [ch conn]
(info "Purging all messages from queue" queue-name)
(lq/purge ch queue-name)
(doseq [wait-queue-num (range 1 (inc (count (config/rabbit-mq-ttls))))
:let [ttl (wait-queue-ttl wait-queue-num)
wq (wait-queue-name queue-name wait-queue-num)]]
(debug "Purging messages from wait queue" wq)
(lq/purge ch wq)))))
(defn delete-queue
"Remove a queue from the RabbitMQ server/cluster"
[broker queue-name]
(let [conn (:conn broker)]
(with-channel [ch conn]
(lq/delete ch queue-name)
(doseq [wait-queue-num (range 1 (inc (count (config/rabbit-mq-ttls))))
:let [ttl (wait-queue-ttl wait-queue-num)
wq (wait-queue-name queue-name wait-queue-num)]]
(lq/delete ch wq)))))
(defn health-fn
"Check that the queue is up and responding"
[queue-broker]
(try
(let [{:keys [host admin-port username password]} queue-broker
{:keys [status body]} (client/request
{:url (format "http://%s:%s/api/aliveness-test/%s"
host admin-port
"%2f")
:method :get
:throw-exceptions false
:basic-auth [username password]})]
(if (= status 200)
(let [rmq-status (-> body (json/decode true) :status)]
(if (= rmq-status "ok")
{:ok? true}
{:ok? false :problem rmq-status}))
{:ok? false :problem body}))
(catch Exception e
{:ok? false :problem (.getMessage e)})))
(defn- publish
"Publishes a message to the given exchange/queue combination. When publishing to a queue set the
exchange name to an empty string and the routing-key to the queue name."
[queue-broker exchange-name routing-key msg]
(let [payload (json/generate-string msg)
metadata {:content-type mt/json :persistent true}]
(with-channel
[pub-ch (:conn queue-broker)]
;; put channel into confirmation mode
(lcf/select pub-ch)
;; publish the message
(lb/publish pub-ch exchange-name routing-key payload metadata)
;; block until the confirm arrives or return false if queue nacks the message
(lcf/wait-for-confirms pub-ch))))
(defn- create-queue
[broker queue-name]
(let [{:keys [conn]} broker]
(with-channel
[ch conn]
;; create the queue
;; see http://reference.clojurerabbitmq.info/langohr.queue.html
(info "Creating queue" queue-name)
(lq/declare ch queue-name {:exclusive false :auto-delete false :durable true})
;; create wait queues to use with the primary queue
(info "Creating wait queues")
(doseq [wait-queue-num (range 1 (inc (count (config/rabbit-mq-ttls))))
:let [ttl (wait-queue-ttl wait-queue-num)
wq (wait-queue-name queue-name wait-queue-num)]]
(lq/declare ch
wq
{:exclusive false
:auto-delete false
:durable true
:arguments {"x-dead-letter-exchange" default-exchange-name
"x-dead-letter-routing-key" queue-name
"x-message-ttl" ttl}})))))
(defn- create-exchange
[broker exchange-name]
(let [{:keys [conn]} broker]
(with-channel
[ch conn]
(info "Creating exchange" exchange-name)
(le/declare ch exchange-name "fanout" {:durable true}))))
(defn- bind-queue-to-exchange
[broker queue-name exchange-name]
(let [{:keys [conn]} broker]
(with-channel
[ch conn]
(info "Binding queue" queue-name "to exchange" exchange-name)
(lq/bind ch queue-name exchange-name))))
(defrecord RabbitMQBroker
[
;; RabbitMQ server host
host
;; RabbitMQ server port for queueing requests
port
;; RabbitMQ server port for admin requests (http)
admin-port
;; RabbitMQ user name
username
;; RabbitMQ password
password
;; Connection to the message queue
conn
;; Queues that should be created on startup
persistent-queues
;; Exchanges that should be created on startup
persistent-exchanges
;; A map of queue name to a sequence of exchange names that the queue should be bound to.
bindings]
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
lifecycle/Lifecycle
(start
[this system]
(info "Starting RabbitMQ connection")
(let [conn (rmq/connect {:host host :port port :username username :password PI:PASSWORD:<PASSWORD>END_PI})
this (assoc this :conn conn)]
(info "RabbitMQ connection opened")
(doseq [queue-name persistent-queues]
(create-queue this queue-name))
(doseq [exchange-name persistent-exchanges]
(create-exchange this exchange-name))
(doseq [[queue-name exchange-names] bindings
exchange-name exchange-names]
(bind-queue-to-exchange this queue-name exchange-name))
this))
(stop
[this system]
;; Close the connection. This will close all channels as well.
(when (:conn this) (rmq/close (:conn this)))
(assoc this :conn nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
queue/Queue
(publish-to-queue
[this queue-name msg]
(publish this default-exchange-name queue-name msg))
(get-queues-bound-to-exchange
[this exchange-name]
(for [[q es] bindings
e es
:when (= e exchange-name)]
q))
(publish-to-exchange
[this exchange-name msg]
(publish this exchange-name "" msg))
(subscribe
[this queue-name handler]
(start-consumer this queue-name handler))
(reset
[this]
(info "Resetting RabbitMQ")
(doseq [queue-name persistent-queues]
(purge-queue this queue-name)))
(health
[this]
(let [timeout-ms (* 1000 (+ 2 (hh/health-check-timeout-seconds)))]
(hh/get-health #(health-fn this) timeout-ms))))
(record-pretty-printer/enable-record-pretty-printing RabbitMQBroker)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn create-queue-broker
"Create a RabbitMQBroker with the given parameters. See RabbitMQBroker comments for information"
[{:keys [host port admin-port username password
queues exchanges queues-to-exchanges]}]
(->RabbitMQBroker host port admin-port username password nil
queues exchanges queues-to-exchanges))
|
[
{
"context": " :user \"clj_dev\"\n :password \"password\"}\n repos (create-database mysql-db)]\n (",
"end": 327,
"score": 0.9995213747024536,
"start": 319,
"tag": "PASSWORD",
"value": "password"
}
] | src/clj_clean_todos/main/console_db.clj | shintaro4/clj-clean-todos | 0 | (ns clj-clean-todos.main.console-db
(:require [clj-clean-todos.ui.console.core :as console]
[clj-clean-todos.repos.db :refer [create-database]]))
(defn -main
[]
(let [mysql-db {:dbtype "mysql"
:dbname "clj_clean_todos"
:user "clj_dev"
:password "password"}
repos (create-database mysql-db)]
(console/start repos)))
| 60166 | (ns clj-clean-todos.main.console-db
(:require [clj-clean-todos.ui.console.core :as console]
[clj-clean-todos.repos.db :refer [create-database]]))
(defn -main
[]
(let [mysql-db {:dbtype "mysql"
:dbname "clj_clean_todos"
:user "clj_dev"
:password "<PASSWORD>"}
repos (create-database mysql-db)]
(console/start repos)))
| true | (ns clj-clean-todos.main.console-db
(:require [clj-clean-todos.ui.console.core :as console]
[clj-clean-todos.repos.db :refer [create-database]]))
(defn -main
[]
(let [mysql-db {:dbtype "mysql"
:dbname "clj_clean_todos"
:user "clj_dev"
:password "PI:PASSWORD:<PASSWORD>END_PI"}
repos (create-database mysql-db)]
(console/start repos)))
|
[
{
"context": " for ClojureScript\"\n :url \"http://github.com/cognitect/transit-cljs\"\n\n :dependencies [[org.clojure/cloj",
"end": 139,
"score": 0.559467077255249,
"start": 134,
"tag": "USERNAME",
"value": "itect"
},
{
"context": " [codox \"0.8.9\"]]\n\n :scm {:connection \"scm:git:git@github.com:cognitect/transit-cljs.git\"\n :developerCon",
"end": 442,
"score": 0.9975687861442566,
"start": 428,
"tag": "EMAIL",
"value": "git@github.com"
},
{
"context": "t-cljs.git\"\n :developerConnection \"scm:git:git@github.com:cognitect/transit-cljs.git\"\n :url \"git@git",
"end": 523,
"score": 0.9985661506652832,
"start": 509,
"tag": "EMAIL",
"value": "git@github.com"
},
{
"context": " :developerConnection \"scm:git:git@github.com:cognitect/transit-cljs.git\"\n :url \"git@github.com:co",
"end": 533,
"score": 0.5652401447296143,
"start": 524,
"tag": "USERNAME",
"value": "cognitect"
},
{
"context": "hub.com:cognitect/transit-cljs.git\"\n :url \"git@github.com:cognitect/transit-cljs.git\"}\n :pom-addition [:de",
"end": 580,
"score": 0.9993947148323059,
"start": 566,
"tag": "EMAIL",
"value": "git@github.com"
},
{
"context": "ransit-cljs.git\"\n :url \"git@github.com:cognitect/transit-cljs.git\"}\n :pom-addition [:developers [",
"end": 590,
"score": 0.5245977640151978,
"start": 585,
"tag": "USERNAME",
"value": "itect"
},
{
"context": "[:developer\n [:name \"David Nolen\"]\n [:email \"david.no",
"end": 700,
"score": 0.999863862991333,
"start": 689,
"tag": "NAME",
"value": "David Nolen"
},
{
"context": "id Nolen\"]\n [:email \"david.nolen@cognitect.com\"]\n [:organization \"C",
"end": 767,
"score": 0.999914288520813,
"start": 742,
"tag": "EMAIL",
"value": "david.nolen@cognitect.com"
},
{
"context": "r \"doc\"\n :src-dir-uri \"http://github.com/cognitect/transit-cljs/blob/master/\"\n :src-linenum",
"end": 3071,
"score": 0.999657154083252,
"start": 3062,
"tag": "USERNAME",
"value": "cognitect"
}
] | project.clj | Day8/transit-cljs | 1 | (defproject com.cognitect/transit-cljs "0.8.202"
:description "transit-js bindings for ClojureScript"
:url "http://github.com/cognitect/transit-cljs"
:dependencies [[org.clojure/clojure "1.6.0"]
[org.clojure/clojurescript "0.0-2665" :scope "provided"]
[com.cognitect/transit-js "0.8.755"]]
:plugins [[lein-cljsbuild "1.0.4"]
[codox "0.8.9"]]
:scm {:connection "scm:git:git@github.com:cognitect/transit-cljs.git"
:developerConnection "scm:git:git@github.com:cognitect/transit-cljs.git"
:url "git@github.com:cognitect/transit-cljs.git"}
:pom-addition [:developers [:developer
[:name "David Nolen"]
[:email "david.nolen@cognitect.com"]
[:organization "Cognitect"]
[:organizationUrl "http://cognitect.com"]]]
:license {:name "The Apache Software License, Version 2.0"
:url "http://www.apache.org/licenses/LICENSE-2.0.txt"
:distribution :repo}
:source-paths ["src"]
:clean-targets ["target"]
:cljsbuild {
:builds [{:id "dev"
:source-paths ["src"]
:compiler {
:output-to "transit.dev.js"
:output-dir "target/out-dev"
:optimizations :none
:source-map true}}
{:id "test-dev"
:source-paths ["src" "test/transit/test"]
:compiler {
:output-to "target/transit.test.js"
:output-dir "target/out-dev-test"
:optimizations :none
:source-map true}}
{:id "test"
:source-paths ["src" "test/transit/test"]
:notify-command ["node" "target/transit.test.js"]
:compiler {
:output-to "target/transit.test.js"
:output-dir "target/out-test"
:optimizations :advanced
:pretty-print false
:target :nodejs}}
{:id "roundtrip"
:source-paths ["src" "test/transit/roundtrip"]
:compiler {
:output-to "target/roundtrip.js"
:output-dir "target/out-roundtrip"
:optimizations :advanced
:externs ["resources/node_externs.js"]}}
{:id "bench"
:source-paths ["src" "bench"]
:compiler {
:output-to "target/transit.bench.js"
:output-dir "target/out-bench"
:optimizations :advanced
:pretty-print false
:externs ["resources/node_externs.js"]}}
{:id "adv"
:source-paths ["src"]
:compiler {
:output-to "target/transit.adv.js"
:output-dir "target/out-adv"
:optimizations :advanced
:pretty-print false}}]}
:codox {:language :clojurescript
:output-dir "doc"
:src-dir-uri "http://github.com/cognitect/transit-cljs/blob/master/"
:src-linenum-anchor-prefix "L"}
)
| 107353 | (defproject com.cognitect/transit-cljs "0.8.202"
:description "transit-js bindings for ClojureScript"
:url "http://github.com/cognitect/transit-cljs"
:dependencies [[org.clojure/clojure "1.6.0"]
[org.clojure/clojurescript "0.0-2665" :scope "provided"]
[com.cognitect/transit-js "0.8.755"]]
:plugins [[lein-cljsbuild "1.0.4"]
[codox "0.8.9"]]
:scm {:connection "scm:git:<EMAIL>:cognitect/transit-cljs.git"
:developerConnection "scm:git:<EMAIL>:cognitect/transit-cljs.git"
:url "<EMAIL>:cognitect/transit-cljs.git"}
:pom-addition [:developers [:developer
[:name "<NAME>"]
[:email "<EMAIL>"]
[:organization "Cognitect"]
[:organizationUrl "http://cognitect.com"]]]
:license {:name "The Apache Software License, Version 2.0"
:url "http://www.apache.org/licenses/LICENSE-2.0.txt"
:distribution :repo}
:source-paths ["src"]
:clean-targets ["target"]
:cljsbuild {
:builds [{:id "dev"
:source-paths ["src"]
:compiler {
:output-to "transit.dev.js"
:output-dir "target/out-dev"
:optimizations :none
:source-map true}}
{:id "test-dev"
:source-paths ["src" "test/transit/test"]
:compiler {
:output-to "target/transit.test.js"
:output-dir "target/out-dev-test"
:optimizations :none
:source-map true}}
{:id "test"
:source-paths ["src" "test/transit/test"]
:notify-command ["node" "target/transit.test.js"]
:compiler {
:output-to "target/transit.test.js"
:output-dir "target/out-test"
:optimizations :advanced
:pretty-print false
:target :nodejs}}
{:id "roundtrip"
:source-paths ["src" "test/transit/roundtrip"]
:compiler {
:output-to "target/roundtrip.js"
:output-dir "target/out-roundtrip"
:optimizations :advanced
:externs ["resources/node_externs.js"]}}
{:id "bench"
:source-paths ["src" "bench"]
:compiler {
:output-to "target/transit.bench.js"
:output-dir "target/out-bench"
:optimizations :advanced
:pretty-print false
:externs ["resources/node_externs.js"]}}
{:id "adv"
:source-paths ["src"]
:compiler {
:output-to "target/transit.adv.js"
:output-dir "target/out-adv"
:optimizations :advanced
:pretty-print false}}]}
:codox {:language :clojurescript
:output-dir "doc"
:src-dir-uri "http://github.com/cognitect/transit-cljs/blob/master/"
:src-linenum-anchor-prefix "L"}
)
| true | (defproject com.cognitect/transit-cljs "0.8.202"
:description "transit-js bindings for ClojureScript"
:url "http://github.com/cognitect/transit-cljs"
:dependencies [[org.clojure/clojure "1.6.0"]
[org.clojure/clojurescript "0.0-2665" :scope "provided"]
[com.cognitect/transit-js "0.8.755"]]
:plugins [[lein-cljsbuild "1.0.4"]
[codox "0.8.9"]]
:scm {:connection "scm:git:PI:EMAIL:<EMAIL>END_PI:cognitect/transit-cljs.git"
:developerConnection "scm:git:PI:EMAIL:<EMAIL>END_PI:cognitect/transit-cljs.git"
:url "PI:EMAIL:<EMAIL>END_PI:cognitect/transit-cljs.git"}
:pom-addition [:developers [:developer
[:name "PI:NAME:<NAME>END_PI"]
[:email "PI:EMAIL:<EMAIL>END_PI"]
[:organization "Cognitect"]
[:organizationUrl "http://cognitect.com"]]]
:license {:name "The Apache Software License, Version 2.0"
:url "http://www.apache.org/licenses/LICENSE-2.0.txt"
:distribution :repo}
:source-paths ["src"]
:clean-targets ["target"]
:cljsbuild {
:builds [{:id "dev"
:source-paths ["src"]
:compiler {
:output-to "transit.dev.js"
:output-dir "target/out-dev"
:optimizations :none
:source-map true}}
{:id "test-dev"
:source-paths ["src" "test/transit/test"]
:compiler {
:output-to "target/transit.test.js"
:output-dir "target/out-dev-test"
:optimizations :none
:source-map true}}
{:id "test"
:source-paths ["src" "test/transit/test"]
:notify-command ["node" "target/transit.test.js"]
:compiler {
:output-to "target/transit.test.js"
:output-dir "target/out-test"
:optimizations :advanced
:pretty-print false
:target :nodejs}}
{:id "roundtrip"
:source-paths ["src" "test/transit/roundtrip"]
:compiler {
:output-to "target/roundtrip.js"
:output-dir "target/out-roundtrip"
:optimizations :advanced
:externs ["resources/node_externs.js"]}}
{:id "bench"
:source-paths ["src" "bench"]
:compiler {
:output-to "target/transit.bench.js"
:output-dir "target/out-bench"
:optimizations :advanced
:pretty-print false
:externs ["resources/node_externs.js"]}}
{:id "adv"
:source-paths ["src"]
:compiler {
:output-to "target/transit.adv.js"
:output-dir "target/out-adv"
:optimizations :advanced
:pretty-print false}}]}
:codox {:language :clojurescript
:output-dir "doc"
:src-dir-uri "http://github.com/cognitect/transit-cljs/blob/master/"
:src-linenum-anchor-prefix "L"}
)
|
[
{
"context": ")\n;; (starts-with :author \"Zola\")\n;; (starts-with :title \"",
"end": 3114,
"score": 0.7863078117370605,
"start": 3110,
"tag": "NAME",
"value": "Zola"
},
{
"context": "cb/query (= :language \"fr\") (starts-with :author \"Dumas\") :limit 3))\n\n;;; Demonstrate transaction rollbac",
"end": 3435,
"score": 0.7988862991333008,
"start": 3430,
"tag": "NAME",
"value": "Dumas"
},
{
"context": "cb/query (= :language \"fr\") (starts-with :author \"Dumas\")\n;; :callback cb/delete)\n;; (print",
"end": 3624,
"score": 0.9642580151557922,
"start": 3619,
"tag": "NAME",
"value": "Dumas"
}
] | examples/examples/cupboard/gutenberg.clj | gcv/cupboard | 16 | (ns examples.cupboard.gutenberg
(:use [clojure.contrib java-utils pprint])
(:require [cupboard.core :as cb])
(:use [cupboard.utils])
(:require [clojure.xml :as xml])
(:require [clojure.contrib.lazy-xml :as lazy-xml]))
;;; ----------------------------------------------------------------------------
;;; Cupboard demonstration
;;; ----------------------------------------------------------------------------
;;; Declare a database-persisted struct-map. This creates a real struct-map with
;;; the given slot names, and with the given indices.
(cb/defpersist etext
((:id :index :unique)
(:title :index :any)
(:author :index :any)
(:language :index :any)
(:date-added :index :any)))
;;; Given a list of raw entry maps, write them to the database. This is done
;;; using cb/make-instance, which both instantiates a database-persisted
;;; struct-map and writes it to the database.
(defn write-entries [entries]
(cb/with-txn [:no-sync true]
(doseq [entry entries]
(cb/make-instance etext [(entry :id)
(entry :title)
(entry :author)
(entry :language)
(entry :date-added)]))))
;;; Start by downloading the Project Gutenberg catalog:
;;; http://www.gutenberg.org/wiki/Gutenberg:Feeds
;;; As of [2009-10-11 Sun], the direct link is:
;;; http://www.gutenberg.org/feeds/offline-package.tar.bz2
;;; You need the large .rdf file for this example's raw data.
;;; Open the default cupboard, cb/*cupboard*. To speed up the initial data
;;; import, disable the cleaner and checkpointer threads.
;; (cb/open-cupboard! "/tmp/gutenberg-catalog" :run-cleaner false :run-checkpointer false)
;;; The data import takes roughly 70 seconds on a mid-2008 MacBook Pro with 4GB
;;; of RAM, with the Java heap size set to 2GB and the concurrent mark-and-sweep
;;; garbage collector turned on (-server -Xms2000M -Xmx2000M -XX:+UseConcMarkSweepGC).
;;; There should be ways to tune the import process and make it faster.
;; (time (import-catalog "/tmp/gutenberg-catalog.rdf"))
;;; Turn the cleaner and checkpointer threads back on.
;; (cb/modify-env :run-cleaner true :run-checkpointer true)
;;; Check the number of imported books. It should exceed 30000.
;; (cb/shelf-count)
;;; List all books written in Afrikaans.
;; (pprint
;; (cb/query (= :language "af")))
;;; Change the language code for all Afrikaans books from "af" to "Afrikaans".
;; (pprint
;; (cb/query (= :language "af") :callback #(cb/passoc! % :language "Afrikaans")))
;;; Now, delete all books written in Afrikaans.
;; (cb/query (= :language "Afrikaans") :callback cb/delete)
;;; Note the decremented count of the number of entries on the default shelf.
;; (cb/shelf-count)
;;; Demonstrate joins and restoring the struct-map types of the results. This
;;; finds all of Émile Zola's originals (not translations) in the catalog,
;;; specifically "J'accuse!.." and returns the result as an etext struct-map.
;; (let [result (cb/query (= :language "fr")
;; (starts-with :author "Zola")
;; (starts-with :title "J'accuse")
;; :struct etext)
;; book (first result)]
;; (pprint book)
;; (pprint (type book)))
;;; Demonstrate retrieving only a subset of entries from the database.
;; (pprint
;; (cb/query (= :language "fr") (starts-with :author "Dumas") :limit 3))
;;; Demonstrate transaction rollback.
;; (cb/with-txn []
;; (println "starting shelf count:" (cb/shelf-count))
;; (cb/query (= :language "fr") (starts-with :author "Dumas")
;; :callback cb/delete)
;; (println "shelf count after deletion:" (cb/shelf-count))
;; (cb/rollback)
;; (println "shelf count after rollback:" (cb/shelf-count)))
;;; Close the default cupboard.
;; (cb/close-cupboard!)
;;; ----------------------------------------------------------------------------
;;; forward declarations
;;; ----------------------------------------------------------------------------
(declare get-etext etexts gutenberg-catalog)
;;; ----------------------------------------------------------------------------
;;; Project Gutenberg catalog extraction
;;; (no Cupboard-specific code; just XML parsing)
;;; ----------------------------------------------------------------------------
(defn import-catalog [catalog-path]
(System/setProperty "entityExpansionLimit" (str Integer/MAX_VALUE))
(let [writer-agent (agent [])]
(doseq [new-entry (etexts (gutenberg-catalog catalog-path lazy-xml/parse-trim))]
(send writer-agent
(fn [curr-val]
(let [new-val (conj curr-val (get-etext new-entry))]
(if (< (count curr-val) 9) ; 10 at a time
;; then: just accumulate
new-val
;; else: write to database
(do
(write-entries new-val)
[]))))))
;; write whatever is left in the agent's queue
(send writer-agent (fn [curr-val] (write-entries curr-val)))
(println "done, waiting for agent")
(await writer-agent)))
(defn gutenberg-catalog [location parser-fn]
(let [location (file location)
full-xml-seq (parser-fn location)
content-seq (full-xml-seq :content)]
content-seq))
(defn etexts [content-seq]
(filter #(= (:tag %) :pgterms:etext) content-seq))
(defn extract-element [element]
(cond
;; title
(and (= (element :tag) :dc:title)
(= (-> element :attrs :rdf:parseType) "Literal"))
[:title (first (-> element :content))]
;; author
(and (= (element :tag) :dc:creator)
(= (-> element :attrs :rdf:parseType) "Literal"))
[:author (first (-> element :content))]
;; language
(= (element :tag) :dc:language)
[:language (let [content (element :content)
all-lang (map #(first ((first (% :content)) :content)) content)]
(if (= (count all-lang) 1) (first all-lang) all-lang))]
;; date added
(= (element :tag) :dc:created)
[:date-added (let [content (element :content)
all-dates (map #(first ((first (% :content)) :content)) content)
date (localdate (first all-dates))]
date)]
:else nil))
(defn get-etext [entry]
(let [id (-> entry :attrs :rdf:ID)
content (entry :content)
literals (remove nil? (map extract-element content))]
(apply hash-map (flatten (concat [:id id] literals)))))
| 21329 | (ns examples.cupboard.gutenberg
(:use [clojure.contrib java-utils pprint])
(:require [cupboard.core :as cb])
(:use [cupboard.utils])
(:require [clojure.xml :as xml])
(:require [clojure.contrib.lazy-xml :as lazy-xml]))
;;; ----------------------------------------------------------------------------
;;; Cupboard demonstration
;;; ----------------------------------------------------------------------------
;;; Declare a database-persisted struct-map. This creates a real struct-map with
;;; the given slot names, and with the given indices.
(cb/defpersist etext
((:id :index :unique)
(:title :index :any)
(:author :index :any)
(:language :index :any)
(:date-added :index :any)))
;;; Given a list of raw entry maps, write them to the database. This is done
;;; using cb/make-instance, which both instantiates a database-persisted
;;; struct-map and writes it to the database.
(defn write-entries [entries]
(cb/with-txn [:no-sync true]
(doseq [entry entries]
(cb/make-instance etext [(entry :id)
(entry :title)
(entry :author)
(entry :language)
(entry :date-added)]))))
;;; Start by downloading the Project Gutenberg catalog:
;;; http://www.gutenberg.org/wiki/Gutenberg:Feeds
;;; As of [2009-10-11 Sun], the direct link is:
;;; http://www.gutenberg.org/feeds/offline-package.tar.bz2
;;; You need the large .rdf file for this example's raw data.
;;; Open the default cupboard, cb/*cupboard*. To speed up the initial data
;;; import, disable the cleaner and checkpointer threads.
;; (cb/open-cupboard! "/tmp/gutenberg-catalog" :run-cleaner false :run-checkpointer false)
;;; The data import takes roughly 70 seconds on a mid-2008 MacBook Pro with 4GB
;;; of RAM, with the Java heap size set to 2GB and the concurrent mark-and-sweep
;;; garbage collector turned on (-server -Xms2000M -Xmx2000M -XX:+UseConcMarkSweepGC).
;;; There should be ways to tune the import process and make it faster.
;; (time (import-catalog "/tmp/gutenberg-catalog.rdf"))
;;; Turn the cleaner and checkpointer threads back on.
;; (cb/modify-env :run-cleaner true :run-checkpointer true)
;;; Check the number of imported books. It should exceed 30000.
;; (cb/shelf-count)
;;; List all books written in Afrikaans.
;; (pprint
;; (cb/query (= :language "af")))
;;; Change the language code for all Afrikaans books from "af" to "Afrikaans".
;; (pprint
;; (cb/query (= :language "af") :callback #(cb/passoc! % :language "Afrikaans")))
;;; Now, delete all books written in Afrikaans.
;; (cb/query (= :language "Afrikaans") :callback cb/delete)
;;; Note the decremented count of the number of entries on the default shelf.
;; (cb/shelf-count)
;;; Demonstrate joins and restoring the struct-map types of the results. This
;;; finds all of Émile Zola's originals (not translations) in the catalog,
;;; specifically "J'accuse!.." and returns the result as an etext struct-map.
;; (let [result (cb/query (= :language "fr")
;; (starts-with :author "<NAME>")
;; (starts-with :title "J'accuse")
;; :struct etext)
;; book (first result)]
;; (pprint book)
;; (pprint (type book)))
;;; Demonstrate retrieving only a subset of entries from the database.
;; (pprint
;; (cb/query (= :language "fr") (starts-with :author "<NAME>") :limit 3))
;;; Demonstrate transaction rollback.
;; (cb/with-txn []
;; (println "starting shelf count:" (cb/shelf-count))
;; (cb/query (= :language "fr") (starts-with :author "<NAME>")
;; :callback cb/delete)
;; (println "shelf count after deletion:" (cb/shelf-count))
;; (cb/rollback)
;; (println "shelf count after rollback:" (cb/shelf-count)))
;;; Close the default cupboard.
;; (cb/close-cupboard!)
;;; ----------------------------------------------------------------------------
;;; forward declarations
;;; ----------------------------------------------------------------------------
(declare get-etext etexts gutenberg-catalog)
;;; ----------------------------------------------------------------------------
;;; Project Gutenberg catalog extraction
;;; (no Cupboard-specific code; just XML parsing)
;;; ----------------------------------------------------------------------------
(defn import-catalog [catalog-path]
(System/setProperty "entityExpansionLimit" (str Integer/MAX_VALUE))
(let [writer-agent (agent [])]
(doseq [new-entry (etexts (gutenberg-catalog catalog-path lazy-xml/parse-trim))]
(send writer-agent
(fn [curr-val]
(let [new-val (conj curr-val (get-etext new-entry))]
(if (< (count curr-val) 9) ; 10 at a time
;; then: just accumulate
new-val
;; else: write to database
(do
(write-entries new-val)
[]))))))
;; write whatever is left in the agent's queue
(send writer-agent (fn [curr-val] (write-entries curr-val)))
(println "done, waiting for agent")
(await writer-agent)))
(defn gutenberg-catalog [location parser-fn]
(let [location (file location)
full-xml-seq (parser-fn location)
content-seq (full-xml-seq :content)]
content-seq))
(defn etexts [content-seq]
(filter #(= (:tag %) :pgterms:etext) content-seq))
(defn extract-element [element]
(cond
;; title
(and (= (element :tag) :dc:title)
(= (-> element :attrs :rdf:parseType) "Literal"))
[:title (first (-> element :content))]
;; author
(and (= (element :tag) :dc:creator)
(= (-> element :attrs :rdf:parseType) "Literal"))
[:author (first (-> element :content))]
;; language
(= (element :tag) :dc:language)
[:language (let [content (element :content)
all-lang (map #(first ((first (% :content)) :content)) content)]
(if (= (count all-lang) 1) (first all-lang) all-lang))]
;; date added
(= (element :tag) :dc:created)
[:date-added (let [content (element :content)
all-dates (map #(first ((first (% :content)) :content)) content)
date (localdate (first all-dates))]
date)]
:else nil))
(defn get-etext [entry]
(let [id (-> entry :attrs :rdf:ID)
content (entry :content)
literals (remove nil? (map extract-element content))]
(apply hash-map (flatten (concat [:id id] literals)))))
| true | (ns examples.cupboard.gutenberg
(:use [clojure.contrib java-utils pprint])
(:require [cupboard.core :as cb])
(:use [cupboard.utils])
(:require [clojure.xml :as xml])
(:require [clojure.contrib.lazy-xml :as lazy-xml]))
;;; ----------------------------------------------------------------------------
;;; Cupboard demonstration
;;; ----------------------------------------------------------------------------
;;; Declare a database-persisted struct-map. This creates a real struct-map with
;;; the given slot names, and with the given indices.
(cb/defpersist etext
((:id :index :unique)
(:title :index :any)
(:author :index :any)
(:language :index :any)
(:date-added :index :any)))
;;; Given a list of raw entry maps, write them to the database. This is done
;;; using cb/make-instance, which both instantiates a database-persisted
;;; struct-map and writes it to the database.
(defn write-entries [entries]
(cb/with-txn [:no-sync true]
(doseq [entry entries]
(cb/make-instance etext [(entry :id)
(entry :title)
(entry :author)
(entry :language)
(entry :date-added)]))))
;;; Start by downloading the Project Gutenberg catalog:
;;; http://www.gutenberg.org/wiki/Gutenberg:Feeds
;;; As of [2009-10-11 Sun], the direct link is:
;;; http://www.gutenberg.org/feeds/offline-package.tar.bz2
;;; You need the large .rdf file for this example's raw data.
;;; Open the default cupboard, cb/*cupboard*. To speed up the initial data
;;; import, disable the cleaner and checkpointer threads.
;; (cb/open-cupboard! "/tmp/gutenberg-catalog" :run-cleaner false :run-checkpointer false)
;;; The data import takes roughly 70 seconds on a mid-2008 MacBook Pro with 4GB
;;; of RAM, with the Java heap size set to 2GB and the concurrent mark-and-sweep
;;; garbage collector turned on (-server -Xms2000M -Xmx2000M -XX:+UseConcMarkSweepGC).
;;; There should be ways to tune the import process and make it faster.
;; (time (import-catalog "/tmp/gutenberg-catalog.rdf"))
;;; Turn the cleaner and checkpointer threads back on.
;; (cb/modify-env :run-cleaner true :run-checkpointer true)
;;; Check the number of imported books. It should exceed 30000.
;; (cb/shelf-count)
;;; List all books written in Afrikaans.
;; (pprint
;; (cb/query (= :language "af")))
;;; Change the language code for all Afrikaans books from "af" to "Afrikaans".
;; (pprint
;; (cb/query (= :language "af") :callback #(cb/passoc! % :language "Afrikaans")))
;;; Now, delete all books written in Afrikaans.
;; (cb/query (= :language "Afrikaans") :callback cb/delete)
;;; Note the decremented count of the number of entries on the default shelf.
;; (cb/shelf-count)
;;; Demonstrate joins and restoring the struct-map types of the results. This
;;; finds all of Émile Zola's originals (not translations) in the catalog,
;;; specifically "J'accuse!.." and returns the result as an etext struct-map.
;; (let [result (cb/query (= :language "fr")
;; (starts-with :author "PI:NAME:<NAME>END_PI")
;; (starts-with :title "J'accuse")
;; :struct etext)
;; book (first result)]
;; (pprint book)
;; (pprint (type book)))
;;; Demonstrate retrieving only a subset of entries from the database.
;; (pprint
;; (cb/query (= :language "fr") (starts-with :author "PI:NAME:<NAME>END_PI") :limit 3))
;;; Demonstrate transaction rollback.
;; (cb/with-txn []
;; (println "starting shelf count:" (cb/shelf-count))
;; (cb/query (= :language "fr") (starts-with :author "PI:NAME:<NAME>END_PI")
;; :callback cb/delete)
;; (println "shelf count after deletion:" (cb/shelf-count))
;; (cb/rollback)
;; (println "shelf count after rollback:" (cb/shelf-count)))
;;; Close the default cupboard.
;; (cb/close-cupboard!)
;;; ----------------------------------------------------------------------------
;;; forward declarations
;;; ----------------------------------------------------------------------------
(declare get-etext etexts gutenberg-catalog)
;;; ----------------------------------------------------------------------------
;;; Project Gutenberg catalog extraction
;;; (no Cupboard-specific code; just XML parsing)
;;; ----------------------------------------------------------------------------
(defn import-catalog [catalog-path]
(System/setProperty "entityExpansionLimit" (str Integer/MAX_VALUE))
(let [writer-agent (agent [])]
(doseq [new-entry (etexts (gutenberg-catalog catalog-path lazy-xml/parse-trim))]
(send writer-agent
(fn [curr-val]
(let [new-val (conj curr-val (get-etext new-entry))]
(if (< (count curr-val) 9) ; 10 at a time
;; then: just accumulate
new-val
;; else: write to database
(do
(write-entries new-val)
[]))))))
;; write whatever is left in the agent's queue
(send writer-agent (fn [curr-val] (write-entries curr-val)))
(println "done, waiting for agent")
(await writer-agent)))
(defn gutenberg-catalog [location parser-fn]
(let [location (file location)
full-xml-seq (parser-fn location)
content-seq (full-xml-seq :content)]
content-seq))
(defn etexts [content-seq]
(filter #(= (:tag %) :pgterms:etext) content-seq))
(defn extract-element [element]
(cond
;; title
(and (= (element :tag) :dc:title)
(= (-> element :attrs :rdf:parseType) "Literal"))
[:title (first (-> element :content))]
;; author
(and (= (element :tag) :dc:creator)
(= (-> element :attrs :rdf:parseType) "Literal"))
[:author (first (-> element :content))]
;; language
(= (element :tag) :dc:language)
[:language (let [content (element :content)
all-lang (map #(first ((first (% :content)) :content)) content)]
(if (= (count all-lang) 1) (first all-lang) all-lang))]
;; date added
(= (element :tag) :dc:created)
[:date-added (let [content (element :content)
all-dates (map #(first ((first (% :content)) :content)) content)
date (localdate (first all-dates))]
date)]
:else nil))
(defn get-etext [entry]
(let [id (-> entry :attrs :rdf:ID)
content (entry :content)
literals (remove nil? (map extract-element content))]
(apply hash-map (flatten (concat [:id id] literals)))))
|
[
{
"context": "(ns ^{:author \"Adam Berger\"} ulvm.mod-combinators.js.sync.ast\n \"Synchronous",
"end": 26,
"score": 0.9998593330383301,
"start": 15,
"tag": "NAME",
"value": "Adam Berger"
},
{
"context": " ; [:ref [:named-ref-arg {:sub-result :username, :result authorized-login}]\n :val (i",
"end": 2176,
"score": 0.9984578490257263,
"start": 2168,
"tag": "USERNAME",
"value": "username"
}
] | examples/mod-combinators/js-sync/src/ulvm/mod_combinators/js/sync/ast.clj | abrgr/ulvm | 0 | (ns ^{:author "Adam Berger"} ulvm.mod-combinators.js.sync.ast
"Synchronous Javascript Module Combinator AST Generation")
(defn- get-arg-positions
[mod]
; arg-mappings is a list of lists of args where each
; inner list represents a single overload
(let [arg-mappings (get-in mod [:ulvm.core/config
:ulvm.arg-mappings/positional])]
; turn [[:a :b] [:c :d]] into {:a 0, :b 1, :c 0, :d 1}
(apply
merge
(->> arg-mappings
(map #(map vector % (range)))
(map (partial into {}))))))
(defmulti to-js-ast type)
(defmethod to-js-ast clojure.lang.Symbol
[id]
{:type :identifier
:identifier (name id)})
(defmethod to-js-ast java.lang.String
[s]
{:type :string-literal
:value s})
(defmethod to-js-ast clojure.lang.Keyword
[k]
{:type :string-literal
:value (name k)})
(defmethod to-js-ast java.lang.Boolean
[b]
{:type :boolean-literal
:value b})
(defmethod to-js-ast java.lang.Long
[n]
{:type :numeric-literal
:value n})
(defmethod to-js-ast java.lang.Double
[n]
{:type :numeric-literal
:value n})
(defmethod to-js-ast clojure.lang.PersistentVector
[v]
{:type :array-expression
:elements (map to-js-ast v)})
(defmethod to-js-ast clojure.lang.PersistentList
[v]
{:type :array-expression
:elements (map to-js-ast v)})
(defmethod to-js-ast clojure.lang.PersistentHashSet
[v]
{:type :array-expression
:elements (map to-js-ast v)})
(defmethod to-js-ast clojure.lang.PersistentArrayMap
[m]
{:type :object-expression
:properties (map
(fn [[k, v]]
{:type :object-property
:key (to-js-ast (name k))
:value (to-js-ast k)})
m)})
(defn- gen-arg-ast
[mod arg-names args]
(let [arg-pos (get-arg-positions mod)]
(->> args
; get a list of maps with :pos and :val
(map
(fn [[n arg]]
{:pos (get arg-pos n)
; arg looks like
; [:data {}] or
; [:ref [:named-ref-arg {:sub-result :username, :result authorized-login}]
:val (if (= (first arg) :data)
; if we have data, we assume it's a valid ast
(second arg)
; if we're using a reference, we look up the name
(get arg-names n))}))
; sort by :pos
(sort-by :pos)
; get a list of vals in order
(map :val)
; translate them into the obvious asts
(map to-js-ast)
(into []))))
(defn- gen-inv-ast
[{:keys [result-names arg-names mod mod-name inv]}]
(let [result-name (get result-names :*default*)
args (get inv :args)]
{:type :expression-statement
:expression {:type :assignment-expression
:left {:type :identifier
:identifier result-name}
:right {:type :call-expression
:callee {:type :identifier
:identifier mod-name}
:arguments (gen-arg-ast mod arg-names args)}}}))
(defn gen
"Generates a js ast for the given invocations"
[{:keys [invocations body]}]
; TODO: can also return :err
{:ast (concat
(map gen-inv-ast invocations)
body)})
| 51635 | (ns ^{:author "<NAME>"} ulvm.mod-combinators.js.sync.ast
"Synchronous Javascript Module Combinator AST Generation")
(defn- get-arg-positions
[mod]
; arg-mappings is a list of lists of args where each
; inner list represents a single overload
(let [arg-mappings (get-in mod [:ulvm.core/config
:ulvm.arg-mappings/positional])]
; turn [[:a :b] [:c :d]] into {:a 0, :b 1, :c 0, :d 1}
(apply
merge
(->> arg-mappings
(map #(map vector % (range)))
(map (partial into {}))))))
(defmulti to-js-ast type)
(defmethod to-js-ast clojure.lang.Symbol
[id]
{:type :identifier
:identifier (name id)})
(defmethod to-js-ast java.lang.String
[s]
{:type :string-literal
:value s})
(defmethod to-js-ast clojure.lang.Keyword
[k]
{:type :string-literal
:value (name k)})
(defmethod to-js-ast java.lang.Boolean
[b]
{:type :boolean-literal
:value b})
(defmethod to-js-ast java.lang.Long
[n]
{:type :numeric-literal
:value n})
(defmethod to-js-ast java.lang.Double
[n]
{:type :numeric-literal
:value n})
(defmethod to-js-ast clojure.lang.PersistentVector
[v]
{:type :array-expression
:elements (map to-js-ast v)})
(defmethod to-js-ast clojure.lang.PersistentList
[v]
{:type :array-expression
:elements (map to-js-ast v)})
(defmethod to-js-ast clojure.lang.PersistentHashSet
[v]
{:type :array-expression
:elements (map to-js-ast v)})
(defmethod to-js-ast clojure.lang.PersistentArrayMap
[m]
{:type :object-expression
:properties (map
(fn [[k, v]]
{:type :object-property
:key (to-js-ast (name k))
:value (to-js-ast k)})
m)})
(defn- gen-arg-ast
[mod arg-names args]
(let [arg-pos (get-arg-positions mod)]
(->> args
; get a list of maps with :pos and :val
(map
(fn [[n arg]]
{:pos (get arg-pos n)
; arg looks like
; [:data {}] or
; [:ref [:named-ref-arg {:sub-result :username, :result authorized-login}]
:val (if (= (first arg) :data)
; if we have data, we assume it's a valid ast
(second arg)
; if we're using a reference, we look up the name
(get arg-names n))}))
; sort by :pos
(sort-by :pos)
; get a list of vals in order
(map :val)
; translate them into the obvious asts
(map to-js-ast)
(into []))))
(defn- gen-inv-ast
[{:keys [result-names arg-names mod mod-name inv]}]
(let [result-name (get result-names :*default*)
args (get inv :args)]
{:type :expression-statement
:expression {:type :assignment-expression
:left {:type :identifier
:identifier result-name}
:right {:type :call-expression
:callee {:type :identifier
:identifier mod-name}
:arguments (gen-arg-ast mod arg-names args)}}}))
(defn gen
"Generates a js ast for the given invocations"
[{:keys [invocations body]}]
; TODO: can also return :err
{:ast (concat
(map gen-inv-ast invocations)
body)})
| true | (ns ^{:author "PI:NAME:<NAME>END_PI"} ulvm.mod-combinators.js.sync.ast
"Synchronous Javascript Module Combinator AST Generation")
(defn- get-arg-positions
[mod]
; arg-mappings is a list of lists of args where each
; inner list represents a single overload
(let [arg-mappings (get-in mod [:ulvm.core/config
:ulvm.arg-mappings/positional])]
; turn [[:a :b] [:c :d]] into {:a 0, :b 1, :c 0, :d 1}
(apply
merge
(->> arg-mappings
(map #(map vector % (range)))
(map (partial into {}))))))
(defmulti to-js-ast type)
(defmethod to-js-ast clojure.lang.Symbol
[id]
{:type :identifier
:identifier (name id)})
(defmethod to-js-ast java.lang.String
[s]
{:type :string-literal
:value s})
(defmethod to-js-ast clojure.lang.Keyword
[k]
{:type :string-literal
:value (name k)})
(defmethod to-js-ast java.lang.Boolean
[b]
{:type :boolean-literal
:value b})
(defmethod to-js-ast java.lang.Long
[n]
{:type :numeric-literal
:value n})
(defmethod to-js-ast java.lang.Double
[n]
{:type :numeric-literal
:value n})
(defmethod to-js-ast clojure.lang.PersistentVector
[v]
{:type :array-expression
:elements (map to-js-ast v)})
(defmethod to-js-ast clojure.lang.PersistentList
[v]
{:type :array-expression
:elements (map to-js-ast v)})
(defmethod to-js-ast clojure.lang.PersistentHashSet
[v]
{:type :array-expression
:elements (map to-js-ast v)})
(defmethod to-js-ast clojure.lang.PersistentArrayMap
[m]
{:type :object-expression
:properties (map
(fn [[k, v]]
{:type :object-property
:key (to-js-ast (name k))
:value (to-js-ast k)})
m)})
(defn- gen-arg-ast
[mod arg-names args]
(let [arg-pos (get-arg-positions mod)]
(->> args
; get a list of maps with :pos and :val
(map
(fn [[n arg]]
{:pos (get arg-pos n)
; arg looks like
; [:data {}] or
; [:ref [:named-ref-arg {:sub-result :username, :result authorized-login}]
:val (if (= (first arg) :data)
; if we have data, we assume it's a valid ast
(second arg)
; if we're using a reference, we look up the name
(get arg-names n))}))
; sort by :pos
(sort-by :pos)
; get a list of vals in order
(map :val)
; translate them into the obvious asts
(map to-js-ast)
(into []))))
(defn- gen-inv-ast
[{:keys [result-names arg-names mod mod-name inv]}]
(let [result-name (get result-names :*default*)
args (get inv :args)]
{:type :expression-statement
:expression {:type :assignment-expression
:left {:type :identifier
:identifier result-name}
:right {:type :call-expression
:callee {:type :identifier
:identifier mod-name}
:arguments (gen-arg-ast mod arg-names args)}}}))
(defn gen
"Generates a js ast for the given invocations"
[{:keys [invocations body]}]
; TODO: can also return :err
{:ast (concat
(map gen-inv-ast invocations)
body)})
|
[
{
"context": "cksDB]))\n\n(defn- db-keys [key]\n {:meta-key (str \"meta/\" key)\n :blob-key (str \"blobs/\" key)})\n\n(deftype ",
"end": 259,
"score": 0.9615601301193237,
"start": 253,
"tag": "KEY",
"value": "meta/\""
},
{
"context": " {:meta-key (str \"meta/\" key)\n :blob-key (str \"blobs/\" key)})\n\n(deftype RocksDBCache\n [db]\n CacheBac",
"end": 291,
"score": 0.9752862453460693,
"start": 284,
"tag": "KEY",
"value": "blobs/\""
}
] | src/skyscraper/cache/rocksdb.clj | nathell/skyscraper-cache-rocksdb | 0 | (ns skyscraper.cache.rocksdb
(:require [skyscraper.cache :as cache]
[taoensso.nippy :as nippy])
(:import [skyscraper.cache CacheBackend]
[org.rocksdb CompressionType Options RocksDB]))
(defn- db-keys [key]
{:meta-key (str "meta/" key)
:blob-key (str "blobs/" key)})
(deftype RocksDBCache
[db]
CacheBackend
(save-blob [cache key blob metadata]
(let [{:keys [meta-key blob-key]} (db-keys key)]
(.put db (nippy/freeze meta-key) (nippy/freeze metadata))
(.put db (nippy/freeze blob-key) blob)))
(load-blob [cache key]
(let [{:keys [meta-key blob-key]} (db-keys key)
meta (.get db (nippy/freeze meta-key))
blob (.get db (nippy/freeze blob-key))]
(when (and meta blob)
{:meta (nippy/thaw meta)
:blob blob}))))
(defn rocks-db-cache [dir]
(let [opts (doto (Options.)
(.setCreateIfMissing true)
(.setCompressionType CompressionType/LZ4_COMPRESSION)
(.setBottommostCompressionType CompressionType/ZSTD_COMPRESSION))
db (RocksDB/open opts dir)]
(RocksDBCache. db)))
| 109449 | (ns skyscraper.cache.rocksdb
(:require [skyscraper.cache :as cache]
[taoensso.nippy :as nippy])
(:import [skyscraper.cache CacheBackend]
[org.rocksdb CompressionType Options RocksDB]))
(defn- db-keys [key]
{:meta-key (str "<KEY> key)
:blob-key (str "<KEY> key)})
(deftype RocksDBCache
[db]
CacheBackend
(save-blob [cache key blob metadata]
(let [{:keys [meta-key blob-key]} (db-keys key)]
(.put db (nippy/freeze meta-key) (nippy/freeze metadata))
(.put db (nippy/freeze blob-key) blob)))
(load-blob [cache key]
(let [{:keys [meta-key blob-key]} (db-keys key)
meta (.get db (nippy/freeze meta-key))
blob (.get db (nippy/freeze blob-key))]
(when (and meta blob)
{:meta (nippy/thaw meta)
:blob blob}))))
(defn rocks-db-cache [dir]
(let [opts (doto (Options.)
(.setCreateIfMissing true)
(.setCompressionType CompressionType/LZ4_COMPRESSION)
(.setBottommostCompressionType CompressionType/ZSTD_COMPRESSION))
db (RocksDB/open opts dir)]
(RocksDBCache. db)))
| true | (ns skyscraper.cache.rocksdb
(:require [skyscraper.cache :as cache]
[taoensso.nippy :as nippy])
(:import [skyscraper.cache CacheBackend]
[org.rocksdb CompressionType Options RocksDB]))
(defn- db-keys [key]
{:meta-key (str "PI:KEY:<KEY>END_PI key)
:blob-key (str "PI:KEY:<KEY>END_PI key)})
(deftype RocksDBCache
[db]
CacheBackend
(save-blob [cache key blob metadata]
(let [{:keys [meta-key blob-key]} (db-keys key)]
(.put db (nippy/freeze meta-key) (nippy/freeze metadata))
(.put db (nippy/freeze blob-key) blob)))
(load-blob [cache key]
(let [{:keys [meta-key blob-key]} (db-keys key)
meta (.get db (nippy/freeze meta-key))
blob (.get db (nippy/freeze blob-key))]
(when (and meta blob)
{:meta (nippy/thaw meta)
:blob blob}))))
(defn rocks-db-cache [dir]
(let [opts (doto (Options.)
(.setCreateIfMissing true)
(.setCompressionType CompressionType/LZ4_COMPRESSION)
(.setBottommostCompressionType CompressionType/ZSTD_COMPRESSION))
db (RocksDB/open opts dir)]
(RocksDBCache. db)))
|
[
{
"context": "her Mother Child)\n\n(def parents (pldb/db [father 'Vito 'Michael]\n [father 'Vito 'So",
"end": 218,
"score": 0.9996857643127441,
"start": 214,
"tag": "NAME",
"value": "Vito"
},
{
"context": "ther Child)\n\n(def parents (pldb/db [father 'Vito 'Michael]\n [father 'Vito 'Sonny]\n ",
"end": 227,
"score": 0.9997654557228088,
"start": 220,
"tag": "NAME",
"value": "Michael"
},
{
"context": "er 'Vito 'Michael]\n [father 'Vito 'Sonny]\n [father 'Vito 'Fred",
"end": 264,
"score": 0.9996885061264038,
"start": 260,
"tag": "NAME",
"value": "Vito"
},
{
"context": "to 'Michael]\n [father 'Vito 'Sonny]\n [father 'Vito 'Fredo]\n ",
"end": 271,
"score": 0.9996830821037292,
"start": 266,
"tag": "NAME",
"value": "Sonny"
},
{
"context": "ther 'Vito 'Sonny]\n [father 'Vito 'Fredo]\n [father 'Michael 'A",
"end": 308,
"score": 0.9997158050537109,
"start": 304,
"tag": "NAME",
"value": "Vito"
},
{
"context": "Vito 'Sonny]\n [father 'Vito 'Fredo]\n [father 'Michael 'Anthony]",
"end": 315,
"score": 0.9996700286865234,
"start": 310,
"tag": "NAME",
"value": "Fredo"
},
{
"context": "ther 'Vito 'Fredo]\n [father 'Michael 'Anthony]\n [father 'Michael ",
"end": 355,
"score": 0.9998295307159424,
"start": 348,
"tag": "NAME",
"value": "Michael"
},
{
"context": "o 'Fredo]\n [father 'Michael 'Anthony]\n [father 'Michael 'Mary]\n ",
"end": 364,
"score": 0.9997159838676453,
"start": 357,
"tag": "NAME",
"value": "Anthony"
},
{
"context": "'Michael 'Anthony]\n [father 'Michael 'Mary]\n [father 'Sonny 'Vice",
"end": 404,
"score": 0.9998359680175781,
"start": 397,
"tag": "NAME",
"value": "Michael"
},
{
"context": "'Anthony]\n [father 'Michael 'Mary]\n [father 'Sonny 'Vicent]\n ",
"end": 410,
"score": 0.9997051954269409,
"start": 406,
"tag": "NAME",
"value": "Mary"
},
{
"context": "er 'Michael 'Mary]\n [father 'Sonny 'Vicent]\n [father 'Sonny 'Fr",
"end": 448,
"score": 0.9997540712356567,
"start": 443,
"tag": "NAME",
"value": "Sonny"
},
{
"context": "hael 'Mary]\n [father 'Sonny 'Vicent]\n [father 'Sonny 'Francesca]",
"end": 456,
"score": 0.9997496604919434,
"start": 450,
"tag": "NAME",
"value": "Vicent"
},
{
"context": "er 'Sonny 'Vicent]\n [father 'Sonny 'Francesca]\n [father 'Sonny ",
"end": 494,
"score": 0.9997501373291016,
"start": 489,
"tag": "NAME",
"value": "Sonny"
},
{
"context": "ny 'Vicent]\n [father 'Sonny 'Francesca]\n [father 'Sonny 'Kathryn]\n ",
"end": 505,
"score": 0.9997655749320984,
"start": 496,
"tag": "NAME",
"value": "Francesca"
},
{
"context": "'Sonny 'Francesca]\n [father 'Sonny 'Kathryn]\n [father 'Sonny 'F",
"end": 543,
"score": 0.9996311664581299,
"start": 538,
"tag": "NAME",
"value": "Sonny"
},
{
"context": "'Francesca]\n [father 'Sonny 'Kathryn]\n [father 'Sonny 'Frank]\n ",
"end": 552,
"score": 0.9997497797012329,
"start": 545,
"tag": "NAME",
"value": "Kathryn"
},
{
"context": "r 'Sonny 'Kathryn]\n [father 'Sonny 'Frank]\n [father 'Sonny 'San",
"end": 590,
"score": 0.9996959567070007,
"start": 585,
"tag": "NAME",
"value": "Sonny"
},
{
"context": "y 'Kathryn]\n [father 'Sonny 'Frank]\n [father 'Sonny 'Santino]\n\n",
"end": 597,
"score": 0.9997619390487671,
"start": 592,
"tag": "NAME",
"value": "Frank"
},
{
"context": "her 'Sonny 'Frank]\n [father 'Sonny 'Santino]\n\n [mother 'Carmela",
"end": 635,
"score": 0.9996490478515625,
"start": 630,
"tag": "NAME",
"value": "Sonny"
},
{
"context": "nny 'Frank]\n [father 'Sonny 'Santino]\n\n [mother 'Carmela 'Michael",
"end": 644,
"score": 0.9997098445892334,
"start": 637,
"tag": "NAME",
"value": "Santino"
},
{
"context": " 'Sonny 'Santino]\n\n [mother 'Carmela 'Michael]\n [mother 'Carmela ",
"end": 685,
"score": 0.9997854828834534,
"start": 678,
"tag": "NAME",
"value": "Carmela"
},
{
"context": "Santino]\n\n [mother 'Carmela 'Michael]\n [mother 'Carmela 'Sonny]\n ",
"end": 694,
"score": 0.9993576407432556,
"start": 687,
"tag": "NAME",
"value": "Michael"
},
{
"context": "'Carmela 'Michael]\n [mother 'Carmela 'Sonny]\n [mother 'Carmela 'F",
"end": 734,
"score": 0.9997586607933044,
"start": 727,
"tag": "NAME",
"value": "Carmela"
},
{
"context": "'Michael]\n [mother 'Carmela 'Sonny]\n [mother 'Carmela 'Fredo]\n ",
"end": 741,
"score": 0.9991142153739929,
"start": 736,
"tag": "NAME",
"value": "Sonny"
},
{
"context": "r 'Carmela 'Sonny]\n [mother 'Carmela 'Fredo]\n [mother 'Kay 'Mary]",
"end": 781,
"score": 0.999711811542511,
"start": 774,
"tag": "NAME",
"value": "Carmela"
},
{
"context": "a 'Sonny]\n [mother 'Carmela 'Fredo]\n [mother 'Kay 'Mary]\n ",
"end": 788,
"score": 0.998015284538269,
"start": 783,
"tag": "NAME",
"value": "Fredo"
},
{
"context": "r 'Carmela 'Fredo]\n [mother 'Kay 'Mary]\n [mother 'Kay 'Anthon",
"end": 824,
"score": 0.9996836185455322,
"start": 821,
"tag": "NAME",
"value": "Kay"
},
{
"context": "rmela 'Fredo]\n [mother 'Kay 'Mary]\n [mother 'Kay 'Anthony]\n ",
"end": 830,
"score": 0.9995660781860352,
"start": 826,
"tag": "NAME",
"value": "Mary"
},
{
"context": "mother 'Kay 'Mary]\n [mother 'Kay 'Anthony]\n [mother 'Sandra '",
"end": 866,
"score": 0.9996551275253296,
"start": 863,
"tag": "NAME",
"value": "Kay"
},
{
"context": "r 'Kay 'Mary]\n [mother 'Kay 'Anthony]\n [mother 'Sandra 'Francesca",
"end": 875,
"score": 0.9996139407157898,
"start": 868,
"tag": "NAME",
"value": "Anthony"
},
{
"context": "her 'Kay 'Anthony]\n [mother 'Sandra 'Francesca]\n [mother 'Sandra",
"end": 914,
"score": 0.9997159242630005,
"start": 908,
"tag": "NAME",
"value": "Sandra"
},
{
"context": " 'Anthony]\n [mother 'Sandra 'Francesca]\n [mother 'Sandra 'Kathryn]\n",
"end": 925,
"score": 0.9996933937072754,
"start": 916,
"tag": "NAME",
"value": "Francesca"
},
{
"context": "Sandra 'Francesca]\n [mother 'Sandra 'Kathryn]\n [mother 'Sandra '",
"end": 964,
"score": 0.9996366500854492,
"start": 958,
"tag": "NAME",
"value": "Sandra"
},
{
"context": "Francesca]\n [mother 'Sandra 'Kathryn]\n [mother 'Sandra 'Frank]\n ",
"end": 973,
"score": 0.9996605515480042,
"start": 966,
"tag": "NAME",
"value": "Kathryn"
},
{
"context": " 'Sandra 'Kathryn]\n [mother 'Sandra 'Frank]\n [mother 'Sandra 'Sa",
"end": 1012,
"score": 0.9996082782745361,
"start": 1006,
"tag": "NAME",
"value": "Sandra"
},
{
"context": " 'Kathryn]\n [mother 'Sandra 'Frank]\n [mother 'Sandra 'Santino])",
"end": 1019,
"score": 0.9997286796569824,
"start": 1014,
"tag": "NAME",
"value": "Frank"
},
{
"context": "er 'Sandra 'Frank]\n [mother 'Sandra 'Santino]))\n\n;; Qui sont les enfants de Vito ?\n\n(",
"end": 1058,
"score": 0.9995918273925781,
"start": 1052,
"tag": "NAME",
"value": "Sandra"
},
{
"context": "ra 'Frank]\n [mother 'Sandra 'Santino]))\n\n;; Qui sont les enfants de Vito ?\n\n(pldb/with",
"end": 1067,
"score": 0.9995658993721008,
"start": 1060,
"tag": "NAME",
"value": "Santino"
},
{
"context": "er 'Sandra 'Santino]))\n\n;; Qui sont les enfants de Vito ?\n\n(pldb/with-db parents\n (l/run* [q]\n (fathe",
"end": 1103,
"score": 0.9933921098709106,
"start": 1099,
"tag": "NAME",
"value": "Vito"
},
{
"context": "\n(pldb/with-db parents\n (l/run* [q]\n (father 'Vito q)))\n\n;; Qui est la mère de Frank ?\n\n(pldb/with-d",
"end": 1160,
"score": 0.9953198432922363,
"start": 1156,
"tag": "NAME",
"value": "Vito"
},
{
"context": " [q]\n (father 'Vito q)))\n\n;; Qui est la mère de Frank ?\n\n(pldb/with-db parents\n (l/run* [q]\n (mothe",
"end": 1194,
"score": 0.9996631145477295,
"start": 1189,
"tag": "NAME",
"value": "Frank"
},
{
"context": "pldb/with-db parents\n (l/run* [q]\n (mother q 'Frank)))\n\n;; Définir une relation parent :\n;; Un parent",
"end": 1254,
"score": 0.9993982911109924,
"start": 1249,
"tag": "NAME",
"value": "Frank"
},
{
"context": " [(mother p child)]))\n\n;; Qui sont les parents de Michael ?\n\n(pldb/with-db parents\n (l/run* [q]\n (p",
"end": 1446,
"score": 0.9994994401931763,
"start": 1439,
"tag": "NAME",
"value": "Michael"
},
{
"context": "with-db parents\n (l/run* [q]\n (parento q 'Michael)))\n\n;; Définir une relation grand-parent :\n;; Un ",
"end": 1513,
"score": 0.9992894530296326,
"start": 1506,
"tag": "NAME",
"value": "Michael"
}
] | src/core_logic_primer/relations_solutions.clj | DjebbZ/core-logic-primer | 1 | (ns relations-solutions
(:require [clojure.core.logic :as l])
(:require [clojure.core.logic.pldb :as pldb]))
(pldb/db-rel father Father Child)
(pldb/db-rel mother Mother Child)
(def parents (pldb/db [father 'Vito 'Michael]
[father 'Vito 'Sonny]
[father 'Vito 'Fredo]
[father 'Michael 'Anthony]
[father 'Michael 'Mary]
[father 'Sonny 'Vicent]
[father 'Sonny 'Francesca]
[father 'Sonny 'Kathryn]
[father 'Sonny 'Frank]
[father 'Sonny 'Santino]
[mother 'Carmela 'Michael]
[mother 'Carmela 'Sonny]
[mother 'Carmela 'Fredo]
[mother 'Kay 'Mary]
[mother 'Kay 'Anthony]
[mother 'Sandra 'Francesca]
[mother 'Sandra 'Kathryn]
[mother 'Sandra 'Frank]
[mother 'Sandra 'Santino]))
;; Qui sont les enfants de Vito ?
(pldb/with-db parents
(l/run* [q]
(father 'Vito q)))
;; Qui est la mère de Frank ?
(pldb/with-db parents
(l/run* [q]
(mother q 'Frank)))
;; Définir une relation parent :
;; Un parent est un père OU une mère
(defn parento [p child]
(l/conde
[(father p child)]
[(mother p child)]))
;; Qui sont les parents de Michael ?
(pldb/with-db parents
(l/run* [q]
(parento q 'Michael)))
;; Définir une relation grand-parent :
;; Un grand-parent est le parent du parent d'un enfant !
(defn grand-parento [gparent child]
(l/fresh [q]
(parento gparent q)
(parento q child)))
;; Qui sont les petits enfants de Vito ?
(pldb/with-db parents
(l/run* [q]
(grand-parento 'Vito q)))
;; Trouvez les couples distincts de parents
(distinct (pldb/with-db parents
(l/run* [q]
(l/fresh [p m c]
(l/== q [p m])
(mother m c)
(father p c)))))
| 15650 | (ns relations-solutions
(:require [clojure.core.logic :as l])
(:require [clojure.core.logic.pldb :as pldb]))
(pldb/db-rel father Father Child)
(pldb/db-rel mother Mother Child)
(def parents (pldb/db [father '<NAME> '<NAME>]
[father '<NAME> '<NAME>]
[father '<NAME> '<NAME>]
[father '<NAME> '<NAME>]
[father '<NAME> '<NAME>]
[father '<NAME> '<NAME>]
[father '<NAME> '<NAME>]
[father '<NAME> '<NAME>]
[father '<NAME> '<NAME>]
[father '<NAME> '<NAME>]
[mother '<NAME> '<NAME>]
[mother '<NAME> '<NAME>]
[mother '<NAME> '<NAME>]
[mother '<NAME> '<NAME>]
[mother '<NAME> '<NAME>]
[mother '<NAME> '<NAME>]
[mother '<NAME> '<NAME>]
[mother '<NAME> '<NAME>]
[mother '<NAME> '<NAME>]))
;; Qui sont les enfants de <NAME> ?
(pldb/with-db parents
(l/run* [q]
(father '<NAME> q)))
;; Qui est la mère de <NAME> ?
(pldb/with-db parents
(l/run* [q]
(mother q '<NAME>)))
;; Définir une relation parent :
;; Un parent est un père OU une mère
(defn parento [p child]
(l/conde
[(father p child)]
[(mother p child)]))
;; Qui sont les parents de <NAME> ?
(pldb/with-db parents
(l/run* [q]
(parento q '<NAME>)))
;; Définir une relation grand-parent :
;; Un grand-parent est le parent du parent d'un enfant !
(defn grand-parento [gparent child]
(l/fresh [q]
(parento gparent q)
(parento q child)))
;; Qui sont les petits enfants de Vito ?
(pldb/with-db parents
(l/run* [q]
(grand-parento 'Vito q)))
;; Trouvez les couples distincts de parents
(distinct (pldb/with-db parents
(l/run* [q]
(l/fresh [p m c]
(l/== q [p m])
(mother m c)
(father p c)))))
| true | (ns relations-solutions
(:require [clojure.core.logic :as l])
(:require [clojure.core.logic.pldb :as pldb]))
(pldb/db-rel father Father Child)
(pldb/db-rel mother Mother Child)
(def parents (pldb/db [father 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI]
[father 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI]
[father 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI]
[father 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI]
[father 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI]
[father 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI]
[father 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI]
[father 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI]
[father 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI]
[father 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI]
[mother 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI]
[mother 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI]
[mother 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI]
[mother 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI]
[mother 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI]
[mother 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI]
[mother 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI]
[mother 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI]
[mother 'PI:NAME:<NAME>END_PI 'PI:NAME:<NAME>END_PI]))
;; Qui sont les enfants de PI:NAME:<NAME>END_PI ?
(pldb/with-db parents
(l/run* [q]
(father 'PI:NAME:<NAME>END_PI q)))
;; Qui est la mère de PI:NAME:<NAME>END_PI ?
(pldb/with-db parents
(l/run* [q]
(mother q 'PI:NAME:<NAME>END_PI)))
;; Définir une relation parent :
;; Un parent est un père OU une mère
(defn parento [p child]
(l/conde
[(father p child)]
[(mother p child)]))
;; Qui sont les parents de PI:NAME:<NAME>END_PI ?
(pldb/with-db parents
(l/run* [q]
(parento q 'PI:NAME:<NAME>END_PI)))
;; Définir une relation grand-parent :
;; Un grand-parent est le parent du parent d'un enfant !
(defn grand-parento [gparent child]
(l/fresh [q]
(parento gparent q)
(parento q child)))
;; Qui sont les petits enfants de Vito ?
(pldb/with-db parents
(l/run* [q]
(grand-parento 'Vito q)))
;; Trouvez les couples distincts de parents
(distinct (pldb/with-db parents
(l/run* [q]
(l/fresh [p m c]
(l/== q [p m])
(mother m c)
(father p c)))))
|
[
{
"context": "/certs/localhost.pem\")\n(def default-ssl-key \"test-resources/puppetserver/ssl/private_keys/localhost.pem\")\n\n(pls/defn-validated get-ssl\n \"Executes a mutu",
"end": 9328,
"score": 0.8741447329521179,
"start": 9275,
"tag": "KEY",
"value": "resources/puppetserver/ssl/private_keys/localhost.pem"
}
] | test/puppetlabs/puppetdb/testutils/services.clj | Zak-Kent/puppetdb | 0 | (ns puppetlabs.puppetdb.testutils.services
(:refer-clojure :exclude [get])
(:require [clj-time.core :as t]
[clj-time.coerce :as time-coerce]
[puppetlabs.kitchensink.core :as kitchensink]
[puppetlabs.puppetdb.testutils :as testutils]
[puppetlabs.puppetdb.testutils.db :refer [*db* with-test-db]]
[puppetlabs.puppetdb.testutils.log :refer [notable-pdb-event?]]
[puppetlabs.trapperkeeper.testutils.logging :refer [with-log-suppressed-unless-notable]]
[puppetlabs.puppetdb.scf.storage-utils :as sutils]
[metrics.counters :refer [clear!]]
[clojure.walk :as walk]
[puppetlabs.trapperkeeper.app :as tk-app :refer [get-service]]
[puppetlabs.trapperkeeper.testutils.bootstrap :as tkbs]
[puppetlabs.trapperkeeper.services.webserver.jetty9-service :refer [jetty9-service]]
[puppetlabs.trapperkeeper.services.webrouting.webrouting-service :refer [webrouting-service]]
[puppetlabs.trapperkeeper.services.status.status-service :refer [status-service]]
[puppetlabs.trapperkeeper.services.scheduler.scheduler-service :refer [scheduler-service]]
[puppetlabs.trapperkeeper.services.metrics.metrics-service :refer [metrics-webservice]]
[puppetlabs.puppetdb.client :as pdb-client]
[puppetlabs.puppetdb.cli.services :refer [puppetdb-service]]
[puppetlabs.puppetdb.admin :as admin]
[puppetlabs.puppetdb.command :refer [command-service] :as dispatch]
[puppetlabs.puppetdb.http :refer [json-utf8-ctype?]]
[puppetlabs.puppetdb.utils :as utils]
[puppetlabs.puppetdb.config :as conf]
[puppetlabs.puppetdb.cheshire :as json]
[puppetlabs.puppetdb.utils :refer [base-url->str base-url->str-with-prefix]]
[clojure.string :as str]
[me.raynes.fs :as fs]
[slingshot.slingshot :refer [throw+]]
[clojure.tools.logging :as log]
[puppetlabs.puppetdb.dashboard :refer [dashboard-redirect-service]]
[puppetlabs.puppetdb.pdb-routing :refer [pdb-routing-service
maint-mode-service]]
[puppetlabs.puppetdb.config :refer [config-service]]
[puppetlabs.http.client.sync :as http]
[puppetlabs.puppetdb.schema :as pls]
[ring.util.response :as rr]))
;; See utils.clj for more information about base-urls.
(def ^:dynamic *base-url* nil) ; Will not have a :version.
(defn create-temp-config
"Returns a config that refers to a temporary vardir."
[]
{:nrepl {}
:global {:vardir (testutils/temp-dir)}
:jetty {:port 0}
:command-processing {}})
(defn open-port-num
"Returns a currently open port number"
[]
(with-open [s (java.net.ServerSocket. 0)]
(.getLocalPort s)))
(defn assoc-open-port
"Updates `config` to include a (currently open) port number"
[config]
(let [port-key (if (-> config :jetty :ssl-port)
:ssl-port
:port)]
(assoc-in config [:jetty port-key] (open-port-num))))
(def ^:dynamic *server*)
(def default-services
[#'jetty9-service
#'webrouting-service
#'puppetdb-service
#'command-service
#'status-service
#'scheduler-service
#'metrics-webservice
#'dashboard-redirect-service
#'pdb-routing-service
#'maint-mode-service
#'config-service])
(defn clear-counters!
[metrics]
(walk/postwalk
(fn [x] (if (= (type x)
com.codahale.metrics.Counter)
(clear! x)
x))
metrics))
(defn jdbc-configs->pdb-if-needed [config]
(-> config
(update :database #(dissoc % :classname :subprotocol))
(update :read-database #(dissoc % :classname :subprotocol))))
(defn run-test-puppetdb [config services bind-attempts]
(when (zero? bind-attempts)
(throw (RuntimeException. "Repeated attempts to bind port failed, giving up")))
(let [config (-> config
jdbc-configs->pdb-if-needed
conf/adjust-and-validate-tk-config
assoc-open-port)
port (or (get-in config [:jetty :port])
(get-in config [:jetty :ssl-port]))
is-ssl (boolean (get-in config [:jetty :ssl-port]))
base-url {:protocol (if is-ssl "https" "http")
:host "localhost"
:port port
:prefix "/pdb/query"
:version :v4}]
(try
(swap! dispatch/metrics clear-counters!)
{:app (tkbs/bootstrap-services-with-config (map var-get services) config)
:base-url base-url}
(catch java.net.BindException e
(log/errorf e "Error occured when Jetty tried to bind to port %s, attempt #%s"
port bind-attempts)
(run-test-puppetdb config services (dec bind-attempts))))))
(defn call-with-puppetdb-instance
"Stands up a puppetdb instance with the specified config, calls f,
and then tears the instance down, binding *server* to the instance
and *base-url* to the instance's URL during the execution of f.
Starts any specified services in addition to the core PuppetDB
services, and tries to bind to an HTTP port up to bind-attempts
times (default 10) before giving up. If a config is not specified,
one will be generated by create-temp-config, using a database
managed by with-test-db."
([f]
(with-test-db
(call-with-puppetdb-instance
(assoc (create-temp-config) :database *db*)
f)))
([config f] (call-with-puppetdb-instance config default-services f))
([config services f]
(call-with-puppetdb-instance config services 10 f))
([config services bind-attempts f]
(let [{:keys [app base-url]} (run-test-puppetdb config services bind-attempts)]
(try
(binding [*server* app
*base-url* base-url]
(f))
(finally
(tk-app/stop app))))))
(defn create-url-str [base-url url-suffix]
(str (utils/base-url->str base-url)
(when url-suffix
url-suffix)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Functions that return URLs and strings for the top level services
;; in PDB
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn pdb-query-url
([]
(pdb-query-url *base-url*))
([base-url]
(assoc base-url :prefix "/pdb/query" :version :v4)))
(defn query-url-str
([url-suffix]
(query-url-str *base-url* url-suffix))
([base-url url-suffix]
(create-url-str (pdb-query-url base-url) url-suffix)))
(defn pdb-cmd-url
([]
(pdb-cmd-url *base-url*))
([base-url]
(assoc base-url :prefix "/pdb/cmd" :version :v1)))
(defn cmd-url-str
([url-suffix]
(cmd-url-str *base-url* url-suffix))
([base-url url-suffix]
(create-url-str (pdb-cmd-url base-url) url-suffix)))
(defn pdb-admin-url
([]
(pdb-admin-url *base-url*))
([base-url]
(assoc base-url :prefix "/pdb/admin" :version :v1)))
(defn admin-url-str
([url-suffix]
(admin-url-str *base-url* url-suffix))
([base-url url-suffix]
(create-url-str (pdb-admin-url base-url) url-suffix)))
(defn pdb-metrics-url
([]
(pdb-metrics-url *base-url*))
([base-url]
(assoc base-url :prefix "/metrics" :version :v1)))
(defn metrics-url-str
([url-suffix]
(metrics-url-str *base-url* url-suffix))
([base-url url-suffix]
(create-url-str (pdb-metrics-url base-url) url-suffix)))
(defn pdb-meta-url
([]
(pdb-meta-url *base-url*))
([base-url]
(assoc base-url :prefix "/pdb/meta" :version :v1)))
(defn meta-url-str
([url-suffix]
(meta-url-str *base-url* url-suffix))
([base-url url-suffix]
(create-url-str (pdb-meta-url base-url) url-suffix)))
(defn root-url-str
([]
(root-url-str *base-url*))
([base-url]
(-> base-url
(assoc :prefix "/")
utils/base-url->str-with-prefix)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Basic HTTP functions for interacting with PuppetDB services, the
;; url-str arguments below will likely come from the above functions
;; relating to the various top level services
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(pls/defn-validated get-unparsed
"Executes a GET HTTP request against `url-str`. `opts` are merged
into the request map. The response is unparsed but returned as a
string."
[url-str :- String
& [opts]]
(http/get url-str
(merge
{:as :text
:headers {"Content-Type" "application/json"}}
opts)))
(pls/defn-validated get
"Executes a GET HTTP request against `url-str`. `opts` are merged
into the request map. JSON responses are automatically parsed before
returning. Error responses are returned (i.e. 404) and not thrown."
[url-str :- String
& [opts]]
(let [resp (get-unparsed url-str opts)
ctype (rr/get-header resp "content-type")]
(if (some-> ctype json-utf8-ctype?)
(update resp :body #(json/parse-string % true))
resp)))
(def default-ca-cert "test-resources/puppetserver/ssl/certs/ca.pem")
(def default-cert "test-resources/puppetserver/ssl/certs/localhost.pem")
(def default-ssl-key "test-resources/puppetserver/ssl/private_keys/localhost.pem")
(pls/defn-validated get-ssl
"Executes a mutually authenticated GET HTTPS request against
`url-str` using the above `get` function."
[url-str & [opts]]
(get url-str
(merge {:ssl-ca-cert default-ca-cert
:ssl-cert default-cert
:ssl-key default-ssl-key}
opts)))
(pls/defn-validated get-or-throw
"Same as `get` except will throw if an error status is returned."
[url-str :- String
& [opts]]
(let [resp (get url-str opts)]
(if (>= (:status resp) 400)
(throw+ {:url url-str
:response resp
:status (:status resp)}
(format "Failed request to '%s' with status '%s'" url-str (:status resp)))
resp)))
(pls/defn-validated post
"Executes a POST HTTP request against `url-str`. `body` is a clojure
data structure that is converted to a JSON string before POSTing."
[url-str :- String
body
& [opts]]
(http/post url-str
(merge
{:body (json/generate-string body)
:headers {"Content-Type" "application/json"}}
opts)))
(pls/defn-validated post-ssl
"Executes a mutually authenticated POST HTTP request against
`url-str`. Uses the above `post` function"
[url-str :- String
body
& [opts]]
(post url-str
body
{:ssl-ca-cert default-ca-cert
:ssl-cert default-cert
:ssl-key default-ssl-key}))
(defn certname-query
"Returns a function that will query the given endpoint (`suffix`)
for the provided `certname`"
[base-url suffix certname]
(-> (query-url-str base-url suffix)
(get-or-throw {:query-params {"query" (json/generate-string [:= :certname certname])}})
:body))
(defn get-reports
([certname]
(get-reports *base-url* certname))
([base-url certname]
(certname-query base-url "/reports" certname)))
(defn get-factsets
([certname]
(get-factsets *base-url* certname))
([base-url certname]
(certname-query base-url "/factsets" certname)))
(defn get-catalogs
([certname]
(get-catalogs *base-url* certname))
([base-url certname]
(certname-query base-url "/catalogs" certname)))
(defn get-summary-stats []
(-> (admin-url-str "/summary-stats")
get-or-throw
:body))
(defmacro with-puppetdb-instance
"Convenience macro to launch a puppetdb instance"
[& body]
`(with-redefs [sutils/db-metadata (delay (sutils/db-metadata-fn))]
(call-with-puppetdb-instance
(fn []
~@body))))
(def ^:dynamic *notable-log-event?* notable-pdb-event?)
(defn call-with-single-quiet-pdb-instance
"Calls the call-with-puppetdb-instance with args after suppressing
all log events. If there's an error or worse, prints the log to
*err*. Should not be nested, nor nested with calls to
with-log-suppressed-unless-notable."
[& args]
(with-log-suppressed-unless-notable *notable-log-event?*
(apply call-with-puppetdb-instance args)))
(defmacro with-single-quiet-pdb-instance
"Convenience macro for call-with-single-quiet-pdb-instance."
[& body]
`(call-with-single-quiet-pdb-instance
(fn [] ~@body)))
(defmacro with-pdb-with-no-gc [& body]
`(with-test-db
(call-with-single-quiet-pdb-instance
(-> (svc-utils/create-temp-config)
(assoc :database *db*)
(assoc-in [:database :gc-interval] 0))
(fn []
~@body))))
(def max-attempts 50)
(defn url-encode [s]
(java.net.URLEncoder/encode s "UTF-8"))
(defn discard-count
"Returns the number of messages discarded from the command queue by
the current PuppetDB instance."
[]
(-> (pdb-metrics-url "/mbeans/puppetlabs.puppetdb.command:type=global,name=discarded")
get-or-throw
(get-in [:body :Count])))
(defn sync-command-post
"Syncronously post a command to PDB by blocking until the message is consumed
off the queue."
[base-url certname cmd version payload]
(let [timeout-seconds 20]
(let [response (pdb-client/submit-command-via-http!
base-url certname cmd version payload timeout-seconds)]
(if (>= (:status response) 400)
(throw (ex-info "Command processing failed" {:response response}))
response))))
(defn wait-for-server-processing
"Returns a truthy value indicating whether the wait was
successful (i.e. didn't time out). The current timeout granularity
may be as bad as 10ms."
[server timeout-ms]
(let [now-ms #(time-coerce/to-long (t/now))
deadline (+ (now-ms) timeout-ms)]
(loop []
(cond
(> (now-ms) deadline)
false
(let [srv (get-service server :PuppetDBCommandDispatcher)
stats (dispatch/stats srv)]
(= (:executed-commands stats) (:received-commands stats)))
true
:else ;; In theory, polling might be avoided via watcher.
(do
(Thread/sleep 10)
(recur))))))
| 4942 | (ns puppetlabs.puppetdb.testutils.services
(:refer-clojure :exclude [get])
(:require [clj-time.core :as t]
[clj-time.coerce :as time-coerce]
[puppetlabs.kitchensink.core :as kitchensink]
[puppetlabs.puppetdb.testutils :as testutils]
[puppetlabs.puppetdb.testutils.db :refer [*db* with-test-db]]
[puppetlabs.puppetdb.testutils.log :refer [notable-pdb-event?]]
[puppetlabs.trapperkeeper.testutils.logging :refer [with-log-suppressed-unless-notable]]
[puppetlabs.puppetdb.scf.storage-utils :as sutils]
[metrics.counters :refer [clear!]]
[clojure.walk :as walk]
[puppetlabs.trapperkeeper.app :as tk-app :refer [get-service]]
[puppetlabs.trapperkeeper.testutils.bootstrap :as tkbs]
[puppetlabs.trapperkeeper.services.webserver.jetty9-service :refer [jetty9-service]]
[puppetlabs.trapperkeeper.services.webrouting.webrouting-service :refer [webrouting-service]]
[puppetlabs.trapperkeeper.services.status.status-service :refer [status-service]]
[puppetlabs.trapperkeeper.services.scheduler.scheduler-service :refer [scheduler-service]]
[puppetlabs.trapperkeeper.services.metrics.metrics-service :refer [metrics-webservice]]
[puppetlabs.puppetdb.client :as pdb-client]
[puppetlabs.puppetdb.cli.services :refer [puppetdb-service]]
[puppetlabs.puppetdb.admin :as admin]
[puppetlabs.puppetdb.command :refer [command-service] :as dispatch]
[puppetlabs.puppetdb.http :refer [json-utf8-ctype?]]
[puppetlabs.puppetdb.utils :as utils]
[puppetlabs.puppetdb.config :as conf]
[puppetlabs.puppetdb.cheshire :as json]
[puppetlabs.puppetdb.utils :refer [base-url->str base-url->str-with-prefix]]
[clojure.string :as str]
[me.raynes.fs :as fs]
[slingshot.slingshot :refer [throw+]]
[clojure.tools.logging :as log]
[puppetlabs.puppetdb.dashboard :refer [dashboard-redirect-service]]
[puppetlabs.puppetdb.pdb-routing :refer [pdb-routing-service
maint-mode-service]]
[puppetlabs.puppetdb.config :refer [config-service]]
[puppetlabs.http.client.sync :as http]
[puppetlabs.puppetdb.schema :as pls]
[ring.util.response :as rr]))
;; See utils.clj for more information about base-urls.
(def ^:dynamic *base-url* nil) ; Will not have a :version.
(defn create-temp-config
"Returns a config that refers to a temporary vardir."
[]
{:nrepl {}
:global {:vardir (testutils/temp-dir)}
:jetty {:port 0}
:command-processing {}})
(defn open-port-num
"Returns a currently open port number"
[]
(with-open [s (java.net.ServerSocket. 0)]
(.getLocalPort s)))
(defn assoc-open-port
"Updates `config` to include a (currently open) port number"
[config]
(let [port-key (if (-> config :jetty :ssl-port)
:ssl-port
:port)]
(assoc-in config [:jetty port-key] (open-port-num))))
(def ^:dynamic *server*)
(def default-services
[#'jetty9-service
#'webrouting-service
#'puppetdb-service
#'command-service
#'status-service
#'scheduler-service
#'metrics-webservice
#'dashboard-redirect-service
#'pdb-routing-service
#'maint-mode-service
#'config-service])
(defn clear-counters!
[metrics]
(walk/postwalk
(fn [x] (if (= (type x)
com.codahale.metrics.Counter)
(clear! x)
x))
metrics))
(defn jdbc-configs->pdb-if-needed [config]
(-> config
(update :database #(dissoc % :classname :subprotocol))
(update :read-database #(dissoc % :classname :subprotocol))))
(defn run-test-puppetdb [config services bind-attempts]
(when (zero? bind-attempts)
(throw (RuntimeException. "Repeated attempts to bind port failed, giving up")))
(let [config (-> config
jdbc-configs->pdb-if-needed
conf/adjust-and-validate-tk-config
assoc-open-port)
port (or (get-in config [:jetty :port])
(get-in config [:jetty :ssl-port]))
is-ssl (boolean (get-in config [:jetty :ssl-port]))
base-url {:protocol (if is-ssl "https" "http")
:host "localhost"
:port port
:prefix "/pdb/query"
:version :v4}]
(try
(swap! dispatch/metrics clear-counters!)
{:app (tkbs/bootstrap-services-with-config (map var-get services) config)
:base-url base-url}
(catch java.net.BindException e
(log/errorf e "Error occured when Jetty tried to bind to port %s, attempt #%s"
port bind-attempts)
(run-test-puppetdb config services (dec bind-attempts))))))
(defn call-with-puppetdb-instance
"Stands up a puppetdb instance with the specified config, calls f,
and then tears the instance down, binding *server* to the instance
and *base-url* to the instance's URL during the execution of f.
Starts any specified services in addition to the core PuppetDB
services, and tries to bind to an HTTP port up to bind-attempts
times (default 10) before giving up. If a config is not specified,
one will be generated by create-temp-config, using a database
managed by with-test-db."
([f]
(with-test-db
(call-with-puppetdb-instance
(assoc (create-temp-config) :database *db*)
f)))
([config f] (call-with-puppetdb-instance config default-services f))
([config services f]
(call-with-puppetdb-instance config services 10 f))
([config services bind-attempts f]
(let [{:keys [app base-url]} (run-test-puppetdb config services bind-attempts)]
(try
(binding [*server* app
*base-url* base-url]
(f))
(finally
(tk-app/stop app))))))
(defn create-url-str [base-url url-suffix]
(str (utils/base-url->str base-url)
(when url-suffix
url-suffix)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Functions that return URLs and strings for the top level services
;; in PDB
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn pdb-query-url
([]
(pdb-query-url *base-url*))
([base-url]
(assoc base-url :prefix "/pdb/query" :version :v4)))
(defn query-url-str
([url-suffix]
(query-url-str *base-url* url-suffix))
([base-url url-suffix]
(create-url-str (pdb-query-url base-url) url-suffix)))
(defn pdb-cmd-url
([]
(pdb-cmd-url *base-url*))
([base-url]
(assoc base-url :prefix "/pdb/cmd" :version :v1)))
(defn cmd-url-str
([url-suffix]
(cmd-url-str *base-url* url-suffix))
([base-url url-suffix]
(create-url-str (pdb-cmd-url base-url) url-suffix)))
(defn pdb-admin-url
([]
(pdb-admin-url *base-url*))
([base-url]
(assoc base-url :prefix "/pdb/admin" :version :v1)))
(defn admin-url-str
([url-suffix]
(admin-url-str *base-url* url-suffix))
([base-url url-suffix]
(create-url-str (pdb-admin-url base-url) url-suffix)))
(defn pdb-metrics-url
([]
(pdb-metrics-url *base-url*))
([base-url]
(assoc base-url :prefix "/metrics" :version :v1)))
(defn metrics-url-str
([url-suffix]
(metrics-url-str *base-url* url-suffix))
([base-url url-suffix]
(create-url-str (pdb-metrics-url base-url) url-suffix)))
(defn pdb-meta-url
([]
(pdb-meta-url *base-url*))
([base-url]
(assoc base-url :prefix "/pdb/meta" :version :v1)))
(defn meta-url-str
([url-suffix]
(meta-url-str *base-url* url-suffix))
([base-url url-suffix]
(create-url-str (pdb-meta-url base-url) url-suffix)))
(defn root-url-str
([]
(root-url-str *base-url*))
([base-url]
(-> base-url
(assoc :prefix "/")
utils/base-url->str-with-prefix)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Basic HTTP functions for interacting with PuppetDB services, the
;; url-str arguments below will likely come from the above functions
;; relating to the various top level services
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(pls/defn-validated get-unparsed
"Executes a GET HTTP request against `url-str`. `opts` are merged
into the request map. The response is unparsed but returned as a
string."
[url-str :- String
& [opts]]
(http/get url-str
(merge
{:as :text
:headers {"Content-Type" "application/json"}}
opts)))
(pls/defn-validated get
"Executes a GET HTTP request against `url-str`. `opts` are merged
into the request map. JSON responses are automatically parsed before
returning. Error responses are returned (i.e. 404) and not thrown."
[url-str :- String
& [opts]]
(let [resp (get-unparsed url-str opts)
ctype (rr/get-header resp "content-type")]
(if (some-> ctype json-utf8-ctype?)
(update resp :body #(json/parse-string % true))
resp)))
(def default-ca-cert "test-resources/puppetserver/ssl/certs/ca.pem")
(def default-cert "test-resources/puppetserver/ssl/certs/localhost.pem")
(def default-ssl-key "test-<KEY>")
(pls/defn-validated get-ssl
"Executes a mutually authenticated GET HTTPS request against
`url-str` using the above `get` function."
[url-str & [opts]]
(get url-str
(merge {:ssl-ca-cert default-ca-cert
:ssl-cert default-cert
:ssl-key default-ssl-key}
opts)))
(pls/defn-validated get-or-throw
"Same as `get` except will throw if an error status is returned."
[url-str :- String
& [opts]]
(let [resp (get url-str opts)]
(if (>= (:status resp) 400)
(throw+ {:url url-str
:response resp
:status (:status resp)}
(format "Failed request to '%s' with status '%s'" url-str (:status resp)))
resp)))
(pls/defn-validated post
"Executes a POST HTTP request against `url-str`. `body` is a clojure
data structure that is converted to a JSON string before POSTing."
[url-str :- String
body
& [opts]]
(http/post url-str
(merge
{:body (json/generate-string body)
:headers {"Content-Type" "application/json"}}
opts)))
(pls/defn-validated post-ssl
"Executes a mutually authenticated POST HTTP request against
`url-str`. Uses the above `post` function"
[url-str :- String
body
& [opts]]
(post url-str
body
{:ssl-ca-cert default-ca-cert
:ssl-cert default-cert
:ssl-key default-ssl-key}))
(defn certname-query
"Returns a function that will query the given endpoint (`suffix`)
for the provided `certname`"
[base-url suffix certname]
(-> (query-url-str base-url suffix)
(get-or-throw {:query-params {"query" (json/generate-string [:= :certname certname])}})
:body))
(defn get-reports
([certname]
(get-reports *base-url* certname))
([base-url certname]
(certname-query base-url "/reports" certname)))
(defn get-factsets
([certname]
(get-factsets *base-url* certname))
([base-url certname]
(certname-query base-url "/factsets" certname)))
(defn get-catalogs
([certname]
(get-catalogs *base-url* certname))
([base-url certname]
(certname-query base-url "/catalogs" certname)))
(defn get-summary-stats []
(-> (admin-url-str "/summary-stats")
get-or-throw
:body))
(defmacro with-puppetdb-instance
"Convenience macro to launch a puppetdb instance"
[& body]
`(with-redefs [sutils/db-metadata (delay (sutils/db-metadata-fn))]
(call-with-puppetdb-instance
(fn []
~@body))))
(def ^:dynamic *notable-log-event?* notable-pdb-event?)
(defn call-with-single-quiet-pdb-instance
"Calls the call-with-puppetdb-instance with args after suppressing
all log events. If there's an error or worse, prints the log to
*err*. Should not be nested, nor nested with calls to
with-log-suppressed-unless-notable."
[& args]
(with-log-suppressed-unless-notable *notable-log-event?*
(apply call-with-puppetdb-instance args)))
(defmacro with-single-quiet-pdb-instance
"Convenience macro for call-with-single-quiet-pdb-instance."
[& body]
`(call-with-single-quiet-pdb-instance
(fn [] ~@body)))
(defmacro with-pdb-with-no-gc [& body]
`(with-test-db
(call-with-single-quiet-pdb-instance
(-> (svc-utils/create-temp-config)
(assoc :database *db*)
(assoc-in [:database :gc-interval] 0))
(fn []
~@body))))
(def max-attempts 50)
(defn url-encode [s]
(java.net.URLEncoder/encode s "UTF-8"))
(defn discard-count
"Returns the number of messages discarded from the command queue by
the current PuppetDB instance."
[]
(-> (pdb-metrics-url "/mbeans/puppetlabs.puppetdb.command:type=global,name=discarded")
get-or-throw
(get-in [:body :Count])))
(defn sync-command-post
"Syncronously post a command to PDB by blocking until the message is consumed
off the queue."
[base-url certname cmd version payload]
(let [timeout-seconds 20]
(let [response (pdb-client/submit-command-via-http!
base-url certname cmd version payload timeout-seconds)]
(if (>= (:status response) 400)
(throw (ex-info "Command processing failed" {:response response}))
response))))
(defn wait-for-server-processing
"Returns a truthy value indicating whether the wait was
successful (i.e. didn't time out). The current timeout granularity
may be as bad as 10ms."
[server timeout-ms]
(let [now-ms #(time-coerce/to-long (t/now))
deadline (+ (now-ms) timeout-ms)]
(loop []
(cond
(> (now-ms) deadline)
false
(let [srv (get-service server :PuppetDBCommandDispatcher)
stats (dispatch/stats srv)]
(= (:executed-commands stats) (:received-commands stats)))
true
:else ;; In theory, polling might be avoided via watcher.
(do
(Thread/sleep 10)
(recur))))))
| true | (ns puppetlabs.puppetdb.testutils.services
(:refer-clojure :exclude [get])
(:require [clj-time.core :as t]
[clj-time.coerce :as time-coerce]
[puppetlabs.kitchensink.core :as kitchensink]
[puppetlabs.puppetdb.testutils :as testutils]
[puppetlabs.puppetdb.testutils.db :refer [*db* with-test-db]]
[puppetlabs.puppetdb.testutils.log :refer [notable-pdb-event?]]
[puppetlabs.trapperkeeper.testutils.logging :refer [with-log-suppressed-unless-notable]]
[puppetlabs.puppetdb.scf.storage-utils :as sutils]
[metrics.counters :refer [clear!]]
[clojure.walk :as walk]
[puppetlabs.trapperkeeper.app :as tk-app :refer [get-service]]
[puppetlabs.trapperkeeper.testutils.bootstrap :as tkbs]
[puppetlabs.trapperkeeper.services.webserver.jetty9-service :refer [jetty9-service]]
[puppetlabs.trapperkeeper.services.webrouting.webrouting-service :refer [webrouting-service]]
[puppetlabs.trapperkeeper.services.status.status-service :refer [status-service]]
[puppetlabs.trapperkeeper.services.scheduler.scheduler-service :refer [scheduler-service]]
[puppetlabs.trapperkeeper.services.metrics.metrics-service :refer [metrics-webservice]]
[puppetlabs.puppetdb.client :as pdb-client]
[puppetlabs.puppetdb.cli.services :refer [puppetdb-service]]
[puppetlabs.puppetdb.admin :as admin]
[puppetlabs.puppetdb.command :refer [command-service] :as dispatch]
[puppetlabs.puppetdb.http :refer [json-utf8-ctype?]]
[puppetlabs.puppetdb.utils :as utils]
[puppetlabs.puppetdb.config :as conf]
[puppetlabs.puppetdb.cheshire :as json]
[puppetlabs.puppetdb.utils :refer [base-url->str base-url->str-with-prefix]]
[clojure.string :as str]
[me.raynes.fs :as fs]
[slingshot.slingshot :refer [throw+]]
[clojure.tools.logging :as log]
[puppetlabs.puppetdb.dashboard :refer [dashboard-redirect-service]]
[puppetlabs.puppetdb.pdb-routing :refer [pdb-routing-service
maint-mode-service]]
[puppetlabs.puppetdb.config :refer [config-service]]
[puppetlabs.http.client.sync :as http]
[puppetlabs.puppetdb.schema :as pls]
[ring.util.response :as rr]))
;; See utils.clj for more information about base-urls.
(def ^:dynamic *base-url* nil) ; Will not have a :version.
(defn create-temp-config
"Returns a config that refers to a temporary vardir."
[]
{:nrepl {}
:global {:vardir (testutils/temp-dir)}
:jetty {:port 0}
:command-processing {}})
(defn open-port-num
"Returns a currently open port number"
[]
(with-open [s (java.net.ServerSocket. 0)]
(.getLocalPort s)))
(defn assoc-open-port
"Updates `config` to include a (currently open) port number"
[config]
(let [port-key (if (-> config :jetty :ssl-port)
:ssl-port
:port)]
(assoc-in config [:jetty port-key] (open-port-num))))
(def ^:dynamic *server*)
(def default-services
[#'jetty9-service
#'webrouting-service
#'puppetdb-service
#'command-service
#'status-service
#'scheduler-service
#'metrics-webservice
#'dashboard-redirect-service
#'pdb-routing-service
#'maint-mode-service
#'config-service])
(defn clear-counters!
[metrics]
(walk/postwalk
(fn [x] (if (= (type x)
com.codahale.metrics.Counter)
(clear! x)
x))
metrics))
(defn jdbc-configs->pdb-if-needed [config]
(-> config
(update :database #(dissoc % :classname :subprotocol))
(update :read-database #(dissoc % :classname :subprotocol))))
(defn run-test-puppetdb [config services bind-attempts]
(when (zero? bind-attempts)
(throw (RuntimeException. "Repeated attempts to bind port failed, giving up")))
(let [config (-> config
jdbc-configs->pdb-if-needed
conf/adjust-and-validate-tk-config
assoc-open-port)
port (or (get-in config [:jetty :port])
(get-in config [:jetty :ssl-port]))
is-ssl (boolean (get-in config [:jetty :ssl-port]))
base-url {:protocol (if is-ssl "https" "http")
:host "localhost"
:port port
:prefix "/pdb/query"
:version :v4}]
(try
(swap! dispatch/metrics clear-counters!)
{:app (tkbs/bootstrap-services-with-config (map var-get services) config)
:base-url base-url}
(catch java.net.BindException e
(log/errorf e "Error occured when Jetty tried to bind to port %s, attempt #%s"
port bind-attempts)
(run-test-puppetdb config services (dec bind-attempts))))))
(defn call-with-puppetdb-instance
"Stands up a puppetdb instance with the specified config, calls f,
and then tears the instance down, binding *server* to the instance
and *base-url* to the instance's URL during the execution of f.
Starts any specified services in addition to the core PuppetDB
services, and tries to bind to an HTTP port up to bind-attempts
times (default 10) before giving up. If a config is not specified,
one will be generated by create-temp-config, using a database
managed by with-test-db."
([f]
(with-test-db
(call-with-puppetdb-instance
(assoc (create-temp-config) :database *db*)
f)))
([config f] (call-with-puppetdb-instance config default-services f))
([config services f]
(call-with-puppetdb-instance config services 10 f))
([config services bind-attempts f]
(let [{:keys [app base-url]} (run-test-puppetdb config services bind-attempts)]
(try
(binding [*server* app
*base-url* base-url]
(f))
(finally
(tk-app/stop app))))))
(defn create-url-str [base-url url-suffix]
(str (utils/base-url->str base-url)
(when url-suffix
url-suffix)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Functions that return URLs and strings for the top level services
;; in PDB
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn pdb-query-url
([]
(pdb-query-url *base-url*))
([base-url]
(assoc base-url :prefix "/pdb/query" :version :v4)))
(defn query-url-str
([url-suffix]
(query-url-str *base-url* url-suffix))
([base-url url-suffix]
(create-url-str (pdb-query-url base-url) url-suffix)))
(defn pdb-cmd-url
([]
(pdb-cmd-url *base-url*))
([base-url]
(assoc base-url :prefix "/pdb/cmd" :version :v1)))
(defn cmd-url-str
([url-suffix]
(cmd-url-str *base-url* url-suffix))
([base-url url-suffix]
(create-url-str (pdb-cmd-url base-url) url-suffix)))
(defn pdb-admin-url
([]
(pdb-admin-url *base-url*))
([base-url]
(assoc base-url :prefix "/pdb/admin" :version :v1)))
(defn admin-url-str
([url-suffix]
(admin-url-str *base-url* url-suffix))
([base-url url-suffix]
(create-url-str (pdb-admin-url base-url) url-suffix)))
(defn pdb-metrics-url
([]
(pdb-metrics-url *base-url*))
([base-url]
(assoc base-url :prefix "/metrics" :version :v1)))
(defn metrics-url-str
([url-suffix]
(metrics-url-str *base-url* url-suffix))
([base-url url-suffix]
(create-url-str (pdb-metrics-url base-url) url-suffix)))
(defn pdb-meta-url
([]
(pdb-meta-url *base-url*))
([base-url]
(assoc base-url :prefix "/pdb/meta" :version :v1)))
(defn meta-url-str
([url-suffix]
(meta-url-str *base-url* url-suffix))
([base-url url-suffix]
(create-url-str (pdb-meta-url base-url) url-suffix)))
(defn root-url-str
([]
(root-url-str *base-url*))
([base-url]
(-> base-url
(assoc :prefix "/")
utils/base-url->str-with-prefix)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Basic HTTP functions for interacting with PuppetDB services, the
;; url-str arguments below will likely come from the above functions
;; relating to the various top level services
;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(pls/defn-validated get-unparsed
"Executes a GET HTTP request against `url-str`. `opts` are merged
into the request map. The response is unparsed but returned as a
string."
[url-str :- String
& [opts]]
(http/get url-str
(merge
{:as :text
:headers {"Content-Type" "application/json"}}
opts)))
(pls/defn-validated get
"Executes a GET HTTP request against `url-str`. `opts` are merged
into the request map. JSON responses are automatically parsed before
returning. Error responses are returned (i.e. 404) and not thrown."
[url-str :- String
& [opts]]
(let [resp (get-unparsed url-str opts)
ctype (rr/get-header resp "content-type")]
(if (some-> ctype json-utf8-ctype?)
(update resp :body #(json/parse-string % true))
resp)))
(def default-ca-cert "test-resources/puppetserver/ssl/certs/ca.pem")
(def default-cert "test-resources/puppetserver/ssl/certs/localhost.pem")
(def default-ssl-key "test-PI:KEY:<KEY>END_PI")
(pls/defn-validated get-ssl
"Executes a mutually authenticated GET HTTPS request against
`url-str` using the above `get` function."
[url-str & [opts]]
(get url-str
(merge {:ssl-ca-cert default-ca-cert
:ssl-cert default-cert
:ssl-key default-ssl-key}
opts)))
(pls/defn-validated get-or-throw
"Same as `get` except will throw if an error status is returned."
[url-str :- String
& [opts]]
(let [resp (get url-str opts)]
(if (>= (:status resp) 400)
(throw+ {:url url-str
:response resp
:status (:status resp)}
(format "Failed request to '%s' with status '%s'" url-str (:status resp)))
resp)))
(pls/defn-validated post
"Executes a POST HTTP request against `url-str`. `body` is a clojure
data structure that is converted to a JSON string before POSTing."
[url-str :- String
body
& [opts]]
(http/post url-str
(merge
{:body (json/generate-string body)
:headers {"Content-Type" "application/json"}}
opts)))
(pls/defn-validated post-ssl
"Executes a mutually authenticated POST HTTP request against
`url-str`. Uses the above `post` function"
[url-str :- String
body
& [opts]]
(post url-str
body
{:ssl-ca-cert default-ca-cert
:ssl-cert default-cert
:ssl-key default-ssl-key}))
(defn certname-query
"Returns a function that will query the given endpoint (`suffix`)
for the provided `certname`"
[base-url suffix certname]
(-> (query-url-str base-url suffix)
(get-or-throw {:query-params {"query" (json/generate-string [:= :certname certname])}})
:body))
(defn get-reports
([certname]
(get-reports *base-url* certname))
([base-url certname]
(certname-query base-url "/reports" certname)))
(defn get-factsets
([certname]
(get-factsets *base-url* certname))
([base-url certname]
(certname-query base-url "/factsets" certname)))
(defn get-catalogs
([certname]
(get-catalogs *base-url* certname))
([base-url certname]
(certname-query base-url "/catalogs" certname)))
(defn get-summary-stats []
(-> (admin-url-str "/summary-stats")
get-or-throw
:body))
(defmacro with-puppetdb-instance
"Convenience macro to launch a puppetdb instance"
[& body]
`(with-redefs [sutils/db-metadata (delay (sutils/db-metadata-fn))]
(call-with-puppetdb-instance
(fn []
~@body))))
(def ^:dynamic *notable-log-event?* notable-pdb-event?)
(defn call-with-single-quiet-pdb-instance
"Calls the call-with-puppetdb-instance with args after suppressing
all log events. If there's an error or worse, prints the log to
*err*. Should not be nested, nor nested with calls to
with-log-suppressed-unless-notable."
[& args]
(with-log-suppressed-unless-notable *notable-log-event?*
(apply call-with-puppetdb-instance args)))
(defmacro with-single-quiet-pdb-instance
"Convenience macro for call-with-single-quiet-pdb-instance."
[& body]
`(call-with-single-quiet-pdb-instance
(fn [] ~@body)))
(defmacro with-pdb-with-no-gc [& body]
`(with-test-db
(call-with-single-quiet-pdb-instance
(-> (svc-utils/create-temp-config)
(assoc :database *db*)
(assoc-in [:database :gc-interval] 0))
(fn []
~@body))))
(def max-attempts 50)
(defn url-encode [s]
(java.net.URLEncoder/encode s "UTF-8"))
(defn discard-count
"Returns the number of messages discarded from the command queue by
the current PuppetDB instance."
[]
(-> (pdb-metrics-url "/mbeans/puppetlabs.puppetdb.command:type=global,name=discarded")
get-or-throw
(get-in [:body :Count])))
(defn sync-command-post
"Syncronously post a command to PDB by blocking until the message is consumed
off the queue."
[base-url certname cmd version payload]
(let [timeout-seconds 20]
(let [response (pdb-client/submit-command-via-http!
base-url certname cmd version payload timeout-seconds)]
(if (>= (:status response) 400)
(throw (ex-info "Command processing failed" {:response response}))
response))))
(defn wait-for-server-processing
"Returns a truthy value indicating whether the wait was
successful (i.e. didn't time out). The current timeout granularity
may be as bad as 10ms."
[server timeout-ms]
(let [now-ms #(time-coerce/to-long (t/now))
deadline (+ (now-ms) timeout-ms)]
(loop []
(cond
(> (now-ms) deadline)
false
(let [srv (get-service server :PuppetDBCommandDispatcher)
stats (dispatch/stats srv)]
(= (:executed-commands stats) (:received-commands stats)))
true
:else ;; In theory, polling might be avoided via watcher.
(do
(Thread/sleep 10)
(recur))))))
|
[
{
"context": "(holo/add-asset! \"plywood\" \"p125\" {\"producer\" \"UPM Plywood\"}\n (holo",
"end": 8305,
"score": 0.6670941710472107,
"start": 8298,
"tag": "NAME",
"value": "Plywood"
}
] | query-service/src/clj/query_service/model/ogre_db.clj | AaltoGoWood/gowood-poc | 0 | (ns query-service.model.ogre-db
(:require
[clojure.edn :as edn]
[clojure.walk :refer [keywordize-keys]]
[clojurewerkz.ogre.core :refer [open-graph traversal traverse value-map
match out has in select into-seq!
values as by V __] :as ogre]
[query-service.model.holochain :as holo])
(:import (org.apache.tinkerpop.gremlin.process.traversal Compare Operator Order P Pop SackFunctions$Barrier Scope Traversal)
(org.apache.tinkerpop.gremlin.structure Graph T Column VertexProperty$Cardinality Vertex)
(org.apache.tinkerpop.gremlin.structure.util GraphFactory)
(org.apache.tinkerpop.gremlin.structure.util.empty EmptyGraph)
(org.apache.tinkerpop.gremlin.process.traversal.dsl.graph GraphTraversal GraphTraversalSource)
(org.apache.tinkerpop.gremlin.driver.remote DriverRemoteConnection)
(org.apache.tinkerpop.gremlin.driver Cluster Cluster$Builder))
(:gen-class))
(defn- attr->keyword [k]
(case k
"node-id" :id
"node-type" :type
(keyword k)))
(defn- parse-coords [coordStr]
(let [[lng lat] (clojure.string/split coordStr #",[ ]?")]
(if (and lng lat)
{:lng (edn/read-string lng) :lat (edn/read-string lat)}
nil)))
(declare normalize-object)
(defn- normalize-value [k v]
(cond
(= k "coords") (parse-coords (first v))
(or (vector? v)
(instance? java.util.ArrayList v)) (first v)
(instance? org.apache.tinkerpop.gremlin.process.traversal.step.util.BulkSet v)
(vec (map normalize-object v))
(instance? java.util.LinkedHashMap v)
(normalize-object v)
:else v))
(defn normalize-object [obj]
(cond
(and (instance? java.util.Optional obj) (not (.isPresent obj))) nil
(and (instance? java.util.Optional obj) (.isPresent obj)) (normalize-object (.get obj))
:else (into {} (map (fn [[k vl]] [(attr->keyword k) (normalize-value k vl)]) obj))))
(defn get-graph []
(let [conf-file-url ^java.net.URL (clojure.java.io/resource "conf/remote-objects.yaml")
conf-file (.getPath conf-file-url)
driverConnection (DriverRemoteConnection/using conf-file "g")
graph (EmptyGraph/instance)
g (.withRemote (traversal graph) driverConnection)]
g))
(defn reset-graph []
(let [g (get-graph)]
(-> g V (ogre/drop) (.iterate))))
(defn count-V
"count-V return number of nodes (verticles) in graph.
Function is created for mainly dev purpose"
[]
(let [g (get-graph)]
(or
(first (traverse g V (.count) (ogre/into-vec!)))
0)))
(defn count-E
"count-E return number of edges in graph.
Function is created for mainly dev purpose"
[]
(let [g (get-graph)]
(or
(first (traverse g ogre/E (.count) (ogre/into-vec!)))
0)))
(defn- entity [acc type id & [props]]
(-> acc
(.addV type)
(ogre/property "node-id" id)
(ogre/property "node-type" type)
(#(reduce (fn [acc, [k, v]] (ogre/property acc k v))
%
(or props {})))
(ogre/as (str type "/" id))))
(defn- hc-entity [acc alias type id & [props]]
(-> acc
(.addV type)
(ogre/property "node-id" id)
(ogre/property "node-type" type)
(#(reduce (fn [acc, [k, v]] (ogre/property acc k v))
%
(or props {})))
(ogre/as (str alias))))
(defn- composed-of [acc fromNode toNode]
(-> acc
(.addE "composed-of")
(.from fromNode)
(.to toNode)))
(defn init-poc-graph-without-holodata []
(let [g (get-graph)]
(-> g
(entity "building" "746103")
(entity "plywood" "p123" {"producer" "UPM Plywood"})
(entity "plywood" "p124" {"producer" "UPM Plywood"})
(entity "plywood" "p125" {"producer" "UPM Plywood"})
(entity "tree-trunk" "455829" {"speciesOfTree" "birch"
"trunkWidth" "29.33"
"timestamp" "2019-10-14T09:12:13.012Z"
"length" "27.78667329"
"coords" "30.15397461, 62.4168632"})
(entity "tree-trunk" "455874" {"speciesOfTree" "birch"
"trunkWidth" "28.57"
"timestamp" "2019-10-12T09:12:13.012Z"
"length" "28.65986376"
"coords" "30.15477914, 62.41683654"})
(entity "tree-trunk" "461782" {"speciesOfTree" "spruce"
"trunkWidth" "57.41"
"timestamp" "2019-10-11T09:10:13.012Z"
"length" "31.66797217"
"coords" "30.1541639467, 62.4171853834"})
(entity "tree-trunk" "467166" {"speciesOfTree" "pine"
"trunkWidth" "42.96"
"timestamp" "2019-10-11T09:10:13.012Z"
"length" "27.85418971"
"coords" "30.1541639467, 62.4171853834"})
(composed-of "building/746103" "plywood/p123")
(composed-of "building/746103" "plywood/p124")
(composed-of "building/746103" "plywood/p125")
(composed-of "plywood/p123" "tree-trunk/455829")
(composed-of "plywood/p123" "tree-trunk/455874")
(composed-of "plywood/p124" "tree-trunk/461782")
(composed-of "plywood/p125" "tree-trunk/467166")
(.next))))
(def test-data
[{:type "entity" :node-type "building" :node-id "A1"}
{:type "entity" :node-type "building" :node-id "A2"}
{:type "entity" :node-type "plywood" :node-id "p1" :attributes {"producer" "UPM Plywood"}}
{:type "edge" :from "building/A1" :to "plywood/p1"}])
(defmulti add-item (fn [_ {:keys [type] :as item}] type))
(defmethod add-item "entity" [g {:keys [node-type node-id attributes] :as item}]
(entity g node-type node-id attributes))
(defmethod add-item "edge" [g {:keys [node-type from to] :as item}]
(composed-of g from to))
(defn add-data
"Add a data set of nodes and/or vertices to the database"
[data]
(let [traversal (reduce add-item (get-graph) data)]
(.next traversal)))
(defn init-poc-graph-with-holodata []
(let [g (get-graph)
holo-keys {:p123 (holo/add-asset! "plywood" "p123" {"producer" "UPM Plywood"}
(holo/add-asset! "tree-trunk" "455829" {"speciesOfTree" "birch"
"trunkWidth" "29.33"
"timestamp" "2019-10-14T09:12:13.012Z"
"length" "27.78667329"
"coords" "30.15397461, 62.4168632"})
(holo/add-asset! "tree-trunk" "455874" {"speciesOfTree" "birch"
"trunkWidth" "28.57"
"timestamp" "2019-10-12T09:12:13.012Z"
"length" "28.65986376"
"coords" "30.15477914, 62.41683654"}))
:p124 (holo/add-asset! "plywood" "p124" {"producer" "UPM Plywood"}
(holo/add-asset! "tree-trunk" "461782" {"speciesOfTree" "spruce"
"trunkWidth" "57.41"
"timestamp" "2019-10-11T09:10:13.012Z"
"length" "31.66797217"
"coords" "30.1541639467, 62.4171853834"}))
:p125 (holo/add-asset! "plywood" "p125" {"producer" "UPM Plywood"}
(holo/add-asset! "tree-trunk" "467166" {"speciesOfTree" "pine"
"trunkWidth" "42.96"
"timestamp" "2019-10-11T09:10:13.012Z"
"length" "27.85418971"
"coords" "30.1541639467, 62.4171853834"}))}]
(-> g
(entity "building" "746103")
(hc-entity "1" "holochain-link" (:p123 holo-keys))
(hc-entity "2" "holochain-link" (:p124 holo-keys))
(hc-entity "3" "holochain-link" (:p125 holo-keys))
(composed-of "building/746103" "1")
(composed-of "building/746103" "2")
(composed-of "building/746103" "3")
(.next))))
(defn get-nodes []
(let [g (get-graph)]
(traverse g V
(ogre/value-map)
(ogre/into-vec!))))
(defn get-node-with-components [node-type node-id]
(let [g (get-graph)]
(->
(traverse g V
(ogre/has node-type "node-id" node-id)
(ogre/as :attributes)
(ogre/optional (__ (out) (ogre/value-map) (ogre/aggregate :row)))
(ogre/project "attributes" "rows")
(ogre/by (__ (select :attributes) (ogre/value-map)))
(ogre/by (__ (select :row)))
(.tryNext))
normalize-object)))
(defn get-edges []
(let [g (get-graph)]
(traverse g ogre/E
(ogre/into-vec!))))
(defn ->normal-data-row [{:keys [type id] :as row}]
(println "->normal-data-row" row)
(if (= type "holochain-link")
(holo/->normal-data-row id)
(merge row {:original_id id :original_type type})))
(defn with-data-from-holochain [{:keys [rows attributes] :as data}]
(when data
(-> data
(assoc :rows (map ->normal-data-row rows))
(assoc :attributes (->normal-data-row attributes)))))
(defn apply-command [op body]
(let [{{id :id type :type} :from} body
data-raw (get-node-with-components type id)
data (with-data-from-holochain data-raw)
found? (some? data)]
(println "result data: " data)
(println "ogre -> id: " id "; type: " type "; found " found?)
{:req {:op op :body body}
:result {:found found?
:data data}
:external-nodes []}))
| 2514 | (ns query-service.model.ogre-db
(:require
[clojure.edn :as edn]
[clojure.walk :refer [keywordize-keys]]
[clojurewerkz.ogre.core :refer [open-graph traversal traverse value-map
match out has in select into-seq!
values as by V __] :as ogre]
[query-service.model.holochain :as holo])
(:import (org.apache.tinkerpop.gremlin.process.traversal Compare Operator Order P Pop SackFunctions$Barrier Scope Traversal)
(org.apache.tinkerpop.gremlin.structure Graph T Column VertexProperty$Cardinality Vertex)
(org.apache.tinkerpop.gremlin.structure.util GraphFactory)
(org.apache.tinkerpop.gremlin.structure.util.empty EmptyGraph)
(org.apache.tinkerpop.gremlin.process.traversal.dsl.graph GraphTraversal GraphTraversalSource)
(org.apache.tinkerpop.gremlin.driver.remote DriverRemoteConnection)
(org.apache.tinkerpop.gremlin.driver Cluster Cluster$Builder))
(:gen-class))
(defn- attr->keyword [k]
(case k
"node-id" :id
"node-type" :type
(keyword k)))
(defn- parse-coords [coordStr]
(let [[lng lat] (clojure.string/split coordStr #",[ ]?")]
(if (and lng lat)
{:lng (edn/read-string lng) :lat (edn/read-string lat)}
nil)))
(declare normalize-object)
(defn- normalize-value [k v]
(cond
(= k "coords") (parse-coords (first v))
(or (vector? v)
(instance? java.util.ArrayList v)) (first v)
(instance? org.apache.tinkerpop.gremlin.process.traversal.step.util.BulkSet v)
(vec (map normalize-object v))
(instance? java.util.LinkedHashMap v)
(normalize-object v)
:else v))
(defn normalize-object [obj]
(cond
(and (instance? java.util.Optional obj) (not (.isPresent obj))) nil
(and (instance? java.util.Optional obj) (.isPresent obj)) (normalize-object (.get obj))
:else (into {} (map (fn [[k vl]] [(attr->keyword k) (normalize-value k vl)]) obj))))
(defn get-graph []
(let [conf-file-url ^java.net.URL (clojure.java.io/resource "conf/remote-objects.yaml")
conf-file (.getPath conf-file-url)
driverConnection (DriverRemoteConnection/using conf-file "g")
graph (EmptyGraph/instance)
g (.withRemote (traversal graph) driverConnection)]
g))
(defn reset-graph []
(let [g (get-graph)]
(-> g V (ogre/drop) (.iterate))))
(defn count-V
"count-V return number of nodes (verticles) in graph.
Function is created for mainly dev purpose"
[]
(let [g (get-graph)]
(or
(first (traverse g V (.count) (ogre/into-vec!)))
0)))
(defn count-E
"count-E return number of edges in graph.
Function is created for mainly dev purpose"
[]
(let [g (get-graph)]
(or
(first (traverse g ogre/E (.count) (ogre/into-vec!)))
0)))
(defn- entity [acc type id & [props]]
(-> acc
(.addV type)
(ogre/property "node-id" id)
(ogre/property "node-type" type)
(#(reduce (fn [acc, [k, v]] (ogre/property acc k v))
%
(or props {})))
(ogre/as (str type "/" id))))
(defn- hc-entity [acc alias type id & [props]]
(-> acc
(.addV type)
(ogre/property "node-id" id)
(ogre/property "node-type" type)
(#(reduce (fn [acc, [k, v]] (ogre/property acc k v))
%
(or props {})))
(ogre/as (str alias))))
(defn- composed-of [acc fromNode toNode]
(-> acc
(.addE "composed-of")
(.from fromNode)
(.to toNode)))
(defn init-poc-graph-without-holodata []
(let [g (get-graph)]
(-> g
(entity "building" "746103")
(entity "plywood" "p123" {"producer" "UPM Plywood"})
(entity "plywood" "p124" {"producer" "UPM Plywood"})
(entity "plywood" "p125" {"producer" "UPM Plywood"})
(entity "tree-trunk" "455829" {"speciesOfTree" "birch"
"trunkWidth" "29.33"
"timestamp" "2019-10-14T09:12:13.012Z"
"length" "27.78667329"
"coords" "30.15397461, 62.4168632"})
(entity "tree-trunk" "455874" {"speciesOfTree" "birch"
"trunkWidth" "28.57"
"timestamp" "2019-10-12T09:12:13.012Z"
"length" "28.65986376"
"coords" "30.15477914, 62.41683654"})
(entity "tree-trunk" "461782" {"speciesOfTree" "spruce"
"trunkWidth" "57.41"
"timestamp" "2019-10-11T09:10:13.012Z"
"length" "31.66797217"
"coords" "30.1541639467, 62.4171853834"})
(entity "tree-trunk" "467166" {"speciesOfTree" "pine"
"trunkWidth" "42.96"
"timestamp" "2019-10-11T09:10:13.012Z"
"length" "27.85418971"
"coords" "30.1541639467, 62.4171853834"})
(composed-of "building/746103" "plywood/p123")
(composed-of "building/746103" "plywood/p124")
(composed-of "building/746103" "plywood/p125")
(composed-of "plywood/p123" "tree-trunk/455829")
(composed-of "plywood/p123" "tree-trunk/455874")
(composed-of "plywood/p124" "tree-trunk/461782")
(composed-of "plywood/p125" "tree-trunk/467166")
(.next))))
(def test-data
[{:type "entity" :node-type "building" :node-id "A1"}
{:type "entity" :node-type "building" :node-id "A2"}
{:type "entity" :node-type "plywood" :node-id "p1" :attributes {"producer" "UPM Plywood"}}
{:type "edge" :from "building/A1" :to "plywood/p1"}])
(defmulti add-item (fn [_ {:keys [type] :as item}] type))
(defmethod add-item "entity" [g {:keys [node-type node-id attributes] :as item}]
(entity g node-type node-id attributes))
(defmethod add-item "edge" [g {:keys [node-type from to] :as item}]
(composed-of g from to))
(defn add-data
"Add a data set of nodes and/or vertices to the database"
[data]
(let [traversal (reduce add-item (get-graph) data)]
(.next traversal)))
(defn init-poc-graph-with-holodata []
(let [g (get-graph)
holo-keys {:p123 (holo/add-asset! "plywood" "p123" {"producer" "UPM Plywood"}
(holo/add-asset! "tree-trunk" "455829" {"speciesOfTree" "birch"
"trunkWidth" "29.33"
"timestamp" "2019-10-14T09:12:13.012Z"
"length" "27.78667329"
"coords" "30.15397461, 62.4168632"})
(holo/add-asset! "tree-trunk" "455874" {"speciesOfTree" "birch"
"trunkWidth" "28.57"
"timestamp" "2019-10-12T09:12:13.012Z"
"length" "28.65986376"
"coords" "30.15477914, 62.41683654"}))
:p124 (holo/add-asset! "plywood" "p124" {"producer" "UPM Plywood"}
(holo/add-asset! "tree-trunk" "461782" {"speciesOfTree" "spruce"
"trunkWidth" "57.41"
"timestamp" "2019-10-11T09:10:13.012Z"
"length" "31.66797217"
"coords" "30.1541639467, 62.4171853834"}))
:p125 (holo/add-asset! "plywood" "p125" {"producer" "UPM <NAME>"}
(holo/add-asset! "tree-trunk" "467166" {"speciesOfTree" "pine"
"trunkWidth" "42.96"
"timestamp" "2019-10-11T09:10:13.012Z"
"length" "27.85418971"
"coords" "30.1541639467, 62.4171853834"}))}]
(-> g
(entity "building" "746103")
(hc-entity "1" "holochain-link" (:p123 holo-keys))
(hc-entity "2" "holochain-link" (:p124 holo-keys))
(hc-entity "3" "holochain-link" (:p125 holo-keys))
(composed-of "building/746103" "1")
(composed-of "building/746103" "2")
(composed-of "building/746103" "3")
(.next))))
(defn get-nodes []
(let [g (get-graph)]
(traverse g V
(ogre/value-map)
(ogre/into-vec!))))
(defn get-node-with-components [node-type node-id]
(let [g (get-graph)]
(->
(traverse g V
(ogre/has node-type "node-id" node-id)
(ogre/as :attributes)
(ogre/optional (__ (out) (ogre/value-map) (ogre/aggregate :row)))
(ogre/project "attributes" "rows")
(ogre/by (__ (select :attributes) (ogre/value-map)))
(ogre/by (__ (select :row)))
(.tryNext))
normalize-object)))
(defn get-edges []
(let [g (get-graph)]
(traverse g ogre/E
(ogre/into-vec!))))
(defn ->normal-data-row [{:keys [type id] :as row}]
(println "->normal-data-row" row)
(if (= type "holochain-link")
(holo/->normal-data-row id)
(merge row {:original_id id :original_type type})))
(defn with-data-from-holochain [{:keys [rows attributes] :as data}]
(when data
(-> data
(assoc :rows (map ->normal-data-row rows))
(assoc :attributes (->normal-data-row attributes)))))
(defn apply-command [op body]
(let [{{id :id type :type} :from} body
data-raw (get-node-with-components type id)
data (with-data-from-holochain data-raw)
found? (some? data)]
(println "result data: " data)
(println "ogre -> id: " id "; type: " type "; found " found?)
{:req {:op op :body body}
:result {:found found?
:data data}
:external-nodes []}))
| true | (ns query-service.model.ogre-db
(:require
[clojure.edn :as edn]
[clojure.walk :refer [keywordize-keys]]
[clojurewerkz.ogre.core :refer [open-graph traversal traverse value-map
match out has in select into-seq!
values as by V __] :as ogre]
[query-service.model.holochain :as holo])
(:import (org.apache.tinkerpop.gremlin.process.traversal Compare Operator Order P Pop SackFunctions$Barrier Scope Traversal)
(org.apache.tinkerpop.gremlin.structure Graph T Column VertexProperty$Cardinality Vertex)
(org.apache.tinkerpop.gremlin.structure.util GraphFactory)
(org.apache.tinkerpop.gremlin.structure.util.empty EmptyGraph)
(org.apache.tinkerpop.gremlin.process.traversal.dsl.graph GraphTraversal GraphTraversalSource)
(org.apache.tinkerpop.gremlin.driver.remote DriverRemoteConnection)
(org.apache.tinkerpop.gremlin.driver Cluster Cluster$Builder))
(:gen-class))
(defn- attr->keyword [k]
(case k
"node-id" :id
"node-type" :type
(keyword k)))
(defn- parse-coords [coordStr]
(let [[lng lat] (clojure.string/split coordStr #",[ ]?")]
(if (and lng lat)
{:lng (edn/read-string lng) :lat (edn/read-string lat)}
nil)))
(declare normalize-object)
(defn- normalize-value [k v]
(cond
(= k "coords") (parse-coords (first v))
(or (vector? v)
(instance? java.util.ArrayList v)) (first v)
(instance? org.apache.tinkerpop.gremlin.process.traversal.step.util.BulkSet v)
(vec (map normalize-object v))
(instance? java.util.LinkedHashMap v)
(normalize-object v)
:else v))
(defn normalize-object [obj]
(cond
(and (instance? java.util.Optional obj) (not (.isPresent obj))) nil
(and (instance? java.util.Optional obj) (.isPresent obj)) (normalize-object (.get obj))
:else (into {} (map (fn [[k vl]] [(attr->keyword k) (normalize-value k vl)]) obj))))
(defn get-graph []
(let [conf-file-url ^java.net.URL (clojure.java.io/resource "conf/remote-objects.yaml")
conf-file (.getPath conf-file-url)
driverConnection (DriverRemoteConnection/using conf-file "g")
graph (EmptyGraph/instance)
g (.withRemote (traversal graph) driverConnection)]
g))
(defn reset-graph []
(let [g (get-graph)]
(-> g V (ogre/drop) (.iterate))))
(defn count-V
"count-V return number of nodes (verticles) in graph.
Function is created for mainly dev purpose"
[]
(let [g (get-graph)]
(or
(first (traverse g V (.count) (ogre/into-vec!)))
0)))
(defn count-E
"count-E return number of edges in graph.
Function is created for mainly dev purpose"
[]
(let [g (get-graph)]
(or
(first (traverse g ogre/E (.count) (ogre/into-vec!)))
0)))
(defn- entity [acc type id & [props]]
(-> acc
(.addV type)
(ogre/property "node-id" id)
(ogre/property "node-type" type)
(#(reduce (fn [acc, [k, v]] (ogre/property acc k v))
%
(or props {})))
(ogre/as (str type "/" id))))
(defn- hc-entity [acc alias type id & [props]]
(-> acc
(.addV type)
(ogre/property "node-id" id)
(ogre/property "node-type" type)
(#(reduce (fn [acc, [k, v]] (ogre/property acc k v))
%
(or props {})))
(ogre/as (str alias))))
(defn- composed-of [acc fromNode toNode]
(-> acc
(.addE "composed-of")
(.from fromNode)
(.to toNode)))
(defn init-poc-graph-without-holodata []
(let [g (get-graph)]
(-> g
(entity "building" "746103")
(entity "plywood" "p123" {"producer" "UPM Plywood"})
(entity "plywood" "p124" {"producer" "UPM Plywood"})
(entity "plywood" "p125" {"producer" "UPM Plywood"})
(entity "tree-trunk" "455829" {"speciesOfTree" "birch"
"trunkWidth" "29.33"
"timestamp" "2019-10-14T09:12:13.012Z"
"length" "27.78667329"
"coords" "30.15397461, 62.4168632"})
(entity "tree-trunk" "455874" {"speciesOfTree" "birch"
"trunkWidth" "28.57"
"timestamp" "2019-10-12T09:12:13.012Z"
"length" "28.65986376"
"coords" "30.15477914, 62.41683654"})
(entity "tree-trunk" "461782" {"speciesOfTree" "spruce"
"trunkWidth" "57.41"
"timestamp" "2019-10-11T09:10:13.012Z"
"length" "31.66797217"
"coords" "30.1541639467, 62.4171853834"})
(entity "tree-trunk" "467166" {"speciesOfTree" "pine"
"trunkWidth" "42.96"
"timestamp" "2019-10-11T09:10:13.012Z"
"length" "27.85418971"
"coords" "30.1541639467, 62.4171853834"})
(composed-of "building/746103" "plywood/p123")
(composed-of "building/746103" "plywood/p124")
(composed-of "building/746103" "plywood/p125")
(composed-of "plywood/p123" "tree-trunk/455829")
(composed-of "plywood/p123" "tree-trunk/455874")
(composed-of "plywood/p124" "tree-trunk/461782")
(composed-of "plywood/p125" "tree-trunk/467166")
(.next))))
(def test-data
[{:type "entity" :node-type "building" :node-id "A1"}
{:type "entity" :node-type "building" :node-id "A2"}
{:type "entity" :node-type "plywood" :node-id "p1" :attributes {"producer" "UPM Plywood"}}
{:type "edge" :from "building/A1" :to "plywood/p1"}])
(defmulti add-item (fn [_ {:keys [type] :as item}] type))
(defmethod add-item "entity" [g {:keys [node-type node-id attributes] :as item}]
(entity g node-type node-id attributes))
(defmethod add-item "edge" [g {:keys [node-type from to] :as item}]
(composed-of g from to))
(defn add-data
"Add a data set of nodes and/or vertices to the database"
[data]
(let [traversal (reduce add-item (get-graph) data)]
(.next traversal)))
(defn init-poc-graph-with-holodata []
(let [g (get-graph)
holo-keys {:p123 (holo/add-asset! "plywood" "p123" {"producer" "UPM Plywood"}
(holo/add-asset! "tree-trunk" "455829" {"speciesOfTree" "birch"
"trunkWidth" "29.33"
"timestamp" "2019-10-14T09:12:13.012Z"
"length" "27.78667329"
"coords" "30.15397461, 62.4168632"})
(holo/add-asset! "tree-trunk" "455874" {"speciesOfTree" "birch"
"trunkWidth" "28.57"
"timestamp" "2019-10-12T09:12:13.012Z"
"length" "28.65986376"
"coords" "30.15477914, 62.41683654"}))
:p124 (holo/add-asset! "plywood" "p124" {"producer" "UPM Plywood"}
(holo/add-asset! "tree-trunk" "461782" {"speciesOfTree" "spruce"
"trunkWidth" "57.41"
"timestamp" "2019-10-11T09:10:13.012Z"
"length" "31.66797217"
"coords" "30.1541639467, 62.4171853834"}))
:p125 (holo/add-asset! "plywood" "p125" {"producer" "UPM PI:NAME:<NAME>END_PI"}
(holo/add-asset! "tree-trunk" "467166" {"speciesOfTree" "pine"
"trunkWidth" "42.96"
"timestamp" "2019-10-11T09:10:13.012Z"
"length" "27.85418971"
"coords" "30.1541639467, 62.4171853834"}))}]
(-> g
(entity "building" "746103")
(hc-entity "1" "holochain-link" (:p123 holo-keys))
(hc-entity "2" "holochain-link" (:p124 holo-keys))
(hc-entity "3" "holochain-link" (:p125 holo-keys))
(composed-of "building/746103" "1")
(composed-of "building/746103" "2")
(composed-of "building/746103" "3")
(.next))))
(defn get-nodes []
(let [g (get-graph)]
(traverse g V
(ogre/value-map)
(ogre/into-vec!))))
(defn get-node-with-components [node-type node-id]
(let [g (get-graph)]
(->
(traverse g V
(ogre/has node-type "node-id" node-id)
(ogre/as :attributes)
(ogre/optional (__ (out) (ogre/value-map) (ogre/aggregate :row)))
(ogre/project "attributes" "rows")
(ogre/by (__ (select :attributes) (ogre/value-map)))
(ogre/by (__ (select :row)))
(.tryNext))
normalize-object)))
(defn get-edges []
(let [g (get-graph)]
(traverse g ogre/E
(ogre/into-vec!))))
(defn ->normal-data-row [{:keys [type id] :as row}]
(println "->normal-data-row" row)
(if (= type "holochain-link")
(holo/->normal-data-row id)
(merge row {:original_id id :original_type type})))
(defn with-data-from-holochain [{:keys [rows attributes] :as data}]
(when data
(-> data
(assoc :rows (map ->normal-data-row rows))
(assoc :attributes (->normal-data-row attributes)))))
(defn apply-command [op body]
(let [{{id :id type :type} :from} body
data-raw (get-node-with-components type id)
data (with-data-from-holochain data-raw)
found? (some? data)]
(println "result data: " data)
(println "ogre -> id: " id "; type: " type "; found " found?)
{:req {:op op :body body}
:result {:found found?
:data data}
:external-nodes []}))
|
[
{
"context": "tr-replace, reverse str-reverse}])\n\n(def users #{\"mr_paul smith\" \"dr_john blake\" \"miss_katie hudson\"})\n\n(map #(st",
"end": 103,
"score": 0.9725627899169922,
"start": 90,
"tag": "USERNAME",
"value": "mr_paul smith"
},
{
"context": "rse str-reverse}])\n\n(def users #{\"mr_paul smith\" \"dr_john blake\" \"miss_katie hudson\"})\n\n(map #(str-replace % #\"_\"",
"end": 119,
"score": 0.9868767857551575,
"start": 106,
"tag": "USERNAME",
"value": "dr_john blake"
},
{
"context": "])\n\n(def users #{\"mr_paul smith\" \"dr_john blake\" \"miss_katie hudson\"})\n\n(map #(str-replace % #\"_\" \" \") users)\n\n(map #",
"end": 139,
"score": 0.9240310192108154,
"start": 122,
"tag": "USERNAME",
"value": "miss_katie hudson"
},
{
"context": "e '[clojure.set :exclude (join)])\n\n(def admins #{\"Mr Paul Smith\" \"Miss Katie Hudson\" \"Dr Mike Rose\" \"Mrs Tracy Fo",
"end": 548,
"score": 0.9909326434135437,
"start": 535,
"tag": "NAME",
"value": "Mr Paul Smith"
},
{
"context": ":exclude (join)])\n\n(def admins #{\"Mr Paul Smith\" \"Miss Katie Hudson\" \"Dr Mike Rose\" \"Mrs Tracy Ford\"})\n\n(subset? use",
"end": 568,
"score": 0.9995279312133789,
"start": 551,
"tag": "NAME",
"value": "Miss Katie Hudson"
},
{
"context": "def admins #{\"Mr Paul Smith\" \"Miss Katie Hudson\" \"Dr Mike Rose\" \"Mrs Tracy Ford\"})\n\n(subset? users ad",
"end": 573,
"score": 0.7942349314689636,
"start": 571,
"tag": "NAME",
"value": "Dr"
},
{
"context": "f admins #{\"Mr Paul Smith\" \"Miss Katie Hudson\" \"Dr Mike Rose\" \"Mrs Tracy Ford\"})\n\n(subset? users admins)\n\n(us",
"end": 583,
"score": 0.9624171257019043,
"start": 574,
"tag": "NAME",
"value": "Mike Rose"
},
{
"context": "r Paul Smith\" \"Miss Katie Hudson\" \"Dr Mike Rose\" \"Mrs Tracy Ford\"})\n\n(subset? users admins)\n\n(use '[clojure.pprin",
"end": 600,
"score": 0.9879854321479797,
"start": 586,
"tag": "NAME",
"value": "Mrs Tracy Ford"
}
] | Chapter08/Activity8.01/repl.clj | transducer/The-Clojure-Workshop | 55 | (use '[clojure.string :rename {replace str-replace, reverse str-reverse}])
(def users #{"mr_paul smith" "dr_john blake" "miss_katie hudson"})
(map #(str-replace % #"_" " ") users)
(map #(capitalize %) users)
(def updated-users (into #{}
(map #(join " "
(map (fn [sub-str] (capitalize sub-str))
(split (str-replace % #"_" " ") #" ")))
users)))
(use '[clojure.set :exclude (join)])
(def admins #{"Mr Paul Smith" "Miss Katie Hudson" "Dr Mike Rose" "Mrs Tracy Ford"})
(subset? users admins)
(use '[clojure.pprint :only (print-table)])
(print-table (map #(hash-map :user-name %) updated-users)) | 54850 | (use '[clojure.string :rename {replace str-replace, reverse str-reverse}])
(def users #{"mr_paul smith" "dr_john blake" "miss_katie hudson"})
(map #(str-replace % #"_" " ") users)
(map #(capitalize %) users)
(def updated-users (into #{}
(map #(join " "
(map (fn [sub-str] (capitalize sub-str))
(split (str-replace % #"_" " ") #" ")))
users)))
(use '[clojure.set :exclude (join)])
(def admins #{"<NAME>" "<NAME>" "<NAME> <NAME>" "<NAME>"})
(subset? users admins)
(use '[clojure.pprint :only (print-table)])
(print-table (map #(hash-map :user-name %) updated-users)) | true | (use '[clojure.string :rename {replace str-replace, reverse str-reverse}])
(def users #{"mr_paul smith" "dr_john blake" "miss_katie hudson"})
(map #(str-replace % #"_" " ") users)
(map #(capitalize %) users)
(def updated-users (into #{}
(map #(join " "
(map (fn [sub-str] (capitalize sub-str))
(split (str-replace % #"_" " ") #" ")))
users)))
(use '[clojure.set :exclude (join)])
(def admins #{"PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"})
(subset? users admins)
(use '[clojure.pprint :only (print-table)])
(print-table (map #(hash-map :user-name %) updated-users)) |
[
{
"context": ")))\n\n(read-string \"(+ 1 2)\")\n\n(def person {:name \"John Smith\" :city \"Tardis\"})\n\n(:city person)\n\n;an example of",
"end": 292,
"score": 0.9998047351837158,
"start": 282,
"tag": "NAME",
"value": "John Smith"
},
{
"context": " named values (such as vars)\n\n(def pizza\n\t{:name \"Gino's\"\n\t :location \"Robertsham\"\n\t ::location \"43222 342",
"end": 552,
"score": 0.9998035430908203,
"start": 546,
"tag": "NAME",
"value": "Gino's"
},
{
"context": "\n(let [{f \"foo\"} m]\n\t(+ f 12))\n\n(def chas {:name \"Chas\" :age 31 :location \"Johannesburg\"})\n\n(let [{:keys",
"end": 1699,
"score": 0.9997568726539612,
"start": 1695,
"tag": "NAME",
"value": "Chas"
},
{
"context": "ves in %s.\" name age location))\n\n(def user-info [\"robert\" 2011 :name \"Bob\" :city \"Cape Town\"])\n\n(let [[use",
"end": 1868,
"score": 0.9959962368011475,
"start": 1862,
"tag": "NAME",
"value": "robert"
},
{
"context": " location))\n\n(def user-info [\"robert\" 2011 :name \"Bob\" :city \"Cape Town\"])\n\n(let [[username account-yea",
"end": 1885,
"score": 0.9995588660240173,
"start": 1882,
"tag": "NAME",
"value": "Bob"
}
] | Clojure/cp/src/cp/core.clj | vanonselenp/Learning | 0 | (ns cp.core)
;the point of this project is to put the code of the clojure programming
;book.
(defn foo
"I don't do a whole lot."
[x]
(println x "Hello, World!"))
(defn average
[numbers]
(/ (apply + numbers) (count numbers)))
(read-string "(+ 1 2)")
(def person {:name "John Smith" :city "Tardis"})
(:city person)
;an example of namespaces, a way of binding a var, keyword etc
;to a specific name so that if can be used multiple times.
;these are named values, sybols are the other named values (such as vars)
(def pizza
{:name "Gino's"
:location "Robertsham"
::location "43222 342432"})
(user/location pizza)
(name :user/location)
(namespace :user/location)
;anything that includes a / is indicating the namespace it is from
;regex any string wtih a # is treated as a regex
(re-seq #"(...) (...)" "foo bar")
;?? (re-seq #"(\d+)-(\d+)" "1-3")
;wait what? can comment out parts of a form with #_
(+ 1 2 3 #_(* 2 222) 8)
;lists
'(1 2 3 4) ;lists
[1 2 3 4] ;vectors
{:a "a" :b "b"} ;maps
#{1 2 3} ;set
(def x 1)
(def x "hello")
(let [a (inc (rand-int 6))
b (inc (rand-int 6))]
(println (format "You rolled a %s and a %s" a b))
(+ a b))
(defn hypot
[x y]
(let [x2 (* x x)
y2 (* y y)]
(Math/sqrt (+ x2 y2))))
;Destructureing a vector
(def v [42 "foo" 99.2 [5 12]])
(let [[x y z] v] (+ x z))
(let [[x _ _ [y z]] v] (+ x y z))
(let [[x & rest] v] rest) ;rest is a var name not a keyword
(let [[x _ z :as original-vector] v]
(conj original-vector (+ x z)))
;Destructuring a map
(def m {:a 5, :b 6
:c [7 8 9]
:d {:e 10 :f 11}
"foo" 88
42 false})
(let [{a :a b :b} m]
(+ a b))
(let [{f "foo"} m]
(+ f 12))
(def chas {:name "Chas" :age 31 :location "Johannesburg"})
(let [{:keys [name age location]} chas]
(format "%s is %s years old and lives in %s." name age location))
(def user-info ["robert" 2011 :name "Bob" :city "Cape Town"])
(let [[username account-year & {:keys [name city]}] user-info]
(format "%s is in %s" username city))
(fn [x] (+ 10 x)) ;anoymous methods ... lambdas?
(def strange-adder
(fn adder-self-reference
([x] (adder-self-reference x 1))
([x y] (+ x y))))
(loop [x 5]
(if (neg? x)
x
(recur (dec x))))
(defn embedded-repl
[]
(print (str (ns-name *ns*) ">>> "))
(flush)
(let [expr (read)
value (eval expr)]
(when (not= :quit value)
(println value)
(recur))))
(defn call-twice [f x]
(f x)
(f x))
(def squared-up
(reduce
(fn [m v]
(assoc m v (* v v)))
{}
[ 1 2 3 4]))
(def only-strings (partial filter string?))
(only-strings ["a" 5 6 "b"])
(defn negated-sum-str
[& numbers]
(str (- (apply + numbers))))
(def negated-sum-str-2 (comp str - +))
(require '[clojure.string :as str])
;due to the \- this has to be copied to the repl and not run through
;the auto evaluate run thing
(def camel->keyword (comp keyword
str/join
(partial interpose \-)
(partial map str/lower-case)
#(str/split % #"(?<=[a-z])(?=[A-Z])")))
(camel->keyword "CamelCaseAndOtherCoolThings")
(camel->keyword2 "CamelCaseAndOtherCoolThings")
(defn camel->keyword2
[s]
(->> (str/split s #"(?<=[a-z])(?=[A-Z])")
(map str/lower-case)
(interpose \-)
str/join
keyword))
(def camel-pairs->map (comp (partial apply hash-map)
(partial map-indexed (fn [i x]
(if (odd? i)
x
(camel->keyword x))))))
(camel-pairs->map ["CamelCase" 5])
(defn adder
[n]
(fn [x] (+ n x)))
(defn doubler
[f]
(fn [& args]
(* 2 (apply f args))))
(def double-+ (doubler +))
| 99644 | (ns cp.core)
;the point of this project is to put the code of the clojure programming
;book.
(defn foo
"I don't do a whole lot."
[x]
(println x "Hello, World!"))
(defn average
[numbers]
(/ (apply + numbers) (count numbers)))
(read-string "(+ 1 2)")
(def person {:name "<NAME>" :city "Tardis"})
(:city person)
;an example of namespaces, a way of binding a var, keyword etc
;to a specific name so that if can be used multiple times.
;these are named values, sybols are the other named values (such as vars)
(def pizza
{:name "<NAME>"
:location "Robertsham"
::location "43222 342432"})
(user/location pizza)
(name :user/location)
(namespace :user/location)
;anything that includes a / is indicating the namespace it is from
;regex any string wtih a # is treated as a regex
(re-seq #"(...) (...)" "foo bar")
;?? (re-seq #"(\d+)-(\d+)" "1-3")
;wait what? can comment out parts of a form with #_
(+ 1 2 3 #_(* 2 222) 8)
;lists
'(1 2 3 4) ;lists
[1 2 3 4] ;vectors
{:a "a" :b "b"} ;maps
#{1 2 3} ;set
(def x 1)
(def x "hello")
(let [a (inc (rand-int 6))
b (inc (rand-int 6))]
(println (format "You rolled a %s and a %s" a b))
(+ a b))
(defn hypot
[x y]
(let [x2 (* x x)
y2 (* y y)]
(Math/sqrt (+ x2 y2))))
;Destructureing a vector
(def v [42 "foo" 99.2 [5 12]])
(let [[x y z] v] (+ x z))
(let [[x _ _ [y z]] v] (+ x y z))
(let [[x & rest] v] rest) ;rest is a var name not a keyword
(let [[x _ z :as original-vector] v]
(conj original-vector (+ x z)))
;Destructuring a map
(def m {:a 5, :b 6
:c [7 8 9]
:d {:e 10 :f 11}
"foo" 88
42 false})
(let [{a :a b :b} m]
(+ a b))
(let [{f "foo"} m]
(+ f 12))
(def chas {:name "<NAME>" :age 31 :location "Johannesburg"})
(let [{:keys [name age location]} chas]
(format "%s is %s years old and lives in %s." name age location))
(def user-info ["<NAME>" 2011 :name "<NAME>" :city "Cape Town"])
(let [[username account-year & {:keys [name city]}] user-info]
(format "%s is in %s" username city))
(fn [x] (+ 10 x)) ;anoymous methods ... lambdas?
(def strange-adder
(fn adder-self-reference
([x] (adder-self-reference x 1))
([x y] (+ x y))))
(loop [x 5]
(if (neg? x)
x
(recur (dec x))))
(defn embedded-repl
[]
(print (str (ns-name *ns*) ">>> "))
(flush)
(let [expr (read)
value (eval expr)]
(when (not= :quit value)
(println value)
(recur))))
(defn call-twice [f x]
(f x)
(f x))
(def squared-up
(reduce
(fn [m v]
(assoc m v (* v v)))
{}
[ 1 2 3 4]))
(def only-strings (partial filter string?))
(only-strings ["a" 5 6 "b"])
(defn negated-sum-str
[& numbers]
(str (- (apply + numbers))))
(def negated-sum-str-2 (comp str - +))
(require '[clojure.string :as str])
;due to the \- this has to be copied to the repl and not run through
;the auto evaluate run thing
(def camel->keyword (comp keyword
str/join
(partial interpose \-)
(partial map str/lower-case)
#(str/split % #"(?<=[a-z])(?=[A-Z])")))
(camel->keyword "CamelCaseAndOtherCoolThings")
(camel->keyword2 "CamelCaseAndOtherCoolThings")
(defn camel->keyword2
[s]
(->> (str/split s #"(?<=[a-z])(?=[A-Z])")
(map str/lower-case)
(interpose \-)
str/join
keyword))
(def camel-pairs->map (comp (partial apply hash-map)
(partial map-indexed (fn [i x]
(if (odd? i)
x
(camel->keyword x))))))
(camel-pairs->map ["CamelCase" 5])
(defn adder
[n]
(fn [x] (+ n x)))
(defn doubler
[f]
(fn [& args]
(* 2 (apply f args))))
(def double-+ (doubler +))
| true | (ns cp.core)
;the point of this project is to put the code of the clojure programming
;book.
(defn foo
"I don't do a whole lot."
[x]
(println x "Hello, World!"))
(defn average
[numbers]
(/ (apply + numbers) (count numbers)))
(read-string "(+ 1 2)")
(def person {:name "PI:NAME:<NAME>END_PI" :city "Tardis"})
(:city person)
;an example of namespaces, a way of binding a var, keyword etc
;to a specific name so that if can be used multiple times.
;these are named values, sybols are the other named values (such as vars)
(def pizza
{:name "PI:NAME:<NAME>END_PI"
:location "Robertsham"
::location "43222 342432"})
(user/location pizza)
(name :user/location)
(namespace :user/location)
;anything that includes a / is indicating the namespace it is from
;regex any string wtih a # is treated as a regex
(re-seq #"(...) (...)" "foo bar")
;?? (re-seq #"(\d+)-(\d+)" "1-3")
;wait what? can comment out parts of a form with #_
(+ 1 2 3 #_(* 2 222) 8)
;lists
'(1 2 3 4) ;lists
[1 2 3 4] ;vectors
{:a "a" :b "b"} ;maps
#{1 2 3} ;set
(def x 1)
(def x "hello")
(let [a (inc (rand-int 6))
b (inc (rand-int 6))]
(println (format "You rolled a %s and a %s" a b))
(+ a b))
(defn hypot
[x y]
(let [x2 (* x x)
y2 (* y y)]
(Math/sqrt (+ x2 y2))))
;Destructureing a vector
(def v [42 "foo" 99.2 [5 12]])
(let [[x y z] v] (+ x z))
(let [[x _ _ [y z]] v] (+ x y z))
(let [[x & rest] v] rest) ;rest is a var name not a keyword
(let [[x _ z :as original-vector] v]
(conj original-vector (+ x z)))
;Destructuring a map
(def m {:a 5, :b 6
:c [7 8 9]
:d {:e 10 :f 11}
"foo" 88
42 false})
(let [{a :a b :b} m]
(+ a b))
(let [{f "foo"} m]
(+ f 12))
(def chas {:name "PI:NAME:<NAME>END_PI" :age 31 :location "Johannesburg"})
(let [{:keys [name age location]} chas]
(format "%s is %s years old and lives in %s." name age location))
(def user-info ["PI:NAME:<NAME>END_PI" 2011 :name "PI:NAME:<NAME>END_PI" :city "Cape Town"])
(let [[username account-year & {:keys [name city]}] user-info]
(format "%s is in %s" username city))
(fn [x] (+ 10 x)) ;anoymous methods ... lambdas?
(def strange-adder
(fn adder-self-reference
([x] (adder-self-reference x 1))
([x y] (+ x y))))
(loop [x 5]
(if (neg? x)
x
(recur (dec x))))
(defn embedded-repl
[]
(print (str (ns-name *ns*) ">>> "))
(flush)
(let [expr (read)
value (eval expr)]
(when (not= :quit value)
(println value)
(recur))))
(defn call-twice [f x]
(f x)
(f x))
(def squared-up
(reduce
(fn [m v]
(assoc m v (* v v)))
{}
[ 1 2 3 4]))
(def only-strings (partial filter string?))
(only-strings ["a" 5 6 "b"])
(defn negated-sum-str
[& numbers]
(str (- (apply + numbers))))
(def negated-sum-str-2 (comp str - +))
(require '[clojure.string :as str])
;due to the \- this has to be copied to the repl and not run through
;the auto evaluate run thing
(def camel->keyword (comp keyword
str/join
(partial interpose \-)
(partial map str/lower-case)
#(str/split % #"(?<=[a-z])(?=[A-Z])")))
(camel->keyword "CamelCaseAndOtherCoolThings")
(camel->keyword2 "CamelCaseAndOtherCoolThings")
(defn camel->keyword2
[s]
(->> (str/split s #"(?<=[a-z])(?=[A-Z])")
(map str/lower-case)
(interpose \-)
str/join
keyword))
(def camel-pairs->map (comp (partial apply hash-map)
(partial map-indexed (fn [i x]
(if (odd? i)
x
(camel->keyword x))))))
(camel-pairs->map ["CamelCase" 5])
(defn adder
[n]
(fn [x] (+ n x)))
(defn doubler
[f]
(fn [& args]
(* 2 (apply f args))))
(def double-+ (doubler +))
|
[
{
"context": "e to run\n\n(def unknown-string (u/base64-to-byte' \"Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkgaGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBqdXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUgYnkK\"))\n\n#_\n(deftest break-ecb-simple-test\n (testing ",
"end": 1016,
"score": 0.9995996356010437,
"start": 832,
"tag": "KEY",
"value": "Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkgaGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBqdXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUgYnkK"
}
] | test/set2/break_ecb_harder_test.clj | milapsheth/Crypto-Challenges | 3 | (ns set2.break-ecb-harder-test
(:require [clojure.test :refer :all]
[set2.break-ecb-harder :as sut]
[util
[aes :as aes]
[random :as rand]
[tools :as u]]))
(def random-cipher-key (rand/byte-lst 16))
(def random-prefix (rand/byte-lst (rand/rand-num 32)))
(defn oracle-encrypt
[plaintext unknown-string]
(aes/encrypt (concat random-prefix plaintext unknown-string) random-cipher-key :ecb))
(deftest break-ecb-basic-test
(testing "Failed to break ECB mode on sample string"
(let [unknown-string (map int "MY UNKNOWN STRING")]
(is (= unknown-string
(sut/break-ecb #(oracle-encrypt % unknown-string)))))))
;; Actual challenge test
;; Not run as part of the suite as it takes a bit of time to run
(def unknown-string (u/base64-to-byte' "Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkgaGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBqdXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUgYnkK"))
#_
(deftest break-ecb-simple-test
(testing "Failed to break ECB mode(simple)"
(is (= unknown-string
(sut/break-ecb #(oracle-encrypt % unknown-string))))))
| 83069 | (ns set2.break-ecb-harder-test
(:require [clojure.test :refer :all]
[set2.break-ecb-harder :as sut]
[util
[aes :as aes]
[random :as rand]
[tools :as u]]))
(def random-cipher-key (rand/byte-lst 16))
(def random-prefix (rand/byte-lst (rand/rand-num 32)))
(defn oracle-encrypt
[plaintext unknown-string]
(aes/encrypt (concat random-prefix plaintext unknown-string) random-cipher-key :ecb))
(deftest break-ecb-basic-test
(testing "Failed to break ECB mode on sample string"
(let [unknown-string (map int "MY UNKNOWN STRING")]
(is (= unknown-string
(sut/break-ecb #(oracle-encrypt % unknown-string)))))))
;; Actual challenge test
;; Not run as part of the suite as it takes a bit of time to run
(def unknown-string (u/base64-to-byte' "<KEY>"))
#_
(deftest break-ecb-simple-test
(testing "Failed to break ECB mode(simple)"
(is (= unknown-string
(sut/break-ecb #(oracle-encrypt % unknown-string))))))
| true | (ns set2.break-ecb-harder-test
(:require [clojure.test :refer :all]
[set2.break-ecb-harder :as sut]
[util
[aes :as aes]
[random :as rand]
[tools :as u]]))
(def random-cipher-key (rand/byte-lst 16))
(def random-prefix (rand/byte-lst (rand/rand-num 32)))
(defn oracle-encrypt
[plaintext unknown-string]
(aes/encrypt (concat random-prefix plaintext unknown-string) random-cipher-key :ecb))
(deftest break-ecb-basic-test
(testing "Failed to break ECB mode on sample string"
(let [unknown-string (map int "MY UNKNOWN STRING")]
(is (= unknown-string
(sut/break-ecb #(oracle-encrypt % unknown-string)))))))
;; Actual challenge test
;; Not run as part of the suite as it takes a bit of time to run
(def unknown-string (u/base64-to-byte' "PI:KEY:<KEY>END_PI"))
#_
(deftest break-ecb-simple-test
(testing "Failed to break ECB mode(simple)"
(is (= unknown-string
(sut/break-ecb #(oracle-encrypt % unknown-string))))))
|
[
{
"context": "s :as combo]))\n\n;; data structures\n\n;; links\n;; [:Alice :Bob 54]\n;; [:Alice :Carol -79]\n\n;; neighbours\n;;",
"end": 156,
"score": 0.9509183764457703,
"start": 151,
"tag": "NAME",
"value": "Alice"
},
{
"context": "ombo]))\n\n;; data structures\n\n;; links\n;; [:Alice :Bob 54]\n;; [:Alice :Carol -79]\n\n;; neighbours\n;; [:Al",
"end": 161,
"score": 0.9846506714820862,
"start": 158,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ata structures\n\n;; links\n;; [:Alice :Bob 54]\n;; [:Alice :Carol -79]\n\n;; neighbours\n;; [:Alice :Bob]\n;; [:",
"end": 176,
"score": 0.9852404594421387,
"start": 171,
"tag": "NAME",
"value": "Alice"
},
{
"context": "uctures\n\n;; links\n;; [:Alice :Bob 54]\n;; [:Alice :Carol -79]\n\n;; neighbours\n;; [:Alice :Bob]\n;; [:Alice :",
"end": 183,
"score": 0.9991875290870667,
"start": 178,
"tag": "NAME",
"value": "Carol"
},
{
"context": "ob 54]\n;; [:Alice :Carol -79]\n\n;; neighbours\n;; [:Alice :Bob]\n;; [:Alice :David]\n\n;; normailised\n;; {:Ali",
"end": 214,
"score": 0.9593214392662048,
"start": 209,
"tag": "NAME",
"value": "Alice"
},
{
"context": ";; [:Alice :Carol -79]\n\n;; neighbours\n;; [:Alice :Bob]\n;; [:Alice :David]\n\n;; normailised\n;; {:Alice {:",
"end": 219,
"score": 0.9753987789154053,
"start": 216,
"tag": "NAME",
"value": "Bob"
},
{
"context": " :Carol -79]\n\n;; neighbours\n;; [:Alice :Bob]\n;; [:Alice :David]\n\n;; normailised\n;; {:Alice {:Bob 54, :Car",
"end": 231,
"score": 0.9733163714408875,
"start": 226,
"tag": "NAME",
"value": "Alice"
},
{
"context": " -79]\n\n;; neighbours\n;; [:Alice :Bob]\n;; [:Alice :David]\n\n;; normailised\n;; {:Alice {:Bob 54, :Carol -79}",
"end": 238,
"score": 0.9919302463531494,
"start": 233,
"tag": "NAME",
"value": "David"
},
{
"context": "ice :Bob]\n;; [:Alice :David]\n\n;; normailised\n;; {:Alice {:Bob 54, :Carol -79}, ...}\n\n;; seating arrangeme",
"end": 266,
"score": 0.9874384999275208,
"start": 261,
"tag": "NAME",
"value": "Alice"
},
{
"context": "]\n;; [:Alice :David]\n\n;; normailised\n;; {:Alice {:Bob 54, :Carol -79}, ...}\n\n;; seating arrangements\n;;",
"end": 272,
"score": 0.9971087574958801,
"start": 269,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ice :David]\n\n;; normailised\n;; {:Alice {:Bob 54, :Carol -79}, ...}\n\n;; seating arrangements\n;; wrap aroun",
"end": 283,
"score": 0.9991049766540527,
"start": 278,
"tag": "NAME",
"value": "Carol"
},
{
"context": "...}\n\n;; seating arrangements\n;; wrap around\n;; [:Alice :Bob :Carol :David]\n\n;; seating cost\n;; [{:cost 5",
"end": 345,
"score": 0.9907330274581909,
"start": 340,
"tag": "NAME",
"value": "Alice"
},
{
"context": "; seating arrangements\n;; wrap around\n;; [:Alice :Bob :Carol :David]\n\n;; seating cost\n;; [{:cost 55 :ar",
"end": 350,
"score": 0.9983152747154236,
"start": 347,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ting arrangements\n;; wrap around\n;; [:Alice :Bob :Carol :David]\n\n;; seating cost\n;; [{:cost 55 :arrangeme",
"end": 357,
"score": 0.9994428753852844,
"start": 352,
"tag": "NAME",
"value": "Carol"
},
{
"context": "rangements\n;; wrap around\n;; [:Alice :Bob :Carol :David]\n\n;; seating cost\n;; [{:cost 55 :arrangement [:Al",
"end": 364,
"score": 0.98548823595047,
"start": 359,
"tag": "NAME",
"value": "David"
},
{
"context": "id]\n\n;; seating cost\n;; [{:cost 55 :arrangement [:Alice :Bob :Carol :David]} ...]\n\n(defn neighbour-cost [",
"end": 417,
"score": 0.9976431131362915,
"start": 412,
"tag": "NAME",
"value": "Alice"
},
{
"context": " seating cost\n;; [{:cost 55 :arrangement [:Alice :Bob :Carol :David]} ...]\n\n(defn neighbour-cost [norma",
"end": 422,
"score": 0.9985144734382629,
"start": 419,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ing cost\n;; [{:cost 55 :arrangement [:Alice :Bob :Carol :David]} ...]\n\n(defn neighbour-cost [normalised n",
"end": 429,
"score": 0.9994512796401978,
"start": 424,
"tag": "NAME",
"value": "Carol"
},
{
"context": "t\n;; [{:cost 55 :arrangement [:Alice :Bob :Carol :David]} ...]\n\n(defn neighbour-cost [normalised neighbou",
"end": 436,
"score": 0.9955465793609619,
"start": 431,
"tag": "NAME",
"value": "David"
}
] | src/advent_of_code/day13/core.clj | bnomis/advent-of-code-2015 | 1 | (ns advent-of-code.day13.core
(:require
[clojure.string :as str]
[clojure.math.combinatorics :as combo]))
;; data structures
;; links
;; [:Alice :Bob 54]
;; [:Alice :Carol -79]
;; neighbours
;; [:Alice :Bob]
;; [:Alice :David]
;; normailised
;; {:Alice {:Bob 54, :Carol -79}, ...}
;; seating arrangements
;; wrap around
;; [:Alice :Bob :Carol :David]
;; seating cost
;; [{:cost 55 :arrangement [:Alice :Bob :Carol :David]} ...]
(defn neighbour-cost [normalised neighbour]
(get-in normalised neighbour))
(defn neighbours-in-arrangement [arrangement index]
(let [length (count arrangement)
center (nth arrangement index)
left (if (= index 0) (- length 1) (- index 1))
right (if (= index (- length 1)) 0 (+ index 1))]
[[center (nth arrangement left)] [center (nth arrangement right)]]))
(defn neighbours [arrangement]
(let [length (count arrangement)]
(loop [out []
index 0]
(if (> index (- length 1))
out
(recur (concat out (neighbours-in-arrangement arrangement index)) (inc index))))))
(defn arrangement-cost [normalised arrangement]
(reduce + (mapv #(neighbour-cost normalised %) (neighbours arrangement))))
(defn cost-arrangements [normalised arrangements]
;;(println "cost-arrangements:" arrangements)
(loop [out []
a (first arrangements)
arrangements (rest arrangements)]
(if-not a
out
(recur (conj out {:cost (arrangement-cost normalised a), :arrangement a}) (first arrangements) (rest arrangements)))))
(defn sort-arrangements [arrangements]
;;(println "sort-arrangements:" arrangements)
(sort-by :cost arrangements))
(defn guest-list [normalised]
;;(println "guest-list:" normalised)
(vec (keys normalised)))
(defn make-arrangements [guests]
;;(println "make-arrangements:" guests)
(vec (combo/permutations guests)))
(defn add-link [out [person1 person2 cost]]
(let [path [person1 person2]]
(assoc-in out path cost)))
(defn normalise-links [links]
;;(println "normalise-links:" links)
(loop [out {}
l (first links)
links (rest links)]
(if-not l
out
(recur (add-link out l) (first links) (rest links)))))
(defn remove-last-char [s]
(let [parts (vec (seq s))
length (count parts)]
(str/join (subvec parts 0 (- length 1)))))
(defn line->link [line]
(let [tokes (str/split line #" ")
person1 (keyword (get tokes 0))
person2 (keyword (remove-last-char (get tokes 10)))
cost (Integer/parseInt (get tokes 3))
sign (get tokes 2)
mult (if (= sign "gain") 1 -1)]
[person1 person2 (* mult cost)]))
(defn lines->links [lines]
(mapv line->link lines))
(defn read-links [file]
(let [input (slurp file)
lines (str/split input #"\n")]
(lines->links lines)))
(defn most-happy [sorted]
(last sorted))
(defn least-happy [sorted]
(first sorted))
(defn add-me-to-normalised [normalised]
(let [keys (keys normalised)]
(loop [out normalised
k (first keys)
keys (rest keys)]
(if-not k
out
(recur (-> out (assoc-in [k :Me] 0) (assoc-in [:Me k] 0)) (first keys) (rest keys))))))
(defn process-file [file]
(let [links (read-links file)
normalised (normalise-links links)
guests (guest-list normalised)
arrangements (make-arrangements guests)
costed (cost-arrangements normalised arrangements)
sorted (sort-arrangements costed)]
sorted))
(defn process-file-add-me [file]
(let [links (read-links file)
normalised (normalise-links links)
normalised (add-me-to-normalised normalised)
guests (guest-list normalised)
arrangements (make-arrangements guests)
costed (cost-arrangements normalised arrangements)
sorted (sort-arrangements costed)]
sorted))
(defn run []
(println "Day 13, part 1:" (:cost (most-happy (process-file "src/advent_of_code/day13/input.txt"))))
(println "Day 13, part 2:" (:cost (most-happy (process-file-add-me "src/advent_of_code/day13/input.txt")))))
| 96710 | (ns advent-of-code.day13.core
(:require
[clojure.string :as str]
[clojure.math.combinatorics :as combo]))
;; data structures
;; links
;; [:<NAME> :<NAME> 54]
;; [:<NAME> :<NAME> -79]
;; neighbours
;; [:<NAME> :<NAME>]
;; [:<NAME> :<NAME>]
;; normailised
;; {:<NAME> {:<NAME> 54, :<NAME> -79}, ...}
;; seating arrangements
;; wrap around
;; [:<NAME> :<NAME> :<NAME> :<NAME>]
;; seating cost
;; [{:cost 55 :arrangement [:<NAME> :<NAME> :<NAME> :<NAME>]} ...]
(defn neighbour-cost [normalised neighbour]
(get-in normalised neighbour))
(defn neighbours-in-arrangement [arrangement index]
(let [length (count arrangement)
center (nth arrangement index)
left (if (= index 0) (- length 1) (- index 1))
right (if (= index (- length 1)) 0 (+ index 1))]
[[center (nth arrangement left)] [center (nth arrangement right)]]))
(defn neighbours [arrangement]
(let [length (count arrangement)]
(loop [out []
index 0]
(if (> index (- length 1))
out
(recur (concat out (neighbours-in-arrangement arrangement index)) (inc index))))))
(defn arrangement-cost [normalised arrangement]
(reduce + (mapv #(neighbour-cost normalised %) (neighbours arrangement))))
(defn cost-arrangements [normalised arrangements]
;;(println "cost-arrangements:" arrangements)
(loop [out []
a (first arrangements)
arrangements (rest arrangements)]
(if-not a
out
(recur (conj out {:cost (arrangement-cost normalised a), :arrangement a}) (first arrangements) (rest arrangements)))))
(defn sort-arrangements [arrangements]
;;(println "sort-arrangements:" arrangements)
(sort-by :cost arrangements))
(defn guest-list [normalised]
;;(println "guest-list:" normalised)
(vec (keys normalised)))
(defn make-arrangements [guests]
;;(println "make-arrangements:" guests)
(vec (combo/permutations guests)))
(defn add-link [out [person1 person2 cost]]
(let [path [person1 person2]]
(assoc-in out path cost)))
(defn normalise-links [links]
;;(println "normalise-links:" links)
(loop [out {}
l (first links)
links (rest links)]
(if-not l
out
(recur (add-link out l) (first links) (rest links)))))
(defn remove-last-char [s]
(let [parts (vec (seq s))
length (count parts)]
(str/join (subvec parts 0 (- length 1)))))
(defn line->link [line]
(let [tokes (str/split line #" ")
person1 (keyword (get tokes 0))
person2 (keyword (remove-last-char (get tokes 10)))
cost (Integer/parseInt (get tokes 3))
sign (get tokes 2)
mult (if (= sign "gain") 1 -1)]
[person1 person2 (* mult cost)]))
(defn lines->links [lines]
(mapv line->link lines))
(defn read-links [file]
(let [input (slurp file)
lines (str/split input #"\n")]
(lines->links lines)))
(defn most-happy [sorted]
(last sorted))
(defn least-happy [sorted]
(first sorted))
(defn add-me-to-normalised [normalised]
(let [keys (keys normalised)]
(loop [out normalised
k (first keys)
keys (rest keys)]
(if-not k
out
(recur (-> out (assoc-in [k :Me] 0) (assoc-in [:Me k] 0)) (first keys) (rest keys))))))
(defn process-file [file]
(let [links (read-links file)
normalised (normalise-links links)
guests (guest-list normalised)
arrangements (make-arrangements guests)
costed (cost-arrangements normalised arrangements)
sorted (sort-arrangements costed)]
sorted))
(defn process-file-add-me [file]
(let [links (read-links file)
normalised (normalise-links links)
normalised (add-me-to-normalised normalised)
guests (guest-list normalised)
arrangements (make-arrangements guests)
costed (cost-arrangements normalised arrangements)
sorted (sort-arrangements costed)]
sorted))
(defn run []
(println "Day 13, part 1:" (:cost (most-happy (process-file "src/advent_of_code/day13/input.txt"))))
(println "Day 13, part 2:" (:cost (most-happy (process-file-add-me "src/advent_of_code/day13/input.txt")))))
| true | (ns advent-of-code.day13.core
(:require
[clojure.string :as str]
[clojure.math.combinatorics :as combo]))
;; data structures
;; links
;; [:PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI 54]
;; [:PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI -79]
;; neighbours
;; [:PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI]
;; [:PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI]
;; normailised
;; {:PI:NAME:<NAME>END_PI {:PI:NAME:<NAME>END_PI 54, :PI:NAME:<NAME>END_PI -79}, ...}
;; seating arrangements
;; wrap around
;; [:PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI]
;; seating cost
;; [{:cost 55 :arrangement [:PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI]} ...]
(defn neighbour-cost [normalised neighbour]
(get-in normalised neighbour))
(defn neighbours-in-arrangement [arrangement index]
(let [length (count arrangement)
center (nth arrangement index)
left (if (= index 0) (- length 1) (- index 1))
right (if (= index (- length 1)) 0 (+ index 1))]
[[center (nth arrangement left)] [center (nth arrangement right)]]))
(defn neighbours [arrangement]
(let [length (count arrangement)]
(loop [out []
index 0]
(if (> index (- length 1))
out
(recur (concat out (neighbours-in-arrangement arrangement index)) (inc index))))))
(defn arrangement-cost [normalised arrangement]
(reduce + (mapv #(neighbour-cost normalised %) (neighbours arrangement))))
(defn cost-arrangements [normalised arrangements]
;;(println "cost-arrangements:" arrangements)
(loop [out []
a (first arrangements)
arrangements (rest arrangements)]
(if-not a
out
(recur (conj out {:cost (arrangement-cost normalised a), :arrangement a}) (first arrangements) (rest arrangements)))))
(defn sort-arrangements [arrangements]
;;(println "sort-arrangements:" arrangements)
(sort-by :cost arrangements))
(defn guest-list [normalised]
;;(println "guest-list:" normalised)
(vec (keys normalised)))
(defn make-arrangements [guests]
;;(println "make-arrangements:" guests)
(vec (combo/permutations guests)))
(defn add-link [out [person1 person2 cost]]
(let [path [person1 person2]]
(assoc-in out path cost)))
(defn normalise-links [links]
;;(println "normalise-links:" links)
(loop [out {}
l (first links)
links (rest links)]
(if-not l
out
(recur (add-link out l) (first links) (rest links)))))
(defn remove-last-char [s]
(let [parts (vec (seq s))
length (count parts)]
(str/join (subvec parts 0 (- length 1)))))
(defn line->link [line]
(let [tokes (str/split line #" ")
person1 (keyword (get tokes 0))
person2 (keyword (remove-last-char (get tokes 10)))
cost (Integer/parseInt (get tokes 3))
sign (get tokes 2)
mult (if (= sign "gain") 1 -1)]
[person1 person2 (* mult cost)]))
(defn lines->links [lines]
(mapv line->link lines))
(defn read-links [file]
(let [input (slurp file)
lines (str/split input #"\n")]
(lines->links lines)))
(defn most-happy [sorted]
(last sorted))
(defn least-happy [sorted]
(first sorted))
(defn add-me-to-normalised [normalised]
(let [keys (keys normalised)]
(loop [out normalised
k (first keys)
keys (rest keys)]
(if-not k
out
(recur (-> out (assoc-in [k :Me] 0) (assoc-in [:Me k] 0)) (first keys) (rest keys))))))
(defn process-file [file]
(let [links (read-links file)
normalised (normalise-links links)
guests (guest-list normalised)
arrangements (make-arrangements guests)
costed (cost-arrangements normalised arrangements)
sorted (sort-arrangements costed)]
sorted))
(defn process-file-add-me [file]
(let [links (read-links file)
normalised (normalise-links links)
normalised (add-me-to-normalised normalised)
guests (guest-list normalised)
arrangements (make-arrangements guests)
costed (cost-arrangements normalised arrangements)
sorted (sort-arrangements costed)]
sorted))
(defn run []
(println "Day 13, part 1:" (:cost (most-happy (process-file "src/advent_of_code/day13/input.txt"))))
(println "Day 13, part 2:" (:cost (most-happy (process-file-add-me "src/advent_of_code/day13/input.txt")))))
|
[
{
"context": "wap! s assoc\n :title (str (:username user) \"'s game\")\n :side side\n ",
"end": 4221,
"score": 0.5370170474052429,
"start": 4217,
"tag": "USERNAME",
"value": "user"
},
{
"context": " [:div.username (get-in msg [:user :username])]\n [:div (:text msg",
"end": 12248,
"score": 0.9643850326538086,
"start": 12240,
"tag": "USERNAME",
"value": "username"
},
{
"context": "isible #(or (contains? (get % :players) (:username user))\n (hidden-formats visib",
"end": 13098,
"score": 0.989686906337738,
"start": 13094,
"tag": "USERNAME",
"value": "user"
},
{
"context": "w the old \"competitive\" lobby just got renamed. -- lostgeek, 9th August 2021\n ;\n ; [room-tab user s g",
"end": 17136,
"score": 0.9895450472831726,
"start": 17128,
"tag": "USERNAME",
"value": "lostgeek"
},
{
"context": " :placeholder (tr [:lobby.password \"Password\"])\n :maxLength \"30",
"end": 22967,
"score": 0.9973589777946472,
"start": 22959,
"tag": "PASSWORD",
"value": "Password"
},
{
"context": "iv.button-bar\n (when (first-user? players @user)\n [cond-button\n (tr [:lobby.st",
"end": 26081,
"score": 0.5596053600311279,
"start": 26077,
"tag": "USERNAME",
"value": "user"
},
{
"context": "ve \"Leave\"])]\n (when (first-user? players @user)\n (if (> (count players) 1)\n ",
"end": 26349,
"score": 0.7021838426589966,
"start": 26345,
"tag": "USERNAME",
"value": "user"
}
] | src/cljs/nr/gamelobby.cljs | kjchiu/netrunner | 0 | (ns nr.gamelobby
(:require-macros [cljs.core.async.macros :refer [go]])
(:require
[cljs.core.async :refer [<!] :as async]
[clojure.set :refer [difference union]]
[differ.core :as differ]
[jinteki.utils :refer [str->int]]
[jinteki.validator :refer [trusted-deck-status]]
[nr.ajax :refer [GET]]
[nr.angel-arena :as angel-arena]
[nr.appstate :refer [app-state]]
[nr.auth :refer [authenticated] :as auth]
[nr.avatar :refer [avatar]]
[nr.cardbrowser :refer [image-url] :as cb]
[nr.deck-status :refer [deck-format-status-span]]
[nr.deckbuilder :refer [deck-name]]
[nr.game-row :refer [game-row]]
[nr.gameboard.actions :refer [launch-game]]
[nr.gameboard.state :refer [game-state parse-state]]
[nr.player-view :refer [player-view]]
[nr.sounds :refer [play-sound resume-sound]]
[nr.translations :refer [tr tr-format tr-side]]
[nr.utils :refer [cond-button non-game-toast slug->format]]
[nr.ws :as ws]
[reagent-modals.modals :as reagent-modals]
[reagent.core :as r]))
(def lobby-dom (atom {}))
(defn sort-games-list [games]
(sort-by (fn [game]
[(when-let [players (:players game)]
(not (some (fn [p]
(= (get-in p [:user :_id])
(get-in @app-state [:user :_id])))
players)))
(:started game)
(:date game)])
games))
(defn process-games-update
[{:keys [diff notification]}]
(swap! app-state update :games
(fn [games]
(let [gamemap (into {} (map #(assoc {} (:gameid %) %) games))
update-diff (reduce-kv
(fn [m k v]
; spectators is nil on the client but not the API, confusing differ which expects an empty set
(assoc m k (merge {:spectators '()} (get m k {}) v)))
gamemap
(:update diff))
delete-diff (apply dissoc update-diff (:delete diff))]
(sort-games-list (vals delete-diff)))))
(when-let [current-game (first (filter :selected (:games @app-state)))]
(swap! app-state update :gameid #(:gameid current-game)))
(when (and notification (not (:gameid @app-state)))
(play-sound notification)))
(defmethod ws/-msg-handler :games/list [{data :?data}]
(let [gamemap (into {} (for [d data] [(:gameid d) d]))
missing-gameids (->> (:games @app-state)
(remove #(get gamemap (:gameid %)))
(map :gameid))]
(process-games-update {:diff {:update gamemap
:delete missing-gameids}})))
(defmethod ws/-msg-handler :games/diff [{data :?data}]
(process-games-update data))
(defmethod ws/-msg-handler :games/differ
[{{:keys [diff]} :?data}]
(swap! app-state update :games
(fn [games]
(let [gamemap (into {} (map #(assoc {} (:gameid %) %) games))
update-diff (reduce-kv
(fn [m k v]
(assoc m k (reduce #(differ/patch %1 %2) (get m k {}) v)))
gamemap
(:update diff))]
(sort-games-list (vals update-diff))))))
(defmethod ws/-msg-handler :lobby/select
[{{:keys [gameid started state]} :?data}]
(swap! app-state assoc :gameid gameid)
(reset! angel-arena/queueing false)
(when started
(launch-game (parse-state state))))
(defmethod ws/-msg-handler :lobby/notification [{data :?data}] (play-sound data))
(defmethod ws/-msg-handler :lobby/timeout
[{{:keys [gameid]} :?data}]
(when (= gameid (:gameid @app-state))
(non-game-toast (tr [:lobby.closed-msg "Game lobby closed due to inactivity"]) "error" {:time-out 0 :close-button true})
(swap! app-state assoc :gameid nil)))
(defn new-game [s]
(authenticated
(fn [user]
(let [fmt (:format (:create-game-deck @app-state) "standard")
side (:side (:identity (:create-game-deck @app-state)) "Any Side")]
(swap! s assoc
:title (str (:username user) "'s game")
:side side
:format fmt
:editing true
:replay false
:save-replay (if (= "casual" (:room @s)) false true)
:api-access false
:flash-message ""
:protected false
:password ""
:timed false
:timer nil
:allow-spectator true
:spectatorhands false
:create-game-deck (:create-game-deck @app-state))
(swap! app-state assoc :editing-game true)
(swap! app-state dissoc :create-game-deck)
(-> ".game-title" js/$ .select)))))
(defn replay-game [s]
(authenticated
(fn [user]
(swap! s assoc
:gameid "local-replay"
:title (str (:username user) "'s game")
:side "Corp"
:format "standard"
:editing true
:replay true
:flash-message ""
:protected false
:password ""
:allow-spectator true
:spectatorhands true))))
(defn start-shared-replay
([s gameid]
(start-shared-replay s gameid nil))
([s gameid jump-to]
(authenticated
(fn [user]
(swap! s assoc
:title (str (:username user) "'s game")
:side "Corp"
:format "standard"
:editing false
:replay true
:flash-message ""
:protected false
:password ""
:allow-spectator true
:spectatorhands true)
(go (let [{:keys [status json]} (<! (GET (str "/profile/history/full/" gameid)))]
(case status
200
(let [replay (js->clj json :keywordize-keys true)
history (:history replay)
init-state (first history)
init-state (assoc init-state :gameid gameid)
init-state (assoc-in init-state [:options :spectatorhands] true)
diffs (rest history)
init-state (assoc init-state :replay-diffs diffs)]
(ws/event-msg-handler
{:id :netrunner/start
:?data (.stringify js/JSON (clj->js
(if jump-to
(assoc init-state :replay-jump-to jump-to)
init-state)))}))
404
(non-game-toast (tr [:lobby.replay-link-error "Replay link invalid."])
"error" {:time-out 0 :close-button true}))))))))
(defn start-replay [s]
(let [reader (js/FileReader.)
file (:replay-file s)
onload (fn [onload-ev] (let [replay (-> onload-ev .-target .-result)
replay (js->clj (.parse js/JSON replay) :keywordize-keys true)
history (:history replay)
init-state (first history)
init-state (assoc-in init-state [:options :spectatorhands] true)
diffs (rest history)
init-state (assoc init-state :replay-diffs diffs :gameid "local-replay")]
(ws/event-msg-handler
{:id :netrunner/start
:?data (.stringify js/JSON (clj->js init-state))})))]
(aset reader "onload" onload)
(.readAsText reader file)))
(defn create-game [s]
(authenticated
(fn [_]
(if (:replay @s)
(cond
(not (:replay-file @s))
(swap! s assoc :flash-message (tr [:lobby.replay-invalid-file "Select a valid replay file."]))
:else
(do (swap! s assoc :editing false)
(start-replay @s)))
(cond
(empty? (:title @s))
(swap! s assoc :flash-message (tr [:lobby.title-error "Please fill a game title."]))
(and (:protected @s)
(empty? (:password @s)))
(swap! s assoc :flash-message (tr [:lobby.password-error "Please fill a password."]))
:else
(do (swap! s assoc :editing false)
(swap! app-state dissoc :editing-game)
(ws/ws-send! [:lobby/create
(select-keys @s [:title :password :allow-spectator :save-replay
:spectatorhands :side :format :room :timer :api-access])])))))))
(defn leave-lobby [s]
(ws/ws-send! [:lobby/leave])
(swap! app-state assoc :gameid nil :message [] :password-gameid nil)
(swap! s assoc :prompt false))
(defn leave-game []
(ws/ws-send! [:netrunner/leave {:gameid-str (:gameid @game-state)}])
(reset! game-state nil)
(swap! app-state dissoc :gameid :side :password-gameid :win-shown :start-shown)
(set! (.-cursor (.-style (.-body js/document))) "default")
(.removeItem js/localStorage "gameid")
(set! (.-onbeforeunload js/window) nil)
(-> "#gameboard" js/$ .fadeOut)
(-> "#gamelobby" js/$ .fadeIn))
(defn deckselect-modal [user {:keys [gameid games decks format]}]
[:div
[:h3 (tr [:lobby.select-title "Select your deck"])]
[:div.deck-collection.lobby-deck-selector
(let [players (:players (some #(when (= (:gameid %) @gameid) %) @games))
side (:side (some #(when (= (-> % :user :_id) (:_id @user)) %) players))
same-side? (fn [deck] (= side (get-in deck [:identity :side])))
legal? (fn [deck] (get-in deck
[:status (keyword format) :legal]
(get-in (trusted-deck-status (assoc deck :format format))
[(keyword format) :legal]
false)))]
[:div
(doall
(for [deck (->> @decks
(filter same-side?)
(sort-by (juxt legal? :date) >))]
^{:key (:_id deck)}
[:div.deckline {:on-click #(do (ws/ws-send! [:lobby/deck (:_id deck)])
(reagent-modals/close-modal!))}
[:img {:src (image-url (:identity deck))
:alt (get-in deck [:identity :title] "")}]
[:div.float-right [deck-format-status-span deck format true]]
[:h4 (:name deck)]
[:div.float-right (-> (:date deck) js/Date. js/moment (.format "MMM Do YYYY"))]
[:p (get-in deck [:identity :title])]]))])]])
(defn send-msg [s]
(let [text (:msg @s)]
(when-not (empty? text)
(ws/ws-send! [:lobby/say {:gameid (:gameid @app-state)
:msg text}])
(let [msg-list (:message-list @lobby-dom)]
(set! (.-scrollTop msg-list) (+ (.-scrollHeight msg-list) 500)))
(swap! s assoc :msg ""))))
(defn chat-view []
(let [s (r/atom {})]
(r/create-class
{:display-name "chat-view"
:component-did-update
(fn []
(let [msg-list (:message-list @lobby-dom)
height (.-scrollHeight msg-list)]
(when (< (- height (.-scrollTop msg-list) (.height (js/$ ".lobby .chat-box"))) 500)
(set! (.-scrollTop msg-list) (.-scrollHeight msg-list)))))
:reagent-render
(fn [game]
[:div.chat-box
[:h3 (tr [:lobby.chat "Chat"])]
[:div.message-list {:ref #(swap! lobby-dom assoc :message-list %)}
(map-indexed (fn [i msg]
(if (= (:user msg) "__system__")
^{:key i}
[:div.system (:text msg)]
^{:key i}
[:div.message
[avatar (:user msg) {:opts {:size 38}}]
[:div.content
[:div.username (get-in msg [:user :username])]
[:div (:text msg)]]]))
(:messages game))]
[:div
[:form.msg-box {:on-submit #(do (.preventDefault %)
(send-msg s))}
[:input {:placeholder (tr [:chat.placeholder "Say something"])
:type "text"
:value (:msg @s)
:on-change #(swap! s assoc :msg (-> % .-target .-value))}]
[:button (tr [:chat.send "Send"])]]]])})))
(defn- hidden-formats
"Remove games which the user has opted to hide"
[visible-formats game]
(contains? visible-formats (get game :format)))
(defn filter-blocked-games
[user games visible-formats]
(if (= "tournament" (:room (first games)))
games
(let [is-visible #(or (contains? (get % :players) (:username user))
(hidden-formats visible-formats %))]
(filter is-visible games))))
(def open-games-symbol "○")
(def closed-games-symbol "●")
(defn room-count-str [open-count closed-count]
(str " (" @open-count open-games-symbol " " @closed-count closed-games-symbol ")"))
(defn- room-tab
"Creates the room tab for the specified room"
[s games room room-name]
(r/with-let [room-games (r/track (fn [] (filter #(= room (:room %)) @games)))
closed-count (r/track (fn [] (count (filter #(:started %) @room-games))))
open-count (r/track (fn [] (- (count @room-games) @closed-count)))]
[:div.roomtab
(if (= room (:room @s))
{:class "current"}
{:on-click #(swap! s assoc :room room)})
room-name (room-count-str open-count closed-count)]))
(defn- first-user?
"Is this user the first user in the game?"
[players user]
(= (-> players first :user :_id) (:_id user)))
(defn game-list [{:keys [room games gameid password-game editing]}]
(let [room-games (r/track (fn [] (filter #(= (:room %) room) @games)))
is-filtered? (not= (count slug->format) (count (:visible-formats @app-state)))
n (count @room-games)
game-count-str (tr [:lobby.game-count] n)]
[:<>
[:div.game-count
[:h4 (str game-count-str (when is-filtered? (str " " (tr [:lobby.filtered "(filtered)"]))))]]
[:div.game-list
(if (empty? @room-games)
[:h4 (tr [:lobby.no-games "No games"])]
(doall
(for [game @room-games]
^{:key (:gameid game)}
[game-row (assoc game :current-game @gameid :password-game password-game :editing editing)])))]]))
(defn format-visible? [slug] (contains? (:visible-formats @app-state) slug))
(defn- on-change-format-visibility
"Handle change event for format-toggle input"
[slug evt]
(.preventDefault evt)
(if (format-visible? slug)
(swap! app-state update-in [:visible-formats] difference #{slug})
(swap! app-state update-in [:visible-formats] union #{slug}))
(.setItem js/localStorage "visible-formats" (.stringify js/JSON (clj->js (:visible-formats @app-state)))))
(defn format-toggle [slug]
(r/with-let [id (str "filter-" slug)]
[:div
[:input.visible-formats {:id id
:type "checkbox"
:on-change (partial on-change-format-visibility slug)
:checked (format-visible? slug)}]
[:label {:for id} (-> slug slug->format tr-format)]]))
(defn games-list-panel [s games gameid password-gameid user visible-formats]
[:div.games
(when-let [params (:replay-id @app-state)]
(swap! app-state dissoc :replay-id)
(let [bug-report? (re-find #"bug-report" params)
id-match (re-find #"([0-9a-f\-]+)" params)
n-match (re-find #"n=(\d+)" params)
d-match (re-find #"d=(\d+)" params)
b-match (re-find #"b=(\d+)" params)
replay-id (nth id-match 1)
n (when n-match (js/parseInt (nth n-match 1)))
d (when d-match (js/parseInt (nth d-match 1)))
b (when b-match (js/parseInt (nth b-match 1)))]
(when replay-id
(.replaceState (.-history js/window) {} "" "/play") ; remove query parameters from url
(if bug-report?
(start-shared-replay s replay-id {:bug (or b 0)})
(if (and n d)
(start-shared-replay s replay-id {:n n :d d})
(start-shared-replay s replay-id nil)))
(resume-sound)
nil)))
[:div.button-bar
[:div.rooms
[:div#filter.dropdown
[:a.dropdown-toggle {:href "" :data-toggle "dropdown"}
"Filter"
[:b.caret]]
[:div.dropdown-menu.blue-shade
(doall (for [[k] slug->format]
^{:key k}
[format-toggle k (contains? visible-formats k)]))]]
; The real "tournament" lobby can be reenabled, once its functionality is complete. For now the old "competitive" lobby just got renamed. -- lostgeek, 9th August 2021
;
; [room-tab user s games "tournament" (tr [:lobby.tournament "Tournament"])]
; [room-tab user s games "competitive" (tr [:lobby.competitive "Competitive"])]
[room-tab s games "casual" (tr [:lobby.casual "Casual"])]
[room-tab s games "angel-arena" (tr [:lobby.angel-arena "Angel Arena"])]
[room-tab s games "competitive" (tr [:lobby.tournament "Tournament"])]]
(when (not= "angel-arena" (:room @s))
[:div.lobby-buttons
[cond-button (tr [:lobby.new-game "New game"])
(and (not (or @gameid
(:editing @s)
(= "tournament" (:room @s))))
(->> @games
(mapcat :players)
(filter #(= (-> % :user :_id) (:_id @user)))
empty?))
#(do (new-game s)
(resume-sound))]
[:button.reload-button {:type "button"
:on-click #(ws/ws-send! [:lobby/list])} (tr [:lobby.reload "Reload list"])]
[cond-button (tr [:lobby.load-replay "Load replay"])
(and (not (or @gameid
(:editing @s)
(= "tournament" (:room @s))))
(->> @games
(mapcat :players)
(filter #(= (-> % :user :_id) (:_id @user)))
empty?))
#(do (replay-game s)
(resume-sound))]])]
(case (:room @s)
"angel-arena"
[angel-arena/game-list user {:games games
:gameid gameid
:room (:room @s)}]
(let [password-game (some #(when (= @password-gameid (:gameid %)) %) @games)]
[game-list {:password-game password-game
:editing (:editing @s)
:games games
:gameid gameid
:room (:room @s)}]))])
(defn create-new-game
[s user]
(when (:editing @s)
(if (:replay @s)
[:div
[:div.button-bar
[:button {:type "button"
:on-click #(create-game s)} (tr [:lobby.start-replay "Start replay"])]
[:button {:type "button"
:on-click #(do
(swap! s assoc :editing false)
(swap! app-state dissoc :editing-game))}
(tr [:lobby.cancel "Cancel"])]]
(when-let [flash-message (:flash-message @s)]
[:p.flash-message flash-message])
[:div [:input {:field :file
:type :file
:on-change #(swap! s assoc :replay-file (aget (.. % -target -files) 0))}]]]
[:div
[:div.button-bar
[:button {:type "button"
:on-click #(create-game s)} (tr [:lobby.create "Create"])]
[:button {:type "button"
:on-click #(swap! s assoc :editing false)} (tr [:lobby.cancel "Cancel"])]]
(when-let [flash-message (:flash-message @s)]
[:p.flash-message flash-message])
[:div.content
[:section
[:h3 (tr [:lobby.title "Title"])]
[:input.game-title {:on-change #(swap! s assoc :title (.. % -target -value))
:value (:title @s)
:placeholder (tr [:lobby.title "Title"])
:maxLength "100"}]]
[:section
[:h3 (tr [:lobby.side "Side"])]
(doall
(for [option ["Any Side" "Corp" "Runner"]]
^{:key option}
[:p
[:label [:input {:type "radio"
:name "side"
:value option
:on-change #(swap! s assoc :side (.. % -target -value))
:checked (= (:side @s) option)}]
(tr-side option)]]))]
[:section
[:h3 (tr [:lobby.format "Format"])]
[:select.format {:value (:format @s "standard")
:on-change #(swap! s assoc :format (.. % -target -value))}
(doall (for [[k v] slug->format]
^{:key k}
[:option {:value k} (tr-format v)]))]]
[:section
[:h3 (tr [:lobby.options "Options"])]
[:p
[:label
[:input {:type "checkbox" :checked (:allow-spectator @s)
:on-change #(swap! s assoc :allow-spectator (.. % -target -checked))}]
(tr [:lobby.spectators "Allow spectators"])]]
[:p
[:label
[:input {:type "checkbox" :checked (:spectatorhands @s)
:on-change #(swap! s assoc :spectatorhands (.. % -target -checked))
:disabled (not (:allow-spectator @s))}]
(tr [:lobby.hidden "Make players' hidden information visible to spectators"])]]
[:div.infobox.blue-shade {:style {:display (if (:spectatorhands @s) "block" "none")}}
[:p "This will reveal both players' hidden information to ALL spectators of your game, "
"including hand and face-down cards."]
[:p "We recommend using a password to prevent strangers from spoiling the game."]]
[:p
[:label
[:input {:type "checkbox" :checked (:private @s)
:on-change #(let [checked (.. % -target -checked)]
(swap! s assoc :protected checked)
(when (not checked) (swap! s assoc :password "")))}]
(tr [:lobby.password-protected "Password protected"])]]
(when (:protected @s)
[:p
[:input.game-title {:on-change #(swap! s assoc :password (.. % -target -value))
:type "password"
:value (:password @s)
:placeholder (tr [:lobby.password "Password"])
:maxLength "30"}]])
(when-not (= "casual" (:room @s))
[:p
[:label
[:input {:type "checkbox" :checked (:timed @s)
:on-change #(let [checked (.. % -target -checked)]
(swap! s assoc :timed checked)
(swap! s assoc :timer (if checked 35 nil)))}]
(tr [:lobby.timed-game "Start with timer"])]])
(when (:timed @s)
[:p
[:input.game-title {:on-change #(swap! s assoc :timer (-> % (.. -target -value) str->int))
:type "number"
:value (:timer @s)
:placeholder (tr [:lobby.timer-length "Timer length (minutes)"])}]])
[:div.infobox.blue-shade {:style {:display (if (:timed @s) "block" "none")}}
[:p "Timer is only for convenience: the game will not stop when timer runs out."]]
[:p
[:label
[:input {:type "checkbox" :checked (:save-replay @s)
:on-change #(swap! s assoc :save-replay (.. % -target -checked))}]
(str "🟢 " (tr [:lobby.save-replay "Save replay"]))]]
[:div.infobox.blue-shade {:style {:display (if (:save-replay @s) "block" "none")}}
[:p "This will save a replay file of this match with open information (e.g. open cards in hand)."
" The file is available only after the game is finished."]
[:p "Only your latest 15 unshared games will be kept, so make sure to either download or share the match afterwards."]
[:p [:b "BETA Functionality:"] " Be aware that we might need to reset the saved replays, so " [:b "make sure to download games you want to keep."]
" Also, please keep in mind that we might need to do future changes to the site that might make replays incompatible."]]
(let [has-keys (:has-api-keys @user false)]
[:p
[:label
[:input {:disabled (not has-keys)
:type "checkbox" :checked (:api-access @s)
:on-change #(swap! s assoc :api-access (.. % -target -checked))}]
(tr [:lobby.api-access "Allow API access to game information"])
(when (not has-keys)
(str " " (tr [:lobby.api-requires-key "(Requires an API Key in Settings)"])))]])
[:div.infobox.blue-shade {:style {:display (if (:api-access @s) "block" "none")}}
[:p "This allows access to information about your game to 3rd party extensions. Requires an API Key to be created in Settings"]]]]])))
(defn pending-game
[s decks games gameid sets user]
(let [game (some #(when (= @gameid (:gameid %)) %) @games)
players (:players game)]
(when game
(when-let [create-deck (:create-game-deck @s)]
(ws/ws-send! [:lobby/deck (:_id create-deck)])
(swap! app-state dissoc :create-game-deck)
(swap! s dissoc :create-game-deck))
[:div
[:div.button-bar
(when (first-user? players @user)
[cond-button
(tr [:lobby.start "Start"])
(every? :deck players)
#(ws/ws-send! [:netrunner/start @gameid])])
[:button {:on-click #(leave-lobby s)} (tr [:lobby.leave "Leave"])]
(when (first-user? players @user)
(if (> (count players) 1)
[:button {:on-click #(ws/ws-send! [:lobby/swap {:gameid @gameid}])}
(tr [:lobby.swap "Swap sides"])]
[:div.dropdown
[:button.dropdown-toggle {:data-toggle "dropdown"}
(tr [:lobby.swap "Swap sides"])
[:b.caret]]
[:ul.dropdown-menu.blue-shade
[:a.block-link {:on-click #(ws/ws-send! [:lobby/swap {:gameid @gameid
:side "Any Side"} ])}
(tr-side "Any Side")]
[:a.block-link {:on-click #(ws/ws-send! [:lobby/swap {:gameid @gameid
:side "Corp"}])}
(tr-side "Corp")]
[:a.block-link {:on-click #(ws/ws-send! [:lobby/swap {:gameid @gameid
:side "Runner"}])}
(tr-side "Runner")]]]))]
[:div.content
[:h2 (:title game)]
(when-not (every? :deck players)
[:div.flash-message (tr [:lobby.waiting "Waiting players deck selection"])])
[:h3 (tr [:lobby.players "Players"])]
[:div.players
(doall
(map-indexed
(fn [idx player]
(let [player-id (get-in player [:user :_id])
this-player (= player-id (:_id @user))]
^{:key (or player-id idx)}
[:div
[player-view player game]
(when-let [{:keys [status]} (:deck player)]
[:span {:class (:status status)}
[:span.label
(if this-player
(deck-name (:deck player) 25)
(tr [:lobby.deck-selected "Deck selected"]))]])
(when-let [deck (:deck player)]
[:div.float-right [deck-format-status-span deck (:format game "standard") true]])
(when (and this-player (not (= (:side player) (tr-side "Any Side"))))
[:span.fake-link.deck-load
{:on-click #(reagent-modals/modal!
[deckselect-modal user {:games games :gameid gameid
:sets sets :decks decks
:format (:format game "standard")}])}
(tr [:lobby.select-deck "Select Deck"])])]))
players))]
[:h3 (tr [:lobby.options "Options"])]
[:ul.options
(when (:allow-spectator game)
[:li (tr [:lobby.spectators "Allow spectators"])])
(when (:timer game)
[:li "Game timer set for " (:timer game) " minutes"])
(when (:spectatorhands game)
[:li (tr [:lobby.hidden "Make players' hidden information visible to spectators"])])
(when (:password game)
[:li (tr [:lobby.password-protected "Password protected"])])
(when (:save-replay game)
[:li (str "🟢 " (tr [:lobby.save-replay "Save replay"]))])
(when (:save-replay game)
[:div.infobox.blue-shade {:style {:display (if (:save-replay @s) "block" "none")}}
[:p "This will save a replay file of this match with open information (e.g. open cards in hand)."
" The file is available only after the game is finished."]
[:p "Only your latest 15 unshared games will be kept, so make sure to either download or share the match afterwards."]
[:p [:b "BETA Functionality:"] " Be aware that we might need to reset the saved replays, so " [:b "make sure to download games you want to keep."]
" Also, please keep in mind that we might need to do future changes to the site that might make replays incompatible."]])
(when (:api-access game)
[:li (tr [:lobby.api-access "Allow API access to game information"])])]
(when (:allow-spectator game)
[:div.spectators
(let [c (:spectator-count game)]
[:h3 (tr [:lobby.spectator-count "Spectators"] c)])
(for [spectator (:spectators game)
:let [_id (get-in spectator [:user :_id])]]
^{:key _id}
[player-view spectator])])
[chat-view game]]])))
(defn right-panel
[decks s games gameid sets user]
(if (= "angel-arena" (:room @s))
[angel-arena/game-panel decks s user]
[:div.game-panel
[create-new-game s user]
[pending-game s decks games gameid sets user]]))
(defn game-lobby []
(r/with-let [s (r/atom {:room "casual"})
decks (r/cursor app-state [:decks])
games (r/cursor app-state [:games])
gameid (r/cursor app-state [:gameid])
password-gameid (r/cursor app-state [:password-gameid])
sets (r/cursor app-state [:sets])
user (r/cursor app-state [:user])
cards-loaded (r/cursor app-state [:cards-loaded])
active (r/cursor app-state [:active-page])
visible-formats (r/cursor app-state [:visible-formats])]
[:div.container
[:div.lobby-bg]
(when (and (= "/play" (first @active)) @cards-loaded)
(authenticated (fn [_] nil))
(when (and (not (or @gameid (:editing @s)))
(some? (:create-game-deck @app-state)))
(new-game s))
[:div.lobby.panel.blue-shade
[games-list-panel s games gameid password-gameid user visible-formats]
[right-panel decks s games gameid sets user]])]))
| 101856 | (ns nr.gamelobby
(:require-macros [cljs.core.async.macros :refer [go]])
(:require
[cljs.core.async :refer [<!] :as async]
[clojure.set :refer [difference union]]
[differ.core :as differ]
[jinteki.utils :refer [str->int]]
[jinteki.validator :refer [trusted-deck-status]]
[nr.ajax :refer [GET]]
[nr.angel-arena :as angel-arena]
[nr.appstate :refer [app-state]]
[nr.auth :refer [authenticated] :as auth]
[nr.avatar :refer [avatar]]
[nr.cardbrowser :refer [image-url] :as cb]
[nr.deck-status :refer [deck-format-status-span]]
[nr.deckbuilder :refer [deck-name]]
[nr.game-row :refer [game-row]]
[nr.gameboard.actions :refer [launch-game]]
[nr.gameboard.state :refer [game-state parse-state]]
[nr.player-view :refer [player-view]]
[nr.sounds :refer [play-sound resume-sound]]
[nr.translations :refer [tr tr-format tr-side]]
[nr.utils :refer [cond-button non-game-toast slug->format]]
[nr.ws :as ws]
[reagent-modals.modals :as reagent-modals]
[reagent.core :as r]))
(def lobby-dom (atom {}))
(defn sort-games-list [games]
(sort-by (fn [game]
[(when-let [players (:players game)]
(not (some (fn [p]
(= (get-in p [:user :_id])
(get-in @app-state [:user :_id])))
players)))
(:started game)
(:date game)])
games))
(defn process-games-update
[{:keys [diff notification]}]
(swap! app-state update :games
(fn [games]
(let [gamemap (into {} (map #(assoc {} (:gameid %) %) games))
update-diff (reduce-kv
(fn [m k v]
; spectators is nil on the client but not the API, confusing differ which expects an empty set
(assoc m k (merge {:spectators '()} (get m k {}) v)))
gamemap
(:update diff))
delete-diff (apply dissoc update-diff (:delete diff))]
(sort-games-list (vals delete-diff)))))
(when-let [current-game (first (filter :selected (:games @app-state)))]
(swap! app-state update :gameid #(:gameid current-game)))
(when (and notification (not (:gameid @app-state)))
(play-sound notification)))
(defmethod ws/-msg-handler :games/list [{data :?data}]
(let [gamemap (into {} (for [d data] [(:gameid d) d]))
missing-gameids (->> (:games @app-state)
(remove #(get gamemap (:gameid %)))
(map :gameid))]
(process-games-update {:diff {:update gamemap
:delete missing-gameids}})))
(defmethod ws/-msg-handler :games/diff [{data :?data}]
(process-games-update data))
(defmethod ws/-msg-handler :games/differ
[{{:keys [diff]} :?data}]
(swap! app-state update :games
(fn [games]
(let [gamemap (into {} (map #(assoc {} (:gameid %) %) games))
update-diff (reduce-kv
(fn [m k v]
(assoc m k (reduce #(differ/patch %1 %2) (get m k {}) v)))
gamemap
(:update diff))]
(sort-games-list (vals update-diff))))))
(defmethod ws/-msg-handler :lobby/select
[{{:keys [gameid started state]} :?data}]
(swap! app-state assoc :gameid gameid)
(reset! angel-arena/queueing false)
(when started
(launch-game (parse-state state))))
(defmethod ws/-msg-handler :lobby/notification [{data :?data}] (play-sound data))
(defmethod ws/-msg-handler :lobby/timeout
[{{:keys [gameid]} :?data}]
(when (= gameid (:gameid @app-state))
(non-game-toast (tr [:lobby.closed-msg "Game lobby closed due to inactivity"]) "error" {:time-out 0 :close-button true})
(swap! app-state assoc :gameid nil)))
(defn new-game [s]
(authenticated
(fn [user]
(let [fmt (:format (:create-game-deck @app-state) "standard")
side (:side (:identity (:create-game-deck @app-state)) "Any Side")]
(swap! s assoc
:title (str (:username user) "'s game")
:side side
:format fmt
:editing true
:replay false
:save-replay (if (= "casual" (:room @s)) false true)
:api-access false
:flash-message ""
:protected false
:password ""
:timed false
:timer nil
:allow-spectator true
:spectatorhands false
:create-game-deck (:create-game-deck @app-state))
(swap! app-state assoc :editing-game true)
(swap! app-state dissoc :create-game-deck)
(-> ".game-title" js/$ .select)))))
(defn replay-game [s]
(authenticated
(fn [user]
(swap! s assoc
:gameid "local-replay"
:title (str (:username user) "'s game")
:side "Corp"
:format "standard"
:editing true
:replay true
:flash-message ""
:protected false
:password ""
:allow-spectator true
:spectatorhands true))))
(defn start-shared-replay
([s gameid]
(start-shared-replay s gameid nil))
([s gameid jump-to]
(authenticated
(fn [user]
(swap! s assoc
:title (str (:username user) "'s game")
:side "Corp"
:format "standard"
:editing false
:replay true
:flash-message ""
:protected false
:password ""
:allow-spectator true
:spectatorhands true)
(go (let [{:keys [status json]} (<! (GET (str "/profile/history/full/" gameid)))]
(case status
200
(let [replay (js->clj json :keywordize-keys true)
history (:history replay)
init-state (first history)
init-state (assoc init-state :gameid gameid)
init-state (assoc-in init-state [:options :spectatorhands] true)
diffs (rest history)
init-state (assoc init-state :replay-diffs diffs)]
(ws/event-msg-handler
{:id :netrunner/start
:?data (.stringify js/JSON (clj->js
(if jump-to
(assoc init-state :replay-jump-to jump-to)
init-state)))}))
404
(non-game-toast (tr [:lobby.replay-link-error "Replay link invalid."])
"error" {:time-out 0 :close-button true}))))))))
(defn start-replay [s]
(let [reader (js/FileReader.)
file (:replay-file s)
onload (fn [onload-ev] (let [replay (-> onload-ev .-target .-result)
replay (js->clj (.parse js/JSON replay) :keywordize-keys true)
history (:history replay)
init-state (first history)
init-state (assoc-in init-state [:options :spectatorhands] true)
diffs (rest history)
init-state (assoc init-state :replay-diffs diffs :gameid "local-replay")]
(ws/event-msg-handler
{:id :netrunner/start
:?data (.stringify js/JSON (clj->js init-state))})))]
(aset reader "onload" onload)
(.readAsText reader file)))
(defn create-game [s]
(authenticated
(fn [_]
(if (:replay @s)
(cond
(not (:replay-file @s))
(swap! s assoc :flash-message (tr [:lobby.replay-invalid-file "Select a valid replay file."]))
:else
(do (swap! s assoc :editing false)
(start-replay @s)))
(cond
(empty? (:title @s))
(swap! s assoc :flash-message (tr [:lobby.title-error "Please fill a game title."]))
(and (:protected @s)
(empty? (:password @s)))
(swap! s assoc :flash-message (tr [:lobby.password-error "Please fill a password."]))
:else
(do (swap! s assoc :editing false)
(swap! app-state dissoc :editing-game)
(ws/ws-send! [:lobby/create
(select-keys @s [:title :password :allow-spectator :save-replay
:spectatorhands :side :format :room :timer :api-access])])))))))
(defn leave-lobby [s]
(ws/ws-send! [:lobby/leave])
(swap! app-state assoc :gameid nil :message [] :password-gameid nil)
(swap! s assoc :prompt false))
(defn leave-game []
(ws/ws-send! [:netrunner/leave {:gameid-str (:gameid @game-state)}])
(reset! game-state nil)
(swap! app-state dissoc :gameid :side :password-gameid :win-shown :start-shown)
(set! (.-cursor (.-style (.-body js/document))) "default")
(.removeItem js/localStorage "gameid")
(set! (.-onbeforeunload js/window) nil)
(-> "#gameboard" js/$ .fadeOut)
(-> "#gamelobby" js/$ .fadeIn))
(defn deckselect-modal [user {:keys [gameid games decks format]}]
[:div
[:h3 (tr [:lobby.select-title "Select your deck"])]
[:div.deck-collection.lobby-deck-selector
(let [players (:players (some #(when (= (:gameid %) @gameid) %) @games))
side (:side (some #(when (= (-> % :user :_id) (:_id @user)) %) players))
same-side? (fn [deck] (= side (get-in deck [:identity :side])))
legal? (fn [deck] (get-in deck
[:status (keyword format) :legal]
(get-in (trusted-deck-status (assoc deck :format format))
[(keyword format) :legal]
false)))]
[:div
(doall
(for [deck (->> @decks
(filter same-side?)
(sort-by (juxt legal? :date) >))]
^{:key (:_id deck)}
[:div.deckline {:on-click #(do (ws/ws-send! [:lobby/deck (:_id deck)])
(reagent-modals/close-modal!))}
[:img {:src (image-url (:identity deck))
:alt (get-in deck [:identity :title] "")}]
[:div.float-right [deck-format-status-span deck format true]]
[:h4 (:name deck)]
[:div.float-right (-> (:date deck) js/Date. js/moment (.format "MMM Do YYYY"))]
[:p (get-in deck [:identity :title])]]))])]])
(defn send-msg [s]
(let [text (:msg @s)]
(when-not (empty? text)
(ws/ws-send! [:lobby/say {:gameid (:gameid @app-state)
:msg text}])
(let [msg-list (:message-list @lobby-dom)]
(set! (.-scrollTop msg-list) (+ (.-scrollHeight msg-list) 500)))
(swap! s assoc :msg ""))))
(defn chat-view []
(let [s (r/atom {})]
(r/create-class
{:display-name "chat-view"
:component-did-update
(fn []
(let [msg-list (:message-list @lobby-dom)
height (.-scrollHeight msg-list)]
(when (< (- height (.-scrollTop msg-list) (.height (js/$ ".lobby .chat-box"))) 500)
(set! (.-scrollTop msg-list) (.-scrollHeight msg-list)))))
:reagent-render
(fn [game]
[:div.chat-box
[:h3 (tr [:lobby.chat "Chat"])]
[:div.message-list {:ref #(swap! lobby-dom assoc :message-list %)}
(map-indexed (fn [i msg]
(if (= (:user msg) "__system__")
^{:key i}
[:div.system (:text msg)]
^{:key i}
[:div.message
[avatar (:user msg) {:opts {:size 38}}]
[:div.content
[:div.username (get-in msg [:user :username])]
[:div (:text msg)]]]))
(:messages game))]
[:div
[:form.msg-box {:on-submit #(do (.preventDefault %)
(send-msg s))}
[:input {:placeholder (tr [:chat.placeholder "Say something"])
:type "text"
:value (:msg @s)
:on-change #(swap! s assoc :msg (-> % .-target .-value))}]
[:button (tr [:chat.send "Send"])]]]])})))
(defn- hidden-formats
"Remove games which the user has opted to hide"
[visible-formats game]
(contains? visible-formats (get game :format)))
(defn filter-blocked-games
[user games visible-formats]
(if (= "tournament" (:room (first games)))
games
(let [is-visible #(or (contains? (get % :players) (:username user))
(hidden-formats visible-formats %))]
(filter is-visible games))))
(def open-games-symbol "○")
(def closed-games-symbol "●")
(defn room-count-str [open-count closed-count]
(str " (" @open-count open-games-symbol " " @closed-count closed-games-symbol ")"))
(defn- room-tab
"Creates the room tab for the specified room"
[s games room room-name]
(r/with-let [room-games (r/track (fn [] (filter #(= room (:room %)) @games)))
closed-count (r/track (fn [] (count (filter #(:started %) @room-games))))
open-count (r/track (fn [] (- (count @room-games) @closed-count)))]
[:div.roomtab
(if (= room (:room @s))
{:class "current"}
{:on-click #(swap! s assoc :room room)})
room-name (room-count-str open-count closed-count)]))
(defn- first-user?
"Is this user the first user in the game?"
[players user]
(= (-> players first :user :_id) (:_id user)))
(defn game-list [{:keys [room games gameid password-game editing]}]
(let [room-games (r/track (fn [] (filter #(= (:room %) room) @games)))
is-filtered? (not= (count slug->format) (count (:visible-formats @app-state)))
n (count @room-games)
game-count-str (tr [:lobby.game-count] n)]
[:<>
[:div.game-count
[:h4 (str game-count-str (when is-filtered? (str " " (tr [:lobby.filtered "(filtered)"]))))]]
[:div.game-list
(if (empty? @room-games)
[:h4 (tr [:lobby.no-games "No games"])]
(doall
(for [game @room-games]
^{:key (:gameid game)}
[game-row (assoc game :current-game @gameid :password-game password-game :editing editing)])))]]))
(defn format-visible? [slug] (contains? (:visible-formats @app-state) slug))
(defn- on-change-format-visibility
"Handle change event for format-toggle input"
[slug evt]
(.preventDefault evt)
(if (format-visible? slug)
(swap! app-state update-in [:visible-formats] difference #{slug})
(swap! app-state update-in [:visible-formats] union #{slug}))
(.setItem js/localStorage "visible-formats" (.stringify js/JSON (clj->js (:visible-formats @app-state)))))
(defn format-toggle [slug]
(r/with-let [id (str "filter-" slug)]
[:div
[:input.visible-formats {:id id
:type "checkbox"
:on-change (partial on-change-format-visibility slug)
:checked (format-visible? slug)}]
[:label {:for id} (-> slug slug->format tr-format)]]))
(defn games-list-panel [s games gameid password-gameid user visible-formats]
[:div.games
(when-let [params (:replay-id @app-state)]
(swap! app-state dissoc :replay-id)
(let [bug-report? (re-find #"bug-report" params)
id-match (re-find #"([0-9a-f\-]+)" params)
n-match (re-find #"n=(\d+)" params)
d-match (re-find #"d=(\d+)" params)
b-match (re-find #"b=(\d+)" params)
replay-id (nth id-match 1)
n (when n-match (js/parseInt (nth n-match 1)))
d (when d-match (js/parseInt (nth d-match 1)))
b (when b-match (js/parseInt (nth b-match 1)))]
(when replay-id
(.replaceState (.-history js/window) {} "" "/play") ; remove query parameters from url
(if bug-report?
(start-shared-replay s replay-id {:bug (or b 0)})
(if (and n d)
(start-shared-replay s replay-id {:n n :d d})
(start-shared-replay s replay-id nil)))
(resume-sound)
nil)))
[:div.button-bar
[:div.rooms
[:div#filter.dropdown
[:a.dropdown-toggle {:href "" :data-toggle "dropdown"}
"Filter"
[:b.caret]]
[:div.dropdown-menu.blue-shade
(doall (for [[k] slug->format]
^{:key k}
[format-toggle k (contains? visible-formats k)]))]]
; The real "tournament" lobby can be reenabled, once its functionality is complete. For now the old "competitive" lobby just got renamed. -- lostgeek, 9th August 2021
;
; [room-tab user s games "tournament" (tr [:lobby.tournament "Tournament"])]
; [room-tab user s games "competitive" (tr [:lobby.competitive "Competitive"])]
[room-tab s games "casual" (tr [:lobby.casual "Casual"])]
[room-tab s games "angel-arena" (tr [:lobby.angel-arena "Angel Arena"])]
[room-tab s games "competitive" (tr [:lobby.tournament "Tournament"])]]
(when (not= "angel-arena" (:room @s))
[:div.lobby-buttons
[cond-button (tr [:lobby.new-game "New game"])
(and (not (or @gameid
(:editing @s)
(= "tournament" (:room @s))))
(->> @games
(mapcat :players)
(filter #(= (-> % :user :_id) (:_id @user)))
empty?))
#(do (new-game s)
(resume-sound))]
[:button.reload-button {:type "button"
:on-click #(ws/ws-send! [:lobby/list])} (tr [:lobby.reload "Reload list"])]
[cond-button (tr [:lobby.load-replay "Load replay"])
(and (not (or @gameid
(:editing @s)
(= "tournament" (:room @s))))
(->> @games
(mapcat :players)
(filter #(= (-> % :user :_id) (:_id @user)))
empty?))
#(do (replay-game s)
(resume-sound))]])]
(case (:room @s)
"angel-arena"
[angel-arena/game-list user {:games games
:gameid gameid
:room (:room @s)}]
(let [password-game (some #(when (= @password-gameid (:gameid %)) %) @games)]
[game-list {:password-game password-game
:editing (:editing @s)
:games games
:gameid gameid
:room (:room @s)}]))])
(defn create-new-game
[s user]
(when (:editing @s)
(if (:replay @s)
[:div
[:div.button-bar
[:button {:type "button"
:on-click #(create-game s)} (tr [:lobby.start-replay "Start replay"])]
[:button {:type "button"
:on-click #(do
(swap! s assoc :editing false)
(swap! app-state dissoc :editing-game))}
(tr [:lobby.cancel "Cancel"])]]
(when-let [flash-message (:flash-message @s)]
[:p.flash-message flash-message])
[:div [:input {:field :file
:type :file
:on-change #(swap! s assoc :replay-file (aget (.. % -target -files) 0))}]]]
[:div
[:div.button-bar
[:button {:type "button"
:on-click #(create-game s)} (tr [:lobby.create "Create"])]
[:button {:type "button"
:on-click #(swap! s assoc :editing false)} (tr [:lobby.cancel "Cancel"])]]
(when-let [flash-message (:flash-message @s)]
[:p.flash-message flash-message])
[:div.content
[:section
[:h3 (tr [:lobby.title "Title"])]
[:input.game-title {:on-change #(swap! s assoc :title (.. % -target -value))
:value (:title @s)
:placeholder (tr [:lobby.title "Title"])
:maxLength "100"}]]
[:section
[:h3 (tr [:lobby.side "Side"])]
(doall
(for [option ["Any Side" "Corp" "Runner"]]
^{:key option}
[:p
[:label [:input {:type "radio"
:name "side"
:value option
:on-change #(swap! s assoc :side (.. % -target -value))
:checked (= (:side @s) option)}]
(tr-side option)]]))]
[:section
[:h3 (tr [:lobby.format "Format"])]
[:select.format {:value (:format @s "standard")
:on-change #(swap! s assoc :format (.. % -target -value))}
(doall (for [[k v] slug->format]
^{:key k}
[:option {:value k} (tr-format v)]))]]
[:section
[:h3 (tr [:lobby.options "Options"])]
[:p
[:label
[:input {:type "checkbox" :checked (:allow-spectator @s)
:on-change #(swap! s assoc :allow-spectator (.. % -target -checked))}]
(tr [:lobby.spectators "Allow spectators"])]]
[:p
[:label
[:input {:type "checkbox" :checked (:spectatorhands @s)
:on-change #(swap! s assoc :spectatorhands (.. % -target -checked))
:disabled (not (:allow-spectator @s))}]
(tr [:lobby.hidden "Make players' hidden information visible to spectators"])]]
[:div.infobox.blue-shade {:style {:display (if (:spectatorhands @s) "block" "none")}}
[:p "This will reveal both players' hidden information to ALL spectators of your game, "
"including hand and face-down cards."]
[:p "We recommend using a password to prevent strangers from spoiling the game."]]
[:p
[:label
[:input {:type "checkbox" :checked (:private @s)
:on-change #(let [checked (.. % -target -checked)]
(swap! s assoc :protected checked)
(when (not checked) (swap! s assoc :password "")))}]
(tr [:lobby.password-protected "Password protected"])]]
(when (:protected @s)
[:p
[:input.game-title {:on-change #(swap! s assoc :password (.. % -target -value))
:type "password"
:value (:password @s)
:placeholder (tr [:lobby.password "<PASSWORD>"])
:maxLength "30"}]])
(when-not (= "casual" (:room @s))
[:p
[:label
[:input {:type "checkbox" :checked (:timed @s)
:on-change #(let [checked (.. % -target -checked)]
(swap! s assoc :timed checked)
(swap! s assoc :timer (if checked 35 nil)))}]
(tr [:lobby.timed-game "Start with timer"])]])
(when (:timed @s)
[:p
[:input.game-title {:on-change #(swap! s assoc :timer (-> % (.. -target -value) str->int))
:type "number"
:value (:timer @s)
:placeholder (tr [:lobby.timer-length "Timer length (minutes)"])}]])
[:div.infobox.blue-shade {:style {:display (if (:timed @s) "block" "none")}}
[:p "Timer is only for convenience: the game will not stop when timer runs out."]]
[:p
[:label
[:input {:type "checkbox" :checked (:save-replay @s)
:on-change #(swap! s assoc :save-replay (.. % -target -checked))}]
(str "🟢 " (tr [:lobby.save-replay "Save replay"]))]]
[:div.infobox.blue-shade {:style {:display (if (:save-replay @s) "block" "none")}}
[:p "This will save a replay file of this match with open information (e.g. open cards in hand)."
" The file is available only after the game is finished."]
[:p "Only your latest 15 unshared games will be kept, so make sure to either download or share the match afterwards."]
[:p [:b "BETA Functionality:"] " Be aware that we might need to reset the saved replays, so " [:b "make sure to download games you want to keep."]
" Also, please keep in mind that we might need to do future changes to the site that might make replays incompatible."]]
(let [has-keys (:has-api-keys @user false)]
[:p
[:label
[:input {:disabled (not has-keys)
:type "checkbox" :checked (:api-access @s)
:on-change #(swap! s assoc :api-access (.. % -target -checked))}]
(tr [:lobby.api-access "Allow API access to game information"])
(when (not has-keys)
(str " " (tr [:lobby.api-requires-key "(Requires an API Key in Settings)"])))]])
[:div.infobox.blue-shade {:style {:display (if (:api-access @s) "block" "none")}}
[:p "This allows access to information about your game to 3rd party extensions. Requires an API Key to be created in Settings"]]]]])))
(defn pending-game
[s decks games gameid sets user]
(let [game (some #(when (= @gameid (:gameid %)) %) @games)
players (:players game)]
(when game
(when-let [create-deck (:create-game-deck @s)]
(ws/ws-send! [:lobby/deck (:_id create-deck)])
(swap! app-state dissoc :create-game-deck)
(swap! s dissoc :create-game-deck))
[:div
[:div.button-bar
(when (first-user? players @user)
[cond-button
(tr [:lobby.start "Start"])
(every? :deck players)
#(ws/ws-send! [:netrunner/start @gameid])])
[:button {:on-click #(leave-lobby s)} (tr [:lobby.leave "Leave"])]
(when (first-user? players @user)
(if (> (count players) 1)
[:button {:on-click #(ws/ws-send! [:lobby/swap {:gameid @gameid}])}
(tr [:lobby.swap "Swap sides"])]
[:div.dropdown
[:button.dropdown-toggle {:data-toggle "dropdown"}
(tr [:lobby.swap "Swap sides"])
[:b.caret]]
[:ul.dropdown-menu.blue-shade
[:a.block-link {:on-click #(ws/ws-send! [:lobby/swap {:gameid @gameid
:side "Any Side"} ])}
(tr-side "Any Side")]
[:a.block-link {:on-click #(ws/ws-send! [:lobby/swap {:gameid @gameid
:side "Corp"}])}
(tr-side "Corp")]
[:a.block-link {:on-click #(ws/ws-send! [:lobby/swap {:gameid @gameid
:side "Runner"}])}
(tr-side "Runner")]]]))]
[:div.content
[:h2 (:title game)]
(when-not (every? :deck players)
[:div.flash-message (tr [:lobby.waiting "Waiting players deck selection"])])
[:h3 (tr [:lobby.players "Players"])]
[:div.players
(doall
(map-indexed
(fn [idx player]
(let [player-id (get-in player [:user :_id])
this-player (= player-id (:_id @user))]
^{:key (or player-id idx)}
[:div
[player-view player game]
(when-let [{:keys [status]} (:deck player)]
[:span {:class (:status status)}
[:span.label
(if this-player
(deck-name (:deck player) 25)
(tr [:lobby.deck-selected "Deck selected"]))]])
(when-let [deck (:deck player)]
[:div.float-right [deck-format-status-span deck (:format game "standard") true]])
(when (and this-player (not (= (:side player) (tr-side "Any Side"))))
[:span.fake-link.deck-load
{:on-click #(reagent-modals/modal!
[deckselect-modal user {:games games :gameid gameid
:sets sets :decks decks
:format (:format game "standard")}])}
(tr [:lobby.select-deck "Select Deck"])])]))
players))]
[:h3 (tr [:lobby.options "Options"])]
[:ul.options
(when (:allow-spectator game)
[:li (tr [:lobby.spectators "Allow spectators"])])
(when (:timer game)
[:li "Game timer set for " (:timer game) " minutes"])
(when (:spectatorhands game)
[:li (tr [:lobby.hidden "Make players' hidden information visible to spectators"])])
(when (:password game)
[:li (tr [:lobby.password-protected "Password protected"])])
(when (:save-replay game)
[:li (str "🟢 " (tr [:lobby.save-replay "Save replay"]))])
(when (:save-replay game)
[:div.infobox.blue-shade {:style {:display (if (:save-replay @s) "block" "none")}}
[:p "This will save a replay file of this match with open information (e.g. open cards in hand)."
" The file is available only after the game is finished."]
[:p "Only your latest 15 unshared games will be kept, so make sure to either download or share the match afterwards."]
[:p [:b "BETA Functionality:"] " Be aware that we might need to reset the saved replays, so " [:b "make sure to download games you want to keep."]
" Also, please keep in mind that we might need to do future changes to the site that might make replays incompatible."]])
(when (:api-access game)
[:li (tr [:lobby.api-access "Allow API access to game information"])])]
(when (:allow-spectator game)
[:div.spectators
(let [c (:spectator-count game)]
[:h3 (tr [:lobby.spectator-count "Spectators"] c)])
(for [spectator (:spectators game)
:let [_id (get-in spectator [:user :_id])]]
^{:key _id}
[player-view spectator])])
[chat-view game]]])))
(defn right-panel
[decks s games gameid sets user]
(if (= "angel-arena" (:room @s))
[angel-arena/game-panel decks s user]
[:div.game-panel
[create-new-game s user]
[pending-game s decks games gameid sets user]]))
(defn game-lobby []
(r/with-let [s (r/atom {:room "casual"})
decks (r/cursor app-state [:decks])
games (r/cursor app-state [:games])
gameid (r/cursor app-state [:gameid])
password-gameid (r/cursor app-state [:password-gameid])
sets (r/cursor app-state [:sets])
user (r/cursor app-state [:user])
cards-loaded (r/cursor app-state [:cards-loaded])
active (r/cursor app-state [:active-page])
visible-formats (r/cursor app-state [:visible-formats])]
[:div.container
[:div.lobby-bg]
(when (and (= "/play" (first @active)) @cards-loaded)
(authenticated (fn [_] nil))
(when (and (not (or @gameid (:editing @s)))
(some? (:create-game-deck @app-state)))
(new-game s))
[:div.lobby.panel.blue-shade
[games-list-panel s games gameid password-gameid user visible-formats]
[right-panel decks s games gameid sets user]])]))
| true | (ns nr.gamelobby
(:require-macros [cljs.core.async.macros :refer [go]])
(:require
[cljs.core.async :refer [<!] :as async]
[clojure.set :refer [difference union]]
[differ.core :as differ]
[jinteki.utils :refer [str->int]]
[jinteki.validator :refer [trusted-deck-status]]
[nr.ajax :refer [GET]]
[nr.angel-arena :as angel-arena]
[nr.appstate :refer [app-state]]
[nr.auth :refer [authenticated] :as auth]
[nr.avatar :refer [avatar]]
[nr.cardbrowser :refer [image-url] :as cb]
[nr.deck-status :refer [deck-format-status-span]]
[nr.deckbuilder :refer [deck-name]]
[nr.game-row :refer [game-row]]
[nr.gameboard.actions :refer [launch-game]]
[nr.gameboard.state :refer [game-state parse-state]]
[nr.player-view :refer [player-view]]
[nr.sounds :refer [play-sound resume-sound]]
[nr.translations :refer [tr tr-format tr-side]]
[nr.utils :refer [cond-button non-game-toast slug->format]]
[nr.ws :as ws]
[reagent-modals.modals :as reagent-modals]
[reagent.core :as r]))
(def lobby-dom (atom {}))
(defn sort-games-list [games]
(sort-by (fn [game]
[(when-let [players (:players game)]
(not (some (fn [p]
(= (get-in p [:user :_id])
(get-in @app-state [:user :_id])))
players)))
(:started game)
(:date game)])
games))
(defn process-games-update
[{:keys [diff notification]}]
(swap! app-state update :games
(fn [games]
(let [gamemap (into {} (map #(assoc {} (:gameid %) %) games))
update-diff (reduce-kv
(fn [m k v]
; spectators is nil on the client but not the API, confusing differ which expects an empty set
(assoc m k (merge {:spectators '()} (get m k {}) v)))
gamemap
(:update diff))
delete-diff (apply dissoc update-diff (:delete diff))]
(sort-games-list (vals delete-diff)))))
(when-let [current-game (first (filter :selected (:games @app-state)))]
(swap! app-state update :gameid #(:gameid current-game)))
(when (and notification (not (:gameid @app-state)))
(play-sound notification)))
(defmethod ws/-msg-handler :games/list [{data :?data}]
(let [gamemap (into {} (for [d data] [(:gameid d) d]))
missing-gameids (->> (:games @app-state)
(remove #(get gamemap (:gameid %)))
(map :gameid))]
(process-games-update {:diff {:update gamemap
:delete missing-gameids}})))
(defmethod ws/-msg-handler :games/diff [{data :?data}]
(process-games-update data))
(defmethod ws/-msg-handler :games/differ
[{{:keys [diff]} :?data}]
(swap! app-state update :games
(fn [games]
(let [gamemap (into {} (map #(assoc {} (:gameid %) %) games))
update-diff (reduce-kv
(fn [m k v]
(assoc m k (reduce #(differ/patch %1 %2) (get m k {}) v)))
gamemap
(:update diff))]
(sort-games-list (vals update-diff))))))
(defmethod ws/-msg-handler :lobby/select
[{{:keys [gameid started state]} :?data}]
(swap! app-state assoc :gameid gameid)
(reset! angel-arena/queueing false)
(when started
(launch-game (parse-state state))))
(defmethod ws/-msg-handler :lobby/notification [{data :?data}] (play-sound data))
(defmethod ws/-msg-handler :lobby/timeout
[{{:keys [gameid]} :?data}]
(when (= gameid (:gameid @app-state))
(non-game-toast (tr [:lobby.closed-msg "Game lobby closed due to inactivity"]) "error" {:time-out 0 :close-button true})
(swap! app-state assoc :gameid nil)))
(defn new-game [s]
(authenticated
(fn [user]
(let [fmt (:format (:create-game-deck @app-state) "standard")
side (:side (:identity (:create-game-deck @app-state)) "Any Side")]
(swap! s assoc
:title (str (:username user) "'s game")
:side side
:format fmt
:editing true
:replay false
:save-replay (if (= "casual" (:room @s)) false true)
:api-access false
:flash-message ""
:protected false
:password ""
:timed false
:timer nil
:allow-spectator true
:spectatorhands false
:create-game-deck (:create-game-deck @app-state))
(swap! app-state assoc :editing-game true)
(swap! app-state dissoc :create-game-deck)
(-> ".game-title" js/$ .select)))))
(defn replay-game [s]
(authenticated
(fn [user]
(swap! s assoc
:gameid "local-replay"
:title (str (:username user) "'s game")
:side "Corp"
:format "standard"
:editing true
:replay true
:flash-message ""
:protected false
:password ""
:allow-spectator true
:spectatorhands true))))
(defn start-shared-replay
([s gameid]
(start-shared-replay s gameid nil))
([s gameid jump-to]
(authenticated
(fn [user]
(swap! s assoc
:title (str (:username user) "'s game")
:side "Corp"
:format "standard"
:editing false
:replay true
:flash-message ""
:protected false
:password ""
:allow-spectator true
:spectatorhands true)
(go (let [{:keys [status json]} (<! (GET (str "/profile/history/full/" gameid)))]
(case status
200
(let [replay (js->clj json :keywordize-keys true)
history (:history replay)
init-state (first history)
init-state (assoc init-state :gameid gameid)
init-state (assoc-in init-state [:options :spectatorhands] true)
diffs (rest history)
init-state (assoc init-state :replay-diffs diffs)]
(ws/event-msg-handler
{:id :netrunner/start
:?data (.stringify js/JSON (clj->js
(if jump-to
(assoc init-state :replay-jump-to jump-to)
init-state)))}))
404
(non-game-toast (tr [:lobby.replay-link-error "Replay link invalid."])
"error" {:time-out 0 :close-button true}))))))))
(defn start-replay [s]
(let [reader (js/FileReader.)
file (:replay-file s)
onload (fn [onload-ev] (let [replay (-> onload-ev .-target .-result)
replay (js->clj (.parse js/JSON replay) :keywordize-keys true)
history (:history replay)
init-state (first history)
init-state (assoc-in init-state [:options :spectatorhands] true)
diffs (rest history)
init-state (assoc init-state :replay-diffs diffs :gameid "local-replay")]
(ws/event-msg-handler
{:id :netrunner/start
:?data (.stringify js/JSON (clj->js init-state))})))]
(aset reader "onload" onload)
(.readAsText reader file)))
(defn create-game [s]
(authenticated
(fn [_]
(if (:replay @s)
(cond
(not (:replay-file @s))
(swap! s assoc :flash-message (tr [:lobby.replay-invalid-file "Select a valid replay file."]))
:else
(do (swap! s assoc :editing false)
(start-replay @s)))
(cond
(empty? (:title @s))
(swap! s assoc :flash-message (tr [:lobby.title-error "Please fill a game title."]))
(and (:protected @s)
(empty? (:password @s)))
(swap! s assoc :flash-message (tr [:lobby.password-error "Please fill a password."]))
:else
(do (swap! s assoc :editing false)
(swap! app-state dissoc :editing-game)
(ws/ws-send! [:lobby/create
(select-keys @s [:title :password :allow-spectator :save-replay
:spectatorhands :side :format :room :timer :api-access])])))))))
(defn leave-lobby [s]
(ws/ws-send! [:lobby/leave])
(swap! app-state assoc :gameid nil :message [] :password-gameid nil)
(swap! s assoc :prompt false))
(defn leave-game []
(ws/ws-send! [:netrunner/leave {:gameid-str (:gameid @game-state)}])
(reset! game-state nil)
(swap! app-state dissoc :gameid :side :password-gameid :win-shown :start-shown)
(set! (.-cursor (.-style (.-body js/document))) "default")
(.removeItem js/localStorage "gameid")
(set! (.-onbeforeunload js/window) nil)
(-> "#gameboard" js/$ .fadeOut)
(-> "#gamelobby" js/$ .fadeIn))
(defn deckselect-modal [user {:keys [gameid games decks format]}]
[:div
[:h3 (tr [:lobby.select-title "Select your deck"])]
[:div.deck-collection.lobby-deck-selector
(let [players (:players (some #(when (= (:gameid %) @gameid) %) @games))
side (:side (some #(when (= (-> % :user :_id) (:_id @user)) %) players))
same-side? (fn [deck] (= side (get-in deck [:identity :side])))
legal? (fn [deck] (get-in deck
[:status (keyword format) :legal]
(get-in (trusted-deck-status (assoc deck :format format))
[(keyword format) :legal]
false)))]
[:div
(doall
(for [deck (->> @decks
(filter same-side?)
(sort-by (juxt legal? :date) >))]
^{:key (:_id deck)}
[:div.deckline {:on-click #(do (ws/ws-send! [:lobby/deck (:_id deck)])
(reagent-modals/close-modal!))}
[:img {:src (image-url (:identity deck))
:alt (get-in deck [:identity :title] "")}]
[:div.float-right [deck-format-status-span deck format true]]
[:h4 (:name deck)]
[:div.float-right (-> (:date deck) js/Date. js/moment (.format "MMM Do YYYY"))]
[:p (get-in deck [:identity :title])]]))])]])
(defn send-msg [s]
(let [text (:msg @s)]
(when-not (empty? text)
(ws/ws-send! [:lobby/say {:gameid (:gameid @app-state)
:msg text}])
(let [msg-list (:message-list @lobby-dom)]
(set! (.-scrollTop msg-list) (+ (.-scrollHeight msg-list) 500)))
(swap! s assoc :msg ""))))
(defn chat-view []
(let [s (r/atom {})]
(r/create-class
{:display-name "chat-view"
:component-did-update
(fn []
(let [msg-list (:message-list @lobby-dom)
height (.-scrollHeight msg-list)]
(when (< (- height (.-scrollTop msg-list) (.height (js/$ ".lobby .chat-box"))) 500)
(set! (.-scrollTop msg-list) (.-scrollHeight msg-list)))))
:reagent-render
(fn [game]
[:div.chat-box
[:h3 (tr [:lobby.chat "Chat"])]
[:div.message-list {:ref #(swap! lobby-dom assoc :message-list %)}
(map-indexed (fn [i msg]
(if (= (:user msg) "__system__")
^{:key i}
[:div.system (:text msg)]
^{:key i}
[:div.message
[avatar (:user msg) {:opts {:size 38}}]
[:div.content
[:div.username (get-in msg [:user :username])]
[:div (:text msg)]]]))
(:messages game))]
[:div
[:form.msg-box {:on-submit #(do (.preventDefault %)
(send-msg s))}
[:input {:placeholder (tr [:chat.placeholder "Say something"])
:type "text"
:value (:msg @s)
:on-change #(swap! s assoc :msg (-> % .-target .-value))}]
[:button (tr [:chat.send "Send"])]]]])})))
(defn- hidden-formats
"Remove games which the user has opted to hide"
[visible-formats game]
(contains? visible-formats (get game :format)))
(defn filter-blocked-games
[user games visible-formats]
(if (= "tournament" (:room (first games)))
games
(let [is-visible #(or (contains? (get % :players) (:username user))
(hidden-formats visible-formats %))]
(filter is-visible games))))
(def open-games-symbol "○")
(def closed-games-symbol "●")
(defn room-count-str [open-count closed-count]
(str " (" @open-count open-games-symbol " " @closed-count closed-games-symbol ")"))
(defn- room-tab
"Creates the room tab for the specified room"
[s games room room-name]
(r/with-let [room-games (r/track (fn [] (filter #(= room (:room %)) @games)))
closed-count (r/track (fn [] (count (filter #(:started %) @room-games))))
open-count (r/track (fn [] (- (count @room-games) @closed-count)))]
[:div.roomtab
(if (= room (:room @s))
{:class "current"}
{:on-click #(swap! s assoc :room room)})
room-name (room-count-str open-count closed-count)]))
(defn- first-user?
"Is this user the first user in the game?"
[players user]
(= (-> players first :user :_id) (:_id user)))
(defn game-list [{:keys [room games gameid password-game editing]}]
(let [room-games (r/track (fn [] (filter #(= (:room %) room) @games)))
is-filtered? (not= (count slug->format) (count (:visible-formats @app-state)))
n (count @room-games)
game-count-str (tr [:lobby.game-count] n)]
[:<>
[:div.game-count
[:h4 (str game-count-str (when is-filtered? (str " " (tr [:lobby.filtered "(filtered)"]))))]]
[:div.game-list
(if (empty? @room-games)
[:h4 (tr [:lobby.no-games "No games"])]
(doall
(for [game @room-games]
^{:key (:gameid game)}
[game-row (assoc game :current-game @gameid :password-game password-game :editing editing)])))]]))
(defn format-visible? [slug] (contains? (:visible-formats @app-state) slug))
(defn- on-change-format-visibility
"Handle change event for format-toggle input"
[slug evt]
(.preventDefault evt)
(if (format-visible? slug)
(swap! app-state update-in [:visible-formats] difference #{slug})
(swap! app-state update-in [:visible-formats] union #{slug}))
(.setItem js/localStorage "visible-formats" (.stringify js/JSON (clj->js (:visible-formats @app-state)))))
(defn format-toggle [slug]
(r/with-let [id (str "filter-" slug)]
[:div
[:input.visible-formats {:id id
:type "checkbox"
:on-change (partial on-change-format-visibility slug)
:checked (format-visible? slug)}]
[:label {:for id} (-> slug slug->format tr-format)]]))
(defn games-list-panel [s games gameid password-gameid user visible-formats]
[:div.games
(when-let [params (:replay-id @app-state)]
(swap! app-state dissoc :replay-id)
(let [bug-report? (re-find #"bug-report" params)
id-match (re-find #"([0-9a-f\-]+)" params)
n-match (re-find #"n=(\d+)" params)
d-match (re-find #"d=(\d+)" params)
b-match (re-find #"b=(\d+)" params)
replay-id (nth id-match 1)
n (when n-match (js/parseInt (nth n-match 1)))
d (when d-match (js/parseInt (nth d-match 1)))
b (when b-match (js/parseInt (nth b-match 1)))]
(when replay-id
(.replaceState (.-history js/window) {} "" "/play") ; remove query parameters from url
(if bug-report?
(start-shared-replay s replay-id {:bug (or b 0)})
(if (and n d)
(start-shared-replay s replay-id {:n n :d d})
(start-shared-replay s replay-id nil)))
(resume-sound)
nil)))
[:div.button-bar
[:div.rooms
[:div#filter.dropdown
[:a.dropdown-toggle {:href "" :data-toggle "dropdown"}
"Filter"
[:b.caret]]
[:div.dropdown-menu.blue-shade
(doall (for [[k] slug->format]
^{:key k}
[format-toggle k (contains? visible-formats k)]))]]
; The real "tournament" lobby can be reenabled, once its functionality is complete. For now the old "competitive" lobby just got renamed. -- lostgeek, 9th August 2021
;
; [room-tab user s games "tournament" (tr [:lobby.tournament "Tournament"])]
; [room-tab user s games "competitive" (tr [:lobby.competitive "Competitive"])]
[room-tab s games "casual" (tr [:lobby.casual "Casual"])]
[room-tab s games "angel-arena" (tr [:lobby.angel-arena "Angel Arena"])]
[room-tab s games "competitive" (tr [:lobby.tournament "Tournament"])]]
(when (not= "angel-arena" (:room @s))
[:div.lobby-buttons
[cond-button (tr [:lobby.new-game "New game"])
(and (not (or @gameid
(:editing @s)
(= "tournament" (:room @s))))
(->> @games
(mapcat :players)
(filter #(= (-> % :user :_id) (:_id @user)))
empty?))
#(do (new-game s)
(resume-sound))]
[:button.reload-button {:type "button"
:on-click #(ws/ws-send! [:lobby/list])} (tr [:lobby.reload "Reload list"])]
[cond-button (tr [:lobby.load-replay "Load replay"])
(and (not (or @gameid
(:editing @s)
(= "tournament" (:room @s))))
(->> @games
(mapcat :players)
(filter #(= (-> % :user :_id) (:_id @user)))
empty?))
#(do (replay-game s)
(resume-sound))]])]
(case (:room @s)
"angel-arena"
[angel-arena/game-list user {:games games
:gameid gameid
:room (:room @s)}]
(let [password-game (some #(when (= @password-gameid (:gameid %)) %) @games)]
[game-list {:password-game password-game
:editing (:editing @s)
:games games
:gameid gameid
:room (:room @s)}]))])
(defn create-new-game
[s user]
(when (:editing @s)
(if (:replay @s)
[:div
[:div.button-bar
[:button {:type "button"
:on-click #(create-game s)} (tr [:lobby.start-replay "Start replay"])]
[:button {:type "button"
:on-click #(do
(swap! s assoc :editing false)
(swap! app-state dissoc :editing-game))}
(tr [:lobby.cancel "Cancel"])]]
(when-let [flash-message (:flash-message @s)]
[:p.flash-message flash-message])
[:div [:input {:field :file
:type :file
:on-change #(swap! s assoc :replay-file (aget (.. % -target -files) 0))}]]]
[:div
[:div.button-bar
[:button {:type "button"
:on-click #(create-game s)} (tr [:lobby.create "Create"])]
[:button {:type "button"
:on-click #(swap! s assoc :editing false)} (tr [:lobby.cancel "Cancel"])]]
(when-let [flash-message (:flash-message @s)]
[:p.flash-message flash-message])
[:div.content
[:section
[:h3 (tr [:lobby.title "Title"])]
[:input.game-title {:on-change #(swap! s assoc :title (.. % -target -value))
:value (:title @s)
:placeholder (tr [:lobby.title "Title"])
:maxLength "100"}]]
[:section
[:h3 (tr [:lobby.side "Side"])]
(doall
(for [option ["Any Side" "Corp" "Runner"]]
^{:key option}
[:p
[:label [:input {:type "radio"
:name "side"
:value option
:on-change #(swap! s assoc :side (.. % -target -value))
:checked (= (:side @s) option)}]
(tr-side option)]]))]
[:section
[:h3 (tr [:lobby.format "Format"])]
[:select.format {:value (:format @s "standard")
:on-change #(swap! s assoc :format (.. % -target -value))}
(doall (for [[k v] slug->format]
^{:key k}
[:option {:value k} (tr-format v)]))]]
[:section
[:h3 (tr [:lobby.options "Options"])]
[:p
[:label
[:input {:type "checkbox" :checked (:allow-spectator @s)
:on-change #(swap! s assoc :allow-spectator (.. % -target -checked))}]
(tr [:lobby.spectators "Allow spectators"])]]
[:p
[:label
[:input {:type "checkbox" :checked (:spectatorhands @s)
:on-change #(swap! s assoc :spectatorhands (.. % -target -checked))
:disabled (not (:allow-spectator @s))}]
(tr [:lobby.hidden "Make players' hidden information visible to spectators"])]]
[:div.infobox.blue-shade {:style {:display (if (:spectatorhands @s) "block" "none")}}
[:p "This will reveal both players' hidden information to ALL spectators of your game, "
"including hand and face-down cards."]
[:p "We recommend using a password to prevent strangers from spoiling the game."]]
[:p
[:label
[:input {:type "checkbox" :checked (:private @s)
:on-change #(let [checked (.. % -target -checked)]
(swap! s assoc :protected checked)
(when (not checked) (swap! s assoc :password "")))}]
(tr [:lobby.password-protected "Password protected"])]]
(when (:protected @s)
[:p
[:input.game-title {:on-change #(swap! s assoc :password (.. % -target -value))
:type "password"
:value (:password @s)
:placeholder (tr [:lobby.password "PI:PASSWORD:<PASSWORD>END_PI"])
:maxLength "30"}]])
(when-not (= "casual" (:room @s))
[:p
[:label
[:input {:type "checkbox" :checked (:timed @s)
:on-change #(let [checked (.. % -target -checked)]
(swap! s assoc :timed checked)
(swap! s assoc :timer (if checked 35 nil)))}]
(tr [:lobby.timed-game "Start with timer"])]])
(when (:timed @s)
[:p
[:input.game-title {:on-change #(swap! s assoc :timer (-> % (.. -target -value) str->int))
:type "number"
:value (:timer @s)
:placeholder (tr [:lobby.timer-length "Timer length (minutes)"])}]])
[:div.infobox.blue-shade {:style {:display (if (:timed @s) "block" "none")}}
[:p "Timer is only for convenience: the game will not stop when timer runs out."]]
[:p
[:label
[:input {:type "checkbox" :checked (:save-replay @s)
:on-change #(swap! s assoc :save-replay (.. % -target -checked))}]
(str "🟢 " (tr [:lobby.save-replay "Save replay"]))]]
[:div.infobox.blue-shade {:style {:display (if (:save-replay @s) "block" "none")}}
[:p "This will save a replay file of this match with open information (e.g. open cards in hand)."
" The file is available only after the game is finished."]
[:p "Only your latest 15 unshared games will be kept, so make sure to either download or share the match afterwards."]
[:p [:b "BETA Functionality:"] " Be aware that we might need to reset the saved replays, so " [:b "make sure to download games you want to keep."]
" Also, please keep in mind that we might need to do future changes to the site that might make replays incompatible."]]
(let [has-keys (:has-api-keys @user false)]
[:p
[:label
[:input {:disabled (not has-keys)
:type "checkbox" :checked (:api-access @s)
:on-change #(swap! s assoc :api-access (.. % -target -checked))}]
(tr [:lobby.api-access "Allow API access to game information"])
(when (not has-keys)
(str " " (tr [:lobby.api-requires-key "(Requires an API Key in Settings)"])))]])
[:div.infobox.blue-shade {:style {:display (if (:api-access @s) "block" "none")}}
[:p "This allows access to information about your game to 3rd party extensions. Requires an API Key to be created in Settings"]]]]])))
(defn pending-game
[s decks games gameid sets user]
(let [game (some #(when (= @gameid (:gameid %)) %) @games)
players (:players game)]
(when game
(when-let [create-deck (:create-game-deck @s)]
(ws/ws-send! [:lobby/deck (:_id create-deck)])
(swap! app-state dissoc :create-game-deck)
(swap! s dissoc :create-game-deck))
[:div
[:div.button-bar
(when (first-user? players @user)
[cond-button
(tr [:lobby.start "Start"])
(every? :deck players)
#(ws/ws-send! [:netrunner/start @gameid])])
[:button {:on-click #(leave-lobby s)} (tr [:lobby.leave "Leave"])]
(when (first-user? players @user)
(if (> (count players) 1)
[:button {:on-click #(ws/ws-send! [:lobby/swap {:gameid @gameid}])}
(tr [:lobby.swap "Swap sides"])]
[:div.dropdown
[:button.dropdown-toggle {:data-toggle "dropdown"}
(tr [:lobby.swap "Swap sides"])
[:b.caret]]
[:ul.dropdown-menu.blue-shade
[:a.block-link {:on-click #(ws/ws-send! [:lobby/swap {:gameid @gameid
:side "Any Side"} ])}
(tr-side "Any Side")]
[:a.block-link {:on-click #(ws/ws-send! [:lobby/swap {:gameid @gameid
:side "Corp"}])}
(tr-side "Corp")]
[:a.block-link {:on-click #(ws/ws-send! [:lobby/swap {:gameid @gameid
:side "Runner"}])}
(tr-side "Runner")]]]))]
[:div.content
[:h2 (:title game)]
(when-not (every? :deck players)
[:div.flash-message (tr [:lobby.waiting "Waiting players deck selection"])])
[:h3 (tr [:lobby.players "Players"])]
[:div.players
(doall
(map-indexed
(fn [idx player]
(let [player-id (get-in player [:user :_id])
this-player (= player-id (:_id @user))]
^{:key (or player-id idx)}
[:div
[player-view player game]
(when-let [{:keys [status]} (:deck player)]
[:span {:class (:status status)}
[:span.label
(if this-player
(deck-name (:deck player) 25)
(tr [:lobby.deck-selected "Deck selected"]))]])
(when-let [deck (:deck player)]
[:div.float-right [deck-format-status-span deck (:format game "standard") true]])
(when (and this-player (not (= (:side player) (tr-side "Any Side"))))
[:span.fake-link.deck-load
{:on-click #(reagent-modals/modal!
[deckselect-modal user {:games games :gameid gameid
:sets sets :decks decks
:format (:format game "standard")}])}
(tr [:lobby.select-deck "Select Deck"])])]))
players))]
[:h3 (tr [:lobby.options "Options"])]
[:ul.options
(when (:allow-spectator game)
[:li (tr [:lobby.spectators "Allow spectators"])])
(when (:timer game)
[:li "Game timer set for " (:timer game) " minutes"])
(when (:spectatorhands game)
[:li (tr [:lobby.hidden "Make players' hidden information visible to spectators"])])
(when (:password game)
[:li (tr [:lobby.password-protected "Password protected"])])
(when (:save-replay game)
[:li (str "🟢 " (tr [:lobby.save-replay "Save replay"]))])
(when (:save-replay game)
[:div.infobox.blue-shade {:style {:display (if (:save-replay @s) "block" "none")}}
[:p "This will save a replay file of this match with open information (e.g. open cards in hand)."
" The file is available only after the game is finished."]
[:p "Only your latest 15 unshared games will be kept, so make sure to either download or share the match afterwards."]
[:p [:b "BETA Functionality:"] " Be aware that we might need to reset the saved replays, so " [:b "make sure to download games you want to keep."]
" Also, please keep in mind that we might need to do future changes to the site that might make replays incompatible."]])
(when (:api-access game)
[:li (tr [:lobby.api-access "Allow API access to game information"])])]
(when (:allow-spectator game)
[:div.spectators
(let [c (:spectator-count game)]
[:h3 (tr [:lobby.spectator-count "Spectators"] c)])
(for [spectator (:spectators game)
:let [_id (get-in spectator [:user :_id])]]
^{:key _id}
[player-view spectator])])
[chat-view game]]])))
(defn right-panel
[decks s games gameid sets user]
(if (= "angel-arena" (:room @s))
[angel-arena/game-panel decks s user]
[:div.game-panel
[create-new-game s user]
[pending-game s decks games gameid sets user]]))
(defn game-lobby []
(r/with-let [s (r/atom {:room "casual"})
decks (r/cursor app-state [:decks])
games (r/cursor app-state [:games])
gameid (r/cursor app-state [:gameid])
password-gameid (r/cursor app-state [:password-gameid])
sets (r/cursor app-state [:sets])
user (r/cursor app-state [:user])
cards-loaded (r/cursor app-state [:cards-loaded])
active (r/cursor app-state [:active-page])
visible-formats (r/cursor app-state [:visible-formats])]
[:div.container
[:div.lobby-bg]
(when (and (= "/play" (first @active)) @cards-loaded)
(authenticated (fn [_] nil))
(when (and (not (or @gameid (:editing @s)))
(some? (:create-game-deck @app-state)))
(new-game s))
[:div.lobby.panel.blue-shade
[games-list-panel s games gameid password-gameid user visible-formats]
[right-panel decks s games gameid sets user]])]))
|
[
{
"context": ")?nollaig (bheag|na mban)\"]\n (month-day 1 6)\n\n \"Lá Fhéile Vailintín\"\n [#\"(?i)(l[áa] )?(fh[eé]ile|'?le) vailint[íi]n\"",
"end": 2856,
"score": 0.9949370622634888,
"start": 2837,
"tag": "NAME",
"value": "Lá Fhéile Vailintín"
},
{
"context": "é]ile|'?le) vailint[íi]n\"]\n (month-day 2 14)\n\n \"Lá Fhéile Pádraig\"\n [#\"(?i)(l[áa] )?(fh[eé]ile|'?le) ph?[áa]draig\"",
"end": 2948,
"score": 0.9962631464004517,
"start": 2931,
"tag": "NAME",
"value": "Lá Fhéile Pádraig"
},
{
"context": "é]ile|'?le) ph?[áa]draig\"]\n (month-day 3 17)\n\n \"Lá Fhéile Bríde\"\n [#\"(?i)(l[áa] )?(fh[eé]ile|'?le) bh?r[íi]de\"]\n",
"end": 3038,
"score": 0.9926745891571045,
"start": 3023,
"tag": "NAME",
"value": "Lá Fhéile Bríde"
}
] | resources/languages/ga/rules/time.clj | guivn/duckling | 922 | (
;; generic
"intersect"
[(dim :time #(not (:latent %))) (dim :time #(not (:latent %)))] ; sequence of two tokens with a time dimension
(intersect %1 %2)
; FIXME
; same thing, with "of" in between like "Sunday of last week"
; "intersect by \"of\", \"from\", \"'s\""
; [(dim :time #(not (:latent %))) #"(?i)of|from|for|'s" (dim :time #(not (:latent %)))] ; sequence of two tokens with a time fn
; (intersect %1 %3)
; mostly for January 12, 2005
; this is a separate rule, because commas separate very specific tokens
; so we want this rule's classifier to learn this
"intersect by \",\""
[(dim :time #(not (:latent %))) #"," (dim :time #(not (:latent %)))] ; sequence of two tokens with a time fn
(intersect %1 %3)
"ar <date>" ; ar Wed, March 23 ;FIXME
[#"(?i)ar" (dim :time)]
%2 ; does NOT dissoc latent
"on a named-day" ; ar an luan
[#"(?i)ar an" {:form :day-of-week}]
%2 ; does NOT dissoc latent
"dé named-day" ; dé luain
[#"(?i)d[ée]" {:form :day-of-week}]
%2 ; does NOT dissoc latent
"an named-day" ; an luan
[#"(?i)an" {:form :day-of-week}]
%2 ; does NOT dissoc latent
;;;;;;;;;;;;;;;;;;;
;; Named things
"named-day"
#"(?i)luai?n|lu\.?"
(day-of-week 1)
"named-day"
#"(?i)mh?[áa]irt|m[áa]?\.?"
(day-of-week 2)
"named-day"
#"(?i)ch?[ée]adaoin|c[ée]\.?"
(day-of-week 3)
"named-day"
#"(?i)d[ée]ardaoin|d[ée]?\.?"
(day-of-week 4)
"named-day"
#"(?i)h?aoine|ao\.?"
(day-of-week 5)
"named-day"
#"(?i)sathai?rn|sa\.?"
(day-of-week 6)
"named-day"
#"(?i)domhnai?[cg]h|do\.?"
(day-of-week 7)
"named-month"
#"(?i)(mh?[íi] )?(an )?t?ean[áa]ir|ean\.?"
(month 1)
"named-month"
#"(?i)(mh?[íi] )?(na )?feabhra|fea\.?"
(month 2)
"named-month"
#"(?i)(mh?[íi] )?(an )?mh?[áa]rta|m[áa]r\.?"
(month 3)
"named-month"
#"(?i)(mh?[íi] )?(an )?t?aibre[áa]i?n|abr\.?"
(month 4)
"named-month"
#"(?i)(mh?[íi] )?(na )?bh?ealtaine|bea\.?"
(month 5)
"named-month"
#"(?i)(mh?[íi] )?(an )?mh?eith(ea|i)mh|mei\.?"
(month 6)
"named-month"
#"(?i)(mh?[íi] )?i[úu]il|i[úu]i\.?"
(month 7)
"named-month"
#"(?i)(mh?[íi] )?(na )?l[úu]nasa|l[úu]n\.?"
(month 8)
"named-month"
#"(?i)(mh?[íi] )?mh?e[áa]n f[óo]mhair|mef?\.?"
(month 9)
"named-month"
#"(?i)(mh?[íi] )?dh?eireadh f[óo]mhair|def?\.?"
(month 10)
"named-month"
#"(?i)(mh?[íi] )?(na )?samh(ain|na)|sam\.?"
(month 11)
"named-month"
#"(?i)(mh?[íi] )?(na )?nollai?g|nol\.?"
(month 12)
; Holiday TODO: check online holidays
; or define dynamic rule (last thursday of october..)
"An Nollaig" ; "Mí na Nollag" is literally "month of Christmas", so collision with month
[#"(?i)(l[áa] |an )?(nollai?g)"]
(month-day 12 25)
"Nollaig na mBan"
[#"(?i)(l[áa] |an )?nollaig (bheag|na mban)"]
(month-day 1 6)
"Lá Fhéile Vailintín"
[#"(?i)(l[áa] )?(fh[eé]ile|'?le) vailint[íi]n"]
(month-day 2 14)
"Lá Fhéile Pádraig"
[#"(?i)(l[áa] )?(fh[eé]ile|'?le) ph?[áa]draig"]
(month-day 3 17)
"Lá Fhéile Bríde"
[#"(?i)(l[áa] )?(fh[eé]ile|'?le) bh?r[íi]de"]
(month-day 2 1)
"Lá na nAithreacha"; third Sunday of June
[#"(?i)l[áa] na naithreacha"]
(intersect (day-of-week 7) (month 6) (cycle-nth-after :week 2 (month-day 6 1)))
; "Mother's Day"; fourth Sunday of Lent. Need Lent.
; #"(?i)mother'?s? day"
; (intersect (day-of-week 7) (month 5) (cycle-nth-after :week 1 (month-day 5 1)))
"absorption of , after named day"
[{:form :day-of-week} #","]
%1
"anois"
#"(?i)anois|(ag an (t-?)?am seo)"
(cycle-nth :second 0)
"inniu"
#"(?i)inniu"
(cycle-nth :day 0)
"amárach"
#"(?i)am[áa]rach"
(cycle-nth :day 1)
"arú amárach"
#"(?i)ar[úu] am[áa]rach"
(cycle-nth :day 2)
"inné"
#"(?i)inn[ée]"
(cycle-nth :day -1)
"arú inné"
#"(?i)ar[úu] inn[ée]"
(cycle-nth :day -2)
"<time> seo chugainn"
[(dim :time #(not (:latent %))) #"(?i)seo (chugainn|at[aá] ag teacht)"]
(pred-nth-not-immediate %1 0)
"<time> seo chaite"
[(dim :time) #"(?i)seo ch?aite"]
(pred-nth %1 -1)
"<time> seo"
[(dim :time) #"(?i)seo"]
(pred-nth %1 0)
; Years
; Between 1000 and 2100 we assume it's a year
; Outside of this, it's safer to consider it's latent
"year"
(integer 1000 2100)
(year (:value %1))
"year (latent)"
(integer -10000 999)
(assoc (year (:value %1)) :latent true)
"year (latent)"
(integer 2101 10000)
(assoc (year (:value %1)) :latent true)
; Day of month appears in the following context:
; - an 5ú
; - 6ú Feabhra
; - 6ú lá de Feabhra
; - dd/mm (and other numerical formats like yyyy-mm-dd etc.)
; In general we are flexible and accept both ordinals (3rd) and numbers (3)
"an <day-of-month> (ordinal)" ; this one is not latent
[#"(?i)an|na" (dim :ordinal #(<= 1 (:value %) 31))]
(day-of-month (:value %2))
"<day-of-month> (ordinal)" ; this one is latent
[(dim :ordinal #(<= 1 (:value %) 31))]
(assoc (day-of-month (:value %1)) :latent true)
"an <day-of-month> (non ordinal)" ; this one is latent
[#"(?i)an|na" (integer 1 31)]
(assoc (day-of-month (:value %2)) :latent true)
"<day-of-month>(ordinal) <named-month>" ; 12ú feabhra
[(dim :ordinal #(<= 1 (:value %) 31)) {:form :month}]
(intersect %2 (day-of-month (:value %1)))
"<day-of-month>(ordinal) <named-month> year" ; 12ú feabhra 2012
[(dim :ordinal #(<= 1 (:value %) 31)) {:form :month} #"(\d{2,4})"]
(intersect %2 (day-of-month (:value %1)) (year (Integer/parseInt(first (:groups %3)))))
; Formatted dates and times
"dd/mm/yyyy"
#"(3[01]|[12]\d|0?[1-9])[-/](0?[1-9]|1[0-2])[/-](\d{2,4})"
(parse-dmy (first (:groups %1)) (second (:groups %1)) (nth (:groups %1) 2) true)
"yyyy-mm-dd"
#"(\d{2,4})-(0?[1-9]|1[0-2])-(3[01]|[12]\d|0?[1-9])"
(parse-dmy (nth (:groups %1) 2) (second (:groups %1)) (first (:groups %1)) true)
"dd/mm"
#"(3[01]|[12]\d|0?[1-9])/(0?[1-9]|1[0-2])"
(parse-dmy (first (:groups %1)) (second (:groups %1)) nil true)
)
| 31482 | (
;; generic
"intersect"
[(dim :time #(not (:latent %))) (dim :time #(not (:latent %)))] ; sequence of two tokens with a time dimension
(intersect %1 %2)
; FIXME
; same thing, with "of" in between like "Sunday of last week"
; "intersect by \"of\", \"from\", \"'s\""
; [(dim :time #(not (:latent %))) #"(?i)of|from|for|'s" (dim :time #(not (:latent %)))] ; sequence of two tokens with a time fn
; (intersect %1 %3)
; mostly for January 12, 2005
; this is a separate rule, because commas separate very specific tokens
; so we want this rule's classifier to learn this
"intersect by \",\""
[(dim :time #(not (:latent %))) #"," (dim :time #(not (:latent %)))] ; sequence of two tokens with a time fn
(intersect %1 %3)
"ar <date>" ; ar Wed, March 23 ;FIXME
[#"(?i)ar" (dim :time)]
%2 ; does NOT dissoc latent
"on a named-day" ; ar an luan
[#"(?i)ar an" {:form :day-of-week}]
%2 ; does NOT dissoc latent
"dé named-day" ; dé luain
[#"(?i)d[ée]" {:form :day-of-week}]
%2 ; does NOT dissoc latent
"an named-day" ; an luan
[#"(?i)an" {:form :day-of-week}]
%2 ; does NOT dissoc latent
;;;;;;;;;;;;;;;;;;;
;; Named things
"named-day"
#"(?i)luai?n|lu\.?"
(day-of-week 1)
"named-day"
#"(?i)mh?[áa]irt|m[áa]?\.?"
(day-of-week 2)
"named-day"
#"(?i)ch?[ée]adaoin|c[ée]\.?"
(day-of-week 3)
"named-day"
#"(?i)d[ée]ardaoin|d[ée]?\.?"
(day-of-week 4)
"named-day"
#"(?i)h?aoine|ao\.?"
(day-of-week 5)
"named-day"
#"(?i)sathai?rn|sa\.?"
(day-of-week 6)
"named-day"
#"(?i)domhnai?[cg]h|do\.?"
(day-of-week 7)
"named-month"
#"(?i)(mh?[íi] )?(an )?t?ean[áa]ir|ean\.?"
(month 1)
"named-month"
#"(?i)(mh?[íi] )?(na )?feabhra|fea\.?"
(month 2)
"named-month"
#"(?i)(mh?[íi] )?(an )?mh?[áa]rta|m[áa]r\.?"
(month 3)
"named-month"
#"(?i)(mh?[íi] )?(an )?t?aibre[áa]i?n|abr\.?"
(month 4)
"named-month"
#"(?i)(mh?[íi] )?(na )?bh?ealtaine|bea\.?"
(month 5)
"named-month"
#"(?i)(mh?[íi] )?(an )?mh?eith(ea|i)mh|mei\.?"
(month 6)
"named-month"
#"(?i)(mh?[íi] )?i[úu]il|i[úu]i\.?"
(month 7)
"named-month"
#"(?i)(mh?[íi] )?(na )?l[úu]nasa|l[úu]n\.?"
(month 8)
"named-month"
#"(?i)(mh?[íi] )?mh?e[áa]n f[óo]mhair|mef?\.?"
(month 9)
"named-month"
#"(?i)(mh?[íi] )?dh?eireadh f[óo]mhair|def?\.?"
(month 10)
"named-month"
#"(?i)(mh?[íi] )?(na )?samh(ain|na)|sam\.?"
(month 11)
"named-month"
#"(?i)(mh?[íi] )?(na )?nollai?g|nol\.?"
(month 12)
; Holiday TODO: check online holidays
; or define dynamic rule (last thursday of october..)
"An Nollaig" ; "Mí na Nollag" is literally "month of Christmas", so collision with month
[#"(?i)(l[áa] |an )?(nollai?g)"]
(month-day 12 25)
"Nollaig na mBan"
[#"(?i)(l[áa] |an )?nollaig (bheag|na mban)"]
(month-day 1 6)
"<NAME>"
[#"(?i)(l[áa] )?(fh[eé]ile|'?le) vailint[íi]n"]
(month-day 2 14)
"<NAME>"
[#"(?i)(l[áa] )?(fh[eé]ile|'?le) ph?[áa]draig"]
(month-day 3 17)
"<NAME>"
[#"(?i)(l[áa] )?(fh[eé]ile|'?le) bh?r[íi]de"]
(month-day 2 1)
"Lá na nAithreacha"; third Sunday of June
[#"(?i)l[áa] na naithreacha"]
(intersect (day-of-week 7) (month 6) (cycle-nth-after :week 2 (month-day 6 1)))
; "Mother's Day"; fourth Sunday of Lent. Need Lent.
; #"(?i)mother'?s? day"
; (intersect (day-of-week 7) (month 5) (cycle-nth-after :week 1 (month-day 5 1)))
"absorption of , after named day"
[{:form :day-of-week} #","]
%1
"anois"
#"(?i)anois|(ag an (t-?)?am seo)"
(cycle-nth :second 0)
"inniu"
#"(?i)inniu"
(cycle-nth :day 0)
"amárach"
#"(?i)am[áa]rach"
(cycle-nth :day 1)
"arú amárach"
#"(?i)ar[úu] am[áa]rach"
(cycle-nth :day 2)
"inné"
#"(?i)inn[ée]"
(cycle-nth :day -1)
"arú inné"
#"(?i)ar[úu] inn[ée]"
(cycle-nth :day -2)
"<time> seo chugainn"
[(dim :time #(not (:latent %))) #"(?i)seo (chugainn|at[aá] ag teacht)"]
(pred-nth-not-immediate %1 0)
"<time> seo chaite"
[(dim :time) #"(?i)seo ch?aite"]
(pred-nth %1 -1)
"<time> seo"
[(dim :time) #"(?i)seo"]
(pred-nth %1 0)
; Years
; Between 1000 and 2100 we assume it's a year
; Outside of this, it's safer to consider it's latent
"year"
(integer 1000 2100)
(year (:value %1))
"year (latent)"
(integer -10000 999)
(assoc (year (:value %1)) :latent true)
"year (latent)"
(integer 2101 10000)
(assoc (year (:value %1)) :latent true)
; Day of month appears in the following context:
; - an 5ú
; - 6ú Feabhra
; - 6ú lá de Feabhra
; - dd/mm (and other numerical formats like yyyy-mm-dd etc.)
; In general we are flexible and accept both ordinals (3rd) and numbers (3)
"an <day-of-month> (ordinal)" ; this one is not latent
[#"(?i)an|na" (dim :ordinal #(<= 1 (:value %) 31))]
(day-of-month (:value %2))
"<day-of-month> (ordinal)" ; this one is latent
[(dim :ordinal #(<= 1 (:value %) 31))]
(assoc (day-of-month (:value %1)) :latent true)
"an <day-of-month> (non ordinal)" ; this one is latent
[#"(?i)an|na" (integer 1 31)]
(assoc (day-of-month (:value %2)) :latent true)
"<day-of-month>(ordinal) <named-month>" ; 12ú feabhra
[(dim :ordinal #(<= 1 (:value %) 31)) {:form :month}]
(intersect %2 (day-of-month (:value %1)))
"<day-of-month>(ordinal) <named-month> year" ; 12ú feabhra 2012
[(dim :ordinal #(<= 1 (:value %) 31)) {:form :month} #"(\d{2,4})"]
(intersect %2 (day-of-month (:value %1)) (year (Integer/parseInt(first (:groups %3)))))
; Formatted dates and times
"dd/mm/yyyy"
#"(3[01]|[12]\d|0?[1-9])[-/](0?[1-9]|1[0-2])[/-](\d{2,4})"
(parse-dmy (first (:groups %1)) (second (:groups %1)) (nth (:groups %1) 2) true)
"yyyy-mm-dd"
#"(\d{2,4})-(0?[1-9]|1[0-2])-(3[01]|[12]\d|0?[1-9])"
(parse-dmy (nth (:groups %1) 2) (second (:groups %1)) (first (:groups %1)) true)
"dd/mm"
#"(3[01]|[12]\d|0?[1-9])/(0?[1-9]|1[0-2])"
(parse-dmy (first (:groups %1)) (second (:groups %1)) nil true)
)
| true | (
;; generic
"intersect"
[(dim :time #(not (:latent %))) (dim :time #(not (:latent %)))] ; sequence of two tokens with a time dimension
(intersect %1 %2)
; FIXME
; same thing, with "of" in between like "Sunday of last week"
; "intersect by \"of\", \"from\", \"'s\""
; [(dim :time #(not (:latent %))) #"(?i)of|from|for|'s" (dim :time #(not (:latent %)))] ; sequence of two tokens with a time fn
; (intersect %1 %3)
; mostly for January 12, 2005
; this is a separate rule, because commas separate very specific tokens
; so we want this rule's classifier to learn this
"intersect by \",\""
[(dim :time #(not (:latent %))) #"," (dim :time #(not (:latent %)))] ; sequence of two tokens with a time fn
(intersect %1 %3)
"ar <date>" ; ar Wed, March 23 ;FIXME
[#"(?i)ar" (dim :time)]
%2 ; does NOT dissoc latent
"on a named-day" ; ar an luan
[#"(?i)ar an" {:form :day-of-week}]
%2 ; does NOT dissoc latent
"dé named-day" ; dé luain
[#"(?i)d[ée]" {:form :day-of-week}]
%2 ; does NOT dissoc latent
"an named-day" ; an luan
[#"(?i)an" {:form :day-of-week}]
%2 ; does NOT dissoc latent
;;;;;;;;;;;;;;;;;;;
;; Named things
"named-day"
#"(?i)luai?n|lu\.?"
(day-of-week 1)
"named-day"
#"(?i)mh?[áa]irt|m[áa]?\.?"
(day-of-week 2)
"named-day"
#"(?i)ch?[ée]adaoin|c[ée]\.?"
(day-of-week 3)
"named-day"
#"(?i)d[ée]ardaoin|d[ée]?\.?"
(day-of-week 4)
"named-day"
#"(?i)h?aoine|ao\.?"
(day-of-week 5)
"named-day"
#"(?i)sathai?rn|sa\.?"
(day-of-week 6)
"named-day"
#"(?i)domhnai?[cg]h|do\.?"
(day-of-week 7)
"named-month"
#"(?i)(mh?[íi] )?(an )?t?ean[áa]ir|ean\.?"
(month 1)
"named-month"
#"(?i)(mh?[íi] )?(na )?feabhra|fea\.?"
(month 2)
"named-month"
#"(?i)(mh?[íi] )?(an )?mh?[áa]rta|m[áa]r\.?"
(month 3)
"named-month"
#"(?i)(mh?[íi] )?(an )?t?aibre[áa]i?n|abr\.?"
(month 4)
"named-month"
#"(?i)(mh?[íi] )?(na )?bh?ealtaine|bea\.?"
(month 5)
"named-month"
#"(?i)(mh?[íi] )?(an )?mh?eith(ea|i)mh|mei\.?"
(month 6)
"named-month"
#"(?i)(mh?[íi] )?i[úu]il|i[úu]i\.?"
(month 7)
"named-month"
#"(?i)(mh?[íi] )?(na )?l[úu]nasa|l[úu]n\.?"
(month 8)
"named-month"
#"(?i)(mh?[íi] )?mh?e[áa]n f[óo]mhair|mef?\.?"
(month 9)
"named-month"
#"(?i)(mh?[íi] )?dh?eireadh f[óo]mhair|def?\.?"
(month 10)
"named-month"
#"(?i)(mh?[íi] )?(na )?samh(ain|na)|sam\.?"
(month 11)
"named-month"
#"(?i)(mh?[íi] )?(na )?nollai?g|nol\.?"
(month 12)
; Holiday TODO: check online holidays
; or define dynamic rule (last thursday of october..)
"An Nollaig" ; "Mí na Nollag" is literally "month of Christmas", so collision with month
[#"(?i)(l[áa] |an )?(nollai?g)"]
(month-day 12 25)
"Nollaig na mBan"
[#"(?i)(l[áa] |an )?nollaig (bheag|na mban)"]
(month-day 1 6)
"PI:NAME:<NAME>END_PI"
[#"(?i)(l[áa] )?(fh[eé]ile|'?le) vailint[íi]n"]
(month-day 2 14)
"PI:NAME:<NAME>END_PI"
[#"(?i)(l[áa] )?(fh[eé]ile|'?le) ph?[áa]draig"]
(month-day 3 17)
"PI:NAME:<NAME>END_PI"
[#"(?i)(l[áa] )?(fh[eé]ile|'?le) bh?r[íi]de"]
(month-day 2 1)
"Lá na nAithreacha"; third Sunday of June
[#"(?i)l[áa] na naithreacha"]
(intersect (day-of-week 7) (month 6) (cycle-nth-after :week 2 (month-day 6 1)))
; "Mother's Day"; fourth Sunday of Lent. Need Lent.
; #"(?i)mother'?s? day"
; (intersect (day-of-week 7) (month 5) (cycle-nth-after :week 1 (month-day 5 1)))
"absorption of , after named day"
[{:form :day-of-week} #","]
%1
"anois"
#"(?i)anois|(ag an (t-?)?am seo)"
(cycle-nth :second 0)
"inniu"
#"(?i)inniu"
(cycle-nth :day 0)
"amárach"
#"(?i)am[áa]rach"
(cycle-nth :day 1)
"arú amárach"
#"(?i)ar[úu] am[áa]rach"
(cycle-nth :day 2)
"inné"
#"(?i)inn[ée]"
(cycle-nth :day -1)
"arú inné"
#"(?i)ar[úu] inn[ée]"
(cycle-nth :day -2)
"<time> seo chugainn"
[(dim :time #(not (:latent %))) #"(?i)seo (chugainn|at[aá] ag teacht)"]
(pred-nth-not-immediate %1 0)
"<time> seo chaite"
[(dim :time) #"(?i)seo ch?aite"]
(pred-nth %1 -1)
"<time> seo"
[(dim :time) #"(?i)seo"]
(pred-nth %1 0)
; Years
; Between 1000 and 2100 we assume it's a year
; Outside of this, it's safer to consider it's latent
"year"
(integer 1000 2100)
(year (:value %1))
"year (latent)"
(integer -10000 999)
(assoc (year (:value %1)) :latent true)
"year (latent)"
(integer 2101 10000)
(assoc (year (:value %1)) :latent true)
; Day of month appears in the following context:
; - an 5ú
; - 6ú Feabhra
; - 6ú lá de Feabhra
; - dd/mm (and other numerical formats like yyyy-mm-dd etc.)
; In general we are flexible and accept both ordinals (3rd) and numbers (3)
"an <day-of-month> (ordinal)" ; this one is not latent
[#"(?i)an|na" (dim :ordinal #(<= 1 (:value %) 31))]
(day-of-month (:value %2))
"<day-of-month> (ordinal)" ; this one is latent
[(dim :ordinal #(<= 1 (:value %) 31))]
(assoc (day-of-month (:value %1)) :latent true)
"an <day-of-month> (non ordinal)" ; this one is latent
[#"(?i)an|na" (integer 1 31)]
(assoc (day-of-month (:value %2)) :latent true)
"<day-of-month>(ordinal) <named-month>" ; 12ú feabhra
[(dim :ordinal #(<= 1 (:value %) 31)) {:form :month}]
(intersect %2 (day-of-month (:value %1)))
"<day-of-month>(ordinal) <named-month> year" ; 12ú feabhra 2012
[(dim :ordinal #(<= 1 (:value %) 31)) {:form :month} #"(\d{2,4})"]
(intersect %2 (day-of-month (:value %1)) (year (Integer/parseInt(first (:groups %3)))))
; Formatted dates and times
"dd/mm/yyyy"
#"(3[01]|[12]\d|0?[1-9])[-/](0?[1-9]|1[0-2])[/-](\d{2,4})"
(parse-dmy (first (:groups %1)) (second (:groups %1)) (nth (:groups %1) 2) true)
"yyyy-mm-dd"
#"(\d{2,4})-(0?[1-9]|1[0-2])-(3[01]|[12]\d|0?[1-9])"
(parse-dmy (nth (:groups %1) 2) (second (:groups %1)) (first (:groups %1)) true)
"dd/mm"
#"(3[01]|[12]\d|0?[1-9])/(0?[1-9]|1[0-2])"
(parse-dmy (first (:groups %1)) (second (:groups %1)) nil true)
)
|
[
{
"context": "lPort 123\n :senderUsername \"senderUsername\"\n :senderPassword \"senderPw",
"end": 613,
"score": 0.9995516538619995,
"start": 599,
"tag": "USERNAME",
"value": "senderUsername"
},
{
"context": "Username\"\n :senderPassword \"senderPwd\"\n :senderEmail \"sender@doma",
"end": 664,
"score": 0.9994335174560547,
"start": 655,
"tag": "PASSWORD",
"value": "senderPwd"
},
{
"context": " \"senderPwd\"\n :senderEmail \"sender@domain.com\"\n :senderId \"senderId\"})\n\n(",
"end": 720,
"score": 0.9999138712882996,
"start": 703,
"tag": "EMAIL",
"value": "sender@domain.com"
},
{
"context": "nfig-dao/get-user-config-by-username h2-db \"senderUsername\") => user-config-test)\n \n (fact \"get-",
"end": 1756,
"score": 0.5169797539710999,
"start": 1748,
"tag": "USERNAME",
"value": "Username"
},
{
"context": " (user-config-dao/get-user-config-by-email h2-db \"sender@domain.com\") => user-config-test)\n \n (fact \"get-",
"end": 2152,
"score": 0.9998888969421387,
"start": 2135,
"tag": "EMAIL",
"value": "sender@domain.com"
}
] | test/mofficer/persistence/user_config_dao_test.clj | granpanda/mofficer | 1 | (ns mofficer.persistence.user-config-dao-test
(:use [midje.sweet])
(:require [clojure.java.jdbc :as jdbc-clj]
[mofficer.domain.entities.user-config]
[mofficer.persistence.user-config-dao :as user-config-dao])
(:import [mofficer.domain.entities.user_config UserConfig]))
(def h2-db {:subprotocol "h2"
:subname "jdbc:h2:tcp://localhost/mem:testdb;DATABASE_TO_UPPER=FALSE"
:user "sa"
:password ""})
(def user-config-test {:emailHost "http://www.gmail.com"
:emailPort 123
:senderUsername "senderUsername"
:senderPassword "senderPwd"
:senderEmail "sender@domain.com"
:senderId "senderId"})
(defn drop-db [db]
(let [drop-table-sql (str "DROP TABLE IF EXISTS " user-config-dao/user-config-table-name)]
(jdbc-clj/db-do-commands db drop-table-sql)))
(background (before :facts (user-config-dao/create-user-configs-table-if-not-exists h2-db))
(after :facts (drop-db h2-db)))
(facts "About the user-config-dao:"
(fact "create-user-config creates a new user config into the database."
(user-config-dao/count-table-rows h2-db) => 0
(user-config-dao/create-user-config h2-db user-config-test) => true
(user-config-dao/count-table-rows h2-db) => 1)
(fact "get-user-config-by-username returns the user-config with the given username."
(user-config-dao/count-table-rows h2-db) => 0
(user-config-dao/create-user-config h2-db user-config-test) => true
(user-config-dao/count-table-rows h2-db) => 1
(user-config-dao/get-user-config-by-username h2-db "senderUsername") => user-config-test)
(fact "get-user-config-by-email returns the user-config with the given email."
(user-config-dao/count-table-rows h2-db) => 0
(user-config-dao/create-user-config h2-db user-config-test) => true
(user-config-dao/count-table-rows h2-db) => 1
(user-config-dao/get-user-config-by-email h2-db "sender@domain.com") => user-config-test)
(fact "get-user-config-by-sender-id returns the user-config with the given ID."
(user-config-dao/count-table-rows h2-db) => 0
(user-config-dao/create-user-config h2-db user-config-test) => true
(user-config-dao/count-table-rows h2-db) => 1
(user-config-dao/get-user-config-by-sender-id h2-db "senderId") => user-config-test))
| 90418 | (ns mofficer.persistence.user-config-dao-test
(:use [midje.sweet])
(:require [clojure.java.jdbc :as jdbc-clj]
[mofficer.domain.entities.user-config]
[mofficer.persistence.user-config-dao :as user-config-dao])
(:import [mofficer.domain.entities.user_config UserConfig]))
(def h2-db {:subprotocol "h2"
:subname "jdbc:h2:tcp://localhost/mem:testdb;DATABASE_TO_UPPER=FALSE"
:user "sa"
:password ""})
(def user-config-test {:emailHost "http://www.gmail.com"
:emailPort 123
:senderUsername "senderUsername"
:senderPassword "<PASSWORD>"
:senderEmail "<EMAIL>"
:senderId "senderId"})
(defn drop-db [db]
(let [drop-table-sql (str "DROP TABLE IF EXISTS " user-config-dao/user-config-table-name)]
(jdbc-clj/db-do-commands db drop-table-sql)))
(background (before :facts (user-config-dao/create-user-configs-table-if-not-exists h2-db))
(after :facts (drop-db h2-db)))
(facts "About the user-config-dao:"
(fact "create-user-config creates a new user config into the database."
(user-config-dao/count-table-rows h2-db) => 0
(user-config-dao/create-user-config h2-db user-config-test) => true
(user-config-dao/count-table-rows h2-db) => 1)
(fact "get-user-config-by-username returns the user-config with the given username."
(user-config-dao/count-table-rows h2-db) => 0
(user-config-dao/create-user-config h2-db user-config-test) => true
(user-config-dao/count-table-rows h2-db) => 1
(user-config-dao/get-user-config-by-username h2-db "senderUsername") => user-config-test)
(fact "get-user-config-by-email returns the user-config with the given email."
(user-config-dao/count-table-rows h2-db) => 0
(user-config-dao/create-user-config h2-db user-config-test) => true
(user-config-dao/count-table-rows h2-db) => 1
(user-config-dao/get-user-config-by-email h2-db "<EMAIL>") => user-config-test)
(fact "get-user-config-by-sender-id returns the user-config with the given ID."
(user-config-dao/count-table-rows h2-db) => 0
(user-config-dao/create-user-config h2-db user-config-test) => true
(user-config-dao/count-table-rows h2-db) => 1
(user-config-dao/get-user-config-by-sender-id h2-db "senderId") => user-config-test))
| true | (ns mofficer.persistence.user-config-dao-test
(:use [midje.sweet])
(:require [clojure.java.jdbc :as jdbc-clj]
[mofficer.domain.entities.user-config]
[mofficer.persistence.user-config-dao :as user-config-dao])
(:import [mofficer.domain.entities.user_config UserConfig]))
(def h2-db {:subprotocol "h2"
:subname "jdbc:h2:tcp://localhost/mem:testdb;DATABASE_TO_UPPER=FALSE"
:user "sa"
:password ""})
(def user-config-test {:emailHost "http://www.gmail.com"
:emailPort 123
:senderUsername "senderUsername"
:senderPassword "PI:PASSWORD:<PASSWORD>END_PI"
:senderEmail "PI:EMAIL:<EMAIL>END_PI"
:senderId "senderId"})
(defn drop-db [db]
(let [drop-table-sql (str "DROP TABLE IF EXISTS " user-config-dao/user-config-table-name)]
(jdbc-clj/db-do-commands db drop-table-sql)))
(background (before :facts (user-config-dao/create-user-configs-table-if-not-exists h2-db))
(after :facts (drop-db h2-db)))
(facts "About the user-config-dao:"
(fact "create-user-config creates a new user config into the database."
(user-config-dao/count-table-rows h2-db) => 0
(user-config-dao/create-user-config h2-db user-config-test) => true
(user-config-dao/count-table-rows h2-db) => 1)
(fact "get-user-config-by-username returns the user-config with the given username."
(user-config-dao/count-table-rows h2-db) => 0
(user-config-dao/create-user-config h2-db user-config-test) => true
(user-config-dao/count-table-rows h2-db) => 1
(user-config-dao/get-user-config-by-username h2-db "senderUsername") => user-config-test)
(fact "get-user-config-by-email returns the user-config with the given email."
(user-config-dao/count-table-rows h2-db) => 0
(user-config-dao/create-user-config h2-db user-config-test) => true
(user-config-dao/count-table-rows h2-db) => 1
(user-config-dao/get-user-config-by-email h2-db "PI:EMAIL:<EMAIL>END_PI") => user-config-test)
(fact "get-user-config-by-sender-id returns the user-config with the given ID."
(user-config-dao/count-table-rows h2-db) => 0
(user-config-dao/create-user-config h2-db user-config-test) => true
(user-config-dao/count-table-rows h2-db) => 1
(user-config-dao/get-user-config-by-sender-id h2-db "senderId") => user-config-test))
|
[
{
"context": " {[:user uid] {:user/email \"username@example.com\"}})\n :db-before :db-after :se",
"end": 5457,
"score": 0.9999149441719055,
"start": 5437,
"tag": "EMAIL",
"value": "username@example.com"
},
{
"context": " {:changes [{:tx-item [[:user uid] #:user{:email \"username@example.com\"}],\n :doc-id uid\n ",
"end": 5605,
"score": 0.999914288520813,
"start": 5585,
"tag": "EMAIL",
"value": "username@example.com"
},
{
"context": "il,\n :after {:user/email \"username@example.com\",\n :crux.db/id uid}}],\n ",
"end": 5793,
"score": 0.9999136924743652,
"start": 5773,
"tag": "EMAIL",
"value": "username@example.com"
},
{
"context": " [:crux.tx/put {:user/email \"username@example.com\",\n :crux.db",
"end": 5963,
"score": 0.9999122619628906,
"start": 5943,
"tag": "EMAIL",
"value": "username@example.com"
}
] | libs/tests/src/biff/crux_test.clj | jeffp42ker/biff | 273 | (ns biff.crux-test
(:require
[biff.crux :as bc]
[biff.util :as bu]
[crux.api :as crux]
[biff.misc :as misc]
[clojure.test :refer [deftest is run-tests]]))
(defn submit-await-tx [node tx]
(crux/await-tx
node
(crux/submit-tx
node
tx)))
(defn start-node [docs]
(let [node (crux/start-node {})]
(when (not-empty docs)
(crux/await-tx
node
(crux/submit-tx
node
(for [d docs]
[:crux.tx/put d]))))
node))
(deftest test-foo
(is (= 4 (+ 2 2))))
(defn authorize [{:keys [doc-type operation]} & _]
(case [doc-type operation]
[:foo :read] true
[:bar :create] true
false))
(def doc {:crux.db/id :foo})
(deftest check-read
(is (some? (bc/check-read {} {:docs [doc]})))
(with-redefs [bc/authorize (constantly true)]
(is (nil? (bc/check-read {} {:docs [doc]}))))
(with-redefs [bc/authorize authorize]
(is (nil? (bc/check-read
{}
{:query {:doc-type :foo
:where []}
:docs [doc]})))))
(deftest check-write
(is (some? (bc/check-write {} {:changes [{:after doc}]})))
(with-redefs [bc/authorize (constantly true)]
(is (nil? (bc/check-write {} {:changes [{:after doc}]}))))
(with-redefs [bc/authorize authorize]
(is (nil? (bc/check-write
{}
{:changes [{:after doc
:doc-type :bar}]})))))
(deftest normalize-tx-doc
(is (= {:crux.db/id {:foo "bar"}
:foo "bar"
:yeeted-at #inst "1970"
:numbers #{1 2 3}
:ek-ek-ek #{:whoppa}
:flavors #{"peach"}
:hot-dogs 116
:hello "there"}
(bc/normalize-tx-doc
{:doc-id {:foo "bar"}
:tx-doc {:db/merge true
:yeeted-at :db/server-timestamp
:numbers [:db/union 1 2]
:ek-ek-ek [:db/union :whoppa]
:flavors [:db/difference "dirt"]
:zebra :db/remove
:hot-dogs [:db/add 50]}
:server-timestamp #inst "1970"
:before {:hello "there"
:numbers #{3}
:flavors #{"peach" "dirt"}
:zebra "kevin"
:hot-dogs 66}}))))
(deftest get-changes
(let [random-ids [:x :y :z]
expected [{:tx-item [[:foo :c] {:hello "there"}]
:doc-id :c
:doc-type :foo
:before nil
:after {:crux.db/id :c
:hello "there"}}
{:tx-item [[:foo] {:hello "there"
:db/merge true}]
:doc-id :y
:doc-type :foo
:before {:crux.db/id :y
:a "b"}
:after {:crux.db/id :y
:hello "there"
:a "b"}}
{:tx-item [[:foo :a] nil]
:doc-id :a
:doc-type :foo
:before {:crux.db/id :a
:a "b"}
:after nil}]]
(with-open [node (start-node
[{:crux.db/id :y :a "b"}
{:crux.db/id :a :a "b"}])]
(is (= expected
(bc/get-changes
{:db (crux/db node)
:random-uuids random-ids
:biff-tx (map :tx-item expected)}))))))
(def registry
{:user/id :uuid
:user/email :string
:user/foo :string
:user/bar :string
:user [:map {:closed true}
[:crux.db/id :user/id]
:user/email
[:user/foo {:optional true}]
[:user/bar {:optional true}]]
:msg/id :uuid
:msg/user :user/id
:msg/text :string
:msg/sent-at inst?
:msg [:map {:closed true}
[:crux.db/id :msg/id]
:msg/user
:msg/text
:msg/sent-at]})
(def schema (misc/map->MalliSchema
{:doc-types [:user :msg]
:malli-opts {:registry (misc/malli-registry registry)}}))
(deftest get-tx-info
(is (thrown-with-msg?
Exception #"TX doesn't match schema."
(bc/get-tx-info nil {1 {:foo "bar"}})))
(with-open [node (start-node [])]
(is (some? (bc/get-tx-info
{:biff/schema schema
:biff.crux/db (delay (crux/db node))}
{}))))
(with-open [node (start-node [])]
(is (thrown-with-msg?
Exception #"Attempted to update on a new doc."
(bc/get-tx-info
{:biff/schema schema
:biff.crux/db (delay (crux/db node))}
{[:user] {:db/update true}}))))
(with-open [node (start-node [])]
(is (thrown-with-msg?
Exception #"Doc doesn't match doc-type."
(bc/get-tx-info
{:biff/schema schema
:biff.crux/db (delay (crux/db node))}
{[:user #uuid "0b5377f2-126d-44c9-b73c-d90f0efd0d7c"]
{:hello "there"}}))))
(with-open [node (start-node [])]
(let [uid (java.util.UUID/randomUUID)]
(is (= (dissoc (bc/get-tx-info
{:biff/schema schema
:biff.crux/db (delay (crux/db node))}
{[:user uid] {:user/email "username@example.com"}})
:db-before :db-after :server-timestamp)
{:changes [{:tx-item [[:user uid] #:user{:email "username@example.com"}],
:doc-id uid
:doc-type :user,
:before nil,
:after {:user/email "username@example.com",
:crux.db/id uid}}],
:crux-tx [[:crux.tx/match uid nil]
[:crux.tx/put {:user/email "username@example.com",
:crux.db/id uid}]]})))))
(deftest subscription+updates
(with-open [node (start-node [{:crux.db/id :foo
:a 1}])]
(is (= (#'bc/subscription+updates
{:txes [{:crux.tx.event/tx-events [[nil :foo]]}]
:db-before (crux/db node)
:db-after (crux/with-tx (crux/db node)
[[:crux.tx/put {:crux.db/id :foo
:a 2}]])
:subscriptions #{{:query {:id :foo
:doc-type :x}}
{:query {:where [[:a 1]]
:doc-type :x}}
{:query {:where '[[:a a]
[(<= a 2)]]
:doc-type :x}}
{:query {:id :bar
:doc-type :x}}}})
'([{:query {:id :foo,
:doc-type :x}}
{[:x :foo] {:crux.db/id :foo,
:a 2}}]
[{:query {:where [[:a 1]],
:doc-type :x}}
{[:x :foo] nil}]
[{:query {:where [[:a a]
[(<= a 2)]],
:doc-type :x}}
{[:x :foo] {:crux.db/id :foo,
:a 2}}])))))
(deftest biff-q
(with-open [node (start-node [{:crux.db/id :foo
:a 1}])]
(with-redefs [bc/check-read (constantly nil)]
(is (= (bc/biff-q {:biff.crux/db (delay (crux/db node))}
{:doc-type :x
:id :foo})
{[:x :foo] {:crux.db/id :foo, :a 1}}))
(is (= (bc/biff-q {:biff.crux/db (delay (crux/db node))}
{:doc-type :x
:where [[:a]]})
{[:x :foo] {:crux.db/id :foo, :a 1}}))
(is (= (bc/biff-q {:biff.crux/db (delay (crux/db node))}
{:doc-type :x
:where '[[:a a]
[(== a 1)]]})
{[:x :foo] {:crux.db/id :foo, :a 1}}))
(is (= (bc/biff-q {:biff.crux/db (delay (crux/db node))}
{:doc-type :x
:where [[:b]]})
{}))
(is (thrown-with-msg?
Exception #"fn in query not authorized."
(bc/biff-q {:biff.crux/db (delay (crux/db node))}
{:doc-type :x
:where '[[:a 1]
[(foo)]]}))))))
#_(run-tests)
| 78317 | (ns biff.crux-test
(:require
[biff.crux :as bc]
[biff.util :as bu]
[crux.api :as crux]
[biff.misc :as misc]
[clojure.test :refer [deftest is run-tests]]))
(defn submit-await-tx [node tx]
(crux/await-tx
node
(crux/submit-tx
node
tx)))
(defn start-node [docs]
(let [node (crux/start-node {})]
(when (not-empty docs)
(crux/await-tx
node
(crux/submit-tx
node
(for [d docs]
[:crux.tx/put d]))))
node))
(deftest test-foo
(is (= 4 (+ 2 2))))
(defn authorize [{:keys [doc-type operation]} & _]
(case [doc-type operation]
[:foo :read] true
[:bar :create] true
false))
(def doc {:crux.db/id :foo})
(deftest check-read
(is (some? (bc/check-read {} {:docs [doc]})))
(with-redefs [bc/authorize (constantly true)]
(is (nil? (bc/check-read {} {:docs [doc]}))))
(with-redefs [bc/authorize authorize]
(is (nil? (bc/check-read
{}
{:query {:doc-type :foo
:where []}
:docs [doc]})))))
(deftest check-write
(is (some? (bc/check-write {} {:changes [{:after doc}]})))
(with-redefs [bc/authorize (constantly true)]
(is (nil? (bc/check-write {} {:changes [{:after doc}]}))))
(with-redefs [bc/authorize authorize]
(is (nil? (bc/check-write
{}
{:changes [{:after doc
:doc-type :bar}]})))))
(deftest normalize-tx-doc
(is (= {:crux.db/id {:foo "bar"}
:foo "bar"
:yeeted-at #inst "1970"
:numbers #{1 2 3}
:ek-ek-ek #{:whoppa}
:flavors #{"peach"}
:hot-dogs 116
:hello "there"}
(bc/normalize-tx-doc
{:doc-id {:foo "bar"}
:tx-doc {:db/merge true
:yeeted-at :db/server-timestamp
:numbers [:db/union 1 2]
:ek-ek-ek [:db/union :whoppa]
:flavors [:db/difference "dirt"]
:zebra :db/remove
:hot-dogs [:db/add 50]}
:server-timestamp #inst "1970"
:before {:hello "there"
:numbers #{3}
:flavors #{"peach" "dirt"}
:zebra "kevin"
:hot-dogs 66}}))))
(deftest get-changes
(let [random-ids [:x :y :z]
expected [{:tx-item [[:foo :c] {:hello "there"}]
:doc-id :c
:doc-type :foo
:before nil
:after {:crux.db/id :c
:hello "there"}}
{:tx-item [[:foo] {:hello "there"
:db/merge true}]
:doc-id :y
:doc-type :foo
:before {:crux.db/id :y
:a "b"}
:after {:crux.db/id :y
:hello "there"
:a "b"}}
{:tx-item [[:foo :a] nil]
:doc-id :a
:doc-type :foo
:before {:crux.db/id :a
:a "b"}
:after nil}]]
(with-open [node (start-node
[{:crux.db/id :y :a "b"}
{:crux.db/id :a :a "b"}])]
(is (= expected
(bc/get-changes
{:db (crux/db node)
:random-uuids random-ids
:biff-tx (map :tx-item expected)}))))))
(def registry
{:user/id :uuid
:user/email :string
:user/foo :string
:user/bar :string
:user [:map {:closed true}
[:crux.db/id :user/id]
:user/email
[:user/foo {:optional true}]
[:user/bar {:optional true}]]
:msg/id :uuid
:msg/user :user/id
:msg/text :string
:msg/sent-at inst?
:msg [:map {:closed true}
[:crux.db/id :msg/id]
:msg/user
:msg/text
:msg/sent-at]})
(def schema (misc/map->MalliSchema
{:doc-types [:user :msg]
:malli-opts {:registry (misc/malli-registry registry)}}))
(deftest get-tx-info
(is (thrown-with-msg?
Exception #"TX doesn't match schema."
(bc/get-tx-info nil {1 {:foo "bar"}})))
(with-open [node (start-node [])]
(is (some? (bc/get-tx-info
{:biff/schema schema
:biff.crux/db (delay (crux/db node))}
{}))))
(with-open [node (start-node [])]
(is (thrown-with-msg?
Exception #"Attempted to update on a new doc."
(bc/get-tx-info
{:biff/schema schema
:biff.crux/db (delay (crux/db node))}
{[:user] {:db/update true}}))))
(with-open [node (start-node [])]
(is (thrown-with-msg?
Exception #"Doc doesn't match doc-type."
(bc/get-tx-info
{:biff/schema schema
:biff.crux/db (delay (crux/db node))}
{[:user #uuid "0b5377f2-126d-44c9-b73c-d90f0efd0d7c"]
{:hello "there"}}))))
(with-open [node (start-node [])]
(let [uid (java.util.UUID/randomUUID)]
(is (= (dissoc (bc/get-tx-info
{:biff/schema schema
:biff.crux/db (delay (crux/db node))}
{[:user uid] {:user/email "<EMAIL>"}})
:db-before :db-after :server-timestamp)
{:changes [{:tx-item [[:user uid] #:user{:email "<EMAIL>"}],
:doc-id uid
:doc-type :user,
:before nil,
:after {:user/email "<EMAIL>",
:crux.db/id uid}}],
:crux-tx [[:crux.tx/match uid nil]
[:crux.tx/put {:user/email "<EMAIL>",
:crux.db/id uid}]]})))))
(deftest subscription+updates
(with-open [node (start-node [{:crux.db/id :foo
:a 1}])]
(is (= (#'bc/subscription+updates
{:txes [{:crux.tx.event/tx-events [[nil :foo]]}]
:db-before (crux/db node)
:db-after (crux/with-tx (crux/db node)
[[:crux.tx/put {:crux.db/id :foo
:a 2}]])
:subscriptions #{{:query {:id :foo
:doc-type :x}}
{:query {:where [[:a 1]]
:doc-type :x}}
{:query {:where '[[:a a]
[(<= a 2)]]
:doc-type :x}}
{:query {:id :bar
:doc-type :x}}}})
'([{:query {:id :foo,
:doc-type :x}}
{[:x :foo] {:crux.db/id :foo,
:a 2}}]
[{:query {:where [[:a 1]],
:doc-type :x}}
{[:x :foo] nil}]
[{:query {:where [[:a a]
[(<= a 2)]],
:doc-type :x}}
{[:x :foo] {:crux.db/id :foo,
:a 2}}])))))
(deftest biff-q
(with-open [node (start-node [{:crux.db/id :foo
:a 1}])]
(with-redefs [bc/check-read (constantly nil)]
(is (= (bc/biff-q {:biff.crux/db (delay (crux/db node))}
{:doc-type :x
:id :foo})
{[:x :foo] {:crux.db/id :foo, :a 1}}))
(is (= (bc/biff-q {:biff.crux/db (delay (crux/db node))}
{:doc-type :x
:where [[:a]]})
{[:x :foo] {:crux.db/id :foo, :a 1}}))
(is (= (bc/biff-q {:biff.crux/db (delay (crux/db node))}
{:doc-type :x
:where '[[:a a]
[(== a 1)]]})
{[:x :foo] {:crux.db/id :foo, :a 1}}))
(is (= (bc/biff-q {:biff.crux/db (delay (crux/db node))}
{:doc-type :x
:where [[:b]]})
{}))
(is (thrown-with-msg?
Exception #"fn in query not authorized."
(bc/biff-q {:biff.crux/db (delay (crux/db node))}
{:doc-type :x
:where '[[:a 1]
[(foo)]]}))))))
#_(run-tests)
| true | (ns biff.crux-test
(:require
[biff.crux :as bc]
[biff.util :as bu]
[crux.api :as crux]
[biff.misc :as misc]
[clojure.test :refer [deftest is run-tests]]))
(defn submit-await-tx [node tx]
(crux/await-tx
node
(crux/submit-tx
node
tx)))
(defn start-node [docs]
(let [node (crux/start-node {})]
(when (not-empty docs)
(crux/await-tx
node
(crux/submit-tx
node
(for [d docs]
[:crux.tx/put d]))))
node))
(deftest test-foo
(is (= 4 (+ 2 2))))
(defn authorize [{:keys [doc-type operation]} & _]
(case [doc-type operation]
[:foo :read] true
[:bar :create] true
false))
(def doc {:crux.db/id :foo})
(deftest check-read
(is (some? (bc/check-read {} {:docs [doc]})))
(with-redefs [bc/authorize (constantly true)]
(is (nil? (bc/check-read {} {:docs [doc]}))))
(with-redefs [bc/authorize authorize]
(is (nil? (bc/check-read
{}
{:query {:doc-type :foo
:where []}
:docs [doc]})))))
(deftest check-write
(is (some? (bc/check-write {} {:changes [{:after doc}]})))
(with-redefs [bc/authorize (constantly true)]
(is (nil? (bc/check-write {} {:changes [{:after doc}]}))))
(with-redefs [bc/authorize authorize]
(is (nil? (bc/check-write
{}
{:changes [{:after doc
:doc-type :bar}]})))))
(deftest normalize-tx-doc
(is (= {:crux.db/id {:foo "bar"}
:foo "bar"
:yeeted-at #inst "1970"
:numbers #{1 2 3}
:ek-ek-ek #{:whoppa}
:flavors #{"peach"}
:hot-dogs 116
:hello "there"}
(bc/normalize-tx-doc
{:doc-id {:foo "bar"}
:tx-doc {:db/merge true
:yeeted-at :db/server-timestamp
:numbers [:db/union 1 2]
:ek-ek-ek [:db/union :whoppa]
:flavors [:db/difference "dirt"]
:zebra :db/remove
:hot-dogs [:db/add 50]}
:server-timestamp #inst "1970"
:before {:hello "there"
:numbers #{3}
:flavors #{"peach" "dirt"}
:zebra "kevin"
:hot-dogs 66}}))))
(deftest get-changes
(let [random-ids [:x :y :z]
expected [{:tx-item [[:foo :c] {:hello "there"}]
:doc-id :c
:doc-type :foo
:before nil
:after {:crux.db/id :c
:hello "there"}}
{:tx-item [[:foo] {:hello "there"
:db/merge true}]
:doc-id :y
:doc-type :foo
:before {:crux.db/id :y
:a "b"}
:after {:crux.db/id :y
:hello "there"
:a "b"}}
{:tx-item [[:foo :a] nil]
:doc-id :a
:doc-type :foo
:before {:crux.db/id :a
:a "b"}
:after nil}]]
(with-open [node (start-node
[{:crux.db/id :y :a "b"}
{:crux.db/id :a :a "b"}])]
(is (= expected
(bc/get-changes
{:db (crux/db node)
:random-uuids random-ids
:biff-tx (map :tx-item expected)}))))))
(def registry
{:user/id :uuid
:user/email :string
:user/foo :string
:user/bar :string
:user [:map {:closed true}
[:crux.db/id :user/id]
:user/email
[:user/foo {:optional true}]
[:user/bar {:optional true}]]
:msg/id :uuid
:msg/user :user/id
:msg/text :string
:msg/sent-at inst?
:msg [:map {:closed true}
[:crux.db/id :msg/id]
:msg/user
:msg/text
:msg/sent-at]})
(def schema (misc/map->MalliSchema
{:doc-types [:user :msg]
:malli-opts {:registry (misc/malli-registry registry)}}))
(deftest get-tx-info
(is (thrown-with-msg?
Exception #"TX doesn't match schema."
(bc/get-tx-info nil {1 {:foo "bar"}})))
(with-open [node (start-node [])]
(is (some? (bc/get-tx-info
{:biff/schema schema
:biff.crux/db (delay (crux/db node))}
{}))))
(with-open [node (start-node [])]
(is (thrown-with-msg?
Exception #"Attempted to update on a new doc."
(bc/get-tx-info
{:biff/schema schema
:biff.crux/db (delay (crux/db node))}
{[:user] {:db/update true}}))))
(with-open [node (start-node [])]
(is (thrown-with-msg?
Exception #"Doc doesn't match doc-type."
(bc/get-tx-info
{:biff/schema schema
:biff.crux/db (delay (crux/db node))}
{[:user #uuid "0b5377f2-126d-44c9-b73c-d90f0efd0d7c"]
{:hello "there"}}))))
(with-open [node (start-node [])]
(let [uid (java.util.UUID/randomUUID)]
(is (= (dissoc (bc/get-tx-info
{:biff/schema schema
:biff.crux/db (delay (crux/db node))}
{[:user uid] {:user/email "PI:EMAIL:<EMAIL>END_PI"}})
:db-before :db-after :server-timestamp)
{:changes [{:tx-item [[:user uid] #:user{:email "PI:EMAIL:<EMAIL>END_PI"}],
:doc-id uid
:doc-type :user,
:before nil,
:after {:user/email "PI:EMAIL:<EMAIL>END_PI",
:crux.db/id uid}}],
:crux-tx [[:crux.tx/match uid nil]
[:crux.tx/put {:user/email "PI:EMAIL:<EMAIL>END_PI",
:crux.db/id uid}]]})))))
(deftest subscription+updates
(with-open [node (start-node [{:crux.db/id :foo
:a 1}])]
(is (= (#'bc/subscription+updates
{:txes [{:crux.tx.event/tx-events [[nil :foo]]}]
:db-before (crux/db node)
:db-after (crux/with-tx (crux/db node)
[[:crux.tx/put {:crux.db/id :foo
:a 2}]])
:subscriptions #{{:query {:id :foo
:doc-type :x}}
{:query {:where [[:a 1]]
:doc-type :x}}
{:query {:where '[[:a a]
[(<= a 2)]]
:doc-type :x}}
{:query {:id :bar
:doc-type :x}}}})
'([{:query {:id :foo,
:doc-type :x}}
{[:x :foo] {:crux.db/id :foo,
:a 2}}]
[{:query {:where [[:a 1]],
:doc-type :x}}
{[:x :foo] nil}]
[{:query {:where [[:a a]
[(<= a 2)]],
:doc-type :x}}
{[:x :foo] {:crux.db/id :foo,
:a 2}}])))))
(deftest biff-q
(with-open [node (start-node [{:crux.db/id :foo
:a 1}])]
(with-redefs [bc/check-read (constantly nil)]
(is (= (bc/biff-q {:biff.crux/db (delay (crux/db node))}
{:doc-type :x
:id :foo})
{[:x :foo] {:crux.db/id :foo, :a 1}}))
(is (= (bc/biff-q {:biff.crux/db (delay (crux/db node))}
{:doc-type :x
:where [[:a]]})
{[:x :foo] {:crux.db/id :foo, :a 1}}))
(is (= (bc/biff-q {:biff.crux/db (delay (crux/db node))}
{:doc-type :x
:where '[[:a a]
[(== a 1)]]})
{[:x :foo] {:crux.db/id :foo, :a 1}}))
(is (= (bc/biff-q {:biff.crux/db (delay (crux/db node))}
{:doc-type :x
:where [[:b]]})
{}))
(is (thrown-with-msg?
Exception #"fn in query not authorized."
(bc/biff-q {:biff.crux/db (delay (crux/db node))}
{:doc-type :x
:where '[[:a 1]
[(foo)]]}))))))
#_(run-tests)
|
[
{
"context": "ATED-AT \"2020-06-14T12:52:56.000Z\")\n\n(def AUTHOR \"fred-astaire\")\n\n(def SCORE 1)\n\n(defsc Root [_this {:keys [thre",
"end": 1131,
"score": 0.9701272249221802,
"start": 1119,
"tag": "USERNAME",
"value": "fred-astaire"
},
{
"context": " :author AUTHOR\n ",
"end": 2081,
"score": 0.9351373910903931,
"start": 2075,
"tag": "NAME",
"value": "AUTHOR"
}
] | src/workspaces/violit/threads/thread_item_cards.cljs | eoogbe/violit-clj | 0 | ;;; Copyright 2022 Google LLC
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
(ns violit.threads.thread-item-cards
(:require
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro-css.css-injection :as inj]
[com.fulcrologic.fulcro-css.localized-dom :as dom]
[nubank.workspaces.card-types.fulcro3 :as ct.fulcro]
[nubank.workspaces.core :as ws]
[violit.ui.core.styles :as styles]
[violit.ui.threads.thread-item :as thread-item]))
(def SLUG "lorem-ipsum")
(def TITLE "Lorem ipsum")
(def CREATED-AT "2020-06-14T12:52:56.000Z")
(def AUTHOR "fred-astaire")
(def SCORE 1)
(defsc Root [_this {:keys [thread-item]}]
{:query [{:thread-item (comp/get-query thread-item/ThreadItem)}]
:initial-state (fn [params]
{:thread-item (comp/get-initial-state thread-item/ThreadItem params)})
:css [[:* {:box-sizing "border-box"}]
[:.root styles/body]]}
(dom/div
:.root
(thread-item/ui-thread-item thread-item)
(inj/style-element {:component Root})))
(ws/defcard thread-item
(ct.fulcro/fulcro-card {::ct.fulcro/root Root
::ct.fulcro/wrap-root? false
::ct.fulcro/initial-state {:slug SLUG
:title TITLE
:created-at CREATED-AT
:author AUTHOR
:score SCORE}}))
| 60126 | ;;; Copyright 2022 Google LLC
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
(ns violit.threads.thread-item-cards
(:require
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro-css.css-injection :as inj]
[com.fulcrologic.fulcro-css.localized-dom :as dom]
[nubank.workspaces.card-types.fulcro3 :as ct.fulcro]
[nubank.workspaces.core :as ws]
[violit.ui.core.styles :as styles]
[violit.ui.threads.thread-item :as thread-item]))
(def SLUG "lorem-ipsum")
(def TITLE "Lorem ipsum")
(def CREATED-AT "2020-06-14T12:52:56.000Z")
(def AUTHOR "fred-astaire")
(def SCORE 1)
(defsc Root [_this {:keys [thread-item]}]
{:query [{:thread-item (comp/get-query thread-item/ThreadItem)}]
:initial-state (fn [params]
{:thread-item (comp/get-initial-state thread-item/ThreadItem params)})
:css [[:* {:box-sizing "border-box"}]
[:.root styles/body]]}
(dom/div
:.root
(thread-item/ui-thread-item thread-item)
(inj/style-element {:component Root})))
(ws/defcard thread-item
(ct.fulcro/fulcro-card {::ct.fulcro/root Root
::ct.fulcro/wrap-root? false
::ct.fulcro/initial-state {:slug SLUG
:title TITLE
:created-at CREATED-AT
:author <NAME>
:score SCORE}}))
| true | ;;; Copyright 2022 Google LLC
;;; Licensed under the Apache License, Version 2.0 (the "License");
;;; you may not use this file except in compliance with the License.
;;; You may obtain a copy of the License at
;;;
;;; http://www.apache.org/licenses/LICENSE-2.0
;;;
;;; Unless required by applicable law or agreed to in writing, software
;;; distributed under the License is distributed on an "AS IS" BASIS,
;;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;;; See the License for the specific language governing permissions and
;;; limitations under the License.
(ns violit.threads.thread-item-cards
(:require
[com.fulcrologic.fulcro.components :as comp :refer [defsc]]
[com.fulcrologic.fulcro-css.css-injection :as inj]
[com.fulcrologic.fulcro-css.localized-dom :as dom]
[nubank.workspaces.card-types.fulcro3 :as ct.fulcro]
[nubank.workspaces.core :as ws]
[violit.ui.core.styles :as styles]
[violit.ui.threads.thread-item :as thread-item]))
(def SLUG "lorem-ipsum")
(def TITLE "Lorem ipsum")
(def CREATED-AT "2020-06-14T12:52:56.000Z")
(def AUTHOR "fred-astaire")
(def SCORE 1)
(defsc Root [_this {:keys [thread-item]}]
{:query [{:thread-item (comp/get-query thread-item/ThreadItem)}]
:initial-state (fn [params]
{:thread-item (comp/get-initial-state thread-item/ThreadItem params)})
:css [[:* {:box-sizing "border-box"}]
[:.root styles/body]]}
(dom/div
:.root
(thread-item/ui-thread-item thread-item)
(inj/style-element {:component Root})))
(ws/defcard thread-item
(ct.fulcro/fulcro-card {::ct.fulcro/root Root
::ct.fulcro/wrap-root? false
::ct.fulcro/initial-state {:slug SLUG
:title TITLE
:created-at CREATED-AT
:author PI:NAME:<NAME>END_PI
:score SCORE}}))
|
[
{
"context": "subname subname\n :user username\n :password password}))\n\n(defn- postgres-db-spec [db]\n (connection-sp",
"end": 1391,
"score": 0.9979504346847534,
"start": 1383,
"tag": "PASSWORD",
"value": "password"
}
] | src/zanmi/component/database/postgres.clj | zonotope/zanmi | 35 | (ns zanmi.component.database.postgres
(:require [zanmi.boundary.database :as database]
[zanmi.config :as config]
[camel-snake-kebab.core :refer [->kebab-case-keyword]]
[clojure.string :refer [join]]
[clojure.set :refer [rename-keys]]
[com.stuartsierra.component :as component]
[hikari-cp.core :refer [make-datasource close-datasource]]
[honeysql.core :as sql]
[honeysql.format :as sql.fmt]
[honeysql.helpers :as sql-helper :refer [defhelper delete-from
from insert-into select
sset update values where]]
[jdbc.core :as jdbc]
[jdbc.proto]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; db connection specs ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- pooled-spec [postgres]
{:datasource (make-datasource postgres)})
(defn- connection-spec [{:keys [username password server-name
database-name]
:as db}]
(let [subname (str "//" server-name "/" database-name)]
{:subprotocol "postgresql"
:subname subname
:user username
:password password}))
(defn- postgres-db-spec [db]
(connection-spec (assoc db :database-name "postgres")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ddl ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^:private table :profiles)
(defn- create-database! [{:keys [database-name] :as db}]
(with-open [conn (jdbc/connection (postgres-db-spec db))]
(jdbc/execute conn (str "CREATE DATABASE " database-name))))
(defn- create-table! [db]
(with-open [conn (jdbc/connection (connection-spec db))]
(let [length 32]
(jdbc/execute conn (str "CREATE TABLE " (name table) " ("
" id UUID PRIMARY KEY NOT NULL,"
" username VARCHAR(" length ") NOT NULL UNIQUE,"
" hashed_password VARCHAR(128) NOT NULL,"
" created TIMESTAMP NOT NULL,"
" modified TIMESTAMP NOT NULL"
")")))))
(defn- drop-database! [{:keys [database-name] :as db}]
(with-open [conn (jdbc/connection (postgres-db-spec db))]
(jdbc/execute conn (str "DROP DATABASE " database-name))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; sql time conversion ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(extend-protocol jdbc.proto/ISQLType
java.util.Date
(as-sql-type [date conn]
(java.sql.Timestamp. (.getTime date)))
(set-stmt-parameter! [date conn stmt index]
(.setObject stmt index (jdbc.proto/as-sql-type date conn))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; querying ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod sql.fmt/format-clause :returning [[_ fields] _]
(str "RETURNING " (join ", " (map sql.fmt/to-sql fields))))
(defhelper returning [m args]
(assoc m :returning args))
(defn- sanitize-keys [m]
(let [keymap (into {} (map (fn [k] {k (->kebab-case-keyword k)})
(keys m)))]
(rename-keys m keymap)))
(defn- query-one [db-spec statement]
(with-open [conn (jdbc/connection db-spec)]
(->> statement
(sql/format)
(jdbc/fetch conn)
(first)
(sanitize-keys))))
(defn- execute [db-spec statement]
(with-open [conn (jdbc/connection db-spec)]
(->> statement
(sql/format)
(jdbc/execute conn))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; component ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord Postgres []
component/Lifecycle
(start [postgres]
(if (:spec postgres)
postgres
(assoc postgres :spec (pooled-spec postgres))))
(stop [postgres]
(if-let [datasource (-> postgres :spec :datasource)]
(do (close-datasource datasource)
(dissoc postgres :spec))
postgres))
database/Database
(initialize! [db]
(create-database! db)
(create-table! db))
(destroy! [db]
(drop-database! db))
(fetch [{db-spec :spec} username]
(query-one db-spec (-> (select :*)
(from table)
(where [:= :username username]))))
(create! [{db-spec :spec} attrs]
(query-one db-spec (-> (insert-into table)
(values [attrs])
(returning :*))))
(update! [{db-spec :spec} username attrs]
(query-one db-spec (-> (update table)
(sset attrs)
(where [:= :username username])
(returning :*))))
(delete! [{db-spec :spec} username]
(execute db-spec (-> (delete-from table)
(where [:= :username username])))))
(defn postgres [{:keys [db-name host] :as config}]
(-> config
(dissoc :engine :host :db-name)
(assoc :adapter "postgresql"
:server-name host
:database-name db-name)
(map->Postgres)))
| 95486 | (ns zanmi.component.database.postgres
(:require [zanmi.boundary.database :as database]
[zanmi.config :as config]
[camel-snake-kebab.core :refer [->kebab-case-keyword]]
[clojure.string :refer [join]]
[clojure.set :refer [rename-keys]]
[com.stuartsierra.component :as component]
[hikari-cp.core :refer [make-datasource close-datasource]]
[honeysql.core :as sql]
[honeysql.format :as sql.fmt]
[honeysql.helpers :as sql-helper :refer [defhelper delete-from
from insert-into select
sset update values where]]
[jdbc.core :as jdbc]
[jdbc.proto]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; db connection specs ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- pooled-spec [postgres]
{:datasource (make-datasource postgres)})
(defn- connection-spec [{:keys [username password server-name
database-name]
:as db}]
(let [subname (str "//" server-name "/" database-name)]
{:subprotocol "postgresql"
:subname subname
:user username
:password <PASSWORD>}))
(defn- postgres-db-spec [db]
(connection-spec (assoc db :database-name "postgres")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ddl ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^:private table :profiles)
(defn- create-database! [{:keys [database-name] :as db}]
(with-open [conn (jdbc/connection (postgres-db-spec db))]
(jdbc/execute conn (str "CREATE DATABASE " database-name))))
(defn- create-table! [db]
(with-open [conn (jdbc/connection (connection-spec db))]
(let [length 32]
(jdbc/execute conn (str "CREATE TABLE " (name table) " ("
" id UUID PRIMARY KEY NOT NULL,"
" username VARCHAR(" length ") NOT NULL UNIQUE,"
" hashed_password VARCHAR(128) NOT NULL,"
" created TIMESTAMP NOT NULL,"
" modified TIMESTAMP NOT NULL"
")")))))
(defn- drop-database! [{:keys [database-name] :as db}]
(with-open [conn (jdbc/connection (postgres-db-spec db))]
(jdbc/execute conn (str "DROP DATABASE " database-name))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; sql time conversion ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(extend-protocol jdbc.proto/ISQLType
java.util.Date
(as-sql-type [date conn]
(java.sql.Timestamp. (.getTime date)))
(set-stmt-parameter! [date conn stmt index]
(.setObject stmt index (jdbc.proto/as-sql-type date conn))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; querying ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod sql.fmt/format-clause :returning [[_ fields] _]
(str "RETURNING " (join ", " (map sql.fmt/to-sql fields))))
(defhelper returning [m args]
(assoc m :returning args))
(defn- sanitize-keys [m]
(let [keymap (into {} (map (fn [k] {k (->kebab-case-keyword k)})
(keys m)))]
(rename-keys m keymap)))
(defn- query-one [db-spec statement]
(with-open [conn (jdbc/connection db-spec)]
(->> statement
(sql/format)
(jdbc/fetch conn)
(first)
(sanitize-keys))))
(defn- execute [db-spec statement]
(with-open [conn (jdbc/connection db-spec)]
(->> statement
(sql/format)
(jdbc/execute conn))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; component ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord Postgres []
component/Lifecycle
(start [postgres]
(if (:spec postgres)
postgres
(assoc postgres :spec (pooled-spec postgres))))
(stop [postgres]
(if-let [datasource (-> postgres :spec :datasource)]
(do (close-datasource datasource)
(dissoc postgres :spec))
postgres))
database/Database
(initialize! [db]
(create-database! db)
(create-table! db))
(destroy! [db]
(drop-database! db))
(fetch [{db-spec :spec} username]
(query-one db-spec (-> (select :*)
(from table)
(where [:= :username username]))))
(create! [{db-spec :spec} attrs]
(query-one db-spec (-> (insert-into table)
(values [attrs])
(returning :*))))
(update! [{db-spec :spec} username attrs]
(query-one db-spec (-> (update table)
(sset attrs)
(where [:= :username username])
(returning :*))))
(delete! [{db-spec :spec} username]
(execute db-spec (-> (delete-from table)
(where [:= :username username])))))
(defn postgres [{:keys [db-name host] :as config}]
(-> config
(dissoc :engine :host :db-name)
(assoc :adapter "postgresql"
:server-name host
:database-name db-name)
(map->Postgres)))
| true | (ns zanmi.component.database.postgres
(:require [zanmi.boundary.database :as database]
[zanmi.config :as config]
[camel-snake-kebab.core :refer [->kebab-case-keyword]]
[clojure.string :refer [join]]
[clojure.set :refer [rename-keys]]
[com.stuartsierra.component :as component]
[hikari-cp.core :refer [make-datasource close-datasource]]
[honeysql.core :as sql]
[honeysql.format :as sql.fmt]
[honeysql.helpers :as sql-helper :refer [defhelper delete-from
from insert-into select
sset update values where]]
[jdbc.core :as jdbc]
[jdbc.proto]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; db connection specs ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- pooled-spec [postgres]
{:datasource (make-datasource postgres)})
(defn- connection-spec [{:keys [username password server-name
database-name]
:as db}]
(let [subname (str "//" server-name "/" database-name)]
{:subprotocol "postgresql"
:subname subname
:user username
:password PI:PASSWORD:<PASSWORD>END_PI}))
(defn- postgres-db-spec [db]
(connection-spec (assoc db :database-name "postgres")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ddl ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^:private table :profiles)
(defn- create-database! [{:keys [database-name] :as db}]
(with-open [conn (jdbc/connection (postgres-db-spec db))]
(jdbc/execute conn (str "CREATE DATABASE " database-name))))
(defn- create-table! [db]
(with-open [conn (jdbc/connection (connection-spec db))]
(let [length 32]
(jdbc/execute conn (str "CREATE TABLE " (name table) " ("
" id UUID PRIMARY KEY NOT NULL,"
" username VARCHAR(" length ") NOT NULL UNIQUE,"
" hashed_password VARCHAR(128) NOT NULL,"
" created TIMESTAMP NOT NULL,"
" modified TIMESTAMP NOT NULL"
")")))))
(defn- drop-database! [{:keys [database-name] :as db}]
(with-open [conn (jdbc/connection (postgres-db-spec db))]
(jdbc/execute conn (str "DROP DATABASE " database-name))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; sql time conversion ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(extend-protocol jdbc.proto/ISQLType
java.util.Date
(as-sql-type [date conn]
(java.sql.Timestamp. (.getTime date)))
(set-stmt-parameter! [date conn stmt index]
(.setObject stmt index (jdbc.proto/as-sql-type date conn))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; querying ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod sql.fmt/format-clause :returning [[_ fields] _]
(str "RETURNING " (join ", " (map sql.fmt/to-sql fields))))
(defhelper returning [m args]
(assoc m :returning args))
(defn- sanitize-keys [m]
(let [keymap (into {} (map (fn [k] {k (->kebab-case-keyword k)})
(keys m)))]
(rename-keys m keymap)))
(defn- query-one [db-spec statement]
(with-open [conn (jdbc/connection db-spec)]
(->> statement
(sql/format)
(jdbc/fetch conn)
(first)
(sanitize-keys))))
(defn- execute [db-spec statement]
(with-open [conn (jdbc/connection db-spec)]
(->> statement
(sql/format)
(jdbc/execute conn))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; component ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord Postgres []
component/Lifecycle
(start [postgres]
(if (:spec postgres)
postgres
(assoc postgres :spec (pooled-spec postgres))))
(stop [postgres]
(if-let [datasource (-> postgres :spec :datasource)]
(do (close-datasource datasource)
(dissoc postgres :spec))
postgres))
database/Database
(initialize! [db]
(create-database! db)
(create-table! db))
(destroy! [db]
(drop-database! db))
(fetch [{db-spec :spec} username]
(query-one db-spec (-> (select :*)
(from table)
(where [:= :username username]))))
(create! [{db-spec :spec} attrs]
(query-one db-spec (-> (insert-into table)
(values [attrs])
(returning :*))))
(update! [{db-spec :spec} username attrs]
(query-one db-spec (-> (update table)
(sset attrs)
(where [:= :username username])
(returning :*))))
(delete! [{db-spec :spec} username]
(execute db-spec (-> (delete-from table)
(where [:= :username username])))))
(defn postgres [{:keys [db-name host] :as config}]
(-> config
(dissoc :engine :host :db-name)
(assoc :adapter "postgresql"
:server-name host
:database-name db-name)
(map->Postgres)))
|
[
{
"context": "\"\n (let [saved (db/tx {:kind :bibelot :name \"thingy\"})]\n (should= saved (db/entity! (:id save",
"end": 1777,
"score": 0.583084762096405,
"start": 1772,
"tag": "NAME",
"value": "thing"
},
{
"context": "ingy\"})\n updated (db/tx saved :name \"whatsamajigger\")\n loaded (db/entity (:id saved))]\n ",
"end": 2452,
"score": 0.9783353805541992,
"start": 2438,
"tag": "USERNAME",
"value": "whatsamajigger"
},
{
"context": "(db/entity (:id saved))]\n (should= \"whatsamajigger\" (:name loaded))\n (should= (:id saved",
"end": 2532,
"score": 0.6872218251228333,
"start": 2526,
"tag": "USERNAME",
"value": "amajig"
},
{
"context": "\"\n (let [saved (db/tx {:kind :bibelot :name \"thingy\" :color \"blue\" :size 123})\n loaded (d",
"end": 4022,
"score": 0.5684735178947449,
"start": 4017,
"tag": "NAME",
"value": "thing"
},
{
"context": "\"\n (let [saved (db/tx {:kind :bibelot :name \"thingy\" :color \"blue\" :size 123})\n loaded (d",
"end": 4391,
"score": 0.6567482352256775,
"start": 4386,
"tag": "NAME",
"value": "thing"
},
{
"context": "\"\n (let [bibby (db/tx {:kind :bibelot :name \"bibby\"})\n saved (db/tx :kind :thingy :foo \"p",
"end": 4880,
"score": 0.8840448260307312,
"start": 4875,
"tag": "NAME",
"value": "bibby"
},
{
"context": "y\"})\n saved (db/tx :kind :thingy :foo \"paul\" :bar (:id bibby) :fizz 2 :bang :paul)]\n (",
"end": 4933,
"score": 0.9864548444747925,
"start": 4929,
"tag": "NAME",
"value": "paul"
},
{
"context": "paul)]\n (should (db/ffind-by :thingy :foo \"paul\" :bar (:id bibby) :fizz 2 :bang :paul))\n (",
"end": 5021,
"score": 0.9653215408325195,
"start": 5017,
"tag": "NAME",
"value": "paul"
},
{
"context": "))\n (should-not (db/ffind-by :thingy :foo \"ringo\" :bar (:id bibby) :fizz 2 :bang :paul))))\n\n (i",
"end": 5114,
"score": 0.9170212149620056,
"start": 5109,
"tag": "NAME",
"value": "ringo"
},
{
"context": "\"\n (let [bibby (db/tx {:kind :bibelot :name \"bibby\"})\n saved (db/tx :kind :thingy :foo \"p",
"end": 6024,
"score": 0.6656227111816406,
"start": 6019,
"tag": "NAME",
"value": "bibby"
},
{
"context": "y\"})\n saved (db/tx :kind :thingy :foo \"paul\" :bar (:id bibby) :fizz 2 :bang :paul)]\n (",
"end": 6077,
"score": 0.9914496541023254,
"start": 6073,
"tag": "NAME",
"value": "paul"
},
{
"context": "l)]\n (should= 1 (db/count-by :thingy :foo \"paul\" :bar (:id bibby) :fizz 2 :bang :paul))\n (",
"end": 6168,
"score": 0.9657435417175293,
"start": 6164,
"tag": "NAME",
"value": "paul"
},
{
"context": "hingy :foo \"paul\" :bar (:id bibby) :fizz 2 :bang :paul))\n (should= 0 (db/count-by :thingy :foo \"r",
"end": 6206,
"score": 0.9415280222892761,
"start": 6202,
"tag": "NAME",
"value": "paul"
},
{
"context": "l))\n (should= 0 (db/count-by :thingy :foo \"ringo\" :bar (:id bibby) :fizz 2 :bang :paul))))\n )\n\n",
"end": 6260,
"score": 0.9930729269981384,
"start": 6255,
"tag": "NAME",
"value": "ringo"
},
{
"context": "ingy :foo \"ringo\" :bar (:id bibby) :fizz 2 :bang :paul))))\n )\n\n (context \"find-all\"\n\n #?(:clj (h",
"end": 6298,
"score": 0.7529488205909729,
"start": 6294,
"tag": "NAME",
"value": "paul"
},
{
"context": "belot]))\n (before (db/tx :kind :bibelot :name \"john\" :color \"red\" :size 1)\n (db/tx :kind :",
"end": 6475,
"score": 0.99942946434021,
"start": 6471,
"tag": "NAME",
"value": "john"
},
{
"context": ":size 1)\n (db/tx :kind :bibelot :name \"paul\" :color \"green\" :size 2)\n (db/tx :kind",
"end": 6544,
"score": 0.9993464350700378,
"start": 6540,
"tag": "NAME",
"value": "paul"
},
{
"context": ":size 2)\n (db/tx :kind :bibelot :name \"george\" :color \"blue\" :size 3))\n\n (it \"find all bibel",
"end": 6617,
"score": 0.9955812692642212,
"start": 6611,
"tag": "NAME",
"value": "george"
},
{
"context": "hingy]))\n (before (db/tx :kind :bibelot :name \"john\" :color \"red\" :size 1)\n (db/tx :kind :",
"end": 7156,
"score": 0.9995537400245667,
"start": 7152,
"tag": "NAME",
"value": "john"
},
{
"context": ":size 1)\n (db/tx :kind :bibelot :name \"paul\" :color \"green\" :size 2)\n (db/tx :kind",
"end": 7225,
"score": 0.9993183612823486,
"start": 7221,
"tag": "NAME",
"value": "paul"
},
{
"context": ":size 2)\n (db/tx :kind :bibelot :name \"george\" :color \"blue\" :size 3))\n\n (it \"find all bibel",
"end": 7298,
"score": 0.9951545000076294,
"start": 7292,
"tag": "NAME",
"value": "george"
}
] | bucket/spec/cljc/c3kit/bucket/dbc_spec.cljc | cleancoders/kit | 1 | (ns c3kit.bucket.dbc-spec
(:require
[speclj.core #?(:clj :refer :cljs :refer-macros) [context describe it xit should= should-contain
should-not-contain should-throw should-be-a with
should-not= before should should-not should-not-throw]]
[c3kit.bucket.db :as db]
[c3kit.apron.log :as log]
[c3kit.apron.schema :as s]
[c3kit.bucket.spec-helper :as helper]
))
(def bibelot
{:kind (s/kind :bibelot)
:id s/id
:name {:type :string}
:size {:type :long}
:color {:type :string}})
(def gewgaw
{:kind (s/kind :gewgaw)
:id s/id
:name {:type :string}
:thing {:type :ref}})
(def doodad
{:kind (s/kind :doodad)
:id s/id
:names {:type [:string]}
:numbers {:type [:long]}
:things {:type [:ref]}})
(def thingy
{:kind (s/kind :thingy)
:id s/id
:foo {:type :string}
:bar {:type :ref}
:fizz {:type :long}
:bang {:type :keyword}})
(def child :undefined)
(def original :undefined)
(describe "DB Common"
(context "CRUD"
(helper/with-db-schemas [bibelot])
(it "returns nil on missing id"
(should= nil (db/entity -1))
(should= nil (db/entity nil))
(should= nil (db/entity ""))
(should= nil (db/entity "-1")))
(it "tx nil entities"
(should-not-throw (db/tx nil))
(should-not-throw (db/tx* [nil])))
(it "create and read"
(let [saved (db/tx {:kind :bibelot :name "thingy"})
loaded (db/entity (:id saved))]
(should= :bibelot (:kind loaded))
(should= "thingy" (:name loaded))
(should= (:id loaded) (:id saved))))
(it "entity!"
(let [saved (db/tx {:kind :bibelot :name "thingy"})]
(should= saved (db/entity! (:id saved)))
(should-throw (db/entity! 9999))))
(it "entity-of-kind"
(let [saved (db/tx {:kind :bibelot :name "thingy"})]
(should= saved (db/entity-of-kind :bibelot (:id saved)))
(should= nil (db/entity-of-kind :other (:id saved)))))
(it "entity-of-kind!"
(let [saved (db/tx {:kind :bibelot :name "thingy"})]
(should= saved (db/entity-of-kind! :bibelot (:id saved)))
(should-throw (db/entity-of-kind! :other (:id saved)))))
(it "updating"
(try
(let [saved (db/tx {:kind :bibelot :name "thingy"})
updated (db/tx saved :name "whatsamajigger")
loaded (db/entity (:id saved))]
(should= "whatsamajigger" (:name loaded))
(should= (:id saved) (:id loaded))
(should= (:id saved) (:id updated)))
(catch #?(:clj Exception :cljs :default) e
(log/error e))))
(it "retracting via metadata"
(let [saved (db/tx {:kind :bibelot :name "thingy"})
updated (db/tx (with-meta saved {:retract true}))]
(should= nil (db/entity (:id saved)))
(should= {:kind :db/retract :id (:id saved)} updated)))
(it "retracting via :kind :db/retract"
(let [saved (db/tx {:kind :bibelot :name "thingy"})
updated (db/tx (assoc saved :kind :db/retract))]
(should= nil (db/entity (:id saved)))
(should= {:kind :db/retract :id (:id saved)} updated)))
(it "retracting when passed an entity"
(let [saved (db/tx {:kind :bibelot :name "thingy"})
retracted (db/retract saved)]
(should= {:kind :db/retract :id (:id saved)} retracted)
(should= [] (db/find-by :bibelot :name "thingy"))))
(it "retracting when passed an id"
(let [saved (db/tx {:kind :bibelot :name "thingy"})
retracted (db/retract (:id saved))]
(should= {:kind :db/retract :id (:id saved)} retracted)
(should= [] (db/find-by :bibelot :name "thingy"))))
)
(context "find-by"
#?(:clj (helper/with-db-schemas [bibelot thingy])
:cljs (helper/with-db-schemas [bibelot thingy]))
(it "find by attribute"
(let [saved (db/tx {:kind :bibelot :name "thingy" :color "blue" :size 123})
loaded (db/find-by :bibelot :name "thingy")]
(should= (:id saved) (:id (first loaded)))
(should= "thingy" (:name (first loaded)))
(should= "blue" (:color (first loaded)))
(should= 123 (:size (first loaded)))))
(it "find by two attribute"
(let [saved (db/tx {:kind :bibelot :name "thingy" :color "blue" :size 123})
loaded (db/find-by :bibelot :name "thingy" :color "blue")]
(should= (:id saved) (:id (first loaded)))))
(it "find by three attribute"
(let [saved (db/tx {:kind :bibelot :name "thingy" :color "blue" :size 123})
loaded (db/find-by :bibelot :name "thingy" :color "blue" :size 123)]
(should= (:id saved) (:id (first loaded)))))
(it "find-by with 4 attrs"
(let [bibby (db/tx {:kind :bibelot :name "bibby"})
saved (db/tx :kind :thingy :foo "paul" :bar (:id bibby) :fizz 2 :bang :paul)]
(should (db/ffind-by :thingy :foo "paul" :bar (:id bibby) :fizz 2 :bang :paul))
(should-not (db/ffind-by :thingy :foo "ringo" :bar (:id bibby) :fizz 2 :bang :paul))))
(it "find by nil"
(let [b1 (db/tx :kind :bibelot :name "Bee" :size 1)
b2 (db/tx :kind :bibelot :name "Bee" :color "blue")
b3 (db/tx :kind :bibelot :size 1 :color "blue")]
(should= [b1] (db/find-by :bibelot :name "Bee" :color nil))
(should= [b2] (db/find-by :bibelot :name "Bee" :size nil))
(should= [b3] (db/find-by :bibelot :color "blue" :name nil))))
)
(context "count-by"
#?(:clj (helper/with-db-schemas [bibelot thingy])
:cljs (helper/with-db-schemas [bibelot thingy]))
(it "count by attribute"
(let [saved (db/tx {:kind :bibelot :name "thingy" :color "blue" :size 123})]
(should= 1 (db/count-by :bibelot :name "thingy"))
(should= 0 (db/count-by :bibelot :name "blah"))))
(it "find-by with 4 attrs"
(let [bibby (db/tx {:kind :bibelot :name "bibby"})
saved (db/tx :kind :thingy :foo "paul" :bar (:id bibby) :fizz 2 :bang :paul)]
(should= 1 (db/count-by :thingy :foo "paul" :bar (:id bibby) :fizz 2 :bang :paul))
(should= 0 (db/count-by :thingy :foo "ringo" :bar (:id bibby) :fizz 2 :bang :paul))))
)
(context "find-all"
#?(:clj (helper/with-db-schemas [bibelot])
:cljs (helper/with-db-schemas [bibelot]))
(before (db/tx :kind :bibelot :name "john" :color "red" :size 1)
(db/tx :kind :bibelot :name "paul" :color "green" :size 2)
(db/tx :kind :bibelot :name "george" :color "blue" :size 3))
(it "find all bibelot/name"
(let [all (db/find-all :bibelot :name)]
(should= 3 (count all))
(should= #{1 2 3} (set (map :size all)))))
(it "find all bibelot/color"
(let [all (db/find-all :bibelot :color)]
(should= 3 (count all))
(should= #{1 2 3} (set (map :size all)))))
)
(context "count-all"
#?(:clj (helper/with-db-schemas [bibelot thingy])
:cljs (helper/with-db-schemas [bibelot thingy]))
(before (db/tx :kind :bibelot :name "john" :color "red" :size 1)
(db/tx :kind :bibelot :name "paul" :color "green" :size 2)
(db/tx :kind :bibelot :name "george" :color "blue" :size 3))
(it "find all bibelot/name"
(should= 0 (db/count-all :thingy :foo))
(should= 3 (db/count-all :bibelot :name)))
)
(context "reference values"
#?(:clj (helper/with-db-schemas [bibelot gewgaw])
:cljs (helper/with-db-schemas [bibelot gewgaw]))
(it "loading"
(let [child (db/tx {:kind :bibelot :name "child" :color "golden"})
saved (db/tx {:kind :gewgaw :name "parent" :thing (:id child)})
loaded (db/entity (:id saved))
loaded-child (db/entity (:thing loaded))]
(should= (:id loaded) (:id saved))
(should= (:id child) (:id loaded-child))))
(it "find by attribute"
(let [child (db/tx {:kind :bibelot :name "child" :color "golden"})
saved (db/tx {:kind :gewgaw :name "parent" :thing (:id child)})
result (db/find-by :gewgaw :thing (:id child))]
(should= (:id saved) (:id (first result)))
(should= "parent" (:name (first result)))))
(it "pass through loading and saving seamelessly"
(let [child (db/tx {:kind :bibelot :name "child" :color "golden"})
saved (db/tx {:kind :gewgaw :name "parent" :thing (:id child)})
loaded (db/entity (:id saved))
saved-again (db/tx loaded)]
(should= (:thing loaded) (:thing saved-again))))
)
(context "multiple values"
#?(:clj (helper/with-db-schemas [bibelot doodad])
:cljs (helper/with-db-schemas [bibelot doodad]))
(it "loading"
(let [saved (db/tx {:kind :doodad :names ["foo" "bar"] :numbers [8 42]})
loaded (db/entity (:id saved))]
(should= (:id loaded) (:id saved))
(should= #{"foo" "bar"} (set (:names loaded)))
(should= #{8 42} (set (:numbers loaded)))))
(it "find by attribute"
(let [saved (db/tx {:kind :doodad :names ["foo" "bar"] :numbers [8 42]})
loaded (db/find-by :doodad :names "bar")]
(should= 1 (count loaded))
(should= (:id saved) (:id (first loaded)))))
(it "retracting [string] value"
(let [saved (db/tx {:kind :doodad :names ["foo" "bar"] :numbers [8 42]})
updated (db/tx saved :names nil)]
(should= nil (seq (:names updated)))))
(it "retracting one value from [string]"
(let [saved (db/tx {:kind :doodad :names ["foo" "bar"] :numbers [8 42]})
updated (db/tx saved :names ["foo"])]
(should= #{"foo"} (set (:names updated)))))
(it "adding one value to [string]"
(let [saved (db/tx {:kind :doodad :names ["foo" "bar"] :numbers [8 42]})
updated (db/tx saved :names ["foo" "bar" "fizz"])]
(should= #{"foo" "bar" "fizz"} (set (:names updated)))))
(it "using refs"
(let [child1 (db/tx {:kind :bibelot :name "child1" :color "golden"})
child2 (db/tx {:kind :bibelot :name "child2" :color "silver"})
saved (db/tx {:kind :doodad :things [(:id child1) (:id child2)]})
loaded (db/entity (:id saved))]
(should= #{(:id child1) (:id child2)} (set (:things saved)))
(should= #{(:id child1) (:id child2)} (set (:things loaded)))))
(it "retracting whole [ref] value"
(let [child1 (db/tx {:kind :bibelot :name "child1" :color "golden"})
child2 (db/tx {:kind :bibelot :name "child2" :color "silver"})
saved (db/tx {:kind :doodad :things [(:id child1) (:id child2)]})
updated (db/tx saved :things nil)]
(should= nil (seq (:things updated)))))
(it "removing one [ref] values"
(let [child1 (db/tx {:kind :bibelot :name "child1" :color "golden"})
child2 (db/tx {:kind :bibelot :name "child2" :color "silver"})
saved (db/tx {:kind :doodad :things [(:id child1) (:id child2)]})
updated (db/tx saved :things [(:id child1)])]
(should= #{(:id child1)} (set (:things updated)))))
(it "adding one [ref] values"
(let [child1 (db/tx {:kind :bibelot :name "child1" :color "golden"})
child2 (db/tx {:kind :bibelot :name "child2" :color "silver"})
child3 (db/tx {:kind :bibelot :name "child3" :color "bronze"})
saved (db/tx {:kind :doodad :things [(:id child1) (:id child2)]})
updated (db/tx saved :things [(:id child1) (:id child2) (:id child3)])]
(should= #{(:id child1) (:id child2) (:id child3)} (set (:things updated)))))
)
(context "retracting null values"
#?(:clj (helper/with-db-schemas [bibelot thingy])
:cljs (helper/with-db-schemas [bibelot thingy]))
(with child (db/tx {:kind :bibelot :name "child" :color "golden"}))
(with original (db/tx {:kind :thingy
:foo "foo"
:bar (:id @child)
:fizz 2015
:bang :kapow!}))
(it "can set a string to nil"
(let [result (db/tx (assoc @original :foo nil))]
(should= nil (:foo result))
(should= nil (:foo (db/reload @original)))))
(it "can set a ref to nil"
(let [result (db/tx (assoc @original :bar nil))]
(should= nil (:bar result))
(should= nil (:bar (db/reload @original)))))
(it "can set a long to nil"
(let [result (db/tx (dissoc @original :fizz))]
(should= nil (:fizz result))
(should= nil (:fizz (db/reload @original)))))
(it "can set a keyword to nil"
(let [result (db/tx (dissoc @original :bang))]
(should= nil (:bang result))
(should= nil (:bang (db/reload @original)))))
)
(context "transactions"
#?(:clj (helper/with-db-schemas [bibelot gewgaw])
:cljs (helper/with-db-schemas [bibelot gewgaw]))
(it "save multiple entities at the same time"
(let [g1 {:kind :gewgaw :name "1"}
g2 {:kind :gewgaw :name "2"}
result (db/tx* [g1 g2])]
(should= "1" (:name (db/reload (first result))))
(should= "2" (:name (db/reload (second result))))))
(it "update multiple entities at the same time"
(let [g1 (db/tx {:kind :gewgaw :name "1"})
g2 (db/tx {:kind :gewgaw :name "2"})
result (db/tx* [(assoc g1 :name "one") (dissoc g2 :name)])]
(should= "one" (:name (db/reload (first result))))
(should= nil (:name (db/reload (second result))))))
(it "retract with meta-data on any of the entities"
(let [g1 (db/tx {:kind :gewgaw :name "1"})
g2 (db/tx {:kind :gewgaw :name "2"})
[u1 u2] (db/tx* [(assoc g1 :name "one") (assoc g2 :kind :db/retract)])]
(should= "one" (:name (db/reload u1)))
(should= nil (db/reload u2))
(should= {:kind :db/retract :id (:id g2)} u2)))
(it "temp-ids are resolved"
(let [bibby {:kind :bibelot :name "bibby" :id (db/tempid)}
gewy {:kind :gewgaw :thing (:id bibby)}
result (db/tx* [bibby gewy])
[saved-bibby saved-gewy] result]
(should= (:id saved-bibby) (:thing saved-gewy))))
)
)
| 41753 | (ns c3kit.bucket.dbc-spec
(:require
[speclj.core #?(:clj :refer :cljs :refer-macros) [context describe it xit should= should-contain
should-not-contain should-throw should-be-a with
should-not= before should should-not should-not-throw]]
[c3kit.bucket.db :as db]
[c3kit.apron.log :as log]
[c3kit.apron.schema :as s]
[c3kit.bucket.spec-helper :as helper]
))
(def bibelot
{:kind (s/kind :bibelot)
:id s/id
:name {:type :string}
:size {:type :long}
:color {:type :string}})
(def gewgaw
{:kind (s/kind :gewgaw)
:id s/id
:name {:type :string}
:thing {:type :ref}})
(def doodad
{:kind (s/kind :doodad)
:id s/id
:names {:type [:string]}
:numbers {:type [:long]}
:things {:type [:ref]}})
(def thingy
{:kind (s/kind :thingy)
:id s/id
:foo {:type :string}
:bar {:type :ref}
:fizz {:type :long}
:bang {:type :keyword}})
(def child :undefined)
(def original :undefined)
(describe "DB Common"
(context "CRUD"
(helper/with-db-schemas [bibelot])
(it "returns nil on missing id"
(should= nil (db/entity -1))
(should= nil (db/entity nil))
(should= nil (db/entity ""))
(should= nil (db/entity "-1")))
(it "tx nil entities"
(should-not-throw (db/tx nil))
(should-not-throw (db/tx* [nil])))
(it "create and read"
(let [saved (db/tx {:kind :bibelot :name "thingy"})
loaded (db/entity (:id saved))]
(should= :bibelot (:kind loaded))
(should= "thingy" (:name loaded))
(should= (:id loaded) (:id saved))))
(it "entity!"
(let [saved (db/tx {:kind :bibelot :name "<NAME>y"})]
(should= saved (db/entity! (:id saved)))
(should-throw (db/entity! 9999))))
(it "entity-of-kind"
(let [saved (db/tx {:kind :bibelot :name "thingy"})]
(should= saved (db/entity-of-kind :bibelot (:id saved)))
(should= nil (db/entity-of-kind :other (:id saved)))))
(it "entity-of-kind!"
(let [saved (db/tx {:kind :bibelot :name "thingy"})]
(should= saved (db/entity-of-kind! :bibelot (:id saved)))
(should-throw (db/entity-of-kind! :other (:id saved)))))
(it "updating"
(try
(let [saved (db/tx {:kind :bibelot :name "thingy"})
updated (db/tx saved :name "whatsamajigger")
loaded (db/entity (:id saved))]
(should= "whatsamajigger" (:name loaded))
(should= (:id saved) (:id loaded))
(should= (:id saved) (:id updated)))
(catch #?(:clj Exception :cljs :default) e
(log/error e))))
(it "retracting via metadata"
(let [saved (db/tx {:kind :bibelot :name "thingy"})
updated (db/tx (with-meta saved {:retract true}))]
(should= nil (db/entity (:id saved)))
(should= {:kind :db/retract :id (:id saved)} updated)))
(it "retracting via :kind :db/retract"
(let [saved (db/tx {:kind :bibelot :name "thingy"})
updated (db/tx (assoc saved :kind :db/retract))]
(should= nil (db/entity (:id saved)))
(should= {:kind :db/retract :id (:id saved)} updated)))
(it "retracting when passed an entity"
(let [saved (db/tx {:kind :bibelot :name "thingy"})
retracted (db/retract saved)]
(should= {:kind :db/retract :id (:id saved)} retracted)
(should= [] (db/find-by :bibelot :name "thingy"))))
(it "retracting when passed an id"
(let [saved (db/tx {:kind :bibelot :name "thingy"})
retracted (db/retract (:id saved))]
(should= {:kind :db/retract :id (:id saved)} retracted)
(should= [] (db/find-by :bibelot :name "thingy"))))
)
(context "find-by"
#?(:clj (helper/with-db-schemas [bibelot thingy])
:cljs (helper/with-db-schemas [bibelot thingy]))
(it "find by attribute"
(let [saved (db/tx {:kind :bibelot :name "<NAME>y" :color "blue" :size 123})
loaded (db/find-by :bibelot :name "thingy")]
(should= (:id saved) (:id (first loaded)))
(should= "thingy" (:name (first loaded)))
(should= "blue" (:color (first loaded)))
(should= 123 (:size (first loaded)))))
(it "find by two attribute"
(let [saved (db/tx {:kind :bibelot :name "<NAME>y" :color "blue" :size 123})
loaded (db/find-by :bibelot :name "thingy" :color "blue")]
(should= (:id saved) (:id (first loaded)))))
(it "find by three attribute"
(let [saved (db/tx {:kind :bibelot :name "thingy" :color "blue" :size 123})
loaded (db/find-by :bibelot :name "thingy" :color "blue" :size 123)]
(should= (:id saved) (:id (first loaded)))))
(it "find-by with 4 attrs"
(let [bibby (db/tx {:kind :bibelot :name "<NAME>"})
saved (db/tx :kind :thingy :foo "<NAME>" :bar (:id bibby) :fizz 2 :bang :paul)]
(should (db/ffind-by :thingy :foo "<NAME>" :bar (:id bibby) :fizz 2 :bang :paul))
(should-not (db/ffind-by :thingy :foo "<NAME>" :bar (:id bibby) :fizz 2 :bang :paul))))
(it "find by nil"
(let [b1 (db/tx :kind :bibelot :name "Bee" :size 1)
b2 (db/tx :kind :bibelot :name "Bee" :color "blue")
b3 (db/tx :kind :bibelot :size 1 :color "blue")]
(should= [b1] (db/find-by :bibelot :name "Bee" :color nil))
(should= [b2] (db/find-by :bibelot :name "Bee" :size nil))
(should= [b3] (db/find-by :bibelot :color "blue" :name nil))))
)
(context "count-by"
#?(:clj (helper/with-db-schemas [bibelot thingy])
:cljs (helper/with-db-schemas [bibelot thingy]))
(it "count by attribute"
(let [saved (db/tx {:kind :bibelot :name "thingy" :color "blue" :size 123})]
(should= 1 (db/count-by :bibelot :name "thingy"))
(should= 0 (db/count-by :bibelot :name "blah"))))
(it "find-by with 4 attrs"
(let [bibby (db/tx {:kind :bibelot :name "<NAME>"})
saved (db/tx :kind :thingy :foo "<NAME>" :bar (:id bibby) :fizz 2 :bang :paul)]
(should= 1 (db/count-by :thingy :foo "<NAME>" :bar (:id bibby) :fizz 2 :bang :<NAME>))
(should= 0 (db/count-by :thingy :foo "<NAME>" :bar (:id bibby) :fizz 2 :bang :<NAME>))))
)
(context "find-all"
#?(:clj (helper/with-db-schemas [bibelot])
:cljs (helper/with-db-schemas [bibelot]))
(before (db/tx :kind :bibelot :name "<NAME>" :color "red" :size 1)
(db/tx :kind :bibelot :name "<NAME>" :color "green" :size 2)
(db/tx :kind :bibelot :name "<NAME>" :color "blue" :size 3))
(it "find all bibelot/name"
(let [all (db/find-all :bibelot :name)]
(should= 3 (count all))
(should= #{1 2 3} (set (map :size all)))))
(it "find all bibelot/color"
(let [all (db/find-all :bibelot :color)]
(should= 3 (count all))
(should= #{1 2 3} (set (map :size all)))))
)
(context "count-all"
#?(:clj (helper/with-db-schemas [bibelot thingy])
:cljs (helper/with-db-schemas [bibelot thingy]))
(before (db/tx :kind :bibelot :name "<NAME>" :color "red" :size 1)
(db/tx :kind :bibelot :name "<NAME>" :color "green" :size 2)
(db/tx :kind :bibelot :name "<NAME>" :color "blue" :size 3))
(it "find all bibelot/name"
(should= 0 (db/count-all :thingy :foo))
(should= 3 (db/count-all :bibelot :name)))
)
(context "reference values"
#?(:clj (helper/with-db-schemas [bibelot gewgaw])
:cljs (helper/with-db-schemas [bibelot gewgaw]))
(it "loading"
(let [child (db/tx {:kind :bibelot :name "child" :color "golden"})
saved (db/tx {:kind :gewgaw :name "parent" :thing (:id child)})
loaded (db/entity (:id saved))
loaded-child (db/entity (:thing loaded))]
(should= (:id loaded) (:id saved))
(should= (:id child) (:id loaded-child))))
(it "find by attribute"
(let [child (db/tx {:kind :bibelot :name "child" :color "golden"})
saved (db/tx {:kind :gewgaw :name "parent" :thing (:id child)})
result (db/find-by :gewgaw :thing (:id child))]
(should= (:id saved) (:id (first result)))
(should= "parent" (:name (first result)))))
(it "pass through loading and saving seamelessly"
(let [child (db/tx {:kind :bibelot :name "child" :color "golden"})
saved (db/tx {:kind :gewgaw :name "parent" :thing (:id child)})
loaded (db/entity (:id saved))
saved-again (db/tx loaded)]
(should= (:thing loaded) (:thing saved-again))))
)
(context "multiple values"
#?(:clj (helper/with-db-schemas [bibelot doodad])
:cljs (helper/with-db-schemas [bibelot doodad]))
(it "loading"
(let [saved (db/tx {:kind :doodad :names ["foo" "bar"] :numbers [8 42]})
loaded (db/entity (:id saved))]
(should= (:id loaded) (:id saved))
(should= #{"foo" "bar"} (set (:names loaded)))
(should= #{8 42} (set (:numbers loaded)))))
(it "find by attribute"
(let [saved (db/tx {:kind :doodad :names ["foo" "bar"] :numbers [8 42]})
loaded (db/find-by :doodad :names "bar")]
(should= 1 (count loaded))
(should= (:id saved) (:id (first loaded)))))
(it "retracting [string] value"
(let [saved (db/tx {:kind :doodad :names ["foo" "bar"] :numbers [8 42]})
updated (db/tx saved :names nil)]
(should= nil (seq (:names updated)))))
(it "retracting one value from [string]"
(let [saved (db/tx {:kind :doodad :names ["foo" "bar"] :numbers [8 42]})
updated (db/tx saved :names ["foo"])]
(should= #{"foo"} (set (:names updated)))))
(it "adding one value to [string]"
(let [saved (db/tx {:kind :doodad :names ["foo" "bar"] :numbers [8 42]})
updated (db/tx saved :names ["foo" "bar" "fizz"])]
(should= #{"foo" "bar" "fizz"} (set (:names updated)))))
(it "using refs"
(let [child1 (db/tx {:kind :bibelot :name "child1" :color "golden"})
child2 (db/tx {:kind :bibelot :name "child2" :color "silver"})
saved (db/tx {:kind :doodad :things [(:id child1) (:id child2)]})
loaded (db/entity (:id saved))]
(should= #{(:id child1) (:id child2)} (set (:things saved)))
(should= #{(:id child1) (:id child2)} (set (:things loaded)))))
(it "retracting whole [ref] value"
(let [child1 (db/tx {:kind :bibelot :name "child1" :color "golden"})
child2 (db/tx {:kind :bibelot :name "child2" :color "silver"})
saved (db/tx {:kind :doodad :things [(:id child1) (:id child2)]})
updated (db/tx saved :things nil)]
(should= nil (seq (:things updated)))))
(it "removing one [ref] values"
(let [child1 (db/tx {:kind :bibelot :name "child1" :color "golden"})
child2 (db/tx {:kind :bibelot :name "child2" :color "silver"})
saved (db/tx {:kind :doodad :things [(:id child1) (:id child2)]})
updated (db/tx saved :things [(:id child1)])]
(should= #{(:id child1)} (set (:things updated)))))
(it "adding one [ref] values"
(let [child1 (db/tx {:kind :bibelot :name "child1" :color "golden"})
child2 (db/tx {:kind :bibelot :name "child2" :color "silver"})
child3 (db/tx {:kind :bibelot :name "child3" :color "bronze"})
saved (db/tx {:kind :doodad :things [(:id child1) (:id child2)]})
updated (db/tx saved :things [(:id child1) (:id child2) (:id child3)])]
(should= #{(:id child1) (:id child2) (:id child3)} (set (:things updated)))))
)
(context "retracting null values"
#?(:clj (helper/with-db-schemas [bibelot thingy])
:cljs (helper/with-db-schemas [bibelot thingy]))
(with child (db/tx {:kind :bibelot :name "child" :color "golden"}))
(with original (db/tx {:kind :thingy
:foo "foo"
:bar (:id @child)
:fizz 2015
:bang :kapow!}))
(it "can set a string to nil"
(let [result (db/tx (assoc @original :foo nil))]
(should= nil (:foo result))
(should= nil (:foo (db/reload @original)))))
(it "can set a ref to nil"
(let [result (db/tx (assoc @original :bar nil))]
(should= nil (:bar result))
(should= nil (:bar (db/reload @original)))))
(it "can set a long to nil"
(let [result (db/tx (dissoc @original :fizz))]
(should= nil (:fizz result))
(should= nil (:fizz (db/reload @original)))))
(it "can set a keyword to nil"
(let [result (db/tx (dissoc @original :bang))]
(should= nil (:bang result))
(should= nil (:bang (db/reload @original)))))
)
(context "transactions"
#?(:clj (helper/with-db-schemas [bibelot gewgaw])
:cljs (helper/with-db-schemas [bibelot gewgaw]))
(it "save multiple entities at the same time"
(let [g1 {:kind :gewgaw :name "1"}
g2 {:kind :gewgaw :name "2"}
result (db/tx* [g1 g2])]
(should= "1" (:name (db/reload (first result))))
(should= "2" (:name (db/reload (second result))))))
(it "update multiple entities at the same time"
(let [g1 (db/tx {:kind :gewgaw :name "1"})
g2 (db/tx {:kind :gewgaw :name "2"})
result (db/tx* [(assoc g1 :name "one") (dissoc g2 :name)])]
(should= "one" (:name (db/reload (first result))))
(should= nil (:name (db/reload (second result))))))
(it "retract with meta-data on any of the entities"
(let [g1 (db/tx {:kind :gewgaw :name "1"})
g2 (db/tx {:kind :gewgaw :name "2"})
[u1 u2] (db/tx* [(assoc g1 :name "one") (assoc g2 :kind :db/retract)])]
(should= "one" (:name (db/reload u1)))
(should= nil (db/reload u2))
(should= {:kind :db/retract :id (:id g2)} u2)))
(it "temp-ids are resolved"
(let [bibby {:kind :bibelot :name "bibby" :id (db/tempid)}
gewy {:kind :gewgaw :thing (:id bibby)}
result (db/tx* [bibby gewy])
[saved-bibby saved-gewy] result]
(should= (:id saved-bibby) (:thing saved-gewy))))
)
)
| true | (ns c3kit.bucket.dbc-spec
(:require
[speclj.core #?(:clj :refer :cljs :refer-macros) [context describe it xit should= should-contain
should-not-contain should-throw should-be-a with
should-not= before should should-not should-not-throw]]
[c3kit.bucket.db :as db]
[c3kit.apron.log :as log]
[c3kit.apron.schema :as s]
[c3kit.bucket.spec-helper :as helper]
))
(def bibelot
{:kind (s/kind :bibelot)
:id s/id
:name {:type :string}
:size {:type :long}
:color {:type :string}})
(def gewgaw
{:kind (s/kind :gewgaw)
:id s/id
:name {:type :string}
:thing {:type :ref}})
(def doodad
{:kind (s/kind :doodad)
:id s/id
:names {:type [:string]}
:numbers {:type [:long]}
:things {:type [:ref]}})
(def thingy
{:kind (s/kind :thingy)
:id s/id
:foo {:type :string}
:bar {:type :ref}
:fizz {:type :long}
:bang {:type :keyword}})
(def child :undefined)
(def original :undefined)
(describe "DB Common"
(context "CRUD"
(helper/with-db-schemas [bibelot])
(it "returns nil on missing id"
(should= nil (db/entity -1))
(should= nil (db/entity nil))
(should= nil (db/entity ""))
(should= nil (db/entity "-1")))
(it "tx nil entities"
(should-not-throw (db/tx nil))
(should-not-throw (db/tx* [nil])))
(it "create and read"
(let [saved (db/tx {:kind :bibelot :name "thingy"})
loaded (db/entity (:id saved))]
(should= :bibelot (:kind loaded))
(should= "thingy" (:name loaded))
(should= (:id loaded) (:id saved))))
(it "entity!"
(let [saved (db/tx {:kind :bibelot :name "PI:NAME:<NAME>END_PIy"})]
(should= saved (db/entity! (:id saved)))
(should-throw (db/entity! 9999))))
(it "entity-of-kind"
(let [saved (db/tx {:kind :bibelot :name "thingy"})]
(should= saved (db/entity-of-kind :bibelot (:id saved)))
(should= nil (db/entity-of-kind :other (:id saved)))))
(it "entity-of-kind!"
(let [saved (db/tx {:kind :bibelot :name "thingy"})]
(should= saved (db/entity-of-kind! :bibelot (:id saved)))
(should-throw (db/entity-of-kind! :other (:id saved)))))
(it "updating"
(try
(let [saved (db/tx {:kind :bibelot :name "thingy"})
updated (db/tx saved :name "whatsamajigger")
loaded (db/entity (:id saved))]
(should= "whatsamajigger" (:name loaded))
(should= (:id saved) (:id loaded))
(should= (:id saved) (:id updated)))
(catch #?(:clj Exception :cljs :default) e
(log/error e))))
(it "retracting via metadata"
(let [saved (db/tx {:kind :bibelot :name "thingy"})
updated (db/tx (with-meta saved {:retract true}))]
(should= nil (db/entity (:id saved)))
(should= {:kind :db/retract :id (:id saved)} updated)))
(it "retracting via :kind :db/retract"
(let [saved (db/tx {:kind :bibelot :name "thingy"})
updated (db/tx (assoc saved :kind :db/retract))]
(should= nil (db/entity (:id saved)))
(should= {:kind :db/retract :id (:id saved)} updated)))
(it "retracting when passed an entity"
(let [saved (db/tx {:kind :bibelot :name "thingy"})
retracted (db/retract saved)]
(should= {:kind :db/retract :id (:id saved)} retracted)
(should= [] (db/find-by :bibelot :name "thingy"))))
(it "retracting when passed an id"
(let [saved (db/tx {:kind :bibelot :name "thingy"})
retracted (db/retract (:id saved))]
(should= {:kind :db/retract :id (:id saved)} retracted)
(should= [] (db/find-by :bibelot :name "thingy"))))
)
(context "find-by"
#?(:clj (helper/with-db-schemas [bibelot thingy])
:cljs (helper/with-db-schemas [bibelot thingy]))
(it "find by attribute"
(let [saved (db/tx {:kind :bibelot :name "PI:NAME:<NAME>END_PIy" :color "blue" :size 123})
loaded (db/find-by :bibelot :name "thingy")]
(should= (:id saved) (:id (first loaded)))
(should= "thingy" (:name (first loaded)))
(should= "blue" (:color (first loaded)))
(should= 123 (:size (first loaded)))))
(it "find by two attribute"
(let [saved (db/tx {:kind :bibelot :name "PI:NAME:<NAME>END_PIy" :color "blue" :size 123})
loaded (db/find-by :bibelot :name "thingy" :color "blue")]
(should= (:id saved) (:id (first loaded)))))
(it "find by three attribute"
(let [saved (db/tx {:kind :bibelot :name "thingy" :color "blue" :size 123})
loaded (db/find-by :bibelot :name "thingy" :color "blue" :size 123)]
(should= (:id saved) (:id (first loaded)))))
(it "find-by with 4 attrs"
(let [bibby (db/tx {:kind :bibelot :name "PI:NAME:<NAME>END_PI"})
saved (db/tx :kind :thingy :foo "PI:NAME:<NAME>END_PI" :bar (:id bibby) :fizz 2 :bang :paul)]
(should (db/ffind-by :thingy :foo "PI:NAME:<NAME>END_PI" :bar (:id bibby) :fizz 2 :bang :paul))
(should-not (db/ffind-by :thingy :foo "PI:NAME:<NAME>END_PI" :bar (:id bibby) :fizz 2 :bang :paul))))
(it "find by nil"
(let [b1 (db/tx :kind :bibelot :name "Bee" :size 1)
b2 (db/tx :kind :bibelot :name "Bee" :color "blue")
b3 (db/tx :kind :bibelot :size 1 :color "blue")]
(should= [b1] (db/find-by :bibelot :name "Bee" :color nil))
(should= [b2] (db/find-by :bibelot :name "Bee" :size nil))
(should= [b3] (db/find-by :bibelot :color "blue" :name nil))))
)
(context "count-by"
#?(:clj (helper/with-db-schemas [bibelot thingy])
:cljs (helper/with-db-schemas [bibelot thingy]))
(it "count by attribute"
(let [saved (db/tx {:kind :bibelot :name "thingy" :color "blue" :size 123})]
(should= 1 (db/count-by :bibelot :name "thingy"))
(should= 0 (db/count-by :bibelot :name "blah"))))
(it "find-by with 4 attrs"
(let [bibby (db/tx {:kind :bibelot :name "PI:NAME:<NAME>END_PI"})
saved (db/tx :kind :thingy :foo "PI:NAME:<NAME>END_PI" :bar (:id bibby) :fizz 2 :bang :paul)]
(should= 1 (db/count-by :thingy :foo "PI:NAME:<NAME>END_PI" :bar (:id bibby) :fizz 2 :bang :PI:NAME:<NAME>END_PI))
(should= 0 (db/count-by :thingy :foo "PI:NAME:<NAME>END_PI" :bar (:id bibby) :fizz 2 :bang :PI:NAME:<NAME>END_PI))))
)
(context "find-all"
#?(:clj (helper/with-db-schemas [bibelot])
:cljs (helper/with-db-schemas [bibelot]))
(before (db/tx :kind :bibelot :name "PI:NAME:<NAME>END_PI" :color "red" :size 1)
(db/tx :kind :bibelot :name "PI:NAME:<NAME>END_PI" :color "green" :size 2)
(db/tx :kind :bibelot :name "PI:NAME:<NAME>END_PI" :color "blue" :size 3))
(it "find all bibelot/name"
(let [all (db/find-all :bibelot :name)]
(should= 3 (count all))
(should= #{1 2 3} (set (map :size all)))))
(it "find all bibelot/color"
(let [all (db/find-all :bibelot :color)]
(should= 3 (count all))
(should= #{1 2 3} (set (map :size all)))))
)
(context "count-all"
#?(:clj (helper/with-db-schemas [bibelot thingy])
:cljs (helper/with-db-schemas [bibelot thingy]))
(before (db/tx :kind :bibelot :name "PI:NAME:<NAME>END_PI" :color "red" :size 1)
(db/tx :kind :bibelot :name "PI:NAME:<NAME>END_PI" :color "green" :size 2)
(db/tx :kind :bibelot :name "PI:NAME:<NAME>END_PI" :color "blue" :size 3))
(it "find all bibelot/name"
(should= 0 (db/count-all :thingy :foo))
(should= 3 (db/count-all :bibelot :name)))
)
(context "reference values"
#?(:clj (helper/with-db-schemas [bibelot gewgaw])
:cljs (helper/with-db-schemas [bibelot gewgaw]))
(it "loading"
(let [child (db/tx {:kind :bibelot :name "child" :color "golden"})
saved (db/tx {:kind :gewgaw :name "parent" :thing (:id child)})
loaded (db/entity (:id saved))
loaded-child (db/entity (:thing loaded))]
(should= (:id loaded) (:id saved))
(should= (:id child) (:id loaded-child))))
(it "find by attribute"
(let [child (db/tx {:kind :bibelot :name "child" :color "golden"})
saved (db/tx {:kind :gewgaw :name "parent" :thing (:id child)})
result (db/find-by :gewgaw :thing (:id child))]
(should= (:id saved) (:id (first result)))
(should= "parent" (:name (first result)))))
(it "pass through loading and saving seamelessly"
(let [child (db/tx {:kind :bibelot :name "child" :color "golden"})
saved (db/tx {:kind :gewgaw :name "parent" :thing (:id child)})
loaded (db/entity (:id saved))
saved-again (db/tx loaded)]
(should= (:thing loaded) (:thing saved-again))))
)
(context "multiple values"
#?(:clj (helper/with-db-schemas [bibelot doodad])
:cljs (helper/with-db-schemas [bibelot doodad]))
(it "loading"
(let [saved (db/tx {:kind :doodad :names ["foo" "bar"] :numbers [8 42]})
loaded (db/entity (:id saved))]
(should= (:id loaded) (:id saved))
(should= #{"foo" "bar"} (set (:names loaded)))
(should= #{8 42} (set (:numbers loaded)))))
(it "find by attribute"
(let [saved (db/tx {:kind :doodad :names ["foo" "bar"] :numbers [8 42]})
loaded (db/find-by :doodad :names "bar")]
(should= 1 (count loaded))
(should= (:id saved) (:id (first loaded)))))
(it "retracting [string] value"
(let [saved (db/tx {:kind :doodad :names ["foo" "bar"] :numbers [8 42]})
updated (db/tx saved :names nil)]
(should= nil (seq (:names updated)))))
(it "retracting one value from [string]"
(let [saved (db/tx {:kind :doodad :names ["foo" "bar"] :numbers [8 42]})
updated (db/tx saved :names ["foo"])]
(should= #{"foo"} (set (:names updated)))))
(it "adding one value to [string]"
(let [saved (db/tx {:kind :doodad :names ["foo" "bar"] :numbers [8 42]})
updated (db/tx saved :names ["foo" "bar" "fizz"])]
(should= #{"foo" "bar" "fizz"} (set (:names updated)))))
(it "using refs"
(let [child1 (db/tx {:kind :bibelot :name "child1" :color "golden"})
child2 (db/tx {:kind :bibelot :name "child2" :color "silver"})
saved (db/tx {:kind :doodad :things [(:id child1) (:id child2)]})
loaded (db/entity (:id saved))]
(should= #{(:id child1) (:id child2)} (set (:things saved)))
(should= #{(:id child1) (:id child2)} (set (:things loaded)))))
(it "retracting whole [ref] value"
(let [child1 (db/tx {:kind :bibelot :name "child1" :color "golden"})
child2 (db/tx {:kind :bibelot :name "child2" :color "silver"})
saved (db/tx {:kind :doodad :things [(:id child1) (:id child2)]})
updated (db/tx saved :things nil)]
(should= nil (seq (:things updated)))))
(it "removing one [ref] values"
(let [child1 (db/tx {:kind :bibelot :name "child1" :color "golden"})
child2 (db/tx {:kind :bibelot :name "child2" :color "silver"})
saved (db/tx {:kind :doodad :things [(:id child1) (:id child2)]})
updated (db/tx saved :things [(:id child1)])]
(should= #{(:id child1)} (set (:things updated)))))
(it "adding one [ref] values"
(let [child1 (db/tx {:kind :bibelot :name "child1" :color "golden"})
child2 (db/tx {:kind :bibelot :name "child2" :color "silver"})
child3 (db/tx {:kind :bibelot :name "child3" :color "bronze"})
saved (db/tx {:kind :doodad :things [(:id child1) (:id child2)]})
updated (db/tx saved :things [(:id child1) (:id child2) (:id child3)])]
(should= #{(:id child1) (:id child2) (:id child3)} (set (:things updated)))))
)
(context "retracting null values"
#?(:clj (helper/with-db-schemas [bibelot thingy])
:cljs (helper/with-db-schemas [bibelot thingy]))
(with child (db/tx {:kind :bibelot :name "child" :color "golden"}))
(with original (db/tx {:kind :thingy
:foo "foo"
:bar (:id @child)
:fizz 2015
:bang :kapow!}))
(it "can set a string to nil"
(let [result (db/tx (assoc @original :foo nil))]
(should= nil (:foo result))
(should= nil (:foo (db/reload @original)))))
(it "can set a ref to nil"
(let [result (db/tx (assoc @original :bar nil))]
(should= nil (:bar result))
(should= nil (:bar (db/reload @original)))))
(it "can set a long to nil"
(let [result (db/tx (dissoc @original :fizz))]
(should= nil (:fizz result))
(should= nil (:fizz (db/reload @original)))))
(it "can set a keyword to nil"
(let [result (db/tx (dissoc @original :bang))]
(should= nil (:bang result))
(should= nil (:bang (db/reload @original)))))
)
(context "transactions"
#?(:clj (helper/with-db-schemas [bibelot gewgaw])
:cljs (helper/with-db-schemas [bibelot gewgaw]))
(it "save multiple entities at the same time"
(let [g1 {:kind :gewgaw :name "1"}
g2 {:kind :gewgaw :name "2"}
result (db/tx* [g1 g2])]
(should= "1" (:name (db/reload (first result))))
(should= "2" (:name (db/reload (second result))))))
(it "update multiple entities at the same time"
(let [g1 (db/tx {:kind :gewgaw :name "1"})
g2 (db/tx {:kind :gewgaw :name "2"})
result (db/tx* [(assoc g1 :name "one") (dissoc g2 :name)])]
(should= "one" (:name (db/reload (first result))))
(should= nil (:name (db/reload (second result))))))
(it "retract with meta-data on any of the entities"
(let [g1 (db/tx {:kind :gewgaw :name "1"})
g2 (db/tx {:kind :gewgaw :name "2"})
[u1 u2] (db/tx* [(assoc g1 :name "one") (assoc g2 :kind :db/retract)])]
(should= "one" (:name (db/reload u1)))
(should= nil (db/reload u2))
(should= {:kind :db/retract :id (:id g2)} u2)))
(it "temp-ids are resolved"
(let [bibby {:kind :bibelot :name "bibby" :id (db/tempid)}
gewy {:kind :gewgaw :thing (:id bibby)}
result (db/tx* [bibby gewy])
[saved-bibby saved-gewy] result]
(should= (:id saved-bibby) (:thing saved-gewy))))
)
)
|
[
{
"context": "d :accounts add (seed/new-account (new-uuid 100) \"Tony\" \"tony@example.com\" \"letmein\"\n ",
"end": 1332,
"score": 0.9995402097702026,
"start": 1328,
"tag": "NAME",
"value": "Tony"
},
{
"context": "unts add (seed/new-account (new-uuid 100) \"Tony\" \"tony@example.com\" \"letmein\"\n ",
"end": 1351,
"score": 0.9999232888221741,
"start": 1335,
"tag": "EMAIL",
"value": "tony@example.com"
},
{
"context": "account (new-uuid 100) \"Tony\" \"tony@example.com\" \"letmein\"\n ",
"end": 1361,
"score": 0.9200431704521179,
"start": 1354,
"tag": "USERNAME",
"value": "letmein"
},
{
"context": ":accounts add (seed/new-account (new-uuid 101) \"Sam\" \"sam@example.com\" \"letmein\"))\n ",
"end": 1875,
"score": 0.9997908473014832,
"start": 1872,
"tag": "NAME",
"value": "Sam"
},
{
"context": "nts add (seed/new-account (new-uuid 101) \"Sam\" \"sam@example.com\" \"letmein\"))\n (update :accoun",
"end": 1893,
"score": 0.999925971031189,
"start": 1878,
"tag": "EMAIL",
"value": "sam@example.com"
},
{
"context": ":accounts add (seed/new-account (new-uuid 102) \"Sally\" \"sally@example.com\" \"letmein\"))\n ",
"end": 1991,
"score": 0.9998199939727783,
"start": 1986,
"tag": "NAME",
"value": "Sally"
},
{
"context": "s add (seed/new-account (new-uuid 102) \"Sally\" \"sally@example.com\" \"letmein\"))\n (update :accoun",
"end": 2011,
"score": 0.9999266266822815,
"start": 1994,
"tag": "EMAIL",
"value": "sally@example.com"
},
{
"context": ":accounts add (seed/new-account (new-uuid 103) \"Barbara\" \"barb@example.com\" \"letmein\"))\n ",
"end": 2111,
"score": 0.9997944831848145,
"start": 2104,
"tag": "NAME",
"value": "Barbara"
},
{
"context": " add (seed/new-account (new-uuid 103) \"Barbara\" \"barb@example.com\" \"letmein\"))\n (update :catego",
"end": 2130,
"score": 0.9999259114265442,
"start": 2114,
"tag": "EMAIL",
"value": "barb@example.com"
}
] | src/crux/development.clj | somanythings/fulcro-rad-demo | 11 | (ns development
(:require
[clojure.tools.namespace.repl :as tools-ns :refer [set-refresh-dirs]]
[com.example.components.crux :refer [crux-nodes]]
[com.example.components.ring-middleware]
[com.example.components.server]
[com.example.model.seed :as seed]
[com.fulcrologic.rad.ids :refer [new-uuid]]
[mount.core :as mount]
[taoensso.timbre :as log]
[crux.api :as crux]
[com.fulcrologic.rad.type-support.date-time :as dt]))
(set-refresh-dirs "src/main" "src/crux" "src/dev" "src/shared")
(defn seed! []
(dt/set-timezone! "America/Los_Angeles")
(let [node (:main crux-nodes)
date-1 (dt/html-datetime-string->inst "2020-01-01T12:00")
date-2 (dt/html-datetime-string->inst "2020-01-05T12:00")
date-3 (dt/html-datetime-string->inst "2020-02-01T12:00")
date-4 (dt/html-datetime-string->inst "2020-03-10T12:00")
date-5 (dt/html-datetime-string->inst "2020-03-21T12:00")
add (fnil conj [])]
(when node
(log/info "SEEDING data.")
(let [data (-> {}
(update :addresses add (seed/new-address (new-uuid 1) "111 Main St."))
(update :addresses add (seed/new-address (new-uuid 300) "222 Other"))
(as-> d (update d :accounts add (seed/new-account (new-uuid 100) "Tony" "tony@example.com" "letmein"
:account/addresses #{(get-in d [:addresses 0 :crux.db/id])}
:account/primary-address (get-in d [:addresses 1 :crux.db/id])
:time-zone/zone-id :time-zone.zone-id/America-Los_Angeles)))
(update :accounts add (seed/new-account (new-uuid 101) "Sam" "sam@example.com" "letmein"))
(update :accounts add (seed/new-account (new-uuid 102) "Sally" "sally@example.com" "letmein"))
(update :accounts add (seed/new-account (new-uuid 103) "Barbara" "barb@example.com" "letmein"))
(update :categories add (seed/new-category (new-uuid 1000) "Tools"))
(update :categories add (seed/new-category (new-uuid 1002) "Toys"))
(update :categories add (seed/new-category (new-uuid 1003) "Misc"))
(as-> d (update d :items add (seed/new-item (new-uuid 200) "Widget" 33.99
:item/category (get-in d [:categories 2 :crux.db/id]))))
(as-> d (update d :items add (seed/new-item (new-uuid 201) "Screwdriver" 4.99
:item/category (get-in d [:categories 0 :crux.db/id]))))
(as-> d (update d :items add (seed/new-item (new-uuid 202) "Wrench" 14.99
:item/category (get-in d [:categories 0 :crux.db/id]))))
(as-> d (update d :items add (seed/new-item (new-uuid 203) "Hammer" 14.99
:item/category (get-in d [:categories 0 :crux.db/id]))))
(as-> d (update d :items add (seed/new-item (new-uuid 204) "Doll" 4.99
:item/category (get-in d [:categories 1 :crux.db/id]))))
(as-> d (update d :items add (seed/new-item (new-uuid 205) "Robot" 94.99
:item/category (get-in d [:categories 1 :crux.db/id]))))
(as-> d (update d :items add (seed/new-item (new-uuid 206) "Building Blocks" 24.99
:item/category (get-in d [:categories 1 :crux.db/id]))))
(as-> d (update d :line-items add (seed/new-line-item (new-uuid 212) (get-in d [:items 4 :crux.db/id]) 1 5.0M)))
(as-> d (update d :line-items add (seed/new-line-item (new-uuid 213) (get-in d [:items 3 :crux.db/id]) 1 14.99M)))
(as-> d (update d :line-items add (seed/new-line-item (new-uuid 214) (get-in d [:items 2 :crux.db/id]) 1 12.50M)))
(as-> d (update d :line-items add (seed/new-line-item (new-uuid 215)(get-in d [:items 0 :crux.db/id]) 2 32.0M)))
(as-> d (update d :line-items add (seed/new-line-item (new-uuid 216)(get-in d [:items 2 :crux.db/id]) 2 12.50M)))
(as-> d (update d :line-items add (seed/new-line-item (new-uuid 217)(get-in d [:items 3 :crux.db/id]) 2 12.50M)))
(as-> d (update d :line-items add (seed/new-line-item (new-uuid 218)(get-in d [:items 5 :crux.db/id]) 6 89.99M)))
(as-> d (update d :line-items add (seed/new-line-item (new-uuid 219)(get-in d [:items 6 :crux.db/id]) 10 20.0M)))
(as-> d (update d :invoices add (seed/new-invoice (new-uuid 207) date-1 (get-in d [:accounts 0 :crux.db/id])
[(get-in d [:line-items 0]) (get-in d [:line-items 1])])))
(as-> d (update d :invoices add (seed/new-invoice (new-uuid 208) date-2 (get-in d [:accounts 2 :crux.db/id])
[(get-in d [:line-items 2]) (get-in d [:line-items 3])])))
(as-> d (update d :invoices add (seed/new-invoice (new-uuid 209) date-3 (get-in d [:accounts 1 :crux.db/id])
[(get-in d [:line-items 4]) (get-in d [:line-items 5])])))
(as-> d (update d :invoices add (seed/new-invoice (new-uuid 210) date-4 (get-in d [:accounts 2 :crux.db/id])
[(get-in d [:line-items 6])])))
(as-> d (update d :invoices add (seed/new-invoice (new-uuid 211) date-5 (get-in d [:accounts 3 :crux.db/id])
[(get-in d [:line-items 7])]))))]
(crux/submit-tx node (->> data
vals
flatten
(mapv (fn [d] [:crux.tx/put d]))))))))
(defn start []
(mount/start-with-args {:config "config/dev.edn"})
(seed!)
:ok)
(defn stop
"Stop the server."
[]
(mount/stop))
(def go start)
(defn restart
"Stop, refresh, and restart the server."
[]
(stop)
(tools-ns/refresh :after 'development/start))
(def reset #'restart)
(comment
(start)
)
| 101374 | (ns development
(:require
[clojure.tools.namespace.repl :as tools-ns :refer [set-refresh-dirs]]
[com.example.components.crux :refer [crux-nodes]]
[com.example.components.ring-middleware]
[com.example.components.server]
[com.example.model.seed :as seed]
[com.fulcrologic.rad.ids :refer [new-uuid]]
[mount.core :as mount]
[taoensso.timbre :as log]
[crux.api :as crux]
[com.fulcrologic.rad.type-support.date-time :as dt]))
(set-refresh-dirs "src/main" "src/crux" "src/dev" "src/shared")
(defn seed! []
(dt/set-timezone! "America/Los_Angeles")
(let [node (:main crux-nodes)
date-1 (dt/html-datetime-string->inst "2020-01-01T12:00")
date-2 (dt/html-datetime-string->inst "2020-01-05T12:00")
date-3 (dt/html-datetime-string->inst "2020-02-01T12:00")
date-4 (dt/html-datetime-string->inst "2020-03-10T12:00")
date-5 (dt/html-datetime-string->inst "2020-03-21T12:00")
add (fnil conj [])]
(when node
(log/info "SEEDING data.")
(let [data (-> {}
(update :addresses add (seed/new-address (new-uuid 1) "111 Main St."))
(update :addresses add (seed/new-address (new-uuid 300) "222 Other"))
(as-> d (update d :accounts add (seed/new-account (new-uuid 100) "<NAME>" "<EMAIL>" "letmein"
:account/addresses #{(get-in d [:addresses 0 :crux.db/id])}
:account/primary-address (get-in d [:addresses 1 :crux.db/id])
:time-zone/zone-id :time-zone.zone-id/America-Los_Angeles)))
(update :accounts add (seed/new-account (new-uuid 101) "<NAME>" "<EMAIL>" "letmein"))
(update :accounts add (seed/new-account (new-uuid 102) "<NAME>" "<EMAIL>" "letmein"))
(update :accounts add (seed/new-account (new-uuid 103) "<NAME>" "<EMAIL>" "letmein"))
(update :categories add (seed/new-category (new-uuid 1000) "Tools"))
(update :categories add (seed/new-category (new-uuid 1002) "Toys"))
(update :categories add (seed/new-category (new-uuid 1003) "Misc"))
(as-> d (update d :items add (seed/new-item (new-uuid 200) "Widget" 33.99
:item/category (get-in d [:categories 2 :crux.db/id]))))
(as-> d (update d :items add (seed/new-item (new-uuid 201) "Screwdriver" 4.99
:item/category (get-in d [:categories 0 :crux.db/id]))))
(as-> d (update d :items add (seed/new-item (new-uuid 202) "Wrench" 14.99
:item/category (get-in d [:categories 0 :crux.db/id]))))
(as-> d (update d :items add (seed/new-item (new-uuid 203) "Hammer" 14.99
:item/category (get-in d [:categories 0 :crux.db/id]))))
(as-> d (update d :items add (seed/new-item (new-uuid 204) "Doll" 4.99
:item/category (get-in d [:categories 1 :crux.db/id]))))
(as-> d (update d :items add (seed/new-item (new-uuid 205) "Robot" 94.99
:item/category (get-in d [:categories 1 :crux.db/id]))))
(as-> d (update d :items add (seed/new-item (new-uuid 206) "Building Blocks" 24.99
:item/category (get-in d [:categories 1 :crux.db/id]))))
(as-> d (update d :line-items add (seed/new-line-item (new-uuid 212) (get-in d [:items 4 :crux.db/id]) 1 5.0M)))
(as-> d (update d :line-items add (seed/new-line-item (new-uuid 213) (get-in d [:items 3 :crux.db/id]) 1 14.99M)))
(as-> d (update d :line-items add (seed/new-line-item (new-uuid 214) (get-in d [:items 2 :crux.db/id]) 1 12.50M)))
(as-> d (update d :line-items add (seed/new-line-item (new-uuid 215)(get-in d [:items 0 :crux.db/id]) 2 32.0M)))
(as-> d (update d :line-items add (seed/new-line-item (new-uuid 216)(get-in d [:items 2 :crux.db/id]) 2 12.50M)))
(as-> d (update d :line-items add (seed/new-line-item (new-uuid 217)(get-in d [:items 3 :crux.db/id]) 2 12.50M)))
(as-> d (update d :line-items add (seed/new-line-item (new-uuid 218)(get-in d [:items 5 :crux.db/id]) 6 89.99M)))
(as-> d (update d :line-items add (seed/new-line-item (new-uuid 219)(get-in d [:items 6 :crux.db/id]) 10 20.0M)))
(as-> d (update d :invoices add (seed/new-invoice (new-uuid 207) date-1 (get-in d [:accounts 0 :crux.db/id])
[(get-in d [:line-items 0]) (get-in d [:line-items 1])])))
(as-> d (update d :invoices add (seed/new-invoice (new-uuid 208) date-2 (get-in d [:accounts 2 :crux.db/id])
[(get-in d [:line-items 2]) (get-in d [:line-items 3])])))
(as-> d (update d :invoices add (seed/new-invoice (new-uuid 209) date-3 (get-in d [:accounts 1 :crux.db/id])
[(get-in d [:line-items 4]) (get-in d [:line-items 5])])))
(as-> d (update d :invoices add (seed/new-invoice (new-uuid 210) date-4 (get-in d [:accounts 2 :crux.db/id])
[(get-in d [:line-items 6])])))
(as-> d (update d :invoices add (seed/new-invoice (new-uuid 211) date-5 (get-in d [:accounts 3 :crux.db/id])
[(get-in d [:line-items 7])]))))]
(crux/submit-tx node (->> data
vals
flatten
(mapv (fn [d] [:crux.tx/put d]))))))))
(defn start []
(mount/start-with-args {:config "config/dev.edn"})
(seed!)
:ok)
(defn stop
"Stop the server."
[]
(mount/stop))
(def go start)
(defn restart
"Stop, refresh, and restart the server."
[]
(stop)
(tools-ns/refresh :after 'development/start))
(def reset #'restart)
(comment
(start)
)
| true | (ns development
(:require
[clojure.tools.namespace.repl :as tools-ns :refer [set-refresh-dirs]]
[com.example.components.crux :refer [crux-nodes]]
[com.example.components.ring-middleware]
[com.example.components.server]
[com.example.model.seed :as seed]
[com.fulcrologic.rad.ids :refer [new-uuid]]
[mount.core :as mount]
[taoensso.timbre :as log]
[crux.api :as crux]
[com.fulcrologic.rad.type-support.date-time :as dt]))
(set-refresh-dirs "src/main" "src/crux" "src/dev" "src/shared")
(defn seed! []
(dt/set-timezone! "America/Los_Angeles")
(let [node (:main crux-nodes)
date-1 (dt/html-datetime-string->inst "2020-01-01T12:00")
date-2 (dt/html-datetime-string->inst "2020-01-05T12:00")
date-3 (dt/html-datetime-string->inst "2020-02-01T12:00")
date-4 (dt/html-datetime-string->inst "2020-03-10T12:00")
date-5 (dt/html-datetime-string->inst "2020-03-21T12:00")
add (fnil conj [])]
(when node
(log/info "SEEDING data.")
(let [data (-> {}
(update :addresses add (seed/new-address (new-uuid 1) "111 Main St."))
(update :addresses add (seed/new-address (new-uuid 300) "222 Other"))
(as-> d (update d :accounts add (seed/new-account (new-uuid 100) "PI:NAME:<NAME>END_PI" "PI:EMAIL:<EMAIL>END_PI" "letmein"
:account/addresses #{(get-in d [:addresses 0 :crux.db/id])}
:account/primary-address (get-in d [:addresses 1 :crux.db/id])
:time-zone/zone-id :time-zone.zone-id/America-Los_Angeles)))
(update :accounts add (seed/new-account (new-uuid 101) "PI:NAME:<NAME>END_PI" "PI:EMAIL:<EMAIL>END_PI" "letmein"))
(update :accounts add (seed/new-account (new-uuid 102) "PI:NAME:<NAME>END_PI" "PI:EMAIL:<EMAIL>END_PI" "letmein"))
(update :accounts add (seed/new-account (new-uuid 103) "PI:NAME:<NAME>END_PI" "PI:EMAIL:<EMAIL>END_PI" "letmein"))
(update :categories add (seed/new-category (new-uuid 1000) "Tools"))
(update :categories add (seed/new-category (new-uuid 1002) "Toys"))
(update :categories add (seed/new-category (new-uuid 1003) "Misc"))
(as-> d (update d :items add (seed/new-item (new-uuid 200) "Widget" 33.99
:item/category (get-in d [:categories 2 :crux.db/id]))))
(as-> d (update d :items add (seed/new-item (new-uuid 201) "Screwdriver" 4.99
:item/category (get-in d [:categories 0 :crux.db/id]))))
(as-> d (update d :items add (seed/new-item (new-uuid 202) "Wrench" 14.99
:item/category (get-in d [:categories 0 :crux.db/id]))))
(as-> d (update d :items add (seed/new-item (new-uuid 203) "Hammer" 14.99
:item/category (get-in d [:categories 0 :crux.db/id]))))
(as-> d (update d :items add (seed/new-item (new-uuid 204) "Doll" 4.99
:item/category (get-in d [:categories 1 :crux.db/id]))))
(as-> d (update d :items add (seed/new-item (new-uuid 205) "Robot" 94.99
:item/category (get-in d [:categories 1 :crux.db/id]))))
(as-> d (update d :items add (seed/new-item (new-uuid 206) "Building Blocks" 24.99
:item/category (get-in d [:categories 1 :crux.db/id]))))
(as-> d (update d :line-items add (seed/new-line-item (new-uuid 212) (get-in d [:items 4 :crux.db/id]) 1 5.0M)))
(as-> d (update d :line-items add (seed/new-line-item (new-uuid 213) (get-in d [:items 3 :crux.db/id]) 1 14.99M)))
(as-> d (update d :line-items add (seed/new-line-item (new-uuid 214) (get-in d [:items 2 :crux.db/id]) 1 12.50M)))
(as-> d (update d :line-items add (seed/new-line-item (new-uuid 215)(get-in d [:items 0 :crux.db/id]) 2 32.0M)))
(as-> d (update d :line-items add (seed/new-line-item (new-uuid 216)(get-in d [:items 2 :crux.db/id]) 2 12.50M)))
(as-> d (update d :line-items add (seed/new-line-item (new-uuid 217)(get-in d [:items 3 :crux.db/id]) 2 12.50M)))
(as-> d (update d :line-items add (seed/new-line-item (new-uuid 218)(get-in d [:items 5 :crux.db/id]) 6 89.99M)))
(as-> d (update d :line-items add (seed/new-line-item (new-uuid 219)(get-in d [:items 6 :crux.db/id]) 10 20.0M)))
(as-> d (update d :invoices add (seed/new-invoice (new-uuid 207) date-1 (get-in d [:accounts 0 :crux.db/id])
[(get-in d [:line-items 0]) (get-in d [:line-items 1])])))
(as-> d (update d :invoices add (seed/new-invoice (new-uuid 208) date-2 (get-in d [:accounts 2 :crux.db/id])
[(get-in d [:line-items 2]) (get-in d [:line-items 3])])))
(as-> d (update d :invoices add (seed/new-invoice (new-uuid 209) date-3 (get-in d [:accounts 1 :crux.db/id])
[(get-in d [:line-items 4]) (get-in d [:line-items 5])])))
(as-> d (update d :invoices add (seed/new-invoice (new-uuid 210) date-4 (get-in d [:accounts 2 :crux.db/id])
[(get-in d [:line-items 6])])))
(as-> d (update d :invoices add (seed/new-invoice (new-uuid 211) date-5 (get-in d [:accounts 3 :crux.db/id])
[(get-in d [:line-items 7])]))))]
(crux/submit-tx node (->> data
vals
flatten
(mapv (fn [d] [:crux.tx/put d]))))))))
(defn start []
(mount/start-with-args {:config "config/dev.edn"})
(seed!)
:ok)
(defn stop
"Stop the server."
[]
(mount/stop))
(def go start)
(defn restart
"Stop, refresh, and restart the server."
[]
(stop)
(tools-ns/refresh :after 'development/start))
(def reset #'restart)
(comment
(start)
)
|
[
{
"context": "\n\n; Test-Data\n(def me {:surname \"Nachname\" :name \"Vorname\" :time 10})\n(def you {:surname \"Highly\" :name \"Sp",
"end": 711,
"score": 0.9638617038726807,
"start": 704,
"tag": "NAME",
"value": "Vorname"
}
] | src/seven_guis_cljs/task5crud.cljs | LuccaHellriegel/7guis-cljs | 1 | (ns seven-guis-cljs.task5crud
(:require [clojure.string :as string]
[reagent.core :as r]))
;; -------------------------
;; UTIL
;; -------------------------
(defn gen-key []
(gensym "key-"))
(defn event->target-value [e]
(-> e .-target .-value))
;; -------------------------
;; STATE
;; -------------------------
(def default-state {:crud-db []
:prefix ""
:selected-full-name nil
:name ""
:surname ""})
(def state (r/atom default-state))
(defn get-name-cursor []
(r/cursor state [:name]))
(defn get-surname-cursor []
(r/cursor state [:surname]))
; Test-Data
(def me {:surname "Nachname" :name "Vorname" :time 10})
(def you {:surname "Highly" :name "Specific" :time 10})
(reset! state (assoc @state :crud-db [me you] :selected-full-name me :name (:name me) :surname (:surname me)))
(defn get-cur-full-name [state]
{:name (:name state) :surname (:surname state) :time (js/Date.now)})
(defn add-cur-full-name-to-crud-db []
(swap! state (fn [st] (assoc st :crud-db
(conj (:crud-db st)
(get-cur-full-name st))))))
(defn replace-selected-full-name-in-crud-db []
(swap! state (fn [st] (assoc st :crud-db
(vec (replace {(:selected-full-name st) (get-cur-full-name st)} (:crud-db st)))
:selected-full-name nil))))
(defn remove-selected-full-name-from-crud-db []
(swap! state (fn [st] (assoc st :crud-db
(vec (remove #(= % (:selected-full-name st)) (:crud-db st)))))))
;; -------------------------
;; COMPONENTS
;; -------------------------
(defn prefix-field []
(let [prefix-cursor (r/cursor state [:prefix])]
(fn []
[:input {:class "input-field crud-filter-prefix-field" :type "text" :on-change #(reset! prefix-cursor (event->target-value %))}])))
(defn name-field []
(let [name-cursor (get-name-cursor)]
(fn []
[:input {:class "input-field"
:type "text"
:value @name-cursor
:on-change #(reset! name-cursor (event->target-value %))}])))
(defn surname-field []
(let [surname-cursor (get-surname-cursor)]
(fn []
[:input {:class "input-field"
:type "text"
:value @surname-cursor
:on-change #(reset! surname-cursor (event->target-value %))}])))
(defn fields []
[:div {:class "crud-fields"}
[:div {:class "crud-field mobile-flex-column-start"}
[:div {:class "crud-field-text"} "Name:"] [name-field]]
[:div {:class "crud-field mobile-flex-column-start"}
[:div {:class "crud-field-text"} "Surname:"] [surname-field]]])
(defn full-name-list-entry [full-name]
(let [selected-full-name-cursor (r/cursor state [:selected-full-name])]
(fn []
[:div {:on-click #(if (= @selected-full-name-cursor full-name)
(reset! selected-full-name-cursor nil)
(reset! selected-full-name-cursor full-name))
:class (if (= @selected-full-name-cursor full-name)
"list-entry list-entry-active"
"list-entry")}
(:surname full-name) ", " (:name full-name)])))
(defn surname-starts-with-prefix [full-name prefix]
(string/starts-with? (:surname full-name) prefix))
(defn full-name-list []
(let [selected-full-name-cursor (r/cursor state [:selected-full-name])
crud-db-cursor (r/cursor state [:crud-db])
prefix-cursor (r/cursor state [:prefix])]
(fn []
[:div
{:class "list-entries"}
(doall
(for [full-name
; assuming "filter" in the spec has the same interpretation as in Clojure
; (filter everything else out / select where pred = true)
(filter #(if
(surname-starts-with-prefix % @prefix-cursor)
true
; if the selected name is filtered out,
; it should be set nil to make sure the correct buttons are enabled
; at this scale this could also be solved by iterating over the names twice
; but a future improvement / more robust solution would be to make an extra function that returns
; the filtered names and the one that was filtered out
(do
(when (= @selected-full-name-cursor %)
(reset! selected-full-name-cursor nil))
false)) @crud-db-cursor)]
^{:key (gen-key)} [full-name-list-entry full-name]))])))
(defn create-button []
[:button {:class "crud-button"
:on-click add-cur-full-name-to-crud-db} "Create"])
; cant find anything about "" / empty updates in the spec, so we will allow it
(defn update-button []
(let [selected-full-name-cursor (r/cursor state [:selected-full-name])]
(fn []
[:button {:class "crud-button"
:on-click replace-selected-full-name-in-crud-db
:disabled (not @selected-full-name-cursor)} "Update"])))
(defn delete-button []
(let [selected-full-name-cursor (r/cursor state [:selected-full-name])]
(fn []
[:button {:class "crud-button"
:on-click #(do
(remove-selected-full-name-from-crud-db)
(reset! selected-full-name-cursor nil))
:disabled (not @selected-full-name-cursor)} "Delete"])))
(defn buttons []
[:div {:class "crud-button-container"}
[create-button]
[update-button]
[delete-button]])
(defn crud-gui []
[:div
{:class "flex-column-start"}
[:div {:class "crud-filter-prefix"}
[:div {:class "crud-filter-prefix-text"} "Filter prefix:"] [prefix-field]]
[:div {:class "crud-main-row"}
[full-name-list] [fields]]
[buttons]])
| 81316 | (ns seven-guis-cljs.task5crud
(:require [clojure.string :as string]
[reagent.core :as r]))
;; -------------------------
;; UTIL
;; -------------------------
(defn gen-key []
(gensym "key-"))
(defn event->target-value [e]
(-> e .-target .-value))
;; -------------------------
;; STATE
;; -------------------------
(def default-state {:crud-db []
:prefix ""
:selected-full-name nil
:name ""
:surname ""})
(def state (r/atom default-state))
(defn get-name-cursor []
(r/cursor state [:name]))
(defn get-surname-cursor []
(r/cursor state [:surname]))
; Test-Data
(def me {:surname "Nachname" :name "<NAME>" :time 10})
(def you {:surname "Highly" :name "Specific" :time 10})
(reset! state (assoc @state :crud-db [me you] :selected-full-name me :name (:name me) :surname (:surname me)))
(defn get-cur-full-name [state]
{:name (:name state) :surname (:surname state) :time (js/Date.now)})
(defn add-cur-full-name-to-crud-db []
(swap! state (fn [st] (assoc st :crud-db
(conj (:crud-db st)
(get-cur-full-name st))))))
(defn replace-selected-full-name-in-crud-db []
(swap! state (fn [st] (assoc st :crud-db
(vec (replace {(:selected-full-name st) (get-cur-full-name st)} (:crud-db st)))
:selected-full-name nil))))
(defn remove-selected-full-name-from-crud-db []
(swap! state (fn [st] (assoc st :crud-db
(vec (remove #(= % (:selected-full-name st)) (:crud-db st)))))))
;; -------------------------
;; COMPONENTS
;; -------------------------
(defn prefix-field []
(let [prefix-cursor (r/cursor state [:prefix])]
(fn []
[:input {:class "input-field crud-filter-prefix-field" :type "text" :on-change #(reset! prefix-cursor (event->target-value %))}])))
(defn name-field []
(let [name-cursor (get-name-cursor)]
(fn []
[:input {:class "input-field"
:type "text"
:value @name-cursor
:on-change #(reset! name-cursor (event->target-value %))}])))
(defn surname-field []
(let [surname-cursor (get-surname-cursor)]
(fn []
[:input {:class "input-field"
:type "text"
:value @surname-cursor
:on-change #(reset! surname-cursor (event->target-value %))}])))
(defn fields []
[:div {:class "crud-fields"}
[:div {:class "crud-field mobile-flex-column-start"}
[:div {:class "crud-field-text"} "Name:"] [name-field]]
[:div {:class "crud-field mobile-flex-column-start"}
[:div {:class "crud-field-text"} "Surname:"] [surname-field]]])
(defn full-name-list-entry [full-name]
(let [selected-full-name-cursor (r/cursor state [:selected-full-name])]
(fn []
[:div {:on-click #(if (= @selected-full-name-cursor full-name)
(reset! selected-full-name-cursor nil)
(reset! selected-full-name-cursor full-name))
:class (if (= @selected-full-name-cursor full-name)
"list-entry list-entry-active"
"list-entry")}
(:surname full-name) ", " (:name full-name)])))
(defn surname-starts-with-prefix [full-name prefix]
(string/starts-with? (:surname full-name) prefix))
(defn full-name-list []
(let [selected-full-name-cursor (r/cursor state [:selected-full-name])
crud-db-cursor (r/cursor state [:crud-db])
prefix-cursor (r/cursor state [:prefix])]
(fn []
[:div
{:class "list-entries"}
(doall
(for [full-name
; assuming "filter" in the spec has the same interpretation as in Clojure
; (filter everything else out / select where pred = true)
(filter #(if
(surname-starts-with-prefix % @prefix-cursor)
true
; if the selected name is filtered out,
; it should be set nil to make sure the correct buttons are enabled
; at this scale this could also be solved by iterating over the names twice
; but a future improvement / more robust solution would be to make an extra function that returns
; the filtered names and the one that was filtered out
(do
(when (= @selected-full-name-cursor %)
(reset! selected-full-name-cursor nil))
false)) @crud-db-cursor)]
^{:key (gen-key)} [full-name-list-entry full-name]))])))
(defn create-button []
[:button {:class "crud-button"
:on-click add-cur-full-name-to-crud-db} "Create"])
; cant find anything about "" / empty updates in the spec, so we will allow it
(defn update-button []
(let [selected-full-name-cursor (r/cursor state [:selected-full-name])]
(fn []
[:button {:class "crud-button"
:on-click replace-selected-full-name-in-crud-db
:disabled (not @selected-full-name-cursor)} "Update"])))
(defn delete-button []
(let [selected-full-name-cursor (r/cursor state [:selected-full-name])]
(fn []
[:button {:class "crud-button"
:on-click #(do
(remove-selected-full-name-from-crud-db)
(reset! selected-full-name-cursor nil))
:disabled (not @selected-full-name-cursor)} "Delete"])))
(defn buttons []
[:div {:class "crud-button-container"}
[create-button]
[update-button]
[delete-button]])
(defn crud-gui []
[:div
{:class "flex-column-start"}
[:div {:class "crud-filter-prefix"}
[:div {:class "crud-filter-prefix-text"} "Filter prefix:"] [prefix-field]]
[:div {:class "crud-main-row"}
[full-name-list] [fields]]
[buttons]])
| true | (ns seven-guis-cljs.task5crud
(:require [clojure.string :as string]
[reagent.core :as r]))
;; -------------------------
;; UTIL
;; -------------------------
(defn gen-key []
(gensym "key-"))
(defn event->target-value [e]
(-> e .-target .-value))
;; -------------------------
;; STATE
;; -------------------------
(def default-state {:crud-db []
:prefix ""
:selected-full-name nil
:name ""
:surname ""})
(def state (r/atom default-state))
(defn get-name-cursor []
(r/cursor state [:name]))
(defn get-surname-cursor []
(r/cursor state [:surname]))
; Test-Data
(def me {:surname "Nachname" :name "PI:NAME:<NAME>END_PI" :time 10})
(def you {:surname "Highly" :name "Specific" :time 10})
(reset! state (assoc @state :crud-db [me you] :selected-full-name me :name (:name me) :surname (:surname me)))
(defn get-cur-full-name [state]
{:name (:name state) :surname (:surname state) :time (js/Date.now)})
(defn add-cur-full-name-to-crud-db []
(swap! state (fn [st] (assoc st :crud-db
(conj (:crud-db st)
(get-cur-full-name st))))))
(defn replace-selected-full-name-in-crud-db []
(swap! state (fn [st] (assoc st :crud-db
(vec (replace {(:selected-full-name st) (get-cur-full-name st)} (:crud-db st)))
:selected-full-name nil))))
(defn remove-selected-full-name-from-crud-db []
(swap! state (fn [st] (assoc st :crud-db
(vec (remove #(= % (:selected-full-name st)) (:crud-db st)))))))
;; -------------------------
;; COMPONENTS
;; -------------------------
(defn prefix-field []
(let [prefix-cursor (r/cursor state [:prefix])]
(fn []
[:input {:class "input-field crud-filter-prefix-field" :type "text" :on-change #(reset! prefix-cursor (event->target-value %))}])))
(defn name-field []
(let [name-cursor (get-name-cursor)]
(fn []
[:input {:class "input-field"
:type "text"
:value @name-cursor
:on-change #(reset! name-cursor (event->target-value %))}])))
(defn surname-field []
(let [surname-cursor (get-surname-cursor)]
(fn []
[:input {:class "input-field"
:type "text"
:value @surname-cursor
:on-change #(reset! surname-cursor (event->target-value %))}])))
(defn fields []
[:div {:class "crud-fields"}
[:div {:class "crud-field mobile-flex-column-start"}
[:div {:class "crud-field-text"} "Name:"] [name-field]]
[:div {:class "crud-field mobile-flex-column-start"}
[:div {:class "crud-field-text"} "Surname:"] [surname-field]]])
(defn full-name-list-entry [full-name]
(let [selected-full-name-cursor (r/cursor state [:selected-full-name])]
(fn []
[:div {:on-click #(if (= @selected-full-name-cursor full-name)
(reset! selected-full-name-cursor nil)
(reset! selected-full-name-cursor full-name))
:class (if (= @selected-full-name-cursor full-name)
"list-entry list-entry-active"
"list-entry")}
(:surname full-name) ", " (:name full-name)])))
(defn surname-starts-with-prefix [full-name prefix]
(string/starts-with? (:surname full-name) prefix))
(defn full-name-list []
(let [selected-full-name-cursor (r/cursor state [:selected-full-name])
crud-db-cursor (r/cursor state [:crud-db])
prefix-cursor (r/cursor state [:prefix])]
(fn []
[:div
{:class "list-entries"}
(doall
(for [full-name
; assuming "filter" in the spec has the same interpretation as in Clojure
; (filter everything else out / select where pred = true)
(filter #(if
(surname-starts-with-prefix % @prefix-cursor)
true
; if the selected name is filtered out,
; it should be set nil to make sure the correct buttons are enabled
; at this scale this could also be solved by iterating over the names twice
; but a future improvement / more robust solution would be to make an extra function that returns
; the filtered names and the one that was filtered out
(do
(when (= @selected-full-name-cursor %)
(reset! selected-full-name-cursor nil))
false)) @crud-db-cursor)]
^{:key (gen-key)} [full-name-list-entry full-name]))])))
(defn create-button []
[:button {:class "crud-button"
:on-click add-cur-full-name-to-crud-db} "Create"])
; cant find anything about "" / empty updates in the spec, so we will allow it
(defn update-button []
(let [selected-full-name-cursor (r/cursor state [:selected-full-name])]
(fn []
[:button {:class "crud-button"
:on-click replace-selected-full-name-in-crud-db
:disabled (not @selected-full-name-cursor)} "Update"])))
(defn delete-button []
(let [selected-full-name-cursor (r/cursor state [:selected-full-name])]
(fn []
[:button {:class "crud-button"
:on-click #(do
(remove-selected-full-name-from-crud-db)
(reset! selected-full-name-cursor nil))
:disabled (not @selected-full-name-cursor)} "Delete"])))
(defn buttons []
[:div {:class "crud-button-container"}
[create-button]
[update-button]
[delete-button]])
(defn crud-gui []
[:div
{:class "flex-column-start"}
[:div {:class "crud-filter-prefix"}
[:div {:class "crud-filter-prefix-text"} "Filter prefix:"] [prefix-field]]
[:div {:class "crud-main-row"}
[full-name-list] [fields]]
[buttons]])
|
[
{
"context": "lines)))\n\n(take 10 freqs)\n\n(filter #(= (first %) \"Andrew\") freqs)\n\n(take 10 (reverse (sort-by second freqs",
"end": 1144,
"score": 0.9993219375610352,
"start": 1138,
"tag": "NAME",
"value": "Andrew"
}
] | src/clj/tutorials/data_processing/reducers.clj | jocrau/clojure-meetup | 7 | ;; Basics
(range 10)
(map inc (range 10))
(take 10 (filter even? (map inc (range))))
(reduce + (filter even? (map inc (range 10))))
(->> (range 10)
(map inc)
(filter even?)
(reduce +))
;; Reducers
(require '[clojure.core.reducers :as r])
(r/reduce + (r/filter even? (r/map inc (range 10))))
(r/filter even? (r/map inc (range 10)))
(into [] (r/filter even? (r/map inc (range 10))))
;; Word Count
(def book (slurp "http://www.gutenberg.org/files/2600/2600-0.txt"))
(def lines (drop 844 (clojure.string/split-lines book)))
(take 10 lines)
(defn combine-fn
([] {})
([a b]
(merge-with + a b)))
(defn reduce-fn [acc [word cnt]]
(assoc acc word (+ cnt (get acc word 0))))
(defn word-count [lines]
(->> lines
(mapcat #(re-seq #"\w+" %))
(map #(vector % 1))
(reduce reduce-fn {})
(into [])))
(def freqs (time (word-count lines)))
(defn word-count [lines]
(->> lines
(r/mapcat #(re-seq #"\w+" %))
(r/map #(vector % 1))
(r/fold combine-fn reduce-fn)
(into [])))
(def freqs (time (word-count lines)))
(take 10 freqs)
(filter #(= (first %) "Andrew") freqs)
(take 10 (reverse (sort-by second freqs)))
;; Transducers
(map inc)
(into [] (range 10))
(into [] (map inc) (range 10))
(def my-transformation
(comp (map inc)
(filter even?)))
(into [] my-transformation (range 10))
| 78515 | ;; Basics
(range 10)
(map inc (range 10))
(take 10 (filter even? (map inc (range))))
(reduce + (filter even? (map inc (range 10))))
(->> (range 10)
(map inc)
(filter even?)
(reduce +))
;; Reducers
(require '[clojure.core.reducers :as r])
(r/reduce + (r/filter even? (r/map inc (range 10))))
(r/filter even? (r/map inc (range 10)))
(into [] (r/filter even? (r/map inc (range 10))))
;; Word Count
(def book (slurp "http://www.gutenberg.org/files/2600/2600-0.txt"))
(def lines (drop 844 (clojure.string/split-lines book)))
(take 10 lines)
(defn combine-fn
([] {})
([a b]
(merge-with + a b)))
(defn reduce-fn [acc [word cnt]]
(assoc acc word (+ cnt (get acc word 0))))
(defn word-count [lines]
(->> lines
(mapcat #(re-seq #"\w+" %))
(map #(vector % 1))
(reduce reduce-fn {})
(into [])))
(def freqs (time (word-count lines)))
(defn word-count [lines]
(->> lines
(r/mapcat #(re-seq #"\w+" %))
(r/map #(vector % 1))
(r/fold combine-fn reduce-fn)
(into [])))
(def freqs (time (word-count lines)))
(take 10 freqs)
(filter #(= (first %) "<NAME>") freqs)
(take 10 (reverse (sort-by second freqs)))
;; Transducers
(map inc)
(into [] (range 10))
(into [] (map inc) (range 10))
(def my-transformation
(comp (map inc)
(filter even?)))
(into [] my-transformation (range 10))
| true | ;; Basics
(range 10)
(map inc (range 10))
(take 10 (filter even? (map inc (range))))
(reduce + (filter even? (map inc (range 10))))
(->> (range 10)
(map inc)
(filter even?)
(reduce +))
;; Reducers
(require '[clojure.core.reducers :as r])
(r/reduce + (r/filter even? (r/map inc (range 10))))
(r/filter even? (r/map inc (range 10)))
(into [] (r/filter even? (r/map inc (range 10))))
;; Word Count
(def book (slurp "http://www.gutenberg.org/files/2600/2600-0.txt"))
(def lines (drop 844 (clojure.string/split-lines book)))
(take 10 lines)
(defn combine-fn
([] {})
([a b]
(merge-with + a b)))
(defn reduce-fn [acc [word cnt]]
(assoc acc word (+ cnt (get acc word 0))))
(defn word-count [lines]
(->> lines
(mapcat #(re-seq #"\w+" %))
(map #(vector % 1))
(reduce reduce-fn {})
(into [])))
(def freqs (time (word-count lines)))
(defn word-count [lines]
(->> lines
(r/mapcat #(re-seq #"\w+" %))
(r/map #(vector % 1))
(r/fold combine-fn reduce-fn)
(into [])))
(def freqs (time (word-count lines)))
(take 10 freqs)
(filter #(= (first %) "PI:NAME:<NAME>END_PI") freqs)
(take 10 (reverse (sort-by second freqs)))
;; Transducers
(map inc)
(into [] (range 10))
(into [] (map inc) (range 10))
(def my-transformation
(comp (map inc)
(filter even?)))
(into [] my-transformation (range 10))
|
[
{
"context": ")))\n\n(defn repository-public-key\n [{:keys [github-repository github-api-url github-actor walter-gith",
"end": 388,
"score": 0.7227646112442017,
"start": 388,
"tag": "KEY",
"value": ""
},
{
"context": " :key_id key-id})\n\n(defn upsert-value\n [{:keys [github-repository github-api-url github-actor walter-gith",
"end": 1577,
"score": 0.6957151293754578,
"start": 1570,
"tag": "KEY",
"value": "github-"
}
] | src/piotr_yuxuan/walter_ci/secrets.clj | piotr-yuxuan/walter-ci | 2 | (ns piotr-yuxuan.walter-ci.secrets
(:require [byte-streams :as byte-streams]
[caesium.crypto.box :as crypto]
[clj-http.client :as http]
[clojure.string :as str]
[jsonista.core :as json]
[leiningen.change]
[safely.core :refer [safely]])
(:import (java.util Base64)))
(defn repository-public-key
[{:keys [github-repository github-api-url github-actor walter-github-password]}]
(let [response (safely
(http/request
{:request-method :get
:url (str/join "/" [github-api-url "repos" github-repository "actions/secrets/public-key"])
:basic-auth [github-actor walter-github-password]
:headers {"Content-Type" "application/json"
"Accept" "application/vnd.github.v3+json"}})
:on-error
:max-retries 5)
payload (->> response
:body
json/read-value)
^String encoded-key (get payload "key")]
{:encoded-key encoded-key
:decoded-key (.decode (Base64/getDecoder) (.getBytes encoded-key))
:key-id (get payload "key_id")}))
(defn public-key-sealed-box
[{:keys [^String decoded-key key-id]} ^String secret-value]
{:encrypted_value (->> (byte-streams/to-byte-array secret-value)
(crypto/anonymous-encrypt decoded-key)
(.encodeToString (Base64/getEncoder)))
:key_id key-id})
(defn upsert-value
[{:keys [github-repository github-api-url github-actor walter-github-password] :as config} ^String secret-name ^String secret-value]
(let [public-key (repository-public-key config)
sealed-box (public-key-sealed-box public-key secret-value)]
(safely
(http/request
{:request-method :put
:url (str/join "/" [github-api-url "repos" github-repository "actions" "secrets" secret-name])
:body (json/write-value-as-string sealed-box)
:basic-auth [github-actor walter-github-password]
:headers {"Content-Type" "application/json"
"Accept" "application/vnd.github.v3+json"}})
:on-error
:max-retries 5)))
| 37863 | (ns piotr-yuxuan.walter-ci.secrets
(:require [byte-streams :as byte-streams]
[caesium.crypto.box :as crypto]
[clj-http.client :as http]
[clojure.string :as str]
[jsonista.core :as json]
[leiningen.change]
[safely.core :refer [safely]])
(:import (java.util Base64)))
(defn repository-public-key
[{:keys [github<KEY>-repository github-api-url github-actor walter-github-password]}]
(let [response (safely
(http/request
{:request-method :get
:url (str/join "/" [github-api-url "repos" github-repository "actions/secrets/public-key"])
:basic-auth [github-actor walter-github-password]
:headers {"Content-Type" "application/json"
"Accept" "application/vnd.github.v3+json"}})
:on-error
:max-retries 5)
payload (->> response
:body
json/read-value)
^String encoded-key (get payload "key")]
{:encoded-key encoded-key
:decoded-key (.decode (Base64/getDecoder) (.getBytes encoded-key))
:key-id (get payload "key_id")}))
(defn public-key-sealed-box
[{:keys [^String decoded-key key-id]} ^String secret-value]
{:encrypted_value (->> (byte-streams/to-byte-array secret-value)
(crypto/anonymous-encrypt decoded-key)
(.encodeToString (Base64/getEncoder)))
:key_id key-id})
(defn upsert-value
[{:keys [<KEY>repository github-api-url github-actor walter-github-password] :as config} ^String secret-name ^String secret-value]
(let [public-key (repository-public-key config)
sealed-box (public-key-sealed-box public-key secret-value)]
(safely
(http/request
{:request-method :put
:url (str/join "/" [github-api-url "repos" github-repository "actions" "secrets" secret-name])
:body (json/write-value-as-string sealed-box)
:basic-auth [github-actor walter-github-password]
:headers {"Content-Type" "application/json"
"Accept" "application/vnd.github.v3+json"}})
:on-error
:max-retries 5)))
| true | (ns piotr-yuxuan.walter-ci.secrets
(:require [byte-streams :as byte-streams]
[caesium.crypto.box :as crypto]
[clj-http.client :as http]
[clojure.string :as str]
[jsonista.core :as json]
[leiningen.change]
[safely.core :refer [safely]])
(:import (java.util Base64)))
(defn repository-public-key
[{:keys [githubPI:KEY:<KEY>END_PI-repository github-api-url github-actor walter-github-password]}]
(let [response (safely
(http/request
{:request-method :get
:url (str/join "/" [github-api-url "repos" github-repository "actions/secrets/public-key"])
:basic-auth [github-actor walter-github-password]
:headers {"Content-Type" "application/json"
"Accept" "application/vnd.github.v3+json"}})
:on-error
:max-retries 5)
payload (->> response
:body
json/read-value)
^String encoded-key (get payload "key")]
{:encoded-key encoded-key
:decoded-key (.decode (Base64/getDecoder) (.getBytes encoded-key))
:key-id (get payload "key_id")}))
(defn public-key-sealed-box
[{:keys [^String decoded-key key-id]} ^String secret-value]
{:encrypted_value (->> (byte-streams/to-byte-array secret-value)
(crypto/anonymous-encrypt decoded-key)
(.encodeToString (Base64/getEncoder)))
:key_id key-id})
(defn upsert-value
[{:keys [PI:KEY:<KEY>END_PIrepository github-api-url github-actor walter-github-password] :as config} ^String secret-name ^String secret-value]
(let [public-key (repository-public-key config)
sealed-box (public-key-sealed-box public-key secret-value)]
(safely
(http/request
{:request-method :put
:url (str/join "/" [github-api-url "repos" github-repository "actions" "secrets" secret-name])
:body (json/write-value-as-string sealed-box)
:basic-auth [github-actor walter-github-password]
:headers {"Content-Type" "application/json"
"Accept" "application/vnd.github.v3+json"}})
:on-error
:max-retries 5)))
|
[
{
"context": "\"2751ab3d678ff0277ae80f9e8a74f218cfc70fe9a9cdc7bb1c137d7e47e33d53\")\n (run anaconda)\n (run set-password)))",
"end": 1739,
"score": 0.9967526197433472,
"start": 1724,
"tag": "PASSWORD",
"value": "c137d7e47e33d53"
}
] | src/re_cipes/apps/jupyter.clj | re-ops/re-cipes | 7 | (ns re-cipes.apps.jupyter
"Setting up Jupyter notebook"
(:require
[re-cipes.hardening]
[re-cog.resources.download :refer (download)]
[re-cipes.docker.nginx]
[re-cog.resources.exec :refer (run)]
[re-cog.resources.systemd :refer (set-service)]
[re-cog.resources.nginx :refer (site-enabled)]
[re-cog.resources.ufw :refer (add-rule)]
[re-cog.common.recipe :refer (require-recipe)]
[re-cog.facts.config :refer (configuration)]
[re-cog.resources.file :refer (symlink directory)]))
(require-recipe)
(def-inline anaconda
"Setting up Anaconda"
[]
(let [{:keys [home user]} (configuration)
password (configuration :jupyter :password)
binary "Anaconda3-2021.05-Linux-x86_64.sh"
url (<< "https://repo.anaconda.com/archive/~{binary}")
target (<< "/usr/src/~{binary}")
anaconda-home (<< "~{home}/anaconda")
jupyter-bin (<< "~{anaconda-home}/bin/jupyter")
jupyter-config (<< "~{home}/.jupyter/jupyter_notebook_config.py")
python3 (<< "~{anaconda-home}/bin/python3")
passwd (<< "\"from notebook.auth import passwd; print(passwd('~{password}'))\"")]
(letfn [(anaconda []
(script
(if (file-exists? ~anaconda-home)
("exit" 0))
("/usr/bin/bash" ~target "-b" "-p" ~anaconda-home)))
(set-password []
(script
(set! PASS @(~python3 "-c" ~passwd))
(~jupyter-bin "notebook" "--generate-config" "-y")
("echo" (quoted "c.NotebookApp.password='${PASS}'") >> ~jupyter-config)))]
(download url target "2751ab3d678ff0277ae80f9e8a74f218cfc70fe9a9cdc7bb1c137d7e47e33d53")
(run anaconda)
(run set-password))))
(def-inline {:depends [#'re-cipes.docker.nginx/get-source #'re-cipes.hardening/firewall]} nginx
"Nginx site enable"
[]
(let [external-port 443
{:keys [nginx]} (configuration)]
(site-enabled nginx "jupyter" external-port 8888 {:basic-auth false :websockets true})
(add-rule external-port :allow {})))
| 5085 | (ns re-cipes.apps.jupyter
"Setting up Jupyter notebook"
(:require
[re-cipes.hardening]
[re-cog.resources.download :refer (download)]
[re-cipes.docker.nginx]
[re-cog.resources.exec :refer (run)]
[re-cog.resources.systemd :refer (set-service)]
[re-cog.resources.nginx :refer (site-enabled)]
[re-cog.resources.ufw :refer (add-rule)]
[re-cog.common.recipe :refer (require-recipe)]
[re-cog.facts.config :refer (configuration)]
[re-cog.resources.file :refer (symlink directory)]))
(require-recipe)
(def-inline anaconda
"Setting up Anaconda"
[]
(let [{:keys [home user]} (configuration)
password (configuration :jupyter :password)
binary "Anaconda3-2021.05-Linux-x86_64.sh"
url (<< "https://repo.anaconda.com/archive/~{binary}")
target (<< "/usr/src/~{binary}")
anaconda-home (<< "~{home}/anaconda")
jupyter-bin (<< "~{anaconda-home}/bin/jupyter")
jupyter-config (<< "~{home}/.jupyter/jupyter_notebook_config.py")
python3 (<< "~{anaconda-home}/bin/python3")
passwd (<< "\"from notebook.auth import passwd; print(passwd('~{password}'))\"")]
(letfn [(anaconda []
(script
(if (file-exists? ~anaconda-home)
("exit" 0))
("/usr/bin/bash" ~target "-b" "-p" ~anaconda-home)))
(set-password []
(script
(set! PASS @(~python3 "-c" ~passwd))
(~jupyter-bin "notebook" "--generate-config" "-y")
("echo" (quoted "c.NotebookApp.password='${PASS}'") >> ~jupyter-config)))]
(download url target "2751ab3d678ff0277ae80f9e8a74f218cfc70fe9a9cdc7bb1<PASSWORD>")
(run anaconda)
(run set-password))))
(def-inline {:depends [#'re-cipes.docker.nginx/get-source #'re-cipes.hardening/firewall]} nginx
"Nginx site enable"
[]
(let [external-port 443
{:keys [nginx]} (configuration)]
(site-enabled nginx "jupyter" external-port 8888 {:basic-auth false :websockets true})
(add-rule external-port :allow {})))
| true | (ns re-cipes.apps.jupyter
"Setting up Jupyter notebook"
(:require
[re-cipes.hardening]
[re-cog.resources.download :refer (download)]
[re-cipes.docker.nginx]
[re-cog.resources.exec :refer (run)]
[re-cog.resources.systemd :refer (set-service)]
[re-cog.resources.nginx :refer (site-enabled)]
[re-cog.resources.ufw :refer (add-rule)]
[re-cog.common.recipe :refer (require-recipe)]
[re-cog.facts.config :refer (configuration)]
[re-cog.resources.file :refer (symlink directory)]))
(require-recipe)
(def-inline anaconda
"Setting up Anaconda"
[]
(let [{:keys [home user]} (configuration)
password (configuration :jupyter :password)
binary "Anaconda3-2021.05-Linux-x86_64.sh"
url (<< "https://repo.anaconda.com/archive/~{binary}")
target (<< "/usr/src/~{binary}")
anaconda-home (<< "~{home}/anaconda")
jupyter-bin (<< "~{anaconda-home}/bin/jupyter")
jupyter-config (<< "~{home}/.jupyter/jupyter_notebook_config.py")
python3 (<< "~{anaconda-home}/bin/python3")
passwd (<< "\"from notebook.auth import passwd; print(passwd('~{password}'))\"")]
(letfn [(anaconda []
(script
(if (file-exists? ~anaconda-home)
("exit" 0))
("/usr/bin/bash" ~target "-b" "-p" ~anaconda-home)))
(set-password []
(script
(set! PASS @(~python3 "-c" ~passwd))
(~jupyter-bin "notebook" "--generate-config" "-y")
("echo" (quoted "c.NotebookApp.password='${PASS}'") >> ~jupyter-config)))]
(download url target "2751ab3d678ff0277ae80f9e8a74f218cfc70fe9a9cdc7bb1PI:PASSWORD:<PASSWORD>END_PI")
(run anaconda)
(run set-password))))
(def-inline {:depends [#'re-cipes.docker.nginx/get-source #'re-cipes.hardening/firewall]} nginx
"Nginx site enable"
[]
(let [external-port 443
{:keys [nginx]} (configuration)]
(site-enabled nginx "jupyter" external-port 8888 {:basic-auth false :websockets true})
(add-rule external-port :allow {})))
|
[
{
"context": "(comment \n re-core, Copyright 2012 Ronen Narkis, narkisr.com\n Licensed under the Apache License,",
"end": 48,
"score": 0.9998857378959656,
"start": 36,
"tag": "NAME",
"value": "Ronen Narkis"
}
] | src/kvm/validations.clj | celestial-ops/core | 1 | (comment
re-core, Copyright 2012 Ronen Narkis, narkisr.com
Licensed under the Apache License,
Version 2.0 (the "License") you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.)
(ns kvm.validations
"KVM validations"
(:require
[re-core.model :refer (check-validity)]
[clojure.core.strint :refer (<<)]
[subs.core :as subs :refer (validate! combine every-v every-kv validation when-not-nil)])
)
(def machine-entity
{:machine {
:hostname #{:required :String} :domain #{:required :String}
:user #{:required :String} :os #{:required :Keyword}
:cpu #{:required :number} :ram #{:required :number}
}})
(def kvm-entity
{:kvm {
:node #{:required :Keyword}
}
})
(def domain-provider
{:name #{:required :String} :user #{:required :String}
:image {:template #{:required :String} :flavor #{:required :Keyword}}
:cpu #{:required :number} :ram #{:required :number}
})
(def node-provider
{:user #{:required :String} :host #{:required :String}
:port #{:required :number}
})
(defmethod check-validity [:kvm :entity] [domain]
(validate! domain (combine machine-entity kvm-entity) :error ::invalid-system))
(defn provider-validation [domain node*]
(validate! domain domain-provider :error ::invalid-domain)
(validate! node* node-provider :error ::invalid-node))
| 44731 | (comment
re-core, Copyright 2012 <NAME>, narkisr.com
Licensed under the Apache License,
Version 2.0 (the "License") you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.)
(ns kvm.validations
"KVM validations"
(:require
[re-core.model :refer (check-validity)]
[clojure.core.strint :refer (<<)]
[subs.core :as subs :refer (validate! combine every-v every-kv validation when-not-nil)])
)
(def machine-entity
{:machine {
:hostname #{:required :String} :domain #{:required :String}
:user #{:required :String} :os #{:required :Keyword}
:cpu #{:required :number} :ram #{:required :number}
}})
(def kvm-entity
{:kvm {
:node #{:required :Keyword}
}
})
(def domain-provider
{:name #{:required :String} :user #{:required :String}
:image {:template #{:required :String} :flavor #{:required :Keyword}}
:cpu #{:required :number} :ram #{:required :number}
})
(def node-provider
{:user #{:required :String} :host #{:required :String}
:port #{:required :number}
})
(defmethod check-validity [:kvm :entity] [domain]
(validate! domain (combine machine-entity kvm-entity) :error ::invalid-system))
(defn provider-validation [domain node*]
(validate! domain domain-provider :error ::invalid-domain)
(validate! node* node-provider :error ::invalid-node))
| true | (comment
re-core, Copyright 2012 PI:NAME:<NAME>END_PI, narkisr.com
Licensed under the Apache License,
Version 2.0 (the "License") you may not use this file except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.)
(ns kvm.validations
"KVM validations"
(:require
[re-core.model :refer (check-validity)]
[clojure.core.strint :refer (<<)]
[subs.core :as subs :refer (validate! combine every-v every-kv validation when-not-nil)])
)
(def machine-entity
{:machine {
:hostname #{:required :String} :domain #{:required :String}
:user #{:required :String} :os #{:required :Keyword}
:cpu #{:required :number} :ram #{:required :number}
}})
(def kvm-entity
{:kvm {
:node #{:required :Keyword}
}
})
(def domain-provider
{:name #{:required :String} :user #{:required :String}
:image {:template #{:required :String} :flavor #{:required :Keyword}}
:cpu #{:required :number} :ram #{:required :number}
})
(def node-provider
{:user #{:required :String} :host #{:required :String}
:port #{:required :number}
})
(defmethod check-validity [:kvm :entity] [domain]
(validate! domain (combine machine-entity kvm-entity) :error ::invalid-system))
(defn provider-validation [domain node*]
(validate! domain domain-provider :error ::invalid-domain)
(validate! node* node-provider :error ::invalid-node))
|
[
{
"context": "identifiers for Say-Sila\n;;;;\n;;;; @copyright 2020 Dennis Drown et l'Université du Québec à Montréal\n;;;; -------",
"end": 391,
"score": 0.9998796582221985,
"start": 379,
"tag": "NAME",
"value": "Dennis Drown"
}
] | apps/say_sila/priv/fnode/say/src/say/label.clj | dendrown/say_sila | 0 | ;;;; -------------------------------------------------------------------------
;;;;
;;;; _/_/_/ _/_/_/ _/ _/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/ _/ _/ _/_/_/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/
;;;;
;;;; Labels and identifiers for Say-Sila
;;;;
;;;; @copyright 2020 Dennis Drown et l'Université du Québec à Montréal
;;;; -------------------------------------------------------------------------
(ns say.label
(:require [say.genie :refer :all]
[say.log :as log]
[say.cmu-pos :as pos]
[weka.dataset :as dset]
[clojure.string :as str])
(:import (weka.core Instance)))
;;; --------------------------------------------------------------------------
(set! *warn-on-reflection* true)
(def ^:const Tweet-Tag "t") ; Tweet individual have this tag plus the ID ( "t42" )
(def ^:const Profile-Tag "ProfileOf_") ; User profiles look like "ProfileOf_ArthurDent
(defonce Columns (dset/columns :s)) ; Weka format for Say-Sila status/sentiment feed
;;; --------------------------------------------------------------------------
(defprotocol Polarizer
"Determines negative|positive polarity for various datatypes."
(polarize [x] "Return the sentiment polarity as :positive or :negative."))
(extend-protocol Polarizer
Number
(polarize [x]
;(log/debug "polarize:" x)
(if (Double/isNaN x)
:?
(if (<= x 0.0)
:negative
:positive)))
Instance
(polarize [inst]
(if (.classIsMissing inst)
:?
(polarize (.classValue inst))))
String
(polarize [pn]
(polarize (Integer/parseInt pn))))
;;; --------------------------------------------------------------------------
(defn label-polarity
"Returns the String «pos» or «neg» according to the polarity of x."
[x]
(label-polarity [x]
(case (polarize x)
:negative "neg"
:positive "pos")))
;;; --------------------------------------------------------------------------
(defprotocol Labeller
"Creates labels for say-senti purposes."
;; TODO: label-polarity [from above]
(label-text [x] "Returns a String identifier for a Text (tweet)."))
(extend-protocol Labeller
Instance
(label-text [inst]
(label-text (.value inst (int (Columns :id)))))
String
(label-text [s]
;; Allow multiple calls without retagging
(if (str/starts-with? s Tweet-Tag)
s
(str Tweet-Tag s)))
Object
(label-text [x]
(str Tweet-Tag (longify x))))
(defn label-text-token
"Returns a String identifier for a Text (tweet) and the token number.
Examples:
- for the tenth token on the 42nd tweet, the label will be: t42-10
- and for a MWE (multi-word expression) role on that token: t42-mwe10"
([txt tok]
(hyphenize (label-text txt) tok))
([txt tok role]
(hyphenize (label-text txt) (str (str/lower-case (name role)) tok))))
| 20114 | ;;;; -------------------------------------------------------------------------
;;;;
;;;; _/_/_/ _/_/_/ _/ _/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/ _/ _/ _/_/_/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/
;;;;
;;;; Labels and identifiers for Say-Sila
;;;;
;;;; @copyright 2020 <NAME> et l'Université du Québec à Montréal
;;;; -------------------------------------------------------------------------
(ns say.label
(:require [say.genie :refer :all]
[say.log :as log]
[say.cmu-pos :as pos]
[weka.dataset :as dset]
[clojure.string :as str])
(:import (weka.core Instance)))
;;; --------------------------------------------------------------------------
(set! *warn-on-reflection* true)
(def ^:const Tweet-Tag "t") ; Tweet individual have this tag plus the ID ( "t42" )
(def ^:const Profile-Tag "ProfileOf_") ; User profiles look like "ProfileOf_ArthurDent
(defonce Columns (dset/columns :s)) ; Weka format for Say-Sila status/sentiment feed
;;; --------------------------------------------------------------------------
(defprotocol Polarizer
"Determines negative|positive polarity for various datatypes."
(polarize [x] "Return the sentiment polarity as :positive or :negative."))
(extend-protocol Polarizer
Number
(polarize [x]
;(log/debug "polarize:" x)
(if (Double/isNaN x)
:?
(if (<= x 0.0)
:negative
:positive)))
Instance
(polarize [inst]
(if (.classIsMissing inst)
:?
(polarize (.classValue inst))))
String
(polarize [pn]
(polarize (Integer/parseInt pn))))
;;; --------------------------------------------------------------------------
(defn label-polarity
"Returns the String «pos» or «neg» according to the polarity of x."
[x]
(label-polarity [x]
(case (polarize x)
:negative "neg"
:positive "pos")))
;;; --------------------------------------------------------------------------
(defprotocol Labeller
"Creates labels for say-senti purposes."
;; TODO: label-polarity [from above]
(label-text [x] "Returns a String identifier for a Text (tweet)."))
(extend-protocol Labeller
Instance
(label-text [inst]
(label-text (.value inst (int (Columns :id)))))
String
(label-text [s]
;; Allow multiple calls without retagging
(if (str/starts-with? s Tweet-Tag)
s
(str Tweet-Tag s)))
Object
(label-text [x]
(str Tweet-Tag (longify x))))
(defn label-text-token
"Returns a String identifier for a Text (tweet) and the token number.
Examples:
- for the tenth token on the 42nd tweet, the label will be: t42-10
- and for a MWE (multi-word expression) role on that token: t42-mwe10"
([txt tok]
(hyphenize (label-text txt) tok))
([txt tok role]
(hyphenize (label-text txt) (str (str/lower-case (name role)) tok))))
| true | ;;;; -------------------------------------------------------------------------
;;;;
;;;; _/_/_/ _/_/_/ _/ _/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/ _/ _/ _/_/_/_/
;;;; _/ _/ _/ _/ _/
;;;; _/_/_/ _/_/_/ _/_/_/_/ _/ _/
;;;;
;;;; Labels and identifiers for Say-Sila
;;;;
;;;; @copyright 2020 PI:NAME:<NAME>END_PI et l'Université du Québec à Montréal
;;;; -------------------------------------------------------------------------
(ns say.label
(:require [say.genie :refer :all]
[say.log :as log]
[say.cmu-pos :as pos]
[weka.dataset :as dset]
[clojure.string :as str])
(:import (weka.core Instance)))
;;; --------------------------------------------------------------------------
(set! *warn-on-reflection* true)
(def ^:const Tweet-Tag "t") ; Tweet individual have this tag plus the ID ( "t42" )
(def ^:const Profile-Tag "ProfileOf_") ; User profiles look like "ProfileOf_ArthurDent
(defonce Columns (dset/columns :s)) ; Weka format for Say-Sila status/sentiment feed
;;; --------------------------------------------------------------------------
(defprotocol Polarizer
"Determines negative|positive polarity for various datatypes."
(polarize [x] "Return the sentiment polarity as :positive or :negative."))
(extend-protocol Polarizer
Number
(polarize [x]
;(log/debug "polarize:" x)
(if (Double/isNaN x)
:?
(if (<= x 0.0)
:negative
:positive)))
Instance
(polarize [inst]
(if (.classIsMissing inst)
:?
(polarize (.classValue inst))))
String
(polarize [pn]
(polarize (Integer/parseInt pn))))
;;; --------------------------------------------------------------------------
(defn label-polarity
"Returns the String «pos» or «neg» according to the polarity of x."
[x]
(label-polarity [x]
(case (polarize x)
:negative "neg"
:positive "pos")))
;;; --------------------------------------------------------------------------
(defprotocol Labeller
"Creates labels for say-senti purposes."
;; TODO: label-polarity [from above]
(label-text [x] "Returns a String identifier for a Text (tweet)."))
(extend-protocol Labeller
Instance
(label-text [inst]
(label-text (.value inst (int (Columns :id)))))
String
(label-text [s]
;; Allow multiple calls without retagging
(if (str/starts-with? s Tweet-Tag)
s
(str Tweet-Tag s)))
Object
(label-text [x]
(str Tweet-Tag (longify x))))
(defn label-text-token
"Returns a String identifier for a Text (tweet) and the token number.
Examples:
- for the tenth token on the 42nd tweet, the label will be: t42-10
- and for a MWE (multi-word expression) role on that token: t42-mwe10"
([txt tok]
(hyphenize (label-text txt) tok))
([txt tok role]
(hyphenize (label-text txt) (str (str/lower-case (name role)) tok))))
|
[
{
"context": "s for clojure:\n\n - [errorkit](https://github.com/richhickey/clojure-contrib/blob/master/src/main/clojure/cloj",
"end": 357,
"score": 0.9996984004974365,
"start": 347,
"tag": "USERNAME",
"value": "richhickey"
},
{
"context": "or this library.\n\n\n - [swell](https://github.com/hugoduncan/swell) and [conditions](https://github.com/bwo/co",
"end": 547,
"score": 0.7251533269882202,
"start": 537,
"tag": "USERNAME",
"value": "hugoduncan"
},
{
"context": "duncan/swell) and [conditions](https://github.com/bwo/conditions) have been written to work with [sling",
"end": 594,
"score": 0.8803976774215698,
"start": 591,
"tag": "USERNAME",
"value": "bwo"
},
{
"context": "itten to work with [slingshot](https://github.com/scgilardi/slingshot).\n\nA simple use case looking at the adv",
"end": 678,
"score": 0.9817203879356384,
"start": 669,
"tag": "USERNAME",
"value": "scgilardi"
},
{
"context": "lodge an issue on github or contact me directly.\n\nChris.\n\"\n",
"end": 5946,
"score": 0.9976271986961365,
"start": 5941,
"tag": "NAME",
"value": "Chris"
}
] | data/train/clojure/f4c97edce346a95138392d55abaf691bba8458f1ribol_guide.clj | harshp8l/deep-learning-lang-detection | 84 | (ns midje-doc.ribol-guide
(:require [ribol.core :refer :all]
[midje.sweet :refer :all]))
[[:chapter {:title "Overview"}]]
"
This is quite a comprehensive guide to `ribol` and how conditional restart libraries may be used. There are currently three other conditional restart libraries for clojure:
- [errorkit](https://github.com/richhickey/clojure-contrib/blob/master/src/main/clojure/clojure/contrib/error_kit.clj) was the first and provided the guiding architecture for this library.
- [swell](https://github.com/hugoduncan/swell) and [conditions](https://github.com/bwo/conditions) have been written to work with [slingshot](https://github.com/scgilardi/slingshot).
A simple use case looking at the advantage in using restarts over exceptions can be seen in [Unlucky Numbers](#unlucky-numbers). There is also a [Core library API](#api-reference) with examples.
For those that wish to know more about conditional restarts, a comparison of different strategies that can be implemented is done in [Control Strategies](#control-strategies). While for those curious about how this jumping around has been achieved, look at [Implementation](#implementation).
"
[[:section {:title "Installation"}]]
"Add to `project.clj` dependencies (use double quotes):
[im.chit/ribol '{{PROJECT.version}}']"
"All functionality is found contained in `ribol.core`"
[[{:numbered false}]]
(comment (use 'ribol.core))
[[:file {:src "test/clj/midje_doc/ribol_unlucky_numbers.clj"}]]
[[:chapter {:title "Conditional Restarts"}]]
"
`ribol` provides a conditional restart system. It can be thought of as an issue resolution system or `try++/catch++`. We use the term `issues` to differentiate them from `exceptions`. The difference is purely semantic: `issues` are `managed` whilst `exceptions` are `caught`. They all refer to abnormal program flow.
*Restart systems* are somewhat analogous to a *management structure*. A low level function will do work until it encounter an abnormal situation. An `issue` is `raised` up the chain to higher-level functions. These can `manage` the situation depending upon the type of `issue` raised.
"
"In the author's experience, there are two forms of `exceptions` that a programmer will encounter:
1. **Programming Mistakes** - These are a result of logic and reasoning errors, should not occur in normal operation and should be eliminated as soon as possible. The best strategy for dealing with this is to write unit tests and have functions fail early with a clear message to the programmer what the error is.
- Null pointers
- Wrong inputs to functions
2. **Exceptions due to Circumstances** - These are circumstancial and should be considered part of the normal operation of the program.
- A database connection going down
- A file not found
- User input not valid
The common method of `try` and `catch` is not really needed when dealing with the *Type 1* exceptions and a little too weak when dealing with those of *Type 2*.
The net effect of using only the `try/catch` paradigm in application code is that in order to mitigate these *Type 2* exceptions, there requires a lot of defensive programming. This turns the middle level of the application into spagetti code with program control flow (`try/catch`) mixed in with program logic.
Conditional restarts provide a way for the top-level application to more cleanly deal with *Type 2* exceptions.
"
[[:section {:title "Raising issues"}]]
"
`ribol` provide richer semantics for resolution of *Type 2* exceptions. Instead of `throw`, a new form `raise` is introduced ([e.{{raise-syntax}}](#raise-syntax)).
"
[[{:title "raise syntax"}]]
(comment
(raise {:input-not-string true :input-data 3} ;; issue payload
(option :use-na [] "NA") ;; option 1
(option :use-custom [n] n) ;; option 2
(default :use-custom "nil")) ;; default choice
)
"
`raise` differs to `throw` in a few ways:
- issues are of type `clojure.lang.ExceptionInfo`.
- the payload is a `hash-map`.
- **optional**: multiple `option` handlers can be specified.
- **optional**: a `default` choice can be specified.
"
[[:section {:title "Managing issues"}]]
"Instead of the `try/catch` combination, `manage/on` is used ([e.{{manage-syntax}}](#manage-syntax))."
[[{:title "manage/on syntax" :tag "manage-syntax"}]]
(comment
(manage (complex-operation)
(on :node-working [node-name]
(choose :wait-for-node))
(on :node-failed [node-name]
(choose :reinit-node))
(on :database-down []
(choose :use-database backup-database))
(on :core-failed []
(terminate-everything)))
)
"Issues are managed through `on` handlers within a `manage` block. If any `issue` is raised with the manage block, it is passed to each handler. There are six ways that a handler can deal with a raised issue:
- directly (same as `try/catch`)
- using `continue` to keep going with a given value
- using `choose` to specify an option
- using `escalate` to notify higher level managers
- using `default` to allow the issue to resolve itself
- using `fail` to throw an exception
Using these six different different issue resolution directives, the programmer has the richness of language to craft complex process control flow strategies without mixing logic handling code in the middle tier. Restarts can also create new ways of thinking about the problem beyond the standard `throw/catch` mechanism and offer more elegant ways to build programs and workflows.
"
[[:file {:src "test/clj/midje_doc/ribol_api.clj"}]]
[[:file {:src "test/clj/midje_doc/ribol_strategies.clj"}]]
[[:file {:src "test/clj/midje_doc/ribol_implementation.clj"}]]
[[:chapter {:title "End Notes"}]]
"For any feedback, requests and comments, please feel free to lodge an issue on github or contact me directly.
Chris.
"
| 114707 | (ns midje-doc.ribol-guide
(:require [ribol.core :refer :all]
[midje.sweet :refer :all]))
[[:chapter {:title "Overview"}]]
"
This is quite a comprehensive guide to `ribol` and how conditional restart libraries may be used. There are currently three other conditional restart libraries for clojure:
- [errorkit](https://github.com/richhickey/clojure-contrib/blob/master/src/main/clojure/clojure/contrib/error_kit.clj) was the first and provided the guiding architecture for this library.
- [swell](https://github.com/hugoduncan/swell) and [conditions](https://github.com/bwo/conditions) have been written to work with [slingshot](https://github.com/scgilardi/slingshot).
A simple use case looking at the advantage in using restarts over exceptions can be seen in [Unlucky Numbers](#unlucky-numbers). There is also a [Core library API](#api-reference) with examples.
For those that wish to know more about conditional restarts, a comparison of different strategies that can be implemented is done in [Control Strategies](#control-strategies). While for those curious about how this jumping around has been achieved, look at [Implementation](#implementation).
"
[[:section {:title "Installation"}]]
"Add to `project.clj` dependencies (use double quotes):
[im.chit/ribol '{{PROJECT.version}}']"
"All functionality is found contained in `ribol.core`"
[[{:numbered false}]]
(comment (use 'ribol.core))
[[:file {:src "test/clj/midje_doc/ribol_unlucky_numbers.clj"}]]
[[:chapter {:title "Conditional Restarts"}]]
"
`ribol` provides a conditional restart system. It can be thought of as an issue resolution system or `try++/catch++`. We use the term `issues` to differentiate them from `exceptions`. The difference is purely semantic: `issues` are `managed` whilst `exceptions` are `caught`. They all refer to abnormal program flow.
*Restart systems* are somewhat analogous to a *management structure*. A low level function will do work until it encounter an abnormal situation. An `issue` is `raised` up the chain to higher-level functions. These can `manage` the situation depending upon the type of `issue` raised.
"
"In the author's experience, there are two forms of `exceptions` that a programmer will encounter:
1. **Programming Mistakes** - These are a result of logic and reasoning errors, should not occur in normal operation and should be eliminated as soon as possible. The best strategy for dealing with this is to write unit tests and have functions fail early with a clear message to the programmer what the error is.
- Null pointers
- Wrong inputs to functions
2. **Exceptions due to Circumstances** - These are circumstancial and should be considered part of the normal operation of the program.
- A database connection going down
- A file not found
- User input not valid
The common method of `try` and `catch` is not really needed when dealing with the *Type 1* exceptions and a little too weak when dealing with those of *Type 2*.
The net effect of using only the `try/catch` paradigm in application code is that in order to mitigate these *Type 2* exceptions, there requires a lot of defensive programming. This turns the middle level of the application into spagetti code with program control flow (`try/catch`) mixed in with program logic.
Conditional restarts provide a way for the top-level application to more cleanly deal with *Type 2* exceptions.
"
[[:section {:title "Raising issues"}]]
"
`ribol` provide richer semantics for resolution of *Type 2* exceptions. Instead of `throw`, a new form `raise` is introduced ([e.{{raise-syntax}}](#raise-syntax)).
"
[[{:title "raise syntax"}]]
(comment
(raise {:input-not-string true :input-data 3} ;; issue payload
(option :use-na [] "NA") ;; option 1
(option :use-custom [n] n) ;; option 2
(default :use-custom "nil")) ;; default choice
)
"
`raise` differs to `throw` in a few ways:
- issues are of type `clojure.lang.ExceptionInfo`.
- the payload is a `hash-map`.
- **optional**: multiple `option` handlers can be specified.
- **optional**: a `default` choice can be specified.
"
[[:section {:title "Managing issues"}]]
"Instead of the `try/catch` combination, `manage/on` is used ([e.{{manage-syntax}}](#manage-syntax))."
[[{:title "manage/on syntax" :tag "manage-syntax"}]]
(comment
(manage (complex-operation)
(on :node-working [node-name]
(choose :wait-for-node))
(on :node-failed [node-name]
(choose :reinit-node))
(on :database-down []
(choose :use-database backup-database))
(on :core-failed []
(terminate-everything)))
)
"Issues are managed through `on` handlers within a `manage` block. If any `issue` is raised with the manage block, it is passed to each handler. There are six ways that a handler can deal with a raised issue:
- directly (same as `try/catch`)
- using `continue` to keep going with a given value
- using `choose` to specify an option
- using `escalate` to notify higher level managers
- using `default` to allow the issue to resolve itself
- using `fail` to throw an exception
Using these six different different issue resolution directives, the programmer has the richness of language to craft complex process control flow strategies without mixing logic handling code in the middle tier. Restarts can also create new ways of thinking about the problem beyond the standard `throw/catch` mechanism and offer more elegant ways to build programs and workflows.
"
[[:file {:src "test/clj/midje_doc/ribol_api.clj"}]]
[[:file {:src "test/clj/midje_doc/ribol_strategies.clj"}]]
[[:file {:src "test/clj/midje_doc/ribol_implementation.clj"}]]
[[:chapter {:title "End Notes"}]]
"For any feedback, requests and comments, please feel free to lodge an issue on github or contact me directly.
<NAME>.
"
| true | (ns midje-doc.ribol-guide
(:require [ribol.core :refer :all]
[midje.sweet :refer :all]))
[[:chapter {:title "Overview"}]]
"
This is quite a comprehensive guide to `ribol` and how conditional restart libraries may be used. There are currently three other conditional restart libraries for clojure:
- [errorkit](https://github.com/richhickey/clojure-contrib/blob/master/src/main/clojure/clojure/contrib/error_kit.clj) was the first and provided the guiding architecture for this library.
- [swell](https://github.com/hugoduncan/swell) and [conditions](https://github.com/bwo/conditions) have been written to work with [slingshot](https://github.com/scgilardi/slingshot).
A simple use case looking at the advantage in using restarts over exceptions can be seen in [Unlucky Numbers](#unlucky-numbers). There is also a [Core library API](#api-reference) with examples.
For those that wish to know more about conditional restarts, a comparison of different strategies that can be implemented is done in [Control Strategies](#control-strategies). While for those curious about how this jumping around has been achieved, look at [Implementation](#implementation).
"
[[:section {:title "Installation"}]]
"Add to `project.clj` dependencies (use double quotes):
[im.chit/ribol '{{PROJECT.version}}']"
"All functionality is found contained in `ribol.core`"
[[{:numbered false}]]
(comment (use 'ribol.core))
[[:file {:src "test/clj/midje_doc/ribol_unlucky_numbers.clj"}]]
[[:chapter {:title "Conditional Restarts"}]]
"
`ribol` provides a conditional restart system. It can be thought of as an issue resolution system or `try++/catch++`. We use the term `issues` to differentiate them from `exceptions`. The difference is purely semantic: `issues` are `managed` whilst `exceptions` are `caught`. They all refer to abnormal program flow.
*Restart systems* are somewhat analogous to a *management structure*. A low level function will do work until it encounter an abnormal situation. An `issue` is `raised` up the chain to higher-level functions. These can `manage` the situation depending upon the type of `issue` raised.
"
"In the author's experience, there are two forms of `exceptions` that a programmer will encounter:
1. **Programming Mistakes** - These are a result of logic and reasoning errors, should not occur in normal operation and should be eliminated as soon as possible. The best strategy for dealing with this is to write unit tests and have functions fail early with a clear message to the programmer what the error is.
- Null pointers
- Wrong inputs to functions
2. **Exceptions due to Circumstances** - These are circumstancial and should be considered part of the normal operation of the program.
- A database connection going down
- A file not found
- User input not valid
The common method of `try` and `catch` is not really needed when dealing with the *Type 1* exceptions and a little too weak when dealing with those of *Type 2*.
The net effect of using only the `try/catch` paradigm in application code is that in order to mitigate these *Type 2* exceptions, there requires a lot of defensive programming. This turns the middle level of the application into spagetti code with program control flow (`try/catch`) mixed in with program logic.
Conditional restarts provide a way for the top-level application to more cleanly deal with *Type 2* exceptions.
"
[[:section {:title "Raising issues"}]]
"
`ribol` provide richer semantics for resolution of *Type 2* exceptions. Instead of `throw`, a new form `raise` is introduced ([e.{{raise-syntax}}](#raise-syntax)).
"
[[{:title "raise syntax"}]]
(comment
(raise {:input-not-string true :input-data 3} ;; issue payload
(option :use-na [] "NA") ;; option 1
(option :use-custom [n] n) ;; option 2
(default :use-custom "nil")) ;; default choice
)
"
`raise` differs to `throw` in a few ways:
- issues are of type `clojure.lang.ExceptionInfo`.
- the payload is a `hash-map`.
- **optional**: multiple `option` handlers can be specified.
- **optional**: a `default` choice can be specified.
"
[[:section {:title "Managing issues"}]]
"Instead of the `try/catch` combination, `manage/on` is used ([e.{{manage-syntax}}](#manage-syntax))."
[[{:title "manage/on syntax" :tag "manage-syntax"}]]
(comment
(manage (complex-operation)
(on :node-working [node-name]
(choose :wait-for-node))
(on :node-failed [node-name]
(choose :reinit-node))
(on :database-down []
(choose :use-database backup-database))
(on :core-failed []
(terminate-everything)))
)
"Issues are managed through `on` handlers within a `manage` block. If any `issue` is raised with the manage block, it is passed to each handler. There are six ways that a handler can deal with a raised issue:
- directly (same as `try/catch`)
- using `continue` to keep going with a given value
- using `choose` to specify an option
- using `escalate` to notify higher level managers
- using `default` to allow the issue to resolve itself
- using `fail` to throw an exception
Using these six different different issue resolution directives, the programmer has the richness of language to craft complex process control flow strategies without mixing logic handling code in the middle tier. Restarts can also create new ways of thinking about the problem beyond the standard `throw/catch` mechanism and offer more elegant ways to build programs and workflows.
"
[[:file {:src "test/clj/midje_doc/ribol_api.clj"}]]
[[:file {:src "test/clj/midje_doc/ribol_strategies.clj"}]]
[[:file {:src "test/clj/midje_doc/ribol_implementation.clj"}]]
[[:chapter {:title "End Notes"}]]
"For any feedback, requests and comments, please feel free to lodge an issue on github or contact me directly.
PI:NAME:<NAME>END_PI.
"
|
[
{
"context": "nnection\n [{:db/id :datomic.id/joe :user/name \"Joe\" :user/age 45 :user/mate :datomic.id/mary :user/f",
"end": 396,
"score": 0.9996801614761353,
"start": 393,
"tag": "NAME",
"value": "Joe"
},
{
"context": "/mary}}\n {:db/id :datomic.id/mary :user/name \"Mary\" :user/age 33 :user/mate :datomic.id/joe :user/fr",
"end": 536,
"score": 0.9996585845947266,
"start": 532,
"tag": "NAME",
"value": "Mary"
},
{
"context": "/sally}}\n {:db/id :datomic.id/sam :user/name \"Sam\" :user/age 15 :user/friends #{:datomic.id/sally}}",
"end": 658,
"score": 0.9998038411140442,
"start": 655,
"tag": "NAME",
"value": "Sam"
},
{
"context": "ally}}\n {:db/id :datomic.id/sally :user/name \"Sally\" :user/age 22 :user/friends #{:datomic.id/sam :da",
"end": 757,
"score": 0.9997053146362305,
"start": 752,
"tag": "NAME",
"value": "Sally"
},
{
"context": "id] (some->> (get-id id) (d/entity db)))\n joe (get-user :datomic.id/joe)\n mary (get-us",
"end": 1524,
"score": 0.9923992156982422,
"start": 1521,
"tag": "NAME",
"value": "joe"
},
{
"context": "/entity db)))\n joe (get-user :datomic.id/joe)\n mary (get-user :datomic.id/mary)\n ",
"end": 1550,
"score": 0.9339261651039124,
"start": 1547,
"tag": "NAME",
"value": "joe"
},
{
"context": " joe (get-user :datomic.id/joe)\n mary (get-user :datomic.id/mary)\n sam (get-us",
"end": 1566,
"score": 0.9976426362991333,
"start": 1562,
"tag": "NAME",
"value": "mary"
},
{
"context": "omic.id/joe)\n mary (get-user :datomic.id/mary)\n sam (get-user :datomic.id/sam)\n ",
"end": 1593,
"score": 0.9615280032157898,
"start": 1589,
"tag": "NAME",
"value": "mary"
},
{
"context": " mary (get-user :datomic.id/mary)\n sam (get-user :datomic.id/sam)\n sally (get-u",
"end": 1608,
"score": 0.7776314616203308,
"start": 1605,
"tag": "NAME",
"value": "sam"
},
{
"context": " sam (get-user :datomic.id/sam)\n sally (get-user :datomic.id/sally)]\n (assertions\n ",
"end": 1651,
"score": 0.894267201423645,
"start": 1646,
"tag": "NAME",
"value": "sally"
},
{
"context": "er :datomic.id/sally)]\n (assertions\n \"Joe is married to Mary\"\n :TODO => :NOT-DONE\n ",
"end": 1712,
"score": 0.999416172504425,
"start": 1709,
"tag": "NAME",
"value": "Joe"
},
{
"context": "lly)]\n (assertions\n \"Joe is married to Mary\"\n :TODO => :NOT-DONE\n \"Mary is frie",
"end": 1731,
"score": 0.9996278285980225,
"start": 1727,
"tag": "NAME",
"value": "Mary"
},
{
"context": "ried to Mary\"\n :TODO => :NOT-DONE\n \"Mary is friends with Sally\"\n :TODO => :NOT-DONE",
"end": 1773,
"score": 0.9995789527893066,
"start": 1769,
"tag": "NAME",
"value": "Mary"
},
{
"context": " :TODO => :NOT-DONE\n \"Mary is friends with Sally\"\n :TODO => :NOT-DONE\n \"Joe is frien",
"end": 1795,
"score": 0.9995056390762329,
"start": 1790,
"tag": "NAME",
"value": "Sally"
},
{
"context": "s with Sally\"\n :TODO => :NOT-DONE\n \"Joe is friends with Mary and Sam\"\n :TODO => :N",
"end": 1836,
"score": 0.9991645812988281,
"start": 1833,
"tag": "NAME",
"value": "Joe"
},
{
"context": " :TODO => :NOT-DONE\n \"Joe is friends with Mary and Sam\"\n :TODO => :NOT-DONE\n \"Sam ",
"end": 1857,
"score": 0.9996500015258789,
"start": 1853,
"tag": "NAME",
"value": "Mary"
},
{
"context": "=> :NOT-DONE\n \"Joe is friends with Mary and Sam\"\n :TODO => :NOT-DONE\n \"Sam is 15 ye",
"end": 1865,
"score": 0.9993280172348022,
"start": 1862,
"tag": "NAME",
"value": "Sam"
},
{
"context": "Mary and Sam\"\n :TODO => :NOT-DONE\n \"Sam is 15 years old\"\n :TODO => :NOT-DONE))\n ",
"end": 1906,
"score": 0.994106113910675,
"start": 1903,
"tag": "NAME",
"value": "Sam"
}
] | test/server/app/db_testing_spec.clj | pholas/untangled-devguide | 43 | (ns app.db-testing-spec
(:require [untangled-spec.core :refer [specification provided behavior assertions]]
[datomic.api :as d]
[untangled.datomic.protocols :as udb]
[untangled.datomic.test-helpers :as helpers :refer [with-db-fixture]]))
(defn user-seed [connection]
(helpers/link-and-load-seed-data connection
[{:db/id :datomic.id/joe :user/name "Joe" :user/age 45 :user/mate :datomic.id/mary :user/friends #{:datomic.id/sam :datomic.id/mary}}
{:db/id :datomic.id/mary :user/name "Mary" :user/age 33 :user/mate :datomic.id/joe :user/friends #{:datomic.id/sally}}
{:db/id :datomic.id/sam :user/name "Sam" :user/age 15 :user/friends #{:datomic.id/sally}}
{:db/id :datomic.id/sally :user/name "Sally" :user/age 22 :user/friends #{:datomic.id/sam :datomic.id/mary}}]))
(defn db-fixture-defs
"Given a db-fixture returns a map containing:
`connection`: a connection to the fixture's db
`get-id`: give it a temp-id from seeded data, and it will return the real id from seeded data"
[fixture]
(let [connection (udb/get-connection fixture)
tempid-map (:seed-result (udb/get-info fixture))
get-id (partial get tempid-map)]
{:connection connection
:get-id get-id}))
#_(specification "My Seeded Users"
(with-db-fixture my-db
(let [{:keys [connection get-id]} (db-fixture-defs my-db)
info (udb/get-info my-db)
db (d/db connection)
get-user (fn [id] (some->> (get-id id) (d/entity db)))
joe (get-user :datomic.id/joe)
mary (get-user :datomic.id/mary)
sam (get-user :datomic.id/sam)
sally (get-user :datomic.id/sally)]
(assertions
"Joe is married to Mary"
:TODO => :NOT-DONE
"Mary is friends with Sally"
:TODO => :NOT-DONE
"Joe is friends with Mary and Sam"
:TODO => :NOT-DONE
"Sam is 15 years old"
:TODO => :NOT-DONE))
:migrations "app.sample-migrations"
:seed-fn user-seed))
| 77501 | (ns app.db-testing-spec
(:require [untangled-spec.core :refer [specification provided behavior assertions]]
[datomic.api :as d]
[untangled.datomic.protocols :as udb]
[untangled.datomic.test-helpers :as helpers :refer [with-db-fixture]]))
(defn user-seed [connection]
(helpers/link-and-load-seed-data connection
[{:db/id :datomic.id/joe :user/name "<NAME>" :user/age 45 :user/mate :datomic.id/mary :user/friends #{:datomic.id/sam :datomic.id/mary}}
{:db/id :datomic.id/mary :user/name "<NAME>" :user/age 33 :user/mate :datomic.id/joe :user/friends #{:datomic.id/sally}}
{:db/id :datomic.id/sam :user/name "<NAME>" :user/age 15 :user/friends #{:datomic.id/sally}}
{:db/id :datomic.id/sally :user/name "<NAME>" :user/age 22 :user/friends #{:datomic.id/sam :datomic.id/mary}}]))
(defn db-fixture-defs
"Given a db-fixture returns a map containing:
`connection`: a connection to the fixture's db
`get-id`: give it a temp-id from seeded data, and it will return the real id from seeded data"
[fixture]
(let [connection (udb/get-connection fixture)
tempid-map (:seed-result (udb/get-info fixture))
get-id (partial get tempid-map)]
{:connection connection
:get-id get-id}))
#_(specification "My Seeded Users"
(with-db-fixture my-db
(let [{:keys [connection get-id]} (db-fixture-defs my-db)
info (udb/get-info my-db)
db (d/db connection)
get-user (fn [id] (some->> (get-id id) (d/entity db)))
<NAME> (get-user :datomic.id/<NAME>)
<NAME> (get-user :datomic.id/<NAME>)
<NAME> (get-user :datomic.id/sam)
<NAME> (get-user :datomic.id/sally)]
(assertions
"<NAME> is married to <NAME>"
:TODO => :NOT-DONE
"<NAME> is friends with <NAME>"
:TODO => :NOT-DONE
"<NAME> is friends with <NAME> and <NAME>"
:TODO => :NOT-DONE
"<NAME> is 15 years old"
:TODO => :NOT-DONE))
:migrations "app.sample-migrations"
:seed-fn user-seed))
| true | (ns app.db-testing-spec
(:require [untangled-spec.core :refer [specification provided behavior assertions]]
[datomic.api :as d]
[untangled.datomic.protocols :as udb]
[untangled.datomic.test-helpers :as helpers :refer [with-db-fixture]]))
(defn user-seed [connection]
(helpers/link-and-load-seed-data connection
[{:db/id :datomic.id/joe :user/name "PI:NAME:<NAME>END_PI" :user/age 45 :user/mate :datomic.id/mary :user/friends #{:datomic.id/sam :datomic.id/mary}}
{:db/id :datomic.id/mary :user/name "PI:NAME:<NAME>END_PI" :user/age 33 :user/mate :datomic.id/joe :user/friends #{:datomic.id/sally}}
{:db/id :datomic.id/sam :user/name "PI:NAME:<NAME>END_PI" :user/age 15 :user/friends #{:datomic.id/sally}}
{:db/id :datomic.id/sally :user/name "PI:NAME:<NAME>END_PI" :user/age 22 :user/friends #{:datomic.id/sam :datomic.id/mary}}]))
(defn db-fixture-defs
"Given a db-fixture returns a map containing:
`connection`: a connection to the fixture's db
`get-id`: give it a temp-id from seeded data, and it will return the real id from seeded data"
[fixture]
(let [connection (udb/get-connection fixture)
tempid-map (:seed-result (udb/get-info fixture))
get-id (partial get tempid-map)]
{:connection connection
:get-id get-id}))
#_(specification "My Seeded Users"
(with-db-fixture my-db
(let [{:keys [connection get-id]} (db-fixture-defs my-db)
info (udb/get-info my-db)
db (d/db connection)
get-user (fn [id] (some->> (get-id id) (d/entity db)))
PI:NAME:<NAME>END_PI (get-user :datomic.id/PI:NAME:<NAME>END_PI)
PI:NAME:<NAME>END_PI (get-user :datomic.id/PI:NAME:<NAME>END_PI)
PI:NAME:<NAME>END_PI (get-user :datomic.id/sam)
PI:NAME:<NAME>END_PI (get-user :datomic.id/sally)]
(assertions
"PI:NAME:<NAME>END_PI is married to PI:NAME:<NAME>END_PI"
:TODO => :NOT-DONE
"PI:NAME:<NAME>END_PI is friends with PI:NAME:<NAME>END_PI"
:TODO => :NOT-DONE
"PI:NAME:<NAME>END_PI is friends with PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI"
:TODO => :NOT-DONE
"PI:NAME:<NAME>END_PI is 15 years old"
:TODO => :NOT-DONE))
:migrations "app.sample-migrations"
:seed-fn user-seed))
|
[
{
"context": " [config.core :refer [env]]\n [robert.bruce :refer [try-try-again]]\n [clj-time.for",
"end": 563,
"score": 0.6313247084617615,
"start": 551,
"tag": "USERNAME",
"value": "robert.bruce"
},
{
"context": "DigestUtils])\n (:gen-class))\n\n(def source-token \"8075957f-e0da-405f-9eee-7f35519d7c4c\")\n(def user-agent \"CrossrefEventDataBot (eventdat",
"end": 797,
"score": 0.9963541626930237,
"start": 761,
"tag": "PASSWORD",
"value": "8075957f-e0da-405f-9eee-7f35519d7c4c"
},
{
"context": "519d7c4c\")\n(def user-agent \"CrossrefEventDataBot (eventdata@crossref.org)\")\n(def license \"https://creativecommons.org/publ",
"end": 861,
"score": 0.999870777130127,
"start": 839,
"tag": "EMAIL",
"value": "eventdata@crossref.org"
},
{
"context": "d scan.\"))\n\n(def agent-definition\n {:agent-name \"hypothesis-agent\"\n :version version\n :jwt (:hypothesis-jwt env",
"end": 5364,
"score": 0.9558485150337219,
"start": 5348,
"tag": "USERNAME",
"value": "hypothesis-agent"
}
] | src/event_data_hypothesis_agent/core.clj | CrossRef/event-data-hypothesis-agent | 0 | (ns event-data-hypothesis-agent.core
(:require [org.crossref.event-data-agent-framework.core :as c]
[event-data-common.status :as status]
[crossref.util.doi :as cr-doi]
[clojure.tools.logging :as log]
[clojure.java.io :refer [reader]]
[clojure.data.json :as json]
[clj-time.coerce :as coerce]
[clj-time.core :as clj-time]
[throttler.core :refer [throttle-fn]]
[clj-http.client :as client]
[config.core :refer [env]]
[robert.bruce :refer [try-try-again]]
[clj-time.format :as clj-time-format])
(:import [java.util UUID]
[org.apache.commons.codec.digest DigestUtils])
(:gen-class))
(def source-token "8075957f-e0da-405f-9eee-7f35519d7c4c")
(def user-agent "CrossrefEventDataBot (eventdata@crossref.org)")
(def license "https://creativecommons.org/publicdomain/zero/1.0/")
(def version (System/getProperty "event-data-hypothesis-agent.version"))
(def api-url "https://hypothes.is/api/search")
; Max according to API docs.
(def page-size 200)
(def date-format
(:date-time-no-ms clj-time-format/formatters))
(defn api-item-to-actions
[item]
(let [occurred-at-iso8601 (clj-time-format/unparse date-format (coerce/from-string (:updated item)))]
; Return one action that represents "this annotation is about this DOI".
; ID is legacy from first version where there was only one kind of action per annotation.
[
{:id (str "hypothesis-" (:id item))
:url (-> item :links :html)
:relation-type-id "annotates"
:occurred-at occurred-at-iso8601
:observations [{:type :url :input-url (-> item :uri)}]
:extra {}
:subj {
:json-url (-> item :links :json)
:pid (-> item :links :html)
:url (-> item :links :incontext)
:alternative-id (:id item)
:type "annotation"
:title (-> item :text)
:issued occurred-at-iso8601}}
; And one that says "this annotation mentions these DOIs".
{:id (str "hypothesis-" (:id item) "-text")
:url (-> item :links :html)
:relation-type-id "discusses"
:occurred-at occurred-at-iso8601
:observations [{:type :plaintext :input-content (-> item :text)}]
:extra {}
:subj {
:json-url (-> item :links :json)
:pid (-> item :links :html)
:url (-> item :links :incontext)
:alternative-id (:id item)
:type "annotation"
:title (-> item :text)
:issued occurred-at-iso8601}}]))
; API
(defn parse-page
"Parse response JSON to a page of Actions."
[url json-data]
(let [parsed (json/read-str json-data :key-fn keyword)]
{:url url
:actions (mapcat api-item-to-actions (-> parsed :rows))}))
(defn fetch-page
[offset]
(status/send! "hypothesis-agent" "hypothesis" "fetch-page" 1)
; If the API returns an error
(try
(try-try-again
{:sleep 30000 :tries 10}
#(let [result (client/get api-url {:query-params {:offset offset :limit page-size :sort "updated" :order "desc"} :headers {"User-Agent" user-agent}})]
(log/info "Fetched page" {:offset offset :limit page-size})
(condp = (:status result)
200 (parse-page api-url (:body result))
404 {:url api-url :actions [] :extra {:after nil :before nil :error "Result not found"}}
(do
(log/error "Unexpected status code" (:status result) "from" api-url)
(log/error "Body of error response:" (:body result))
(throw (new Exception "Unexpected status"))))))
(catch Exception ex (do
(log/error "Error fetching" api-url)
(log/error "Exception:" ex)
{:url api-url :actions [] :extra {:error "Failed to retrieve page"}}))))
(def fetch-page-throttled (throttle-fn fetch-page 20 :minute))
(defn fetch-pages
"Lazy sequence of pages."
([] (fetch-pages 0))
([offset]
(log/info "fetch page offset" offset)
(let [result (fetch-page-throttled offset)
actions (:actions result)]
(log/info "Got" (count actions) "actions")
(if (empty? actions)
[result]
(lazy-seq (cons result (fetch-pages (+ offset page-size))))))))
(defn all-action-dates-after?
[date page]
(let [dates (map #(-> % :occurred-at coerce/from-string) (:actions page))]
(every? #(clj-time/after? % date) dates)))
(defn fetch-parsed-pages-after
"Fetch seq parsed pages of Actions until all actions on the page happened before the given time."
[date]
(let [pages (fetch-pages)]
(take-while (partial all-action-dates-after? date) pages)))
(defn retrieve-all
[artifacts callback]
(log/info "Start crawl all hypothesis at" (str (clj-time/now)))
(status/send! "hypothesis-agent" "process" "scan" 1)
(let [counter (atom 0)
cutoff-date (-> 12 clj-time/hours clj-time/ago)]
(let [pages (fetch-parsed-pages-after cutoff-date)]
(doseq [page pages]
(let [evidence-record {:source-token source-token
:source-id "hypothesis"
:license license
:agent {:version version}
:extra {:cutoff-date (str cutoff-date)}
:pages [page]}]
(log/info "Sending evidence record...")
(callback evidence-record)))))
(log/info "Finished scan."))
(def agent-definition
{:agent-name "hypothesis-agent"
:version version
:jwt (:hypothesis-jwt env)
:schedule [{:name "retrieve-all"
:seconds 14400 ; wait four hours between scans
:fixed-delay true
:fun retrieve-all
:required-artifacts []}]
:runners []})
(defn -main [& args]
(c/run agent-definition))
| 98204 | (ns event-data-hypothesis-agent.core
(:require [org.crossref.event-data-agent-framework.core :as c]
[event-data-common.status :as status]
[crossref.util.doi :as cr-doi]
[clojure.tools.logging :as log]
[clojure.java.io :refer [reader]]
[clojure.data.json :as json]
[clj-time.coerce :as coerce]
[clj-time.core :as clj-time]
[throttler.core :refer [throttle-fn]]
[clj-http.client :as client]
[config.core :refer [env]]
[robert.bruce :refer [try-try-again]]
[clj-time.format :as clj-time-format])
(:import [java.util UUID]
[org.apache.commons.codec.digest DigestUtils])
(:gen-class))
(def source-token "<PASSWORD>")
(def user-agent "CrossrefEventDataBot (<EMAIL>)")
(def license "https://creativecommons.org/publicdomain/zero/1.0/")
(def version (System/getProperty "event-data-hypothesis-agent.version"))
(def api-url "https://hypothes.is/api/search")
; Max according to API docs.
(def page-size 200)
(def date-format
(:date-time-no-ms clj-time-format/formatters))
(defn api-item-to-actions
[item]
(let [occurred-at-iso8601 (clj-time-format/unparse date-format (coerce/from-string (:updated item)))]
; Return one action that represents "this annotation is about this DOI".
; ID is legacy from first version where there was only one kind of action per annotation.
[
{:id (str "hypothesis-" (:id item))
:url (-> item :links :html)
:relation-type-id "annotates"
:occurred-at occurred-at-iso8601
:observations [{:type :url :input-url (-> item :uri)}]
:extra {}
:subj {
:json-url (-> item :links :json)
:pid (-> item :links :html)
:url (-> item :links :incontext)
:alternative-id (:id item)
:type "annotation"
:title (-> item :text)
:issued occurred-at-iso8601}}
; And one that says "this annotation mentions these DOIs".
{:id (str "hypothesis-" (:id item) "-text")
:url (-> item :links :html)
:relation-type-id "discusses"
:occurred-at occurred-at-iso8601
:observations [{:type :plaintext :input-content (-> item :text)}]
:extra {}
:subj {
:json-url (-> item :links :json)
:pid (-> item :links :html)
:url (-> item :links :incontext)
:alternative-id (:id item)
:type "annotation"
:title (-> item :text)
:issued occurred-at-iso8601}}]))
; API
(defn parse-page
"Parse response JSON to a page of Actions."
[url json-data]
(let [parsed (json/read-str json-data :key-fn keyword)]
{:url url
:actions (mapcat api-item-to-actions (-> parsed :rows))}))
(defn fetch-page
[offset]
(status/send! "hypothesis-agent" "hypothesis" "fetch-page" 1)
; If the API returns an error
(try
(try-try-again
{:sleep 30000 :tries 10}
#(let [result (client/get api-url {:query-params {:offset offset :limit page-size :sort "updated" :order "desc"} :headers {"User-Agent" user-agent}})]
(log/info "Fetched page" {:offset offset :limit page-size})
(condp = (:status result)
200 (parse-page api-url (:body result))
404 {:url api-url :actions [] :extra {:after nil :before nil :error "Result not found"}}
(do
(log/error "Unexpected status code" (:status result) "from" api-url)
(log/error "Body of error response:" (:body result))
(throw (new Exception "Unexpected status"))))))
(catch Exception ex (do
(log/error "Error fetching" api-url)
(log/error "Exception:" ex)
{:url api-url :actions [] :extra {:error "Failed to retrieve page"}}))))
(def fetch-page-throttled (throttle-fn fetch-page 20 :minute))
(defn fetch-pages
"Lazy sequence of pages."
([] (fetch-pages 0))
([offset]
(log/info "fetch page offset" offset)
(let [result (fetch-page-throttled offset)
actions (:actions result)]
(log/info "Got" (count actions) "actions")
(if (empty? actions)
[result]
(lazy-seq (cons result (fetch-pages (+ offset page-size))))))))
(defn all-action-dates-after?
[date page]
(let [dates (map #(-> % :occurred-at coerce/from-string) (:actions page))]
(every? #(clj-time/after? % date) dates)))
(defn fetch-parsed-pages-after
"Fetch seq parsed pages of Actions until all actions on the page happened before the given time."
[date]
(let [pages (fetch-pages)]
(take-while (partial all-action-dates-after? date) pages)))
(defn retrieve-all
[artifacts callback]
(log/info "Start crawl all hypothesis at" (str (clj-time/now)))
(status/send! "hypothesis-agent" "process" "scan" 1)
(let [counter (atom 0)
cutoff-date (-> 12 clj-time/hours clj-time/ago)]
(let [pages (fetch-parsed-pages-after cutoff-date)]
(doseq [page pages]
(let [evidence-record {:source-token source-token
:source-id "hypothesis"
:license license
:agent {:version version}
:extra {:cutoff-date (str cutoff-date)}
:pages [page]}]
(log/info "Sending evidence record...")
(callback evidence-record)))))
(log/info "Finished scan."))
(def agent-definition
{:agent-name "hypothesis-agent"
:version version
:jwt (:hypothesis-jwt env)
:schedule [{:name "retrieve-all"
:seconds 14400 ; wait four hours between scans
:fixed-delay true
:fun retrieve-all
:required-artifacts []}]
:runners []})
(defn -main [& args]
(c/run agent-definition))
| true | (ns event-data-hypothesis-agent.core
(:require [org.crossref.event-data-agent-framework.core :as c]
[event-data-common.status :as status]
[crossref.util.doi :as cr-doi]
[clojure.tools.logging :as log]
[clojure.java.io :refer [reader]]
[clojure.data.json :as json]
[clj-time.coerce :as coerce]
[clj-time.core :as clj-time]
[throttler.core :refer [throttle-fn]]
[clj-http.client :as client]
[config.core :refer [env]]
[robert.bruce :refer [try-try-again]]
[clj-time.format :as clj-time-format])
(:import [java.util UUID]
[org.apache.commons.codec.digest DigestUtils])
(:gen-class))
(def source-token "PI:PASSWORD:<PASSWORD>END_PI")
(def user-agent "CrossrefEventDataBot (PI:EMAIL:<EMAIL>END_PI)")
(def license "https://creativecommons.org/publicdomain/zero/1.0/")
(def version (System/getProperty "event-data-hypothesis-agent.version"))
(def api-url "https://hypothes.is/api/search")
; Max according to API docs.
(def page-size 200)
(def date-format
(:date-time-no-ms clj-time-format/formatters))
(defn api-item-to-actions
[item]
(let [occurred-at-iso8601 (clj-time-format/unparse date-format (coerce/from-string (:updated item)))]
; Return one action that represents "this annotation is about this DOI".
; ID is legacy from first version where there was only one kind of action per annotation.
[
{:id (str "hypothesis-" (:id item))
:url (-> item :links :html)
:relation-type-id "annotates"
:occurred-at occurred-at-iso8601
:observations [{:type :url :input-url (-> item :uri)}]
:extra {}
:subj {
:json-url (-> item :links :json)
:pid (-> item :links :html)
:url (-> item :links :incontext)
:alternative-id (:id item)
:type "annotation"
:title (-> item :text)
:issued occurred-at-iso8601}}
; And one that says "this annotation mentions these DOIs".
{:id (str "hypothesis-" (:id item) "-text")
:url (-> item :links :html)
:relation-type-id "discusses"
:occurred-at occurred-at-iso8601
:observations [{:type :plaintext :input-content (-> item :text)}]
:extra {}
:subj {
:json-url (-> item :links :json)
:pid (-> item :links :html)
:url (-> item :links :incontext)
:alternative-id (:id item)
:type "annotation"
:title (-> item :text)
:issued occurred-at-iso8601}}]))
; API
(defn parse-page
"Parse response JSON to a page of Actions."
[url json-data]
(let [parsed (json/read-str json-data :key-fn keyword)]
{:url url
:actions (mapcat api-item-to-actions (-> parsed :rows))}))
(defn fetch-page
[offset]
(status/send! "hypothesis-agent" "hypothesis" "fetch-page" 1)
; If the API returns an error
(try
(try-try-again
{:sleep 30000 :tries 10}
#(let [result (client/get api-url {:query-params {:offset offset :limit page-size :sort "updated" :order "desc"} :headers {"User-Agent" user-agent}})]
(log/info "Fetched page" {:offset offset :limit page-size})
(condp = (:status result)
200 (parse-page api-url (:body result))
404 {:url api-url :actions [] :extra {:after nil :before nil :error "Result not found"}}
(do
(log/error "Unexpected status code" (:status result) "from" api-url)
(log/error "Body of error response:" (:body result))
(throw (new Exception "Unexpected status"))))))
(catch Exception ex (do
(log/error "Error fetching" api-url)
(log/error "Exception:" ex)
{:url api-url :actions [] :extra {:error "Failed to retrieve page"}}))))
(def fetch-page-throttled (throttle-fn fetch-page 20 :minute))
(defn fetch-pages
"Lazy sequence of pages."
([] (fetch-pages 0))
([offset]
(log/info "fetch page offset" offset)
(let [result (fetch-page-throttled offset)
actions (:actions result)]
(log/info "Got" (count actions) "actions")
(if (empty? actions)
[result]
(lazy-seq (cons result (fetch-pages (+ offset page-size))))))))
(defn all-action-dates-after?
[date page]
(let [dates (map #(-> % :occurred-at coerce/from-string) (:actions page))]
(every? #(clj-time/after? % date) dates)))
(defn fetch-parsed-pages-after
"Fetch seq parsed pages of Actions until all actions on the page happened before the given time."
[date]
(let [pages (fetch-pages)]
(take-while (partial all-action-dates-after? date) pages)))
(defn retrieve-all
[artifacts callback]
(log/info "Start crawl all hypothesis at" (str (clj-time/now)))
(status/send! "hypothesis-agent" "process" "scan" 1)
(let [counter (atom 0)
cutoff-date (-> 12 clj-time/hours clj-time/ago)]
(let [pages (fetch-parsed-pages-after cutoff-date)]
(doseq [page pages]
(let [evidence-record {:source-token source-token
:source-id "hypothesis"
:license license
:agent {:version version}
:extra {:cutoff-date (str cutoff-date)}
:pages [page]}]
(log/info "Sending evidence record...")
(callback evidence-record)))))
(log/info "Finished scan."))
(def agent-definition
{:agent-name "hypothesis-agent"
:version version
:jwt (:hypothesis-jwt env)
:schedule [{:name "retrieve-all"
:seconds 14400 ; wait four hours between scans
:fixed-delay true
:fun retrieve-all
:required-artifacts []}]
:runners []})
(defn -main [& args]
(c/run agent-definition))
|
[
{
"context": "be passed with `hikari`. See\n https://github.com/tomekw/hikari-cp#configuration-options for that\n list.\"",
"end": 328,
"score": 0.9996115565299988,
"start": 322,
"tag": "USERNAME",
"value": "tomekw"
},
{
"context": "e (or host-part \"\") dbname)\n :username user}\n hikari (merge hikari)\n password (asso",
"end": 620,
"score": 0.7539965510368347,
"start": 616,
"tag": "USERNAME",
"value": "user"
},
{
"context": "ari (merge hikari)\n password (assoc :password password))))\n\n(defn pooled-db\n [spec opts]\n (let [config",
"end": 690,
"score": 0.9796425104141235,
"start": 682,
"tag": "PASSWORD",
"value": "password"
}
] | src/clj_postgresql/pool.clj | remodoy/clj-postgresql | 150 | (ns clj-postgresql.pool
"Hikari based connection pool"
(:require [hikari-cp.core :as hikari])
(:import (java.util.concurrent TimeUnit)))
(defn db-spec->pool-config
"Converts a db-spec with :host :port :dbname and :user to Hikari pool
config. Hikari options can be passed with `hikari`. See
https://github.com/tomekw/hikari-cp#configuration-options for that
list."
[{:keys [dbtype host port dbname user password hikari]}]
(let [host-part (when host (if port (format "%s:%s" host port) host))]
(cond-> {:jdbc-url (format "jdbc:%s://%s/%s" dbtype (or host-part "") dbname)
:username user}
hikari (merge hikari)
password (assoc :password password))))
(defn pooled-db
[spec opts]
(let [config (merge (db-spec->pool-config spec) opts)]
{:datasource (hikari/make-datasource config)}))
(defn close-pooled-db!
[{:keys [datasource]}]
(hikari/close-datasource datasource))
| 88480 | (ns clj-postgresql.pool
"Hikari based connection pool"
(:require [hikari-cp.core :as hikari])
(:import (java.util.concurrent TimeUnit)))
(defn db-spec->pool-config
"Converts a db-spec with :host :port :dbname and :user to Hikari pool
config. Hikari options can be passed with `hikari`. See
https://github.com/tomekw/hikari-cp#configuration-options for that
list."
[{:keys [dbtype host port dbname user password hikari]}]
(let [host-part (when host (if port (format "%s:%s" host port) host))]
(cond-> {:jdbc-url (format "jdbc:%s://%s/%s" dbtype (or host-part "") dbname)
:username user}
hikari (merge hikari)
password (assoc :password <PASSWORD>))))
(defn pooled-db
[spec opts]
(let [config (merge (db-spec->pool-config spec) opts)]
{:datasource (hikari/make-datasource config)}))
(defn close-pooled-db!
[{:keys [datasource]}]
(hikari/close-datasource datasource))
| true | (ns clj-postgresql.pool
"Hikari based connection pool"
(:require [hikari-cp.core :as hikari])
(:import (java.util.concurrent TimeUnit)))
(defn db-spec->pool-config
"Converts a db-spec with :host :port :dbname and :user to Hikari pool
config. Hikari options can be passed with `hikari`. See
https://github.com/tomekw/hikari-cp#configuration-options for that
list."
[{:keys [dbtype host port dbname user password hikari]}]
(let [host-part (when host (if port (format "%s:%s" host port) host))]
(cond-> {:jdbc-url (format "jdbc:%s://%s/%s" dbtype (or host-part "") dbname)
:username user}
hikari (merge hikari)
password (assoc :password PI:PASSWORD:<PASSWORD>END_PI))))
(defn pooled-db
[spec opts]
(let [config (merge (db-spec->pool-config spec) opts)]
{:datasource (hikari/make-datasource config)}))
(defn close-pooled-db!
[{:keys [datasource]}]
(hikari/close-datasource datasource))
|
[
{
"context": " {:cog-client-id client-id}\n {:username canary-username\n :password canary-password})\n ",
"end": 779,
"score": 0.9993340969085693,
"start": 764,
"tag": "USERNAME",
"value": "canary-username"
},
{
"context": " {:username canary-username\n :password canary-password})\n <!\n res/data\n :Authent",
"end": 817,
"score": 0.9991962313652039,
"start": 802,
"tag": "PASSWORD",
"value": "canary-password"
},
{
"context": " creds\n {:username canary-username\n :password canary-password\n ",
"end": 1357,
"score": 0.9990044832229614,
"start": 1342,
"tag": "USERNAME",
"value": "canary-username"
},
{
"context": "ame canary-username\n :password canary-password\n :pool-id pool-id}))\n\n ",
"end": 1404,
"score": 0.9991250038146973,
"start": 1389,
"tag": "PASSWORD",
"value": "canary-password"
},
{
"context": "r4mc12jta38djmhi3g\"\n \n\n :canary-username \"zk+zkdev-prod-canary@heyzk.com\"\n :canary-password \"Test1234!\"}))\n\n\n\n",
"end": 2534,
"score": 0.9996699690818787,
"start": 2504,
"tag": "EMAIL",
"value": "zk+zkdev-prod-canary@heyzk.com"
},
{
"context": "dev-prod-canary@heyzk.com\"\n :canary-password \"Test1234!\"}))\n\n\n\n",
"end": 2567,
"score": 0.9994185566902161,
"start": 2559,
"tag": "PASSWORD",
"value": "Test1234"
}
] | src/cljs-node/rx/node/box/verify_deployment.cljs | zk/rx-lib | 0 | (ns rx.node.box.verify-deployment
"Utilities for verifying a new box sync deployment"
(:require [rx.kitchen-sink :as ks
:refer-macros [go-try <?]]
[rx.res :as res]
[rx.node.box :as box]
[rx.node.aws :as aws]
[rx.jwt :as jwt]
[rx.git :refer-macros [head-hash]]
[cljs.core.async
:refer [<!]
:refer-macros [go]]))
(defn <id-token [{:keys [:aws/creds
:aws.cog/client-id
:aws.cog/pool-id
:canary-username
:canary-password]}]
(go-try
(->> (aws/<cogisp-user-password-auth
creds
{:cog-client-id client-id}
{:username canary-username
:password canary-password})
<!
res/data
:AuthenticationResult
:IdToken)))
(defn <verify-deployment
[{:keys [:aws/creds
:box/schema
:box/entity
:aws.cog/client-id
:aws.cog/pool-id
:canary-username
:canary-password]
:as opts}]
(go-try
(let [conn (<? (box/<conn schema))
_ (ks/pn "Connection: " (not (nil? conn)))
res (<? (aws/<cogisp-admin-set-user-password
creds
{:username canary-username
:password canary-password
:pool-id pool-id}))
_ (ks/pn "Set username / password on canary user: "
(not (res/anom res)))
token (<? (<id-token opts))
_ (ks/pn "Created token: "
(not (nil? token)))
sub (-> token jwt/from-jwt :payload :sub)
_ (ks/pn "User sub: " sub)
res (<? (box/<sync-entities
conn
[(merge
entity
{:box.sync/owner-id sub})]
token))]
(if (box/has-failures? res)
(ks/<spy "Sync Failed" res)
(ks/pn "Sync verified")))))
(comment
(require 'zkdev.schema)
(<verify-deployment
{:box/schema
zkdev.schema/SCHEMA
:aws/creds
(:dev-creds
(ks/edn-read-string
(ks/slurp-cljs "~/.zkdev-prod-secrets.edn")))
:box/entity {:box.canary/id "foo"
:some/other "key"
:foo/bar 123}
:aws.cog/pool-id "us-west-2_H4MFCDqBJ"
:aws.cog/client-id "59dplcj3r4mc12jta38djmhi3g"
:canary-username "zk+zkdev-prod-canary@heyzk.com"
:canary-password "Test1234!"}))
| 72753 | (ns rx.node.box.verify-deployment
"Utilities for verifying a new box sync deployment"
(:require [rx.kitchen-sink :as ks
:refer-macros [go-try <?]]
[rx.res :as res]
[rx.node.box :as box]
[rx.node.aws :as aws]
[rx.jwt :as jwt]
[rx.git :refer-macros [head-hash]]
[cljs.core.async
:refer [<!]
:refer-macros [go]]))
(defn <id-token [{:keys [:aws/creds
:aws.cog/client-id
:aws.cog/pool-id
:canary-username
:canary-password]}]
(go-try
(->> (aws/<cogisp-user-password-auth
creds
{:cog-client-id client-id}
{:username canary-username
:password <PASSWORD>})
<!
res/data
:AuthenticationResult
:IdToken)))
(defn <verify-deployment
[{:keys [:aws/creds
:box/schema
:box/entity
:aws.cog/client-id
:aws.cog/pool-id
:canary-username
:canary-password]
:as opts}]
(go-try
(let [conn (<? (box/<conn schema))
_ (ks/pn "Connection: " (not (nil? conn)))
res (<? (aws/<cogisp-admin-set-user-password
creds
{:username canary-username
:password <PASSWORD>
:pool-id pool-id}))
_ (ks/pn "Set username / password on canary user: "
(not (res/anom res)))
token (<? (<id-token opts))
_ (ks/pn "Created token: "
(not (nil? token)))
sub (-> token jwt/from-jwt :payload :sub)
_ (ks/pn "User sub: " sub)
res (<? (box/<sync-entities
conn
[(merge
entity
{:box.sync/owner-id sub})]
token))]
(if (box/has-failures? res)
(ks/<spy "Sync Failed" res)
(ks/pn "Sync verified")))))
(comment
(require 'zkdev.schema)
(<verify-deployment
{:box/schema
zkdev.schema/SCHEMA
:aws/creds
(:dev-creds
(ks/edn-read-string
(ks/slurp-cljs "~/.zkdev-prod-secrets.edn")))
:box/entity {:box.canary/id "foo"
:some/other "key"
:foo/bar 123}
:aws.cog/pool-id "us-west-2_H4MFCDqBJ"
:aws.cog/client-id "59dplcj3r4mc12jta38djmhi3g"
:canary-username "<EMAIL>"
:canary-password "<PASSWORD>!"}))
| true | (ns rx.node.box.verify-deployment
"Utilities for verifying a new box sync deployment"
(:require [rx.kitchen-sink :as ks
:refer-macros [go-try <?]]
[rx.res :as res]
[rx.node.box :as box]
[rx.node.aws :as aws]
[rx.jwt :as jwt]
[rx.git :refer-macros [head-hash]]
[cljs.core.async
:refer [<!]
:refer-macros [go]]))
(defn <id-token [{:keys [:aws/creds
:aws.cog/client-id
:aws.cog/pool-id
:canary-username
:canary-password]}]
(go-try
(->> (aws/<cogisp-user-password-auth
creds
{:cog-client-id client-id}
{:username canary-username
:password PI:PASSWORD:<PASSWORD>END_PI})
<!
res/data
:AuthenticationResult
:IdToken)))
(defn <verify-deployment
[{:keys [:aws/creds
:box/schema
:box/entity
:aws.cog/client-id
:aws.cog/pool-id
:canary-username
:canary-password]
:as opts}]
(go-try
(let [conn (<? (box/<conn schema))
_ (ks/pn "Connection: " (not (nil? conn)))
res (<? (aws/<cogisp-admin-set-user-password
creds
{:username canary-username
:password PI:PASSWORD:<PASSWORD>END_PI
:pool-id pool-id}))
_ (ks/pn "Set username / password on canary user: "
(not (res/anom res)))
token (<? (<id-token opts))
_ (ks/pn "Created token: "
(not (nil? token)))
sub (-> token jwt/from-jwt :payload :sub)
_ (ks/pn "User sub: " sub)
res (<? (box/<sync-entities
conn
[(merge
entity
{:box.sync/owner-id sub})]
token))]
(if (box/has-failures? res)
(ks/<spy "Sync Failed" res)
(ks/pn "Sync verified")))))
(comment
(require 'zkdev.schema)
(<verify-deployment
{:box/schema
zkdev.schema/SCHEMA
:aws/creds
(:dev-creds
(ks/edn-read-string
(ks/slurp-cljs "~/.zkdev-prod-secrets.edn")))
:box/entity {:box.canary/id "foo"
:some/other "key"
:foo/bar 123}
:aws.cog/pool-id "us-west-2_H4MFCDqBJ"
:aws.cog/client-id "59dplcj3r4mc12jta38djmhi3g"
:canary-username "PI:EMAIL:<EMAIL>END_PI"
:canary-password "PI:PASSWORD:<PASSWORD>END_PI!"}))
|
[
{
"context": " :best-for \"Merlot, Chardonnay, Chianti, Chenin Blanc, and Sauvignon",
"end": 71193,
"score": 0.9931830167770386,
"start": 71187,
"tag": "NAME",
"value": "Merlot"
},
{
"context": " :best-for \"Merlot, Chardonnay, Chianti, Chenin Blanc, and Sauvignon Blanc\"\n ",
"end": 71205,
"score": 0.9976447820663452,
"start": 71195,
"tag": "NAME",
"value": "Chardonnay"
},
{
"context": " :best-for \"Merlot, Chardonnay, Chianti, Chenin Blanc, and Sauvignon Blanc\"\n ",
"end": 71214,
"score": 0.998110830783844,
"start": 71207,
"tag": "NAME",
"value": "Chianti"
},
{
"context": " :best-for \"Merlot, Chardonnay, Chianti, Chenin Blanc, and Sauvignon Blanc\"\n ",
"end": 71228,
"score": 0.9996289014816284,
"start": 71216,
"tag": "NAME",
"value": "Chenin Blanc"
},
{
"context": " \"Merlot, Chardonnay, Chianti, Chenin Blanc, and Sauvignon Blanc\"\n ",
"end": 71249,
"score": 0.9995391964912415,
"start": 71234,
"tag": "NAME",
"value": "Sauvignon Blanc"
},
{
"context": "on complements flavor. WLP760 is also suitable for Merlot, Chardonnay, Chianti, Chenin Blanc, and Sauvig",
"end": 71652,
"score": 0.537900447845459,
"start": 71649,
"tag": "NAME",
"value": "Mer"
},
{
"context": " is also suitable for Merlot, Chardonnay, Chianti, Chenin Blanc, and Sauvignon Blanc. Alcohol Tolerance: ",
"end": 71682,
"score": 0.9888448119163513,
"start": 71678,
"tag": "NAME",
"value": "Chen"
},
{
"context": " :notes \"Licensed by White Labs from Charlie Papazian, author of \\\"The Complete Joy of Home Brewing\\\". ",
"end": 85198,
"score": 0.9998750686645508,
"start": 85182,
"tag": "NAME",
"value": "Charlie Papazian"
}
] | src/common_beer_format/data/yeasts/white_labs.cljc | Wall-Brew-Co/common-beer-format | 1 | (ns common-beer-format.data.yeasts.white-labs
"Data for yeasts cultivated by White Labs"
(:require [common-beer-format.data.yeasts.yeasts :as yeasts]))
(def wlp001-california-ale
(yeasts/build-yeasts :wlp001-california-ale {:min-temperature 20.0
:name "WLP001 California Ale"
:max-temperature 22.78
:type "Ale"
:best-for "American Style Ales, Ambers, Pale Ales, Brown Ale, Strong Ale"
:laboratory "White Labs"
:attenuation 0.765
:notes "Very clean flavor, balance and stability. Accentuates hop flavor Versitile - can be used to make any style ale."
:flocculation "High"
:form "Liquid"
:product-id "WLP001"}))
(def wlp002-english-ale
(yeasts/build-yeasts :wlp002-english-ale {:min-temperature 18.33
:name "WLP002 English Ale"
:max-temperature 20.0
:type "Ale"
:best-for "English Pale Ale, ESB, India Pale Ale, Brown Ale, Porter, Sweet Stouts and Strong Ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Classic ESB strain best for English style milds, bitters, porters and English style stouts. Leaves a clear beer with some residual sweetness."
:flocculation "Very High"
:form "Liquid"
:product-id "WLP002"}))
(def wlp003-german-ale-ii
(yeasts/build-yeasts :wlp003-german-ale-ii {:min-temperature 18.33
:name "WLP003 German Ale II"
:max-temperature 21.11
:type "Ale"
:best-for "Kolsch, Alt and German Pale Ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Strong sulfer component will reduce with aging. Clean flavor, but with more ester production than regular German Ale Yeast."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP003"}))
(def wlp004-irish-ale-yeast
(yeasts/build-yeasts :wlp004-irish-ale-yeast {:min-temperature 18.33
:name "WLP004 Irish Ale Yeast"
:max-temperature 20.0
:type "Ale"
:best-for "Irish Ales, Stouts, Porters, Browns, Reds and Pale Ale"
:laboratory "White Labs"
:attenuation 0.765
:notes "Excellent for Irish Stouts. Produces slight hint of diacetyl balanced by a light fruitiness and a slightly dry crispness."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP004"}))
(def wlp005-british-ale
(yeasts/build-yeasts :wlp005-british-ale {:min-temperature 19.44
:name "WLP005 British Ale"
:max-temperature 23.33
:type "Ale"
:best-for "Excellent for all English style ales including bitters, pale ale, porters and brown ale."
:laboratory "White Labs"
:attenuation 0.765
:notes "This yeast has higher attenuation than the White Labs English Ale yeast strains. Produces a malty flavored beer."
:flocculation "High"
:form "Liquid"
:product-id "WLP005"}))
(def wlp006-bedford-british-ale
(yeasts/build-yeasts :wlp006-bedford-british-ale {:min-temperature 18.33
:name "WLP006 Bedford British Ale"
:max-temperature 21.11
:type "Ale"
:best-for "English style ales - bitter, pale, porter and brown ale"
:laboratory "White Labs"
:attenuation 0.765
:notes "High attenuation. Ferments dry with high flocculation. Distinctive ester profile. Good for most English ale styles."
:flocculation "High"
:form "Liquid"
:product-id "WLP006"}))
(def wlp007-dry-english-ale
(yeasts/build-yeasts :wlp007-dry-english-ale {:min-temperature 18.33
:name "WLP007 Dry English Ale"
:max-temperature 21.11
:type "Ale"
:best-for "Pale Ales, Amber, ESB, Brown Ales, Strong Ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Clean, Highly flocculant, and highly attentive yeast. Similar to White labs English Ale yeast, but more attentive. Suitable for high gravity ales."
:flocculation "High"
:form "Liquid"
:product-id "WLP007"}))
(def wlp008-east-coast-ale
(yeasts/build-yeasts :wlp008-east-coast-ale {:min-temperature 20.0
:name "WLP008 East Coast Ale"
:max-temperature 22.78
:type "Ale"
:best-for "American Ales, Golden ales, Blonde Ale, Pale Ale and German Alt styles"
:laboratory "White Labs"
:attenuation 0.765
:notes "White labs \"Brewer Patriot\"strain can be used to reproduce many of the American versions of classic beer styles. Very clean with low esters. "
:flocculation "Low"
:form "Liquid"
:product-id "WLP008"}))
(def wlp009-australian-ale-yeast
(yeasts/build-yeasts :wlp009-australian-ale-yeast {:min-temperature 18.33
:name "WLP009 Australian Ale Yeast"
:max-temperature 21.11
:type "Ale"
:best-for "Australian Ales, English Ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "White Labs entry for Australian Ales. Produces a clean, malty finish with pleasant ester character. Bready character. Can ferment clean at high temperatures."
:flocculation "High"
:form "Liquid"
:product-id "WLP009"}))
(def wlp011-european-ale
(yeasts/build-yeasts :wlp011-european-ale {:min-temperature 18.33
:name "WLP011 European Ale"
:max-temperature 21.11
:type "Ale"
:best-for "Alt, Kolsch, malty English Ales, Fruit beers"
:laboratory "White Labs"
:attenuation 0.765
:notes "Malty, Northern European ale yeast. Low ester production, low sulfer, gives a clean profile. Low attenuation contributes to malty taste."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP011"}))
(def wlp013-london-ale
(yeasts/build-yeasts :wlp013-london-ale {:min-temperature 18.89
:name "WLP013 London Ale"
:max-temperature 21.67
:type "Ale"
:best-for "Classic British Pale Ales, Bitters and Stouts"
:laboratory "White Labs"
:attenuation 0.765
:notes "Dry, malty ale yeast. Produces a complex, oak flavored ester character. Hop bitterness comes through well."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP013"}))
(def wlp022-essex-ale-yeast
(yeasts/build-yeasts :wlp022-essex-ale-yeast {:min-temperature 18.89
:name "WLP022 Essex Ale Yeast"
:max-temperature 21.11
:type "Ale"
:best-for "British milds, pale ales, bitters, stouts."
:laboratory "White Labs"
:attenuation 0.765
:notes "Flavorful British yeast with a drier finish than many ale yeasts. Bready and fruity in character. Well suited for top cropping (collecting). Does not flocculate as much as WLP005 or WLP002."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP022"}))
(def wlp023-burton-ale
(yeasts/build-yeasts :wlp023-burton-ale {:min-temperature 20.0
:name "WLP023 Burton Ale"
:max-temperature 22.78
:type "Ale"
:best-for "All English styles including Pale Ale, IPA, Porter, Stout and Bitters."
:laboratory "White Labs"
:attenuation 0.765
:notes "Burton-on-trent yeast produces a complex character. Flavors include apple, pear, and clover honey."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP023"}))
(def wlp025-southwold-ale
(yeasts/build-yeasts :wlp025-southwold-ale {:min-temperature 18.89
:name "WLP025 Southwold Ale"
:max-temperature 20.56
:type "Ale"
:best-for "British bitters and pale ales."
:laboratory "White Labs"
:attenuation 0.765
:notes "From Suffolk county. Products complex fruity and citrus flavors. Slight sulfer production, but this will fade with aging."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP025"}))
(def wlp026-premium-bitter-ale
(yeasts/build-yeasts :wlp026-premium-bitter-ale {:min-temperature 19.44
:name "WLP026 Premium Bitter Ale"
:max-temperature 21.11
:type "Ale"
:best-for "All English ales including bitters, milds, ESB, Porter, Stout and Barley Wine"
:laboratory "White Labs"
:attenuation 0.765
:notes "From Staffordshire England. Mild, but complex estery flavor. High attenuation - ferments strong and dry. Suitable for high gravity beers."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP026"}))
(def wlp028-edinburgh-ale
(yeasts/build-yeasts :wlp028-edinburgh-ale {:min-temperature 18.33
:name "WLP028 Edinburgh Ale"
:max-temperature 21.11
:type "Ale"
:best-for "Strong Scottish style ales, ESB, Irish Reds"
:laboratory "White Labs"
:attenuation 0.765
:notes "Malty strong ale yeast. Reproduces complex, malty, flavorful schottish ales. Hop character comes through well."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP028"}))
(def wlp029-german-ale-kolsch
(yeasts/build-yeasts :wlp029-german-ale-kolsch {:min-temperature 18.33
:name "WLP029 German Ale/Kolsch"
:max-temperature 20.56
:type "Ale"
:best-for "Kolsch, Altbiers, Pale Ales, Blonde and Honey Ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Great for light beers. Accentuates hop flavors. Slight sulfer flavor will fade with age and leave a clean, lager like ale."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP029"}))
(def wlp033-klassic-ale-yeast
(yeasts/build-yeasts :wlp033-klassic-ale-yeast {:min-temperature 18.89
:name "WLP033 Klassic Ale Yeast"
:max-temperature 21.11
:type "Ale"
:best-for "Bitters, milds, porters stouts and scottish ale styles."
:laboratory "White Labs"
:attenuation 0.765
:notes "Traditional English Ale style yeast. Produces ester character, and allows hop flavor through. Leaves a slightly sweet malt character in ales."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP033"}))
(def wlp036-dusseldorf-alt-yeast
(yeasts/build-yeasts :wlp036-dusseldorf-alt-yeast {:min-temperature 18.33
:name "WLP036 Dusseldorf Alt Yeast"
:max-temperature 20.56
:type "Ale"
:best-for "Alt biers, Dusseldorf Alts, German Ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Traditional Alt yeast from Dusseldorf, Germany. Produces clean, slightly sweet alt beers. Does not accentuate hop flavor like WLP029 does."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP036"}))
(def wlp037-yorkshire-square-ale-yeast
(yeasts/build-yeasts :wlp037-yorkshire-square-ale-yeast {:min-temperature 18.33
:name "WLP037 Yorkshire Square Ale Yeast"
:max-temperature 20.56
:type "Ale"
:best-for "English pale ales, English brown ales and Mild ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "This yeast produces a malty but well balanced profile. Expect toasty flavors with malt driven esters. Highly flocculent and a good choice for many English ales."
:flocculation "High"
:form "Liquid"
:product-id "WLP037"}))
(def wlp038-manchester-ale-yeast
(yeasts/build-yeasts :wlp038-manchester-ale-yeast {:min-temperature 18.33
:name "WLP038 Manchester Ale Yeast"
:max-temperature 21.11
:type "Ale"
:best-for "English style ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Top fermenting strain that is good for top-cropping. Moderately flocculent with a clean, dry finish. Low ester profile for producing a balanced English ale."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP038"}))
(def wlp039-nottingham-ale-yeast
(yeasts/build-yeasts :wlp039-nottingham-ale-yeast {:min-temperature 18.89
:name "WLP039 Nottingham Ale Yeast"
:max-temperature 21.11
:type "Ale"
:best-for "British ales, pale ales, ambers, porters and stouts."
:laboratory "White Labs"
:attenuation 0.765
:notes "British style of ale yeast with a very dry finish and high attenuation. Medium to low fruit and fusel alcohol production. Good top fermenting yeast for cropping. "
:flocculation "Medium"
:form "Liquid"
:product-id "WLP039"}))
(def wlp041-pacific-ale
(yeasts/build-yeasts :wlp041-pacific-ale {:min-temperature 18.33
:name "WLP041 Pacific Ale"
:max-temperature 20.0
:type "Ale"
:best-for "English & American ales including milds, bitters, IPA, porters and English stouts."
:laboratory "White Labs"
:attenuation 0.765
:notes "Popular yeast from the Pacific Northwest. Leaves a clear and malty profile. More fruity than WLP002. Suitable for many English and American styles."
:flocculation "High"
:form "Liquid"
:product-id "WLP041"}))
(def wlp051-california-ale-v
(yeasts/build-yeasts :wlp051-california-ale-v {:min-temperature 18.89
:name "WLP051 California Ale V"
:max-temperature 21.11
:type "Ale"
:best-for "American style Pales, Ambers, Browns, IPAs, American Strong Ale"
:laboratory "White Labs"
:attenuation 0.765
:notes "Similar to White Labs California Ale Yeast, but slightly lower attenuation leaves a fuller bodied beer."
:flocculation "High"
:form "Liquid"
:product-id "WLP051"}))
(def wlp060-american-ale-yeast-blend
(yeasts/build-yeasts :wlp060-american-ale-yeast-blend {:min-temperature 20.0
:name "WLP060 American Ale Yeast Blend"
:max-temperature 22.22
:type "Ale"
:best-for "American ales with clean finish"
:laboratory "White Labs"
:attenuation 0.765
:notes "A blend that celebrates WLP001 (California Ale Yeast's) clean, neutral fermentation. This strain is versatile and adds two other yeast strains that are also clean/neutral in flavor to add a bit of complexity - almost a lager like finish. Slight sulfur m"
:flocculation "Medium"
:form "Liquid"
:product-id "WLP060"}))
(def wlp080-cream-ale-yeast-blend
(yeasts/build-yeasts :wlp080-cream-ale-yeast-blend {:min-temperature 18.33
:name "WLP080 Cream Ale Yeast Blend"
:max-temperature 21.11
:type "Ale"
:best-for "Cream Ale, Hybrids"
:laboratory "White Labs"
:attenuation 0.765
:notes "A blend of ale and lager yeast strains that work together to create a clean, light American lager style ale. A pleasing estery aroma may be perceived. Hop flavors and bitterness are slightly subdued. Slight sulfer will be produced during fermentation f"
:flocculation "Medium"
:form "Liquid"
:product-id "WLP080"}))
(def wlp090-san-diego-super-yeast
(yeasts/build-yeasts :wlp090-san-diego-super-yeast {:min-temperature 18.33
:name "WLP090 San Diego Super Yeast"
:max-temperature 20.0
:type "Ale"
:best-for "IPAs, American ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "A super clean, super-fast fermenting strain. A low ester-producing strain that results in a balanced, neutral flavor and aroma profile. Alcohol-tolerant and very versatile for a wide variety of styles. Similar to California Ale Yeast WLP001 but it generally ferments faster."
:flocculation "Very High"
:form "Liquid"
:product-id "WLP090"}))
(def wlp099-super-high-gravity-ale
(yeasts/build-yeasts :wlp099-super-high-gravity-ale {:min-temperature 20.56
:name "WLP099 Super High Gravity Ale"
:max-temperature 23.33
:type "Ale"
:best-for "Very high gravity beers and barley wine up to 25% alcohol."
:laboratory "White Labs"
:attenuation 0.765
:notes "Ferments up to 25% alcohol content. Flavor may vary greatly depending on beer alcohol. English like esters at low gravity, but will become more wine-like as alcohol exceeds 16% ABV. Refer to White Labs web page for tips on fermenting high gravity ales."
:flocculation "Low"
:form "Liquid"
:product-id "WLP099"}))
(def wlp300-hefeweizen-ale
(yeasts/build-yeasts :wlp300-hefeweizen-ale {:min-temperature 20.0
:name "WLP300 Hefeweizen Ale"
:max-temperature 22.22
:type "Wheat"
:best-for "German style wheat beers. Weiss, Weizen, Hefeweizen"
:laboratory "White Labs"
:attenuation 0.765
:notes "Produces the banana and clove nose traditionally associated with German Wheat beers. Also produces desired cloudy look."
:flocculation "Low"
:form "Liquid"
:product-id "WLP300"}))
(def wlp320-american-hefeweizen-ale
(yeasts/build-yeasts :wlp320-american-hefeweizen-ale {:min-temperature 18.33
:name "WLP320 American Hefeweizen Ale"
:max-temperature 20.56
:type "Wheat"
:best-for "Oregon style American Hefeweizen"
:laboratory "White Labs"
:attenuation 0.765
:notes "Produces a much smaller amount of clove and banana flavor than the German Hefeweizen White Labs yeast. Some sulfur, and creates desired cloudy look."
:flocculation "Low"
:form "Liquid"
:product-id "WLP320"}))
(def wlp351-bavarian-weizen-yeast
(yeasts/build-yeasts :wlp351-bavarian-weizen-yeast {:min-temperature 18.89
:name "WLP351 Bavarian Weizen Yeast"
:max-temperature 21.11
:type "Wheat"
:best-for "Bavarian Weizen and wheat beers."
:laboratory "White Labs"
:attenuation 0.765
:notes "Former yeast lab W51 strain. Produces a classic German style wheat beer with moderately high, spicy, phenolic overtones reminiscent of cloves."
:flocculation "Low"
:form "Liquid"
:product-id "WLP351"}))
(def wlp380-hefeweizen-iv-ale
(yeasts/build-yeasts :wlp380-hefeweizen-iv-ale {:min-temperature 18.89
:name "WLP380 Hefeweizen IV Ale"
:max-temperature 21.11
:type "Wheat"
:best-for "German style Hefeweizen"
:laboratory "White Labs"
:attenuation 0.765
:notes "Large clove and phenolic aroma, but with minimal banana flavor. Citrus and apricot notes. Crisp and drinkable, with some sulfur production."
:flocculation "Low"
:form "Liquid"
:product-id "WLP380"}))
(def wlp400-belgian-wit-ale
(yeasts/build-yeasts :wlp400-belgian-wit-ale {:min-temperature 19.44
:name "WLP400 Belgian Wit Ale"
:max-temperature 23.33
:type "Wheat"
:best-for "Belgian Wit"
:laboratory "White Labs"
:attenuation 0.765
:notes "Phenolic and tart. The original yeast used to produce Wit in Belgium."
:flocculation "Low"
:form "Liquid"
:product-id "WLP400"}))
(def wlp410-belgian-wit-ii
(yeasts/build-yeasts :wlp410-belgian-wit-ii {:min-temperature 19.44
:name "WLP410 Belgian Wit II"
:max-temperature 23.33
:type "Ale"
:best-for "Belgian Wit, Spiced Ale, Wheat Ales and Specialty Beers"
:laboratory "White Labs"
:attenuation 0.765
:notes "Less phenolic than WLP400 (Belgian Wit Ale) but more spicy. Leaves a little more sweetness and flocculation is higher than WLP400."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP410"}))
(def wlp500-trappist-ale
(yeasts/build-yeasts :wlp500-trappist-ale {:min-temperature 18.33
:name "WLP500 Trappist Ale"
:max-temperature 22.22
:type "Ale"
:best-for "Trappist Ale, Dubbel, Trippel, Belgian Ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Distinctive fruitiness and plum characteristics. Excellent for high gravity beers."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP500"}))
(def wlp510-bastogne-belgian-ale
(yeasts/build-yeasts :wlp510-bastogne-belgian-ale {:min-temperature 18.89
:name "WLP510 Bastogne Belgian Ale"
:max-temperature 22.22
:type "Ale"
:best-for "High gravity beers, Belgian ales, Dubbels, Trippels."
:laboratory "White Labs"
:attenuation 0.765
:notes "High gravity Trappist ale yeast. Creates a dry beer with a slightly acidic finish. Cleaner finish and slightly less spicy than WLP500 or WLP530. "
:flocculation "Medium"
:form "Liquid"
:product-id "WLP510"}))
(def wlp515-antwerp-ale-yeast
(yeasts/build-yeasts :wlp515-antwerp-ale-yeast {:min-temperature 19.44
:name "WLP515 Antwerp Ale Yeast"
:max-temperature 21.11
:type "Ale"
:best-for "Belgian pale and amber ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Clean, almost lager like Belgian ale yeast. Good for Belgian pale and amber ales or with other Belgian yeasts in a blend. Biscuity, ale like aroma present. Hop flavors are accentuated. Slight sulfur during fermentation, and a lager like flavor profile"
:flocculation "Medium"
:form "Liquid"
:product-id "WLP515"}))
(def wlp530-abbey-ale
(yeasts/build-yeasts :wlp530-abbey-ale {:min-temperature 18.89
:name "WLP530 Abbey Ale"
:max-temperature 22.22
:type "Ale"
:best-for "Belgian Trappist Ale, Spiced Ale, Trippel, Dubbel, Grand Cru"
:laboratory "White Labs"
:attenuation 0.765
:notes "Used in two of six remaining Trappist breweries. Distinctive plum and fruitiness. Good for high gravity beers."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP530"}))
(def wlp540-abbey-iv-ale-yeast
(yeasts/build-yeasts :wlp540-abbey-iv-ale-yeast {:min-temperature 18.89
:name "WLP540 Abbey IV Ale Yeast"
:max-temperature 22.22
:type "Ale"
:best-for "Trappist Belgian Ales, Dubbels, Tripels and Specialty ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "An authentic Trappist style ale yeast. Use for Belgian ales including abbey ales (dubbels, tripels). Fruit character is medium - between WLP500 (high) and WLP530 (low)"
:flocculation "Medium"
:form "Liquid"
:product-id "WLP540"}))
(def wlp545-belgian-strong-ale-yeast
(yeasts/build-yeasts :wlp545-belgian-strong-ale-yeast {:min-temperature 18.33
:name "WLP545 Belgian Strong Ale Yeast"
:max-temperature 22.78
:type "Ale"
:best-for "Belgian dark strongs, Abbey ales and Christmas beers"
:laboratory "White Labs"
:attenuation 0.765
:notes "From the Ardennes region of Belgium, this classic strain produces moderate esters and spicy phenolic character. Results in a dry but balanced finish. Use for dark or strong abbey ales."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP545"}))
(def wlp550-belgian-ale
(yeasts/build-yeasts :wlp550-belgian-ale {:min-temperature 20.0
:name "WLP550 Belgian Ale"
:max-temperature 25.56
:type "Ale"
:best-for "Belgian Ales, Saisons, Belgian Reds, Belgian Browns, White beers"
:laboratory "White Labs"
:attenuation 0.765
:notes "Phenolic and spicy flavors. Complex profile, with less fruitiness than White's Trappist Ale strain."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP550"}))
(def wlp565-belgian-saison-i-ale
(yeasts/build-yeasts :wlp565-belgian-saison-i-ale {:min-temperature 20.0
:name "WLP565 Belgian Saison I Ale"
:max-temperature 23.89
:type "Ale"
:best-for "Saison Ale, Belgian Ale, Dubbel, Trippel"
:laboratory "White Labs"
:attenuation 0.765
:notes "Saison yeast from Wallonia. Earthy, spicy and peppery notes. Slightly sweet."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP565"}))
(def wlp566-belgian-saison-ii-yeast
(yeasts/build-yeasts :wlp566-belgian-saison-ii-yeast {:min-temperature 20.0
:name "WLP566 Belgian Saison II Yeast"
:max-temperature 25.56
:type "Ale"
:best-for "Belgian or French Saison"
:laboratory "White Labs"
:attenuation 0.765
:notes "Saison strain with a more fruity ester profile than WLP565 (Belgian Saison I Yeast). Moderately phenolic with a clove-like characteristic in finished beer flavor and aroma. Ferments quickly."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP566"}))
(def wlp568-belgian-style-saison-ale-yeast-blend
(yeasts/build-yeasts :wlp568-belgian-style-saison-ale-yeast-blend {:min-temperature 21.11
:name "WLP568 Belgian Style Saison Ale Yeast Blend"
:max-temperature 26.67
:type "Ale"
:best-for "Belgian and French Saison"
:laboratory "White Labs"
:attenuation 0.765
:notes "This blend melds Belgian style ale and Saison strains. The strains work in harmony to create complex, fruity aromas and flavors. The blend of yeast strains encourages complete fermentation in a timely manner. Phenolic, spicy, earthy, and clove like flavor"
:flocculation "Medium"
:form "Liquid"
:product-id "WLP568"}))
(def wlp570-belgian-golden-ale
(yeasts/build-yeasts :wlp570-belgian-golden-ale {:min-temperature 20.0
:name "WLP570 Belgian Golden Ale"
:max-temperature 23.89
:type "Ale"
:best-for "Belgian Ales, Dubbel, Grand Cru, Belgian Holiday Ale"
:laboratory "White Labs"
:attenuation 0.765
:notes "Combination of fruitiness and phenolic characters dominate the profile. Some sulfur which will dissapate following fermentation."
:flocculation "Low"
:form "Liquid"
:product-id "WLP570"}))
(def wlp575-belgian-style-ale-yeast-blend
(yeasts/build-yeasts :wlp575-belgian-style-ale-yeast-blend {:min-temperature 20.0
:name "WLP575 Belgian Style Ale Yeast Blend"
:max-temperature 23.89
:type "Ale"
:best-for "Trappist and other Belgian ales."
:laboratory "White Labs"
:attenuation 0.765
:notes "Blend of two trappist ale yeasts and one Belgian ale yeast. Creates a versatile blend to be used for Trappist and other Belgian style ales."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP575"}))
(def wlp630-berliner-weisse-blend
(yeasts/build-yeasts :wlp630-berliner-weisse-blend {:min-temperature 20.0
:name "WLP630 Berliner Weisse Blend"
:max-temperature 22.22
:type "Wheat"
:best-for "Berliner Weisse"
:laboratory "White Labs"
:attenuation 0.765
:notes "A blend of a traditional German Weizen yeast and Lactobacillus to create a subtle, tart, drinkable beer. Can take several months to develop tart character. Perfect for traditional Berliner Weisse."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP630"}))
(def wlp645-brettanomyces-claussenii
(yeasts/build-yeasts :wlp645-brettanomyces-claussenii {:min-temperature 18.33
:name "WLP645 Brettanomyces Claussenii"
:max-temperature 22.22
:type "Ale"
:best-for "Sour ales (in secondary)"
:laboratory "White Labs"
:attenuation 0.765
:notes "Low intensity Brett character. Originally isolated from strong English stock beer, in the early 20th century. The Brett flavors produced are more subtle than WLP650 and WLP653. More aroma than flavor contribution. Fruity, pineapple like aroma."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP645"}))
(def wlp650-brettanomyces-bruxellensis
(yeasts/build-yeasts :wlp650-brettanomyces-bruxellensis {:min-temperature 18.33
:name "WLP650 Brettanomyces Bruxellensis"
:max-temperature 22.22
:type "Ale"
:best-for "Belgian sour ales and labics (in secondary)"
:laboratory "White Labs"
:attenuation 0.765
:notes "Medium intensity Brett character. Classic strain used in secondary fermentation for Belgian style beers and lambics. One Trappist brewery uses this strain in secondary fermentation."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP650"}))
(def wlp653-brettanomyces-lambicus
(yeasts/build-yeasts :wlp653-brettanomyces-lambicus {:min-temperature 18.33
:name "WLP653 Brettanomyces Lambicus"
:max-temperature 22.22
:type "Ale"
:best-for "Lambics and Flanders/Sour Brown ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Use in secondary. High intensity Brett character. Defines the \"Brett character\": Horsey, smoky and spicy flavors. As the name suggests, this strain is found most often in Lambic style beers, which are spontaneously fermented beers."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP653"}))
(def wlp655-belgian-sour-mix-1
(yeasts/build-yeasts :wlp655-belgian-sour-mix-1 {:min-temperature 18.33
:name "WLP655 Belgian Sour Mix 1"
:max-temperature 22.22
:type "Ale"
:best-for "Belgian sour beers (in secondary)"
:laboratory "White Labs"
:attenuation 0.765
:notes "Note: Bacteria to use in secondary only. A unique blend perfect for Belgian style beers. Includes Brettanomyces, Saccharomyces, and the bacterial strains Lactobacillus and Pediococcus."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP655"}))
(def wlp670-american-farmhouse-blend
(yeasts/build-yeasts :wlp670-american-farmhouse-blend {:min-temperature 20.0
:name "WLP670 American Farmhouse Blend"
:max-temperature 22.22
:type "Ale"
:best-for "Saisons, Farmhouse Ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Inspired by local American brewers crafting semi- traditional Belgian-style ales. This blend creates a complex flavor profile with a moderate level of sourness. It consists of a traditional farmhouse yeast strain and Brettanomyces. Great yeast for farmho"
:flocculation "Medium"
:form "Liquid"
:product-id "WLP670"}))
(def wlp675-malolactic-bacteria
(yeasts/build-yeasts :wlp675-malolactic-bacteria {:min-temperature 18.33
:name "WLP675 Malolactic Bacteria"
:max-temperature 22.22
:type "Ale"
:best-for "Primarily wine"
:laboratory "White Labs"
:attenuation 0.765
:notes "Bacteria for use in secondary. Malolactic fermentation is the conversion of malic acid to lactic acid by bacteria from the lactic acid bacteria family. Lactic acid is less acidic than malic acid, which in turn decreases acidity and helps to soften and/o"
:flocculation "Medium"
:form "Liquid"
:product-id "WLP675"}))
(def wlp677-lactobacillus-bacteria
(yeasts/build-yeasts :wlp677-lactobacillus-bacteria {:min-temperature 18.33
:name "WLP677 Lactobacillus Bacteria"
:max-temperature 22.22
:type "Ale"
:best-for "Lambic, Berliner Weiss, Sour Brown and Gueze (secondary)"
:laboratory "White Labs"
:attenuation 0.765
:notes "Bacteria for use in secondary. This lactic acid bacteria produces moderate levels of acidity and sour flavors found in lambics, Berliner Weiss, sour brown ale and gueze."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP677"}))
(def wlp700-flor-sherry-yeast
(yeasts/build-yeasts :wlp700-flor-sherry-yeast {:min-temperature 21.11
:name "WLP700 Flor Sherry Yeast"
:max-temperature 24.44
:type "Wine"
:best-for "Sherry wine yeast"
:laboratory "White Labs"
:attenuation 0.765
:notes "This yeast develops a film (flor) on the surface of the wine. Creates green almond, granny smith and nougat characteristics found in sherry. Can also be used for Port, Madeira and other sweet styles. For use in secondary fermentation. Slow fermentor. Al"
:flocculation "Medium"
:form "Liquid"
:product-id "WLP700"}))
(def wlp705-sake-yeast
(yeasts/build-yeasts :wlp705-sake-yeast {:min-temperature 21.11
:name "WLP705 Sake Yeast"
:max-temperature 24.44
:type "Wine"
:best-for "Sake wine yeast"
:laboratory "White Labs"
:attenuation 0.765
:notes "For use in rice based fermentations. For sake, use this yeast in conjunction with Koji (to produce fermentable sugar). WLP705 produces full body sake character, and subtle fragrance. Alcohol tolerance to 16%."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP705"}))
(def wlp715-champagne-yeast
(yeasts/build-yeasts :wlp715-champagne-yeast {:min-temperature 21.11
:name "WLP715 Champagne Yeast"
:max-temperature 23.89
:type "Champagne"
:best-for "Wine, Mead and Cider"
:laboratory "White Labs"
:attenuation 0.765
:notes "Can tolerate alcohol up to 17%. For Barley Wine or Meads."
:flocculation "Low"
:form "Liquid"
:product-id "WLP715"}))
(def wlp718-avize-wine-yeast
(yeasts/build-yeasts :wlp718-avize-wine-yeast {:min-temperature 15.56
:name "WLP718 Avize Wine Yeast"
:max-temperature 32.22
:type "Wine"
:best-for "Chardonnay"
:laboratory "White Labs"
:attenuation 0.765
:notes "Champagne isolate used for complexity in whites. Contributes elegance, especially in barrel fermented Chardonnays. Alcohol tolerance to 15%."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP718"}))
(def wlp720-sweet-mead-wine
(yeasts/build-yeasts :wlp720-sweet-mead-wine {:min-temperature 21.11
:name "WLP720 Sweet Mead/Wine"
:max-temperature 23.89
:type "Wine"
:best-for "Sweet Mead, Wine and Cider"
:laboratory "White Labs"
:attenuation 0.765
:notes "Lower attenuation than White Labs Champagne Yeast. Leaves some residual sweetness as well as fruity flavor. Alcohol concentration up to 15%."
:flocculation "Low"
:form "Liquid"
:product-id "WLP720"}))
(def wlp727-steinberg-geisenheim-wine
(yeasts/build-yeasts :wlp727-steinberg-geisenheim-wine {:min-temperature 10.0
:name "WLP727 Steinberg-Geisenheim Wine"
:max-temperature 32.22
:type "Wine"
:best-for "Riesling wines."
:laboratory "White Labs"
:attenuation 0.765
:notes "German origin wine yeast. High fruit/ester production. Moderate fermentation characteristics and cold tolerant."
:flocculation "Low"
:form "Liquid"
:product-id "WLP727"}))
(def wlp730-chardonnay-white-wine-yeast
(yeasts/build-yeasts :wlp730-chardonnay-white-wine-yeast {:min-temperature 10.0
:name "WLP730 Chardonnay White Wine Yeast"
:max-temperature 32.22
:type "Wine"
:best-for "Chardonnay Wine"
:laboratory "White Labs"
:attenuation 0.765
:notes "Dry wine yeast. Slight ester production, low sulfur dioxide production. Enhances varietal character. WLP730 is a good choice for all white and blush wines, including Chablis, Chenin Blanc, Semillon, and Sauvignon Blanc. Fermentation speed is moderate. Al"
:flocculation "Low"
:form "Liquid"
:product-id "WLP730"}))
(def wlp735-french-white-wine-yeast
(yeasts/build-yeasts :wlp735-french-white-wine-yeast {:min-temperature 15.56
:name "WLP735 French White Wine Yeast"
:max-temperature 32.22
:type "Wine"
:best-for "French white wines"
:laboratory "White Labs"
:attenuation 0.765
:notes "Classic yeast for white wine fermentation. Slow to moderate fermenter and foam producer. Gives an enhanced creamy texture. Alcohol Tolerance: 16%"
:flocculation "Low"
:form "Liquid"
:product-id "WLP735"}))
(def wlp740-merlot-red-wine-yeast
(yeasts/build-yeasts :wlp740-merlot-red-wine-yeast {:min-temperature 15.56
:name "WLP740 Merlot Red Wine Yeast"
:max-temperature 32.22
:type "Wine"
:best-for "Merlot, Shiraz, Pinot Noir, Chardonnay, Cabernet, Sauvignon Blanc, and Semillon"
:laboratory "White Labs"
:attenuation 0.765
:notes "Neutral, low fusel alcohol production. Will ferment to dryness, alcohol tolerance to 18%. Vigorous fermenter. WLP740 is well suited for Merlot, Shiraz, Pinot Noir, Chardonnay, Cabernet, Sauvignon Blanc, and Semillon. Alcohol Tolerance: 18%"
:flocculation "Low"
:form "Liquid"
:product-id "WLP740"}))
(def wlp749-assmanshausen-wine-yeast
(yeasts/build-yeasts :wlp749-assmanshausen-wine-yeast {:min-temperature 10.0
:name "WLP749 Assmanshausen Wine Yeast"
:max-temperature 32.22
:type "Wine"
:best-for "Pinot Noir and Zinfandel"
:laboratory "White Labs"
:attenuation 0.765
:notes "German red wine yeast, which results in spicy, fruit aromas. Perfect for Pinot Noir and Zinfandel. Slow to moderate fermenter which is cold tolerant. Alcohol Tolerance: 16%"
:flocculation "Low"
:form "Liquid"
:product-id "WLP749"}))
(def wlp750-french-red-wine-yeast
(yeasts/build-yeasts :wlp750-french-red-wine-yeast {:min-temperature 15.56
:name "WLP750 French Red Wine Yeast"
:max-temperature 32.22
:type "Wine"
:best-for "Bordeaux"
:laboratory "White Labs"
:attenuation 0.765
:notes "Classic Bordeaux yeast for red wine fermentations. Moderate fermentation characteristics. Tolerates lower fermentation temperatures. Rich, smooth flavor profile. Alcohol Tolerance: 17%"
:flocculation "Low"
:form "Liquid"
:product-id "WLP750"}))
(def wlp760-cabernet-red-wine-yeast
(yeasts/build-yeasts :wlp760-cabernet-red-wine-yeast {:min-temperature 15.56
:name "WLP760 Cabernet Red Wine Yeast"
:max-temperature 32.22
:type "Wine"
:best-for "Merlot, Chardonnay, Chianti, Chenin Blanc, and Sauvignon Blanc"
:laboratory "White Labs"
:attenuation 0.765
:notes "High temperature tolerance. Moderate fermentation speed. Excellent for full-bodied red wines, ester production complements flavor. WLP760 is also suitable for Merlot, Chardonnay, Chianti, Chenin Blanc, and Sauvignon Blanc. Alcohol Tolerance: 16%"
:flocculation "Low"
:form "Liquid"
:product-id "WLP760"}))
(def wlp770-suremain-burgundy-wine-yeast
(yeasts/build-yeasts :wlp770-suremain-burgundy-wine-yeast {:min-temperature 15.56
:name "WLP770 Suremain Burgundy Wine Yeast"
:max-temperature 32.22
:type "Wine"
:best-for "Burgundy"
:laboratory "White Labs"
:attenuation 0.765
:notes "Emphasizes fruit aromas in barrel fermentations. High nutrient requirement to avoid volatile acidity production. Alcohol Tolerance: 16%"
:flocculation "Low"
:form "Liquid"
:product-id "WLP770"}))
(def wlp775-english-cider-yeast
(yeasts/build-yeasts :wlp775-english-cider-yeast {:min-temperature 20.0
:name "WLP775 English Cider Yeast"
:max-temperature 23.89
:type "Wine"
:best-for "Cider, Wine and High Gravity Beer"
:laboratory "White Labs"
:attenuation 0.765
:notes "Classic Cider yeast. Ferments dry, but retains apple flavor. Some sulfer produced during fermentation will fade with age."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP775"}))
(def wlp800-pilsner-lager
(yeasts/build-yeasts :wlp800-pilsner-lager {:min-temperature 10.0
:name "WLP800 Pilsner Lager"
:max-temperature 12.78
:type "Lager"
:best-for "European Pilsners, Bohemian Pilsner"
:laboratory "White Labs"
:attenuation 0.765
:notes "Classic pilsner strain from Czech Republic. Dry with a malty finish."
:flocculation "High"
:form "Liquid"
:product-id "WLP800"}))
(def wlp802-czech-budejovice-lager
(yeasts/build-yeasts :wlp802-czech-budejovice-lager {:min-temperature 10.0
:name "WLP802 Czech Budejovice Lager"
:max-temperature 12.78
:type "Lager"
:best-for "Bohemian Style Pilsner"
:laboratory "White Labs"
:attenuation 0.765
:notes "Dry and crisp with low diacetyl production. From Southern Czech Republic."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP802"}))
(def wlp810-san-francisco-lager
(yeasts/build-yeasts :wlp810-san-francisco-lager {:min-temperature 14.44
:name "WLP810 San Francisco Lager"
:max-temperature 18.33
:type "Lager"
:best-for "California and Premium Lagers, all American Lagers"
:laboratory "White Labs"
:attenuation 0.765
:notes "Produces \"California Common\"style beer."
:flocculation "High"
:form "Liquid"
:product-id "WLP810"}))
(def wlp815-belgian-lager-yeast
(yeasts/build-yeasts :wlp815-belgian-lager-yeast {:min-temperature 10.0
:name "WLP815 Belgian Lager Yeast"
:max-temperature 12.78
:type "Lager"
:best-for "European style pilsners, dark lagers, Vienna lager, and American style lagers"
:laboratory "White Labs"
:attenuation 0.765
:notes "Clean, crisp European lager yeast with low sulfur production. The strain originates from a very old brewery in West Belgium. Great for European style pilsners, dark lagers, Vienna lager, and American style lagers. "
:flocculation "Medium"
:form "Liquid"
:product-id "WLP815"}))
(def wlp820-octoberfest-marzen-lager
(yeasts/build-yeasts :wlp820-octoberfest-marzen-lager {:min-temperature 11.11
:name "WLP820 Octoberfest/Marzen Lager"
:max-temperature 14.44
:type "Lager"
:best-for "Marzen, Oktoberfest, European Lagers, Bocks, Munich Helles"
:laboratory "White Labs"
:attenuation 0.765
:notes "Produces a malty, bock style beer. Does not finish as dry or as fast as White's German Lager yeast. Longer lagering or starter recommended."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP820"}))
(def wlp830-german-lager
(yeasts/build-yeasts :wlp830-german-lager {:min-temperature 10.0
:name "WLP830 German Lager"
:max-temperature 12.78
:type "Lager"
:best-for "German Marzen, Pilsner, Lagers, Oktoberfest beers."
:laboratory "White Labs"
:attenuation 0.765
:notes "Very malty and clean. One of the world's most popular lager yeasts."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP830"}))
(def wlp833-german-bock-lager
(yeasts/build-yeasts :wlp833-german-bock-lager {:min-temperature 8.89
:name "WLP833 German Bock Lager"
:max-temperature 12.78
:type "Lager"
:best-for "Bocks, Doppelbocks, Oktoberfest, Vienna, Helles, some American Pilsners"
:laboratory "White Labs"
:attenuation 0.765
:notes "Produces beer that has balanced malt and hop character. From Southern Bavaria."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP833"}))
(def wlp838-southern-german-lager
(yeasts/build-yeasts :wlp838-southern-german-lager {:min-temperature 10.0
:name "WLP838 Southern German Lager"
:max-temperature 12.78
:type "Lager"
:best-for "German Pilsner, Helles, Oktoberfest, Marzen, Bocks"
:laboratory "White Labs"
:attenuation 0.765
:notes "Malty finish and balanced aroma. Strong fermenter, slight sulfur and low diacetyl."
:flocculation "High"
:form "Liquid"
:product-id "WLP838"}))
(def wlp840-american-lager-yeast
(yeasts/build-yeasts :wlp840-american-lager-yeast {:min-temperature 10.0
:name "WLP840 American Lager Yeast"
:max-temperature 12.78
:type "Lager"
:best-for "All American Style Lagers -- both light and dark."
:laboratory "White Labs"
:attenuation 0.765
:notes "Dry and clean with very slight apple fruitiness. Minimal sulfer and diacetyl."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP840"}))
(def wlp860-munich-helles
(yeasts/build-yeasts :wlp860-munich-helles {:min-temperature 8.89
:name "WLP860 Munich Helles"
:max-temperature 11.11
:type "Ale"
:best-for "Munich Helles, Oktoberfest"
:laboratory "White Labs"
:attenuation 0.765
:notes "Possible Augustiner Strain? This yeast helps to produce a malty, but balanced traditional Munich-style lager. Clean and strong fermenter, it's great for a variety of lager styles ranging from Helles to Rauchbier."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP860"}))
(def wlp862-cry-havoc
(yeasts/build-yeasts :wlp862-cry-havoc {:min-temperature 20.0
:name "WLP862 Cry Havoc"
:max-temperature 23.33
:type "Lager"
:best-for "All American Style Lagers -- both light and dark."
:laboratory "White Labs"
:attenuation 0.765
:notes "Licensed by White Labs from Charlie Papazian, author of \"The Complete Joy of Home Brewing\". This yeast was used to brew many of his original recipes. Diverse strain can ferment at ale and lager temps."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP862"}))
(def wlp885-zurich-lager
(yeasts/build-yeasts :wlp885-zurich-lager {:min-temperature 10.0
:name "WLP885 Zurich Lager"
:max-temperature 12.78
:type "Lager"
:best-for "Swiss style lager, and high gravity lagers (over 11% ABV)"
:laboratory "White Labs"
:attenuation 0.765
:notes "Swiss style lager yeast. Sulfer and diacetyl production is minimal. May be used for high gravity lagers with proper care."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP885"}))
(def wlp920-old-bavarian-lager
(yeasts/build-yeasts :wlp920-old-bavarian-lager {:min-temperature 10.0
:name "WLP920 Old Bavarian Lager"
:max-temperature 12.78
:type "Lager"
:best-for "Oktoberfest, Marzen, Bock and Dark Lagers."
:laboratory "White Labs"
:attenuation 0.765
:notes "Southern Germany/Bavarian lager yeast. Finishes malty with a slight ester profile."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP920"}))
(def wlp940-mexican-lager
(yeasts/build-yeasts :wlp940-mexican-lager {:min-temperature 10.0
:name "WLP940 Mexican Lager"
:max-temperature 12.78
:type "Lager"
:best-for "Mexican style light and dark lagers."
:laboratory "White Labs"
:attenuation 0.765
:notes "From Mexico City - produces a clean lager beer with a crisp finish. Good for mexican style beers."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP940"}))
(def white-labs
(merge wlp001-california-ale wlp002-english-ale wlp003-german-ale-ii wlp004-irish-ale-yeast wlp005-british-ale wlp006-bedford-british-ale wlp007-dry-english-ale
wlp008-east-coast-ale wlp009-australian-ale-yeast wlp011-european-ale wlp013-london-ale wlp022-essex-ale-yeast wlp023-burton-ale wlp025-southwold-ale
wlp026-premium-bitter-ale wlp028-edinburgh-ale wlp029-german-ale-kolsch wlp033-klassic-ale-yeast wlp036-dusseldorf-alt-yeast wlp037-yorkshire-square-ale-yeast
wlp038-manchester-ale-yeast wlp039-nottingham-ale-yeast wlp041-pacific-ale wlp051-california-ale-v wlp060-american-ale-yeast-blend wlp080-cream-ale-yeast-blend
wlp090-san-diego-super-yeast wlp099-super-high-gravity-ale wlp300-hefeweizen-ale wlp320-american-hefeweizen-ale wlp351-bavarian-weizen-yeast wlp380-hefeweizen-iv-ale
wlp400-belgian-wit-ale wlp410-belgian-wit-ii wlp500-trappist-ale wlp510-bastogne-belgian-ale wlp515-antwerp-ale-yeast wlp530-abbey-ale wlp540-abbey-iv-ale-yeast
wlp545-belgian-strong-ale-yeast wlp550-belgian-ale wlp565-belgian-saison-i-ale wlp566-belgian-saison-ii-yeast wlp568-belgian-style-saison-ale-yeast-blend
wlp570-belgian-golden-ale wlp575-belgian-style-ale-yeast-blend wlp630-berliner-weisse-blend wlp645-brettanomyces-claussenii wlp650-brettanomyces-bruxellensis
wlp653-brettanomyces-lambicus wlp655-belgian-sour-mix-1 wlp670-american-farmhouse-blend wlp675-malolactic-bacteria wlp677-lactobacillus-bacteria
wlp700-flor-sherry-yeast wlp705-sake-yeast wlp715-champagne-yeast wlp718-avize-wine-yeast wlp720-sweet-mead-wine wlp727-steinberg-geisenheim-wine
wlp730-chardonnay-white-wine-yeast wlp735-french-white-wine-yeast wlp740-merlot-red-wine-yeast wlp749-assmanshausen-wine-yeast
wlp750-french-red-wine-yeast wlp760-cabernet-red-wine-yeast wlp770-suremain-burgundy-wine-yeast wlp775-english-cider-yeast
wlp800-pilsner-lager wlp802-czech-budejovice-lager wlp810-san-francisco-lager wlp815-belgian-lager-yeast wlp820-octoberfest-marzen-lager
wlp830-german-lager wlp833-german-bock-lager wlp838-southern-german-lager wlp840-american-lager-yeast wlp860-munich-helles wlp862-cry-havoc
wlp885-zurich-lager wlp920-old-bavarian-lager wlp940-mexican-lager))
| 122446 | (ns common-beer-format.data.yeasts.white-labs
"Data for yeasts cultivated by White Labs"
(:require [common-beer-format.data.yeasts.yeasts :as yeasts]))
(def wlp001-california-ale
(yeasts/build-yeasts :wlp001-california-ale {:min-temperature 20.0
:name "WLP001 California Ale"
:max-temperature 22.78
:type "Ale"
:best-for "American Style Ales, Ambers, Pale Ales, Brown Ale, Strong Ale"
:laboratory "White Labs"
:attenuation 0.765
:notes "Very clean flavor, balance and stability. Accentuates hop flavor Versitile - can be used to make any style ale."
:flocculation "High"
:form "Liquid"
:product-id "WLP001"}))
(def wlp002-english-ale
(yeasts/build-yeasts :wlp002-english-ale {:min-temperature 18.33
:name "WLP002 English Ale"
:max-temperature 20.0
:type "Ale"
:best-for "English Pale Ale, ESB, India Pale Ale, Brown Ale, Porter, Sweet Stouts and Strong Ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Classic ESB strain best for English style milds, bitters, porters and English style stouts. Leaves a clear beer with some residual sweetness."
:flocculation "Very High"
:form "Liquid"
:product-id "WLP002"}))
(def wlp003-german-ale-ii
(yeasts/build-yeasts :wlp003-german-ale-ii {:min-temperature 18.33
:name "WLP003 German Ale II"
:max-temperature 21.11
:type "Ale"
:best-for "Kolsch, Alt and German Pale Ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Strong sulfer component will reduce with aging. Clean flavor, but with more ester production than regular German Ale Yeast."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP003"}))
(def wlp004-irish-ale-yeast
(yeasts/build-yeasts :wlp004-irish-ale-yeast {:min-temperature 18.33
:name "WLP004 Irish Ale Yeast"
:max-temperature 20.0
:type "Ale"
:best-for "Irish Ales, Stouts, Porters, Browns, Reds and Pale Ale"
:laboratory "White Labs"
:attenuation 0.765
:notes "Excellent for Irish Stouts. Produces slight hint of diacetyl balanced by a light fruitiness and a slightly dry crispness."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP004"}))
(def wlp005-british-ale
(yeasts/build-yeasts :wlp005-british-ale {:min-temperature 19.44
:name "WLP005 British Ale"
:max-temperature 23.33
:type "Ale"
:best-for "Excellent for all English style ales including bitters, pale ale, porters and brown ale."
:laboratory "White Labs"
:attenuation 0.765
:notes "This yeast has higher attenuation than the White Labs English Ale yeast strains. Produces a malty flavored beer."
:flocculation "High"
:form "Liquid"
:product-id "WLP005"}))
(def wlp006-bedford-british-ale
(yeasts/build-yeasts :wlp006-bedford-british-ale {:min-temperature 18.33
:name "WLP006 Bedford British Ale"
:max-temperature 21.11
:type "Ale"
:best-for "English style ales - bitter, pale, porter and brown ale"
:laboratory "White Labs"
:attenuation 0.765
:notes "High attenuation. Ferments dry with high flocculation. Distinctive ester profile. Good for most English ale styles."
:flocculation "High"
:form "Liquid"
:product-id "WLP006"}))
(def wlp007-dry-english-ale
(yeasts/build-yeasts :wlp007-dry-english-ale {:min-temperature 18.33
:name "WLP007 Dry English Ale"
:max-temperature 21.11
:type "Ale"
:best-for "Pale Ales, Amber, ESB, Brown Ales, Strong Ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Clean, Highly flocculant, and highly attentive yeast. Similar to White labs English Ale yeast, but more attentive. Suitable for high gravity ales."
:flocculation "High"
:form "Liquid"
:product-id "WLP007"}))
(def wlp008-east-coast-ale
(yeasts/build-yeasts :wlp008-east-coast-ale {:min-temperature 20.0
:name "WLP008 East Coast Ale"
:max-temperature 22.78
:type "Ale"
:best-for "American Ales, Golden ales, Blonde Ale, Pale Ale and German Alt styles"
:laboratory "White Labs"
:attenuation 0.765
:notes "White labs \"Brewer Patriot\"strain can be used to reproduce many of the American versions of classic beer styles. Very clean with low esters. "
:flocculation "Low"
:form "Liquid"
:product-id "WLP008"}))
(def wlp009-australian-ale-yeast
(yeasts/build-yeasts :wlp009-australian-ale-yeast {:min-temperature 18.33
:name "WLP009 Australian Ale Yeast"
:max-temperature 21.11
:type "Ale"
:best-for "Australian Ales, English Ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "White Labs entry for Australian Ales. Produces a clean, malty finish with pleasant ester character. Bready character. Can ferment clean at high temperatures."
:flocculation "High"
:form "Liquid"
:product-id "WLP009"}))
(def wlp011-european-ale
(yeasts/build-yeasts :wlp011-european-ale {:min-temperature 18.33
:name "WLP011 European Ale"
:max-temperature 21.11
:type "Ale"
:best-for "Alt, Kolsch, malty English Ales, Fruit beers"
:laboratory "White Labs"
:attenuation 0.765
:notes "Malty, Northern European ale yeast. Low ester production, low sulfer, gives a clean profile. Low attenuation contributes to malty taste."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP011"}))
(def wlp013-london-ale
(yeasts/build-yeasts :wlp013-london-ale {:min-temperature 18.89
:name "WLP013 London Ale"
:max-temperature 21.67
:type "Ale"
:best-for "Classic British Pale Ales, Bitters and Stouts"
:laboratory "White Labs"
:attenuation 0.765
:notes "Dry, malty ale yeast. Produces a complex, oak flavored ester character. Hop bitterness comes through well."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP013"}))
(def wlp022-essex-ale-yeast
(yeasts/build-yeasts :wlp022-essex-ale-yeast {:min-temperature 18.89
:name "WLP022 Essex Ale Yeast"
:max-temperature 21.11
:type "Ale"
:best-for "British milds, pale ales, bitters, stouts."
:laboratory "White Labs"
:attenuation 0.765
:notes "Flavorful British yeast with a drier finish than many ale yeasts. Bready and fruity in character. Well suited for top cropping (collecting). Does not flocculate as much as WLP005 or WLP002."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP022"}))
(def wlp023-burton-ale
(yeasts/build-yeasts :wlp023-burton-ale {:min-temperature 20.0
:name "WLP023 Burton Ale"
:max-temperature 22.78
:type "Ale"
:best-for "All English styles including Pale Ale, IPA, Porter, Stout and Bitters."
:laboratory "White Labs"
:attenuation 0.765
:notes "Burton-on-trent yeast produces a complex character. Flavors include apple, pear, and clover honey."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP023"}))
(def wlp025-southwold-ale
(yeasts/build-yeasts :wlp025-southwold-ale {:min-temperature 18.89
:name "WLP025 Southwold Ale"
:max-temperature 20.56
:type "Ale"
:best-for "British bitters and pale ales."
:laboratory "White Labs"
:attenuation 0.765
:notes "From Suffolk county. Products complex fruity and citrus flavors. Slight sulfer production, but this will fade with aging."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP025"}))
(def wlp026-premium-bitter-ale
(yeasts/build-yeasts :wlp026-premium-bitter-ale {:min-temperature 19.44
:name "WLP026 Premium Bitter Ale"
:max-temperature 21.11
:type "Ale"
:best-for "All English ales including bitters, milds, ESB, Porter, Stout and Barley Wine"
:laboratory "White Labs"
:attenuation 0.765
:notes "From Staffordshire England. Mild, but complex estery flavor. High attenuation - ferments strong and dry. Suitable for high gravity beers."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP026"}))
(def wlp028-edinburgh-ale
(yeasts/build-yeasts :wlp028-edinburgh-ale {:min-temperature 18.33
:name "WLP028 Edinburgh Ale"
:max-temperature 21.11
:type "Ale"
:best-for "Strong Scottish style ales, ESB, Irish Reds"
:laboratory "White Labs"
:attenuation 0.765
:notes "Malty strong ale yeast. Reproduces complex, malty, flavorful schottish ales. Hop character comes through well."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP028"}))
(def wlp029-german-ale-kolsch
(yeasts/build-yeasts :wlp029-german-ale-kolsch {:min-temperature 18.33
:name "WLP029 German Ale/Kolsch"
:max-temperature 20.56
:type "Ale"
:best-for "Kolsch, Altbiers, Pale Ales, Blonde and Honey Ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Great for light beers. Accentuates hop flavors. Slight sulfer flavor will fade with age and leave a clean, lager like ale."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP029"}))
(def wlp033-klassic-ale-yeast
(yeasts/build-yeasts :wlp033-klassic-ale-yeast {:min-temperature 18.89
:name "WLP033 Klassic Ale Yeast"
:max-temperature 21.11
:type "Ale"
:best-for "Bitters, milds, porters stouts and scottish ale styles."
:laboratory "White Labs"
:attenuation 0.765
:notes "Traditional English Ale style yeast. Produces ester character, and allows hop flavor through. Leaves a slightly sweet malt character in ales."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP033"}))
(def wlp036-dusseldorf-alt-yeast
(yeasts/build-yeasts :wlp036-dusseldorf-alt-yeast {:min-temperature 18.33
:name "WLP036 Dusseldorf Alt Yeast"
:max-temperature 20.56
:type "Ale"
:best-for "Alt biers, Dusseldorf Alts, German Ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Traditional Alt yeast from Dusseldorf, Germany. Produces clean, slightly sweet alt beers. Does not accentuate hop flavor like WLP029 does."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP036"}))
(def wlp037-yorkshire-square-ale-yeast
(yeasts/build-yeasts :wlp037-yorkshire-square-ale-yeast {:min-temperature 18.33
:name "WLP037 Yorkshire Square Ale Yeast"
:max-temperature 20.56
:type "Ale"
:best-for "English pale ales, English brown ales and Mild ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "This yeast produces a malty but well balanced profile. Expect toasty flavors with malt driven esters. Highly flocculent and a good choice for many English ales."
:flocculation "High"
:form "Liquid"
:product-id "WLP037"}))
(def wlp038-manchester-ale-yeast
(yeasts/build-yeasts :wlp038-manchester-ale-yeast {:min-temperature 18.33
:name "WLP038 Manchester Ale Yeast"
:max-temperature 21.11
:type "Ale"
:best-for "English style ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Top fermenting strain that is good for top-cropping. Moderately flocculent with a clean, dry finish. Low ester profile for producing a balanced English ale."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP038"}))
(def wlp039-nottingham-ale-yeast
(yeasts/build-yeasts :wlp039-nottingham-ale-yeast {:min-temperature 18.89
:name "WLP039 Nottingham Ale Yeast"
:max-temperature 21.11
:type "Ale"
:best-for "British ales, pale ales, ambers, porters and stouts."
:laboratory "White Labs"
:attenuation 0.765
:notes "British style of ale yeast with a very dry finish and high attenuation. Medium to low fruit and fusel alcohol production. Good top fermenting yeast for cropping. "
:flocculation "Medium"
:form "Liquid"
:product-id "WLP039"}))
(def wlp041-pacific-ale
(yeasts/build-yeasts :wlp041-pacific-ale {:min-temperature 18.33
:name "WLP041 Pacific Ale"
:max-temperature 20.0
:type "Ale"
:best-for "English & American ales including milds, bitters, IPA, porters and English stouts."
:laboratory "White Labs"
:attenuation 0.765
:notes "Popular yeast from the Pacific Northwest. Leaves a clear and malty profile. More fruity than WLP002. Suitable for many English and American styles."
:flocculation "High"
:form "Liquid"
:product-id "WLP041"}))
(def wlp051-california-ale-v
(yeasts/build-yeasts :wlp051-california-ale-v {:min-temperature 18.89
:name "WLP051 California Ale V"
:max-temperature 21.11
:type "Ale"
:best-for "American style Pales, Ambers, Browns, IPAs, American Strong Ale"
:laboratory "White Labs"
:attenuation 0.765
:notes "Similar to White Labs California Ale Yeast, but slightly lower attenuation leaves a fuller bodied beer."
:flocculation "High"
:form "Liquid"
:product-id "WLP051"}))
(def wlp060-american-ale-yeast-blend
(yeasts/build-yeasts :wlp060-american-ale-yeast-blend {:min-temperature 20.0
:name "WLP060 American Ale Yeast Blend"
:max-temperature 22.22
:type "Ale"
:best-for "American ales with clean finish"
:laboratory "White Labs"
:attenuation 0.765
:notes "A blend that celebrates WLP001 (California Ale Yeast's) clean, neutral fermentation. This strain is versatile and adds two other yeast strains that are also clean/neutral in flavor to add a bit of complexity - almost a lager like finish. Slight sulfur m"
:flocculation "Medium"
:form "Liquid"
:product-id "WLP060"}))
(def wlp080-cream-ale-yeast-blend
(yeasts/build-yeasts :wlp080-cream-ale-yeast-blend {:min-temperature 18.33
:name "WLP080 Cream Ale Yeast Blend"
:max-temperature 21.11
:type "Ale"
:best-for "Cream Ale, Hybrids"
:laboratory "White Labs"
:attenuation 0.765
:notes "A blend of ale and lager yeast strains that work together to create a clean, light American lager style ale. A pleasing estery aroma may be perceived. Hop flavors and bitterness are slightly subdued. Slight sulfer will be produced during fermentation f"
:flocculation "Medium"
:form "Liquid"
:product-id "WLP080"}))
(def wlp090-san-diego-super-yeast
(yeasts/build-yeasts :wlp090-san-diego-super-yeast {:min-temperature 18.33
:name "WLP090 San Diego Super Yeast"
:max-temperature 20.0
:type "Ale"
:best-for "IPAs, American ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "A super clean, super-fast fermenting strain. A low ester-producing strain that results in a balanced, neutral flavor and aroma profile. Alcohol-tolerant and very versatile for a wide variety of styles. Similar to California Ale Yeast WLP001 but it generally ferments faster."
:flocculation "Very High"
:form "Liquid"
:product-id "WLP090"}))
(def wlp099-super-high-gravity-ale
(yeasts/build-yeasts :wlp099-super-high-gravity-ale {:min-temperature 20.56
:name "WLP099 Super High Gravity Ale"
:max-temperature 23.33
:type "Ale"
:best-for "Very high gravity beers and barley wine up to 25% alcohol."
:laboratory "White Labs"
:attenuation 0.765
:notes "Ferments up to 25% alcohol content. Flavor may vary greatly depending on beer alcohol. English like esters at low gravity, but will become more wine-like as alcohol exceeds 16% ABV. Refer to White Labs web page for tips on fermenting high gravity ales."
:flocculation "Low"
:form "Liquid"
:product-id "WLP099"}))
(def wlp300-hefeweizen-ale
(yeasts/build-yeasts :wlp300-hefeweizen-ale {:min-temperature 20.0
:name "WLP300 Hefeweizen Ale"
:max-temperature 22.22
:type "Wheat"
:best-for "German style wheat beers. Weiss, Weizen, Hefeweizen"
:laboratory "White Labs"
:attenuation 0.765
:notes "Produces the banana and clove nose traditionally associated with German Wheat beers. Also produces desired cloudy look."
:flocculation "Low"
:form "Liquid"
:product-id "WLP300"}))
(def wlp320-american-hefeweizen-ale
(yeasts/build-yeasts :wlp320-american-hefeweizen-ale {:min-temperature 18.33
:name "WLP320 American Hefeweizen Ale"
:max-temperature 20.56
:type "Wheat"
:best-for "Oregon style American Hefeweizen"
:laboratory "White Labs"
:attenuation 0.765
:notes "Produces a much smaller amount of clove and banana flavor than the German Hefeweizen White Labs yeast. Some sulfur, and creates desired cloudy look."
:flocculation "Low"
:form "Liquid"
:product-id "WLP320"}))
(def wlp351-bavarian-weizen-yeast
(yeasts/build-yeasts :wlp351-bavarian-weizen-yeast {:min-temperature 18.89
:name "WLP351 Bavarian Weizen Yeast"
:max-temperature 21.11
:type "Wheat"
:best-for "Bavarian Weizen and wheat beers."
:laboratory "White Labs"
:attenuation 0.765
:notes "Former yeast lab W51 strain. Produces a classic German style wheat beer with moderately high, spicy, phenolic overtones reminiscent of cloves."
:flocculation "Low"
:form "Liquid"
:product-id "WLP351"}))
(def wlp380-hefeweizen-iv-ale
(yeasts/build-yeasts :wlp380-hefeweizen-iv-ale {:min-temperature 18.89
:name "WLP380 Hefeweizen IV Ale"
:max-temperature 21.11
:type "Wheat"
:best-for "German style Hefeweizen"
:laboratory "White Labs"
:attenuation 0.765
:notes "Large clove and phenolic aroma, but with minimal banana flavor. Citrus and apricot notes. Crisp and drinkable, with some sulfur production."
:flocculation "Low"
:form "Liquid"
:product-id "WLP380"}))
(def wlp400-belgian-wit-ale
(yeasts/build-yeasts :wlp400-belgian-wit-ale {:min-temperature 19.44
:name "WLP400 Belgian Wit Ale"
:max-temperature 23.33
:type "Wheat"
:best-for "Belgian Wit"
:laboratory "White Labs"
:attenuation 0.765
:notes "Phenolic and tart. The original yeast used to produce Wit in Belgium."
:flocculation "Low"
:form "Liquid"
:product-id "WLP400"}))
(def wlp410-belgian-wit-ii
(yeasts/build-yeasts :wlp410-belgian-wit-ii {:min-temperature 19.44
:name "WLP410 Belgian Wit II"
:max-temperature 23.33
:type "Ale"
:best-for "Belgian Wit, Spiced Ale, Wheat Ales and Specialty Beers"
:laboratory "White Labs"
:attenuation 0.765
:notes "Less phenolic than WLP400 (Belgian Wit Ale) but more spicy. Leaves a little more sweetness and flocculation is higher than WLP400."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP410"}))
(def wlp500-trappist-ale
(yeasts/build-yeasts :wlp500-trappist-ale {:min-temperature 18.33
:name "WLP500 Trappist Ale"
:max-temperature 22.22
:type "Ale"
:best-for "Trappist Ale, Dubbel, Trippel, Belgian Ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Distinctive fruitiness and plum characteristics. Excellent for high gravity beers."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP500"}))
(def wlp510-bastogne-belgian-ale
(yeasts/build-yeasts :wlp510-bastogne-belgian-ale {:min-temperature 18.89
:name "WLP510 Bastogne Belgian Ale"
:max-temperature 22.22
:type "Ale"
:best-for "High gravity beers, Belgian ales, Dubbels, Trippels."
:laboratory "White Labs"
:attenuation 0.765
:notes "High gravity Trappist ale yeast. Creates a dry beer with a slightly acidic finish. Cleaner finish and slightly less spicy than WLP500 or WLP530. "
:flocculation "Medium"
:form "Liquid"
:product-id "WLP510"}))
(def wlp515-antwerp-ale-yeast
(yeasts/build-yeasts :wlp515-antwerp-ale-yeast {:min-temperature 19.44
:name "WLP515 Antwerp Ale Yeast"
:max-temperature 21.11
:type "Ale"
:best-for "Belgian pale and amber ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Clean, almost lager like Belgian ale yeast. Good for Belgian pale and amber ales or with other Belgian yeasts in a blend. Biscuity, ale like aroma present. Hop flavors are accentuated. Slight sulfur during fermentation, and a lager like flavor profile"
:flocculation "Medium"
:form "Liquid"
:product-id "WLP515"}))
(def wlp530-abbey-ale
(yeasts/build-yeasts :wlp530-abbey-ale {:min-temperature 18.89
:name "WLP530 Abbey Ale"
:max-temperature 22.22
:type "Ale"
:best-for "Belgian Trappist Ale, Spiced Ale, Trippel, Dubbel, Grand Cru"
:laboratory "White Labs"
:attenuation 0.765
:notes "Used in two of six remaining Trappist breweries. Distinctive plum and fruitiness. Good for high gravity beers."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP530"}))
(def wlp540-abbey-iv-ale-yeast
(yeasts/build-yeasts :wlp540-abbey-iv-ale-yeast {:min-temperature 18.89
:name "WLP540 Abbey IV Ale Yeast"
:max-temperature 22.22
:type "Ale"
:best-for "Trappist Belgian Ales, Dubbels, Tripels and Specialty ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "An authentic Trappist style ale yeast. Use for Belgian ales including abbey ales (dubbels, tripels). Fruit character is medium - between WLP500 (high) and WLP530 (low)"
:flocculation "Medium"
:form "Liquid"
:product-id "WLP540"}))
(def wlp545-belgian-strong-ale-yeast
(yeasts/build-yeasts :wlp545-belgian-strong-ale-yeast {:min-temperature 18.33
:name "WLP545 Belgian Strong Ale Yeast"
:max-temperature 22.78
:type "Ale"
:best-for "Belgian dark strongs, Abbey ales and Christmas beers"
:laboratory "White Labs"
:attenuation 0.765
:notes "From the Ardennes region of Belgium, this classic strain produces moderate esters and spicy phenolic character. Results in a dry but balanced finish. Use for dark or strong abbey ales."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP545"}))
(def wlp550-belgian-ale
(yeasts/build-yeasts :wlp550-belgian-ale {:min-temperature 20.0
:name "WLP550 Belgian Ale"
:max-temperature 25.56
:type "Ale"
:best-for "Belgian Ales, Saisons, Belgian Reds, Belgian Browns, White beers"
:laboratory "White Labs"
:attenuation 0.765
:notes "Phenolic and spicy flavors. Complex profile, with less fruitiness than White's Trappist Ale strain."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP550"}))
(def wlp565-belgian-saison-i-ale
(yeasts/build-yeasts :wlp565-belgian-saison-i-ale {:min-temperature 20.0
:name "WLP565 Belgian Saison I Ale"
:max-temperature 23.89
:type "Ale"
:best-for "Saison Ale, Belgian Ale, Dubbel, Trippel"
:laboratory "White Labs"
:attenuation 0.765
:notes "Saison yeast from Wallonia. Earthy, spicy and peppery notes. Slightly sweet."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP565"}))
(def wlp566-belgian-saison-ii-yeast
(yeasts/build-yeasts :wlp566-belgian-saison-ii-yeast {:min-temperature 20.0
:name "WLP566 Belgian Saison II Yeast"
:max-temperature 25.56
:type "Ale"
:best-for "Belgian or French Saison"
:laboratory "White Labs"
:attenuation 0.765
:notes "Saison strain with a more fruity ester profile than WLP565 (Belgian Saison I Yeast). Moderately phenolic with a clove-like characteristic in finished beer flavor and aroma. Ferments quickly."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP566"}))
(def wlp568-belgian-style-saison-ale-yeast-blend
(yeasts/build-yeasts :wlp568-belgian-style-saison-ale-yeast-blend {:min-temperature 21.11
:name "WLP568 Belgian Style Saison Ale Yeast Blend"
:max-temperature 26.67
:type "Ale"
:best-for "Belgian and French Saison"
:laboratory "White Labs"
:attenuation 0.765
:notes "This blend melds Belgian style ale and Saison strains. The strains work in harmony to create complex, fruity aromas and flavors. The blend of yeast strains encourages complete fermentation in a timely manner. Phenolic, spicy, earthy, and clove like flavor"
:flocculation "Medium"
:form "Liquid"
:product-id "WLP568"}))
(def wlp570-belgian-golden-ale
(yeasts/build-yeasts :wlp570-belgian-golden-ale {:min-temperature 20.0
:name "WLP570 Belgian Golden Ale"
:max-temperature 23.89
:type "Ale"
:best-for "Belgian Ales, Dubbel, Grand Cru, Belgian Holiday Ale"
:laboratory "White Labs"
:attenuation 0.765
:notes "Combination of fruitiness and phenolic characters dominate the profile. Some sulfur which will dissapate following fermentation."
:flocculation "Low"
:form "Liquid"
:product-id "WLP570"}))
(def wlp575-belgian-style-ale-yeast-blend
(yeasts/build-yeasts :wlp575-belgian-style-ale-yeast-blend {:min-temperature 20.0
:name "WLP575 Belgian Style Ale Yeast Blend"
:max-temperature 23.89
:type "Ale"
:best-for "Trappist and other Belgian ales."
:laboratory "White Labs"
:attenuation 0.765
:notes "Blend of two trappist ale yeasts and one Belgian ale yeast. Creates a versatile blend to be used for Trappist and other Belgian style ales."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP575"}))
(def wlp630-berliner-weisse-blend
(yeasts/build-yeasts :wlp630-berliner-weisse-blend {:min-temperature 20.0
:name "WLP630 Berliner Weisse Blend"
:max-temperature 22.22
:type "Wheat"
:best-for "Berliner Weisse"
:laboratory "White Labs"
:attenuation 0.765
:notes "A blend of a traditional German Weizen yeast and Lactobacillus to create a subtle, tart, drinkable beer. Can take several months to develop tart character. Perfect for traditional Berliner Weisse."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP630"}))
(def wlp645-brettanomyces-claussenii
(yeasts/build-yeasts :wlp645-brettanomyces-claussenii {:min-temperature 18.33
:name "WLP645 Brettanomyces Claussenii"
:max-temperature 22.22
:type "Ale"
:best-for "Sour ales (in secondary)"
:laboratory "White Labs"
:attenuation 0.765
:notes "Low intensity Brett character. Originally isolated from strong English stock beer, in the early 20th century. The Brett flavors produced are more subtle than WLP650 and WLP653. More aroma than flavor contribution. Fruity, pineapple like aroma."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP645"}))
(def wlp650-brettanomyces-bruxellensis
(yeasts/build-yeasts :wlp650-brettanomyces-bruxellensis {:min-temperature 18.33
:name "WLP650 Brettanomyces Bruxellensis"
:max-temperature 22.22
:type "Ale"
:best-for "Belgian sour ales and labics (in secondary)"
:laboratory "White Labs"
:attenuation 0.765
:notes "Medium intensity Brett character. Classic strain used in secondary fermentation for Belgian style beers and lambics. One Trappist brewery uses this strain in secondary fermentation."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP650"}))
(def wlp653-brettanomyces-lambicus
(yeasts/build-yeasts :wlp653-brettanomyces-lambicus {:min-temperature 18.33
:name "WLP653 Brettanomyces Lambicus"
:max-temperature 22.22
:type "Ale"
:best-for "Lambics and Flanders/Sour Brown ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Use in secondary. High intensity Brett character. Defines the \"Brett character\": Horsey, smoky and spicy flavors. As the name suggests, this strain is found most often in Lambic style beers, which are spontaneously fermented beers."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP653"}))
(def wlp655-belgian-sour-mix-1
(yeasts/build-yeasts :wlp655-belgian-sour-mix-1 {:min-temperature 18.33
:name "WLP655 Belgian Sour Mix 1"
:max-temperature 22.22
:type "Ale"
:best-for "Belgian sour beers (in secondary)"
:laboratory "White Labs"
:attenuation 0.765
:notes "Note: Bacteria to use in secondary only. A unique blend perfect for Belgian style beers. Includes Brettanomyces, Saccharomyces, and the bacterial strains Lactobacillus and Pediococcus."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP655"}))
(def wlp670-american-farmhouse-blend
(yeasts/build-yeasts :wlp670-american-farmhouse-blend {:min-temperature 20.0
:name "WLP670 American Farmhouse Blend"
:max-temperature 22.22
:type "Ale"
:best-for "Saisons, Farmhouse Ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Inspired by local American brewers crafting semi- traditional Belgian-style ales. This blend creates a complex flavor profile with a moderate level of sourness. It consists of a traditional farmhouse yeast strain and Brettanomyces. Great yeast for farmho"
:flocculation "Medium"
:form "Liquid"
:product-id "WLP670"}))
(def wlp675-malolactic-bacteria
(yeasts/build-yeasts :wlp675-malolactic-bacteria {:min-temperature 18.33
:name "WLP675 Malolactic Bacteria"
:max-temperature 22.22
:type "Ale"
:best-for "Primarily wine"
:laboratory "White Labs"
:attenuation 0.765
:notes "Bacteria for use in secondary. Malolactic fermentation is the conversion of malic acid to lactic acid by bacteria from the lactic acid bacteria family. Lactic acid is less acidic than malic acid, which in turn decreases acidity and helps to soften and/o"
:flocculation "Medium"
:form "Liquid"
:product-id "WLP675"}))
(def wlp677-lactobacillus-bacteria
(yeasts/build-yeasts :wlp677-lactobacillus-bacteria {:min-temperature 18.33
:name "WLP677 Lactobacillus Bacteria"
:max-temperature 22.22
:type "Ale"
:best-for "Lambic, Berliner Weiss, Sour Brown and Gueze (secondary)"
:laboratory "White Labs"
:attenuation 0.765
:notes "Bacteria for use in secondary. This lactic acid bacteria produces moderate levels of acidity and sour flavors found in lambics, Berliner Weiss, sour brown ale and gueze."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP677"}))
(def wlp700-flor-sherry-yeast
(yeasts/build-yeasts :wlp700-flor-sherry-yeast {:min-temperature 21.11
:name "WLP700 Flor Sherry Yeast"
:max-temperature 24.44
:type "Wine"
:best-for "Sherry wine yeast"
:laboratory "White Labs"
:attenuation 0.765
:notes "This yeast develops a film (flor) on the surface of the wine. Creates green almond, granny smith and nougat characteristics found in sherry. Can also be used for Port, Madeira and other sweet styles. For use in secondary fermentation. Slow fermentor. Al"
:flocculation "Medium"
:form "Liquid"
:product-id "WLP700"}))
(def wlp705-sake-yeast
(yeasts/build-yeasts :wlp705-sake-yeast {:min-temperature 21.11
:name "WLP705 Sake Yeast"
:max-temperature 24.44
:type "Wine"
:best-for "Sake wine yeast"
:laboratory "White Labs"
:attenuation 0.765
:notes "For use in rice based fermentations. For sake, use this yeast in conjunction with Koji (to produce fermentable sugar). WLP705 produces full body sake character, and subtle fragrance. Alcohol tolerance to 16%."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP705"}))
(def wlp715-champagne-yeast
(yeasts/build-yeasts :wlp715-champagne-yeast {:min-temperature 21.11
:name "WLP715 Champagne Yeast"
:max-temperature 23.89
:type "Champagne"
:best-for "Wine, Mead and Cider"
:laboratory "White Labs"
:attenuation 0.765
:notes "Can tolerate alcohol up to 17%. For Barley Wine or Meads."
:flocculation "Low"
:form "Liquid"
:product-id "WLP715"}))
(def wlp718-avize-wine-yeast
(yeasts/build-yeasts :wlp718-avize-wine-yeast {:min-temperature 15.56
:name "WLP718 Avize Wine Yeast"
:max-temperature 32.22
:type "Wine"
:best-for "Chardonnay"
:laboratory "White Labs"
:attenuation 0.765
:notes "Champagne isolate used for complexity in whites. Contributes elegance, especially in barrel fermented Chardonnays. Alcohol tolerance to 15%."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP718"}))
(def wlp720-sweet-mead-wine
(yeasts/build-yeasts :wlp720-sweet-mead-wine {:min-temperature 21.11
:name "WLP720 Sweet Mead/Wine"
:max-temperature 23.89
:type "Wine"
:best-for "Sweet Mead, Wine and Cider"
:laboratory "White Labs"
:attenuation 0.765
:notes "Lower attenuation than White Labs Champagne Yeast. Leaves some residual sweetness as well as fruity flavor. Alcohol concentration up to 15%."
:flocculation "Low"
:form "Liquid"
:product-id "WLP720"}))
(def wlp727-steinberg-geisenheim-wine
(yeasts/build-yeasts :wlp727-steinberg-geisenheim-wine {:min-temperature 10.0
:name "WLP727 Steinberg-Geisenheim Wine"
:max-temperature 32.22
:type "Wine"
:best-for "Riesling wines."
:laboratory "White Labs"
:attenuation 0.765
:notes "German origin wine yeast. High fruit/ester production. Moderate fermentation characteristics and cold tolerant."
:flocculation "Low"
:form "Liquid"
:product-id "WLP727"}))
(def wlp730-chardonnay-white-wine-yeast
(yeasts/build-yeasts :wlp730-chardonnay-white-wine-yeast {:min-temperature 10.0
:name "WLP730 Chardonnay White Wine Yeast"
:max-temperature 32.22
:type "Wine"
:best-for "Chardonnay Wine"
:laboratory "White Labs"
:attenuation 0.765
:notes "Dry wine yeast. Slight ester production, low sulfur dioxide production. Enhances varietal character. WLP730 is a good choice for all white and blush wines, including Chablis, Chenin Blanc, Semillon, and Sauvignon Blanc. Fermentation speed is moderate. Al"
:flocculation "Low"
:form "Liquid"
:product-id "WLP730"}))
(def wlp735-french-white-wine-yeast
(yeasts/build-yeasts :wlp735-french-white-wine-yeast {:min-temperature 15.56
:name "WLP735 French White Wine Yeast"
:max-temperature 32.22
:type "Wine"
:best-for "French white wines"
:laboratory "White Labs"
:attenuation 0.765
:notes "Classic yeast for white wine fermentation. Slow to moderate fermenter and foam producer. Gives an enhanced creamy texture. Alcohol Tolerance: 16%"
:flocculation "Low"
:form "Liquid"
:product-id "WLP735"}))
(def wlp740-merlot-red-wine-yeast
(yeasts/build-yeasts :wlp740-merlot-red-wine-yeast {:min-temperature 15.56
:name "WLP740 Merlot Red Wine Yeast"
:max-temperature 32.22
:type "Wine"
:best-for "Merlot, Shiraz, Pinot Noir, Chardonnay, Cabernet, Sauvignon Blanc, and Semillon"
:laboratory "White Labs"
:attenuation 0.765
:notes "Neutral, low fusel alcohol production. Will ferment to dryness, alcohol tolerance to 18%. Vigorous fermenter. WLP740 is well suited for Merlot, Shiraz, Pinot Noir, Chardonnay, Cabernet, Sauvignon Blanc, and Semillon. Alcohol Tolerance: 18%"
:flocculation "Low"
:form "Liquid"
:product-id "WLP740"}))
(def wlp749-assmanshausen-wine-yeast
(yeasts/build-yeasts :wlp749-assmanshausen-wine-yeast {:min-temperature 10.0
:name "WLP749 Assmanshausen Wine Yeast"
:max-temperature 32.22
:type "Wine"
:best-for "Pinot Noir and Zinfandel"
:laboratory "White Labs"
:attenuation 0.765
:notes "German red wine yeast, which results in spicy, fruit aromas. Perfect for Pinot Noir and Zinfandel. Slow to moderate fermenter which is cold tolerant. Alcohol Tolerance: 16%"
:flocculation "Low"
:form "Liquid"
:product-id "WLP749"}))
(def wlp750-french-red-wine-yeast
(yeasts/build-yeasts :wlp750-french-red-wine-yeast {:min-temperature 15.56
:name "WLP750 French Red Wine Yeast"
:max-temperature 32.22
:type "Wine"
:best-for "Bordeaux"
:laboratory "White Labs"
:attenuation 0.765
:notes "Classic Bordeaux yeast for red wine fermentations. Moderate fermentation characteristics. Tolerates lower fermentation temperatures. Rich, smooth flavor profile. Alcohol Tolerance: 17%"
:flocculation "Low"
:form "Liquid"
:product-id "WLP750"}))
(def wlp760-cabernet-red-wine-yeast
(yeasts/build-yeasts :wlp760-cabernet-red-wine-yeast {:min-temperature 15.56
:name "WLP760 Cabernet Red Wine Yeast"
:max-temperature 32.22
:type "Wine"
:best-for "<NAME>, <NAME>, <NAME>, <NAME>, and <NAME>"
:laboratory "White Labs"
:attenuation 0.765
:notes "High temperature tolerance. Moderate fermentation speed. Excellent for full-bodied red wines, ester production complements flavor. WLP760 is also suitable for <NAME>lot, Chardonnay, Chianti, <NAME>in Blanc, and Sauvignon Blanc. Alcohol Tolerance: 16%"
:flocculation "Low"
:form "Liquid"
:product-id "WLP760"}))
(def wlp770-suremain-burgundy-wine-yeast
(yeasts/build-yeasts :wlp770-suremain-burgundy-wine-yeast {:min-temperature 15.56
:name "WLP770 Suremain Burgundy Wine Yeast"
:max-temperature 32.22
:type "Wine"
:best-for "Burgundy"
:laboratory "White Labs"
:attenuation 0.765
:notes "Emphasizes fruit aromas in barrel fermentations. High nutrient requirement to avoid volatile acidity production. Alcohol Tolerance: 16%"
:flocculation "Low"
:form "Liquid"
:product-id "WLP770"}))
(def wlp775-english-cider-yeast
(yeasts/build-yeasts :wlp775-english-cider-yeast {:min-temperature 20.0
:name "WLP775 English Cider Yeast"
:max-temperature 23.89
:type "Wine"
:best-for "Cider, Wine and High Gravity Beer"
:laboratory "White Labs"
:attenuation 0.765
:notes "Classic Cider yeast. Ferments dry, but retains apple flavor. Some sulfer produced during fermentation will fade with age."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP775"}))
(def wlp800-pilsner-lager
(yeasts/build-yeasts :wlp800-pilsner-lager {:min-temperature 10.0
:name "WLP800 Pilsner Lager"
:max-temperature 12.78
:type "Lager"
:best-for "European Pilsners, Bohemian Pilsner"
:laboratory "White Labs"
:attenuation 0.765
:notes "Classic pilsner strain from Czech Republic. Dry with a malty finish."
:flocculation "High"
:form "Liquid"
:product-id "WLP800"}))
(def wlp802-czech-budejovice-lager
(yeasts/build-yeasts :wlp802-czech-budejovice-lager {:min-temperature 10.0
:name "WLP802 Czech Budejovice Lager"
:max-temperature 12.78
:type "Lager"
:best-for "Bohemian Style Pilsner"
:laboratory "White Labs"
:attenuation 0.765
:notes "Dry and crisp with low diacetyl production. From Southern Czech Republic."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP802"}))
(def wlp810-san-francisco-lager
(yeasts/build-yeasts :wlp810-san-francisco-lager {:min-temperature 14.44
:name "WLP810 San Francisco Lager"
:max-temperature 18.33
:type "Lager"
:best-for "California and Premium Lagers, all American Lagers"
:laboratory "White Labs"
:attenuation 0.765
:notes "Produces \"California Common\"style beer."
:flocculation "High"
:form "Liquid"
:product-id "WLP810"}))
(def wlp815-belgian-lager-yeast
(yeasts/build-yeasts :wlp815-belgian-lager-yeast {:min-temperature 10.0
:name "WLP815 Belgian Lager Yeast"
:max-temperature 12.78
:type "Lager"
:best-for "European style pilsners, dark lagers, Vienna lager, and American style lagers"
:laboratory "White Labs"
:attenuation 0.765
:notes "Clean, crisp European lager yeast with low sulfur production. The strain originates from a very old brewery in West Belgium. Great for European style pilsners, dark lagers, Vienna lager, and American style lagers. "
:flocculation "Medium"
:form "Liquid"
:product-id "WLP815"}))
(def wlp820-octoberfest-marzen-lager
(yeasts/build-yeasts :wlp820-octoberfest-marzen-lager {:min-temperature 11.11
:name "WLP820 Octoberfest/Marzen Lager"
:max-temperature 14.44
:type "Lager"
:best-for "Marzen, Oktoberfest, European Lagers, Bocks, Munich Helles"
:laboratory "White Labs"
:attenuation 0.765
:notes "Produces a malty, bock style beer. Does not finish as dry or as fast as White's German Lager yeast. Longer lagering or starter recommended."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP820"}))
(def wlp830-german-lager
(yeasts/build-yeasts :wlp830-german-lager {:min-temperature 10.0
:name "WLP830 German Lager"
:max-temperature 12.78
:type "Lager"
:best-for "German Marzen, Pilsner, Lagers, Oktoberfest beers."
:laboratory "White Labs"
:attenuation 0.765
:notes "Very malty and clean. One of the world's most popular lager yeasts."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP830"}))
(def wlp833-german-bock-lager
(yeasts/build-yeasts :wlp833-german-bock-lager {:min-temperature 8.89
:name "WLP833 German Bock Lager"
:max-temperature 12.78
:type "Lager"
:best-for "Bocks, Doppelbocks, Oktoberfest, Vienna, Helles, some American Pilsners"
:laboratory "White Labs"
:attenuation 0.765
:notes "Produces beer that has balanced malt and hop character. From Southern Bavaria."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP833"}))
(def wlp838-southern-german-lager
(yeasts/build-yeasts :wlp838-southern-german-lager {:min-temperature 10.0
:name "WLP838 Southern German Lager"
:max-temperature 12.78
:type "Lager"
:best-for "German Pilsner, Helles, Oktoberfest, Marzen, Bocks"
:laboratory "White Labs"
:attenuation 0.765
:notes "Malty finish and balanced aroma. Strong fermenter, slight sulfur and low diacetyl."
:flocculation "High"
:form "Liquid"
:product-id "WLP838"}))
(def wlp840-american-lager-yeast
(yeasts/build-yeasts :wlp840-american-lager-yeast {:min-temperature 10.0
:name "WLP840 American Lager Yeast"
:max-temperature 12.78
:type "Lager"
:best-for "All American Style Lagers -- both light and dark."
:laboratory "White Labs"
:attenuation 0.765
:notes "Dry and clean with very slight apple fruitiness. Minimal sulfer and diacetyl."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP840"}))
(def wlp860-munich-helles
(yeasts/build-yeasts :wlp860-munich-helles {:min-temperature 8.89
:name "WLP860 Munich Helles"
:max-temperature 11.11
:type "Ale"
:best-for "Munich Helles, Oktoberfest"
:laboratory "White Labs"
:attenuation 0.765
:notes "Possible Augustiner Strain? This yeast helps to produce a malty, but balanced traditional Munich-style lager. Clean and strong fermenter, it's great for a variety of lager styles ranging from Helles to Rauchbier."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP860"}))
(def wlp862-cry-havoc
(yeasts/build-yeasts :wlp862-cry-havoc {:min-temperature 20.0
:name "WLP862 Cry Havoc"
:max-temperature 23.33
:type "Lager"
:best-for "All American Style Lagers -- both light and dark."
:laboratory "White Labs"
:attenuation 0.765
:notes "Licensed by White Labs from <NAME>, author of \"The Complete Joy of Home Brewing\". This yeast was used to brew many of his original recipes. Diverse strain can ferment at ale and lager temps."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP862"}))
(def wlp885-zurich-lager
(yeasts/build-yeasts :wlp885-zurich-lager {:min-temperature 10.0
:name "WLP885 Zurich Lager"
:max-temperature 12.78
:type "Lager"
:best-for "Swiss style lager, and high gravity lagers (over 11% ABV)"
:laboratory "White Labs"
:attenuation 0.765
:notes "Swiss style lager yeast. Sulfer and diacetyl production is minimal. May be used for high gravity lagers with proper care."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP885"}))
(def wlp920-old-bavarian-lager
(yeasts/build-yeasts :wlp920-old-bavarian-lager {:min-temperature 10.0
:name "WLP920 Old Bavarian Lager"
:max-temperature 12.78
:type "Lager"
:best-for "Oktoberfest, Marzen, Bock and Dark Lagers."
:laboratory "White Labs"
:attenuation 0.765
:notes "Southern Germany/Bavarian lager yeast. Finishes malty with a slight ester profile."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP920"}))
(def wlp940-mexican-lager
(yeasts/build-yeasts :wlp940-mexican-lager {:min-temperature 10.0
:name "WLP940 Mexican Lager"
:max-temperature 12.78
:type "Lager"
:best-for "Mexican style light and dark lagers."
:laboratory "White Labs"
:attenuation 0.765
:notes "From Mexico City - produces a clean lager beer with a crisp finish. Good for mexican style beers."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP940"}))
(def white-labs
(merge wlp001-california-ale wlp002-english-ale wlp003-german-ale-ii wlp004-irish-ale-yeast wlp005-british-ale wlp006-bedford-british-ale wlp007-dry-english-ale
wlp008-east-coast-ale wlp009-australian-ale-yeast wlp011-european-ale wlp013-london-ale wlp022-essex-ale-yeast wlp023-burton-ale wlp025-southwold-ale
wlp026-premium-bitter-ale wlp028-edinburgh-ale wlp029-german-ale-kolsch wlp033-klassic-ale-yeast wlp036-dusseldorf-alt-yeast wlp037-yorkshire-square-ale-yeast
wlp038-manchester-ale-yeast wlp039-nottingham-ale-yeast wlp041-pacific-ale wlp051-california-ale-v wlp060-american-ale-yeast-blend wlp080-cream-ale-yeast-blend
wlp090-san-diego-super-yeast wlp099-super-high-gravity-ale wlp300-hefeweizen-ale wlp320-american-hefeweizen-ale wlp351-bavarian-weizen-yeast wlp380-hefeweizen-iv-ale
wlp400-belgian-wit-ale wlp410-belgian-wit-ii wlp500-trappist-ale wlp510-bastogne-belgian-ale wlp515-antwerp-ale-yeast wlp530-abbey-ale wlp540-abbey-iv-ale-yeast
wlp545-belgian-strong-ale-yeast wlp550-belgian-ale wlp565-belgian-saison-i-ale wlp566-belgian-saison-ii-yeast wlp568-belgian-style-saison-ale-yeast-blend
wlp570-belgian-golden-ale wlp575-belgian-style-ale-yeast-blend wlp630-berliner-weisse-blend wlp645-brettanomyces-claussenii wlp650-brettanomyces-bruxellensis
wlp653-brettanomyces-lambicus wlp655-belgian-sour-mix-1 wlp670-american-farmhouse-blend wlp675-malolactic-bacteria wlp677-lactobacillus-bacteria
wlp700-flor-sherry-yeast wlp705-sake-yeast wlp715-champagne-yeast wlp718-avize-wine-yeast wlp720-sweet-mead-wine wlp727-steinberg-geisenheim-wine
wlp730-chardonnay-white-wine-yeast wlp735-french-white-wine-yeast wlp740-merlot-red-wine-yeast wlp749-assmanshausen-wine-yeast
wlp750-french-red-wine-yeast wlp760-cabernet-red-wine-yeast wlp770-suremain-burgundy-wine-yeast wlp775-english-cider-yeast
wlp800-pilsner-lager wlp802-czech-budejovice-lager wlp810-san-francisco-lager wlp815-belgian-lager-yeast wlp820-octoberfest-marzen-lager
wlp830-german-lager wlp833-german-bock-lager wlp838-southern-german-lager wlp840-american-lager-yeast wlp860-munich-helles wlp862-cry-havoc
wlp885-zurich-lager wlp920-old-bavarian-lager wlp940-mexican-lager))
| true | (ns common-beer-format.data.yeasts.white-labs
"Data for yeasts cultivated by White Labs"
(:require [common-beer-format.data.yeasts.yeasts :as yeasts]))
(def wlp001-california-ale
(yeasts/build-yeasts :wlp001-california-ale {:min-temperature 20.0
:name "WLP001 California Ale"
:max-temperature 22.78
:type "Ale"
:best-for "American Style Ales, Ambers, Pale Ales, Brown Ale, Strong Ale"
:laboratory "White Labs"
:attenuation 0.765
:notes "Very clean flavor, balance and stability. Accentuates hop flavor Versitile - can be used to make any style ale."
:flocculation "High"
:form "Liquid"
:product-id "WLP001"}))
(def wlp002-english-ale
(yeasts/build-yeasts :wlp002-english-ale {:min-temperature 18.33
:name "WLP002 English Ale"
:max-temperature 20.0
:type "Ale"
:best-for "English Pale Ale, ESB, India Pale Ale, Brown Ale, Porter, Sweet Stouts and Strong Ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Classic ESB strain best for English style milds, bitters, porters and English style stouts. Leaves a clear beer with some residual sweetness."
:flocculation "Very High"
:form "Liquid"
:product-id "WLP002"}))
(def wlp003-german-ale-ii
(yeasts/build-yeasts :wlp003-german-ale-ii {:min-temperature 18.33
:name "WLP003 German Ale II"
:max-temperature 21.11
:type "Ale"
:best-for "Kolsch, Alt and German Pale Ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Strong sulfer component will reduce with aging. Clean flavor, but with more ester production than regular German Ale Yeast."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP003"}))
(def wlp004-irish-ale-yeast
(yeasts/build-yeasts :wlp004-irish-ale-yeast {:min-temperature 18.33
:name "WLP004 Irish Ale Yeast"
:max-temperature 20.0
:type "Ale"
:best-for "Irish Ales, Stouts, Porters, Browns, Reds and Pale Ale"
:laboratory "White Labs"
:attenuation 0.765
:notes "Excellent for Irish Stouts. Produces slight hint of diacetyl balanced by a light fruitiness and a slightly dry crispness."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP004"}))
(def wlp005-british-ale
(yeasts/build-yeasts :wlp005-british-ale {:min-temperature 19.44
:name "WLP005 British Ale"
:max-temperature 23.33
:type "Ale"
:best-for "Excellent for all English style ales including bitters, pale ale, porters and brown ale."
:laboratory "White Labs"
:attenuation 0.765
:notes "This yeast has higher attenuation than the White Labs English Ale yeast strains. Produces a malty flavored beer."
:flocculation "High"
:form "Liquid"
:product-id "WLP005"}))
(def wlp006-bedford-british-ale
(yeasts/build-yeasts :wlp006-bedford-british-ale {:min-temperature 18.33
:name "WLP006 Bedford British Ale"
:max-temperature 21.11
:type "Ale"
:best-for "English style ales - bitter, pale, porter and brown ale"
:laboratory "White Labs"
:attenuation 0.765
:notes "High attenuation. Ferments dry with high flocculation. Distinctive ester profile. Good for most English ale styles."
:flocculation "High"
:form "Liquid"
:product-id "WLP006"}))
(def wlp007-dry-english-ale
(yeasts/build-yeasts :wlp007-dry-english-ale {:min-temperature 18.33
:name "WLP007 Dry English Ale"
:max-temperature 21.11
:type "Ale"
:best-for "Pale Ales, Amber, ESB, Brown Ales, Strong Ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Clean, Highly flocculant, and highly attentive yeast. Similar to White labs English Ale yeast, but more attentive. Suitable for high gravity ales."
:flocculation "High"
:form "Liquid"
:product-id "WLP007"}))
(def wlp008-east-coast-ale
(yeasts/build-yeasts :wlp008-east-coast-ale {:min-temperature 20.0
:name "WLP008 East Coast Ale"
:max-temperature 22.78
:type "Ale"
:best-for "American Ales, Golden ales, Blonde Ale, Pale Ale and German Alt styles"
:laboratory "White Labs"
:attenuation 0.765
:notes "White labs \"Brewer Patriot\"strain can be used to reproduce many of the American versions of classic beer styles. Very clean with low esters. "
:flocculation "Low"
:form "Liquid"
:product-id "WLP008"}))
(def wlp009-australian-ale-yeast
(yeasts/build-yeasts :wlp009-australian-ale-yeast {:min-temperature 18.33
:name "WLP009 Australian Ale Yeast"
:max-temperature 21.11
:type "Ale"
:best-for "Australian Ales, English Ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "White Labs entry for Australian Ales. Produces a clean, malty finish with pleasant ester character. Bready character. Can ferment clean at high temperatures."
:flocculation "High"
:form "Liquid"
:product-id "WLP009"}))
(def wlp011-european-ale
(yeasts/build-yeasts :wlp011-european-ale {:min-temperature 18.33
:name "WLP011 European Ale"
:max-temperature 21.11
:type "Ale"
:best-for "Alt, Kolsch, malty English Ales, Fruit beers"
:laboratory "White Labs"
:attenuation 0.765
:notes "Malty, Northern European ale yeast. Low ester production, low sulfer, gives a clean profile. Low attenuation contributes to malty taste."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP011"}))
(def wlp013-london-ale
(yeasts/build-yeasts :wlp013-london-ale {:min-temperature 18.89
:name "WLP013 London Ale"
:max-temperature 21.67
:type "Ale"
:best-for "Classic British Pale Ales, Bitters and Stouts"
:laboratory "White Labs"
:attenuation 0.765
:notes "Dry, malty ale yeast. Produces a complex, oak flavored ester character. Hop bitterness comes through well."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP013"}))
(def wlp022-essex-ale-yeast
(yeasts/build-yeasts :wlp022-essex-ale-yeast {:min-temperature 18.89
:name "WLP022 Essex Ale Yeast"
:max-temperature 21.11
:type "Ale"
:best-for "British milds, pale ales, bitters, stouts."
:laboratory "White Labs"
:attenuation 0.765
:notes "Flavorful British yeast with a drier finish than many ale yeasts. Bready and fruity in character. Well suited for top cropping (collecting). Does not flocculate as much as WLP005 or WLP002."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP022"}))
(def wlp023-burton-ale
(yeasts/build-yeasts :wlp023-burton-ale {:min-temperature 20.0
:name "WLP023 Burton Ale"
:max-temperature 22.78
:type "Ale"
:best-for "All English styles including Pale Ale, IPA, Porter, Stout and Bitters."
:laboratory "White Labs"
:attenuation 0.765
:notes "Burton-on-trent yeast produces a complex character. Flavors include apple, pear, and clover honey."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP023"}))
(def wlp025-southwold-ale
(yeasts/build-yeasts :wlp025-southwold-ale {:min-temperature 18.89
:name "WLP025 Southwold Ale"
:max-temperature 20.56
:type "Ale"
:best-for "British bitters and pale ales."
:laboratory "White Labs"
:attenuation 0.765
:notes "From Suffolk county. Products complex fruity and citrus flavors. Slight sulfer production, but this will fade with aging."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP025"}))
(def wlp026-premium-bitter-ale
(yeasts/build-yeasts :wlp026-premium-bitter-ale {:min-temperature 19.44
:name "WLP026 Premium Bitter Ale"
:max-temperature 21.11
:type "Ale"
:best-for "All English ales including bitters, milds, ESB, Porter, Stout and Barley Wine"
:laboratory "White Labs"
:attenuation 0.765
:notes "From Staffordshire England. Mild, but complex estery flavor. High attenuation - ferments strong and dry. Suitable for high gravity beers."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP026"}))
(def wlp028-edinburgh-ale
(yeasts/build-yeasts :wlp028-edinburgh-ale {:min-temperature 18.33
:name "WLP028 Edinburgh Ale"
:max-temperature 21.11
:type "Ale"
:best-for "Strong Scottish style ales, ESB, Irish Reds"
:laboratory "White Labs"
:attenuation 0.765
:notes "Malty strong ale yeast. Reproduces complex, malty, flavorful schottish ales. Hop character comes through well."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP028"}))
(def wlp029-german-ale-kolsch
(yeasts/build-yeasts :wlp029-german-ale-kolsch {:min-temperature 18.33
:name "WLP029 German Ale/Kolsch"
:max-temperature 20.56
:type "Ale"
:best-for "Kolsch, Altbiers, Pale Ales, Blonde and Honey Ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Great for light beers. Accentuates hop flavors. Slight sulfer flavor will fade with age and leave a clean, lager like ale."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP029"}))
(def wlp033-klassic-ale-yeast
(yeasts/build-yeasts :wlp033-klassic-ale-yeast {:min-temperature 18.89
:name "WLP033 Klassic Ale Yeast"
:max-temperature 21.11
:type "Ale"
:best-for "Bitters, milds, porters stouts and scottish ale styles."
:laboratory "White Labs"
:attenuation 0.765
:notes "Traditional English Ale style yeast. Produces ester character, and allows hop flavor through. Leaves a slightly sweet malt character in ales."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP033"}))
(def wlp036-dusseldorf-alt-yeast
(yeasts/build-yeasts :wlp036-dusseldorf-alt-yeast {:min-temperature 18.33
:name "WLP036 Dusseldorf Alt Yeast"
:max-temperature 20.56
:type "Ale"
:best-for "Alt biers, Dusseldorf Alts, German Ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Traditional Alt yeast from Dusseldorf, Germany. Produces clean, slightly sweet alt beers. Does not accentuate hop flavor like WLP029 does."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP036"}))
(def wlp037-yorkshire-square-ale-yeast
(yeasts/build-yeasts :wlp037-yorkshire-square-ale-yeast {:min-temperature 18.33
:name "WLP037 Yorkshire Square Ale Yeast"
:max-temperature 20.56
:type "Ale"
:best-for "English pale ales, English brown ales and Mild ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "This yeast produces a malty but well balanced profile. Expect toasty flavors with malt driven esters. Highly flocculent and a good choice for many English ales."
:flocculation "High"
:form "Liquid"
:product-id "WLP037"}))
(def wlp038-manchester-ale-yeast
(yeasts/build-yeasts :wlp038-manchester-ale-yeast {:min-temperature 18.33
:name "WLP038 Manchester Ale Yeast"
:max-temperature 21.11
:type "Ale"
:best-for "English style ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Top fermenting strain that is good for top-cropping. Moderately flocculent with a clean, dry finish. Low ester profile for producing a balanced English ale."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP038"}))
(def wlp039-nottingham-ale-yeast
(yeasts/build-yeasts :wlp039-nottingham-ale-yeast {:min-temperature 18.89
:name "WLP039 Nottingham Ale Yeast"
:max-temperature 21.11
:type "Ale"
:best-for "British ales, pale ales, ambers, porters and stouts."
:laboratory "White Labs"
:attenuation 0.765
:notes "British style of ale yeast with a very dry finish and high attenuation. Medium to low fruit and fusel alcohol production. Good top fermenting yeast for cropping. "
:flocculation "Medium"
:form "Liquid"
:product-id "WLP039"}))
(def wlp041-pacific-ale
(yeasts/build-yeasts :wlp041-pacific-ale {:min-temperature 18.33
:name "WLP041 Pacific Ale"
:max-temperature 20.0
:type "Ale"
:best-for "English & American ales including milds, bitters, IPA, porters and English stouts."
:laboratory "White Labs"
:attenuation 0.765
:notes "Popular yeast from the Pacific Northwest. Leaves a clear and malty profile. More fruity than WLP002. Suitable for many English and American styles."
:flocculation "High"
:form "Liquid"
:product-id "WLP041"}))
(def wlp051-california-ale-v
(yeasts/build-yeasts :wlp051-california-ale-v {:min-temperature 18.89
:name "WLP051 California Ale V"
:max-temperature 21.11
:type "Ale"
:best-for "American style Pales, Ambers, Browns, IPAs, American Strong Ale"
:laboratory "White Labs"
:attenuation 0.765
:notes "Similar to White Labs California Ale Yeast, but slightly lower attenuation leaves a fuller bodied beer."
:flocculation "High"
:form "Liquid"
:product-id "WLP051"}))
(def wlp060-american-ale-yeast-blend
(yeasts/build-yeasts :wlp060-american-ale-yeast-blend {:min-temperature 20.0
:name "WLP060 American Ale Yeast Blend"
:max-temperature 22.22
:type "Ale"
:best-for "American ales with clean finish"
:laboratory "White Labs"
:attenuation 0.765
:notes "A blend that celebrates WLP001 (California Ale Yeast's) clean, neutral fermentation. This strain is versatile and adds two other yeast strains that are also clean/neutral in flavor to add a bit of complexity - almost a lager like finish. Slight sulfur m"
:flocculation "Medium"
:form "Liquid"
:product-id "WLP060"}))
(def wlp080-cream-ale-yeast-blend
(yeasts/build-yeasts :wlp080-cream-ale-yeast-blend {:min-temperature 18.33
:name "WLP080 Cream Ale Yeast Blend"
:max-temperature 21.11
:type "Ale"
:best-for "Cream Ale, Hybrids"
:laboratory "White Labs"
:attenuation 0.765
:notes "A blend of ale and lager yeast strains that work together to create a clean, light American lager style ale. A pleasing estery aroma may be perceived. Hop flavors and bitterness are slightly subdued. Slight sulfer will be produced during fermentation f"
:flocculation "Medium"
:form "Liquid"
:product-id "WLP080"}))
(def wlp090-san-diego-super-yeast
(yeasts/build-yeasts :wlp090-san-diego-super-yeast {:min-temperature 18.33
:name "WLP090 San Diego Super Yeast"
:max-temperature 20.0
:type "Ale"
:best-for "IPAs, American ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "A super clean, super-fast fermenting strain. A low ester-producing strain that results in a balanced, neutral flavor and aroma profile. Alcohol-tolerant and very versatile for a wide variety of styles. Similar to California Ale Yeast WLP001 but it generally ferments faster."
:flocculation "Very High"
:form "Liquid"
:product-id "WLP090"}))
(def wlp099-super-high-gravity-ale
(yeasts/build-yeasts :wlp099-super-high-gravity-ale {:min-temperature 20.56
:name "WLP099 Super High Gravity Ale"
:max-temperature 23.33
:type "Ale"
:best-for "Very high gravity beers and barley wine up to 25% alcohol."
:laboratory "White Labs"
:attenuation 0.765
:notes "Ferments up to 25% alcohol content. Flavor may vary greatly depending on beer alcohol. English like esters at low gravity, but will become more wine-like as alcohol exceeds 16% ABV. Refer to White Labs web page for tips on fermenting high gravity ales."
:flocculation "Low"
:form "Liquid"
:product-id "WLP099"}))
(def wlp300-hefeweizen-ale
(yeasts/build-yeasts :wlp300-hefeweizen-ale {:min-temperature 20.0
:name "WLP300 Hefeweizen Ale"
:max-temperature 22.22
:type "Wheat"
:best-for "German style wheat beers. Weiss, Weizen, Hefeweizen"
:laboratory "White Labs"
:attenuation 0.765
:notes "Produces the banana and clove nose traditionally associated with German Wheat beers. Also produces desired cloudy look."
:flocculation "Low"
:form "Liquid"
:product-id "WLP300"}))
(def wlp320-american-hefeweizen-ale
(yeasts/build-yeasts :wlp320-american-hefeweizen-ale {:min-temperature 18.33
:name "WLP320 American Hefeweizen Ale"
:max-temperature 20.56
:type "Wheat"
:best-for "Oregon style American Hefeweizen"
:laboratory "White Labs"
:attenuation 0.765
:notes "Produces a much smaller amount of clove and banana flavor than the German Hefeweizen White Labs yeast. Some sulfur, and creates desired cloudy look."
:flocculation "Low"
:form "Liquid"
:product-id "WLP320"}))
(def wlp351-bavarian-weizen-yeast
(yeasts/build-yeasts :wlp351-bavarian-weizen-yeast {:min-temperature 18.89
:name "WLP351 Bavarian Weizen Yeast"
:max-temperature 21.11
:type "Wheat"
:best-for "Bavarian Weizen and wheat beers."
:laboratory "White Labs"
:attenuation 0.765
:notes "Former yeast lab W51 strain. Produces a classic German style wheat beer with moderately high, spicy, phenolic overtones reminiscent of cloves."
:flocculation "Low"
:form "Liquid"
:product-id "WLP351"}))
(def wlp380-hefeweizen-iv-ale
(yeasts/build-yeasts :wlp380-hefeweizen-iv-ale {:min-temperature 18.89
:name "WLP380 Hefeweizen IV Ale"
:max-temperature 21.11
:type "Wheat"
:best-for "German style Hefeweizen"
:laboratory "White Labs"
:attenuation 0.765
:notes "Large clove and phenolic aroma, but with minimal banana flavor. Citrus and apricot notes. Crisp and drinkable, with some sulfur production."
:flocculation "Low"
:form "Liquid"
:product-id "WLP380"}))
(def wlp400-belgian-wit-ale
(yeasts/build-yeasts :wlp400-belgian-wit-ale {:min-temperature 19.44
:name "WLP400 Belgian Wit Ale"
:max-temperature 23.33
:type "Wheat"
:best-for "Belgian Wit"
:laboratory "White Labs"
:attenuation 0.765
:notes "Phenolic and tart. The original yeast used to produce Wit in Belgium."
:flocculation "Low"
:form "Liquid"
:product-id "WLP400"}))
(def wlp410-belgian-wit-ii
(yeasts/build-yeasts :wlp410-belgian-wit-ii {:min-temperature 19.44
:name "WLP410 Belgian Wit II"
:max-temperature 23.33
:type "Ale"
:best-for "Belgian Wit, Spiced Ale, Wheat Ales and Specialty Beers"
:laboratory "White Labs"
:attenuation 0.765
:notes "Less phenolic than WLP400 (Belgian Wit Ale) but more spicy. Leaves a little more sweetness and flocculation is higher than WLP400."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP410"}))
(def wlp500-trappist-ale
(yeasts/build-yeasts :wlp500-trappist-ale {:min-temperature 18.33
:name "WLP500 Trappist Ale"
:max-temperature 22.22
:type "Ale"
:best-for "Trappist Ale, Dubbel, Trippel, Belgian Ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Distinctive fruitiness and plum characteristics. Excellent for high gravity beers."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP500"}))
(def wlp510-bastogne-belgian-ale
(yeasts/build-yeasts :wlp510-bastogne-belgian-ale {:min-temperature 18.89
:name "WLP510 Bastogne Belgian Ale"
:max-temperature 22.22
:type "Ale"
:best-for "High gravity beers, Belgian ales, Dubbels, Trippels."
:laboratory "White Labs"
:attenuation 0.765
:notes "High gravity Trappist ale yeast. Creates a dry beer with a slightly acidic finish. Cleaner finish and slightly less spicy than WLP500 or WLP530. "
:flocculation "Medium"
:form "Liquid"
:product-id "WLP510"}))
(def wlp515-antwerp-ale-yeast
(yeasts/build-yeasts :wlp515-antwerp-ale-yeast {:min-temperature 19.44
:name "WLP515 Antwerp Ale Yeast"
:max-temperature 21.11
:type "Ale"
:best-for "Belgian pale and amber ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Clean, almost lager like Belgian ale yeast. Good for Belgian pale and amber ales or with other Belgian yeasts in a blend. Biscuity, ale like aroma present. Hop flavors are accentuated. Slight sulfur during fermentation, and a lager like flavor profile"
:flocculation "Medium"
:form "Liquid"
:product-id "WLP515"}))
(def wlp530-abbey-ale
(yeasts/build-yeasts :wlp530-abbey-ale {:min-temperature 18.89
:name "WLP530 Abbey Ale"
:max-temperature 22.22
:type "Ale"
:best-for "Belgian Trappist Ale, Spiced Ale, Trippel, Dubbel, Grand Cru"
:laboratory "White Labs"
:attenuation 0.765
:notes "Used in two of six remaining Trappist breweries. Distinctive plum and fruitiness. Good for high gravity beers."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP530"}))
(def wlp540-abbey-iv-ale-yeast
(yeasts/build-yeasts :wlp540-abbey-iv-ale-yeast {:min-temperature 18.89
:name "WLP540 Abbey IV Ale Yeast"
:max-temperature 22.22
:type "Ale"
:best-for "Trappist Belgian Ales, Dubbels, Tripels and Specialty ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "An authentic Trappist style ale yeast. Use for Belgian ales including abbey ales (dubbels, tripels). Fruit character is medium - between WLP500 (high) and WLP530 (low)"
:flocculation "Medium"
:form "Liquid"
:product-id "WLP540"}))
(def wlp545-belgian-strong-ale-yeast
(yeasts/build-yeasts :wlp545-belgian-strong-ale-yeast {:min-temperature 18.33
:name "WLP545 Belgian Strong Ale Yeast"
:max-temperature 22.78
:type "Ale"
:best-for "Belgian dark strongs, Abbey ales and Christmas beers"
:laboratory "White Labs"
:attenuation 0.765
:notes "From the Ardennes region of Belgium, this classic strain produces moderate esters and spicy phenolic character. Results in a dry but balanced finish. Use for dark or strong abbey ales."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP545"}))
(def wlp550-belgian-ale
(yeasts/build-yeasts :wlp550-belgian-ale {:min-temperature 20.0
:name "WLP550 Belgian Ale"
:max-temperature 25.56
:type "Ale"
:best-for "Belgian Ales, Saisons, Belgian Reds, Belgian Browns, White beers"
:laboratory "White Labs"
:attenuation 0.765
:notes "Phenolic and spicy flavors. Complex profile, with less fruitiness than White's Trappist Ale strain."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP550"}))
(def wlp565-belgian-saison-i-ale
(yeasts/build-yeasts :wlp565-belgian-saison-i-ale {:min-temperature 20.0
:name "WLP565 Belgian Saison I Ale"
:max-temperature 23.89
:type "Ale"
:best-for "Saison Ale, Belgian Ale, Dubbel, Trippel"
:laboratory "White Labs"
:attenuation 0.765
:notes "Saison yeast from Wallonia. Earthy, spicy and peppery notes. Slightly sweet."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP565"}))
(def wlp566-belgian-saison-ii-yeast
(yeasts/build-yeasts :wlp566-belgian-saison-ii-yeast {:min-temperature 20.0
:name "WLP566 Belgian Saison II Yeast"
:max-temperature 25.56
:type "Ale"
:best-for "Belgian or French Saison"
:laboratory "White Labs"
:attenuation 0.765
:notes "Saison strain with a more fruity ester profile than WLP565 (Belgian Saison I Yeast). Moderately phenolic with a clove-like characteristic in finished beer flavor and aroma. Ferments quickly."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP566"}))
(def wlp568-belgian-style-saison-ale-yeast-blend
(yeasts/build-yeasts :wlp568-belgian-style-saison-ale-yeast-blend {:min-temperature 21.11
:name "WLP568 Belgian Style Saison Ale Yeast Blend"
:max-temperature 26.67
:type "Ale"
:best-for "Belgian and French Saison"
:laboratory "White Labs"
:attenuation 0.765
:notes "This blend melds Belgian style ale and Saison strains. The strains work in harmony to create complex, fruity aromas and flavors. The blend of yeast strains encourages complete fermentation in a timely manner. Phenolic, spicy, earthy, and clove like flavor"
:flocculation "Medium"
:form "Liquid"
:product-id "WLP568"}))
(def wlp570-belgian-golden-ale
(yeasts/build-yeasts :wlp570-belgian-golden-ale {:min-temperature 20.0
:name "WLP570 Belgian Golden Ale"
:max-temperature 23.89
:type "Ale"
:best-for "Belgian Ales, Dubbel, Grand Cru, Belgian Holiday Ale"
:laboratory "White Labs"
:attenuation 0.765
:notes "Combination of fruitiness and phenolic characters dominate the profile. Some sulfur which will dissapate following fermentation."
:flocculation "Low"
:form "Liquid"
:product-id "WLP570"}))
(def wlp575-belgian-style-ale-yeast-blend
(yeasts/build-yeasts :wlp575-belgian-style-ale-yeast-blend {:min-temperature 20.0
:name "WLP575 Belgian Style Ale Yeast Blend"
:max-temperature 23.89
:type "Ale"
:best-for "Trappist and other Belgian ales."
:laboratory "White Labs"
:attenuation 0.765
:notes "Blend of two trappist ale yeasts and one Belgian ale yeast. Creates a versatile blend to be used for Trappist and other Belgian style ales."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP575"}))
(def wlp630-berliner-weisse-blend
(yeasts/build-yeasts :wlp630-berliner-weisse-blend {:min-temperature 20.0
:name "WLP630 Berliner Weisse Blend"
:max-temperature 22.22
:type "Wheat"
:best-for "Berliner Weisse"
:laboratory "White Labs"
:attenuation 0.765
:notes "A blend of a traditional German Weizen yeast and Lactobacillus to create a subtle, tart, drinkable beer. Can take several months to develop tart character. Perfect for traditional Berliner Weisse."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP630"}))
(def wlp645-brettanomyces-claussenii
(yeasts/build-yeasts :wlp645-brettanomyces-claussenii {:min-temperature 18.33
:name "WLP645 Brettanomyces Claussenii"
:max-temperature 22.22
:type "Ale"
:best-for "Sour ales (in secondary)"
:laboratory "White Labs"
:attenuation 0.765
:notes "Low intensity Brett character. Originally isolated from strong English stock beer, in the early 20th century. The Brett flavors produced are more subtle than WLP650 and WLP653. More aroma than flavor contribution. Fruity, pineapple like aroma."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP645"}))
(def wlp650-brettanomyces-bruxellensis
(yeasts/build-yeasts :wlp650-brettanomyces-bruxellensis {:min-temperature 18.33
:name "WLP650 Brettanomyces Bruxellensis"
:max-temperature 22.22
:type "Ale"
:best-for "Belgian sour ales and labics (in secondary)"
:laboratory "White Labs"
:attenuation 0.765
:notes "Medium intensity Brett character. Classic strain used in secondary fermentation for Belgian style beers and lambics. One Trappist brewery uses this strain in secondary fermentation."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP650"}))
(def wlp653-brettanomyces-lambicus
(yeasts/build-yeasts :wlp653-brettanomyces-lambicus {:min-temperature 18.33
:name "WLP653 Brettanomyces Lambicus"
:max-temperature 22.22
:type "Ale"
:best-for "Lambics and Flanders/Sour Brown ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Use in secondary. High intensity Brett character. Defines the \"Brett character\": Horsey, smoky and spicy flavors. As the name suggests, this strain is found most often in Lambic style beers, which are spontaneously fermented beers."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP653"}))
(def wlp655-belgian-sour-mix-1
(yeasts/build-yeasts :wlp655-belgian-sour-mix-1 {:min-temperature 18.33
:name "WLP655 Belgian Sour Mix 1"
:max-temperature 22.22
:type "Ale"
:best-for "Belgian sour beers (in secondary)"
:laboratory "White Labs"
:attenuation 0.765
:notes "Note: Bacteria to use in secondary only. A unique blend perfect for Belgian style beers. Includes Brettanomyces, Saccharomyces, and the bacterial strains Lactobacillus and Pediococcus."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP655"}))
(def wlp670-american-farmhouse-blend
(yeasts/build-yeasts :wlp670-american-farmhouse-blend {:min-temperature 20.0
:name "WLP670 American Farmhouse Blend"
:max-temperature 22.22
:type "Ale"
:best-for "Saisons, Farmhouse Ales"
:laboratory "White Labs"
:attenuation 0.765
:notes "Inspired by local American brewers crafting semi- traditional Belgian-style ales. This blend creates a complex flavor profile with a moderate level of sourness. It consists of a traditional farmhouse yeast strain and Brettanomyces. Great yeast for farmho"
:flocculation "Medium"
:form "Liquid"
:product-id "WLP670"}))
(def wlp675-malolactic-bacteria
(yeasts/build-yeasts :wlp675-malolactic-bacteria {:min-temperature 18.33
:name "WLP675 Malolactic Bacteria"
:max-temperature 22.22
:type "Ale"
:best-for "Primarily wine"
:laboratory "White Labs"
:attenuation 0.765
:notes "Bacteria for use in secondary. Malolactic fermentation is the conversion of malic acid to lactic acid by bacteria from the lactic acid bacteria family. Lactic acid is less acidic than malic acid, which in turn decreases acidity and helps to soften and/o"
:flocculation "Medium"
:form "Liquid"
:product-id "WLP675"}))
(def wlp677-lactobacillus-bacteria
(yeasts/build-yeasts :wlp677-lactobacillus-bacteria {:min-temperature 18.33
:name "WLP677 Lactobacillus Bacteria"
:max-temperature 22.22
:type "Ale"
:best-for "Lambic, Berliner Weiss, Sour Brown and Gueze (secondary)"
:laboratory "White Labs"
:attenuation 0.765
:notes "Bacteria for use in secondary. This lactic acid bacteria produces moderate levels of acidity and sour flavors found in lambics, Berliner Weiss, sour brown ale and gueze."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP677"}))
(def wlp700-flor-sherry-yeast
(yeasts/build-yeasts :wlp700-flor-sherry-yeast {:min-temperature 21.11
:name "WLP700 Flor Sherry Yeast"
:max-temperature 24.44
:type "Wine"
:best-for "Sherry wine yeast"
:laboratory "White Labs"
:attenuation 0.765
:notes "This yeast develops a film (flor) on the surface of the wine. Creates green almond, granny smith and nougat characteristics found in sherry. Can also be used for Port, Madeira and other sweet styles. For use in secondary fermentation. Slow fermentor. Al"
:flocculation "Medium"
:form "Liquid"
:product-id "WLP700"}))
(def wlp705-sake-yeast
(yeasts/build-yeasts :wlp705-sake-yeast {:min-temperature 21.11
:name "WLP705 Sake Yeast"
:max-temperature 24.44
:type "Wine"
:best-for "Sake wine yeast"
:laboratory "White Labs"
:attenuation 0.765
:notes "For use in rice based fermentations. For sake, use this yeast in conjunction with Koji (to produce fermentable sugar). WLP705 produces full body sake character, and subtle fragrance. Alcohol tolerance to 16%."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP705"}))
(def wlp715-champagne-yeast
(yeasts/build-yeasts :wlp715-champagne-yeast {:min-temperature 21.11
:name "WLP715 Champagne Yeast"
:max-temperature 23.89
:type "Champagne"
:best-for "Wine, Mead and Cider"
:laboratory "White Labs"
:attenuation 0.765
:notes "Can tolerate alcohol up to 17%. For Barley Wine or Meads."
:flocculation "Low"
:form "Liquid"
:product-id "WLP715"}))
(def wlp718-avize-wine-yeast
(yeasts/build-yeasts :wlp718-avize-wine-yeast {:min-temperature 15.56
:name "WLP718 Avize Wine Yeast"
:max-temperature 32.22
:type "Wine"
:best-for "Chardonnay"
:laboratory "White Labs"
:attenuation 0.765
:notes "Champagne isolate used for complexity in whites. Contributes elegance, especially in barrel fermented Chardonnays. Alcohol tolerance to 15%."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP718"}))
(def wlp720-sweet-mead-wine
(yeasts/build-yeasts :wlp720-sweet-mead-wine {:min-temperature 21.11
:name "WLP720 Sweet Mead/Wine"
:max-temperature 23.89
:type "Wine"
:best-for "Sweet Mead, Wine and Cider"
:laboratory "White Labs"
:attenuation 0.765
:notes "Lower attenuation than White Labs Champagne Yeast. Leaves some residual sweetness as well as fruity flavor. Alcohol concentration up to 15%."
:flocculation "Low"
:form "Liquid"
:product-id "WLP720"}))
(def wlp727-steinberg-geisenheim-wine
(yeasts/build-yeasts :wlp727-steinberg-geisenheim-wine {:min-temperature 10.0
:name "WLP727 Steinberg-Geisenheim Wine"
:max-temperature 32.22
:type "Wine"
:best-for "Riesling wines."
:laboratory "White Labs"
:attenuation 0.765
:notes "German origin wine yeast. High fruit/ester production. Moderate fermentation characteristics and cold tolerant."
:flocculation "Low"
:form "Liquid"
:product-id "WLP727"}))
(def wlp730-chardonnay-white-wine-yeast
(yeasts/build-yeasts :wlp730-chardonnay-white-wine-yeast {:min-temperature 10.0
:name "WLP730 Chardonnay White Wine Yeast"
:max-temperature 32.22
:type "Wine"
:best-for "Chardonnay Wine"
:laboratory "White Labs"
:attenuation 0.765
:notes "Dry wine yeast. Slight ester production, low sulfur dioxide production. Enhances varietal character. WLP730 is a good choice for all white and blush wines, including Chablis, Chenin Blanc, Semillon, and Sauvignon Blanc. Fermentation speed is moderate. Al"
:flocculation "Low"
:form "Liquid"
:product-id "WLP730"}))
(def wlp735-french-white-wine-yeast
(yeasts/build-yeasts :wlp735-french-white-wine-yeast {:min-temperature 15.56
:name "WLP735 French White Wine Yeast"
:max-temperature 32.22
:type "Wine"
:best-for "French white wines"
:laboratory "White Labs"
:attenuation 0.765
:notes "Classic yeast for white wine fermentation. Slow to moderate fermenter and foam producer. Gives an enhanced creamy texture. Alcohol Tolerance: 16%"
:flocculation "Low"
:form "Liquid"
:product-id "WLP735"}))
(def wlp740-merlot-red-wine-yeast
(yeasts/build-yeasts :wlp740-merlot-red-wine-yeast {:min-temperature 15.56
:name "WLP740 Merlot Red Wine Yeast"
:max-temperature 32.22
:type "Wine"
:best-for "Merlot, Shiraz, Pinot Noir, Chardonnay, Cabernet, Sauvignon Blanc, and Semillon"
:laboratory "White Labs"
:attenuation 0.765
:notes "Neutral, low fusel alcohol production. Will ferment to dryness, alcohol tolerance to 18%. Vigorous fermenter. WLP740 is well suited for Merlot, Shiraz, Pinot Noir, Chardonnay, Cabernet, Sauvignon Blanc, and Semillon. Alcohol Tolerance: 18%"
:flocculation "Low"
:form "Liquid"
:product-id "WLP740"}))
(def wlp749-assmanshausen-wine-yeast
(yeasts/build-yeasts :wlp749-assmanshausen-wine-yeast {:min-temperature 10.0
:name "WLP749 Assmanshausen Wine Yeast"
:max-temperature 32.22
:type "Wine"
:best-for "Pinot Noir and Zinfandel"
:laboratory "White Labs"
:attenuation 0.765
:notes "German red wine yeast, which results in spicy, fruit aromas. Perfect for Pinot Noir and Zinfandel. Slow to moderate fermenter which is cold tolerant. Alcohol Tolerance: 16%"
:flocculation "Low"
:form "Liquid"
:product-id "WLP749"}))
(def wlp750-french-red-wine-yeast
(yeasts/build-yeasts :wlp750-french-red-wine-yeast {:min-temperature 15.56
:name "WLP750 French Red Wine Yeast"
:max-temperature 32.22
:type "Wine"
:best-for "Bordeaux"
:laboratory "White Labs"
:attenuation 0.765
:notes "Classic Bordeaux yeast for red wine fermentations. Moderate fermentation characteristics. Tolerates lower fermentation temperatures. Rich, smooth flavor profile. Alcohol Tolerance: 17%"
:flocculation "Low"
:form "Liquid"
:product-id "WLP750"}))
(def wlp760-cabernet-red-wine-yeast
(yeasts/build-yeasts :wlp760-cabernet-red-wine-yeast {:min-temperature 15.56
:name "WLP760 Cabernet Red Wine Yeast"
:max-temperature 32.22
:type "Wine"
:best-for "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, and PI:NAME:<NAME>END_PI"
:laboratory "White Labs"
:attenuation 0.765
:notes "High temperature tolerance. Moderate fermentation speed. Excellent for full-bodied red wines, ester production complements flavor. WLP760 is also suitable for PI:NAME:<NAME>END_PIlot, Chardonnay, Chianti, PI:NAME:<NAME>END_PIin Blanc, and Sauvignon Blanc. Alcohol Tolerance: 16%"
:flocculation "Low"
:form "Liquid"
:product-id "WLP760"}))
(def wlp770-suremain-burgundy-wine-yeast
(yeasts/build-yeasts :wlp770-suremain-burgundy-wine-yeast {:min-temperature 15.56
:name "WLP770 Suremain Burgundy Wine Yeast"
:max-temperature 32.22
:type "Wine"
:best-for "Burgundy"
:laboratory "White Labs"
:attenuation 0.765
:notes "Emphasizes fruit aromas in barrel fermentations. High nutrient requirement to avoid volatile acidity production. Alcohol Tolerance: 16%"
:flocculation "Low"
:form "Liquid"
:product-id "WLP770"}))
(def wlp775-english-cider-yeast
(yeasts/build-yeasts :wlp775-english-cider-yeast {:min-temperature 20.0
:name "WLP775 English Cider Yeast"
:max-temperature 23.89
:type "Wine"
:best-for "Cider, Wine and High Gravity Beer"
:laboratory "White Labs"
:attenuation 0.765
:notes "Classic Cider yeast. Ferments dry, but retains apple flavor. Some sulfer produced during fermentation will fade with age."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP775"}))
(def wlp800-pilsner-lager
(yeasts/build-yeasts :wlp800-pilsner-lager {:min-temperature 10.0
:name "WLP800 Pilsner Lager"
:max-temperature 12.78
:type "Lager"
:best-for "European Pilsners, Bohemian Pilsner"
:laboratory "White Labs"
:attenuation 0.765
:notes "Classic pilsner strain from Czech Republic. Dry with a malty finish."
:flocculation "High"
:form "Liquid"
:product-id "WLP800"}))
(def wlp802-czech-budejovice-lager
(yeasts/build-yeasts :wlp802-czech-budejovice-lager {:min-temperature 10.0
:name "WLP802 Czech Budejovice Lager"
:max-temperature 12.78
:type "Lager"
:best-for "Bohemian Style Pilsner"
:laboratory "White Labs"
:attenuation 0.765
:notes "Dry and crisp with low diacetyl production. From Southern Czech Republic."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP802"}))
(def wlp810-san-francisco-lager
(yeasts/build-yeasts :wlp810-san-francisco-lager {:min-temperature 14.44
:name "WLP810 San Francisco Lager"
:max-temperature 18.33
:type "Lager"
:best-for "California and Premium Lagers, all American Lagers"
:laboratory "White Labs"
:attenuation 0.765
:notes "Produces \"California Common\"style beer."
:flocculation "High"
:form "Liquid"
:product-id "WLP810"}))
(def wlp815-belgian-lager-yeast
(yeasts/build-yeasts :wlp815-belgian-lager-yeast {:min-temperature 10.0
:name "WLP815 Belgian Lager Yeast"
:max-temperature 12.78
:type "Lager"
:best-for "European style pilsners, dark lagers, Vienna lager, and American style lagers"
:laboratory "White Labs"
:attenuation 0.765
:notes "Clean, crisp European lager yeast with low sulfur production. The strain originates from a very old brewery in West Belgium. Great for European style pilsners, dark lagers, Vienna lager, and American style lagers. "
:flocculation "Medium"
:form "Liquid"
:product-id "WLP815"}))
(def wlp820-octoberfest-marzen-lager
(yeasts/build-yeasts :wlp820-octoberfest-marzen-lager {:min-temperature 11.11
:name "WLP820 Octoberfest/Marzen Lager"
:max-temperature 14.44
:type "Lager"
:best-for "Marzen, Oktoberfest, European Lagers, Bocks, Munich Helles"
:laboratory "White Labs"
:attenuation 0.765
:notes "Produces a malty, bock style beer. Does not finish as dry or as fast as White's German Lager yeast. Longer lagering or starter recommended."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP820"}))
(def wlp830-german-lager
(yeasts/build-yeasts :wlp830-german-lager {:min-temperature 10.0
:name "WLP830 German Lager"
:max-temperature 12.78
:type "Lager"
:best-for "German Marzen, Pilsner, Lagers, Oktoberfest beers."
:laboratory "White Labs"
:attenuation 0.765
:notes "Very malty and clean. One of the world's most popular lager yeasts."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP830"}))
(def wlp833-german-bock-lager
(yeasts/build-yeasts :wlp833-german-bock-lager {:min-temperature 8.89
:name "WLP833 German Bock Lager"
:max-temperature 12.78
:type "Lager"
:best-for "Bocks, Doppelbocks, Oktoberfest, Vienna, Helles, some American Pilsners"
:laboratory "White Labs"
:attenuation 0.765
:notes "Produces beer that has balanced malt and hop character. From Southern Bavaria."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP833"}))
(def wlp838-southern-german-lager
(yeasts/build-yeasts :wlp838-southern-german-lager {:min-temperature 10.0
:name "WLP838 Southern German Lager"
:max-temperature 12.78
:type "Lager"
:best-for "German Pilsner, Helles, Oktoberfest, Marzen, Bocks"
:laboratory "White Labs"
:attenuation 0.765
:notes "Malty finish and balanced aroma. Strong fermenter, slight sulfur and low diacetyl."
:flocculation "High"
:form "Liquid"
:product-id "WLP838"}))
(def wlp840-american-lager-yeast
(yeasts/build-yeasts :wlp840-american-lager-yeast {:min-temperature 10.0
:name "WLP840 American Lager Yeast"
:max-temperature 12.78
:type "Lager"
:best-for "All American Style Lagers -- both light and dark."
:laboratory "White Labs"
:attenuation 0.765
:notes "Dry and clean with very slight apple fruitiness. Minimal sulfer and diacetyl."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP840"}))
(def wlp860-munich-helles
(yeasts/build-yeasts :wlp860-munich-helles {:min-temperature 8.89
:name "WLP860 Munich Helles"
:max-temperature 11.11
:type "Ale"
:best-for "Munich Helles, Oktoberfest"
:laboratory "White Labs"
:attenuation 0.765
:notes "Possible Augustiner Strain? This yeast helps to produce a malty, but balanced traditional Munich-style lager. Clean and strong fermenter, it's great for a variety of lager styles ranging from Helles to Rauchbier."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP860"}))
(def wlp862-cry-havoc
(yeasts/build-yeasts :wlp862-cry-havoc {:min-temperature 20.0
:name "WLP862 Cry Havoc"
:max-temperature 23.33
:type "Lager"
:best-for "All American Style Lagers -- both light and dark."
:laboratory "White Labs"
:attenuation 0.765
:notes "Licensed by White Labs from PI:NAME:<NAME>END_PI, author of \"The Complete Joy of Home Brewing\". This yeast was used to brew many of his original recipes. Diverse strain can ferment at ale and lager temps."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP862"}))
(def wlp885-zurich-lager
(yeasts/build-yeasts :wlp885-zurich-lager {:min-temperature 10.0
:name "WLP885 Zurich Lager"
:max-temperature 12.78
:type "Lager"
:best-for "Swiss style lager, and high gravity lagers (over 11% ABV)"
:laboratory "White Labs"
:attenuation 0.765
:notes "Swiss style lager yeast. Sulfer and diacetyl production is minimal. May be used for high gravity lagers with proper care."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP885"}))
(def wlp920-old-bavarian-lager
(yeasts/build-yeasts :wlp920-old-bavarian-lager {:min-temperature 10.0
:name "WLP920 Old Bavarian Lager"
:max-temperature 12.78
:type "Lager"
:best-for "Oktoberfest, Marzen, Bock and Dark Lagers."
:laboratory "White Labs"
:attenuation 0.765
:notes "Southern Germany/Bavarian lager yeast. Finishes malty with a slight ester profile."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP920"}))
(def wlp940-mexican-lager
(yeasts/build-yeasts :wlp940-mexican-lager {:min-temperature 10.0
:name "WLP940 Mexican Lager"
:max-temperature 12.78
:type "Lager"
:best-for "Mexican style light and dark lagers."
:laboratory "White Labs"
:attenuation 0.765
:notes "From Mexico City - produces a clean lager beer with a crisp finish. Good for mexican style beers."
:flocculation "Medium"
:form "Liquid"
:product-id "WLP940"}))
(def white-labs
(merge wlp001-california-ale wlp002-english-ale wlp003-german-ale-ii wlp004-irish-ale-yeast wlp005-british-ale wlp006-bedford-british-ale wlp007-dry-english-ale
wlp008-east-coast-ale wlp009-australian-ale-yeast wlp011-european-ale wlp013-london-ale wlp022-essex-ale-yeast wlp023-burton-ale wlp025-southwold-ale
wlp026-premium-bitter-ale wlp028-edinburgh-ale wlp029-german-ale-kolsch wlp033-klassic-ale-yeast wlp036-dusseldorf-alt-yeast wlp037-yorkshire-square-ale-yeast
wlp038-manchester-ale-yeast wlp039-nottingham-ale-yeast wlp041-pacific-ale wlp051-california-ale-v wlp060-american-ale-yeast-blend wlp080-cream-ale-yeast-blend
wlp090-san-diego-super-yeast wlp099-super-high-gravity-ale wlp300-hefeweizen-ale wlp320-american-hefeweizen-ale wlp351-bavarian-weizen-yeast wlp380-hefeweizen-iv-ale
wlp400-belgian-wit-ale wlp410-belgian-wit-ii wlp500-trappist-ale wlp510-bastogne-belgian-ale wlp515-antwerp-ale-yeast wlp530-abbey-ale wlp540-abbey-iv-ale-yeast
wlp545-belgian-strong-ale-yeast wlp550-belgian-ale wlp565-belgian-saison-i-ale wlp566-belgian-saison-ii-yeast wlp568-belgian-style-saison-ale-yeast-blend
wlp570-belgian-golden-ale wlp575-belgian-style-ale-yeast-blend wlp630-berliner-weisse-blend wlp645-brettanomyces-claussenii wlp650-brettanomyces-bruxellensis
wlp653-brettanomyces-lambicus wlp655-belgian-sour-mix-1 wlp670-american-farmhouse-blend wlp675-malolactic-bacteria wlp677-lactobacillus-bacteria
wlp700-flor-sherry-yeast wlp705-sake-yeast wlp715-champagne-yeast wlp718-avize-wine-yeast wlp720-sweet-mead-wine wlp727-steinberg-geisenheim-wine
wlp730-chardonnay-white-wine-yeast wlp735-french-white-wine-yeast wlp740-merlot-red-wine-yeast wlp749-assmanshausen-wine-yeast
wlp750-french-red-wine-yeast wlp760-cabernet-red-wine-yeast wlp770-suremain-burgundy-wine-yeast wlp775-english-cider-yeast
wlp800-pilsner-lager wlp802-czech-budejovice-lager wlp810-san-francisco-lager wlp815-belgian-lager-yeast wlp820-octoberfest-marzen-lager
wlp830-german-lager wlp833-german-bock-lager wlp838-southern-german-lager wlp840-american-lager-yeast wlp860-munich-helles wlp862-cry-havoc
wlp885-zurich-lager wlp920-old-bavarian-lager wlp940-mexican-lager))
|
[
{
"context": "/todo\"\n :user \"db_user_name_here\"\n :password \"db_user_password_here\"})\n\n\n",
"end": 158,
"score": 0.9973416924476624,
"start": 137,
"tag": "PASSWORD",
"value": "db_user_password_here"
}
] | src/todo/db/schema.clj | vyorkin-play/clojure-todo3 | 0 | (ns todo.db.schema)
(def db-spec
{:subprotocol "postgresql"
:subname "//localhost/todo"
:user "db_user_name_here"
:password "db_user_password_here"})
| 18328 | (ns todo.db.schema)
(def db-spec
{:subprotocol "postgresql"
:subname "//localhost/todo"
:user "db_user_name_here"
:password "<PASSWORD>"})
| true | (ns todo.db.schema)
(def db-spec
{:subprotocol "postgresql"
:subname "//localhost/todo"
:user "db_user_name_here"
:password "PI:PASSWORD:<PASSWORD>END_PI"})
|
[
{
"context": ";; Copyright (c) 2014 Engagor\n;;\n;; The use and distribution terms for this sof",
"end": 29,
"score": 0.9900380969047546,
"start": 22,
"tag": "NAME",
"value": "Engagor"
}
] | project.clj | ghosthamlet/dl4clj | 62 | ;; Copyright (c) 2014 Engagor
;;
;; The use and distribution terms for this software are covered by the
;; BSD License (http://opensource.org/licenses/BSD-2-Clause)
;; which can be found in the file LICENSE at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(defproject dl4clj "0.1.0-alpha"
:description "ports of some DL4J features to Clojure"
:url "https://github.com/yetanalytics/dl4clj"
:license {:name "BSD C2"
:url "http://opensource.org/licenses/BSD-2-Clause"}
:dependencies [[org.clojure/clojure "1.9.0-beta2"]
[org.deeplearning4j/deeplearning4j-core "0.8.0"
:exclusions
[com.google.guava/guava
org.apache.commons/commons-compress]]
[org.nd4j/nd4j-native-platform "0.8.0"
:exclusions [com.google.guava/guava]]
[org.datavec/datavec-api "0.8.0"
:exclusions
[com.google.guava/guava]]
[org.datavec/datavec-spark_2.11 "0.8.0_spark_2"
:exclusions
[org.apache.commons/commons-lang3
com.google.guava/guava
commons-net
org.scala-lang/scala-reflect
org.slf4j/slf4j-api
org.scala-lang/scala-library
org.apache.commons/commons-compress]]
[org.deeplearning4j/dl4j-spark_2.11 "0.8.0_spark_2"
:exclusions
[org.slf4j/slf4j-api
commons-net
org.scala-lang/scala-library
org.scala-lang/scala-reflect
org.apache.commons/commons-lang3
com.google.guava/guava]]
[org.apache.spark/spark-core_2.11 "2.1.0"
:exclusions
[commons-net
org.apache.commons/commons-lang3
org.slf4j/slf4j-api]]
[org.clojure/core.match "0.3.0-alpha5"]
[cheshire "5.7.1"]])
| 56363 | ;; Copyright (c) 2014 <NAME>
;;
;; The use and distribution terms for this software are covered by the
;; BSD License (http://opensource.org/licenses/BSD-2-Clause)
;; which can be found in the file LICENSE at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(defproject dl4clj "0.1.0-alpha"
:description "ports of some DL4J features to Clojure"
:url "https://github.com/yetanalytics/dl4clj"
:license {:name "BSD C2"
:url "http://opensource.org/licenses/BSD-2-Clause"}
:dependencies [[org.clojure/clojure "1.9.0-beta2"]
[org.deeplearning4j/deeplearning4j-core "0.8.0"
:exclusions
[com.google.guava/guava
org.apache.commons/commons-compress]]
[org.nd4j/nd4j-native-platform "0.8.0"
:exclusions [com.google.guava/guava]]
[org.datavec/datavec-api "0.8.0"
:exclusions
[com.google.guava/guava]]
[org.datavec/datavec-spark_2.11 "0.8.0_spark_2"
:exclusions
[org.apache.commons/commons-lang3
com.google.guava/guava
commons-net
org.scala-lang/scala-reflect
org.slf4j/slf4j-api
org.scala-lang/scala-library
org.apache.commons/commons-compress]]
[org.deeplearning4j/dl4j-spark_2.11 "0.8.0_spark_2"
:exclusions
[org.slf4j/slf4j-api
commons-net
org.scala-lang/scala-library
org.scala-lang/scala-reflect
org.apache.commons/commons-lang3
com.google.guava/guava]]
[org.apache.spark/spark-core_2.11 "2.1.0"
:exclusions
[commons-net
org.apache.commons/commons-lang3
org.slf4j/slf4j-api]]
[org.clojure/core.match "0.3.0-alpha5"]
[cheshire "5.7.1"]])
| true | ;; Copyright (c) 2014 PI:NAME:<NAME>END_PI
;;
;; The use and distribution terms for this software are covered by the
;; BSD License (http://opensource.org/licenses/BSD-2-Clause)
;; which can be found in the file LICENSE at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(defproject dl4clj "0.1.0-alpha"
:description "ports of some DL4J features to Clojure"
:url "https://github.com/yetanalytics/dl4clj"
:license {:name "BSD C2"
:url "http://opensource.org/licenses/BSD-2-Clause"}
:dependencies [[org.clojure/clojure "1.9.0-beta2"]
[org.deeplearning4j/deeplearning4j-core "0.8.0"
:exclusions
[com.google.guava/guava
org.apache.commons/commons-compress]]
[org.nd4j/nd4j-native-platform "0.8.0"
:exclusions [com.google.guava/guava]]
[org.datavec/datavec-api "0.8.0"
:exclusions
[com.google.guava/guava]]
[org.datavec/datavec-spark_2.11 "0.8.0_spark_2"
:exclusions
[org.apache.commons/commons-lang3
com.google.guava/guava
commons-net
org.scala-lang/scala-reflect
org.slf4j/slf4j-api
org.scala-lang/scala-library
org.apache.commons/commons-compress]]
[org.deeplearning4j/dl4j-spark_2.11 "0.8.0_spark_2"
:exclusions
[org.slf4j/slf4j-api
commons-net
org.scala-lang/scala-library
org.scala-lang/scala-reflect
org.apache.commons/commons-lang3
com.google.guava/guava]]
[org.apache.spark/spark-core_2.11 "2.1.0"
:exclusions
[commons-net
org.apache.commons/commons-lang3
org.slf4j/slf4j-api]]
[org.clojure/core.match "0.3.0-alpha5"]
[cheshire "5.7.1"]])
|
[
{
"context": "ations from Elements of Artificial Intelligence by Steven Tanimoto\"\n :url \"https://github.com/sandersn/elements-of-",
"end": 143,
"score": 0.999893307685852,
"start": 128,
"tag": "NAME",
"value": "Steven Tanimoto"
},
{
"context": "ce by Steven Tanimoto\"\n :url \"https://github.com/sandersn/elements-of-ai\"\n :license {:name \"MIT\"\n ",
"end": 180,
"score": 0.9996151328086853,
"start": 172,
"tag": "USERNAME",
"value": "sandersn"
},
{
"context": "{:name \"MIT\"\n :url \"https://github.com/sandersn/elements-of-ai/blob/master/LICENSE\"}\n :dependenc",
"end": 266,
"score": 0.9996213316917419,
"start": 258,
"tag": "USERNAME",
"value": "sandersn"
}
] | project.clj | sandersn/elements-of-ai | 5 | (defproject elements-of-ai "0.1.0-SNAPSHOT"
:description "Example implementations from Elements of Artificial Intelligence by Steven Tanimoto"
:url "https://github.com/sandersn/elements-of-ai"
:license {:name "MIT"
:url "https://github.com/sandersn/elements-of-ai/blob/master/LICENSE"}
:dependencies [[org.clojure/clojure "1.7.0"]]
:main ^:skip-aot chapter3.match
:target-path "target/%s"
:profiles {:uberjar {:aot :all}})
| 54622 | (defproject elements-of-ai "0.1.0-SNAPSHOT"
:description "Example implementations from Elements of Artificial Intelligence by <NAME>"
:url "https://github.com/sandersn/elements-of-ai"
:license {:name "MIT"
:url "https://github.com/sandersn/elements-of-ai/blob/master/LICENSE"}
:dependencies [[org.clojure/clojure "1.7.0"]]
:main ^:skip-aot chapter3.match
:target-path "target/%s"
:profiles {:uberjar {:aot :all}})
| true | (defproject elements-of-ai "0.1.0-SNAPSHOT"
:description "Example implementations from Elements of Artificial Intelligence by PI:NAME:<NAME>END_PI"
:url "https://github.com/sandersn/elements-of-ai"
:license {:name "MIT"
:url "https://github.com/sandersn/elements-of-ai/blob/master/LICENSE"}
:dependencies [[org.clojure/clojure "1.7.0"]]
:main ^:skip-aot chapter3.match
:target-path "target/%s"
:profiles {:uberjar {:aot :all}})
|
[
{
"context": ":text \"Quote!\"\n :author \"Costin Dragoi\"}))\n\n(defn fetch-link! [state]\n (GET \"https://qu",
"end": 266,
"score": 0.9998928308486938,
"start": 253,
"tag": "NAME",
"value": "Costin Dragoi"
}
] | src/random_quote/core.cljs | stindrago/random-quote-generator | 0 | (ns random-quote.core
(:require [ajax.core :refer [GET]]
[reagent.core :as reagent :refer [atom]]))
;; define your app data so that it doesn't get over-written on reload
(defonce app-state (atom {:text "Quote!"
:author "Costin Dragoi"}))
(defn fetch-link! [state]
(GET "https://quote-garden.herokuapp.com/api/v2/quotes/random"
{:handler (fn [data]
(println (get-in data ["quote" "quoteAuthor"]))
(swap! state assoc :text (get-in data ["quote" "quoteText"]))
(swap! state assoc :author (get-in data ["quote" "quoteAuthor"])))
:error-handler (fn [{:keys [status status-text]}]
(js/console.log status status-text))}))
(defn tweet-link [state]
(str "https://twitter.com/intent/tweet?hashtags=quote&text="
(:text @state) " - " (:author @state)))
(defn quote [state]
[:div
[:h1 "Random Quote Generator"]
[:div.quote
[:div.quote-container
[:p.quote-content (:text @state)]
[:p.quote-author (:author @state)]]
[:div.quote-buttons
[:a {:href (tweet-link state)
:target "_blank"} "tweet"]
[:button {:on-click #(fetch-link! state)} "next quote"]]]]
)
(defn start []
(reagent/render-component [quote app-state]
(. js/document (getElementById "app"))))
(defn ^:export init []
;; init is called ONCE when the page loads
;; this is called in the index.html and must be exported
;; so it is available even in :advanced release builds
(start))
(defn stop []
;; stop is called before any code is reloaded
;; this is controlled by :before-load in the config
(js/console.log "stop"))
| 119018 | (ns random-quote.core
(:require [ajax.core :refer [GET]]
[reagent.core :as reagent :refer [atom]]))
;; define your app data so that it doesn't get over-written on reload
(defonce app-state (atom {:text "Quote!"
:author "<NAME>"}))
(defn fetch-link! [state]
(GET "https://quote-garden.herokuapp.com/api/v2/quotes/random"
{:handler (fn [data]
(println (get-in data ["quote" "quoteAuthor"]))
(swap! state assoc :text (get-in data ["quote" "quoteText"]))
(swap! state assoc :author (get-in data ["quote" "quoteAuthor"])))
:error-handler (fn [{:keys [status status-text]}]
(js/console.log status status-text))}))
(defn tweet-link [state]
(str "https://twitter.com/intent/tweet?hashtags=quote&text="
(:text @state) " - " (:author @state)))
(defn quote [state]
[:div
[:h1 "Random Quote Generator"]
[:div.quote
[:div.quote-container
[:p.quote-content (:text @state)]
[:p.quote-author (:author @state)]]
[:div.quote-buttons
[:a {:href (tweet-link state)
:target "_blank"} "tweet"]
[:button {:on-click #(fetch-link! state)} "next quote"]]]]
)
(defn start []
(reagent/render-component [quote app-state]
(. js/document (getElementById "app"))))
(defn ^:export init []
;; init is called ONCE when the page loads
;; this is called in the index.html and must be exported
;; so it is available even in :advanced release builds
(start))
(defn stop []
;; stop is called before any code is reloaded
;; this is controlled by :before-load in the config
(js/console.log "stop"))
| true | (ns random-quote.core
(:require [ajax.core :refer [GET]]
[reagent.core :as reagent :refer [atom]]))
;; define your app data so that it doesn't get over-written on reload
(defonce app-state (atom {:text "Quote!"
:author "PI:NAME:<NAME>END_PI"}))
(defn fetch-link! [state]
(GET "https://quote-garden.herokuapp.com/api/v2/quotes/random"
{:handler (fn [data]
(println (get-in data ["quote" "quoteAuthor"]))
(swap! state assoc :text (get-in data ["quote" "quoteText"]))
(swap! state assoc :author (get-in data ["quote" "quoteAuthor"])))
:error-handler (fn [{:keys [status status-text]}]
(js/console.log status status-text))}))
(defn tweet-link [state]
(str "https://twitter.com/intent/tweet?hashtags=quote&text="
(:text @state) " - " (:author @state)))
(defn quote [state]
[:div
[:h1 "Random Quote Generator"]
[:div.quote
[:div.quote-container
[:p.quote-content (:text @state)]
[:p.quote-author (:author @state)]]
[:div.quote-buttons
[:a {:href (tweet-link state)
:target "_blank"} "tweet"]
[:button {:on-click #(fetch-link! state)} "next quote"]]]]
)
(defn start []
(reagent/render-component [quote app-state]
(. js/document (getElementById "app"))))
(defn ^:export init []
;; init is called ONCE when the page loads
;; this is called in the index.html and must be exported
;; so it is available even in :advanced release builds
(start))
(defn stop []
;; stop is called before any code is reloaded
;; this is controlled by :before-load in the config
(js/console.log "stop"))
|
[
{
"context": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;\n; Copyright 2015 Xebia B.V.\n;\n; Licensed under the Apache License, Version 2",
"end": 107,
"score": 0.89960116147995,
"start": 98,
"tag": "NAME",
"value": "Xebia B.V"
}
] | src/main/clojure/com/xebia/visualreview/resource.clj | andstepanuk/VisualReview | 290 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Copyright 2015 Xebia B.V.
;
; Licensed under the Apache License, Version 2.0 (the "License")
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns com.xebia.visualreview.resource
(:require [liberator.core :refer [resource defresource]]
[cheshire.core :as json]
[slingshot.slingshot :as ex]
[com.xebia.visualreview.validation :as v]
[com.xebia.visualreview.resource.util :refer :all]
[com.xebia.visualreview.service.analysis :as analysis]
[com.xebia.visualreview.service.analysis.core :as analysisc]
[com.xebia.visualreview.io :as io]
[com.xebia.visualreview.service.image :as image]
[com.xebia.visualreview.service.screenshot :as screenshot]
[com.xebia.visualreview.service.project :as project]
[com.xebia.visualreview.service.suite :as suite]
[com.xebia.visualreview.service.run :as run]
[com.xebia.visualreview.service.cleanup :as cleanup]
[com.xebia.visualreview.service.baseline :as baseline])
(:import [java.util Map]))
;;;;;;;;; Projects ;;;;;;;;;;;
(def ^:private project-schema
{:name [String [::v/non-empty]]})
(defn project-resource []
(json-resource
:allowed-methods [:get :put]
:processable? (fn [ctx]
(or (get-request? ctx)
(let [v (v/validations project-schema (:parsed-json ctx))]
(if (:valid? v)
{::project-name (-> v :data :name)}
[false {::error-msg (handle-invalid v
::v/non-empty "Name can not be empty")}]))))
:handle-unprocessable-entity ::error-msg
:exists? (fn [ctx]
(or (get-request? ctx)
(when-let [project-id (project/get-project-by-name (tx-conn ctx) (::project-name ctx) :id)]
{::project-id project-id})))
:conflict? (fn [ctx] (::project-id ctx))
:handle-conflict (fn [ctx] (format "A project with name: '%s' already exists." (::project-name ctx)))
:put! (fn [ctx]
(let [new-project-id (project/create-project! (tx-conn ctx) (::project-name ctx))
project (suite/get-suites-by-project-id (tx-conn ctx) new-project-id)]
{::project project}))
:handle-created ::project
:handle-ok (fn [ctx] (project/get-projects (tx-conn ctx)))))
(defn project-by-id [project-id]
(json-resource
:allowed-methods [:get :delete]
:processable? (fn [_]
(try
(when-let [project-id-long (Long/parseLong project-id)]
{::project-id project-id-long})
(catch NumberFormatException _ false)))
:exists? (fn [ctx]
(try
(when-let [project (suite/get-suites-by-project-id (tx-conn ctx) (::project-id ctx))]
{::project project})
(catch NumberFormatException _)))
:delete! (fn [ctx]
(let [result (project/delete-project! (tx-conn ctx) (::project-id ctx))]
(do
(cleanup/cleanup-orphans! (tx-conn ctx))
{::project-deleted result})))
:delete-enacted? (fn [ctx]
(::project-deleted ctx))
:handle-ok ::project))
;;;;;;;;;; Suites ;;;;;;;;;;;
(defn suites-resource [project-id]
(json-resource
:allowed-methods [:get]
:exists? (fn [ctx]
(try
(let [[project-id] (parse-longs [project-id])]
(and (project/get-project-by-id (tx-conn ctx) project-id)
(when-let [suites (suite/get-suites (tx-conn ctx) project-id)]
{::suites suites})))
(catch NumberFormatException _)))
:handle-ok ::suites))
(defn suite-resource [project-id suite-id]
(json-resource
:allowed-methods [:get :delete]
:exists? (fn [ctx]
(try
(let [[project-id suite-id] (parse-longs [project-id suite-id])]
(when-let [suite (suite/get-full-suite (tx-conn ctx) project-id suite-id)]
{::suite suite}))
(catch NumberFormatException _)))
:delete! (fn [ctx]
(let [result (suite/delete-suite! (tx-conn ctx) (:id (::suite ctx)))]
(do
(cleanup/cleanup-orphans! (tx-conn ctx))
{::suite-deleted result})))
:delete-enacted? (fn [ctx]
(::suite-deleted ctx))
:handle-ok ::suite))
(defn suite-status-resource [project-id suite-id]
(resource
:available-media-types ["text/plain"]
:allowed-methods [:get]
:exists? (fn [ctx]
(let [[project-id suite-id] (parse-longs [project-id suite-id])
suite-status (suite/get-suite-status (tx-conn ctx) project-id suite-id)]
(if (= "empty" suite-status)
false
{:suite-status suite-status})))
:handle-ok (fn [ctx]
(:suite-status ctx))))
;;;;;;;;;;; Runs ;;;;;;;;;;;
(def ^:private run-create-schema
{:projectName [String []]
:suiteName [String [::v/non-empty]]})
(defn run-resource [run-id]
(json-resource
:allowed-methods [:get :delete]
:exists? (fn [ctx]
(try
(let [[run-id] (parse-longs [run-id])]
(when-let [run (run/get-run (tx-conn ctx) run-id)]
{::run run}))
(catch NumberFormatException _)))
:delete! (fn [ctx]
(let [result (run/delete-run! (tx-conn ctx) (:id (::run ctx)))]
(do
(cleanup/cleanup-orphans! (tx-conn ctx))
{::run-deleted result })))
:delete-enacted? (fn [ctx]
(::run-deleted ctx))
:handle-ok ::run))
(def runs-resource
(json-resource
:allowed-methods [:get :post]
:processable? (fn [ctx]
(let [v (v/validations run-create-schema (if (get-request? ctx)
(-> ctx :request :params)
(:parsed-json ctx)))]
(if (:valid? v)
{::data (hyphenize-request (:data v))}
[false {::error-msg (handle-invalid v
::v/non-empty "Suite name can not be empty")}])))
:handle-unprocessable-entity ::error-msg
:exists? (fn [ctx]
(if (get-request? ctx)
(when-let [suite (suite/get-suite-by-name (tx-conn ctx) (-> ctx ::data :project-name) (-> ctx ::data :suite-name))]
(let [runs (:runs (suite/get-full-suite (tx-conn ctx) (:project-id suite) (:id suite)))]
{::runs runs ::suite suite}))
(when-let [suite
(and
(or
(project/get-project-by-name (tx-conn ctx) (-> ctx ::data :project-name))
(project/create-project! (tx-conn ctx) (-> ctx ::data :project-name)))
(or
(suite/get-suite-by-name (tx-conn ctx) (-> ctx ::data :project-name) (-> ctx ::data :suite-name))
(suite/get-suite-by-id (tx-conn ctx)
(suite/create-suite-for-project! (tx-conn ctx) (-> ctx ::data :project-name) (-> ctx ::data :suite-name)))))]
{::suite suite})))
:can-post-to-missing? false
:post! (fn [ctx]
(let [new-run-id (run/create-run! (tx-conn ctx) (:id (::suite ctx)))
run (run/get-run (tx-conn ctx) new-run-id)]
{::run run}))
:handle-created ::run
:handle-ok ::runs))
;;;;;;;;;;; Screenshots ;;;;;;;;;;;;;;
(defn- update-diff-status! [conn {:keys [id before after status]} new-status]
(case [status new-status]
(["accepted" "pending"] ["accepted" "rejected"]) (baseline/set-baseline! conn id after before)
(["pending" "accepted"] ["rejected" "accepted"]) (baseline/set-baseline! conn id before after)
:no-op)
(analysis/update-diff-status! conn id new-status))
;; The screenshot resource has been split up into separate handler for each http method.
(def ^:private upload-screenshot-schema
{:file [Map [::v/screenshot]]
:screenshotName [String []]
:meta [Map [::v/screenshot-meta]]
:mask [Map [::v/optional ::v/screenshot-mask]]
:properties [Map [::v/screenshot-meta]]
:compareSettings [Map [::v/optional ::v/screenshot-mask]]})
(defn- update-screenshot-path [screenshot]
(update-in screenshot [:path] #(str "/screenshots/" % "/" (:id screenshot) ".png")))
(defn get-screenshots [run-id]
(json-resource
:allowed-methods [:get]
:exists? (fn [ctx]
(try (let [[run-id] (parse-longs [run-id])
run (run/get-run (tx-conn ctx) run-id)]
(when run {::run run}))
(catch NumberFormatException _)))
:handle-ok (fn [ctx] (let [screenshots (screenshot/get-screenshots-by-run-id (tx-conn ctx) (-> ctx ::run :id))]
(mapv update-screenshot-path screenshots)))))
(defn- proces-diff [conn run-id before-file after-file compare-settings before-id after-id mask]
(let [analysis (analysis/get-analysis conn run-id)
diff-report (analysisc/generate-diff-report before-file after-file mask compare-settings)
diff-file-id (image/insert-image! conn (:diff diff-report))
mask-file-id (image/insert-image! conn (:mask diff-report))
new-diff-id (analysis/save-diff! conn diff-file-id mask-file-id before-id after-id (:percentage diff-report) (:id analysis))]
(do
(.delete (:diff diff-report))
(analysis/get-diff conn run-id new-diff-id))))
(defn- process-screenshot [conn suite-id run-id screenshot-name properties compare-settings meta mask {:keys [tempfile]}]
(let [screenshot-id (screenshot/insert-screenshot! conn run-id screenshot-name properties meta tempfile)
screenshot (screenshot/get-screenshot-by-id conn screenshot-id)
baseline-screenshot (baseline/get-baseline-screenshot conn suite-id "master" screenshot-name properties)
before-file (when baseline-screenshot (io/get-file (image/get-image-path conn (:image-id baseline-screenshot))))
diff (proces-diff conn run-id before-file tempfile compare-settings (:id baseline-screenshot) screenshot-id mask)]
(when (and baseline-screenshot (zero? (:percentage diff)))
(update-diff-status! conn diff "accepted"))
screenshot))
(defn upload-screenshot [run-id]
(json-resource
:allowed-methods [:post]
:known-content-type? #(re-find #"multipart" (content-type %))
:malformed? false
:processable? (fn [ctx]
(let [v (v/validations upload-screenshot-schema (-> ctx :request :params
(update-in [:meta] json/parse-string true)
(update-in [:mask] json/parse-string true)
(update-in [:properties] json/parse-string true)
(update-in [:compareSettings] json/parse-string true)))]
(if (:valid? v)
(let [data (hyphenize-request (:data v))
run (run/get-run (tx-conn ctx) (Long/parseLong run-id))]
(if (or (= (:status run) "running") (nil? run))
{::data data ::run run}
[false {::error-msg (format "Run status must be 'running' to upload screenshots. Status is: %s" (:status run))}]))
[false {::error-msg (handle-invalid v
::v/screenshot "'file' is not a valid PNG file"
::v/screenshot-meta "Invalid meta or properties data. Are the values either strings or numbers?")}])))
:handle-unprocessable-entity ::error-msg
:exists? ::run
:can-post-to-missing? false
:post! (fn [ctx]
(ex/try+
(let [{:keys [meta mask file properties compare-settings screenshot-name]} (::data ctx)
{suite-id :suite-id run-id :id} (::run ctx)
screenshot (process-screenshot (tx-conn ctx) suite-id run-id screenshot-name properties compare-settings meta mask file)]
{::screenshot screenshot ::new? true})
(catch [:type :service-exception :code ::screenshot/screenshot-cannot-store-in-db-already-exists] _
{::screenshot {:error "Screenshot with identical name and properties was already uploaded in this run"
:conflicting-entity (select-keys (::data ctx) [:meta :properties :screenshot-name])}
::new? false})))
:new? ::new?
:respond-with-entity? true
:handle-created ::screenshot
:handle-ok ::screenshot))
(defn screenshots-resource [run-id]
(fn [req]
(if (get-request? {:request req})
(get-screenshots run-id)
(upload-screenshot run-id))))
;; Analysis
(defn- full-path [path id & {:keys [prefix] :or {prefix "/screenshots"}}]
(str prefix "/" path "/" id ".png"))
(defn- transform-diff [diff]
{:id (:id diff)
:before (when (:before diff)
{:id (:before diff)
:image-id (:before-image-id diff)
:size (:before-size diff)
:meta (:before-meta diff)
:properties (:before-properties diff)
:screenshotName (:before-name diff)})
:after {:id (:after diff)
:image-id (:after-image-id diff)
:size (:after-size diff)
:meta (:after-meta diff)
:properties (:after-properties diff)
:screenshotName (:after-name diff)}
:status (:status diff)
:percentage (:percentage diff)
:image-id (:image-id diff)
:mask-image-id (:mask-image-id diff)
})
(defn- transform-analysis [full-analysis]
(update-in full-analysis [:diffs] #(mapv transform-diff %)))
;; Diff Status
(defn analysis-resource [run-id]
(json-resource
:allowed-methods [:get]
:processable? (fn [ctx]
(try
(let [[run-id] (parse-longs [run-id])
analysis (analysis/get-full-analysis (tx-conn ctx) run-id)]
{::analysis analysis})
(catch NumberFormatException _)))
:exists? (fn [ctx] (not (empty? (-> ctx ::analysis :analysis))))
:handle-ok (comp transform-analysis ::analysis)))
(def ^:private update-diff-status-schema
{:status [String [::v/diff-status]]})
(defn diff-status-resource [run-id diff-id]
(json-resource
:allowed-methods [:post]
:processable? (fn [ctx]
(try
(let [[run-id diff-id] (parse-longs [run-id diff-id])
v (v/validations update-diff-status-schema (:parsed-json ctx))]
(if (:valid? v)
{::run-id run-id ::diff-id diff-id ::new-status (-> v :data :status)}
[false {::error-msg (handle-invalid v
::v/diff-status "'status' must be 'pending', 'accepted' or 'rejected'")}]))
(catch NumberFormatException _)))
:handle-unprocessable-entity ::error-msg
:exists? (fn [ctx]
(when-let [diff (analysis/get-diff (tx-conn ctx) (::run-id ctx) (::diff-id ctx))]
{::diff diff}))
:can-post-to-missing? false
:post! (fn [ctx]
;; First checks to see if this diff has a baseline-screenshot. If it has, it updates the diff
;; Otherwise, if the new-status is "accepted", it sets the after-screenshot as the new baseline
;; if it was not set before. If the new-status is "pending" or "rejected" it removes the baseline
;; regardless of whether it existed before
(let [baseline-screenshot (baseline/get-baseline-screenshot-by-diff-id (tx-conn ctx) diff-id)
after-id (-> ctx ::diff :after)]
(when-not baseline-screenshot ; new screenshot
(let [run (run/get-run (tx-conn ctx) run-id)
baseline-node (baseline/get-baseline-head (tx-conn ctx) (:suite-id run))]
(if (= (::new-status ctx) "accepted") ; set as baseline-screenshot
(let [bl (baseline/get-bl-node-screenshot (tx-conn ctx) baseline-node after-id)]
(when (nil? bl)
(baseline/create-bl-node-screenshot! (tx-conn ctx) baseline-node after-id)))
(baseline/delete-bl-node-screenshot! (tx-conn ctx) baseline-node after-id)))))
(update-diff-status! (tx-conn ctx) (::diff ctx) (::new-status ctx))
{::updated-diff (analysis/get-diff (tx-conn ctx) (::run-id ctx) (::diff-id ctx))})
:handle-created ::updated-diff))
(defn image [image-id]
(resource
:available-media-types ["image/png"]
:allowed-methods [:get]
:exists? (fn [ctx]
(let [image-path (image/get-image-path (tx-conn ctx) image-id)]
(if (nil? image-path)
false
{:image-path image-path})))
:handle-ok (fn [ctx]
(io/get-file (:image-path ctx)))))
;; Cleanup
(defn cleanup []
(resource
:allowed-methods [:post]
:post! (fn [ctx] (cleanup/cleanup-orphans! (tx-conn ctx)))
:handle-created (fn [_] (liberator.representation/ring-response
{:status 200}))))
| 8080 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Copyright 2015 <NAME>.
;
; Licensed under the Apache License, Version 2.0 (the "License")
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns com.xebia.visualreview.resource
(:require [liberator.core :refer [resource defresource]]
[cheshire.core :as json]
[slingshot.slingshot :as ex]
[com.xebia.visualreview.validation :as v]
[com.xebia.visualreview.resource.util :refer :all]
[com.xebia.visualreview.service.analysis :as analysis]
[com.xebia.visualreview.service.analysis.core :as analysisc]
[com.xebia.visualreview.io :as io]
[com.xebia.visualreview.service.image :as image]
[com.xebia.visualreview.service.screenshot :as screenshot]
[com.xebia.visualreview.service.project :as project]
[com.xebia.visualreview.service.suite :as suite]
[com.xebia.visualreview.service.run :as run]
[com.xebia.visualreview.service.cleanup :as cleanup]
[com.xebia.visualreview.service.baseline :as baseline])
(:import [java.util Map]))
;;;;;;;;; Projects ;;;;;;;;;;;
(def ^:private project-schema
{:name [String [::v/non-empty]]})
(defn project-resource []
(json-resource
:allowed-methods [:get :put]
:processable? (fn [ctx]
(or (get-request? ctx)
(let [v (v/validations project-schema (:parsed-json ctx))]
(if (:valid? v)
{::project-name (-> v :data :name)}
[false {::error-msg (handle-invalid v
::v/non-empty "Name can not be empty")}]))))
:handle-unprocessable-entity ::error-msg
:exists? (fn [ctx]
(or (get-request? ctx)
(when-let [project-id (project/get-project-by-name (tx-conn ctx) (::project-name ctx) :id)]
{::project-id project-id})))
:conflict? (fn [ctx] (::project-id ctx))
:handle-conflict (fn [ctx] (format "A project with name: '%s' already exists." (::project-name ctx)))
:put! (fn [ctx]
(let [new-project-id (project/create-project! (tx-conn ctx) (::project-name ctx))
project (suite/get-suites-by-project-id (tx-conn ctx) new-project-id)]
{::project project}))
:handle-created ::project
:handle-ok (fn [ctx] (project/get-projects (tx-conn ctx)))))
(defn project-by-id [project-id]
(json-resource
:allowed-methods [:get :delete]
:processable? (fn [_]
(try
(when-let [project-id-long (Long/parseLong project-id)]
{::project-id project-id-long})
(catch NumberFormatException _ false)))
:exists? (fn [ctx]
(try
(when-let [project (suite/get-suites-by-project-id (tx-conn ctx) (::project-id ctx))]
{::project project})
(catch NumberFormatException _)))
:delete! (fn [ctx]
(let [result (project/delete-project! (tx-conn ctx) (::project-id ctx))]
(do
(cleanup/cleanup-orphans! (tx-conn ctx))
{::project-deleted result})))
:delete-enacted? (fn [ctx]
(::project-deleted ctx))
:handle-ok ::project))
;;;;;;;;;; Suites ;;;;;;;;;;;
(defn suites-resource [project-id]
(json-resource
:allowed-methods [:get]
:exists? (fn [ctx]
(try
(let [[project-id] (parse-longs [project-id])]
(and (project/get-project-by-id (tx-conn ctx) project-id)
(when-let [suites (suite/get-suites (tx-conn ctx) project-id)]
{::suites suites})))
(catch NumberFormatException _)))
:handle-ok ::suites))
(defn suite-resource [project-id suite-id]
(json-resource
:allowed-methods [:get :delete]
:exists? (fn [ctx]
(try
(let [[project-id suite-id] (parse-longs [project-id suite-id])]
(when-let [suite (suite/get-full-suite (tx-conn ctx) project-id suite-id)]
{::suite suite}))
(catch NumberFormatException _)))
:delete! (fn [ctx]
(let [result (suite/delete-suite! (tx-conn ctx) (:id (::suite ctx)))]
(do
(cleanup/cleanup-orphans! (tx-conn ctx))
{::suite-deleted result})))
:delete-enacted? (fn [ctx]
(::suite-deleted ctx))
:handle-ok ::suite))
(defn suite-status-resource [project-id suite-id]
(resource
:available-media-types ["text/plain"]
:allowed-methods [:get]
:exists? (fn [ctx]
(let [[project-id suite-id] (parse-longs [project-id suite-id])
suite-status (suite/get-suite-status (tx-conn ctx) project-id suite-id)]
(if (= "empty" suite-status)
false
{:suite-status suite-status})))
:handle-ok (fn [ctx]
(:suite-status ctx))))
;;;;;;;;;;; Runs ;;;;;;;;;;;
(def ^:private run-create-schema
{:projectName [String []]
:suiteName [String [::v/non-empty]]})
(defn run-resource [run-id]
(json-resource
:allowed-methods [:get :delete]
:exists? (fn [ctx]
(try
(let [[run-id] (parse-longs [run-id])]
(when-let [run (run/get-run (tx-conn ctx) run-id)]
{::run run}))
(catch NumberFormatException _)))
:delete! (fn [ctx]
(let [result (run/delete-run! (tx-conn ctx) (:id (::run ctx)))]
(do
(cleanup/cleanup-orphans! (tx-conn ctx))
{::run-deleted result })))
:delete-enacted? (fn [ctx]
(::run-deleted ctx))
:handle-ok ::run))
(def runs-resource
(json-resource
:allowed-methods [:get :post]
:processable? (fn [ctx]
(let [v (v/validations run-create-schema (if (get-request? ctx)
(-> ctx :request :params)
(:parsed-json ctx)))]
(if (:valid? v)
{::data (hyphenize-request (:data v))}
[false {::error-msg (handle-invalid v
::v/non-empty "Suite name can not be empty")}])))
:handle-unprocessable-entity ::error-msg
:exists? (fn [ctx]
(if (get-request? ctx)
(when-let [suite (suite/get-suite-by-name (tx-conn ctx) (-> ctx ::data :project-name) (-> ctx ::data :suite-name))]
(let [runs (:runs (suite/get-full-suite (tx-conn ctx) (:project-id suite) (:id suite)))]
{::runs runs ::suite suite}))
(when-let [suite
(and
(or
(project/get-project-by-name (tx-conn ctx) (-> ctx ::data :project-name))
(project/create-project! (tx-conn ctx) (-> ctx ::data :project-name)))
(or
(suite/get-suite-by-name (tx-conn ctx) (-> ctx ::data :project-name) (-> ctx ::data :suite-name))
(suite/get-suite-by-id (tx-conn ctx)
(suite/create-suite-for-project! (tx-conn ctx) (-> ctx ::data :project-name) (-> ctx ::data :suite-name)))))]
{::suite suite})))
:can-post-to-missing? false
:post! (fn [ctx]
(let [new-run-id (run/create-run! (tx-conn ctx) (:id (::suite ctx)))
run (run/get-run (tx-conn ctx) new-run-id)]
{::run run}))
:handle-created ::run
:handle-ok ::runs))
;;;;;;;;;;; Screenshots ;;;;;;;;;;;;;;
(defn- update-diff-status! [conn {:keys [id before after status]} new-status]
(case [status new-status]
(["accepted" "pending"] ["accepted" "rejected"]) (baseline/set-baseline! conn id after before)
(["pending" "accepted"] ["rejected" "accepted"]) (baseline/set-baseline! conn id before after)
:no-op)
(analysis/update-diff-status! conn id new-status))
;; The screenshot resource has been split up into separate handler for each http method.
(def ^:private upload-screenshot-schema
{:file [Map [::v/screenshot]]
:screenshotName [String []]
:meta [Map [::v/screenshot-meta]]
:mask [Map [::v/optional ::v/screenshot-mask]]
:properties [Map [::v/screenshot-meta]]
:compareSettings [Map [::v/optional ::v/screenshot-mask]]})
(defn- update-screenshot-path [screenshot]
(update-in screenshot [:path] #(str "/screenshots/" % "/" (:id screenshot) ".png")))
(defn get-screenshots [run-id]
(json-resource
:allowed-methods [:get]
:exists? (fn [ctx]
(try (let [[run-id] (parse-longs [run-id])
run (run/get-run (tx-conn ctx) run-id)]
(when run {::run run}))
(catch NumberFormatException _)))
:handle-ok (fn [ctx] (let [screenshots (screenshot/get-screenshots-by-run-id (tx-conn ctx) (-> ctx ::run :id))]
(mapv update-screenshot-path screenshots)))))
(defn- proces-diff [conn run-id before-file after-file compare-settings before-id after-id mask]
(let [analysis (analysis/get-analysis conn run-id)
diff-report (analysisc/generate-diff-report before-file after-file mask compare-settings)
diff-file-id (image/insert-image! conn (:diff diff-report))
mask-file-id (image/insert-image! conn (:mask diff-report))
new-diff-id (analysis/save-diff! conn diff-file-id mask-file-id before-id after-id (:percentage diff-report) (:id analysis))]
(do
(.delete (:diff diff-report))
(analysis/get-diff conn run-id new-diff-id))))
(defn- process-screenshot [conn suite-id run-id screenshot-name properties compare-settings meta mask {:keys [tempfile]}]
(let [screenshot-id (screenshot/insert-screenshot! conn run-id screenshot-name properties meta tempfile)
screenshot (screenshot/get-screenshot-by-id conn screenshot-id)
baseline-screenshot (baseline/get-baseline-screenshot conn suite-id "master" screenshot-name properties)
before-file (when baseline-screenshot (io/get-file (image/get-image-path conn (:image-id baseline-screenshot))))
diff (proces-diff conn run-id before-file tempfile compare-settings (:id baseline-screenshot) screenshot-id mask)]
(when (and baseline-screenshot (zero? (:percentage diff)))
(update-diff-status! conn diff "accepted"))
screenshot))
(defn upload-screenshot [run-id]
(json-resource
:allowed-methods [:post]
:known-content-type? #(re-find #"multipart" (content-type %))
:malformed? false
:processable? (fn [ctx]
(let [v (v/validations upload-screenshot-schema (-> ctx :request :params
(update-in [:meta] json/parse-string true)
(update-in [:mask] json/parse-string true)
(update-in [:properties] json/parse-string true)
(update-in [:compareSettings] json/parse-string true)))]
(if (:valid? v)
(let [data (hyphenize-request (:data v))
run (run/get-run (tx-conn ctx) (Long/parseLong run-id))]
(if (or (= (:status run) "running") (nil? run))
{::data data ::run run}
[false {::error-msg (format "Run status must be 'running' to upload screenshots. Status is: %s" (:status run))}]))
[false {::error-msg (handle-invalid v
::v/screenshot "'file' is not a valid PNG file"
::v/screenshot-meta "Invalid meta or properties data. Are the values either strings or numbers?")}])))
:handle-unprocessable-entity ::error-msg
:exists? ::run
:can-post-to-missing? false
:post! (fn [ctx]
(ex/try+
(let [{:keys [meta mask file properties compare-settings screenshot-name]} (::data ctx)
{suite-id :suite-id run-id :id} (::run ctx)
screenshot (process-screenshot (tx-conn ctx) suite-id run-id screenshot-name properties compare-settings meta mask file)]
{::screenshot screenshot ::new? true})
(catch [:type :service-exception :code ::screenshot/screenshot-cannot-store-in-db-already-exists] _
{::screenshot {:error "Screenshot with identical name and properties was already uploaded in this run"
:conflicting-entity (select-keys (::data ctx) [:meta :properties :screenshot-name])}
::new? false})))
:new? ::new?
:respond-with-entity? true
:handle-created ::screenshot
:handle-ok ::screenshot))
(defn screenshots-resource [run-id]
(fn [req]
(if (get-request? {:request req})
(get-screenshots run-id)
(upload-screenshot run-id))))
;; Analysis
(defn- full-path [path id & {:keys [prefix] :or {prefix "/screenshots"}}]
(str prefix "/" path "/" id ".png"))
(defn- transform-diff [diff]
{:id (:id diff)
:before (when (:before diff)
{:id (:before diff)
:image-id (:before-image-id diff)
:size (:before-size diff)
:meta (:before-meta diff)
:properties (:before-properties diff)
:screenshotName (:before-name diff)})
:after {:id (:after diff)
:image-id (:after-image-id diff)
:size (:after-size diff)
:meta (:after-meta diff)
:properties (:after-properties diff)
:screenshotName (:after-name diff)}
:status (:status diff)
:percentage (:percentage diff)
:image-id (:image-id diff)
:mask-image-id (:mask-image-id diff)
})
(defn- transform-analysis [full-analysis]
(update-in full-analysis [:diffs] #(mapv transform-diff %)))
;; Diff Status
(defn analysis-resource [run-id]
(json-resource
:allowed-methods [:get]
:processable? (fn [ctx]
(try
(let [[run-id] (parse-longs [run-id])
analysis (analysis/get-full-analysis (tx-conn ctx) run-id)]
{::analysis analysis})
(catch NumberFormatException _)))
:exists? (fn [ctx] (not (empty? (-> ctx ::analysis :analysis))))
:handle-ok (comp transform-analysis ::analysis)))
(def ^:private update-diff-status-schema
{:status [String [::v/diff-status]]})
(defn diff-status-resource [run-id diff-id]
(json-resource
:allowed-methods [:post]
:processable? (fn [ctx]
(try
(let [[run-id diff-id] (parse-longs [run-id diff-id])
v (v/validations update-diff-status-schema (:parsed-json ctx))]
(if (:valid? v)
{::run-id run-id ::diff-id diff-id ::new-status (-> v :data :status)}
[false {::error-msg (handle-invalid v
::v/diff-status "'status' must be 'pending', 'accepted' or 'rejected'")}]))
(catch NumberFormatException _)))
:handle-unprocessable-entity ::error-msg
:exists? (fn [ctx]
(when-let [diff (analysis/get-diff (tx-conn ctx) (::run-id ctx) (::diff-id ctx))]
{::diff diff}))
:can-post-to-missing? false
:post! (fn [ctx]
;; First checks to see if this diff has a baseline-screenshot. If it has, it updates the diff
;; Otherwise, if the new-status is "accepted", it sets the after-screenshot as the new baseline
;; if it was not set before. If the new-status is "pending" or "rejected" it removes the baseline
;; regardless of whether it existed before
(let [baseline-screenshot (baseline/get-baseline-screenshot-by-diff-id (tx-conn ctx) diff-id)
after-id (-> ctx ::diff :after)]
(when-not baseline-screenshot ; new screenshot
(let [run (run/get-run (tx-conn ctx) run-id)
baseline-node (baseline/get-baseline-head (tx-conn ctx) (:suite-id run))]
(if (= (::new-status ctx) "accepted") ; set as baseline-screenshot
(let [bl (baseline/get-bl-node-screenshot (tx-conn ctx) baseline-node after-id)]
(when (nil? bl)
(baseline/create-bl-node-screenshot! (tx-conn ctx) baseline-node after-id)))
(baseline/delete-bl-node-screenshot! (tx-conn ctx) baseline-node after-id)))))
(update-diff-status! (tx-conn ctx) (::diff ctx) (::new-status ctx))
{::updated-diff (analysis/get-diff (tx-conn ctx) (::run-id ctx) (::diff-id ctx))})
:handle-created ::updated-diff))
(defn image [image-id]
(resource
:available-media-types ["image/png"]
:allowed-methods [:get]
:exists? (fn [ctx]
(let [image-path (image/get-image-path (tx-conn ctx) image-id)]
(if (nil? image-path)
false
{:image-path image-path})))
:handle-ok (fn [ctx]
(io/get-file (:image-path ctx)))))
;; Cleanup
(defn cleanup []
(resource
:allowed-methods [:post]
:post! (fn [ctx] (cleanup/cleanup-orphans! (tx-conn ctx)))
:handle-created (fn [_] (liberator.representation/ring-response
{:status 200}))))
| true | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Copyright 2015 PI:NAME:<NAME>END_PI.
;
; Licensed under the Apache License, Version 2.0 (the "License")
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
; http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(ns com.xebia.visualreview.resource
(:require [liberator.core :refer [resource defresource]]
[cheshire.core :as json]
[slingshot.slingshot :as ex]
[com.xebia.visualreview.validation :as v]
[com.xebia.visualreview.resource.util :refer :all]
[com.xebia.visualreview.service.analysis :as analysis]
[com.xebia.visualreview.service.analysis.core :as analysisc]
[com.xebia.visualreview.io :as io]
[com.xebia.visualreview.service.image :as image]
[com.xebia.visualreview.service.screenshot :as screenshot]
[com.xebia.visualreview.service.project :as project]
[com.xebia.visualreview.service.suite :as suite]
[com.xebia.visualreview.service.run :as run]
[com.xebia.visualreview.service.cleanup :as cleanup]
[com.xebia.visualreview.service.baseline :as baseline])
(:import [java.util Map]))
;;;;;;;;; Projects ;;;;;;;;;;;
(def ^:private project-schema
{:name [String [::v/non-empty]]})
(defn project-resource []
(json-resource
:allowed-methods [:get :put]
:processable? (fn [ctx]
(or (get-request? ctx)
(let [v (v/validations project-schema (:parsed-json ctx))]
(if (:valid? v)
{::project-name (-> v :data :name)}
[false {::error-msg (handle-invalid v
::v/non-empty "Name can not be empty")}]))))
:handle-unprocessable-entity ::error-msg
:exists? (fn [ctx]
(or (get-request? ctx)
(when-let [project-id (project/get-project-by-name (tx-conn ctx) (::project-name ctx) :id)]
{::project-id project-id})))
:conflict? (fn [ctx] (::project-id ctx))
:handle-conflict (fn [ctx] (format "A project with name: '%s' already exists." (::project-name ctx)))
:put! (fn [ctx]
(let [new-project-id (project/create-project! (tx-conn ctx) (::project-name ctx))
project (suite/get-suites-by-project-id (tx-conn ctx) new-project-id)]
{::project project}))
:handle-created ::project
:handle-ok (fn [ctx] (project/get-projects (tx-conn ctx)))))
(defn project-by-id [project-id]
(json-resource
:allowed-methods [:get :delete]
:processable? (fn [_]
(try
(when-let [project-id-long (Long/parseLong project-id)]
{::project-id project-id-long})
(catch NumberFormatException _ false)))
:exists? (fn [ctx]
(try
(when-let [project (suite/get-suites-by-project-id (tx-conn ctx) (::project-id ctx))]
{::project project})
(catch NumberFormatException _)))
:delete! (fn [ctx]
(let [result (project/delete-project! (tx-conn ctx) (::project-id ctx))]
(do
(cleanup/cleanup-orphans! (tx-conn ctx))
{::project-deleted result})))
:delete-enacted? (fn [ctx]
(::project-deleted ctx))
:handle-ok ::project))
;;;;;;;;;; Suites ;;;;;;;;;;;
(defn suites-resource [project-id]
(json-resource
:allowed-methods [:get]
:exists? (fn [ctx]
(try
(let [[project-id] (parse-longs [project-id])]
(and (project/get-project-by-id (tx-conn ctx) project-id)
(when-let [suites (suite/get-suites (tx-conn ctx) project-id)]
{::suites suites})))
(catch NumberFormatException _)))
:handle-ok ::suites))
(defn suite-resource [project-id suite-id]
(json-resource
:allowed-methods [:get :delete]
:exists? (fn [ctx]
(try
(let [[project-id suite-id] (parse-longs [project-id suite-id])]
(when-let [suite (suite/get-full-suite (tx-conn ctx) project-id suite-id)]
{::suite suite}))
(catch NumberFormatException _)))
:delete! (fn [ctx]
(let [result (suite/delete-suite! (tx-conn ctx) (:id (::suite ctx)))]
(do
(cleanup/cleanup-orphans! (tx-conn ctx))
{::suite-deleted result})))
:delete-enacted? (fn [ctx]
(::suite-deleted ctx))
:handle-ok ::suite))
(defn suite-status-resource [project-id suite-id]
(resource
:available-media-types ["text/plain"]
:allowed-methods [:get]
:exists? (fn [ctx]
(let [[project-id suite-id] (parse-longs [project-id suite-id])
suite-status (suite/get-suite-status (tx-conn ctx) project-id suite-id)]
(if (= "empty" suite-status)
false
{:suite-status suite-status})))
:handle-ok (fn [ctx]
(:suite-status ctx))))
;;;;;;;;;;; Runs ;;;;;;;;;;;
(def ^:private run-create-schema
{:projectName [String []]
:suiteName [String [::v/non-empty]]})
(defn run-resource [run-id]
(json-resource
:allowed-methods [:get :delete]
:exists? (fn [ctx]
(try
(let [[run-id] (parse-longs [run-id])]
(when-let [run (run/get-run (tx-conn ctx) run-id)]
{::run run}))
(catch NumberFormatException _)))
:delete! (fn [ctx]
(let [result (run/delete-run! (tx-conn ctx) (:id (::run ctx)))]
(do
(cleanup/cleanup-orphans! (tx-conn ctx))
{::run-deleted result })))
:delete-enacted? (fn [ctx]
(::run-deleted ctx))
:handle-ok ::run))
(def runs-resource
(json-resource
:allowed-methods [:get :post]
:processable? (fn [ctx]
(let [v (v/validations run-create-schema (if (get-request? ctx)
(-> ctx :request :params)
(:parsed-json ctx)))]
(if (:valid? v)
{::data (hyphenize-request (:data v))}
[false {::error-msg (handle-invalid v
::v/non-empty "Suite name can not be empty")}])))
:handle-unprocessable-entity ::error-msg
:exists? (fn [ctx]
(if (get-request? ctx)
(when-let [suite (suite/get-suite-by-name (tx-conn ctx) (-> ctx ::data :project-name) (-> ctx ::data :suite-name))]
(let [runs (:runs (suite/get-full-suite (tx-conn ctx) (:project-id suite) (:id suite)))]
{::runs runs ::suite suite}))
(when-let [suite
(and
(or
(project/get-project-by-name (tx-conn ctx) (-> ctx ::data :project-name))
(project/create-project! (tx-conn ctx) (-> ctx ::data :project-name)))
(or
(suite/get-suite-by-name (tx-conn ctx) (-> ctx ::data :project-name) (-> ctx ::data :suite-name))
(suite/get-suite-by-id (tx-conn ctx)
(suite/create-suite-for-project! (tx-conn ctx) (-> ctx ::data :project-name) (-> ctx ::data :suite-name)))))]
{::suite suite})))
:can-post-to-missing? false
:post! (fn [ctx]
(let [new-run-id (run/create-run! (tx-conn ctx) (:id (::suite ctx)))
run (run/get-run (tx-conn ctx) new-run-id)]
{::run run}))
:handle-created ::run
:handle-ok ::runs))
;;;;;;;;;;; Screenshots ;;;;;;;;;;;;;;
(defn- update-diff-status! [conn {:keys [id before after status]} new-status]
(case [status new-status]
(["accepted" "pending"] ["accepted" "rejected"]) (baseline/set-baseline! conn id after before)
(["pending" "accepted"] ["rejected" "accepted"]) (baseline/set-baseline! conn id before after)
:no-op)
(analysis/update-diff-status! conn id new-status))
;; The screenshot resource has been split up into separate handler for each http method.
(def ^:private upload-screenshot-schema
{:file [Map [::v/screenshot]]
:screenshotName [String []]
:meta [Map [::v/screenshot-meta]]
:mask [Map [::v/optional ::v/screenshot-mask]]
:properties [Map [::v/screenshot-meta]]
:compareSettings [Map [::v/optional ::v/screenshot-mask]]})
(defn- update-screenshot-path [screenshot]
(update-in screenshot [:path] #(str "/screenshots/" % "/" (:id screenshot) ".png")))
(defn get-screenshots [run-id]
(json-resource
:allowed-methods [:get]
:exists? (fn [ctx]
(try (let [[run-id] (parse-longs [run-id])
run (run/get-run (tx-conn ctx) run-id)]
(when run {::run run}))
(catch NumberFormatException _)))
:handle-ok (fn [ctx] (let [screenshots (screenshot/get-screenshots-by-run-id (tx-conn ctx) (-> ctx ::run :id))]
(mapv update-screenshot-path screenshots)))))
(defn- proces-diff [conn run-id before-file after-file compare-settings before-id after-id mask]
(let [analysis (analysis/get-analysis conn run-id)
diff-report (analysisc/generate-diff-report before-file after-file mask compare-settings)
diff-file-id (image/insert-image! conn (:diff diff-report))
mask-file-id (image/insert-image! conn (:mask diff-report))
new-diff-id (analysis/save-diff! conn diff-file-id mask-file-id before-id after-id (:percentage diff-report) (:id analysis))]
(do
(.delete (:diff diff-report))
(analysis/get-diff conn run-id new-diff-id))))
(defn- process-screenshot [conn suite-id run-id screenshot-name properties compare-settings meta mask {:keys [tempfile]}]
(let [screenshot-id (screenshot/insert-screenshot! conn run-id screenshot-name properties meta tempfile)
screenshot (screenshot/get-screenshot-by-id conn screenshot-id)
baseline-screenshot (baseline/get-baseline-screenshot conn suite-id "master" screenshot-name properties)
before-file (when baseline-screenshot (io/get-file (image/get-image-path conn (:image-id baseline-screenshot))))
diff (proces-diff conn run-id before-file tempfile compare-settings (:id baseline-screenshot) screenshot-id mask)]
(when (and baseline-screenshot (zero? (:percentage diff)))
(update-diff-status! conn diff "accepted"))
screenshot))
(defn upload-screenshot [run-id]
(json-resource
:allowed-methods [:post]
:known-content-type? #(re-find #"multipart" (content-type %))
:malformed? false
:processable? (fn [ctx]
(let [v (v/validations upload-screenshot-schema (-> ctx :request :params
(update-in [:meta] json/parse-string true)
(update-in [:mask] json/parse-string true)
(update-in [:properties] json/parse-string true)
(update-in [:compareSettings] json/parse-string true)))]
(if (:valid? v)
(let [data (hyphenize-request (:data v))
run (run/get-run (tx-conn ctx) (Long/parseLong run-id))]
(if (or (= (:status run) "running") (nil? run))
{::data data ::run run}
[false {::error-msg (format "Run status must be 'running' to upload screenshots. Status is: %s" (:status run))}]))
[false {::error-msg (handle-invalid v
::v/screenshot "'file' is not a valid PNG file"
::v/screenshot-meta "Invalid meta or properties data. Are the values either strings or numbers?")}])))
:handle-unprocessable-entity ::error-msg
:exists? ::run
:can-post-to-missing? false
:post! (fn [ctx]
(ex/try+
(let [{:keys [meta mask file properties compare-settings screenshot-name]} (::data ctx)
{suite-id :suite-id run-id :id} (::run ctx)
screenshot (process-screenshot (tx-conn ctx) suite-id run-id screenshot-name properties compare-settings meta mask file)]
{::screenshot screenshot ::new? true})
(catch [:type :service-exception :code ::screenshot/screenshot-cannot-store-in-db-already-exists] _
{::screenshot {:error "Screenshot with identical name and properties was already uploaded in this run"
:conflicting-entity (select-keys (::data ctx) [:meta :properties :screenshot-name])}
::new? false})))
:new? ::new?
:respond-with-entity? true
:handle-created ::screenshot
:handle-ok ::screenshot))
(defn screenshots-resource [run-id]
(fn [req]
(if (get-request? {:request req})
(get-screenshots run-id)
(upload-screenshot run-id))))
;; Analysis
(defn- full-path [path id & {:keys [prefix] :or {prefix "/screenshots"}}]
(str prefix "/" path "/" id ".png"))
(defn- transform-diff [diff]
{:id (:id diff)
:before (when (:before diff)
{:id (:before diff)
:image-id (:before-image-id diff)
:size (:before-size diff)
:meta (:before-meta diff)
:properties (:before-properties diff)
:screenshotName (:before-name diff)})
:after {:id (:after diff)
:image-id (:after-image-id diff)
:size (:after-size diff)
:meta (:after-meta diff)
:properties (:after-properties diff)
:screenshotName (:after-name diff)}
:status (:status diff)
:percentage (:percentage diff)
:image-id (:image-id diff)
:mask-image-id (:mask-image-id diff)
})
(defn- transform-analysis [full-analysis]
(update-in full-analysis [:diffs] #(mapv transform-diff %)))
;; Diff Status
(defn analysis-resource [run-id]
(json-resource
:allowed-methods [:get]
:processable? (fn [ctx]
(try
(let [[run-id] (parse-longs [run-id])
analysis (analysis/get-full-analysis (tx-conn ctx) run-id)]
{::analysis analysis})
(catch NumberFormatException _)))
:exists? (fn [ctx] (not (empty? (-> ctx ::analysis :analysis))))
:handle-ok (comp transform-analysis ::analysis)))
(def ^:private update-diff-status-schema
{:status [String [::v/diff-status]]})
(defn diff-status-resource [run-id diff-id]
(json-resource
:allowed-methods [:post]
:processable? (fn [ctx]
(try
(let [[run-id diff-id] (parse-longs [run-id diff-id])
v (v/validations update-diff-status-schema (:parsed-json ctx))]
(if (:valid? v)
{::run-id run-id ::diff-id diff-id ::new-status (-> v :data :status)}
[false {::error-msg (handle-invalid v
::v/diff-status "'status' must be 'pending', 'accepted' or 'rejected'")}]))
(catch NumberFormatException _)))
:handle-unprocessable-entity ::error-msg
:exists? (fn [ctx]
(when-let [diff (analysis/get-diff (tx-conn ctx) (::run-id ctx) (::diff-id ctx))]
{::diff diff}))
:can-post-to-missing? false
:post! (fn [ctx]
;; First checks to see if this diff has a baseline-screenshot. If it has, it updates the diff
;; Otherwise, if the new-status is "accepted", it sets the after-screenshot as the new baseline
;; if it was not set before. If the new-status is "pending" or "rejected" it removes the baseline
;; regardless of whether it existed before
(let [baseline-screenshot (baseline/get-baseline-screenshot-by-diff-id (tx-conn ctx) diff-id)
after-id (-> ctx ::diff :after)]
(when-not baseline-screenshot ; new screenshot
(let [run (run/get-run (tx-conn ctx) run-id)
baseline-node (baseline/get-baseline-head (tx-conn ctx) (:suite-id run))]
(if (= (::new-status ctx) "accepted") ; set as baseline-screenshot
(let [bl (baseline/get-bl-node-screenshot (tx-conn ctx) baseline-node after-id)]
(when (nil? bl)
(baseline/create-bl-node-screenshot! (tx-conn ctx) baseline-node after-id)))
(baseline/delete-bl-node-screenshot! (tx-conn ctx) baseline-node after-id)))))
(update-diff-status! (tx-conn ctx) (::diff ctx) (::new-status ctx))
{::updated-diff (analysis/get-diff (tx-conn ctx) (::run-id ctx) (::diff-id ctx))})
:handle-created ::updated-diff))
(defn image [image-id]
(resource
:available-media-types ["image/png"]
:allowed-methods [:get]
:exists? (fn [ctx]
(let [image-path (image/get-image-path (tx-conn ctx) image-id)]
(if (nil? image-path)
false
{:image-path image-path})))
:handle-ok (fn [ctx]
(io/get-file (:image-path ctx)))))
;; Cleanup
(defn cleanup []
(resource
:allowed-methods [:post]
:post! (fn [ctx] (cleanup/cleanup-orphans! (tx-conn ctx)))
:handle-created (fn [_] (liberator.representation/ring-response
{:status 200}))))
|
[
{
"context": "pe-map\n {:string \"VARCHAR(2048)\"\n :password \"VARCHAR(512)\"\n :boolean \"BOOLEAN\"\n :int \"INTEGER\"\n ",
"end": 706,
"score": 0.9917213320732117,
"start": 695,
"tag": "PASSWORD",
"value": "VARCHAR(512"
}
] | src/main/com/fulcrologic/rad/database_adapters/sql/migration.clj | adamfeldman/fulcro-rad-sql | 4 | (ns com.fulcrologic.rad.database-adapters.sql.migration
(:require
[clojure.pprint :refer [pprint]]
[next.jdbc :as jdbc]
[clojure.string :as str]
[com.fulcrologic.rad.attributes :as attr]
[com.fulcrologic.guardrails.core :refer [>defn =>]]
[taoensso.encore :as enc]
[taoensso.timbre :as log]
[com.fulcrologic.rad.database-adapters.sql :as rad.sql]
[com.fulcrologic.rad.database-adapters.sql.vendor :as vendor]
[com.fulcrologic.rad.database-adapters.sql.schema :as sql.schema]
[clojure.spec.alpha :as s])
(:import (org.flywaydb.core Flyway)
(com.zaxxer.hikari HikariDataSource)))
(def type-map
{:string "VARCHAR(2048)"
:password "VARCHAR(512)"
:boolean "BOOLEAN"
:int "INTEGER"
:long "BIGINT"
:decimal "decimal(20,2)"
:instant "TIMESTAMP WITH TIME ZONE"
:inst "BIGINT"
;; There is no standard SQL enum, and many ppl think they are a bad idea in general. Given
;; that we have other ways of enforcing them we use a standard type instead.
:enum "VARCHAR(200)"
:keyword "VARCHAR(200)"
:symbol "VARCHAR(200)"
:uuid "UUID"})
(>defn sql-type [{::attr/keys [type]
::rad.sql/keys [max-length]}]
[::attr/attribute => string?]
(if (#{:string :password :keyword :symbol} type)
(if max-length
(str "VARCHAR(" max-length ")")
"VARCHAR(200)")
(if-let [result (get type-map type)]
result
(do
(log/error "Unsupported type" type)
"TEXT"))))
(>defn new-table [table]
[string? => map?]
{:type :table :table table})
(>defn new-scalar-column
[table column attr]
[string? string? ::attr/attribute => map?]
{:type :column :table table :column column :attr attr})
(>defn new-id-column [table column attr]
[string? string? ::attr/attribute => map?]
{:type :id :table table :column column :attr attr})
(>defn new-ref-column [table column attr]
[string? string? ::attr/attribute => map?]
{:type :ref :table table :column column :attr attr})
(defmulti op->sql (fn [k->attr adapter {:keys [type]}] type))
(defmethod op->sql :table [_ adapter {:keys [table]}] (format "CREATE TABLE IF NOT EXISTS %s ();\n" table))
(defmethod op->sql :ref [k->attr adapter {:keys [table column attr]}]
(let [{::attr/keys [cardinality target identities qualified-key]} attr
target-attr (k->attr target)]
(if (= :many cardinality)
(do
(when (not= 1 (count identities))
(throw (ex-info "Reference column must have exactly 1 ::attr/identities entry." {:k qualified-key})))
(enc/if-let [reverse-target-attr (k->attr (first identities))
rev-target-table (sql.schema/table-name k->attr reverse-target-attr)
rev-target-column (sql.schema/column-name reverse-target-attr)
table (sql.schema/table-name k->attr target-attr)
column (sql.schema/column-name k->attr attr)
index-name (str column "_idx")]
(str
(vendor/add-referential-column-statement adapter
table column (sql-type reverse-target-attr) rev-target-table rev-target-column)
(format "CREATE INDEX IF NOT EXISTS %s ON %s(%s);\n"
index-name table column))
(throw (ex-info "Cannot create to-many reference column." {:k qualified-key}))))
(enc/if-let [origin-table (sql.schema/table-name k->attr attr)
origin-column (sql.schema/column-name attr)
target-table (sql.schema/table-name k->attr target-attr)
target-column (sql.schema/column-name target-attr)
target-type (sql-type target-attr)
index-name (str column "_idx")]
(str
(vendor/add-referential-column-statement adapter
origin-table origin-column target-type target-table target-column)
(format "CREATE INDEX IF NOT EXISTS %s ON %s(%s);\n"
index-name table column))
(throw (ex-info "Cannot create to-many reference column." {:k qualified-key}))))))
(defmethod op->sql :id [k->attr adapter {:keys [table column attr]}]
(let [{::attr/keys [type]} attr
index-name (str table "_" column "_idx")
sequence-name (str table "_" column "_seq")
typ (sql-type attr)]
(str
(if (#{:int :long} type)
(str
(format "CREATE SEQUENCE IF NOT EXISTS %s;\n" sequence-name)
(format "ALTER TABLE %s ADD COLUMN IF NOT EXISTS %s %s DEFAULT nextval('%s');\n"
table column typ sequence-name))
(format "ALTER TABLE %s ADD COLUMN IF NOT EXISTS %s %s;\n"
table column typ sequence-name))
(format "CREATE UNIQUE INDEX IF NOT EXISTS %s ON %s(%s);\n"
index-name table column))))
(defmethod op->sql :column [key->attr adapter {:keys [table column attr]}]
(let [{::attr/keys [type enumerated-values]} attr]
(format "ALTER TABLE %s ADD COLUMN IF NOT EXISTS %s %s;\n" table column (sql-type attr))))
(defn attr->ops [schema-name key->attribute {::attr/keys [qualified-key type identity? identities]
:keys [::attr/schema]
:as attr}]
(when (= schema schema-name)
(enc/if-let [tables-and-columns (seq (sql.schema/tables-and-columns key->attribute attr))]
(reduce
(fn [s [table col]]
(-> s
(conj (new-table table))
(conj (cond
identity? (new-id-column table col attr)
(= :ref type) (new-ref-column table col attr)
:else (new-scalar-column table col attr)))))
[]
tables-and-columns)
(log/error "Correct schema for attribute, but generation failed: "
(::attr/qualified-key attr)
(when (nil? (sql-type attr))
(str " (No mapping for type " type ")"))))))
(>defn automatic-schema
"Returns SQL schema for all attributes that support it."
[schema-name adapter attributes]
[keyword? ::vendor/adapter ::attr/attributes => (s/coll-of string?)]
(let [key->attribute (attr/attribute-map attributes)
db-ops (mapcat (partial attr->ops schema-name key->attribute) attributes)
{:keys [id table column ref]} (group-by :type db-ops)
op (partial op->sql key->attribute adapter)
new-tables (mapv op (set table))
new-ids (mapv op (set id))
new-columns (mapv op (set column))
new-refs (mapv op (set ref))]
(vec (concat new-tables new-ids new-columns new-refs))))
(defn migrate! [config all-attributes connection-pools]
(let [database-map (some-> config ::rad.sql/databases)]
(doseq [[dbkey dbconfig] database-map]
(let [{:sql/keys [auto-create-missing? schema vendor]
:flyway/keys [migrate? migrations]} dbconfig
^HikariDataSource pool (get connection-pools dbkey)
db {:datasource pool}
adapter (case vendor
:postgresql (vendor/->PostgreSQLAdapter)
(vendor/->H2Adapter))]
(if pool
(cond
(and migrate? (seq migrations))
(do
(log/info (str "Processing Flywawy migrations for " dbkey))
(let [flyway (Flyway.)]
(log/info "Migration location is set to: " migrations)
(.setLocations flyway (into-array String migrations))
(.setDataSource flyway pool)
(.setBaselineOnMigrate flyway true)
(.migrate flyway)))
auto-create-missing?
(let [stmts (automatic-schema schema adapter all-attributes)]
(log/info "Automatically trying to create SQL schema from attributes.")
(doseq [s stmts]
(try
(jdbc/execute! pool [s])
(catch Exception e
(log/error e s)
(throw e))))))
(log/error (str "No pool for " dbkey ". Skipping migrations.")))))))
| 36651 | (ns com.fulcrologic.rad.database-adapters.sql.migration
(:require
[clojure.pprint :refer [pprint]]
[next.jdbc :as jdbc]
[clojure.string :as str]
[com.fulcrologic.rad.attributes :as attr]
[com.fulcrologic.guardrails.core :refer [>defn =>]]
[taoensso.encore :as enc]
[taoensso.timbre :as log]
[com.fulcrologic.rad.database-adapters.sql :as rad.sql]
[com.fulcrologic.rad.database-adapters.sql.vendor :as vendor]
[com.fulcrologic.rad.database-adapters.sql.schema :as sql.schema]
[clojure.spec.alpha :as s])
(:import (org.flywaydb.core Flyway)
(com.zaxxer.hikari HikariDataSource)))
(def type-map
{:string "VARCHAR(2048)"
:password "<PASSWORD>)"
:boolean "BOOLEAN"
:int "INTEGER"
:long "BIGINT"
:decimal "decimal(20,2)"
:instant "TIMESTAMP WITH TIME ZONE"
:inst "BIGINT"
;; There is no standard SQL enum, and many ppl think they are a bad idea in general. Given
;; that we have other ways of enforcing them we use a standard type instead.
:enum "VARCHAR(200)"
:keyword "VARCHAR(200)"
:symbol "VARCHAR(200)"
:uuid "UUID"})
(>defn sql-type [{::attr/keys [type]
::rad.sql/keys [max-length]}]
[::attr/attribute => string?]
(if (#{:string :password :keyword :symbol} type)
(if max-length
(str "VARCHAR(" max-length ")")
"VARCHAR(200)")
(if-let [result (get type-map type)]
result
(do
(log/error "Unsupported type" type)
"TEXT"))))
(>defn new-table [table]
[string? => map?]
{:type :table :table table})
(>defn new-scalar-column
[table column attr]
[string? string? ::attr/attribute => map?]
{:type :column :table table :column column :attr attr})
(>defn new-id-column [table column attr]
[string? string? ::attr/attribute => map?]
{:type :id :table table :column column :attr attr})
(>defn new-ref-column [table column attr]
[string? string? ::attr/attribute => map?]
{:type :ref :table table :column column :attr attr})
(defmulti op->sql (fn [k->attr adapter {:keys [type]}] type))
(defmethod op->sql :table [_ adapter {:keys [table]}] (format "CREATE TABLE IF NOT EXISTS %s ();\n" table))
(defmethod op->sql :ref [k->attr adapter {:keys [table column attr]}]
(let [{::attr/keys [cardinality target identities qualified-key]} attr
target-attr (k->attr target)]
(if (= :many cardinality)
(do
(when (not= 1 (count identities))
(throw (ex-info "Reference column must have exactly 1 ::attr/identities entry." {:k qualified-key})))
(enc/if-let [reverse-target-attr (k->attr (first identities))
rev-target-table (sql.schema/table-name k->attr reverse-target-attr)
rev-target-column (sql.schema/column-name reverse-target-attr)
table (sql.schema/table-name k->attr target-attr)
column (sql.schema/column-name k->attr attr)
index-name (str column "_idx")]
(str
(vendor/add-referential-column-statement adapter
table column (sql-type reverse-target-attr) rev-target-table rev-target-column)
(format "CREATE INDEX IF NOT EXISTS %s ON %s(%s);\n"
index-name table column))
(throw (ex-info "Cannot create to-many reference column." {:k qualified-key}))))
(enc/if-let [origin-table (sql.schema/table-name k->attr attr)
origin-column (sql.schema/column-name attr)
target-table (sql.schema/table-name k->attr target-attr)
target-column (sql.schema/column-name target-attr)
target-type (sql-type target-attr)
index-name (str column "_idx")]
(str
(vendor/add-referential-column-statement adapter
origin-table origin-column target-type target-table target-column)
(format "CREATE INDEX IF NOT EXISTS %s ON %s(%s);\n"
index-name table column))
(throw (ex-info "Cannot create to-many reference column." {:k qualified-key}))))))
(defmethod op->sql :id [k->attr adapter {:keys [table column attr]}]
(let [{::attr/keys [type]} attr
index-name (str table "_" column "_idx")
sequence-name (str table "_" column "_seq")
typ (sql-type attr)]
(str
(if (#{:int :long} type)
(str
(format "CREATE SEQUENCE IF NOT EXISTS %s;\n" sequence-name)
(format "ALTER TABLE %s ADD COLUMN IF NOT EXISTS %s %s DEFAULT nextval('%s');\n"
table column typ sequence-name))
(format "ALTER TABLE %s ADD COLUMN IF NOT EXISTS %s %s;\n"
table column typ sequence-name))
(format "CREATE UNIQUE INDEX IF NOT EXISTS %s ON %s(%s);\n"
index-name table column))))
(defmethod op->sql :column [key->attr adapter {:keys [table column attr]}]
(let [{::attr/keys [type enumerated-values]} attr]
(format "ALTER TABLE %s ADD COLUMN IF NOT EXISTS %s %s;\n" table column (sql-type attr))))
(defn attr->ops [schema-name key->attribute {::attr/keys [qualified-key type identity? identities]
:keys [::attr/schema]
:as attr}]
(when (= schema schema-name)
(enc/if-let [tables-and-columns (seq (sql.schema/tables-and-columns key->attribute attr))]
(reduce
(fn [s [table col]]
(-> s
(conj (new-table table))
(conj (cond
identity? (new-id-column table col attr)
(= :ref type) (new-ref-column table col attr)
:else (new-scalar-column table col attr)))))
[]
tables-and-columns)
(log/error "Correct schema for attribute, but generation failed: "
(::attr/qualified-key attr)
(when (nil? (sql-type attr))
(str " (No mapping for type " type ")"))))))
(>defn automatic-schema
"Returns SQL schema for all attributes that support it."
[schema-name adapter attributes]
[keyword? ::vendor/adapter ::attr/attributes => (s/coll-of string?)]
(let [key->attribute (attr/attribute-map attributes)
db-ops (mapcat (partial attr->ops schema-name key->attribute) attributes)
{:keys [id table column ref]} (group-by :type db-ops)
op (partial op->sql key->attribute adapter)
new-tables (mapv op (set table))
new-ids (mapv op (set id))
new-columns (mapv op (set column))
new-refs (mapv op (set ref))]
(vec (concat new-tables new-ids new-columns new-refs))))
(defn migrate! [config all-attributes connection-pools]
(let [database-map (some-> config ::rad.sql/databases)]
(doseq [[dbkey dbconfig] database-map]
(let [{:sql/keys [auto-create-missing? schema vendor]
:flyway/keys [migrate? migrations]} dbconfig
^HikariDataSource pool (get connection-pools dbkey)
db {:datasource pool}
adapter (case vendor
:postgresql (vendor/->PostgreSQLAdapter)
(vendor/->H2Adapter))]
(if pool
(cond
(and migrate? (seq migrations))
(do
(log/info (str "Processing Flywawy migrations for " dbkey))
(let [flyway (Flyway.)]
(log/info "Migration location is set to: " migrations)
(.setLocations flyway (into-array String migrations))
(.setDataSource flyway pool)
(.setBaselineOnMigrate flyway true)
(.migrate flyway)))
auto-create-missing?
(let [stmts (automatic-schema schema adapter all-attributes)]
(log/info "Automatically trying to create SQL schema from attributes.")
(doseq [s stmts]
(try
(jdbc/execute! pool [s])
(catch Exception e
(log/error e s)
(throw e))))))
(log/error (str "No pool for " dbkey ". Skipping migrations.")))))))
| true | (ns com.fulcrologic.rad.database-adapters.sql.migration
(:require
[clojure.pprint :refer [pprint]]
[next.jdbc :as jdbc]
[clojure.string :as str]
[com.fulcrologic.rad.attributes :as attr]
[com.fulcrologic.guardrails.core :refer [>defn =>]]
[taoensso.encore :as enc]
[taoensso.timbre :as log]
[com.fulcrologic.rad.database-adapters.sql :as rad.sql]
[com.fulcrologic.rad.database-adapters.sql.vendor :as vendor]
[com.fulcrologic.rad.database-adapters.sql.schema :as sql.schema]
[clojure.spec.alpha :as s])
(:import (org.flywaydb.core Flyway)
(com.zaxxer.hikari HikariDataSource)))
(def type-map
{:string "VARCHAR(2048)"
:password "PI:PASSWORD:<PASSWORD>END_PI)"
:boolean "BOOLEAN"
:int "INTEGER"
:long "BIGINT"
:decimal "decimal(20,2)"
:instant "TIMESTAMP WITH TIME ZONE"
:inst "BIGINT"
;; There is no standard SQL enum, and many ppl think they are a bad idea in general. Given
;; that we have other ways of enforcing them we use a standard type instead.
:enum "VARCHAR(200)"
:keyword "VARCHAR(200)"
:symbol "VARCHAR(200)"
:uuid "UUID"})
(>defn sql-type [{::attr/keys [type]
::rad.sql/keys [max-length]}]
[::attr/attribute => string?]
(if (#{:string :password :keyword :symbol} type)
(if max-length
(str "VARCHAR(" max-length ")")
"VARCHAR(200)")
(if-let [result (get type-map type)]
result
(do
(log/error "Unsupported type" type)
"TEXT"))))
(>defn new-table [table]
[string? => map?]
{:type :table :table table})
(>defn new-scalar-column
[table column attr]
[string? string? ::attr/attribute => map?]
{:type :column :table table :column column :attr attr})
(>defn new-id-column [table column attr]
[string? string? ::attr/attribute => map?]
{:type :id :table table :column column :attr attr})
(>defn new-ref-column [table column attr]
[string? string? ::attr/attribute => map?]
{:type :ref :table table :column column :attr attr})
(defmulti op->sql (fn [k->attr adapter {:keys [type]}] type))
(defmethod op->sql :table [_ adapter {:keys [table]}] (format "CREATE TABLE IF NOT EXISTS %s ();\n" table))
(defmethod op->sql :ref [k->attr adapter {:keys [table column attr]}]
(let [{::attr/keys [cardinality target identities qualified-key]} attr
target-attr (k->attr target)]
(if (= :many cardinality)
(do
(when (not= 1 (count identities))
(throw (ex-info "Reference column must have exactly 1 ::attr/identities entry." {:k qualified-key})))
(enc/if-let [reverse-target-attr (k->attr (first identities))
rev-target-table (sql.schema/table-name k->attr reverse-target-attr)
rev-target-column (sql.schema/column-name reverse-target-attr)
table (sql.schema/table-name k->attr target-attr)
column (sql.schema/column-name k->attr attr)
index-name (str column "_idx")]
(str
(vendor/add-referential-column-statement adapter
table column (sql-type reverse-target-attr) rev-target-table rev-target-column)
(format "CREATE INDEX IF NOT EXISTS %s ON %s(%s);\n"
index-name table column))
(throw (ex-info "Cannot create to-many reference column." {:k qualified-key}))))
(enc/if-let [origin-table (sql.schema/table-name k->attr attr)
origin-column (sql.schema/column-name attr)
target-table (sql.schema/table-name k->attr target-attr)
target-column (sql.schema/column-name target-attr)
target-type (sql-type target-attr)
index-name (str column "_idx")]
(str
(vendor/add-referential-column-statement adapter
origin-table origin-column target-type target-table target-column)
(format "CREATE INDEX IF NOT EXISTS %s ON %s(%s);\n"
index-name table column))
(throw (ex-info "Cannot create to-many reference column." {:k qualified-key}))))))
(defmethod op->sql :id [k->attr adapter {:keys [table column attr]}]
(let [{::attr/keys [type]} attr
index-name (str table "_" column "_idx")
sequence-name (str table "_" column "_seq")
typ (sql-type attr)]
(str
(if (#{:int :long} type)
(str
(format "CREATE SEQUENCE IF NOT EXISTS %s;\n" sequence-name)
(format "ALTER TABLE %s ADD COLUMN IF NOT EXISTS %s %s DEFAULT nextval('%s');\n"
table column typ sequence-name))
(format "ALTER TABLE %s ADD COLUMN IF NOT EXISTS %s %s;\n"
table column typ sequence-name))
(format "CREATE UNIQUE INDEX IF NOT EXISTS %s ON %s(%s);\n"
index-name table column))))
(defmethod op->sql :column [key->attr adapter {:keys [table column attr]}]
(let [{::attr/keys [type enumerated-values]} attr]
(format "ALTER TABLE %s ADD COLUMN IF NOT EXISTS %s %s;\n" table column (sql-type attr))))
(defn attr->ops [schema-name key->attribute {::attr/keys [qualified-key type identity? identities]
:keys [::attr/schema]
:as attr}]
(when (= schema schema-name)
(enc/if-let [tables-and-columns (seq (sql.schema/tables-and-columns key->attribute attr))]
(reduce
(fn [s [table col]]
(-> s
(conj (new-table table))
(conj (cond
identity? (new-id-column table col attr)
(= :ref type) (new-ref-column table col attr)
:else (new-scalar-column table col attr)))))
[]
tables-and-columns)
(log/error "Correct schema for attribute, but generation failed: "
(::attr/qualified-key attr)
(when (nil? (sql-type attr))
(str " (No mapping for type " type ")"))))))
(>defn automatic-schema
"Returns SQL schema for all attributes that support it."
[schema-name adapter attributes]
[keyword? ::vendor/adapter ::attr/attributes => (s/coll-of string?)]
(let [key->attribute (attr/attribute-map attributes)
db-ops (mapcat (partial attr->ops schema-name key->attribute) attributes)
{:keys [id table column ref]} (group-by :type db-ops)
op (partial op->sql key->attribute adapter)
new-tables (mapv op (set table))
new-ids (mapv op (set id))
new-columns (mapv op (set column))
new-refs (mapv op (set ref))]
(vec (concat new-tables new-ids new-columns new-refs))))
(defn migrate! [config all-attributes connection-pools]
(let [database-map (some-> config ::rad.sql/databases)]
(doseq [[dbkey dbconfig] database-map]
(let [{:sql/keys [auto-create-missing? schema vendor]
:flyway/keys [migrate? migrations]} dbconfig
^HikariDataSource pool (get connection-pools dbkey)
db {:datasource pool}
adapter (case vendor
:postgresql (vendor/->PostgreSQLAdapter)
(vendor/->H2Adapter))]
(if pool
(cond
(and migrate? (seq migrations))
(do
(log/info (str "Processing Flywawy migrations for " dbkey))
(let [flyway (Flyway.)]
(log/info "Migration location is set to: " migrations)
(.setLocations flyway (into-array String migrations))
(.setDataSource flyway pool)
(.setBaselineOnMigrate flyway true)
(.migrate flyway)))
auto-create-missing?
(let [stmts (automatic-schema schema adapter all-attributes)]
(log/info "Automatically trying to create SQL schema from attributes.")
(doseq [s stmts]
(try
(jdbc/execute! pool [s])
(catch Exception e
(log/error e s)
(throw e))))))
(log/error (str "No pool for " dbkey ". Skipping migrations.")))))))
|
[
{
"context": "ey \"groups:\" \"\"))\n\n(def CURRENT_FREE_USER_ID_KEY \"user-id\")\n\n(defn new-user-key [redis-component]\n (if-let",
"end": 523,
"score": 0.8474028706550598,
"start": 516,
"tag": "KEY",
"value": "user-id"
}
] | src/com/github/meandor/user/repository.clj | meandor/the-queen | 1 | (ns com.github.meandor.user.repository
(:require [com.github.meandor.redis-component :as rc]
[taoensso.carmine :as car]
[clojure.walk :as w]
[clojure.string :as str]))
(defn user-id->user-key [user-id]
(str "user:" user-id))
(defn user-key->user-id [user-key]
(str/replace user-key "user:" ""))
(defn group-id->group-key [group-id]
(str "groups:" group-id))
(defn group-key->group-id [group-key]
(str/replace group-key "groups:" ""))
(def CURRENT_FREE_USER_ID_KEY "user-id")
(defn new-user-key [redis-component]
(if-let [user-id (rc/wcar* redis-component (car/get CURRENT_FREE_USER_ID_KEY))]
(user-id->user-key (inc (read-string user-id)))
(user-id->user-key 1)))
(def LIST_SEPARATOR "/")
(defn- combined-group-keys [group-ids]
(->> group-ids
(map group-id->group-key)
(str/join LIST_SEPARATOR)))
(defn- add-user-to-db [redis-component user-key user]
(rc/wcar* redis-component
(doseq [[k v] (update user :groups combined-group-keys)]
(car/hset user-key k v))
(doseq [group-key (map group-id->group-key (:groups user))]
(car/sadd group-key user-key))))
(defn register-user [redis-component user]
(let [user-key (new-user-key redis-component)]
(add-user-to-db redis-component user-key user)
(rc/wcar* redis-component (car/incr CURRENT_FREE_USER_ID_KEY))
(user-key->user-id user-key)))
(defn- split-combined-groups [combined-groups]
(->> (str/split combined-groups (re-pattern LIST_SEPARATOR))
(map group-key->group-id)))
(defn redis-user-vector->user-map [vector]
(when (not (empty? vector))
(-> (w/keywordize-keys (apply hash-map vector))
(update :groups split-combined-groups))))
(defn find-user [redis-component user-id]
(redis-user-vector->user-map (rc/wcar* redis-component (car/hgetall (user-id->user-key user-id)))))
(defn- user-groups-with-keys [redis-component user-key]
(-> redis-component
(rc/wcar* (car/hget user-key "groups"))
(str/split (re-pattern LIST_SEPARATOR))))
(defn find-user-groups [redis-component user-id]
(->> (user-groups-with-keys redis-component (user-id->user-key user-id))
(map group-key->group-id)))
(defn- delete-key [redis-component key]
(rc/wcar* redis-component (car/del key)))
(defn delete-user [redis-component user-id]
(let [user-key (user-id->user-key user-id)]
(rc/wcar* redis-component (doseq [group-key (user-groups-with-keys redis-component user-key)]
(car/srem group-key user-key)))
(delete-key redis-component user-key)))
(defn update-user [redis-component user-id user]
(delete-user redis-component user-id)
(add-user-to-db redis-component (user-id->user-key user-id) user)
user-id)
(defn find-group-member [redis-component group-id]
(map user-key->user-id (rc/wcar* redis-component (car/smembers (group-id->group-key group-id)))))
(defn all-group-ids [redis-component]
(->> (rc/wcar* redis-component (car/keys "groups:*"))
(map group-key->group-id)))
(defn delete-group [redis-component group-id]
(delete-key redis-component (group-id->group-key group-id)))
| 7569 | (ns com.github.meandor.user.repository
(:require [com.github.meandor.redis-component :as rc]
[taoensso.carmine :as car]
[clojure.walk :as w]
[clojure.string :as str]))
(defn user-id->user-key [user-id]
(str "user:" user-id))
(defn user-key->user-id [user-key]
(str/replace user-key "user:" ""))
(defn group-id->group-key [group-id]
(str "groups:" group-id))
(defn group-key->group-id [group-key]
(str/replace group-key "groups:" ""))
(def CURRENT_FREE_USER_ID_KEY "<KEY>")
(defn new-user-key [redis-component]
(if-let [user-id (rc/wcar* redis-component (car/get CURRENT_FREE_USER_ID_KEY))]
(user-id->user-key (inc (read-string user-id)))
(user-id->user-key 1)))
(def LIST_SEPARATOR "/")
(defn- combined-group-keys [group-ids]
(->> group-ids
(map group-id->group-key)
(str/join LIST_SEPARATOR)))
(defn- add-user-to-db [redis-component user-key user]
(rc/wcar* redis-component
(doseq [[k v] (update user :groups combined-group-keys)]
(car/hset user-key k v))
(doseq [group-key (map group-id->group-key (:groups user))]
(car/sadd group-key user-key))))
(defn register-user [redis-component user]
(let [user-key (new-user-key redis-component)]
(add-user-to-db redis-component user-key user)
(rc/wcar* redis-component (car/incr CURRENT_FREE_USER_ID_KEY))
(user-key->user-id user-key)))
(defn- split-combined-groups [combined-groups]
(->> (str/split combined-groups (re-pattern LIST_SEPARATOR))
(map group-key->group-id)))
(defn redis-user-vector->user-map [vector]
(when (not (empty? vector))
(-> (w/keywordize-keys (apply hash-map vector))
(update :groups split-combined-groups))))
(defn find-user [redis-component user-id]
(redis-user-vector->user-map (rc/wcar* redis-component (car/hgetall (user-id->user-key user-id)))))
(defn- user-groups-with-keys [redis-component user-key]
(-> redis-component
(rc/wcar* (car/hget user-key "groups"))
(str/split (re-pattern LIST_SEPARATOR))))
(defn find-user-groups [redis-component user-id]
(->> (user-groups-with-keys redis-component (user-id->user-key user-id))
(map group-key->group-id)))
(defn- delete-key [redis-component key]
(rc/wcar* redis-component (car/del key)))
(defn delete-user [redis-component user-id]
(let [user-key (user-id->user-key user-id)]
(rc/wcar* redis-component (doseq [group-key (user-groups-with-keys redis-component user-key)]
(car/srem group-key user-key)))
(delete-key redis-component user-key)))
(defn update-user [redis-component user-id user]
(delete-user redis-component user-id)
(add-user-to-db redis-component (user-id->user-key user-id) user)
user-id)
(defn find-group-member [redis-component group-id]
(map user-key->user-id (rc/wcar* redis-component (car/smembers (group-id->group-key group-id)))))
(defn all-group-ids [redis-component]
(->> (rc/wcar* redis-component (car/keys "groups:*"))
(map group-key->group-id)))
(defn delete-group [redis-component group-id]
(delete-key redis-component (group-id->group-key group-id)))
| true | (ns com.github.meandor.user.repository
(:require [com.github.meandor.redis-component :as rc]
[taoensso.carmine :as car]
[clojure.walk :as w]
[clojure.string :as str]))
(defn user-id->user-key [user-id]
(str "user:" user-id))
(defn user-key->user-id [user-key]
(str/replace user-key "user:" ""))
(defn group-id->group-key [group-id]
(str "groups:" group-id))
(defn group-key->group-id [group-key]
(str/replace group-key "groups:" ""))
(def CURRENT_FREE_USER_ID_KEY "PI:KEY:<KEY>END_PI")
(defn new-user-key [redis-component]
(if-let [user-id (rc/wcar* redis-component (car/get CURRENT_FREE_USER_ID_KEY))]
(user-id->user-key (inc (read-string user-id)))
(user-id->user-key 1)))
(def LIST_SEPARATOR "/")
(defn- combined-group-keys [group-ids]
(->> group-ids
(map group-id->group-key)
(str/join LIST_SEPARATOR)))
(defn- add-user-to-db [redis-component user-key user]
(rc/wcar* redis-component
(doseq [[k v] (update user :groups combined-group-keys)]
(car/hset user-key k v))
(doseq [group-key (map group-id->group-key (:groups user))]
(car/sadd group-key user-key))))
(defn register-user [redis-component user]
(let [user-key (new-user-key redis-component)]
(add-user-to-db redis-component user-key user)
(rc/wcar* redis-component (car/incr CURRENT_FREE_USER_ID_KEY))
(user-key->user-id user-key)))
(defn- split-combined-groups [combined-groups]
(->> (str/split combined-groups (re-pattern LIST_SEPARATOR))
(map group-key->group-id)))
(defn redis-user-vector->user-map [vector]
(when (not (empty? vector))
(-> (w/keywordize-keys (apply hash-map vector))
(update :groups split-combined-groups))))
(defn find-user [redis-component user-id]
(redis-user-vector->user-map (rc/wcar* redis-component (car/hgetall (user-id->user-key user-id)))))
(defn- user-groups-with-keys [redis-component user-key]
(-> redis-component
(rc/wcar* (car/hget user-key "groups"))
(str/split (re-pattern LIST_SEPARATOR))))
(defn find-user-groups [redis-component user-id]
(->> (user-groups-with-keys redis-component (user-id->user-key user-id))
(map group-key->group-id)))
(defn- delete-key [redis-component key]
(rc/wcar* redis-component (car/del key)))
(defn delete-user [redis-component user-id]
(let [user-key (user-id->user-key user-id)]
(rc/wcar* redis-component (doseq [group-key (user-groups-with-keys redis-component user-key)]
(car/srem group-key user-key)))
(delete-key redis-component user-key)))
(defn update-user [redis-component user-id user]
(delete-user redis-component user-id)
(add-user-to-db redis-component (user-id->user-key user-id) user)
user-id)
(defn find-group-member [redis-component group-id]
(map user-key->user-id (rc/wcar* redis-component (car/smembers (group-id->group-key group-id)))))
(defn all-group-ids [redis-component]
(->> (rc/wcar* redis-component (car/keys "groups:*"))
(map group-key->group-id)))
(defn delete-group [redis-component group-id]
(delete-key redis-component (group-id->group-key group-id)))
|
[
{
"context": " (if (some #{(get-in @app-state [:user :username])} (get-in @app-state [:donators]))\n ",
"end": 49605,
"score": 0.9983797669410706,
"start": 49597,
"tag": "USERNAME",
"value": "username"
},
{
"context": " {:name \"Ringwraith Rune 18mm\" :ref \"rune-w-18\"}]]\n ",
"end": 51529,
"score": 0.7701802849769592,
"start": 51527,
"tag": "NAME",
"value": "ra"
}
] | src/cljs/meccg/deckbuilder.cljs | rezwits/carncode | 15 | (ns meccg.deckbuilder
(:require-macros [cljs.core.async.macros :refer [go]])
(:require [om.core :as om :include-macros true]
[sablono.core :as sab :include-macros true]
[cljs.core.async :refer [chan put! <! timeout] :as async]
[clojure.string :refer [split split-lines join escape] :as s]
[meccg.appstate :refer [app-state]]
[meccg.auth :refer [authenticated] :as auth]
[meccg.cardbrowser :refer [cards-channel image-url card-view card-ndce card-dce filter-title] :as cb]
[meccg.ajax :refer [POST GET DELETE PUT]]
[meccg.utils :refer [banned-span restricted-span rotated-span influence-dot influence-dots alliance-dots dots-html make-dots]]
[goog.string :as gstring]
[goog.string.format]
[cardnum.utils :refer [str->int lookup-deck parse-deck-string INFINITY] :as utils]
[cardnum.cards :refer [all-cards]]
[cardnum.decks :as decks]
[cardnum.cards :as cards]))
(def select-channel (chan))
(def zoom-channel (chan))
(defn num->percent
"Converts an input number to a percent of the second input number for display"
[num1 num2]
(if (zero? num2)
"0"
(gstring/format "%.0f" (* 100 (float (/ num1 num2))))))
(defn noinfcost? [identity card]
(or (= (:faction card) (:faction identity))
(= 0 (:factioncost card)) (= INFINITY (decks/id-inf-limit identity))))
(defn identity-lookup
"Lookup the identity (query) looking at all cards on specified alignment"
[alignment card]
(let [q (.toLowerCase (:title card))
id (:id card)
cards (filter #(= (:alignment %) alignment) @all-cards)
exact-matches (utils/filter-exact-title q cards)]
(cond (and id
(first (filter #(= id (:trimCode %)) cards)))
(let [id-matches (filter #(= id (:trimCode %)) cards)]
(first (utils/filter-exact-title q id-matches)))
(not-empty exact-matches) (utils/take-best-card exact-matches)
:else
(loop [i 2 matches cards]
(let [subquery (subs q 0 i)]
(cond (zero? (count matches)) card
(or (= (count matches) 1) (utils/identical-cards? matches)) (utils/take-best-card matches)
(<= i (count (:title card))) (recur (inc i) (utils/filter-title subquery matches))
:else card))))))
(defn- build-identity-name
[title set_code art]
(let [set-title (if set_code (str title " (" set_code ")") title)]
(if art
(str set-title " [" art "]")
set-title)))
(defn parse-identity
"Parse an id to the corresponding card map"
[{:keys [alignment title art set_code]}]
(let [card (identity-lookup alignment {:title title})]
(assoc card :art art :display-name (build-identity-name title set_code art))))
(defn add-params-to-card
"Add art and id parameters to a card hash"
[card id]
(-> card
(assoc :id id)))
(defn- clean-param
"Parse card parameter key value pairs from a string"
[param]
(if (and param
(= 2 (count param)))
(let [[k v] (map s/trim param)
allowed-keys '("id" "art")]
(if (some #{k} allowed-keys)
[(keyword k) v]
nil))
nil))
(defn- param-reducer
[acc param]
(if param
(assoc acc (first param) (second param))
acc))
(defn- add-params
"Parse a string of parameters and add them to a map"
[result params-str]
(if params-str
(let [params-groups (split params-str #"\,")
params-all (map #(split % #":") params-groups)
params-clean (map #(clean-param %) params-all)]
(reduce param-reducer result params-clean))
result))
(defn load-decks [decks]
(swap! app-state assoc :decks (sort-by :date > decks))
(when-let [selected-deck (first (sort-by :date > decks))]
(put! select-channel selected-deck))
(swap! app-state assoc :decks-loaded true))
(defn org-decks-name [decks owner]
(let [wizard-decks (when (om/get-state owner :wizard) (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "Hero") decks)))
minion-decks (if (om/get-state owner :minion)
(into wizard-decks (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "Minion") decks)))
wizard-decks)
fallen-decks (if (om/get-state owner :fallen)
(into minion-decks (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "Fallen-wizard") decks)))
minion-decks)
balrog-decks (if (om/get-state owner :balrog)
(into fallen-decks (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "Balrog") decks)))
fallen-decks)
el-decks (if (om/get-state owner :el)
(into balrog-decks (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "Elf-lord") decks)))
balrog-decks)
dl-decks (if (om/get-state owner :dl)
(into el-decks (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "Dwarf-lord") decks)))
el-decks)
al-decks (if (om/get-state owner :al)
(into dl-decks (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "Atani-lord") decks)))
dl-decks)
wl-decks (if (om/get-state owner :wl)
(into al-decks (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "War-lord") decks)))
al-decks)
dragon-decks (if (om/get-state owner :dragon)
(into wl-decks (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "Dragon-lord") decks)))
wl-decks)
sorted-decks (sort-by :name < dragon-decks)]
(om/set-state! owner :decks-filtered sorted-decks)
(when-let [selected-deck (first (sort-by :name < :decks-filtered))]
(put! select-channel selected-deck))
(swap! app-state assoc :decks-loaded true)))
(defn org-decks-date [decks owner]
(let [wizard-decks (when (om/get-state owner :wizard) (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "Hero") decks)))
minion-decks (if (om/get-state owner :minion)
(into wizard-decks (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "Minion") decks)))
wizard-decks)
fallen-decks (if (om/get-state owner :fallen)
(into minion-decks (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "Fallen-wizard") decks)))
minion-decks)
balrog-decks (if (om/get-state owner :balrog)
(into fallen-decks (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "Balrog") decks)))
fallen-decks)
el-decks (if (om/get-state owner :el)
(into balrog-decks (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "Elf-lord") decks)))
balrog-decks)
dl-decks (if (om/get-state owner :dl)
(into el-decks (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "Dwarf-lord") decks)))
el-decks)
al-decks (if (om/get-state owner :al)
(into dl-decks (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "Atani-lord") decks)))
dl-decks)
wl-decks (if (om/get-state owner :wl)
(into al-decks (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "War-lord") decks)))
al-decks)
dragon-decks (if (om/get-state owner :dragon)
(into wl-decks (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "Dragon-lord") decks)))
wl-decks)
sorted-decks (sort-by :date > dragon-decks)]
(om/set-state! owner :decks-filtered sorted-decks)
(when-let [selected-deck (first (sort-by :date > :decks-filtered))]
(put! select-channel selected-deck))
(swap! app-state assoc :decks-loaded true)))
(defn process-decks
"Process the raw deck from the database into a more useful format"
[decks]
(for [deck decks]
(let [identity (parse-identity (:identity deck))
donate-dice (:donate-dice deck)
donate-size (:donate-size deck)
resources (lookup-deck (:resources deck))
hazards (lookup-deck (:hazards deck))
sideboard (lookup-deck (:sideboard deck))
characters (lookup-deck (:characters deck))
pool (lookup-deck (:pool deck))
fwsb (lookup-deck (:fwsb deck))
note (:note deck)]
(assoc deck :resources resources :hazards hazards :sideboard sideboard
:characters characters :pool pool :fwsb fwsb
:identity identity :note note
:donate-dice donate-dice :donate-size donate-size
))))
(defn distinct-by [f coll]
(letfn [(step [xs seen]
(lazy-seq (when-let [[x & more] (seq xs)]
(let [k (f x)]
(if (seen k)
(step more seen)
(cons x (step more (conj seen k))))))))]
(step coll #{})))
(defn- add-deck-name
[all-titles card]
(let [card-title (:title card)
indexes (keep-indexed #(if (= %2 card-title) %1 nil) all-titles)
dups (> (count indexes) 1)]
(if dups
(assoc card :display-name (str (:title card) " (" (:set_code card) ")"))
(assoc card :display-name (:title card)))))
(defn alignment-identities [alignment]
(let [cards
(->> @all-cards
(filter #(and (= (:alignment %) alignment)
(= (:Secondary %) "Avatar"))))
all-titles (map :title cards)
add-deck (partial add-deck-name all-titles)]
(map add-deck cards)))
(defn- insert-params
"Add card parameters into the string representation"
[trimCode]
(if (nil? trimCode)
""
(str " " trimCode)))
(defn resources->str [owner]
(let [resources (om/get-state owner [:deck :resources])
str (reduce #(str %1 (:qty %2) " " (get-in %2 [:card :title]) (insert-params (get-in %2 [:card :trimCode])) "\n") "" resources)]
(om/set-state! owner :resource-edit str)))
(defn hazards->str [owner]
(let [hazards (om/get-state owner [:deck :hazards])
str (reduce #(str %1 (:qty %2) " " (get-in %2 [:card :title]) (insert-params (get-in %2 [:card :trimCode])) "\n") "" hazards)]
(om/set-state! owner :hazard-edit str)))
(defn sideboard->str [owner]
(let [sideboard (om/get-state owner [:deck :sideboard])
str (reduce #(str %1 (:qty %2) " " (get-in %2 [:card :title]) (insert-params (get-in %2 [:card :trimCode])) "\n") "" sideboard)]
(om/set-state! owner :sideboard-edit str)))
(defn characters->str [owner]
(let [characters (om/get-state owner [:deck :characters])
str (reduce #(str %1 (:qty %2) " " (get-in %2 [:card :title]) (insert-params (get-in %2 [:card :trimCode])) "\n") "" characters)]
(om/set-state! owner :character-edit str)))
(defn pool->str [owner]
(let [pool (om/get-state owner [:deck :pool])
str (reduce #(str %1 (:qty %2) " " (get-in %2 [:card :title]) (insert-params (get-in %2 [:card :trimCode])) "\n") "" pool)]
(om/set-state! owner :pool-edit str)))
(defn fwsb->str [owner]
(let [fwsb (om/get-state owner [:deck :fwsb])
str (reduce #(str %1 (:qty %2) " " (get-in %2 [:card :title]) (insert-params (get-in %2 [:card :trimCode])) "\n") "" fwsb)]
(om/set-state! owner :fwsb-edit str)))
(defn note->str [owner]
(let [note (om/get-state owner [:deck :note])]
(om/set-state! owner :deck-note note)))
(defn edit-deck [owner]
(let [deck (om/get-state owner :deck)]
(om/set-state! owner :old-deck deck)
(om/set-state! owner :edit true)
(resources->str owner)
(hazards->str owner)
(sideboard->str owner)
(characters->str owner)
(pool->str owner)
(fwsb->str owner)
(note->str owner)
(-> owner (om/get-node "viewport") js/$ (.addClass "edit"))
(try (js/ga "send" "event" "deckbuilder" "edit") (catch js/Error e))
(go (<! (timeout 500))
(-> owner (om/get-node "deckname") js/$ .select))))
(defn end-edit [owner]
(om/set-state! owner :edit false)
(om/set-state! owner :query "")
(-> owner (om/get-node "viewport") js/$ (.removeClass "edit")))
(defn handle-resource-edit [owner]
(let [text (.-value (om/get-node owner "resource-edit"))
cards (parse-deck-string text)]
(om/set-state! owner :resource-edit text)
(om/set-state! owner [:deck :resources] cards)))
(defn handle-hazard-edit [owner]
(let [text (.-value (om/get-node owner "hazard-edit"))
cards (parse-deck-string text)]
(om/set-state! owner :hazard-edit text)
(om/set-state! owner [:deck :hazards] cards)))
(defn handle-character-edit [owner]
(let [text (.-value (om/get-node owner "character-edit"))
cards (parse-deck-string text)]
(om/set-state! owner :character-edit text)
(om/set-state! owner [:deck :characters] cards)))
(defn handle-pool-edit [owner]
(let [text (.-value (om/get-node owner "pool-edit"))
cards (parse-deck-string text)]
(om/set-state! owner :pool-edit text)
(om/set-state! owner [:deck :pool] cards)))
(defn handle-sideboard-edit [owner]
(let [text (.-value (om/get-node owner "sideboard-edit"))
cards (parse-deck-string text)]
(om/set-state! owner :sideboard-edit text)
(om/set-state! owner [:deck :sideboard] cards)))
(defn handle-fwsb-edit [owner]
(let [text (.-value (om/get-node owner "fwsb-edit"))
cards (parse-deck-string text)]
(om/set-state! owner :fwsb-edit text)
(om/set-state! owner [:deck :fwsb] cards)))
(defn handle-deck-note [owner]
(let [text (.-value (om/get-node owner "deck-note"))]
(om/set-state! owner :deck-note text)
(om/set-state! owner [:deck :note] text)))
(defn cancel-edit [owner]
(end-edit owner)
(go (let [deck (om/get-state owner :old-deck)
all-decks (process-decks (:json (<! (GET (str "/data/decks")))))]
(load-decks all-decks)
(put! select-channel deck))))
(defn delete-deck [owner]
(om/set-state! owner :delete true)
(resources->str owner)
(hazards->str owner)
(sideboard->str owner)
(characters->str owner)
(pool->str owner)
(fwsb->str owner)
(note->str owner)
(-> owner (om/get-node "viewport") js/$ (.addClass "delete"))
(try (js/ga "send" "event" "deckbuilder" "delete") (catch js/Error e)))
(defn end-delete [owner]
(om/set-state! owner :delete false)
(-> owner (om/get-node "viewport") js/$ (.removeClass "delete")))
(defn handle-delete [cursor owner]
(authenticated
(fn [user]
(let [deck (om/get-state owner :deck)]
(try (js/ga "send" "event" "deckbuilder" "delete") (catch js/Error e))
(go (let [response (<! (DELETE (str "/data/decks/" (:_id deck))))]))
(do
(om/transact! cursor :decks (fn [ds] (remove #(= deck %) ds)))
(om/set-state! owner :deck (first (sort-by :date > (:decks @cursor))))
(end-delete owner))))))
(defn new-deck [alignment owner]
(let [old-deck (om/get-state owner :deck)
id (->> alignment
alignment-identities
(sort-by :title)
first)]
(om/set-state! owner :deck {:name "New deck" :resources [] :hazards [] :sideboard []
:characters [] :pool [] :fwsb [] :identity id :note []
:donate-dice "empty" :donate-size "none"
})
(try (js/ga "send" "event" "deckbuilder" "new" alignment) (catch js/Error e))
(edit-deck owner)
(om/set-state! owner :old-deck old-deck)))
(defn save-deck [cursor owner]
(authenticated
(fn [user]
(end-edit owner)
(let [deck (assoc (om/get-state owner :deck) :date (.toJSON (js/Date.)))
deck (dissoc deck :stats)
decks (remove #(= (:_id deck) (:_id %)) (:decks @app-state))
resources (for [card (:resources deck) :when (get-in card [:card :title])]
(let [card-map {:qty (:qty card) :card (get-in card [:card :title])}]
(if (contains? card :id) (conj card-map {:id (:id card)}) card-map)))
hazards (for [card (:hazards deck) :when (get-in card [:card :title])]
(let [card-map {:qty (:qty card) :card (get-in card [:card :title])}]
(if (contains? card :id) (conj card-map {:id (:id card)}) card-map)))
sideboard (for [card (:sideboard deck) :when (get-in card [:card :title])]
(let [card-map {:qty (:qty card) :card (get-in card [:card :title])}]
(if (contains? card :id) (conj card-map {:id (:id card)}) card-map)))
characters (for [card (:characters deck) :when (get-in card [:card :title])]
(let [card-map {:qty (:qty card) :card (get-in card [:card :title])}]
(if (contains? card :id) (conj card-map {:id (:id card)}) card-map)))
pool (for [card (:pool deck) :when (get-in card [:card :title])]
(let [card-map {:qty (:qty card) :card (get-in card [:card :title])}]
(if (contains? card :id) (conj card-map {:id (:id card)}) card-map)))
fwsb (for [card (:fwsb deck) :when (get-in card [:card :title])]
(let [card-map {:qty (:qty card) :card (get-in card [:card :title])}]
(if (contains? card :id) (conj card-map {:id (:id card)}) card-map)))
note (:note deck)
;; only include keys that are relevant
identity (select-keys (:identity deck) [:title :alignment :trimCode])
donate-dice (:donate-dice deck)
donate-size (:donate-size deck)
data (assoc deck :resources resources :hazards hazards :sideboard sideboard
:characters characters :pool pool :fwsb fwsb
:identity identity :note note
:donate-dice donate-dice :donate-size donate-size
)]
(try (js/ga "send" "event" "deckbuilder" "save") (catch js/Error e))
(go (let [new-id (get-in (<! (if (:_id deck)
(PUT "/data/decks" data :json)
(POST "/data/decks" data :json)))
[:json :_id])
new-deck (if (:_id deck) deck (assoc deck :_id new-id))
all-decks (process-decks (:json (<! (GET (str "/data/decks")))))]
(om/update! cursor :decks (conj decks new-deck))
(om/set-state! owner :deck new-deck)
(load-decks all-decks)))))))
(defn clear-deck-stats [cursor owner]
(authenticated
(fn [user]
(let [deck (dissoc (om/get-state owner :deck) :stats)
decks (remove #(= (:_id deck) (:_id %)) (:decks @app-state))]
(try (js/ga "send" "event" "deckbuilder" "cleardeckstats") (catch js/Error e))
(go (let [result (<! (DELETE (str "/profile/stats/deck/" (:_id deck))))]
(om/update! cursor :decks (conj decks deck))
(om/set-state! owner :deck deck)
(put! select-channel deck)))))))
(defn html-escape [st]
(escape st {\< "<" \> ">" \& "&" \" "#034;"}))
(defn card-influence-html
"Returns hiccup-ready vector with dots for influence as well as restricted / rotated / banned symbols"
[card qty in-faction allied?]
(let [influence (* (:factioncost card) qty)
banned (decks/banned? card)
restricted (decks/restricted? card)
released (:released card)]
(list " "
(when (and (not banned) (not in-faction))
[:span.influence {:class (utils/faction-label card)}
(if allied?
(alliance-dots influence)
(influence-dots influence))])
(if banned
banned-span
[:span
(when restricted restricted-span)
(when released rotated-span)]))))
(defn deck-influence-html
"Returns hiccup-ready vector with dots colored appropriately to deck's influence."
[deck]
(dots-html influence-dot (decks/influence-map deck)))
(defn build-format-status
"Builds div for alternative format status"
[format violation-details? message]
[:div {:class (if (:legal format) "legal" "invalid") :title (when violation-details? (:reason format))}
[:span.tick (if (:legal format) "✔" "✘")] message " compliant"])
(defn- build-deck-status-label [valid mwl standard rotation cache-refresh onesies modded violation-details?]
(let [status (decks/deck-status mwl valid standard rotation)
message (case status
"legal" "Tournament legal"
"standard" "Standard"
"dreamcard" "Dreamcards"
"casual" "Casual play only"
"invalid" "Invalid"
"")]
[:div.status-tooltip.blue-shade
[:div {:class (if valid "legal" "invalid")}
[:span.tick (if valid "✔" "✘")] "Basic deckbuilding rules"]
[:div {:class (if mwl "legal" "invalid")}
[:span.tick (if mwl "✔" "✘")] (:name @cards/mwl)]
[:div {:class (if rotation "legal" "invalid")}
[:span.tick (if rotation "✔" "✘")] "Only released cards"]
(build-format-status cache-refresh violation-details? "Cache Refresh")
(build-format-status onesies violation-details? "1.1.1.1 format")
(build-format-status modded violation-details? "Modded format")]))
(defn- deck-status-details
[deck use-trusted-info]
; (if use-trusted-info
; (decks/trusted-deck-status deck)
(decks/calculate-deck-status deck))
(defn format-deck-status-span
[deck-status tooltip? violation-details?]
(let [{:keys [valid mwl standard rotation cache-refresh onesies modded status]} deck-status
message (case status
"legal" "Tournament legal"
"standard" "Standard"
"dreamcard" "Dreamcard"
"casual" "Casual play only"
"invalid" "Invalid"
"")]
[:span.deck-status.shift-tooltip {:class status} message
(when tooltip?
(build-deck-status-label valid mwl standard rotation cache-refresh onesies modded violation-details?))]))
(defn deck-status-span-impl [sets deck tooltip? violation-details? use-trusted-info]
(format-deck-status-span (deck-status-details deck use-trusted-info) tooltip? violation-details?))
(def deck-status-span-memoize (memoize deck-status-span-impl))
(defn deck-status-span
"Returns a [:span] with standardized message and colors depending on the deck validity."
([sets deck] (deck-status-span sets deck false false true))
([sets deck tooltip? violation-details? use-trusted-info]
(deck-status-span-memoize sets deck tooltip? violation-details? use-trusted-info)))
(defn match [identity query]
(->> @all-cards
(filter #(decks/allowed? % identity))
(distinct-by :title)
(utils/filter-title query)
(take 10)))
(defn handle-keydown [owner event]
(let [selected (om/get-state owner :selected)
matches (om/get-state owner :matches)]
(case (.-keyCode event)
38 (when (pos? selected)
(om/update-state! owner :selected dec))
40 (when (< selected (dec (count matches)))
(om/update-state! owner :selected inc))
(9 13) (when-not (= (om/get-state owner :query) (:title (first matches)))
(.preventDefault event)
(-> ".deckedit .qty" js/$ .select)
(om/set-state! owner :query (:title (nth matches selected))))
(om/set-state! owner :selected 0))))
(defn handle-add [owner event]
(.preventDefault event)
(let [qty (js/parseInt (om/get-state owner :quantity))
card (nth (om/get-state owner :matches) (om/get-state owner :selected))
best-card (utils/lookup card)]
(if (js/isNaN qty)
(om/set-state! owner :quantity 1)
(let [max-qty 9
limit-qty (if (> qty max-qty) max-qty qty)]
(if (= (:type best-card) "Resource")
(put! (om/get-state owner :resource-edit-channel)
{:qty limit-qty
:card best-card}))
(if (= (:type best-card) "Hazard")
(put! (om/get-state owner :hazard-edit-channel)
{:qty limit-qty
:card best-card}))
(if (= (:type best-card) "Character")
(put! (om/get-state owner :character-edit-channel)
{:qty limit-qty
:card best-card}))
(om/set-state! owner :quantity 1)
(om/set-state! owner :query "")
(-> ".deckedit .lookup" js/$ .select)))))
(defn card-lookup [{:keys [cards]} owner]
(reify
om/IInitState
(init-state [this]
{:query ""
:matches []
:quantity 1
:selected 0})
om/IRenderState
(render-state [this state]
(sab/html
[:p
[:h3 "Add cards"]
[:form.card-search {:on-submit #(handle-add owner %)}
[:input.lookup {:type "text" :placeholder "Card name" :value (:query state)
:on-change #(om/set-state! owner :query (.. % -target -value))
:on-key-down #(handle-keydown owner %)}]
" x "
[:input.qty {:type "text" :value (:quantity state)
:on-change #(om/set-state! owner :quantity (.. % -target -value))}]
[:button "Add to deck"]
(let [query (:query state)
matches (match (get-in state [:deck :identity]) query)
exact-match (= (:title (first matches)) query)]
(cond
exact-match
(do
(om/set-state! owner :matches matches)
(om/set-state! owner :selected 0))
(not (or (empty? query) exact-match))
(do
(om/set-state! owner :matches matches)
[:div.typeahead
(for [i (range (count matches))]
[:div {:class (if (= i (:selected state)) "selected" "")
:on-click (fn [e] (-> ".deckedit .qty" js/$ .select)
(om/set-state! owner :query (.. e -target -textContent))
(om/set-state! owner :selected i))}
(:title (nth matches i))])])))]]))))
(defn deck-collection
[{:keys [sets decks decks-loaded active-deck]} owner]
(reify
om/IRenderState
(render-state [this state]
(sab/html
(cond
(not decks-loaded) [:h4 "Loading deck collection..."]
(empty? decks) [:h4 "No decks"]
:else [:div
(for [deck decks]
[:div.deckline {:class (when (= active-deck deck) "active")
:on-click #(put! select-channel deck)}
[:img {:src (image-url (:identity deck))
:alt (get-in deck [:identity :title] "")}]
[:div.float-right (deck-status-span sets deck)]
[:h4 (:name deck)]
[:div.float-right (-> (:date deck) js/Date. js/moment (.format "MMM Do YYYY"))]
[:p (get-in deck [:identity :title]) [:br]
(when (and (:stats deck) (not= "none" (get-in @app-state [:options :deckstats])))
(let [stats (:stats deck)
games (or (:games stats) 0)
started (or (:games-started stats) 0)
completed (or (:games-completed stats) 0)
wins (or (:wins stats) 0)
losses (or (:loses stats) 0)]
; adding key :games to handle legacy stats before adding started vs completed
[:span " Games: " (+ started games)
" - Completed: " (+ completed games)
" - Won: " wins " (" (num->percent wins (+ wins losses)) "%)"
" - Lost: " losses]))]])])))))
(defn line-span
"Make the view of a single line in the deck - returns a span"
[sets {:keys [identity cards] :as deck} {:keys [qty card] :as line}]
[:span qty " "
(if-let [name (:title card)]
(let [language (get-in @app-state [:options :language])
display (if (:dreamcard card)
name
(case language
"English"
name
"Dutch"
(:title-du card)
"Español"
(:title-es card)
"Finnish"
(:title-fn card)
"French"
(:title-fr card)
"German"
(:title-gr card)
"Italian"
(:title-it card)
"Japanese"
(:title-jp card)
:default
name
))
infaction (noinfcost? identity card)
banned (decks/banned? card)
allied (decks/alliance-is-free? cards line)
valid (and (decks/allowed? card identity)
(decks/legal-num-copies? identity line))
released (decks/released? sets card)
modqty (if (decks/is-prof-prog? deck card) (- qty 1) qty)]
[:span
[:span {:class (cond
(and valid released (not banned)) "fake-link"
valid "casual"
:else "invalid")
:on-mouse-enter #(put! zoom-channel line)
:on-mouse-leave #(put! zoom-channel false)} display]
(card-influence-html card modqty infaction allied)])
card)])
(defn line-qty-span
"Make the view of a single line in the deck - returns a span"
[sets {:keys [identity cards] :as deck} {:keys [qty card] :as line}]
[:span qty " "])
(defn line-name-span
"Make the view of a single line in the deck - returns a span"
[sets {:keys [identity cards] :as deck} {:keys [qty card] :as line}]
[:span (if-let [name (:title card)]
(let [infaction (noinfcost? identity card)
banned (decks/banned? card)
allied (decks/alliance-is-free? cards line)
valid (and (decks/allowed? card identity)
(decks/legal-num-copies? identity line))
released (decks/released? sets card)
modqty (if (decks/is-prof-prog? deck card) (- qty 1) qty)]
[:span
[:span {:class (cond
(and valid released (not banned)) "fake-link"
valid "casual"
:else "invalid")
:on-mouse-enter #(put! zoom-channel line)
:on-mouse-leave #(put! zoom-channel false)} name]
(card-influence-html card modqty infaction allied)])
card)])
(defn- create-identity
[state target-value]
(let [alignment (get-in state [:deck :identity :alignment])
json-map (.parse js/JSON (.. target-value -target -value))
id-map (js->clj json-map :keywordize-keys true)
card (identity-lookup alignment id-map)]
card))
(defn- identity-option-string
[card]
(.stringify js/JSON (clj->js {:title (:title card) :id (:trimCode card)})))
(defn deck-builder
"Make the deckbuilder view"
[{:keys [decks decks-loaded sets] :as cursor} owner]
(reify
om/IInitState
(init-state [this]
{:edit false
:old-deck nil
:resource-edit-channel (chan)
:hazard-edit-channel (chan)
:sideboard-edit-channel (chan)
:character-edit-channel (chan)
:pool-edit-channel (chan)
:fwsb-edit-channel (chan)
:note-edit-channel (chan)
:wizard true
:minion true
:fallen true
:balrog true
:el true
:dl true
:al true
:wl true
:dragon true
:by-date true
:deck-filtered nil
:deck nil
})
om/IWillMount
(will-mount [this]
(let [edit-channel (om/get-state owner :resource-edit-channel)]
(go (while true
(let [card (<! zoom-channel)]
(om/set-state! owner :zoom card))))
(go (while true
(let [edit (<! edit-channel)
card (:card edit)
max-qty (or (:limited card) 9)
cards (om/get-state owner [:deck :resources])
match? #(when (= (get-in % [:card :title]) (:title card)) %)
existing-line (some match? cards)]
(let [new-qty (+ (or (:qty existing-line) 0) (:qty edit))
rest (remove match? cards)
draft-id (decks/is-draft-id? (om/get-state owner [:deck :identity]))
new-cards (cond (and (not draft-id) (> new-qty max-qty))
(conj rest (assoc existing-line :qty max-qty))
(<= new-qty 0) rest
(empty? existing-line) (conj rest {:qty new-qty :card card})
:else (conj rest (assoc existing-line :qty new-qty)))]
(om/set-state! owner [:deck :resources] new-cards))
(resources->str owner)))))
(let [edit-channel (om/get-state owner :hazard-edit-channel)]
(go (while true
(let [card (<! zoom-channel)]
(om/set-state! owner :zoom card))))
(go (while true
(let [edit (<! edit-channel)
card (:card edit)
max-qty (or (:limited card) 9)
cards (om/get-state owner [:deck :hazards])
match? #(when (= (get-in % [:card :title]) (:title card)) %)
existing-line (some match? cards)]
(let [new-qty (+ (or (:qty existing-line) 0) (:qty edit))
rest (remove match? cards)
draft-id (decks/is-draft-id? (om/get-state owner [:deck :identity]))
new-cards (cond (and (not draft-id) (> new-qty max-qty))
(conj rest (assoc existing-line :qty max-qty))
(<= new-qty 0) rest
(empty? existing-line) (conj rest {:qty new-qty :card card})
:else (conj rest (assoc existing-line :qty new-qty)))]
(om/set-state! owner [:deck :hazards] new-cards))
(hazards->str owner)))))
(let [edit-channel (om/get-state owner :sideboard-edit-channel)]
(go (while true
(let [card (<! zoom-channel)]
(om/set-state! owner :zoom card))))
(go (while true
(let [edit (<! edit-channel)
card (:card edit)
max-qty (or (:limited card) 9)
cards (om/get-state owner [:deck :sideboard])
match? #(when (= (get-in % [:card :title]) (:title card)) %)
existing-line (some match? cards)]
(let [new-qty (+ (or (:qty existing-line) 0) (:qty edit))
rest (remove match? cards)
draft-id (decks/is-draft-id? (om/get-state owner [:deck :identity]))
new-cards (cond (and (not draft-id) (> new-qty max-qty))
(conj rest (assoc existing-line :qty max-qty))
(<= new-qty 0) rest
(empty? existing-line) (conj rest {:qty new-qty :card card})
:else (conj rest (assoc existing-line :qty new-qty)))]
(om/set-state! owner [:deck :sideboard] new-cards))
(sideboard->str owner)))))
(let [edit-channel (om/get-state owner :character-edit-channel)]
(go (while true
(let [card (<! zoom-channel)]
(om/set-state! owner :zoom card))))
(go (while true
(let [edit (<! edit-channel)
card (:card edit)
max-qty (or (:limited card) 9)
cards (om/get-state owner [:deck :characters])
match? #(when (= (get-in % [:card :title]) (:title card)) %)
existing-line (some match? cards)]
(let [new-qty (+ (or (:qty existing-line) 0) (:qty edit))
rest (remove match? cards)
draft-id (decks/is-draft-id? (om/get-state owner [:deck :identity]))
new-cards (cond (and (not draft-id) (> new-qty max-qty))
(conj rest (assoc existing-line :qty max-qty))
(<= new-qty 0) rest
(empty? existing-line) (conj rest {:qty new-qty :card card})
:else (conj rest (assoc existing-line :qty new-qty)))]
(om/set-state! owner [:deck :characters] new-cards))
(characters->str owner)))))
(let [edit-channel (om/get-state owner :pool-edit-channel)]
(go (while true
(let [card (<! zoom-channel)]
(om/set-state! owner :zoom card))))
(go (while true
(let [edit (<! edit-channel)
card (:card edit)
max-qty (or (:limited card) 9)
cards (om/get-state owner [:deck :pool])
match? #(when (= (get-in % [:card :title]) (:title card)) %)
existing-line (some match? cards)]
(let [new-qty (+ (or (:qty existing-line) 0) (:qty edit))
rest (remove match? cards)
draft-id (decks/is-draft-id? (om/get-state owner [:deck :identity]))
new-cards (cond (and (not draft-id) (> new-qty max-qty))
(conj rest (assoc existing-line :qty max-qty))
(<= new-qty 0) rest
(empty? existing-line) (conj rest {:qty new-qty :card card})
:else (conj rest (assoc existing-line :qty new-qty)))]
(om/set-state! owner [:deck :pool] new-cards))
(pool->str owner)))))
(let [edit-channel (om/get-state owner :fwsb-edit-channel)]
(go (while true
(let [card (<! zoom-channel)]
(om/set-state! owner :zoom card))))
(go (while true
(let [edit (<! edit-channel)
card (:card edit)
max-qty (or (:limited card) 9)
cards (om/get-state owner [:deck :fwsb])
match? #(when (= (get-in % [:card :title]) (:title card)) %)
existing-line (some match? cards)]
(let [new-qty (+ (or (:qty existing-line) 0) (:qty edit))
rest (remove match? cards)
draft-id (decks/is-draft-id? (om/get-state owner [:deck :identity]))
new-cards (cond (and (not draft-id) (> new-qty max-qty))
(conj rest (assoc existing-line :qty max-qty))
(<= new-qty 0) rest
(empty? existing-line) (conj rest {:qty new-qty :card card})
:else (conj rest (assoc existing-line :qty new-qty)))]
(om/set-state! owner [:deck :fwsb] new-cards))
(fwsb->str owner)))))
(let [edit-channel (om/get-state owner :note-edit-channel)]
(go (while true
(let [edit (<! edit-channel)]
(om/set-state! owner [:deck :note] edit)
(note->str owner)))))
(go (while true
(om/set-state! owner :deck (<! select-channel)))))
om/IRenderState
(render-state [this state]
(sab/html
[:div
[:div.deckbuilder.blue-shade.panel
[:div.viewport {:ref "viewport"}
[:div.decks
[:div.button-bar
[:button {:on-click #(new-deck "Hero" owner)} "New Wizard deck"]
[:button {:on-click #(new-deck "Minion" owner)} "New Minion deck"]
[:button {:on-click #(new-deck "Balrog" owner)} "New Balrog deck"]
[:button {:on-click #(new-deck "Fallen-wizard" owner)} "New Fallen deck"]
[:button {:on-click #(new-deck "Elf-lord" owner)} "New Elf deck"]
[:button {:on-click #(new-deck "Dwarf-lord" owner)} "New Dwarf deck"]
[:button {:on-click #(new-deck "Atani-lord" owner)} "New Atani deck"]
[:button {:on-click #(new-deck "War-lord" owner)} "New Warlord deck"]
[:button {:on-click #(new-deck "Dragon-lord" owner)} "New Dragon deck"]
]
[:div
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :wizard)
:on-change #(do
(om/set-state! owner :wizard (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "Hero "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :minion)
:on-change #(do
(om/set-state! owner :minion (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "Minion "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :fallen)
:on-change #(do
(om/set-state! owner :fallen (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "FW "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :balrog)
:on-change #(do
(om/set-state! owner :balrog (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "BA "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :el)
:on-change #(do
(om/set-state! owner :el (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "EL "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :dl)
:on-change #(do
(om/set-state! owner :dl (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "DL "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :al)
:on-change #(do
(om/set-state! owner :al (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "AL "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :wl)
:on-change #(do
(om/set-state! owner :wl (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "WL "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :dragon)
:on-change #(do
(om/set-state! owner :dragon (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "Dragon "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :by-date)
:on-change #(do
(om/set-state! owner :by-date (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "Date"]]
[:div.deck-collection
(when-not (:edit state)
(if (and (nil? (om/get-state owner :decks-filtered))
(and
(om/get-state owner :wizard)
(om/get-state owner :minion)
(om/get-state owner :fallen)
(om/get-state owner :balrog)
(om/get-state owner :el)
(om/get-state owner :dl)
(om/get-state owner :al)
(om/get-state owner :wl)
(om/get-state owner :dragon)
(om/get-state owner :by-date)))
(om/build deck-collection {:sets sets :decks decks :decks-loaded decks-loaded :active-deck (om/get-state owner :deck)})
(om/build deck-collection {:sets sets :decks (om/get-state owner :decks-filtered) :decks-loaded decks-loaded :active-deck (om/get-state owner :deck)})))
]
[:div {:class (when (:edit state) "edit")}
(when-let [line (om/get-state owner :zoom)]
(if (:standard (decks/calculate-deck-status (om/get-state owner :deck)))
(om/build card-ndce (:card line) {:state {:cursor cursor}})
(om/build card-dce (:card line) {:state {:cursor cursor}})))]]
[:div.decklist
(when-let [deck (:deck state)]
(let [identity (:identity deck)
resources (:resources deck)
hazards (:hazards deck)
sideboard (:sideboard deck)
characters (:characters deck)
pool (:pool deck)
fwsb (:fwsb deck)
note (:note deck)
edit? (:edit state)
delete? (:delete state)]
[:div
(cond
edit? [:div.button-bar
[:button {:on-click #(save-deck cursor owner)} "Save"]
[:button {:on-click #(cancel-edit owner)} "Cancel"]
(if (some #{(get-in @app-state [:user :username])} (get-in @app-state [:donators]))
[:h3.rgtlabel "Donator deck dice: "
[:select {:value (:donate-dice deck)
:on-change #(om/set-state! owner [:deck :donate-dice] (.. % -target -value))}
(for [option [{:name "empty" :ref "empty"}
{:name "Black Flat Red Pips 16mm" :ref "blck-16"}
{:name "Black Swirl Red Pips 18mm" :ref "blacks-18"}
{:name "Silver Swirl Red Pips 16mm" :ref "greys-16"}
{:name "Grey Swirl Red Pips 18mm" :ref "greys-18"}
{:name "Dk. Gold Swirl Black Pips 16mm" :ref "gsdark-16"}
{:name "Lt. Gold Swirl Black Pips 18mm" :ref "gslight-18"}
{:name "Orange Flat Black Pips 16mm" :ref "orgblack-16"}
{:name "Red Swirl Black Pips 16mm" :ref "rsblack-16"}
{:name "Red Swirl Black Pips 18mm" :ref "rsblack-18"}
{:name "Red Swirl White Pips 16mm" :ref "rswhite-16"}
{:name "Saruman Rune 18mm" :ref "rune-s-18"}
{:name "Gandalf Rune 18mm" :ref "rune-g-18"}
{:name "Radagast Rune 18mm" :ref "rune-r-18"}
{:name "Alatar Rune 18mm" :ref "rune-a-18"}
{:name "Pallando Rune 18mm" :ref "rune-p-18"}
{:name "Ringwraith Rune 18mm" :ref "rune-w-18"}]]
[:option {:value (:ref option)} (:name option)])]
[:select {:value (:donate-size deck)
:on-change #(om/set-state! owner [:deck :donate-size] (.. % -target -value))}
(for [option [{:name "none" :ref "none"}
{:name "16mm" :ref "16mm"}
{:name "18mm" :ref "18mm"}]]
[:option {:value (:ref option)} (:name option)])]
])
]
delete? [:div.button-bar
[:button {:on-click #(handle-delete cursor owner)} "Confirm Delete"]
[:button {:on-click #(end-delete owner)} "Cancel"]]
:else [:div.button-bar
[:button {:on-click #(edit-deck owner)} "Edit"]
[:button {:on-click #(delete-deck owner)} "Delete"]
(when (and (:stats deck) (not= "none" (get-in @app-state [:options :deckstats])))
[:button {:on-click #(clear-deck-stats cursor owner)} "Clear Stats"])])
[:h3 (:name deck)]
[:div.header
[:img {:src (image-url identity)
:alt (:title identity)}]
[:h4 {:class (if (decks/released? (:sets @app-state) identity) "fake-link" "casual")
:on-mouse-enter #(put! zoom-channel {:card identity :art (:art identity) :id (:id identity)})
:on-mouse-leave #(put! zoom-channel false)}
(:title identity)
(if (decks/banned? identity)
banned-span
(when (:released identity) rotated-span))]
(let [count (+ (+ (decks/card-count (:resources deck))
(decks/card-count (:hazards deck)))
(decks/card-count (:characters deck)))
min-count (decks/min-deck-size identity)]
[:div count " cards"
(when (< count min-count)
[:span.invalid (str " (minimum " min-count ")")])])
(comment
(let [inf (decks/influence-count deck)
id-limit (decks/id-inf-limit identity)]
[:div "Influence: "
;; we don't use valid? and mwl-legal? functions here, since it concerns influence only
[:span {:class (if (> inf id-limit) (if (> inf id-limit) "invalid" "casual") "legal")} inf]
"/" (if (= INFINITY id-limit) "∞" id-limit)
(if (pos? inf)
(list " " (deck-influence-html deck)))]))
(when (= (:alignment identity) "Crazy")
(let [min-point (decks/min-agenda-points deck)
points (decks/agenda-points deck)]
[:div "Agenda points: " points
(when (< points min-point)
[:span.invalid " (minimum " min-point ")"])
(when (> points (inc min-point))
[:span.invalid " (maximum " (inc min-point) ")"])]))
[:div (deck-status-span sets deck true true false)]]
[:div.cards
(if (not-empty pool) [:h3 "Pool"])
(for [group (sort-by first (group-by #(get-in % [:card :Secondary]) pool))]
[:div.group
[:h4 (str (or (first group) "Unknown") " (" (decks/card-count (last group)) ")") ]
(for [line (sort-by #(get-in % [:card :title]) (last group))]
[:div.line
(when (:edit state)
(let [ch (om/get-state owner :pool-edit-channel)]
[:span
[:button.small {:on-click #(put! ch {:qty 1 :card (:card line)})
:type "button"} "+"]
[:button.small {:on-click #(put! ch {:qty -1 :card (:card line)})
:type "button"} "-"]]))
(line-span sets deck line)])])]
[:div.cards
(if (not-empty characters) [:h3 "Characters"])
(for [group (sort-by first (group-by #(get-in % [:card :Race]) characters))]
[:div.group
[:h4 (str (or (first group) "Unknown") " (" (decks/card-count (last group)) ")") ]
(for [line (sort-by #(get-in % [:card :title]) (last group))]
[:div.line
(when (:edit state)
(let [ch (om/get-state owner :character-edit-channel)]
[:span
[:button.small {:on-click #(put! ch {:qty 1 :card (:card line)})
:type "button"} "+"]
[:button.small {:on-click #(put! ch {:qty -1 :card (:card line)})
:type "button"} "-"]]))
(line-span sets deck line)])])]
[:div.cards
(if (not-empty resources) [:h3 (str "Resources: " (decks/card-count resources) "")])
(for [group (sort-by first (group-by #(get-in % [:card :Secondary]) resources))]
[:div.group
[:h4 (str (or (first group) "Unknown") " (" (decks/card-count (last group)) ")") ]
(for [line (sort-by #(get-in % [:card :title]) (last group))]
[:div.line
(when (:edit state)
(let [ch (om/get-state owner :resource-edit-channel)]
[:span
[:button.small {:on-click #(put! ch {:qty 1 :card (:card line)})
:type "button"} "+"]
[:button.small {:on-click #(put! ch {:qty -1 :card (:card line)})
:type "button"} "-"]]))
(line-span sets deck line)])])]
[:div.cards
(if (not-empty hazards) [:h3 (str "Hazards: " (decks/card-count hazards) "")])
(for [group (sort-by first (group-by #(get-in % [:card :Secondary]) hazards))]
[:div.group
[:h4 (str (or (first group) "Unknown") " (" (decks/card-count (last group)) ")") ]
(for [line (sort-by #(get-in % [:card :title]) (last group))]
[:div.line
(when (:edit state)
(let [ch (om/get-state owner :hazard-edit-channel)]
[:span
[:button.small {:on-click #(put! ch {:qty 1 :card (:card line)})
:type "button"} "+"]
[:button.small {:on-click #(put! ch {:qty -1 :card (:card line)})
:type "button"} "-"]]))
(line-span sets deck line)])])]
[:div.cards
(if (not-empty sideboard) [:h3 (str "Sideboard: " (decks/card-count sideboard) "")])
(for [group (sort-by first (group-by #(get-in % [:card :type]) sideboard))]
[:div.group
[:h4 (str (or (first group) "Unknown") " (" (decks/card-count (last group)) ")") ]
(for [line (sort-by #(get-in % [:card :title]) (last group))]
[:div.line
(when (:edit state)
(let [ch (om/get-state owner :sideboard-edit-channel)]
[:span
[:button.small {:on-click #(put! ch {:qty 1 :card (:card line)})
:type "button"} "+"]
[:button.small {:on-click #(put! ch {:qty -1 :card (:card line)})
:type "button"} "-"]]))
(line-span sets deck line)])])]
[:div.cards
(if (not-empty fwsb) [:h3 "FW-DC-SB"])
(for [group (sort-by first (group-by #(get-in % [:card :type]) fwsb))]
[:div.group
[:h4 (str (or (first group) "Unknown") " (" (decks/card-count (last group)) ")") ]
(for [line (sort-by #(get-in % [:card :title]) (last group))]
[:div.line
(when (:edit state)
(let [ch (om/get-state owner :fwsb-edit-channel)]
[:span
[:button.small {:on-click #(put! ch {:qty 1 :card (:card line)})
:type "button"} "+"]
[:button.small {:on-click #(put! ch {:qty -1 :card (:card line)})
:type "button"} "-"]]))
(line-span sets deck line)])])]
[:div.cards
(if (not-empty note) [:h3 "Deck Notes"])
[:div.note
[:h4 (str note)]]]
]))]
[:div.deckedit
[:div
[:p
[:h3.lftlabel "Deck name"]
[:h3.rgtlabel "Avatar"]
[:input.deckname {:type "text" :placeholder "Deck name"
:ref "deckname" :value (get-in state [:deck :name])
:on-change #(om/set-state! owner [:deck :name] (.. % -target -value))}]]
[:p
[:select.identity {:value (identity-option-string (get-in state [:deck :identity]))
:on-change #(om/set-state! owner [:deck :identity] (create-identity state %))}
(let [idents (alignment-identities (get-in state [:deck :identity :alignment]))]
(for [card (sort-by :display-name idents)]
[:option
{:value (identity-option-string card)}
(:display-name card)]))]]
(om/build card-lookup cursor {:state state})
[:div
[:h3.column1 "Resources"]
[:h3.column2 "Hazards"]
[:h3.column3 "Sideboard"]
]
[:textarea.txttop {:ref "resource-edit" :value (:resource-edit state)
:on-change #(handle-resource-edit owner)}]
[:textarea.txttop {:ref "hazard-edit" :value (:hazard-edit state)
:on-change #(handle-hazard-edit owner)}]
[:textarea.txttop {:ref "sideboard-edit" :value (:sideboard-edit state)
:on-change #(handle-sideboard-edit owner)}]
[:div
[:h3.column1 "Characters"]
[:h3.column2 "Pool"]
[:h3.column3 "FW-DC-SB"]
]
[:textarea.txtbot {:ref "character-edit" :value (:character-edit state)
:on-change #(handle-character-edit owner)}]
[:textarea.txtbot {:ref "pool-edit" :value (:pool-edit state)
:on-change #(handle-pool-edit owner)}]
[:textarea.txtbot {:ref "fwsb-edit" :value (:fwsb-edit state)
:on-change #(handle-fwsb-edit owner)}]
[:div
[:h3 "Deck Notes"]]
[:textarea.txtnte {:ref "deck-note" :value (:deck-note state)
:on-change #(handle-deck-note owner)}]
]]]]]))))
(go (swap! app-state assoc :donators (:json (<! (GET "/data/donors")))))
(go (let [cards (<! cards-channel)
decks (process-decks (:json (<! (GET (str "/data/decks")))))]
(load-decks decks)
(>! cards-channel cards)))
(om/root deck-builder app-state {:target (. js/document (getElementById "deckbuilder"))})
| 42673 | (ns meccg.deckbuilder
(:require-macros [cljs.core.async.macros :refer [go]])
(:require [om.core :as om :include-macros true]
[sablono.core :as sab :include-macros true]
[cljs.core.async :refer [chan put! <! timeout] :as async]
[clojure.string :refer [split split-lines join escape] :as s]
[meccg.appstate :refer [app-state]]
[meccg.auth :refer [authenticated] :as auth]
[meccg.cardbrowser :refer [cards-channel image-url card-view card-ndce card-dce filter-title] :as cb]
[meccg.ajax :refer [POST GET DELETE PUT]]
[meccg.utils :refer [banned-span restricted-span rotated-span influence-dot influence-dots alliance-dots dots-html make-dots]]
[goog.string :as gstring]
[goog.string.format]
[cardnum.utils :refer [str->int lookup-deck parse-deck-string INFINITY] :as utils]
[cardnum.cards :refer [all-cards]]
[cardnum.decks :as decks]
[cardnum.cards :as cards]))
(def select-channel (chan))
(def zoom-channel (chan))
(defn num->percent
"Converts an input number to a percent of the second input number for display"
[num1 num2]
(if (zero? num2)
"0"
(gstring/format "%.0f" (* 100 (float (/ num1 num2))))))
(defn noinfcost? [identity card]
(or (= (:faction card) (:faction identity))
(= 0 (:factioncost card)) (= INFINITY (decks/id-inf-limit identity))))
(defn identity-lookup
"Lookup the identity (query) looking at all cards on specified alignment"
[alignment card]
(let [q (.toLowerCase (:title card))
id (:id card)
cards (filter #(= (:alignment %) alignment) @all-cards)
exact-matches (utils/filter-exact-title q cards)]
(cond (and id
(first (filter #(= id (:trimCode %)) cards)))
(let [id-matches (filter #(= id (:trimCode %)) cards)]
(first (utils/filter-exact-title q id-matches)))
(not-empty exact-matches) (utils/take-best-card exact-matches)
:else
(loop [i 2 matches cards]
(let [subquery (subs q 0 i)]
(cond (zero? (count matches)) card
(or (= (count matches) 1) (utils/identical-cards? matches)) (utils/take-best-card matches)
(<= i (count (:title card))) (recur (inc i) (utils/filter-title subquery matches))
:else card))))))
(defn- build-identity-name
[title set_code art]
(let [set-title (if set_code (str title " (" set_code ")") title)]
(if art
(str set-title " [" art "]")
set-title)))
(defn parse-identity
"Parse an id to the corresponding card map"
[{:keys [alignment title art set_code]}]
(let [card (identity-lookup alignment {:title title})]
(assoc card :art art :display-name (build-identity-name title set_code art))))
(defn add-params-to-card
"Add art and id parameters to a card hash"
[card id]
(-> card
(assoc :id id)))
(defn- clean-param
"Parse card parameter key value pairs from a string"
[param]
(if (and param
(= 2 (count param)))
(let [[k v] (map s/trim param)
allowed-keys '("id" "art")]
(if (some #{k} allowed-keys)
[(keyword k) v]
nil))
nil))
(defn- param-reducer
[acc param]
(if param
(assoc acc (first param) (second param))
acc))
(defn- add-params
"Parse a string of parameters and add them to a map"
[result params-str]
(if params-str
(let [params-groups (split params-str #"\,")
params-all (map #(split % #":") params-groups)
params-clean (map #(clean-param %) params-all)]
(reduce param-reducer result params-clean))
result))
(defn load-decks [decks]
(swap! app-state assoc :decks (sort-by :date > decks))
(when-let [selected-deck (first (sort-by :date > decks))]
(put! select-channel selected-deck))
(swap! app-state assoc :decks-loaded true))
(defn org-decks-name [decks owner]
(let [wizard-decks (when (om/get-state owner :wizard) (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "Hero") decks)))
minion-decks (if (om/get-state owner :minion)
(into wizard-decks (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "Minion") decks)))
wizard-decks)
fallen-decks (if (om/get-state owner :fallen)
(into minion-decks (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "Fallen-wizard") decks)))
minion-decks)
balrog-decks (if (om/get-state owner :balrog)
(into fallen-decks (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "Balrog") decks)))
fallen-decks)
el-decks (if (om/get-state owner :el)
(into balrog-decks (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "Elf-lord") decks)))
balrog-decks)
dl-decks (if (om/get-state owner :dl)
(into el-decks (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "Dwarf-lord") decks)))
el-decks)
al-decks (if (om/get-state owner :al)
(into dl-decks (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "Atani-lord") decks)))
dl-decks)
wl-decks (if (om/get-state owner :wl)
(into al-decks (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "War-lord") decks)))
al-decks)
dragon-decks (if (om/get-state owner :dragon)
(into wl-decks (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "Dragon-lord") decks)))
wl-decks)
sorted-decks (sort-by :name < dragon-decks)]
(om/set-state! owner :decks-filtered sorted-decks)
(when-let [selected-deck (first (sort-by :name < :decks-filtered))]
(put! select-channel selected-deck))
(swap! app-state assoc :decks-loaded true)))
(defn org-decks-date [decks owner]
(let [wizard-decks (when (om/get-state owner :wizard) (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "Hero") decks)))
minion-decks (if (om/get-state owner :minion)
(into wizard-decks (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "Minion") decks)))
wizard-decks)
fallen-decks (if (om/get-state owner :fallen)
(into minion-decks (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "Fallen-wizard") decks)))
minion-decks)
balrog-decks (if (om/get-state owner :balrog)
(into fallen-decks (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "Balrog") decks)))
fallen-decks)
el-decks (if (om/get-state owner :el)
(into balrog-decks (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "Elf-lord") decks)))
balrog-decks)
dl-decks (if (om/get-state owner :dl)
(into el-decks (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "Dwarf-lord") decks)))
el-decks)
al-decks (if (om/get-state owner :al)
(into dl-decks (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "Atani-lord") decks)))
dl-decks)
wl-decks (if (om/get-state owner :wl)
(into al-decks (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "War-lord") decks)))
al-decks)
dragon-decks (if (om/get-state owner :dragon)
(into wl-decks (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "Dragon-lord") decks)))
wl-decks)
sorted-decks (sort-by :date > dragon-decks)]
(om/set-state! owner :decks-filtered sorted-decks)
(when-let [selected-deck (first (sort-by :date > :decks-filtered))]
(put! select-channel selected-deck))
(swap! app-state assoc :decks-loaded true)))
(defn process-decks
"Process the raw deck from the database into a more useful format"
[decks]
(for [deck decks]
(let [identity (parse-identity (:identity deck))
donate-dice (:donate-dice deck)
donate-size (:donate-size deck)
resources (lookup-deck (:resources deck))
hazards (lookup-deck (:hazards deck))
sideboard (lookup-deck (:sideboard deck))
characters (lookup-deck (:characters deck))
pool (lookup-deck (:pool deck))
fwsb (lookup-deck (:fwsb deck))
note (:note deck)]
(assoc deck :resources resources :hazards hazards :sideboard sideboard
:characters characters :pool pool :fwsb fwsb
:identity identity :note note
:donate-dice donate-dice :donate-size donate-size
))))
(defn distinct-by [f coll]
(letfn [(step [xs seen]
(lazy-seq (when-let [[x & more] (seq xs)]
(let [k (f x)]
(if (seen k)
(step more seen)
(cons x (step more (conj seen k))))))))]
(step coll #{})))
(defn- add-deck-name
[all-titles card]
(let [card-title (:title card)
indexes (keep-indexed #(if (= %2 card-title) %1 nil) all-titles)
dups (> (count indexes) 1)]
(if dups
(assoc card :display-name (str (:title card) " (" (:set_code card) ")"))
(assoc card :display-name (:title card)))))
(defn alignment-identities [alignment]
(let [cards
(->> @all-cards
(filter #(and (= (:alignment %) alignment)
(= (:Secondary %) "Avatar"))))
all-titles (map :title cards)
add-deck (partial add-deck-name all-titles)]
(map add-deck cards)))
(defn- insert-params
"Add card parameters into the string representation"
[trimCode]
(if (nil? trimCode)
""
(str " " trimCode)))
(defn resources->str [owner]
(let [resources (om/get-state owner [:deck :resources])
str (reduce #(str %1 (:qty %2) " " (get-in %2 [:card :title]) (insert-params (get-in %2 [:card :trimCode])) "\n") "" resources)]
(om/set-state! owner :resource-edit str)))
(defn hazards->str [owner]
(let [hazards (om/get-state owner [:deck :hazards])
str (reduce #(str %1 (:qty %2) " " (get-in %2 [:card :title]) (insert-params (get-in %2 [:card :trimCode])) "\n") "" hazards)]
(om/set-state! owner :hazard-edit str)))
(defn sideboard->str [owner]
(let [sideboard (om/get-state owner [:deck :sideboard])
str (reduce #(str %1 (:qty %2) " " (get-in %2 [:card :title]) (insert-params (get-in %2 [:card :trimCode])) "\n") "" sideboard)]
(om/set-state! owner :sideboard-edit str)))
(defn characters->str [owner]
(let [characters (om/get-state owner [:deck :characters])
str (reduce #(str %1 (:qty %2) " " (get-in %2 [:card :title]) (insert-params (get-in %2 [:card :trimCode])) "\n") "" characters)]
(om/set-state! owner :character-edit str)))
(defn pool->str [owner]
(let [pool (om/get-state owner [:deck :pool])
str (reduce #(str %1 (:qty %2) " " (get-in %2 [:card :title]) (insert-params (get-in %2 [:card :trimCode])) "\n") "" pool)]
(om/set-state! owner :pool-edit str)))
(defn fwsb->str [owner]
(let [fwsb (om/get-state owner [:deck :fwsb])
str (reduce #(str %1 (:qty %2) " " (get-in %2 [:card :title]) (insert-params (get-in %2 [:card :trimCode])) "\n") "" fwsb)]
(om/set-state! owner :fwsb-edit str)))
(defn note->str [owner]
(let [note (om/get-state owner [:deck :note])]
(om/set-state! owner :deck-note note)))
(defn edit-deck [owner]
(let [deck (om/get-state owner :deck)]
(om/set-state! owner :old-deck deck)
(om/set-state! owner :edit true)
(resources->str owner)
(hazards->str owner)
(sideboard->str owner)
(characters->str owner)
(pool->str owner)
(fwsb->str owner)
(note->str owner)
(-> owner (om/get-node "viewport") js/$ (.addClass "edit"))
(try (js/ga "send" "event" "deckbuilder" "edit") (catch js/Error e))
(go (<! (timeout 500))
(-> owner (om/get-node "deckname") js/$ .select))))
(defn end-edit [owner]
(om/set-state! owner :edit false)
(om/set-state! owner :query "")
(-> owner (om/get-node "viewport") js/$ (.removeClass "edit")))
(defn handle-resource-edit [owner]
(let [text (.-value (om/get-node owner "resource-edit"))
cards (parse-deck-string text)]
(om/set-state! owner :resource-edit text)
(om/set-state! owner [:deck :resources] cards)))
(defn handle-hazard-edit [owner]
(let [text (.-value (om/get-node owner "hazard-edit"))
cards (parse-deck-string text)]
(om/set-state! owner :hazard-edit text)
(om/set-state! owner [:deck :hazards] cards)))
(defn handle-character-edit [owner]
(let [text (.-value (om/get-node owner "character-edit"))
cards (parse-deck-string text)]
(om/set-state! owner :character-edit text)
(om/set-state! owner [:deck :characters] cards)))
(defn handle-pool-edit [owner]
(let [text (.-value (om/get-node owner "pool-edit"))
cards (parse-deck-string text)]
(om/set-state! owner :pool-edit text)
(om/set-state! owner [:deck :pool] cards)))
(defn handle-sideboard-edit [owner]
(let [text (.-value (om/get-node owner "sideboard-edit"))
cards (parse-deck-string text)]
(om/set-state! owner :sideboard-edit text)
(om/set-state! owner [:deck :sideboard] cards)))
(defn handle-fwsb-edit [owner]
(let [text (.-value (om/get-node owner "fwsb-edit"))
cards (parse-deck-string text)]
(om/set-state! owner :fwsb-edit text)
(om/set-state! owner [:deck :fwsb] cards)))
(defn handle-deck-note [owner]
(let [text (.-value (om/get-node owner "deck-note"))]
(om/set-state! owner :deck-note text)
(om/set-state! owner [:deck :note] text)))
(defn cancel-edit [owner]
(end-edit owner)
(go (let [deck (om/get-state owner :old-deck)
all-decks (process-decks (:json (<! (GET (str "/data/decks")))))]
(load-decks all-decks)
(put! select-channel deck))))
(defn delete-deck [owner]
(om/set-state! owner :delete true)
(resources->str owner)
(hazards->str owner)
(sideboard->str owner)
(characters->str owner)
(pool->str owner)
(fwsb->str owner)
(note->str owner)
(-> owner (om/get-node "viewport") js/$ (.addClass "delete"))
(try (js/ga "send" "event" "deckbuilder" "delete") (catch js/Error e)))
(defn end-delete [owner]
(om/set-state! owner :delete false)
(-> owner (om/get-node "viewport") js/$ (.removeClass "delete")))
(defn handle-delete [cursor owner]
(authenticated
(fn [user]
(let [deck (om/get-state owner :deck)]
(try (js/ga "send" "event" "deckbuilder" "delete") (catch js/Error e))
(go (let [response (<! (DELETE (str "/data/decks/" (:_id deck))))]))
(do
(om/transact! cursor :decks (fn [ds] (remove #(= deck %) ds)))
(om/set-state! owner :deck (first (sort-by :date > (:decks @cursor))))
(end-delete owner))))))
(defn new-deck [alignment owner]
(let [old-deck (om/get-state owner :deck)
id (->> alignment
alignment-identities
(sort-by :title)
first)]
(om/set-state! owner :deck {:name "New deck" :resources [] :hazards [] :sideboard []
:characters [] :pool [] :fwsb [] :identity id :note []
:donate-dice "empty" :donate-size "none"
})
(try (js/ga "send" "event" "deckbuilder" "new" alignment) (catch js/Error e))
(edit-deck owner)
(om/set-state! owner :old-deck old-deck)))
(defn save-deck [cursor owner]
(authenticated
(fn [user]
(end-edit owner)
(let [deck (assoc (om/get-state owner :deck) :date (.toJSON (js/Date.)))
deck (dissoc deck :stats)
decks (remove #(= (:_id deck) (:_id %)) (:decks @app-state))
resources (for [card (:resources deck) :when (get-in card [:card :title])]
(let [card-map {:qty (:qty card) :card (get-in card [:card :title])}]
(if (contains? card :id) (conj card-map {:id (:id card)}) card-map)))
hazards (for [card (:hazards deck) :when (get-in card [:card :title])]
(let [card-map {:qty (:qty card) :card (get-in card [:card :title])}]
(if (contains? card :id) (conj card-map {:id (:id card)}) card-map)))
sideboard (for [card (:sideboard deck) :when (get-in card [:card :title])]
(let [card-map {:qty (:qty card) :card (get-in card [:card :title])}]
(if (contains? card :id) (conj card-map {:id (:id card)}) card-map)))
characters (for [card (:characters deck) :when (get-in card [:card :title])]
(let [card-map {:qty (:qty card) :card (get-in card [:card :title])}]
(if (contains? card :id) (conj card-map {:id (:id card)}) card-map)))
pool (for [card (:pool deck) :when (get-in card [:card :title])]
(let [card-map {:qty (:qty card) :card (get-in card [:card :title])}]
(if (contains? card :id) (conj card-map {:id (:id card)}) card-map)))
fwsb (for [card (:fwsb deck) :when (get-in card [:card :title])]
(let [card-map {:qty (:qty card) :card (get-in card [:card :title])}]
(if (contains? card :id) (conj card-map {:id (:id card)}) card-map)))
note (:note deck)
;; only include keys that are relevant
identity (select-keys (:identity deck) [:title :alignment :trimCode])
donate-dice (:donate-dice deck)
donate-size (:donate-size deck)
data (assoc deck :resources resources :hazards hazards :sideboard sideboard
:characters characters :pool pool :fwsb fwsb
:identity identity :note note
:donate-dice donate-dice :donate-size donate-size
)]
(try (js/ga "send" "event" "deckbuilder" "save") (catch js/Error e))
(go (let [new-id (get-in (<! (if (:_id deck)
(PUT "/data/decks" data :json)
(POST "/data/decks" data :json)))
[:json :_id])
new-deck (if (:_id deck) deck (assoc deck :_id new-id))
all-decks (process-decks (:json (<! (GET (str "/data/decks")))))]
(om/update! cursor :decks (conj decks new-deck))
(om/set-state! owner :deck new-deck)
(load-decks all-decks)))))))
(defn clear-deck-stats [cursor owner]
(authenticated
(fn [user]
(let [deck (dissoc (om/get-state owner :deck) :stats)
decks (remove #(= (:_id deck) (:_id %)) (:decks @app-state))]
(try (js/ga "send" "event" "deckbuilder" "cleardeckstats") (catch js/Error e))
(go (let [result (<! (DELETE (str "/profile/stats/deck/" (:_id deck))))]
(om/update! cursor :decks (conj decks deck))
(om/set-state! owner :deck deck)
(put! select-channel deck)))))))
(defn html-escape [st]
(escape st {\< "<" \> ">" \& "&" \" "#034;"}))
(defn card-influence-html
"Returns hiccup-ready vector with dots for influence as well as restricted / rotated / banned symbols"
[card qty in-faction allied?]
(let [influence (* (:factioncost card) qty)
banned (decks/banned? card)
restricted (decks/restricted? card)
released (:released card)]
(list " "
(when (and (not banned) (not in-faction))
[:span.influence {:class (utils/faction-label card)}
(if allied?
(alliance-dots influence)
(influence-dots influence))])
(if banned
banned-span
[:span
(when restricted restricted-span)
(when released rotated-span)]))))
(defn deck-influence-html
"Returns hiccup-ready vector with dots colored appropriately to deck's influence."
[deck]
(dots-html influence-dot (decks/influence-map deck)))
(defn build-format-status
"Builds div for alternative format status"
[format violation-details? message]
[:div {:class (if (:legal format) "legal" "invalid") :title (when violation-details? (:reason format))}
[:span.tick (if (:legal format) "✔" "✘")] message " compliant"])
(defn- build-deck-status-label [valid mwl standard rotation cache-refresh onesies modded violation-details?]
(let [status (decks/deck-status mwl valid standard rotation)
message (case status
"legal" "Tournament legal"
"standard" "Standard"
"dreamcard" "Dreamcards"
"casual" "Casual play only"
"invalid" "Invalid"
"")]
[:div.status-tooltip.blue-shade
[:div {:class (if valid "legal" "invalid")}
[:span.tick (if valid "✔" "✘")] "Basic deckbuilding rules"]
[:div {:class (if mwl "legal" "invalid")}
[:span.tick (if mwl "✔" "✘")] (:name @cards/mwl)]
[:div {:class (if rotation "legal" "invalid")}
[:span.tick (if rotation "✔" "✘")] "Only released cards"]
(build-format-status cache-refresh violation-details? "Cache Refresh")
(build-format-status onesies violation-details? "1.1.1.1 format")
(build-format-status modded violation-details? "Modded format")]))
(defn- deck-status-details
[deck use-trusted-info]
; (if use-trusted-info
; (decks/trusted-deck-status deck)
(decks/calculate-deck-status deck))
(defn format-deck-status-span
[deck-status tooltip? violation-details?]
(let [{:keys [valid mwl standard rotation cache-refresh onesies modded status]} deck-status
message (case status
"legal" "Tournament legal"
"standard" "Standard"
"dreamcard" "Dreamcard"
"casual" "Casual play only"
"invalid" "Invalid"
"")]
[:span.deck-status.shift-tooltip {:class status} message
(when tooltip?
(build-deck-status-label valid mwl standard rotation cache-refresh onesies modded violation-details?))]))
(defn deck-status-span-impl [sets deck tooltip? violation-details? use-trusted-info]
(format-deck-status-span (deck-status-details deck use-trusted-info) tooltip? violation-details?))
(def deck-status-span-memoize (memoize deck-status-span-impl))
(defn deck-status-span
"Returns a [:span] with standardized message and colors depending on the deck validity."
([sets deck] (deck-status-span sets deck false false true))
([sets deck tooltip? violation-details? use-trusted-info]
(deck-status-span-memoize sets deck tooltip? violation-details? use-trusted-info)))
(defn match [identity query]
(->> @all-cards
(filter #(decks/allowed? % identity))
(distinct-by :title)
(utils/filter-title query)
(take 10)))
(defn handle-keydown [owner event]
(let [selected (om/get-state owner :selected)
matches (om/get-state owner :matches)]
(case (.-keyCode event)
38 (when (pos? selected)
(om/update-state! owner :selected dec))
40 (when (< selected (dec (count matches)))
(om/update-state! owner :selected inc))
(9 13) (when-not (= (om/get-state owner :query) (:title (first matches)))
(.preventDefault event)
(-> ".deckedit .qty" js/$ .select)
(om/set-state! owner :query (:title (nth matches selected))))
(om/set-state! owner :selected 0))))
(defn handle-add [owner event]
(.preventDefault event)
(let [qty (js/parseInt (om/get-state owner :quantity))
card (nth (om/get-state owner :matches) (om/get-state owner :selected))
best-card (utils/lookup card)]
(if (js/isNaN qty)
(om/set-state! owner :quantity 1)
(let [max-qty 9
limit-qty (if (> qty max-qty) max-qty qty)]
(if (= (:type best-card) "Resource")
(put! (om/get-state owner :resource-edit-channel)
{:qty limit-qty
:card best-card}))
(if (= (:type best-card) "Hazard")
(put! (om/get-state owner :hazard-edit-channel)
{:qty limit-qty
:card best-card}))
(if (= (:type best-card) "Character")
(put! (om/get-state owner :character-edit-channel)
{:qty limit-qty
:card best-card}))
(om/set-state! owner :quantity 1)
(om/set-state! owner :query "")
(-> ".deckedit .lookup" js/$ .select)))))
(defn card-lookup [{:keys [cards]} owner]
(reify
om/IInitState
(init-state [this]
{:query ""
:matches []
:quantity 1
:selected 0})
om/IRenderState
(render-state [this state]
(sab/html
[:p
[:h3 "Add cards"]
[:form.card-search {:on-submit #(handle-add owner %)}
[:input.lookup {:type "text" :placeholder "Card name" :value (:query state)
:on-change #(om/set-state! owner :query (.. % -target -value))
:on-key-down #(handle-keydown owner %)}]
" x "
[:input.qty {:type "text" :value (:quantity state)
:on-change #(om/set-state! owner :quantity (.. % -target -value))}]
[:button "Add to deck"]
(let [query (:query state)
matches (match (get-in state [:deck :identity]) query)
exact-match (= (:title (first matches)) query)]
(cond
exact-match
(do
(om/set-state! owner :matches matches)
(om/set-state! owner :selected 0))
(not (or (empty? query) exact-match))
(do
(om/set-state! owner :matches matches)
[:div.typeahead
(for [i (range (count matches))]
[:div {:class (if (= i (:selected state)) "selected" "")
:on-click (fn [e] (-> ".deckedit .qty" js/$ .select)
(om/set-state! owner :query (.. e -target -textContent))
(om/set-state! owner :selected i))}
(:title (nth matches i))])])))]]))))
(defn deck-collection
[{:keys [sets decks decks-loaded active-deck]} owner]
(reify
om/IRenderState
(render-state [this state]
(sab/html
(cond
(not decks-loaded) [:h4 "Loading deck collection..."]
(empty? decks) [:h4 "No decks"]
:else [:div
(for [deck decks]
[:div.deckline {:class (when (= active-deck deck) "active")
:on-click #(put! select-channel deck)}
[:img {:src (image-url (:identity deck))
:alt (get-in deck [:identity :title] "")}]
[:div.float-right (deck-status-span sets deck)]
[:h4 (:name deck)]
[:div.float-right (-> (:date deck) js/Date. js/moment (.format "MMM Do YYYY"))]
[:p (get-in deck [:identity :title]) [:br]
(when (and (:stats deck) (not= "none" (get-in @app-state [:options :deckstats])))
(let [stats (:stats deck)
games (or (:games stats) 0)
started (or (:games-started stats) 0)
completed (or (:games-completed stats) 0)
wins (or (:wins stats) 0)
losses (or (:loses stats) 0)]
; adding key :games to handle legacy stats before adding started vs completed
[:span " Games: " (+ started games)
" - Completed: " (+ completed games)
" - Won: " wins " (" (num->percent wins (+ wins losses)) "%)"
" - Lost: " losses]))]])])))))
(defn line-span
"Make the view of a single line in the deck - returns a span"
[sets {:keys [identity cards] :as deck} {:keys [qty card] :as line}]
[:span qty " "
(if-let [name (:title card)]
(let [language (get-in @app-state [:options :language])
display (if (:dreamcard card)
name
(case language
"English"
name
"Dutch"
(:title-du card)
"Español"
(:title-es card)
"Finnish"
(:title-fn card)
"French"
(:title-fr card)
"German"
(:title-gr card)
"Italian"
(:title-it card)
"Japanese"
(:title-jp card)
:default
name
))
infaction (noinfcost? identity card)
banned (decks/banned? card)
allied (decks/alliance-is-free? cards line)
valid (and (decks/allowed? card identity)
(decks/legal-num-copies? identity line))
released (decks/released? sets card)
modqty (if (decks/is-prof-prog? deck card) (- qty 1) qty)]
[:span
[:span {:class (cond
(and valid released (not banned)) "fake-link"
valid "casual"
:else "invalid")
:on-mouse-enter #(put! zoom-channel line)
:on-mouse-leave #(put! zoom-channel false)} display]
(card-influence-html card modqty infaction allied)])
card)])
(defn line-qty-span
"Make the view of a single line in the deck - returns a span"
[sets {:keys [identity cards] :as deck} {:keys [qty card] :as line}]
[:span qty " "])
(defn line-name-span
"Make the view of a single line in the deck - returns a span"
[sets {:keys [identity cards] :as deck} {:keys [qty card] :as line}]
[:span (if-let [name (:title card)]
(let [infaction (noinfcost? identity card)
banned (decks/banned? card)
allied (decks/alliance-is-free? cards line)
valid (and (decks/allowed? card identity)
(decks/legal-num-copies? identity line))
released (decks/released? sets card)
modqty (if (decks/is-prof-prog? deck card) (- qty 1) qty)]
[:span
[:span {:class (cond
(and valid released (not banned)) "fake-link"
valid "casual"
:else "invalid")
:on-mouse-enter #(put! zoom-channel line)
:on-mouse-leave #(put! zoom-channel false)} name]
(card-influence-html card modqty infaction allied)])
card)])
(defn- create-identity
[state target-value]
(let [alignment (get-in state [:deck :identity :alignment])
json-map (.parse js/JSON (.. target-value -target -value))
id-map (js->clj json-map :keywordize-keys true)
card (identity-lookup alignment id-map)]
card))
(defn- identity-option-string
[card]
(.stringify js/JSON (clj->js {:title (:title card) :id (:trimCode card)})))
(defn deck-builder
"Make the deckbuilder view"
[{:keys [decks decks-loaded sets] :as cursor} owner]
(reify
om/IInitState
(init-state [this]
{:edit false
:old-deck nil
:resource-edit-channel (chan)
:hazard-edit-channel (chan)
:sideboard-edit-channel (chan)
:character-edit-channel (chan)
:pool-edit-channel (chan)
:fwsb-edit-channel (chan)
:note-edit-channel (chan)
:wizard true
:minion true
:fallen true
:balrog true
:el true
:dl true
:al true
:wl true
:dragon true
:by-date true
:deck-filtered nil
:deck nil
})
om/IWillMount
(will-mount [this]
(let [edit-channel (om/get-state owner :resource-edit-channel)]
(go (while true
(let [card (<! zoom-channel)]
(om/set-state! owner :zoom card))))
(go (while true
(let [edit (<! edit-channel)
card (:card edit)
max-qty (or (:limited card) 9)
cards (om/get-state owner [:deck :resources])
match? #(when (= (get-in % [:card :title]) (:title card)) %)
existing-line (some match? cards)]
(let [new-qty (+ (or (:qty existing-line) 0) (:qty edit))
rest (remove match? cards)
draft-id (decks/is-draft-id? (om/get-state owner [:deck :identity]))
new-cards (cond (and (not draft-id) (> new-qty max-qty))
(conj rest (assoc existing-line :qty max-qty))
(<= new-qty 0) rest
(empty? existing-line) (conj rest {:qty new-qty :card card})
:else (conj rest (assoc existing-line :qty new-qty)))]
(om/set-state! owner [:deck :resources] new-cards))
(resources->str owner)))))
(let [edit-channel (om/get-state owner :hazard-edit-channel)]
(go (while true
(let [card (<! zoom-channel)]
(om/set-state! owner :zoom card))))
(go (while true
(let [edit (<! edit-channel)
card (:card edit)
max-qty (or (:limited card) 9)
cards (om/get-state owner [:deck :hazards])
match? #(when (= (get-in % [:card :title]) (:title card)) %)
existing-line (some match? cards)]
(let [new-qty (+ (or (:qty existing-line) 0) (:qty edit))
rest (remove match? cards)
draft-id (decks/is-draft-id? (om/get-state owner [:deck :identity]))
new-cards (cond (and (not draft-id) (> new-qty max-qty))
(conj rest (assoc existing-line :qty max-qty))
(<= new-qty 0) rest
(empty? existing-line) (conj rest {:qty new-qty :card card})
:else (conj rest (assoc existing-line :qty new-qty)))]
(om/set-state! owner [:deck :hazards] new-cards))
(hazards->str owner)))))
(let [edit-channel (om/get-state owner :sideboard-edit-channel)]
(go (while true
(let [card (<! zoom-channel)]
(om/set-state! owner :zoom card))))
(go (while true
(let [edit (<! edit-channel)
card (:card edit)
max-qty (or (:limited card) 9)
cards (om/get-state owner [:deck :sideboard])
match? #(when (= (get-in % [:card :title]) (:title card)) %)
existing-line (some match? cards)]
(let [new-qty (+ (or (:qty existing-line) 0) (:qty edit))
rest (remove match? cards)
draft-id (decks/is-draft-id? (om/get-state owner [:deck :identity]))
new-cards (cond (and (not draft-id) (> new-qty max-qty))
(conj rest (assoc existing-line :qty max-qty))
(<= new-qty 0) rest
(empty? existing-line) (conj rest {:qty new-qty :card card})
:else (conj rest (assoc existing-line :qty new-qty)))]
(om/set-state! owner [:deck :sideboard] new-cards))
(sideboard->str owner)))))
(let [edit-channel (om/get-state owner :character-edit-channel)]
(go (while true
(let [card (<! zoom-channel)]
(om/set-state! owner :zoom card))))
(go (while true
(let [edit (<! edit-channel)
card (:card edit)
max-qty (or (:limited card) 9)
cards (om/get-state owner [:deck :characters])
match? #(when (= (get-in % [:card :title]) (:title card)) %)
existing-line (some match? cards)]
(let [new-qty (+ (or (:qty existing-line) 0) (:qty edit))
rest (remove match? cards)
draft-id (decks/is-draft-id? (om/get-state owner [:deck :identity]))
new-cards (cond (and (not draft-id) (> new-qty max-qty))
(conj rest (assoc existing-line :qty max-qty))
(<= new-qty 0) rest
(empty? existing-line) (conj rest {:qty new-qty :card card})
:else (conj rest (assoc existing-line :qty new-qty)))]
(om/set-state! owner [:deck :characters] new-cards))
(characters->str owner)))))
(let [edit-channel (om/get-state owner :pool-edit-channel)]
(go (while true
(let [card (<! zoom-channel)]
(om/set-state! owner :zoom card))))
(go (while true
(let [edit (<! edit-channel)
card (:card edit)
max-qty (or (:limited card) 9)
cards (om/get-state owner [:deck :pool])
match? #(when (= (get-in % [:card :title]) (:title card)) %)
existing-line (some match? cards)]
(let [new-qty (+ (or (:qty existing-line) 0) (:qty edit))
rest (remove match? cards)
draft-id (decks/is-draft-id? (om/get-state owner [:deck :identity]))
new-cards (cond (and (not draft-id) (> new-qty max-qty))
(conj rest (assoc existing-line :qty max-qty))
(<= new-qty 0) rest
(empty? existing-line) (conj rest {:qty new-qty :card card})
:else (conj rest (assoc existing-line :qty new-qty)))]
(om/set-state! owner [:deck :pool] new-cards))
(pool->str owner)))))
(let [edit-channel (om/get-state owner :fwsb-edit-channel)]
(go (while true
(let [card (<! zoom-channel)]
(om/set-state! owner :zoom card))))
(go (while true
(let [edit (<! edit-channel)
card (:card edit)
max-qty (or (:limited card) 9)
cards (om/get-state owner [:deck :fwsb])
match? #(when (= (get-in % [:card :title]) (:title card)) %)
existing-line (some match? cards)]
(let [new-qty (+ (or (:qty existing-line) 0) (:qty edit))
rest (remove match? cards)
draft-id (decks/is-draft-id? (om/get-state owner [:deck :identity]))
new-cards (cond (and (not draft-id) (> new-qty max-qty))
(conj rest (assoc existing-line :qty max-qty))
(<= new-qty 0) rest
(empty? existing-line) (conj rest {:qty new-qty :card card})
:else (conj rest (assoc existing-line :qty new-qty)))]
(om/set-state! owner [:deck :fwsb] new-cards))
(fwsb->str owner)))))
(let [edit-channel (om/get-state owner :note-edit-channel)]
(go (while true
(let [edit (<! edit-channel)]
(om/set-state! owner [:deck :note] edit)
(note->str owner)))))
(go (while true
(om/set-state! owner :deck (<! select-channel)))))
om/IRenderState
(render-state [this state]
(sab/html
[:div
[:div.deckbuilder.blue-shade.panel
[:div.viewport {:ref "viewport"}
[:div.decks
[:div.button-bar
[:button {:on-click #(new-deck "Hero" owner)} "New Wizard deck"]
[:button {:on-click #(new-deck "Minion" owner)} "New Minion deck"]
[:button {:on-click #(new-deck "Balrog" owner)} "New Balrog deck"]
[:button {:on-click #(new-deck "Fallen-wizard" owner)} "New Fallen deck"]
[:button {:on-click #(new-deck "Elf-lord" owner)} "New Elf deck"]
[:button {:on-click #(new-deck "Dwarf-lord" owner)} "New Dwarf deck"]
[:button {:on-click #(new-deck "Atani-lord" owner)} "New Atani deck"]
[:button {:on-click #(new-deck "War-lord" owner)} "New Warlord deck"]
[:button {:on-click #(new-deck "Dragon-lord" owner)} "New Dragon deck"]
]
[:div
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :wizard)
:on-change #(do
(om/set-state! owner :wizard (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "Hero "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :minion)
:on-change #(do
(om/set-state! owner :minion (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "Minion "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :fallen)
:on-change #(do
(om/set-state! owner :fallen (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "FW "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :balrog)
:on-change #(do
(om/set-state! owner :balrog (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "BA "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :el)
:on-change #(do
(om/set-state! owner :el (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "EL "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :dl)
:on-change #(do
(om/set-state! owner :dl (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "DL "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :al)
:on-change #(do
(om/set-state! owner :al (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "AL "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :wl)
:on-change #(do
(om/set-state! owner :wl (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "WL "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :dragon)
:on-change #(do
(om/set-state! owner :dragon (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "Dragon "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :by-date)
:on-change #(do
(om/set-state! owner :by-date (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "Date"]]
[:div.deck-collection
(when-not (:edit state)
(if (and (nil? (om/get-state owner :decks-filtered))
(and
(om/get-state owner :wizard)
(om/get-state owner :minion)
(om/get-state owner :fallen)
(om/get-state owner :balrog)
(om/get-state owner :el)
(om/get-state owner :dl)
(om/get-state owner :al)
(om/get-state owner :wl)
(om/get-state owner :dragon)
(om/get-state owner :by-date)))
(om/build deck-collection {:sets sets :decks decks :decks-loaded decks-loaded :active-deck (om/get-state owner :deck)})
(om/build deck-collection {:sets sets :decks (om/get-state owner :decks-filtered) :decks-loaded decks-loaded :active-deck (om/get-state owner :deck)})))
]
[:div {:class (when (:edit state) "edit")}
(when-let [line (om/get-state owner :zoom)]
(if (:standard (decks/calculate-deck-status (om/get-state owner :deck)))
(om/build card-ndce (:card line) {:state {:cursor cursor}})
(om/build card-dce (:card line) {:state {:cursor cursor}})))]]
[:div.decklist
(when-let [deck (:deck state)]
(let [identity (:identity deck)
resources (:resources deck)
hazards (:hazards deck)
sideboard (:sideboard deck)
characters (:characters deck)
pool (:pool deck)
fwsb (:fwsb deck)
note (:note deck)
edit? (:edit state)
delete? (:delete state)]
[:div
(cond
edit? [:div.button-bar
[:button {:on-click #(save-deck cursor owner)} "Save"]
[:button {:on-click #(cancel-edit owner)} "Cancel"]
(if (some #{(get-in @app-state [:user :username])} (get-in @app-state [:donators]))
[:h3.rgtlabel "Donator deck dice: "
[:select {:value (:donate-dice deck)
:on-change #(om/set-state! owner [:deck :donate-dice] (.. % -target -value))}
(for [option [{:name "empty" :ref "empty"}
{:name "Black Flat Red Pips 16mm" :ref "blck-16"}
{:name "Black Swirl Red Pips 18mm" :ref "blacks-18"}
{:name "Silver Swirl Red Pips 16mm" :ref "greys-16"}
{:name "Grey Swirl Red Pips 18mm" :ref "greys-18"}
{:name "Dk. Gold Swirl Black Pips 16mm" :ref "gsdark-16"}
{:name "Lt. Gold Swirl Black Pips 18mm" :ref "gslight-18"}
{:name "Orange Flat Black Pips 16mm" :ref "orgblack-16"}
{:name "Red Swirl Black Pips 16mm" :ref "rsblack-16"}
{:name "Red Swirl Black Pips 18mm" :ref "rsblack-18"}
{:name "Red Swirl White Pips 16mm" :ref "rswhite-16"}
{:name "Saruman Rune 18mm" :ref "rune-s-18"}
{:name "Gandalf Rune 18mm" :ref "rune-g-18"}
{:name "Radagast Rune 18mm" :ref "rune-r-18"}
{:name "Alatar Rune 18mm" :ref "rune-a-18"}
{:name "Pallando Rune 18mm" :ref "rune-p-18"}
{:name "Ringw<NAME>ith Rune 18mm" :ref "rune-w-18"}]]
[:option {:value (:ref option)} (:name option)])]
[:select {:value (:donate-size deck)
:on-change #(om/set-state! owner [:deck :donate-size] (.. % -target -value))}
(for [option [{:name "none" :ref "none"}
{:name "16mm" :ref "16mm"}
{:name "18mm" :ref "18mm"}]]
[:option {:value (:ref option)} (:name option)])]
])
]
delete? [:div.button-bar
[:button {:on-click #(handle-delete cursor owner)} "Confirm Delete"]
[:button {:on-click #(end-delete owner)} "Cancel"]]
:else [:div.button-bar
[:button {:on-click #(edit-deck owner)} "Edit"]
[:button {:on-click #(delete-deck owner)} "Delete"]
(when (and (:stats deck) (not= "none" (get-in @app-state [:options :deckstats])))
[:button {:on-click #(clear-deck-stats cursor owner)} "Clear Stats"])])
[:h3 (:name deck)]
[:div.header
[:img {:src (image-url identity)
:alt (:title identity)}]
[:h4 {:class (if (decks/released? (:sets @app-state) identity) "fake-link" "casual")
:on-mouse-enter #(put! zoom-channel {:card identity :art (:art identity) :id (:id identity)})
:on-mouse-leave #(put! zoom-channel false)}
(:title identity)
(if (decks/banned? identity)
banned-span
(when (:released identity) rotated-span))]
(let [count (+ (+ (decks/card-count (:resources deck))
(decks/card-count (:hazards deck)))
(decks/card-count (:characters deck)))
min-count (decks/min-deck-size identity)]
[:div count " cards"
(when (< count min-count)
[:span.invalid (str " (minimum " min-count ")")])])
(comment
(let [inf (decks/influence-count deck)
id-limit (decks/id-inf-limit identity)]
[:div "Influence: "
;; we don't use valid? and mwl-legal? functions here, since it concerns influence only
[:span {:class (if (> inf id-limit) (if (> inf id-limit) "invalid" "casual") "legal")} inf]
"/" (if (= INFINITY id-limit) "∞" id-limit)
(if (pos? inf)
(list " " (deck-influence-html deck)))]))
(when (= (:alignment identity) "Crazy")
(let [min-point (decks/min-agenda-points deck)
points (decks/agenda-points deck)]
[:div "Agenda points: " points
(when (< points min-point)
[:span.invalid " (minimum " min-point ")"])
(when (> points (inc min-point))
[:span.invalid " (maximum " (inc min-point) ")"])]))
[:div (deck-status-span sets deck true true false)]]
[:div.cards
(if (not-empty pool) [:h3 "Pool"])
(for [group (sort-by first (group-by #(get-in % [:card :Secondary]) pool))]
[:div.group
[:h4 (str (or (first group) "Unknown") " (" (decks/card-count (last group)) ")") ]
(for [line (sort-by #(get-in % [:card :title]) (last group))]
[:div.line
(when (:edit state)
(let [ch (om/get-state owner :pool-edit-channel)]
[:span
[:button.small {:on-click #(put! ch {:qty 1 :card (:card line)})
:type "button"} "+"]
[:button.small {:on-click #(put! ch {:qty -1 :card (:card line)})
:type "button"} "-"]]))
(line-span sets deck line)])])]
[:div.cards
(if (not-empty characters) [:h3 "Characters"])
(for [group (sort-by first (group-by #(get-in % [:card :Race]) characters))]
[:div.group
[:h4 (str (or (first group) "Unknown") " (" (decks/card-count (last group)) ")") ]
(for [line (sort-by #(get-in % [:card :title]) (last group))]
[:div.line
(when (:edit state)
(let [ch (om/get-state owner :character-edit-channel)]
[:span
[:button.small {:on-click #(put! ch {:qty 1 :card (:card line)})
:type "button"} "+"]
[:button.small {:on-click #(put! ch {:qty -1 :card (:card line)})
:type "button"} "-"]]))
(line-span sets deck line)])])]
[:div.cards
(if (not-empty resources) [:h3 (str "Resources: " (decks/card-count resources) "")])
(for [group (sort-by first (group-by #(get-in % [:card :Secondary]) resources))]
[:div.group
[:h4 (str (or (first group) "Unknown") " (" (decks/card-count (last group)) ")") ]
(for [line (sort-by #(get-in % [:card :title]) (last group))]
[:div.line
(when (:edit state)
(let [ch (om/get-state owner :resource-edit-channel)]
[:span
[:button.small {:on-click #(put! ch {:qty 1 :card (:card line)})
:type "button"} "+"]
[:button.small {:on-click #(put! ch {:qty -1 :card (:card line)})
:type "button"} "-"]]))
(line-span sets deck line)])])]
[:div.cards
(if (not-empty hazards) [:h3 (str "Hazards: " (decks/card-count hazards) "")])
(for [group (sort-by first (group-by #(get-in % [:card :Secondary]) hazards))]
[:div.group
[:h4 (str (or (first group) "Unknown") " (" (decks/card-count (last group)) ")") ]
(for [line (sort-by #(get-in % [:card :title]) (last group))]
[:div.line
(when (:edit state)
(let [ch (om/get-state owner :hazard-edit-channel)]
[:span
[:button.small {:on-click #(put! ch {:qty 1 :card (:card line)})
:type "button"} "+"]
[:button.small {:on-click #(put! ch {:qty -1 :card (:card line)})
:type "button"} "-"]]))
(line-span sets deck line)])])]
[:div.cards
(if (not-empty sideboard) [:h3 (str "Sideboard: " (decks/card-count sideboard) "")])
(for [group (sort-by first (group-by #(get-in % [:card :type]) sideboard))]
[:div.group
[:h4 (str (or (first group) "Unknown") " (" (decks/card-count (last group)) ")") ]
(for [line (sort-by #(get-in % [:card :title]) (last group))]
[:div.line
(when (:edit state)
(let [ch (om/get-state owner :sideboard-edit-channel)]
[:span
[:button.small {:on-click #(put! ch {:qty 1 :card (:card line)})
:type "button"} "+"]
[:button.small {:on-click #(put! ch {:qty -1 :card (:card line)})
:type "button"} "-"]]))
(line-span sets deck line)])])]
[:div.cards
(if (not-empty fwsb) [:h3 "FW-DC-SB"])
(for [group (sort-by first (group-by #(get-in % [:card :type]) fwsb))]
[:div.group
[:h4 (str (or (first group) "Unknown") " (" (decks/card-count (last group)) ")") ]
(for [line (sort-by #(get-in % [:card :title]) (last group))]
[:div.line
(when (:edit state)
(let [ch (om/get-state owner :fwsb-edit-channel)]
[:span
[:button.small {:on-click #(put! ch {:qty 1 :card (:card line)})
:type "button"} "+"]
[:button.small {:on-click #(put! ch {:qty -1 :card (:card line)})
:type "button"} "-"]]))
(line-span sets deck line)])])]
[:div.cards
(if (not-empty note) [:h3 "Deck Notes"])
[:div.note
[:h4 (str note)]]]
]))]
[:div.deckedit
[:div
[:p
[:h3.lftlabel "Deck name"]
[:h3.rgtlabel "Avatar"]
[:input.deckname {:type "text" :placeholder "Deck name"
:ref "deckname" :value (get-in state [:deck :name])
:on-change #(om/set-state! owner [:deck :name] (.. % -target -value))}]]
[:p
[:select.identity {:value (identity-option-string (get-in state [:deck :identity]))
:on-change #(om/set-state! owner [:deck :identity] (create-identity state %))}
(let [idents (alignment-identities (get-in state [:deck :identity :alignment]))]
(for [card (sort-by :display-name idents)]
[:option
{:value (identity-option-string card)}
(:display-name card)]))]]
(om/build card-lookup cursor {:state state})
[:div
[:h3.column1 "Resources"]
[:h3.column2 "Hazards"]
[:h3.column3 "Sideboard"]
]
[:textarea.txttop {:ref "resource-edit" :value (:resource-edit state)
:on-change #(handle-resource-edit owner)}]
[:textarea.txttop {:ref "hazard-edit" :value (:hazard-edit state)
:on-change #(handle-hazard-edit owner)}]
[:textarea.txttop {:ref "sideboard-edit" :value (:sideboard-edit state)
:on-change #(handle-sideboard-edit owner)}]
[:div
[:h3.column1 "Characters"]
[:h3.column2 "Pool"]
[:h3.column3 "FW-DC-SB"]
]
[:textarea.txtbot {:ref "character-edit" :value (:character-edit state)
:on-change #(handle-character-edit owner)}]
[:textarea.txtbot {:ref "pool-edit" :value (:pool-edit state)
:on-change #(handle-pool-edit owner)}]
[:textarea.txtbot {:ref "fwsb-edit" :value (:fwsb-edit state)
:on-change #(handle-fwsb-edit owner)}]
[:div
[:h3 "Deck Notes"]]
[:textarea.txtnte {:ref "deck-note" :value (:deck-note state)
:on-change #(handle-deck-note owner)}]
]]]]]))))
(go (swap! app-state assoc :donators (:json (<! (GET "/data/donors")))))
(go (let [cards (<! cards-channel)
decks (process-decks (:json (<! (GET (str "/data/decks")))))]
(load-decks decks)
(>! cards-channel cards)))
(om/root deck-builder app-state {:target (. js/document (getElementById "deckbuilder"))})
| true | (ns meccg.deckbuilder
(:require-macros [cljs.core.async.macros :refer [go]])
(:require [om.core :as om :include-macros true]
[sablono.core :as sab :include-macros true]
[cljs.core.async :refer [chan put! <! timeout] :as async]
[clojure.string :refer [split split-lines join escape] :as s]
[meccg.appstate :refer [app-state]]
[meccg.auth :refer [authenticated] :as auth]
[meccg.cardbrowser :refer [cards-channel image-url card-view card-ndce card-dce filter-title] :as cb]
[meccg.ajax :refer [POST GET DELETE PUT]]
[meccg.utils :refer [banned-span restricted-span rotated-span influence-dot influence-dots alliance-dots dots-html make-dots]]
[goog.string :as gstring]
[goog.string.format]
[cardnum.utils :refer [str->int lookup-deck parse-deck-string INFINITY] :as utils]
[cardnum.cards :refer [all-cards]]
[cardnum.decks :as decks]
[cardnum.cards :as cards]))
(def select-channel (chan))
(def zoom-channel (chan))
(defn num->percent
"Converts an input number to a percent of the second input number for display"
[num1 num2]
(if (zero? num2)
"0"
(gstring/format "%.0f" (* 100 (float (/ num1 num2))))))
(defn noinfcost? [identity card]
(or (= (:faction card) (:faction identity))
(= 0 (:factioncost card)) (= INFINITY (decks/id-inf-limit identity))))
(defn identity-lookup
"Lookup the identity (query) looking at all cards on specified alignment"
[alignment card]
(let [q (.toLowerCase (:title card))
id (:id card)
cards (filter #(= (:alignment %) alignment) @all-cards)
exact-matches (utils/filter-exact-title q cards)]
(cond (and id
(first (filter #(= id (:trimCode %)) cards)))
(let [id-matches (filter #(= id (:trimCode %)) cards)]
(first (utils/filter-exact-title q id-matches)))
(not-empty exact-matches) (utils/take-best-card exact-matches)
:else
(loop [i 2 matches cards]
(let [subquery (subs q 0 i)]
(cond (zero? (count matches)) card
(or (= (count matches) 1) (utils/identical-cards? matches)) (utils/take-best-card matches)
(<= i (count (:title card))) (recur (inc i) (utils/filter-title subquery matches))
:else card))))))
(defn- build-identity-name
[title set_code art]
(let [set-title (if set_code (str title " (" set_code ")") title)]
(if art
(str set-title " [" art "]")
set-title)))
(defn parse-identity
"Parse an id to the corresponding card map"
[{:keys [alignment title art set_code]}]
(let [card (identity-lookup alignment {:title title})]
(assoc card :art art :display-name (build-identity-name title set_code art))))
(defn add-params-to-card
"Add art and id parameters to a card hash"
[card id]
(-> card
(assoc :id id)))
(defn- clean-param
"Parse card parameter key value pairs from a string"
[param]
(if (and param
(= 2 (count param)))
(let [[k v] (map s/trim param)
allowed-keys '("id" "art")]
(if (some #{k} allowed-keys)
[(keyword k) v]
nil))
nil))
(defn- param-reducer
[acc param]
(if param
(assoc acc (first param) (second param))
acc))
(defn- add-params
"Parse a string of parameters and add them to a map"
[result params-str]
(if params-str
(let [params-groups (split params-str #"\,")
params-all (map #(split % #":") params-groups)
params-clean (map #(clean-param %) params-all)]
(reduce param-reducer result params-clean))
result))
(defn load-decks [decks]
(swap! app-state assoc :decks (sort-by :date > decks))
(when-let [selected-deck (first (sort-by :date > decks))]
(put! select-channel selected-deck))
(swap! app-state assoc :decks-loaded true))
(defn org-decks-name [decks owner]
(let [wizard-decks (when (om/get-state owner :wizard) (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "Hero") decks)))
minion-decks (if (om/get-state owner :minion)
(into wizard-decks (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "Minion") decks)))
wizard-decks)
fallen-decks (if (om/get-state owner :fallen)
(into minion-decks (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "Fallen-wizard") decks)))
minion-decks)
balrog-decks (if (om/get-state owner :balrog)
(into fallen-decks (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "Balrog") decks)))
fallen-decks)
el-decks (if (om/get-state owner :el)
(into balrog-decks (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "Elf-lord") decks)))
balrog-decks)
dl-decks (if (om/get-state owner :dl)
(into el-decks (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "Dwarf-lord") decks)))
el-decks)
al-decks (if (om/get-state owner :al)
(into dl-decks (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "Atani-lord") decks)))
dl-decks)
wl-decks (if (om/get-state owner :wl)
(into al-decks (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "War-lord") decks)))
al-decks)
dragon-decks (if (om/get-state owner :dragon)
(into wl-decks (sort-by :name < (filter #(= (get-in % [:identity :alignment]) "Dragon-lord") decks)))
wl-decks)
sorted-decks (sort-by :name < dragon-decks)]
(om/set-state! owner :decks-filtered sorted-decks)
(when-let [selected-deck (first (sort-by :name < :decks-filtered))]
(put! select-channel selected-deck))
(swap! app-state assoc :decks-loaded true)))
(defn org-decks-date [decks owner]
(let [wizard-decks (when (om/get-state owner :wizard) (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "Hero") decks)))
minion-decks (if (om/get-state owner :minion)
(into wizard-decks (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "Minion") decks)))
wizard-decks)
fallen-decks (if (om/get-state owner :fallen)
(into minion-decks (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "Fallen-wizard") decks)))
minion-decks)
balrog-decks (if (om/get-state owner :balrog)
(into fallen-decks (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "Balrog") decks)))
fallen-decks)
el-decks (if (om/get-state owner :el)
(into balrog-decks (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "Elf-lord") decks)))
balrog-decks)
dl-decks (if (om/get-state owner :dl)
(into el-decks (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "Dwarf-lord") decks)))
el-decks)
al-decks (if (om/get-state owner :al)
(into dl-decks (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "Atani-lord") decks)))
dl-decks)
wl-decks (if (om/get-state owner :wl)
(into al-decks (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "War-lord") decks)))
al-decks)
dragon-decks (if (om/get-state owner :dragon)
(into wl-decks (sort-by :date > (filter #(= (get-in % [:identity :alignment]) "Dragon-lord") decks)))
wl-decks)
sorted-decks (sort-by :date > dragon-decks)]
(om/set-state! owner :decks-filtered sorted-decks)
(when-let [selected-deck (first (sort-by :date > :decks-filtered))]
(put! select-channel selected-deck))
(swap! app-state assoc :decks-loaded true)))
(defn process-decks
"Process the raw deck from the database into a more useful format"
[decks]
(for [deck decks]
(let [identity (parse-identity (:identity deck))
donate-dice (:donate-dice deck)
donate-size (:donate-size deck)
resources (lookup-deck (:resources deck))
hazards (lookup-deck (:hazards deck))
sideboard (lookup-deck (:sideboard deck))
characters (lookup-deck (:characters deck))
pool (lookup-deck (:pool deck))
fwsb (lookup-deck (:fwsb deck))
note (:note deck)]
(assoc deck :resources resources :hazards hazards :sideboard sideboard
:characters characters :pool pool :fwsb fwsb
:identity identity :note note
:donate-dice donate-dice :donate-size donate-size
))))
(defn distinct-by [f coll]
(letfn [(step [xs seen]
(lazy-seq (when-let [[x & more] (seq xs)]
(let [k (f x)]
(if (seen k)
(step more seen)
(cons x (step more (conj seen k))))))))]
(step coll #{})))
(defn- add-deck-name
[all-titles card]
(let [card-title (:title card)
indexes (keep-indexed #(if (= %2 card-title) %1 nil) all-titles)
dups (> (count indexes) 1)]
(if dups
(assoc card :display-name (str (:title card) " (" (:set_code card) ")"))
(assoc card :display-name (:title card)))))
(defn alignment-identities [alignment]
(let [cards
(->> @all-cards
(filter #(and (= (:alignment %) alignment)
(= (:Secondary %) "Avatar"))))
all-titles (map :title cards)
add-deck (partial add-deck-name all-titles)]
(map add-deck cards)))
(defn- insert-params
"Add card parameters into the string representation"
[trimCode]
(if (nil? trimCode)
""
(str " " trimCode)))
(defn resources->str [owner]
(let [resources (om/get-state owner [:deck :resources])
str (reduce #(str %1 (:qty %2) " " (get-in %2 [:card :title]) (insert-params (get-in %2 [:card :trimCode])) "\n") "" resources)]
(om/set-state! owner :resource-edit str)))
(defn hazards->str [owner]
(let [hazards (om/get-state owner [:deck :hazards])
str (reduce #(str %1 (:qty %2) " " (get-in %2 [:card :title]) (insert-params (get-in %2 [:card :trimCode])) "\n") "" hazards)]
(om/set-state! owner :hazard-edit str)))
(defn sideboard->str [owner]
(let [sideboard (om/get-state owner [:deck :sideboard])
str (reduce #(str %1 (:qty %2) " " (get-in %2 [:card :title]) (insert-params (get-in %2 [:card :trimCode])) "\n") "" sideboard)]
(om/set-state! owner :sideboard-edit str)))
(defn characters->str [owner]
(let [characters (om/get-state owner [:deck :characters])
str (reduce #(str %1 (:qty %2) " " (get-in %2 [:card :title]) (insert-params (get-in %2 [:card :trimCode])) "\n") "" characters)]
(om/set-state! owner :character-edit str)))
(defn pool->str [owner]
(let [pool (om/get-state owner [:deck :pool])
str (reduce #(str %1 (:qty %2) " " (get-in %2 [:card :title]) (insert-params (get-in %2 [:card :trimCode])) "\n") "" pool)]
(om/set-state! owner :pool-edit str)))
(defn fwsb->str [owner]
(let [fwsb (om/get-state owner [:deck :fwsb])
str (reduce #(str %1 (:qty %2) " " (get-in %2 [:card :title]) (insert-params (get-in %2 [:card :trimCode])) "\n") "" fwsb)]
(om/set-state! owner :fwsb-edit str)))
(defn note->str [owner]
(let [note (om/get-state owner [:deck :note])]
(om/set-state! owner :deck-note note)))
(defn edit-deck [owner]
(let [deck (om/get-state owner :deck)]
(om/set-state! owner :old-deck deck)
(om/set-state! owner :edit true)
(resources->str owner)
(hazards->str owner)
(sideboard->str owner)
(characters->str owner)
(pool->str owner)
(fwsb->str owner)
(note->str owner)
(-> owner (om/get-node "viewport") js/$ (.addClass "edit"))
(try (js/ga "send" "event" "deckbuilder" "edit") (catch js/Error e))
(go (<! (timeout 500))
(-> owner (om/get-node "deckname") js/$ .select))))
(defn end-edit [owner]
(om/set-state! owner :edit false)
(om/set-state! owner :query "")
(-> owner (om/get-node "viewport") js/$ (.removeClass "edit")))
(defn handle-resource-edit [owner]
(let [text (.-value (om/get-node owner "resource-edit"))
cards (parse-deck-string text)]
(om/set-state! owner :resource-edit text)
(om/set-state! owner [:deck :resources] cards)))
(defn handle-hazard-edit [owner]
(let [text (.-value (om/get-node owner "hazard-edit"))
cards (parse-deck-string text)]
(om/set-state! owner :hazard-edit text)
(om/set-state! owner [:deck :hazards] cards)))
(defn handle-character-edit [owner]
(let [text (.-value (om/get-node owner "character-edit"))
cards (parse-deck-string text)]
(om/set-state! owner :character-edit text)
(om/set-state! owner [:deck :characters] cards)))
(defn handle-pool-edit [owner]
(let [text (.-value (om/get-node owner "pool-edit"))
cards (parse-deck-string text)]
(om/set-state! owner :pool-edit text)
(om/set-state! owner [:deck :pool] cards)))
(defn handle-sideboard-edit [owner]
(let [text (.-value (om/get-node owner "sideboard-edit"))
cards (parse-deck-string text)]
(om/set-state! owner :sideboard-edit text)
(om/set-state! owner [:deck :sideboard] cards)))
(defn handle-fwsb-edit [owner]
(let [text (.-value (om/get-node owner "fwsb-edit"))
cards (parse-deck-string text)]
(om/set-state! owner :fwsb-edit text)
(om/set-state! owner [:deck :fwsb] cards)))
(defn handle-deck-note [owner]
(let [text (.-value (om/get-node owner "deck-note"))]
(om/set-state! owner :deck-note text)
(om/set-state! owner [:deck :note] text)))
(defn cancel-edit [owner]
(end-edit owner)
(go (let [deck (om/get-state owner :old-deck)
all-decks (process-decks (:json (<! (GET (str "/data/decks")))))]
(load-decks all-decks)
(put! select-channel deck))))
(defn delete-deck [owner]
(om/set-state! owner :delete true)
(resources->str owner)
(hazards->str owner)
(sideboard->str owner)
(characters->str owner)
(pool->str owner)
(fwsb->str owner)
(note->str owner)
(-> owner (om/get-node "viewport") js/$ (.addClass "delete"))
(try (js/ga "send" "event" "deckbuilder" "delete") (catch js/Error e)))
(defn end-delete [owner]
(om/set-state! owner :delete false)
(-> owner (om/get-node "viewport") js/$ (.removeClass "delete")))
(defn handle-delete [cursor owner]
(authenticated
(fn [user]
(let [deck (om/get-state owner :deck)]
(try (js/ga "send" "event" "deckbuilder" "delete") (catch js/Error e))
(go (let [response (<! (DELETE (str "/data/decks/" (:_id deck))))]))
(do
(om/transact! cursor :decks (fn [ds] (remove #(= deck %) ds)))
(om/set-state! owner :deck (first (sort-by :date > (:decks @cursor))))
(end-delete owner))))))
(defn new-deck [alignment owner]
(let [old-deck (om/get-state owner :deck)
id (->> alignment
alignment-identities
(sort-by :title)
first)]
(om/set-state! owner :deck {:name "New deck" :resources [] :hazards [] :sideboard []
:characters [] :pool [] :fwsb [] :identity id :note []
:donate-dice "empty" :donate-size "none"
})
(try (js/ga "send" "event" "deckbuilder" "new" alignment) (catch js/Error e))
(edit-deck owner)
(om/set-state! owner :old-deck old-deck)))
(defn save-deck [cursor owner]
(authenticated
(fn [user]
(end-edit owner)
(let [deck (assoc (om/get-state owner :deck) :date (.toJSON (js/Date.)))
deck (dissoc deck :stats)
decks (remove #(= (:_id deck) (:_id %)) (:decks @app-state))
resources (for [card (:resources deck) :when (get-in card [:card :title])]
(let [card-map {:qty (:qty card) :card (get-in card [:card :title])}]
(if (contains? card :id) (conj card-map {:id (:id card)}) card-map)))
hazards (for [card (:hazards deck) :when (get-in card [:card :title])]
(let [card-map {:qty (:qty card) :card (get-in card [:card :title])}]
(if (contains? card :id) (conj card-map {:id (:id card)}) card-map)))
sideboard (for [card (:sideboard deck) :when (get-in card [:card :title])]
(let [card-map {:qty (:qty card) :card (get-in card [:card :title])}]
(if (contains? card :id) (conj card-map {:id (:id card)}) card-map)))
characters (for [card (:characters deck) :when (get-in card [:card :title])]
(let [card-map {:qty (:qty card) :card (get-in card [:card :title])}]
(if (contains? card :id) (conj card-map {:id (:id card)}) card-map)))
pool (for [card (:pool deck) :when (get-in card [:card :title])]
(let [card-map {:qty (:qty card) :card (get-in card [:card :title])}]
(if (contains? card :id) (conj card-map {:id (:id card)}) card-map)))
fwsb (for [card (:fwsb deck) :when (get-in card [:card :title])]
(let [card-map {:qty (:qty card) :card (get-in card [:card :title])}]
(if (contains? card :id) (conj card-map {:id (:id card)}) card-map)))
note (:note deck)
;; only include keys that are relevant
identity (select-keys (:identity deck) [:title :alignment :trimCode])
donate-dice (:donate-dice deck)
donate-size (:donate-size deck)
data (assoc deck :resources resources :hazards hazards :sideboard sideboard
:characters characters :pool pool :fwsb fwsb
:identity identity :note note
:donate-dice donate-dice :donate-size donate-size
)]
(try (js/ga "send" "event" "deckbuilder" "save") (catch js/Error e))
(go (let [new-id (get-in (<! (if (:_id deck)
(PUT "/data/decks" data :json)
(POST "/data/decks" data :json)))
[:json :_id])
new-deck (if (:_id deck) deck (assoc deck :_id new-id))
all-decks (process-decks (:json (<! (GET (str "/data/decks")))))]
(om/update! cursor :decks (conj decks new-deck))
(om/set-state! owner :deck new-deck)
(load-decks all-decks)))))))
(defn clear-deck-stats [cursor owner]
(authenticated
(fn [user]
(let [deck (dissoc (om/get-state owner :deck) :stats)
decks (remove #(= (:_id deck) (:_id %)) (:decks @app-state))]
(try (js/ga "send" "event" "deckbuilder" "cleardeckstats") (catch js/Error e))
(go (let [result (<! (DELETE (str "/profile/stats/deck/" (:_id deck))))]
(om/update! cursor :decks (conj decks deck))
(om/set-state! owner :deck deck)
(put! select-channel deck)))))))
(defn html-escape [st]
(escape st {\< "<" \> ">" \& "&" \" "#034;"}))
(defn card-influence-html
"Returns hiccup-ready vector with dots for influence as well as restricted / rotated / banned symbols"
[card qty in-faction allied?]
(let [influence (* (:factioncost card) qty)
banned (decks/banned? card)
restricted (decks/restricted? card)
released (:released card)]
(list " "
(when (and (not banned) (not in-faction))
[:span.influence {:class (utils/faction-label card)}
(if allied?
(alliance-dots influence)
(influence-dots influence))])
(if banned
banned-span
[:span
(when restricted restricted-span)
(when released rotated-span)]))))
(defn deck-influence-html
"Returns hiccup-ready vector with dots colored appropriately to deck's influence."
[deck]
(dots-html influence-dot (decks/influence-map deck)))
(defn build-format-status
"Builds div for alternative format status"
[format violation-details? message]
[:div {:class (if (:legal format) "legal" "invalid") :title (when violation-details? (:reason format))}
[:span.tick (if (:legal format) "✔" "✘")] message " compliant"])
(defn- build-deck-status-label [valid mwl standard rotation cache-refresh onesies modded violation-details?]
(let [status (decks/deck-status mwl valid standard rotation)
message (case status
"legal" "Tournament legal"
"standard" "Standard"
"dreamcard" "Dreamcards"
"casual" "Casual play only"
"invalid" "Invalid"
"")]
[:div.status-tooltip.blue-shade
[:div {:class (if valid "legal" "invalid")}
[:span.tick (if valid "✔" "✘")] "Basic deckbuilding rules"]
[:div {:class (if mwl "legal" "invalid")}
[:span.tick (if mwl "✔" "✘")] (:name @cards/mwl)]
[:div {:class (if rotation "legal" "invalid")}
[:span.tick (if rotation "✔" "✘")] "Only released cards"]
(build-format-status cache-refresh violation-details? "Cache Refresh")
(build-format-status onesies violation-details? "1.1.1.1 format")
(build-format-status modded violation-details? "Modded format")]))
(defn- deck-status-details
[deck use-trusted-info]
; (if use-trusted-info
; (decks/trusted-deck-status deck)
(decks/calculate-deck-status deck))
(defn format-deck-status-span
[deck-status tooltip? violation-details?]
(let [{:keys [valid mwl standard rotation cache-refresh onesies modded status]} deck-status
message (case status
"legal" "Tournament legal"
"standard" "Standard"
"dreamcard" "Dreamcard"
"casual" "Casual play only"
"invalid" "Invalid"
"")]
[:span.deck-status.shift-tooltip {:class status} message
(when tooltip?
(build-deck-status-label valid mwl standard rotation cache-refresh onesies modded violation-details?))]))
(defn deck-status-span-impl [sets deck tooltip? violation-details? use-trusted-info]
(format-deck-status-span (deck-status-details deck use-trusted-info) tooltip? violation-details?))
(def deck-status-span-memoize (memoize deck-status-span-impl))
(defn deck-status-span
"Returns a [:span] with standardized message and colors depending on the deck validity."
([sets deck] (deck-status-span sets deck false false true))
([sets deck tooltip? violation-details? use-trusted-info]
(deck-status-span-memoize sets deck tooltip? violation-details? use-trusted-info)))
(defn match [identity query]
(->> @all-cards
(filter #(decks/allowed? % identity))
(distinct-by :title)
(utils/filter-title query)
(take 10)))
(defn handle-keydown [owner event]
(let [selected (om/get-state owner :selected)
matches (om/get-state owner :matches)]
(case (.-keyCode event)
38 (when (pos? selected)
(om/update-state! owner :selected dec))
40 (when (< selected (dec (count matches)))
(om/update-state! owner :selected inc))
(9 13) (when-not (= (om/get-state owner :query) (:title (first matches)))
(.preventDefault event)
(-> ".deckedit .qty" js/$ .select)
(om/set-state! owner :query (:title (nth matches selected))))
(om/set-state! owner :selected 0))))
(defn handle-add [owner event]
(.preventDefault event)
(let [qty (js/parseInt (om/get-state owner :quantity))
card (nth (om/get-state owner :matches) (om/get-state owner :selected))
best-card (utils/lookup card)]
(if (js/isNaN qty)
(om/set-state! owner :quantity 1)
(let [max-qty 9
limit-qty (if (> qty max-qty) max-qty qty)]
(if (= (:type best-card) "Resource")
(put! (om/get-state owner :resource-edit-channel)
{:qty limit-qty
:card best-card}))
(if (= (:type best-card) "Hazard")
(put! (om/get-state owner :hazard-edit-channel)
{:qty limit-qty
:card best-card}))
(if (= (:type best-card) "Character")
(put! (om/get-state owner :character-edit-channel)
{:qty limit-qty
:card best-card}))
(om/set-state! owner :quantity 1)
(om/set-state! owner :query "")
(-> ".deckedit .lookup" js/$ .select)))))
(defn card-lookup [{:keys [cards]} owner]
(reify
om/IInitState
(init-state [this]
{:query ""
:matches []
:quantity 1
:selected 0})
om/IRenderState
(render-state [this state]
(sab/html
[:p
[:h3 "Add cards"]
[:form.card-search {:on-submit #(handle-add owner %)}
[:input.lookup {:type "text" :placeholder "Card name" :value (:query state)
:on-change #(om/set-state! owner :query (.. % -target -value))
:on-key-down #(handle-keydown owner %)}]
" x "
[:input.qty {:type "text" :value (:quantity state)
:on-change #(om/set-state! owner :quantity (.. % -target -value))}]
[:button "Add to deck"]
(let [query (:query state)
matches (match (get-in state [:deck :identity]) query)
exact-match (= (:title (first matches)) query)]
(cond
exact-match
(do
(om/set-state! owner :matches matches)
(om/set-state! owner :selected 0))
(not (or (empty? query) exact-match))
(do
(om/set-state! owner :matches matches)
[:div.typeahead
(for [i (range (count matches))]
[:div {:class (if (= i (:selected state)) "selected" "")
:on-click (fn [e] (-> ".deckedit .qty" js/$ .select)
(om/set-state! owner :query (.. e -target -textContent))
(om/set-state! owner :selected i))}
(:title (nth matches i))])])))]]))))
(defn deck-collection
[{:keys [sets decks decks-loaded active-deck]} owner]
(reify
om/IRenderState
(render-state [this state]
(sab/html
(cond
(not decks-loaded) [:h4 "Loading deck collection..."]
(empty? decks) [:h4 "No decks"]
:else [:div
(for [deck decks]
[:div.deckline {:class (when (= active-deck deck) "active")
:on-click #(put! select-channel deck)}
[:img {:src (image-url (:identity deck))
:alt (get-in deck [:identity :title] "")}]
[:div.float-right (deck-status-span sets deck)]
[:h4 (:name deck)]
[:div.float-right (-> (:date deck) js/Date. js/moment (.format "MMM Do YYYY"))]
[:p (get-in deck [:identity :title]) [:br]
(when (and (:stats deck) (not= "none" (get-in @app-state [:options :deckstats])))
(let [stats (:stats deck)
games (or (:games stats) 0)
started (or (:games-started stats) 0)
completed (or (:games-completed stats) 0)
wins (or (:wins stats) 0)
losses (or (:loses stats) 0)]
; adding key :games to handle legacy stats before adding started vs completed
[:span " Games: " (+ started games)
" - Completed: " (+ completed games)
" - Won: " wins " (" (num->percent wins (+ wins losses)) "%)"
" - Lost: " losses]))]])])))))
(defn line-span
"Make the view of a single line in the deck - returns a span"
[sets {:keys [identity cards] :as deck} {:keys [qty card] :as line}]
[:span qty " "
(if-let [name (:title card)]
(let [language (get-in @app-state [:options :language])
display (if (:dreamcard card)
name
(case language
"English"
name
"Dutch"
(:title-du card)
"Español"
(:title-es card)
"Finnish"
(:title-fn card)
"French"
(:title-fr card)
"German"
(:title-gr card)
"Italian"
(:title-it card)
"Japanese"
(:title-jp card)
:default
name
))
infaction (noinfcost? identity card)
banned (decks/banned? card)
allied (decks/alliance-is-free? cards line)
valid (and (decks/allowed? card identity)
(decks/legal-num-copies? identity line))
released (decks/released? sets card)
modqty (if (decks/is-prof-prog? deck card) (- qty 1) qty)]
[:span
[:span {:class (cond
(and valid released (not banned)) "fake-link"
valid "casual"
:else "invalid")
:on-mouse-enter #(put! zoom-channel line)
:on-mouse-leave #(put! zoom-channel false)} display]
(card-influence-html card modqty infaction allied)])
card)])
(defn line-qty-span
"Make the view of a single line in the deck - returns a span"
[sets {:keys [identity cards] :as deck} {:keys [qty card] :as line}]
[:span qty " "])
(defn line-name-span
"Make the view of a single line in the deck - returns a span"
[sets {:keys [identity cards] :as deck} {:keys [qty card] :as line}]
[:span (if-let [name (:title card)]
(let [infaction (noinfcost? identity card)
banned (decks/banned? card)
allied (decks/alliance-is-free? cards line)
valid (and (decks/allowed? card identity)
(decks/legal-num-copies? identity line))
released (decks/released? sets card)
modqty (if (decks/is-prof-prog? deck card) (- qty 1) qty)]
[:span
[:span {:class (cond
(and valid released (not banned)) "fake-link"
valid "casual"
:else "invalid")
:on-mouse-enter #(put! zoom-channel line)
:on-mouse-leave #(put! zoom-channel false)} name]
(card-influence-html card modqty infaction allied)])
card)])
(defn- create-identity
[state target-value]
(let [alignment (get-in state [:deck :identity :alignment])
json-map (.parse js/JSON (.. target-value -target -value))
id-map (js->clj json-map :keywordize-keys true)
card (identity-lookup alignment id-map)]
card))
(defn- identity-option-string
[card]
(.stringify js/JSON (clj->js {:title (:title card) :id (:trimCode card)})))
(defn deck-builder
"Make the deckbuilder view"
[{:keys [decks decks-loaded sets] :as cursor} owner]
(reify
om/IInitState
(init-state [this]
{:edit false
:old-deck nil
:resource-edit-channel (chan)
:hazard-edit-channel (chan)
:sideboard-edit-channel (chan)
:character-edit-channel (chan)
:pool-edit-channel (chan)
:fwsb-edit-channel (chan)
:note-edit-channel (chan)
:wizard true
:minion true
:fallen true
:balrog true
:el true
:dl true
:al true
:wl true
:dragon true
:by-date true
:deck-filtered nil
:deck nil
})
om/IWillMount
(will-mount [this]
(let [edit-channel (om/get-state owner :resource-edit-channel)]
(go (while true
(let [card (<! zoom-channel)]
(om/set-state! owner :zoom card))))
(go (while true
(let [edit (<! edit-channel)
card (:card edit)
max-qty (or (:limited card) 9)
cards (om/get-state owner [:deck :resources])
match? #(when (= (get-in % [:card :title]) (:title card)) %)
existing-line (some match? cards)]
(let [new-qty (+ (or (:qty existing-line) 0) (:qty edit))
rest (remove match? cards)
draft-id (decks/is-draft-id? (om/get-state owner [:deck :identity]))
new-cards (cond (and (not draft-id) (> new-qty max-qty))
(conj rest (assoc existing-line :qty max-qty))
(<= new-qty 0) rest
(empty? existing-line) (conj rest {:qty new-qty :card card})
:else (conj rest (assoc existing-line :qty new-qty)))]
(om/set-state! owner [:deck :resources] new-cards))
(resources->str owner)))))
(let [edit-channel (om/get-state owner :hazard-edit-channel)]
(go (while true
(let [card (<! zoom-channel)]
(om/set-state! owner :zoom card))))
(go (while true
(let [edit (<! edit-channel)
card (:card edit)
max-qty (or (:limited card) 9)
cards (om/get-state owner [:deck :hazards])
match? #(when (= (get-in % [:card :title]) (:title card)) %)
existing-line (some match? cards)]
(let [new-qty (+ (or (:qty existing-line) 0) (:qty edit))
rest (remove match? cards)
draft-id (decks/is-draft-id? (om/get-state owner [:deck :identity]))
new-cards (cond (and (not draft-id) (> new-qty max-qty))
(conj rest (assoc existing-line :qty max-qty))
(<= new-qty 0) rest
(empty? existing-line) (conj rest {:qty new-qty :card card})
:else (conj rest (assoc existing-line :qty new-qty)))]
(om/set-state! owner [:deck :hazards] new-cards))
(hazards->str owner)))))
(let [edit-channel (om/get-state owner :sideboard-edit-channel)]
(go (while true
(let [card (<! zoom-channel)]
(om/set-state! owner :zoom card))))
(go (while true
(let [edit (<! edit-channel)
card (:card edit)
max-qty (or (:limited card) 9)
cards (om/get-state owner [:deck :sideboard])
match? #(when (= (get-in % [:card :title]) (:title card)) %)
existing-line (some match? cards)]
(let [new-qty (+ (or (:qty existing-line) 0) (:qty edit))
rest (remove match? cards)
draft-id (decks/is-draft-id? (om/get-state owner [:deck :identity]))
new-cards (cond (and (not draft-id) (> new-qty max-qty))
(conj rest (assoc existing-line :qty max-qty))
(<= new-qty 0) rest
(empty? existing-line) (conj rest {:qty new-qty :card card})
:else (conj rest (assoc existing-line :qty new-qty)))]
(om/set-state! owner [:deck :sideboard] new-cards))
(sideboard->str owner)))))
(let [edit-channel (om/get-state owner :character-edit-channel)]
(go (while true
(let [card (<! zoom-channel)]
(om/set-state! owner :zoom card))))
(go (while true
(let [edit (<! edit-channel)
card (:card edit)
max-qty (or (:limited card) 9)
cards (om/get-state owner [:deck :characters])
match? #(when (= (get-in % [:card :title]) (:title card)) %)
existing-line (some match? cards)]
(let [new-qty (+ (or (:qty existing-line) 0) (:qty edit))
rest (remove match? cards)
draft-id (decks/is-draft-id? (om/get-state owner [:deck :identity]))
new-cards (cond (and (not draft-id) (> new-qty max-qty))
(conj rest (assoc existing-line :qty max-qty))
(<= new-qty 0) rest
(empty? existing-line) (conj rest {:qty new-qty :card card})
:else (conj rest (assoc existing-line :qty new-qty)))]
(om/set-state! owner [:deck :characters] new-cards))
(characters->str owner)))))
(let [edit-channel (om/get-state owner :pool-edit-channel)]
(go (while true
(let [card (<! zoom-channel)]
(om/set-state! owner :zoom card))))
(go (while true
(let [edit (<! edit-channel)
card (:card edit)
max-qty (or (:limited card) 9)
cards (om/get-state owner [:deck :pool])
match? #(when (= (get-in % [:card :title]) (:title card)) %)
existing-line (some match? cards)]
(let [new-qty (+ (or (:qty existing-line) 0) (:qty edit))
rest (remove match? cards)
draft-id (decks/is-draft-id? (om/get-state owner [:deck :identity]))
new-cards (cond (and (not draft-id) (> new-qty max-qty))
(conj rest (assoc existing-line :qty max-qty))
(<= new-qty 0) rest
(empty? existing-line) (conj rest {:qty new-qty :card card})
:else (conj rest (assoc existing-line :qty new-qty)))]
(om/set-state! owner [:deck :pool] new-cards))
(pool->str owner)))))
(let [edit-channel (om/get-state owner :fwsb-edit-channel)]
(go (while true
(let [card (<! zoom-channel)]
(om/set-state! owner :zoom card))))
(go (while true
(let [edit (<! edit-channel)
card (:card edit)
max-qty (or (:limited card) 9)
cards (om/get-state owner [:deck :fwsb])
match? #(when (= (get-in % [:card :title]) (:title card)) %)
existing-line (some match? cards)]
(let [new-qty (+ (or (:qty existing-line) 0) (:qty edit))
rest (remove match? cards)
draft-id (decks/is-draft-id? (om/get-state owner [:deck :identity]))
new-cards (cond (and (not draft-id) (> new-qty max-qty))
(conj rest (assoc existing-line :qty max-qty))
(<= new-qty 0) rest
(empty? existing-line) (conj rest {:qty new-qty :card card})
:else (conj rest (assoc existing-line :qty new-qty)))]
(om/set-state! owner [:deck :fwsb] new-cards))
(fwsb->str owner)))))
(let [edit-channel (om/get-state owner :note-edit-channel)]
(go (while true
(let [edit (<! edit-channel)]
(om/set-state! owner [:deck :note] edit)
(note->str owner)))))
(go (while true
(om/set-state! owner :deck (<! select-channel)))))
om/IRenderState
(render-state [this state]
(sab/html
[:div
[:div.deckbuilder.blue-shade.panel
[:div.viewport {:ref "viewport"}
[:div.decks
[:div.button-bar
[:button {:on-click #(new-deck "Hero" owner)} "New Wizard deck"]
[:button {:on-click #(new-deck "Minion" owner)} "New Minion deck"]
[:button {:on-click #(new-deck "Balrog" owner)} "New Balrog deck"]
[:button {:on-click #(new-deck "Fallen-wizard" owner)} "New Fallen deck"]
[:button {:on-click #(new-deck "Elf-lord" owner)} "New Elf deck"]
[:button {:on-click #(new-deck "Dwarf-lord" owner)} "New Dwarf deck"]
[:button {:on-click #(new-deck "Atani-lord" owner)} "New Atani deck"]
[:button {:on-click #(new-deck "War-lord" owner)} "New Warlord deck"]
[:button {:on-click #(new-deck "Dragon-lord" owner)} "New Dragon deck"]
]
[:div
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :wizard)
:on-change #(do
(om/set-state! owner :wizard (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "Hero "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :minion)
:on-change #(do
(om/set-state! owner :minion (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "Minion "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :fallen)
:on-change #(do
(om/set-state! owner :fallen (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "FW "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :balrog)
:on-change #(do
(om/set-state! owner :balrog (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "BA "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :el)
:on-change #(do
(om/set-state! owner :el (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "EL "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :dl)
:on-change #(do
(om/set-state! owner :dl (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "DL "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :al)
:on-change #(do
(om/set-state! owner :al (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "AL "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :wl)
:on-change #(do
(om/set-state! owner :wl (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "WL "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :dragon)
:on-change #(do
(om/set-state! owner :dragon (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "Dragon "]
[:label [:input {:type "checkbox"
:value true
:checked (om/get-state owner :by-date)
:on-change #(do
(om/set-state! owner :by-date (.. % -target -checked))
(if (om/get-state owner :by-date)
(org-decks-date decks owner)
(org-decks-name decks owner))
)}] "Date"]]
[:div.deck-collection
(when-not (:edit state)
(if (and (nil? (om/get-state owner :decks-filtered))
(and
(om/get-state owner :wizard)
(om/get-state owner :minion)
(om/get-state owner :fallen)
(om/get-state owner :balrog)
(om/get-state owner :el)
(om/get-state owner :dl)
(om/get-state owner :al)
(om/get-state owner :wl)
(om/get-state owner :dragon)
(om/get-state owner :by-date)))
(om/build deck-collection {:sets sets :decks decks :decks-loaded decks-loaded :active-deck (om/get-state owner :deck)})
(om/build deck-collection {:sets sets :decks (om/get-state owner :decks-filtered) :decks-loaded decks-loaded :active-deck (om/get-state owner :deck)})))
]
[:div {:class (when (:edit state) "edit")}
(when-let [line (om/get-state owner :zoom)]
(if (:standard (decks/calculate-deck-status (om/get-state owner :deck)))
(om/build card-ndce (:card line) {:state {:cursor cursor}})
(om/build card-dce (:card line) {:state {:cursor cursor}})))]]
[:div.decklist
(when-let [deck (:deck state)]
(let [identity (:identity deck)
resources (:resources deck)
hazards (:hazards deck)
sideboard (:sideboard deck)
characters (:characters deck)
pool (:pool deck)
fwsb (:fwsb deck)
note (:note deck)
edit? (:edit state)
delete? (:delete state)]
[:div
(cond
edit? [:div.button-bar
[:button {:on-click #(save-deck cursor owner)} "Save"]
[:button {:on-click #(cancel-edit owner)} "Cancel"]
(if (some #{(get-in @app-state [:user :username])} (get-in @app-state [:donators]))
[:h3.rgtlabel "Donator deck dice: "
[:select {:value (:donate-dice deck)
:on-change #(om/set-state! owner [:deck :donate-dice] (.. % -target -value))}
(for [option [{:name "empty" :ref "empty"}
{:name "Black Flat Red Pips 16mm" :ref "blck-16"}
{:name "Black Swirl Red Pips 18mm" :ref "blacks-18"}
{:name "Silver Swirl Red Pips 16mm" :ref "greys-16"}
{:name "Grey Swirl Red Pips 18mm" :ref "greys-18"}
{:name "Dk. Gold Swirl Black Pips 16mm" :ref "gsdark-16"}
{:name "Lt. Gold Swirl Black Pips 18mm" :ref "gslight-18"}
{:name "Orange Flat Black Pips 16mm" :ref "orgblack-16"}
{:name "Red Swirl Black Pips 16mm" :ref "rsblack-16"}
{:name "Red Swirl Black Pips 18mm" :ref "rsblack-18"}
{:name "Red Swirl White Pips 16mm" :ref "rswhite-16"}
{:name "Saruman Rune 18mm" :ref "rune-s-18"}
{:name "Gandalf Rune 18mm" :ref "rune-g-18"}
{:name "Radagast Rune 18mm" :ref "rune-r-18"}
{:name "Alatar Rune 18mm" :ref "rune-a-18"}
{:name "Pallando Rune 18mm" :ref "rune-p-18"}
{:name "RingwPI:NAME:<NAME>END_PIith Rune 18mm" :ref "rune-w-18"}]]
[:option {:value (:ref option)} (:name option)])]
[:select {:value (:donate-size deck)
:on-change #(om/set-state! owner [:deck :donate-size] (.. % -target -value))}
(for [option [{:name "none" :ref "none"}
{:name "16mm" :ref "16mm"}
{:name "18mm" :ref "18mm"}]]
[:option {:value (:ref option)} (:name option)])]
])
]
delete? [:div.button-bar
[:button {:on-click #(handle-delete cursor owner)} "Confirm Delete"]
[:button {:on-click #(end-delete owner)} "Cancel"]]
:else [:div.button-bar
[:button {:on-click #(edit-deck owner)} "Edit"]
[:button {:on-click #(delete-deck owner)} "Delete"]
(when (and (:stats deck) (not= "none" (get-in @app-state [:options :deckstats])))
[:button {:on-click #(clear-deck-stats cursor owner)} "Clear Stats"])])
[:h3 (:name deck)]
[:div.header
[:img {:src (image-url identity)
:alt (:title identity)}]
[:h4 {:class (if (decks/released? (:sets @app-state) identity) "fake-link" "casual")
:on-mouse-enter #(put! zoom-channel {:card identity :art (:art identity) :id (:id identity)})
:on-mouse-leave #(put! zoom-channel false)}
(:title identity)
(if (decks/banned? identity)
banned-span
(when (:released identity) rotated-span))]
(let [count (+ (+ (decks/card-count (:resources deck))
(decks/card-count (:hazards deck)))
(decks/card-count (:characters deck)))
min-count (decks/min-deck-size identity)]
[:div count " cards"
(when (< count min-count)
[:span.invalid (str " (minimum " min-count ")")])])
(comment
(let [inf (decks/influence-count deck)
id-limit (decks/id-inf-limit identity)]
[:div "Influence: "
;; we don't use valid? and mwl-legal? functions here, since it concerns influence only
[:span {:class (if (> inf id-limit) (if (> inf id-limit) "invalid" "casual") "legal")} inf]
"/" (if (= INFINITY id-limit) "∞" id-limit)
(if (pos? inf)
(list " " (deck-influence-html deck)))]))
(when (= (:alignment identity) "Crazy")
(let [min-point (decks/min-agenda-points deck)
points (decks/agenda-points deck)]
[:div "Agenda points: " points
(when (< points min-point)
[:span.invalid " (minimum " min-point ")"])
(when (> points (inc min-point))
[:span.invalid " (maximum " (inc min-point) ")"])]))
[:div (deck-status-span sets deck true true false)]]
[:div.cards
(if (not-empty pool) [:h3 "Pool"])
(for [group (sort-by first (group-by #(get-in % [:card :Secondary]) pool))]
[:div.group
[:h4 (str (or (first group) "Unknown") " (" (decks/card-count (last group)) ")") ]
(for [line (sort-by #(get-in % [:card :title]) (last group))]
[:div.line
(when (:edit state)
(let [ch (om/get-state owner :pool-edit-channel)]
[:span
[:button.small {:on-click #(put! ch {:qty 1 :card (:card line)})
:type "button"} "+"]
[:button.small {:on-click #(put! ch {:qty -1 :card (:card line)})
:type "button"} "-"]]))
(line-span sets deck line)])])]
[:div.cards
(if (not-empty characters) [:h3 "Characters"])
(for [group (sort-by first (group-by #(get-in % [:card :Race]) characters))]
[:div.group
[:h4 (str (or (first group) "Unknown") " (" (decks/card-count (last group)) ")") ]
(for [line (sort-by #(get-in % [:card :title]) (last group))]
[:div.line
(when (:edit state)
(let [ch (om/get-state owner :character-edit-channel)]
[:span
[:button.small {:on-click #(put! ch {:qty 1 :card (:card line)})
:type "button"} "+"]
[:button.small {:on-click #(put! ch {:qty -1 :card (:card line)})
:type "button"} "-"]]))
(line-span sets deck line)])])]
[:div.cards
(if (not-empty resources) [:h3 (str "Resources: " (decks/card-count resources) "")])
(for [group (sort-by first (group-by #(get-in % [:card :Secondary]) resources))]
[:div.group
[:h4 (str (or (first group) "Unknown") " (" (decks/card-count (last group)) ")") ]
(for [line (sort-by #(get-in % [:card :title]) (last group))]
[:div.line
(when (:edit state)
(let [ch (om/get-state owner :resource-edit-channel)]
[:span
[:button.small {:on-click #(put! ch {:qty 1 :card (:card line)})
:type "button"} "+"]
[:button.small {:on-click #(put! ch {:qty -1 :card (:card line)})
:type "button"} "-"]]))
(line-span sets deck line)])])]
[:div.cards
(if (not-empty hazards) [:h3 (str "Hazards: " (decks/card-count hazards) "")])
(for [group (sort-by first (group-by #(get-in % [:card :Secondary]) hazards))]
[:div.group
[:h4 (str (or (first group) "Unknown") " (" (decks/card-count (last group)) ")") ]
(for [line (sort-by #(get-in % [:card :title]) (last group))]
[:div.line
(when (:edit state)
(let [ch (om/get-state owner :hazard-edit-channel)]
[:span
[:button.small {:on-click #(put! ch {:qty 1 :card (:card line)})
:type "button"} "+"]
[:button.small {:on-click #(put! ch {:qty -1 :card (:card line)})
:type "button"} "-"]]))
(line-span sets deck line)])])]
[:div.cards
(if (not-empty sideboard) [:h3 (str "Sideboard: " (decks/card-count sideboard) "")])
(for [group (sort-by first (group-by #(get-in % [:card :type]) sideboard))]
[:div.group
[:h4 (str (or (first group) "Unknown") " (" (decks/card-count (last group)) ")") ]
(for [line (sort-by #(get-in % [:card :title]) (last group))]
[:div.line
(when (:edit state)
(let [ch (om/get-state owner :sideboard-edit-channel)]
[:span
[:button.small {:on-click #(put! ch {:qty 1 :card (:card line)})
:type "button"} "+"]
[:button.small {:on-click #(put! ch {:qty -1 :card (:card line)})
:type "button"} "-"]]))
(line-span sets deck line)])])]
[:div.cards
(if (not-empty fwsb) [:h3 "FW-DC-SB"])
(for [group (sort-by first (group-by #(get-in % [:card :type]) fwsb))]
[:div.group
[:h4 (str (or (first group) "Unknown") " (" (decks/card-count (last group)) ")") ]
(for [line (sort-by #(get-in % [:card :title]) (last group))]
[:div.line
(when (:edit state)
(let [ch (om/get-state owner :fwsb-edit-channel)]
[:span
[:button.small {:on-click #(put! ch {:qty 1 :card (:card line)})
:type "button"} "+"]
[:button.small {:on-click #(put! ch {:qty -1 :card (:card line)})
:type "button"} "-"]]))
(line-span sets deck line)])])]
[:div.cards
(if (not-empty note) [:h3 "Deck Notes"])
[:div.note
[:h4 (str note)]]]
]))]
[:div.deckedit
[:div
[:p
[:h3.lftlabel "Deck name"]
[:h3.rgtlabel "Avatar"]
[:input.deckname {:type "text" :placeholder "Deck name"
:ref "deckname" :value (get-in state [:deck :name])
:on-change #(om/set-state! owner [:deck :name] (.. % -target -value))}]]
[:p
[:select.identity {:value (identity-option-string (get-in state [:deck :identity]))
:on-change #(om/set-state! owner [:deck :identity] (create-identity state %))}
(let [idents (alignment-identities (get-in state [:deck :identity :alignment]))]
(for [card (sort-by :display-name idents)]
[:option
{:value (identity-option-string card)}
(:display-name card)]))]]
(om/build card-lookup cursor {:state state})
[:div
[:h3.column1 "Resources"]
[:h3.column2 "Hazards"]
[:h3.column3 "Sideboard"]
]
[:textarea.txttop {:ref "resource-edit" :value (:resource-edit state)
:on-change #(handle-resource-edit owner)}]
[:textarea.txttop {:ref "hazard-edit" :value (:hazard-edit state)
:on-change #(handle-hazard-edit owner)}]
[:textarea.txttop {:ref "sideboard-edit" :value (:sideboard-edit state)
:on-change #(handle-sideboard-edit owner)}]
[:div
[:h3.column1 "Characters"]
[:h3.column2 "Pool"]
[:h3.column3 "FW-DC-SB"]
]
[:textarea.txtbot {:ref "character-edit" :value (:character-edit state)
:on-change #(handle-character-edit owner)}]
[:textarea.txtbot {:ref "pool-edit" :value (:pool-edit state)
:on-change #(handle-pool-edit owner)}]
[:textarea.txtbot {:ref "fwsb-edit" :value (:fwsb-edit state)
:on-change #(handle-fwsb-edit owner)}]
[:div
[:h3 "Deck Notes"]]
[:textarea.txtnte {:ref "deck-note" :value (:deck-note state)
:on-change #(handle-deck-note owner)}]
]]]]]))))
(go (swap! app-state assoc :donators (:json (<! (GET "/data/donors")))))
(go (let [cards (<! cards-channel)
decks (process-decks (:json (<! (GET (str "/data/decks")))))]
(load-decks decks)
(>! cards-channel cards)))
(om/root deck-builder app-state {:target (. js/document (getElementById "deckbuilder"))})
|
[
{
"context": " :name \"Luke Skywalker\"})}}})\n q1 \"{ human(id: \\\"1003\\\") { ",
"end": 4452,
"score": 0.9998111128807068,
"start": 4438,
"tag": "NAME",
"value": "Luke Skywalker"
}
] | test/com/walmartlabs/lacinia/custom_scalars_test.clj | gusbicalho/lacinia | 0 | (ns com.walmartlabs.lacinia.custom-scalars-test
(:require [clojure.spec.alpha :as s]
[clojure.test :refer [deftest is testing]]
[com.walmartlabs.lacinia.schema :as schema]
[com.walmartlabs.test-schema :refer [test-schema]]
[com.walmartlabs.test-utils :refer [is-thrown execute]]
[clojure.java.io :as io]
[clojure.edn :as edn]
[com.walmartlabs.lacinia.util :as util])
(:import (java.text SimpleDateFormat)
(java.util Date)
(org.joda.time DateTime DateTimeConstants)
(org.joda.time.format DateTimeFormat)))
(def default-schema (schema/compile test-schema))
;;-------------------------------------------------------------------------------
;; ## Tests
(deftest custom-scalar-query
(let [q "{ now { date }}"]
(is (= {:data {:now {:date "A long time ago"}}}
(execute default-schema q nil nil)))))
(deftest custom-scalars
(testing "custom scalars defined as conformers"
(let [parse-conformer (s/conformer
(fn [x]
(if (and
(string? x)
(< (count x) 3))
x
:clojure.spec.alpha/invalid)))
serialize-conformer (s/conformer
(fn [x]
(case x
"200" "OK"
"500" "ERROR"
:clojure.spec.alpha/invalid)))]
(testing "custom scalar's serializing option"
(let [schema (schema/compile {:scalars
{:Event {:parse parse-conformer
:serialize serialize-conformer}}
:objects
{:galaxy_event
{:fields {:lookup {:type :Event}}}}
:queries
{:events {:type :galaxy_event
:resolve (fn [ctx args v]
{:lookup "200"})}}})
q "{ events { lookup }}"]
(is (= {:data {:events {:lookup "OK"}}} (execute schema q nil nil))
"should return conformed value")))
(testing "custom scalar's invalid value"
(let [schema (schema/compile {:scalars
{:Event {:parse parse-conformer
:serialize serialize-conformer}
:EventId {:parse parse-conformer
:serialize (s/conformer str)}}
:objects
{:galaxy_event
{:fields {:lookup {:type :Event}}}
:human
{:fields {:id {:type :EventId}
:name {:type 'String}}}}
:queries
{:events {:type :galaxy_event
:resolve (fn [ctx args v]
;; type of :lookup is :Event
;; that is a custom scalar with
;; a serialize function that
;; deems anything other than
;; "200" or "500" invalid.
;; So value 1 should cause
;; an error.
{:lookup 1})}
:human {:type '(non-null :human)
:args {:id {:type :EventId}}
:resolve (fn [ctx args v]
{:id "1000"
:name "Luke Skywalker"})}}})
q1 "{ human(id: \"1003\") { id, name }}"
q2 "{ events { lookup }}"]
(is (= {:errors [{:argument :id
:field :human
:locations [{:column 0
:line 1}]
:message "Exception applying arguments to field `human': For argument `id', scalar value is not parsable as type `EventId'."
:query-path []
:type-name :EventId
:value "1003"}]}
(execute schema q1 nil nil))
"should return error message")
(is (= {:data {:events {:lookup nil}}
:errors [{:locations [{:column 9
:line 1}]
:message "Invalid value for a scalar type."
:query-path [:events
:lookup]
:type :Event
:value "1"}]}
(execute schema q2 nil nil))
"should return error message"))))))
(deftest custom-scalars-with-variables
(let [date-formatter (SimpleDateFormat. "yyyy-MM-dd")
parse-conformer (s/conformer (fn [input]
(try (.parse date-formatter input)
(catch Exception e
:clojure.spec.alpha/invalid))))
serialize-conformer (s/conformer (fn [output] (.format date-formatter output)))
schema (schema/compile
{:scalars {:Date {:parse parse-conformer
:serialize serialize-conformer}}
:queries {:today {:type :Date
:args {:asOf {:type :Date}}
:resolve (fn [ctx args v] (:asOf args))}}})]
(is (= {:data {:today "2017-04-05"}}
(execute schema "query ($asOf : Date = \"2017-04-05\") {
today (asOf: $asOf)
}"
nil
nil))
"should return parsed and serialized value")
(is (= {:data {:today "2017-04-05"}}
(execute schema "query ($asOf: Date) {
today(asOf: $asOf)
}"
{:asOf "2017-04-05"}
nil))
"should return parsed and serialized value")
(is (= {:errors [{:message "Scalar value is not parsable as type `Date'.",
:value "abc",
:type-name :Date}]}
(execute schema "query ($asOf: Date) {
today(asOf: $asOf)
}"
{:asOf "abc"}
nil))
"should return error message")))
(defn ^:private periodic-seq
[^Date start ^Date end]
(take-while (fn [^Date date]
(not (.isAfter date end)))
(map (fn [i] (.plusDays start i)) (iterate inc 0))))
(defn ^:private sunday? [t]
(= (.getDayOfWeek t) (DateTimeConstants/SUNDAY)))
(defn ^:private sundays [start end]
(let [date-range (if (and start end) (periodic-seq start end) [])]
(filter sunday? date-range)))
(deftest custom-scalars-with-complex-types
(let [date-formatter (DateTimeFormat/forPattern "yyyy-MM-dd")
parse-conformer (s/conformer (fn [input]
(try (DateTime. (.parseDateTime date-formatter input))
(catch Exception e
:clojure.spec/invalid))))
serialize-conformer (s/conformer (fn [output] (.print date-formatter output)))
schema (schema/compile {:scalars {:Date {:parse parse-conformer
:serialize serialize-conformer}}
:queries {:sundays {:type '(list (non-null :Date))
:args {:between {:type '(non-null (list (non-null :Date)))}}
:resolve (fn [ctx args v]
(let [[start end] (:between args)]
(sundays start end)))}}})]
(is (= {:data {:sundays ["2017-03-05" "2017-03-12" "2017-03-19" "2017-03-26"]}}
(execute schema "query ($between: [Date!]!) {
sundays(between: $between)
}"
{:between ["2017-03-05" "2017-03-30"]}
nil))
"should return list of serialized dates")
(is (= {:data {:sundays []}}
(execute schema "query ($between: [Date!]!) {
sundays(between: $between)
}"
{:between ["2017-03-06" "2017-03-07"]}
nil))
"should return empty list")
(is (= {:data {:sundays []}}
(execute schema "query ($between: [Date!]!) {
sundays(between: $between)
}"
{:between []}
nil))
"should return empty list (:between can be an empty list) ")
(is (= {:errors [{:message "No value was provided for variable `between', which is non-nullable.",
:variable-name :between}]}
(execute schema "query ($between: [Date!]!) {
sundays(between: $between)
}"
{:between nil}
nil))
"should return an error")
(is (= {:errors [{:message "Variable `between' contains null members but supplies the value for a list that can't have any null members."
:variable-name :between}]}
(execute schema "query ($between: [Date!]!) {
sundays(between: $between)
}"
{:between [nil]}
nil))
"should return an error")
(is (= {:errors [{:message "Variable `between' contains null members but supplies the value for a list that can't have any null members."
:variable-name :between}]}
(execute schema "query ($between: [Date!]!) {
sundays(between: $between)
}"
{:between ["2017-03-01" nil]}
nil))
"should return an error")
(is (= {:errors [{:message "No value was provided for variable `between', which is non-nullable."
:variable-name :between}]}
(execute schema "query ($between: [Date!]!) {
sundays(between: $between)
}"
nil
nil))
"should return an error"))
(testing "nested lists"
(let [scalars {:CustomType {:parse (s/conformer (fn [x] (name x)))
:serialize (s/conformer (fn [x] (.toUpperCase x)))}}
schema (schema/compile {:scalars scalars
:queries {:shout {:type '(list (list (list :CustomType)))
:args {:words {:type '(list (list (list :CustomType)))}}
:resolve (fn [ctx args v]
(:words args))}}})]
(is (= {:data {:shout [[["FOO" "BAR"]]]}}
(execute schema "query ($words: [[[CustomType]]]) {
shout(words: $words)
}"
{:words [[["foo" "bar"]]]}
nil))
"should return nested list")
(is (= {:errors [{:message "Variable `words' doesn't contain the correct number of (nested) lists.",
:variable-name :words}]}
(execute schema "query ($words: [[[CustomType]]]) {
shout(words: $words)
}"
{:words [["foo" "bar"]]}
nil))
"should return an error")
(is (= {:data {:shout []}}
(execute schema "query ($words: [[[CustomType]]]) {
shout(words: $words)
}"
{:words nil}
nil))
"should return empty list")))
(testing "nested list with a non-null root element in query result"
(let [scalars {:CustomType {:parse (s/conformer (fn [x] (name x)))
:serialize (s/conformer (fn [x] (.toUpperCase x)))}}
schema (schema/compile {:scalars scalars
:queries {:shout {:type '(list (list (list (non-null :CustomType))))
:args {:words {:type '(list (list (list :CustomType)))}}
:resolve (fn [ctx args v]
(:words args))}}})]
(is (= {:data {:shout [[[nil]]]},
:errors [{:message "Non-nullable field was null.",
:locations [{:line 1, :column 33}],
:query-path [:shout],
:arguments {:words '$words}}]}
(execute schema "query ($words: [[[CustomType]]]) {
shout(words: $words)
}"
{:words [[[nil]]]}
nil))
"should return an error")
(is (= {:errors [{:message"Variable `words' doesn't contain the correct number of (nested) lists.",
:variable-name :words}]}
(execute schema "query ($words: [[[CustomType]]]) {
shout(words: $words)
}"
{:words [[nil]]}
nil))
"should return an error")
(is (= {:data {:shout [[["BAR"]]]}}
(execute schema "query ($words: [[[CustomType]]]) {
shout(words: $words)
}"
{:words [[["bar"]]]}
nil))
"should return data")))
(testing "nested list with a non-null root element in query args"
(let [scalars {:CustomType {:parse (s/conformer (fn [x] (name x)))
:serialize (s/conformer (fn [x] (.toUpperCase x)))}}
schema (schema/compile {:scalars scalars
:queries {:shout {:type '(list (list (list :CustomType)))
:args {:words {:type '(list (list (list (non-null :CustomType))))}}
:resolve (fn [ctx args v]
(:words args))}}})]
(is (= {:errors [{:message "Variable `words' contains null members but supplies the value for a list that can't have any null members.",
:variable-name :words}]}
(execute schema "query ($words: [[[CustomType!]]]) {
shout(words: $words)
}"
{:words [[[nil]]]}
nil))
"should return an error")
(is (= {:errors [{:message"Variable `words' doesn't contain the correct number of (nested) lists.",
:variable-name :words}]}
(execute schema "query ($words: [[[CustomType!]]]) {
shout(words: $words)
}"
{:words [["foo"]]}
nil))
"should return an error")
(is (= {:errors [{:message "Exception applying arguments to field `shout': For argument `words', variable and argument are not compatible types.",
:query-path []
:locations [{:line 1 :column 33}]
:field :shout
:argument :words
:argument-type "[[[CustomType!]]]"
:variable-type "[[[CustomType]]]"}]}
(execute schema "query ($words: [[[CustomType]]]) {
shout(words: $words)
}"
{:words [["foo"]]}
nil))
"should return an error")
(is (= {:data {:shout [[["FOO"]]]}}
(execute schema "query ($words: [[[CustomType!]]]) {
shout(words: $words)
}"
{:words [[["foo"]]]}
nil))
"should return an error")))
(testing "nested non-null lists with a root list allowed to contain nulls in query args"
(let [scalars {:CustomType {:parse (s/conformer (fn [x] (if (some? x)
(name x)
:clojure.spec/invalid)))
:serialize (s/conformer (fn [x] (when x (.toUpperCase x))))}}
schema (schema/compile {:scalars scalars
:queries {:shout {:type '(list (list (list :CustomType)))
:args {:words {:type '(non-null (list (non-null (list (non-null (list :CustomType))))))}}
:resolve (fn [ctx args v]
(:words args))}}})]
(is (= {:data {:shout [[[nil]]]}}
(execute schema "query ($words: [[[CustomType]!]!]!) {
shout(words: $words)
}"
{:words [[[nil]]]}
nil))
"should return data")
(is (= {:data {:shout [[["FOO"]]]}}
(execute schema "query ($words: [[[CustomType]!]!]!) {
shout(words: $words)
}"
{:words [[["foo"]]]}
nil))
"should return data")
(is (= {:data {:shout [[[] ["FOO"]]]}}
(execute schema "query ($words: [[[CustomType]!]!]!) {
shout(words: $words)
}"
{:words [[[] ["foo"]]]}
nil))
"should coerece single value to a list of size one"))))
(deftest use-of-coercion-error
(let [schema (-> "custom-scalar-serialize-schema.edn"
io/resource
slurp
edn/read-string
(util/attach-resolvers {:test-query
(fn [_ args _]
(:in args))})
(util/attach-scalar-transformers
{:parse (schema/as-conformer (fn [s]
(if (= "5" s)
(schema/coercion-failure "Just don't like 5.")
(Integer/parseInt s))))
:serialize (schema/as-conformer
(fn [v]
(if (< v 5)
v
(schema/coercion-failure "5 is too big."))))})
schema/compile)]
(testing "parsers"
(is (= {:data {:dupe 4}}
(execute schema
"{ dupe (in:4) }"
nil
nil)))
(is (= {:errors [{:argument :in
:field :dupe
:locations [{:column 0
:line 1}]
:message "Exception applying arguments to field `dupe': For argument `in', just don't like 5."
:query-path []
:type-name :LimitedInt
:value "5"}]}
(execute schema
"{ dupe (in: 5) }"
nil
nil))))
(testing "serializers"
(is (= {:data {:test 4}}
(execute schema
"{ test (in:4) }"
nil
nil)))
(is (= {:data {:test nil}
:errors [{:arguments {:in "5"}
:locations [{:column 0
:line 1}]
:message "5 is too big."
:query-path [:test]}]}
(execute schema
"{ test (in:5) }"
nil
nil))))))
| 87187 | (ns com.walmartlabs.lacinia.custom-scalars-test
(:require [clojure.spec.alpha :as s]
[clojure.test :refer [deftest is testing]]
[com.walmartlabs.lacinia.schema :as schema]
[com.walmartlabs.test-schema :refer [test-schema]]
[com.walmartlabs.test-utils :refer [is-thrown execute]]
[clojure.java.io :as io]
[clojure.edn :as edn]
[com.walmartlabs.lacinia.util :as util])
(:import (java.text SimpleDateFormat)
(java.util Date)
(org.joda.time DateTime DateTimeConstants)
(org.joda.time.format DateTimeFormat)))
(def default-schema (schema/compile test-schema))
;;-------------------------------------------------------------------------------
;; ## Tests
(deftest custom-scalar-query
(let [q "{ now { date }}"]
(is (= {:data {:now {:date "A long time ago"}}}
(execute default-schema q nil nil)))))
(deftest custom-scalars
(testing "custom scalars defined as conformers"
(let [parse-conformer (s/conformer
(fn [x]
(if (and
(string? x)
(< (count x) 3))
x
:clojure.spec.alpha/invalid)))
serialize-conformer (s/conformer
(fn [x]
(case x
"200" "OK"
"500" "ERROR"
:clojure.spec.alpha/invalid)))]
(testing "custom scalar's serializing option"
(let [schema (schema/compile {:scalars
{:Event {:parse parse-conformer
:serialize serialize-conformer}}
:objects
{:galaxy_event
{:fields {:lookup {:type :Event}}}}
:queries
{:events {:type :galaxy_event
:resolve (fn [ctx args v]
{:lookup "200"})}}})
q "{ events { lookup }}"]
(is (= {:data {:events {:lookup "OK"}}} (execute schema q nil nil))
"should return conformed value")))
(testing "custom scalar's invalid value"
(let [schema (schema/compile {:scalars
{:Event {:parse parse-conformer
:serialize serialize-conformer}
:EventId {:parse parse-conformer
:serialize (s/conformer str)}}
:objects
{:galaxy_event
{:fields {:lookup {:type :Event}}}
:human
{:fields {:id {:type :EventId}
:name {:type 'String}}}}
:queries
{:events {:type :galaxy_event
:resolve (fn [ctx args v]
;; type of :lookup is :Event
;; that is a custom scalar with
;; a serialize function that
;; deems anything other than
;; "200" or "500" invalid.
;; So value 1 should cause
;; an error.
{:lookup 1})}
:human {:type '(non-null :human)
:args {:id {:type :EventId}}
:resolve (fn [ctx args v]
{:id "1000"
:name "<NAME>"})}}})
q1 "{ human(id: \"1003\") { id, name }}"
q2 "{ events { lookup }}"]
(is (= {:errors [{:argument :id
:field :human
:locations [{:column 0
:line 1}]
:message "Exception applying arguments to field `human': For argument `id', scalar value is not parsable as type `EventId'."
:query-path []
:type-name :EventId
:value "1003"}]}
(execute schema q1 nil nil))
"should return error message")
(is (= {:data {:events {:lookup nil}}
:errors [{:locations [{:column 9
:line 1}]
:message "Invalid value for a scalar type."
:query-path [:events
:lookup]
:type :Event
:value "1"}]}
(execute schema q2 nil nil))
"should return error message"))))))
(deftest custom-scalars-with-variables
(let [date-formatter (SimpleDateFormat. "yyyy-MM-dd")
parse-conformer (s/conformer (fn [input]
(try (.parse date-formatter input)
(catch Exception e
:clojure.spec.alpha/invalid))))
serialize-conformer (s/conformer (fn [output] (.format date-formatter output)))
schema (schema/compile
{:scalars {:Date {:parse parse-conformer
:serialize serialize-conformer}}
:queries {:today {:type :Date
:args {:asOf {:type :Date}}
:resolve (fn [ctx args v] (:asOf args))}}})]
(is (= {:data {:today "2017-04-05"}}
(execute schema "query ($asOf : Date = \"2017-04-05\") {
today (asOf: $asOf)
}"
nil
nil))
"should return parsed and serialized value")
(is (= {:data {:today "2017-04-05"}}
(execute schema "query ($asOf: Date) {
today(asOf: $asOf)
}"
{:asOf "2017-04-05"}
nil))
"should return parsed and serialized value")
(is (= {:errors [{:message "Scalar value is not parsable as type `Date'.",
:value "abc",
:type-name :Date}]}
(execute schema "query ($asOf: Date) {
today(asOf: $asOf)
}"
{:asOf "abc"}
nil))
"should return error message")))
(defn ^:private periodic-seq
[^Date start ^Date end]
(take-while (fn [^Date date]
(not (.isAfter date end)))
(map (fn [i] (.plusDays start i)) (iterate inc 0))))
(defn ^:private sunday? [t]
(= (.getDayOfWeek t) (DateTimeConstants/SUNDAY)))
(defn ^:private sundays [start end]
(let [date-range (if (and start end) (periodic-seq start end) [])]
(filter sunday? date-range)))
(deftest custom-scalars-with-complex-types
(let [date-formatter (DateTimeFormat/forPattern "yyyy-MM-dd")
parse-conformer (s/conformer (fn [input]
(try (DateTime. (.parseDateTime date-formatter input))
(catch Exception e
:clojure.spec/invalid))))
serialize-conformer (s/conformer (fn [output] (.print date-formatter output)))
schema (schema/compile {:scalars {:Date {:parse parse-conformer
:serialize serialize-conformer}}
:queries {:sundays {:type '(list (non-null :Date))
:args {:between {:type '(non-null (list (non-null :Date)))}}
:resolve (fn [ctx args v]
(let [[start end] (:between args)]
(sundays start end)))}}})]
(is (= {:data {:sundays ["2017-03-05" "2017-03-12" "2017-03-19" "2017-03-26"]}}
(execute schema "query ($between: [Date!]!) {
sundays(between: $between)
}"
{:between ["2017-03-05" "2017-03-30"]}
nil))
"should return list of serialized dates")
(is (= {:data {:sundays []}}
(execute schema "query ($between: [Date!]!) {
sundays(between: $between)
}"
{:between ["2017-03-06" "2017-03-07"]}
nil))
"should return empty list")
(is (= {:data {:sundays []}}
(execute schema "query ($between: [Date!]!) {
sundays(between: $between)
}"
{:between []}
nil))
"should return empty list (:between can be an empty list) ")
(is (= {:errors [{:message "No value was provided for variable `between', which is non-nullable.",
:variable-name :between}]}
(execute schema "query ($between: [Date!]!) {
sundays(between: $between)
}"
{:between nil}
nil))
"should return an error")
(is (= {:errors [{:message "Variable `between' contains null members but supplies the value for a list that can't have any null members."
:variable-name :between}]}
(execute schema "query ($between: [Date!]!) {
sundays(between: $between)
}"
{:between [nil]}
nil))
"should return an error")
(is (= {:errors [{:message "Variable `between' contains null members but supplies the value for a list that can't have any null members."
:variable-name :between}]}
(execute schema "query ($between: [Date!]!) {
sundays(between: $between)
}"
{:between ["2017-03-01" nil]}
nil))
"should return an error")
(is (= {:errors [{:message "No value was provided for variable `between', which is non-nullable."
:variable-name :between}]}
(execute schema "query ($between: [Date!]!) {
sundays(between: $between)
}"
nil
nil))
"should return an error"))
(testing "nested lists"
(let [scalars {:CustomType {:parse (s/conformer (fn [x] (name x)))
:serialize (s/conformer (fn [x] (.toUpperCase x)))}}
schema (schema/compile {:scalars scalars
:queries {:shout {:type '(list (list (list :CustomType)))
:args {:words {:type '(list (list (list :CustomType)))}}
:resolve (fn [ctx args v]
(:words args))}}})]
(is (= {:data {:shout [[["FOO" "BAR"]]]}}
(execute schema "query ($words: [[[CustomType]]]) {
shout(words: $words)
}"
{:words [[["foo" "bar"]]]}
nil))
"should return nested list")
(is (= {:errors [{:message "Variable `words' doesn't contain the correct number of (nested) lists.",
:variable-name :words}]}
(execute schema "query ($words: [[[CustomType]]]) {
shout(words: $words)
}"
{:words [["foo" "bar"]]}
nil))
"should return an error")
(is (= {:data {:shout []}}
(execute schema "query ($words: [[[CustomType]]]) {
shout(words: $words)
}"
{:words nil}
nil))
"should return empty list")))
(testing "nested list with a non-null root element in query result"
(let [scalars {:CustomType {:parse (s/conformer (fn [x] (name x)))
:serialize (s/conformer (fn [x] (.toUpperCase x)))}}
schema (schema/compile {:scalars scalars
:queries {:shout {:type '(list (list (list (non-null :CustomType))))
:args {:words {:type '(list (list (list :CustomType)))}}
:resolve (fn [ctx args v]
(:words args))}}})]
(is (= {:data {:shout [[[nil]]]},
:errors [{:message "Non-nullable field was null.",
:locations [{:line 1, :column 33}],
:query-path [:shout],
:arguments {:words '$words}}]}
(execute schema "query ($words: [[[CustomType]]]) {
shout(words: $words)
}"
{:words [[[nil]]]}
nil))
"should return an error")
(is (= {:errors [{:message"Variable `words' doesn't contain the correct number of (nested) lists.",
:variable-name :words}]}
(execute schema "query ($words: [[[CustomType]]]) {
shout(words: $words)
}"
{:words [[nil]]}
nil))
"should return an error")
(is (= {:data {:shout [[["BAR"]]]}}
(execute schema "query ($words: [[[CustomType]]]) {
shout(words: $words)
}"
{:words [[["bar"]]]}
nil))
"should return data")))
(testing "nested list with a non-null root element in query args"
(let [scalars {:CustomType {:parse (s/conformer (fn [x] (name x)))
:serialize (s/conformer (fn [x] (.toUpperCase x)))}}
schema (schema/compile {:scalars scalars
:queries {:shout {:type '(list (list (list :CustomType)))
:args {:words {:type '(list (list (list (non-null :CustomType))))}}
:resolve (fn [ctx args v]
(:words args))}}})]
(is (= {:errors [{:message "Variable `words' contains null members but supplies the value for a list that can't have any null members.",
:variable-name :words}]}
(execute schema "query ($words: [[[CustomType!]]]) {
shout(words: $words)
}"
{:words [[[nil]]]}
nil))
"should return an error")
(is (= {:errors [{:message"Variable `words' doesn't contain the correct number of (nested) lists.",
:variable-name :words}]}
(execute schema "query ($words: [[[CustomType!]]]) {
shout(words: $words)
}"
{:words [["foo"]]}
nil))
"should return an error")
(is (= {:errors [{:message "Exception applying arguments to field `shout': For argument `words', variable and argument are not compatible types.",
:query-path []
:locations [{:line 1 :column 33}]
:field :shout
:argument :words
:argument-type "[[[CustomType!]]]"
:variable-type "[[[CustomType]]]"}]}
(execute schema "query ($words: [[[CustomType]]]) {
shout(words: $words)
}"
{:words [["foo"]]}
nil))
"should return an error")
(is (= {:data {:shout [[["FOO"]]]}}
(execute schema "query ($words: [[[CustomType!]]]) {
shout(words: $words)
}"
{:words [[["foo"]]]}
nil))
"should return an error")))
(testing "nested non-null lists with a root list allowed to contain nulls in query args"
(let [scalars {:CustomType {:parse (s/conformer (fn [x] (if (some? x)
(name x)
:clojure.spec/invalid)))
:serialize (s/conformer (fn [x] (when x (.toUpperCase x))))}}
schema (schema/compile {:scalars scalars
:queries {:shout {:type '(list (list (list :CustomType)))
:args {:words {:type '(non-null (list (non-null (list (non-null (list :CustomType))))))}}
:resolve (fn [ctx args v]
(:words args))}}})]
(is (= {:data {:shout [[[nil]]]}}
(execute schema "query ($words: [[[CustomType]!]!]!) {
shout(words: $words)
}"
{:words [[[nil]]]}
nil))
"should return data")
(is (= {:data {:shout [[["FOO"]]]}}
(execute schema "query ($words: [[[CustomType]!]!]!) {
shout(words: $words)
}"
{:words [[["foo"]]]}
nil))
"should return data")
(is (= {:data {:shout [[[] ["FOO"]]]}}
(execute schema "query ($words: [[[CustomType]!]!]!) {
shout(words: $words)
}"
{:words [[[] ["foo"]]]}
nil))
"should coerece single value to a list of size one"))))
(deftest use-of-coercion-error
(let [schema (-> "custom-scalar-serialize-schema.edn"
io/resource
slurp
edn/read-string
(util/attach-resolvers {:test-query
(fn [_ args _]
(:in args))})
(util/attach-scalar-transformers
{:parse (schema/as-conformer (fn [s]
(if (= "5" s)
(schema/coercion-failure "Just don't like 5.")
(Integer/parseInt s))))
:serialize (schema/as-conformer
(fn [v]
(if (< v 5)
v
(schema/coercion-failure "5 is too big."))))})
schema/compile)]
(testing "parsers"
(is (= {:data {:dupe 4}}
(execute schema
"{ dupe (in:4) }"
nil
nil)))
(is (= {:errors [{:argument :in
:field :dupe
:locations [{:column 0
:line 1}]
:message "Exception applying arguments to field `dupe': For argument `in', just don't like 5."
:query-path []
:type-name :LimitedInt
:value "5"}]}
(execute schema
"{ dupe (in: 5) }"
nil
nil))))
(testing "serializers"
(is (= {:data {:test 4}}
(execute schema
"{ test (in:4) }"
nil
nil)))
(is (= {:data {:test nil}
:errors [{:arguments {:in "5"}
:locations [{:column 0
:line 1}]
:message "5 is too big."
:query-path [:test]}]}
(execute schema
"{ test (in:5) }"
nil
nil))))))
| true | (ns com.walmartlabs.lacinia.custom-scalars-test
(:require [clojure.spec.alpha :as s]
[clojure.test :refer [deftest is testing]]
[com.walmartlabs.lacinia.schema :as schema]
[com.walmartlabs.test-schema :refer [test-schema]]
[com.walmartlabs.test-utils :refer [is-thrown execute]]
[clojure.java.io :as io]
[clojure.edn :as edn]
[com.walmartlabs.lacinia.util :as util])
(:import (java.text SimpleDateFormat)
(java.util Date)
(org.joda.time DateTime DateTimeConstants)
(org.joda.time.format DateTimeFormat)))
(def default-schema (schema/compile test-schema))
;;-------------------------------------------------------------------------------
;; ## Tests
(deftest custom-scalar-query
(let [q "{ now { date }}"]
(is (= {:data {:now {:date "A long time ago"}}}
(execute default-schema q nil nil)))))
(deftest custom-scalars
(testing "custom scalars defined as conformers"
(let [parse-conformer (s/conformer
(fn [x]
(if (and
(string? x)
(< (count x) 3))
x
:clojure.spec.alpha/invalid)))
serialize-conformer (s/conformer
(fn [x]
(case x
"200" "OK"
"500" "ERROR"
:clojure.spec.alpha/invalid)))]
(testing "custom scalar's serializing option"
(let [schema (schema/compile {:scalars
{:Event {:parse parse-conformer
:serialize serialize-conformer}}
:objects
{:galaxy_event
{:fields {:lookup {:type :Event}}}}
:queries
{:events {:type :galaxy_event
:resolve (fn [ctx args v]
{:lookup "200"})}}})
q "{ events { lookup }}"]
(is (= {:data {:events {:lookup "OK"}}} (execute schema q nil nil))
"should return conformed value")))
(testing "custom scalar's invalid value"
(let [schema (schema/compile {:scalars
{:Event {:parse parse-conformer
:serialize serialize-conformer}
:EventId {:parse parse-conformer
:serialize (s/conformer str)}}
:objects
{:galaxy_event
{:fields {:lookup {:type :Event}}}
:human
{:fields {:id {:type :EventId}
:name {:type 'String}}}}
:queries
{:events {:type :galaxy_event
:resolve (fn [ctx args v]
;; type of :lookup is :Event
;; that is a custom scalar with
;; a serialize function that
;; deems anything other than
;; "200" or "500" invalid.
;; So value 1 should cause
;; an error.
{:lookup 1})}
:human {:type '(non-null :human)
:args {:id {:type :EventId}}
:resolve (fn [ctx args v]
{:id "1000"
:name "PI:NAME:<NAME>END_PI"})}}})
q1 "{ human(id: \"1003\") { id, name }}"
q2 "{ events { lookup }}"]
(is (= {:errors [{:argument :id
:field :human
:locations [{:column 0
:line 1}]
:message "Exception applying arguments to field `human': For argument `id', scalar value is not parsable as type `EventId'."
:query-path []
:type-name :EventId
:value "1003"}]}
(execute schema q1 nil nil))
"should return error message")
(is (= {:data {:events {:lookup nil}}
:errors [{:locations [{:column 9
:line 1}]
:message "Invalid value for a scalar type."
:query-path [:events
:lookup]
:type :Event
:value "1"}]}
(execute schema q2 nil nil))
"should return error message"))))))
(deftest custom-scalars-with-variables
(let [date-formatter (SimpleDateFormat. "yyyy-MM-dd")
parse-conformer (s/conformer (fn [input]
(try (.parse date-formatter input)
(catch Exception e
:clojure.spec.alpha/invalid))))
serialize-conformer (s/conformer (fn [output] (.format date-formatter output)))
schema (schema/compile
{:scalars {:Date {:parse parse-conformer
:serialize serialize-conformer}}
:queries {:today {:type :Date
:args {:asOf {:type :Date}}
:resolve (fn [ctx args v] (:asOf args))}}})]
(is (= {:data {:today "2017-04-05"}}
(execute schema "query ($asOf : Date = \"2017-04-05\") {
today (asOf: $asOf)
}"
nil
nil))
"should return parsed and serialized value")
(is (= {:data {:today "2017-04-05"}}
(execute schema "query ($asOf: Date) {
today(asOf: $asOf)
}"
{:asOf "2017-04-05"}
nil))
"should return parsed and serialized value")
(is (= {:errors [{:message "Scalar value is not parsable as type `Date'.",
:value "abc",
:type-name :Date}]}
(execute schema "query ($asOf: Date) {
today(asOf: $asOf)
}"
{:asOf "abc"}
nil))
"should return error message")))
(defn ^:private periodic-seq
[^Date start ^Date end]
(take-while (fn [^Date date]
(not (.isAfter date end)))
(map (fn [i] (.plusDays start i)) (iterate inc 0))))
(defn ^:private sunday? [t]
(= (.getDayOfWeek t) (DateTimeConstants/SUNDAY)))
(defn ^:private sundays [start end]
(let [date-range (if (and start end) (periodic-seq start end) [])]
(filter sunday? date-range)))
(deftest custom-scalars-with-complex-types
(let [date-formatter (DateTimeFormat/forPattern "yyyy-MM-dd")
parse-conformer (s/conformer (fn [input]
(try (DateTime. (.parseDateTime date-formatter input))
(catch Exception e
:clojure.spec/invalid))))
serialize-conformer (s/conformer (fn [output] (.print date-formatter output)))
schema (schema/compile {:scalars {:Date {:parse parse-conformer
:serialize serialize-conformer}}
:queries {:sundays {:type '(list (non-null :Date))
:args {:between {:type '(non-null (list (non-null :Date)))}}
:resolve (fn [ctx args v]
(let [[start end] (:between args)]
(sundays start end)))}}})]
(is (= {:data {:sundays ["2017-03-05" "2017-03-12" "2017-03-19" "2017-03-26"]}}
(execute schema "query ($between: [Date!]!) {
sundays(between: $between)
}"
{:between ["2017-03-05" "2017-03-30"]}
nil))
"should return list of serialized dates")
(is (= {:data {:sundays []}}
(execute schema "query ($between: [Date!]!) {
sundays(between: $between)
}"
{:between ["2017-03-06" "2017-03-07"]}
nil))
"should return empty list")
(is (= {:data {:sundays []}}
(execute schema "query ($between: [Date!]!) {
sundays(between: $between)
}"
{:between []}
nil))
"should return empty list (:between can be an empty list) ")
(is (= {:errors [{:message "No value was provided for variable `between', which is non-nullable.",
:variable-name :between}]}
(execute schema "query ($between: [Date!]!) {
sundays(between: $between)
}"
{:between nil}
nil))
"should return an error")
(is (= {:errors [{:message "Variable `between' contains null members but supplies the value for a list that can't have any null members."
:variable-name :between}]}
(execute schema "query ($between: [Date!]!) {
sundays(between: $between)
}"
{:between [nil]}
nil))
"should return an error")
(is (= {:errors [{:message "Variable `between' contains null members but supplies the value for a list that can't have any null members."
:variable-name :between}]}
(execute schema "query ($between: [Date!]!) {
sundays(between: $between)
}"
{:between ["2017-03-01" nil]}
nil))
"should return an error")
(is (= {:errors [{:message "No value was provided for variable `between', which is non-nullable."
:variable-name :between}]}
(execute schema "query ($between: [Date!]!) {
sundays(between: $between)
}"
nil
nil))
"should return an error"))
(testing "nested lists"
(let [scalars {:CustomType {:parse (s/conformer (fn [x] (name x)))
:serialize (s/conformer (fn [x] (.toUpperCase x)))}}
schema (schema/compile {:scalars scalars
:queries {:shout {:type '(list (list (list :CustomType)))
:args {:words {:type '(list (list (list :CustomType)))}}
:resolve (fn [ctx args v]
(:words args))}}})]
(is (= {:data {:shout [[["FOO" "BAR"]]]}}
(execute schema "query ($words: [[[CustomType]]]) {
shout(words: $words)
}"
{:words [[["foo" "bar"]]]}
nil))
"should return nested list")
(is (= {:errors [{:message "Variable `words' doesn't contain the correct number of (nested) lists.",
:variable-name :words}]}
(execute schema "query ($words: [[[CustomType]]]) {
shout(words: $words)
}"
{:words [["foo" "bar"]]}
nil))
"should return an error")
(is (= {:data {:shout []}}
(execute schema "query ($words: [[[CustomType]]]) {
shout(words: $words)
}"
{:words nil}
nil))
"should return empty list")))
(testing "nested list with a non-null root element in query result"
(let [scalars {:CustomType {:parse (s/conformer (fn [x] (name x)))
:serialize (s/conformer (fn [x] (.toUpperCase x)))}}
schema (schema/compile {:scalars scalars
:queries {:shout {:type '(list (list (list (non-null :CustomType))))
:args {:words {:type '(list (list (list :CustomType)))}}
:resolve (fn [ctx args v]
(:words args))}}})]
(is (= {:data {:shout [[[nil]]]},
:errors [{:message "Non-nullable field was null.",
:locations [{:line 1, :column 33}],
:query-path [:shout],
:arguments {:words '$words}}]}
(execute schema "query ($words: [[[CustomType]]]) {
shout(words: $words)
}"
{:words [[[nil]]]}
nil))
"should return an error")
(is (= {:errors [{:message"Variable `words' doesn't contain the correct number of (nested) lists.",
:variable-name :words}]}
(execute schema "query ($words: [[[CustomType]]]) {
shout(words: $words)
}"
{:words [[nil]]}
nil))
"should return an error")
(is (= {:data {:shout [[["BAR"]]]}}
(execute schema "query ($words: [[[CustomType]]]) {
shout(words: $words)
}"
{:words [[["bar"]]]}
nil))
"should return data")))
(testing "nested list with a non-null root element in query args"
(let [scalars {:CustomType {:parse (s/conformer (fn [x] (name x)))
:serialize (s/conformer (fn [x] (.toUpperCase x)))}}
schema (schema/compile {:scalars scalars
:queries {:shout {:type '(list (list (list :CustomType)))
:args {:words {:type '(list (list (list (non-null :CustomType))))}}
:resolve (fn [ctx args v]
(:words args))}}})]
(is (= {:errors [{:message "Variable `words' contains null members but supplies the value for a list that can't have any null members.",
:variable-name :words}]}
(execute schema "query ($words: [[[CustomType!]]]) {
shout(words: $words)
}"
{:words [[[nil]]]}
nil))
"should return an error")
(is (= {:errors [{:message"Variable `words' doesn't contain the correct number of (nested) lists.",
:variable-name :words}]}
(execute schema "query ($words: [[[CustomType!]]]) {
shout(words: $words)
}"
{:words [["foo"]]}
nil))
"should return an error")
(is (= {:errors [{:message "Exception applying arguments to field `shout': For argument `words', variable and argument are not compatible types.",
:query-path []
:locations [{:line 1 :column 33}]
:field :shout
:argument :words
:argument-type "[[[CustomType!]]]"
:variable-type "[[[CustomType]]]"}]}
(execute schema "query ($words: [[[CustomType]]]) {
shout(words: $words)
}"
{:words [["foo"]]}
nil))
"should return an error")
(is (= {:data {:shout [[["FOO"]]]}}
(execute schema "query ($words: [[[CustomType!]]]) {
shout(words: $words)
}"
{:words [[["foo"]]]}
nil))
"should return an error")))
(testing "nested non-null lists with a root list allowed to contain nulls in query args"
(let [scalars {:CustomType {:parse (s/conformer (fn [x] (if (some? x)
(name x)
:clojure.spec/invalid)))
:serialize (s/conformer (fn [x] (when x (.toUpperCase x))))}}
schema (schema/compile {:scalars scalars
:queries {:shout {:type '(list (list (list :CustomType)))
:args {:words {:type '(non-null (list (non-null (list (non-null (list :CustomType))))))}}
:resolve (fn [ctx args v]
(:words args))}}})]
(is (= {:data {:shout [[[nil]]]}}
(execute schema "query ($words: [[[CustomType]!]!]!) {
shout(words: $words)
}"
{:words [[[nil]]]}
nil))
"should return data")
(is (= {:data {:shout [[["FOO"]]]}}
(execute schema "query ($words: [[[CustomType]!]!]!) {
shout(words: $words)
}"
{:words [[["foo"]]]}
nil))
"should return data")
(is (= {:data {:shout [[[] ["FOO"]]]}}
(execute schema "query ($words: [[[CustomType]!]!]!) {
shout(words: $words)
}"
{:words [[[] ["foo"]]]}
nil))
"should coerece single value to a list of size one"))))
(deftest use-of-coercion-error
(let [schema (-> "custom-scalar-serialize-schema.edn"
io/resource
slurp
edn/read-string
(util/attach-resolvers {:test-query
(fn [_ args _]
(:in args))})
(util/attach-scalar-transformers
{:parse (schema/as-conformer (fn [s]
(if (= "5" s)
(schema/coercion-failure "Just don't like 5.")
(Integer/parseInt s))))
:serialize (schema/as-conformer
(fn [v]
(if (< v 5)
v
(schema/coercion-failure "5 is too big."))))})
schema/compile)]
(testing "parsers"
(is (= {:data {:dupe 4}}
(execute schema
"{ dupe (in:4) }"
nil
nil)))
(is (= {:errors [{:argument :in
:field :dupe
:locations [{:column 0
:line 1}]
:message "Exception applying arguments to field `dupe': For argument `in', just don't like 5."
:query-path []
:type-name :LimitedInt
:value "5"}]}
(execute schema
"{ dupe (in: 5) }"
nil
nil))))
(testing "serializers"
(is (= {:data {:test 4}}
(execute schema
"{ test (in:4) }"
nil
nil)))
(is (= {:data {:test nil}
:errors [{:arguments {:in "5"}
:locations [{:column 0
:line 1}]
:message "5 is too big."
:query-path [:test]}]}
(execute schema
"{ test (in:5) }"
nil
nil))))))
|
[
{
"context": "ssword]}]\n {:grant_type \"password\"\n :username username\n :password password\n :scope \"openid pr",
"end": 176,
"score": 0.9984980821609497,
"start": 168,
"tag": "USERNAME",
"value": "username"
},
{
"context": " \"password\"\n :username username\n :password password\n :scope \"openid profile email federated:id",
"end": 200,
"score": 0.9992746710777283,
"start": 192,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "/sky/issuer/token\")\n {:basic-auth \"fly:Zmx5\"\n :form-params (config->form-params confi",
"end": 403,
"score": 0.4852848947048187,
"start": 402,
"tag": "KEY",
"value": "5"
}
] | src/clj_concourse/auth.clj | JDurstberger/clj-concourse | 0 | (ns clj-concourse.auth
(:require
[clj-http.client :as http]))
(defn config->form-params
[{:keys [username password]}]
{:grant_type "password"
:username username
:password password
:scope "openid profile email federated:id groups"})
(defn create-access-token
[{:keys [url] :as config}]
(-> (http/post
(str url "/sky/issuer/token")
{:basic-auth "fly:Zmx5"
:form-params (config->form-params config)
:as :json-kebab-keys})
(get-in [:body :access-token])))
| 97119 | (ns clj-concourse.auth
(:require
[clj-http.client :as http]))
(defn config->form-params
[{:keys [username password]}]
{:grant_type "password"
:username username
:password <PASSWORD>
:scope "openid profile email federated:id groups"})
(defn create-access-token
[{:keys [url] :as config}]
(-> (http/post
(str url "/sky/issuer/token")
{:basic-auth "fly:Zmx<KEY>"
:form-params (config->form-params config)
:as :json-kebab-keys})
(get-in [:body :access-token])))
| true | (ns clj-concourse.auth
(:require
[clj-http.client :as http]))
(defn config->form-params
[{:keys [username password]}]
{:grant_type "password"
:username username
:password PI:PASSWORD:<PASSWORD>END_PI
:scope "openid profile email federated:id groups"})
(defn create-access-token
[{:keys [url] :as config}]
(-> (http/post
(str url "/sky/issuer/token")
{:basic-auth "fly:ZmxPI:KEY:<KEY>END_PI"
:form-params (config->form-params config)
:as :json-kebab-keys})
(get-in [:body :access-token])))
|
[
{
"context": "ttern01.person-example-ex)\n\n(def p1 {:first-name \"Aaron\" :middle-name \"Jeffrey\" :last-name \"Smith\"})\n(def",
"end": 74,
"score": 0.9997155666351318,
"start": 69,
"tag": "NAME",
"value": "Aaron"
},
{
"context": "e-ex)\n\n(def p1 {:first-name \"Aaron\" :middle-name \"Jeffrey\" :last-name \"Smith\"})\n(def p2 {:first-name \"Aaron",
"end": 97,
"score": 0.9997575283050537,
"start": 90,
"tag": "NAME",
"value": "Jeffrey"
},
{
"context": "t-name \"Aaron\" :middle-name \"Jeffrey\" :last-name \"Smith\"})\n(def p2 {:first-name \"Aaron\" :middle-name \"Bai",
"end": 116,
"score": 0.9997116923332214,
"start": 111,
"tag": "NAME",
"value": "Smith"
},
{
"context": "ffrey\" :last-name \"Smith\"})\n(def p2 {:first-name \"Aaron\" :middle-name \"Bailey\" :last-name \"Zanthar\"})\n(de",
"end": 147,
"score": 0.9996817111968994,
"start": 142,
"tag": "NAME",
"value": "Aaron"
},
{
"context": "ith\"})\n(def p2 {:first-name \"Aaron\" :middle-name \"Bailey\" :last-name \"Zanthar\"})\n(def p3 {:first-name \"Bri",
"end": 169,
"score": 0.9997729063034058,
"start": 163,
"tag": "NAME",
"value": "Bailey"
},
{
"context": "st-name \"Aaron\" :middle-name \"Bailey\" :last-name \"Zanthar\"})\n(def p3 {:first-name \"Brian\" :middle-name \"Ada",
"end": 190,
"score": 0.9997608065605164,
"start": 183,
"tag": "NAME",
"value": "Zanthar"
},
{
"context": "ley\" :last-name \"Zanthar\"})\n(def p3 {:first-name \"Brian\" :middle-name \"Adams\" :last-name \"Smith\"})\n(def p",
"end": 221,
"score": 0.9997332096099854,
"start": 216,
"tag": "NAME",
"value": "Brian"
},
{
"context": "har\"})\n(def p3 {:first-name \"Brian\" :middle-name \"Adams\" :last-name \"Smith\"})\n(def people [p1 p2 p3])\n(de",
"end": 242,
"score": 0.9997602701187134,
"start": 237,
"tag": "NAME",
"value": "Adams"
},
{
"context": "rst-name \"Brian\" :middle-name \"Adams\" :last-name \"Smith\"})\n(def people [p1 p2 p3])\n(defn complicated-sort",
"end": 261,
"score": 0.9997450113296509,
"start": 256,
"tag": "NAME",
"value": "Smith"
}
] | Clojure/src/com/yourtion/Pattern01/person_example_ex.clj | yourtion/LearningFunctionalProgramming | 14 | (ns com.yourtion.Pattern01.person-example-ex)
(def p1 {:first-name "Aaron" :middle-name "Jeffrey" :last-name "Smith"})
(def p2 {:first-name "Aaron" :middle-name "Bailey" :last-name "Zanthar"})
(def p3 {:first-name "Brian" :middle-name "Adams" :last-name "Smith"})
(def people [p1 p2 p3])
(defn complicated-sort [p1 p2]
(let [first-name-compare (compare (p1 :first-name) (p2 :first-name))
middle-name-compare (compare (p1 :middle-name) (p2 :middle-name))
last-name-compare (compare (p1 :last-name) (p2 :last-name))]
(cond
(not (= 0 first-name-compare)) first-name-compare
(not (= 0 last-name-compare)) last-name-compare
:else middle-name-compare)))
(def sorted_people (sort complicated-sort people))
(defn run [] (doseq [col sorted_people :when (not= col nil)]
(println (col :first-name) (col :middle-name) (col :last-name))))
| 18413 | (ns com.yourtion.Pattern01.person-example-ex)
(def p1 {:first-name "<NAME>" :middle-name "<NAME>" :last-name "<NAME>"})
(def p2 {:first-name "<NAME>" :middle-name "<NAME>" :last-name "<NAME>"})
(def p3 {:first-name "<NAME>" :middle-name "<NAME>" :last-name "<NAME>"})
(def people [p1 p2 p3])
(defn complicated-sort [p1 p2]
(let [first-name-compare (compare (p1 :first-name) (p2 :first-name))
middle-name-compare (compare (p1 :middle-name) (p2 :middle-name))
last-name-compare (compare (p1 :last-name) (p2 :last-name))]
(cond
(not (= 0 first-name-compare)) first-name-compare
(not (= 0 last-name-compare)) last-name-compare
:else middle-name-compare)))
(def sorted_people (sort complicated-sort people))
(defn run [] (doseq [col sorted_people :when (not= col nil)]
(println (col :first-name) (col :middle-name) (col :last-name))))
| true | (ns com.yourtion.Pattern01.person-example-ex)
(def p1 {:first-name "PI:NAME:<NAME>END_PI" :middle-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"})
(def p2 {:first-name "PI:NAME:<NAME>END_PI" :middle-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"})
(def p3 {:first-name "PI:NAME:<NAME>END_PI" :middle-name "PI:NAME:<NAME>END_PI" :last-name "PI:NAME:<NAME>END_PI"})
(def people [p1 p2 p3])
(defn complicated-sort [p1 p2]
(let [first-name-compare (compare (p1 :first-name) (p2 :first-name))
middle-name-compare (compare (p1 :middle-name) (p2 :middle-name))
last-name-compare (compare (p1 :last-name) (p2 :last-name))]
(cond
(not (= 0 first-name-compare)) first-name-compare
(not (= 0 last-name-compare)) last-name-compare
:else middle-name-compare)))
(def sorted_people (sort complicated-sort people))
(defn run [] (doseq [col sorted_people :when (not= col nil)]
(println (col :first-name) (col :middle-name) (col :last-name))))
|
[
{
"context": "\n\n;(expect 9 (count movie-collection))\n\n;(expect \"Ben Affleck\" (:director (get-movie-object \"Argo\")))\n\n;(expect",
"end": 530,
"score": 0.9998724460601807,
"start": 519,
"tag": "NAME",
"value": "Ben Affleck"
},
{
"context": "###\n\n;(expect (helper-movie-object-has-director? \"Steve McQueen\" (get-movie-object\n; ",
"end": 3141,
"score": 0.9998339414596558,
"start": 3128,
"tag": "NAME",
"value": "Steve McQueen"
},
{
"context": "ode.\n;(expect (helper-movie-object-has-director? \"Steve McQueen\") (get-movie-object\n; ",
"end": 3401,
"score": 0.9997898936271667,
"start": 3388,
"tag": "NAME",
"value": "Steve McQueen"
},
{
"context": "a Slave\"))\n\n;(expect (movie-object-has-director? \"Steve McQueen\") (get-movie-object\n; ",
"end": 3557,
"score": 0.9996753334999084,
"start": 3544,
"tag": "NAME",
"value": "Steve McQueen"
},
{
"context": "ct Exception ((helper-movie-object-has-director? \"Steve McQueen\")\n; (get-movie-object \"12 Years",
"end": 4068,
"score": 0.9996383786201477,
"start": 4055,
"tag": "NAME",
"value": "Steve McQueen"
},
{
"context": "ore-> \"The Hunger Games\" :title\n; \"Gary Ross\" :director\n; 2012 :year\n; ",
"end": 5123,
"score": 0.9998345375061035,
"start": 5114,
"tag": "NAME",
"value": "Gary Ross"
},
{
"context": "ore-> :title \"The Hunger Games\"\n; \"Gary Ross\" :director\n; 2012 :year\n; ",
"end": 5682,
"score": 0.999846339225769,
"start": 5673,
"tag": "NAME",
"value": "Gary Ross"
},
{
"context": "edicate of x\n; #(= (:director %) \"Gary Ross\") x\n; #(= (:year %) 2012) x\n; ",
"end": 6784,
"score": 0.9998393058776855,
"start": 6775,
"tag": "NAME",
"value": "Gary Ross"
}
] | test-project/test/test_project/core_test.clj | emma-sax4/Introduction-to-LightTable | 0 | (ns test-project.core-test
(:require [expectations :refer :all]
[test-project.core :refer :all]))
;##################################################################################
;; You can use Expectations to check that two things are equal using this form: ###
;; (expect expected actual). ###
;##################################################################################
;(expect 5 (+ 2 3))
;(expect 9 (count movie-collection))
;(expect "Ben Affleck" (:director (get-movie-object "Argo")))
;(expect "R" (:rating (get-movie-object "The Prestige")))
;; This will fail
;(expect 1752 (:year (get-movie-object "The Ring")))
;#########################################################################
;; These tests use regular expressions to search for parts of strings. ###
;#########################################################################
;(expect #"van" "nirvana")
;(expect #"Juliet" (:title (get-movie-object "Romeo and Juliet")))
;(expect #"(.*) Years a Slave" (:title (get-movie-object "12 Years a Slave")))
;; This will fail
;(expect #"(.+) Obama" (:director (get-movie-object "Frozen")))
;######################################################################
;; We can use Expectations to see if an element is in a collection. ###
;######################################################################
;(expect 5 (in #{1 3 5 7}))
;(expect {:genre "Drama"} (in (get-movie-object "12 Years a Slave")))
;(expect {:year 2012} (in (get-movie-object "The Hunger Games")))
;; This will fail
;(expect {:year 1776} (in (get-movie-object "The Prestige")))
;###########################################################################
;; You can also use Expectations using a predicate as the first argument ###
;; and something else as the second argument. ###
;; A predicate is a function that returns true or false. ###
;###########################################################################
;(expect number? 2093)
;(expect true? (number? 4))
;(expect zero? 0)
;(expect char? \h)
;(expect list? '(:this :is :an :example))
;(expect number? (:year (first movie-collection)))
;(expect not-string? (:year (get-movie-object "Frozen")))
;; This will fail
;(expect number? (:genre (get-movie-object "The Big Lebowski")))
;###########################################################################
;; Above, a predicate is used as the first argument, but we could write ###
;; the same test by clarifying whether we expect true or false, and then ###
;; calling the predicate explicitly in the second argument. ###
;###########################################################################
;(expect true (number? (:year (first movie-collection))))
;(expect true (not-string? (:year (get-movie-object "Frozen"))))
;(expect false (number? (:director (get-movie-object "Frozen"))))
;###########################################
;; Example of how partial would be used: ###
;###########################################
;(expect (helper-movie-object-has-director? "Steve McQueen" (get-movie-object
; "12 Years a Slave")))
;; This will throw an error
;; The error is caused by a problem in the test syntax, not the code.
;(expect (helper-movie-object-has-director? "Steve McQueen") (get-movie-object
; "12 Years a Slave"))
;(expect (movie-object-has-director? "Steve McQueen") (get-movie-object
; "12 Years a Slave"))
;#########################################################################
;; If you are expecting a piece of code to throw an exception, you can ###
;; test for it like this: ###
;#########################################################################
;(expect ClassCastException (+ :one :two))
;(expect Exception ((helper-movie-object-has-director? "Steve McQueen")
; (get-movie-object "12 Years a Slave")))
;#################################################################################
;; More is a macro and can be used to combine multiple checks into one assert. ###
;#################################################################################
;(expect (more vector? not-empty) movie-collection)
;(expect (more vector? not-empty #(= 9 (count %))) movie-collection)
;; This will fail
;(expect (more set? not-empty #(= 9 (count %))) movie-collection)
;##############################################################################
;; However, when you want to check things that take more than one argument, ###
;; you can use more->. ###
;##############################################################################
;(expect (more-> (get-movie-object "The Ring") first
; (get-movie-object "The Big Lebowski") last)
; movie-collection)
;(expect (more-> "The Hunger Games" :title
; "Gary Ross" :director
; 2012 :year
; "Adventure" :genre
; 142 :length
; "PG-13" :rating)
; (get-movie-object "The Hunger Games"))
;##################################################################
;; However, you must be careful because order is very specific. ###
;; Here, we've just switched :title and "The Hunger Games". ###
;##################################################################
;; This will throw an error
;(expect (more-> :title "The Hunger Games"
; "Gary Ross" :director
; 2012 :year
; "Adventure" :genre
; 142 :length
; "PG-13" :rating)
; (get-movie-object "The Hunger Games"))
;#############################################################################
;; If you'd like to give a name to the object you're testing, then more-of ###
;; should be used: ###
;#############################################################################
;(expect (more-of x
; vector? x
; not-empty x)
; movie-collection)
;(expect (more-of x
; vector? x
; not-empty x
; #(= 9 (count %)) x)
; movie-collection)
;#################################################################
;; More-of is especially nice when your x is more complicated: ###
;#################################################################
;(expect (more-of x
; #(= (:title %) "The Hunger Games") x ;can do predicate of x
; #(= (:director %) "Gary Ross") x
; #(= (:year %) 2012) x
; "Adventure" (:genre x) ;or can check that two things are equal
; 142 (:length x)
; "PG-13" (:rating x))
; (get-movie-object "The Hunger Games"))
;###########################################################################
;; Using from-each, we can loop over the elements of some collection and ###
;; check that all of the elements pass an assertion: ###
;###########################################################################
;(expect map?
; (from-each [movie-object movie-collection]
; movie-object))
;###########################################################################
;; From-each can be combined with :when and :let to narrow down what you ###
;; want to examine: ###
;###########################################################################
;(expect even? (from-each [val (vals (get-movie-object "Argo"))
; :when (number? val)]
; val))
;(expect odd? (from-each [val (vals (get-movie-object "Argo"))
; :when (number? val)
; :let [val-increment (inc val)]]
; val-increment))
;##################################################################################
;; This below test is the same thing as above, but just with the :when removed. ###
;##################################################################################
;; This will throw an error
;(expect odd? (from-each [val (vals (get-movie-object "Argo"))
; :let [val-increment (inc val)]]
; val-increment))
;##############################################################################
;; Using a variety of more, more->, more-of, and from-each, you can combine ###
;; parts together to create more elaborate tests: ###
;##############################################################################
;(expect (more map? #(= 6 (count %)))
; (from-each [movie-object movie-collection]
; movie-object))
;################################################################################
;; Expect-focused is a way to ensure that only those tests (the ones declared ###
;; with expect-focused) are ran. All others are ignored. ###
;################################################################################
;(expect-focused 9 (count movie-collection))
| 9951 | (ns test-project.core-test
(:require [expectations :refer :all]
[test-project.core :refer :all]))
;##################################################################################
;; You can use Expectations to check that two things are equal using this form: ###
;; (expect expected actual). ###
;##################################################################################
;(expect 5 (+ 2 3))
;(expect 9 (count movie-collection))
;(expect "<NAME>" (:director (get-movie-object "Argo")))
;(expect "R" (:rating (get-movie-object "The Prestige")))
;; This will fail
;(expect 1752 (:year (get-movie-object "The Ring")))
;#########################################################################
;; These tests use regular expressions to search for parts of strings. ###
;#########################################################################
;(expect #"van" "nirvana")
;(expect #"Juliet" (:title (get-movie-object "Romeo and Juliet")))
;(expect #"(.*) Years a Slave" (:title (get-movie-object "12 Years a Slave")))
;; This will fail
;(expect #"(.+) Obama" (:director (get-movie-object "Frozen")))
;######################################################################
;; We can use Expectations to see if an element is in a collection. ###
;######################################################################
;(expect 5 (in #{1 3 5 7}))
;(expect {:genre "Drama"} (in (get-movie-object "12 Years a Slave")))
;(expect {:year 2012} (in (get-movie-object "The Hunger Games")))
;; This will fail
;(expect {:year 1776} (in (get-movie-object "The Prestige")))
;###########################################################################
;; You can also use Expectations using a predicate as the first argument ###
;; and something else as the second argument. ###
;; A predicate is a function that returns true or false. ###
;###########################################################################
;(expect number? 2093)
;(expect true? (number? 4))
;(expect zero? 0)
;(expect char? \h)
;(expect list? '(:this :is :an :example))
;(expect number? (:year (first movie-collection)))
;(expect not-string? (:year (get-movie-object "Frozen")))
;; This will fail
;(expect number? (:genre (get-movie-object "The Big Lebowski")))
;###########################################################################
;; Above, a predicate is used as the first argument, but we could write ###
;; the same test by clarifying whether we expect true or false, and then ###
;; calling the predicate explicitly in the second argument. ###
;###########################################################################
;(expect true (number? (:year (first movie-collection))))
;(expect true (not-string? (:year (get-movie-object "Frozen"))))
;(expect false (number? (:director (get-movie-object "Frozen"))))
;###########################################
;; Example of how partial would be used: ###
;###########################################
;(expect (helper-movie-object-has-director? "<NAME>" (get-movie-object
; "12 Years a Slave")))
;; This will throw an error
;; The error is caused by a problem in the test syntax, not the code.
;(expect (helper-movie-object-has-director? "<NAME>") (get-movie-object
; "12 Years a Slave"))
;(expect (movie-object-has-director? "<NAME>") (get-movie-object
; "12 Years a Slave"))
;#########################################################################
;; If you are expecting a piece of code to throw an exception, you can ###
;; test for it like this: ###
;#########################################################################
;(expect ClassCastException (+ :one :two))
;(expect Exception ((helper-movie-object-has-director? "<NAME>")
; (get-movie-object "12 Years a Slave")))
;#################################################################################
;; More is a macro and can be used to combine multiple checks into one assert. ###
;#################################################################################
;(expect (more vector? not-empty) movie-collection)
;(expect (more vector? not-empty #(= 9 (count %))) movie-collection)
;; This will fail
;(expect (more set? not-empty #(= 9 (count %))) movie-collection)
;##############################################################################
;; However, when you want to check things that take more than one argument, ###
;; you can use more->. ###
;##############################################################################
;(expect (more-> (get-movie-object "The Ring") first
; (get-movie-object "The Big Lebowski") last)
; movie-collection)
;(expect (more-> "The Hunger Games" :title
; "<NAME>" :director
; 2012 :year
; "Adventure" :genre
; 142 :length
; "PG-13" :rating)
; (get-movie-object "The Hunger Games"))
;##################################################################
;; However, you must be careful because order is very specific. ###
;; Here, we've just switched :title and "The Hunger Games". ###
;##################################################################
;; This will throw an error
;(expect (more-> :title "The Hunger Games"
; "<NAME>" :director
; 2012 :year
; "Adventure" :genre
; 142 :length
; "PG-13" :rating)
; (get-movie-object "The Hunger Games"))
;#############################################################################
;; If you'd like to give a name to the object you're testing, then more-of ###
;; should be used: ###
;#############################################################################
;(expect (more-of x
; vector? x
; not-empty x)
; movie-collection)
;(expect (more-of x
; vector? x
; not-empty x
; #(= 9 (count %)) x)
; movie-collection)
;#################################################################
;; More-of is especially nice when your x is more complicated: ###
;#################################################################
;(expect (more-of x
; #(= (:title %) "The Hunger Games") x ;can do predicate of x
; #(= (:director %) "<NAME>") x
; #(= (:year %) 2012) x
; "Adventure" (:genre x) ;or can check that two things are equal
; 142 (:length x)
; "PG-13" (:rating x))
; (get-movie-object "The Hunger Games"))
;###########################################################################
;; Using from-each, we can loop over the elements of some collection and ###
;; check that all of the elements pass an assertion: ###
;###########################################################################
;(expect map?
; (from-each [movie-object movie-collection]
; movie-object))
;###########################################################################
;; From-each can be combined with :when and :let to narrow down what you ###
;; want to examine: ###
;###########################################################################
;(expect even? (from-each [val (vals (get-movie-object "Argo"))
; :when (number? val)]
; val))
;(expect odd? (from-each [val (vals (get-movie-object "Argo"))
; :when (number? val)
; :let [val-increment (inc val)]]
; val-increment))
;##################################################################################
;; This below test is the same thing as above, but just with the :when removed. ###
;##################################################################################
;; This will throw an error
;(expect odd? (from-each [val (vals (get-movie-object "Argo"))
; :let [val-increment (inc val)]]
; val-increment))
;##############################################################################
;; Using a variety of more, more->, more-of, and from-each, you can combine ###
;; parts together to create more elaborate tests: ###
;##############################################################################
;(expect (more map? #(= 6 (count %)))
; (from-each [movie-object movie-collection]
; movie-object))
;################################################################################
;; Expect-focused is a way to ensure that only those tests (the ones declared ###
;; with expect-focused) are ran. All others are ignored. ###
;################################################################################
;(expect-focused 9 (count movie-collection))
| true | (ns test-project.core-test
(:require [expectations :refer :all]
[test-project.core :refer :all]))
;##################################################################################
;; You can use Expectations to check that two things are equal using this form: ###
;; (expect expected actual). ###
;##################################################################################
;(expect 5 (+ 2 3))
;(expect 9 (count movie-collection))
;(expect "PI:NAME:<NAME>END_PI" (:director (get-movie-object "Argo")))
;(expect "R" (:rating (get-movie-object "The Prestige")))
;; This will fail
;(expect 1752 (:year (get-movie-object "The Ring")))
;#########################################################################
;; These tests use regular expressions to search for parts of strings. ###
;#########################################################################
;(expect #"van" "nirvana")
;(expect #"Juliet" (:title (get-movie-object "Romeo and Juliet")))
;(expect #"(.*) Years a Slave" (:title (get-movie-object "12 Years a Slave")))
;; This will fail
;(expect #"(.+) Obama" (:director (get-movie-object "Frozen")))
;######################################################################
;; We can use Expectations to see if an element is in a collection. ###
;######################################################################
;(expect 5 (in #{1 3 5 7}))
;(expect {:genre "Drama"} (in (get-movie-object "12 Years a Slave")))
;(expect {:year 2012} (in (get-movie-object "The Hunger Games")))
;; This will fail
;(expect {:year 1776} (in (get-movie-object "The Prestige")))
;###########################################################################
;; You can also use Expectations using a predicate as the first argument ###
;; and something else as the second argument. ###
;; A predicate is a function that returns true or false. ###
;###########################################################################
;(expect number? 2093)
;(expect true? (number? 4))
;(expect zero? 0)
;(expect char? \h)
;(expect list? '(:this :is :an :example))
;(expect number? (:year (first movie-collection)))
;(expect not-string? (:year (get-movie-object "Frozen")))
;; This will fail
;(expect number? (:genre (get-movie-object "The Big Lebowski")))
;###########################################################################
;; Above, a predicate is used as the first argument, but we could write ###
;; the same test by clarifying whether we expect true or false, and then ###
;; calling the predicate explicitly in the second argument. ###
;###########################################################################
;(expect true (number? (:year (first movie-collection))))
;(expect true (not-string? (:year (get-movie-object "Frozen"))))
;(expect false (number? (:director (get-movie-object "Frozen"))))
;###########################################
;; Example of how partial would be used: ###
;###########################################
;(expect (helper-movie-object-has-director? "PI:NAME:<NAME>END_PI" (get-movie-object
; "12 Years a Slave")))
;; This will throw an error
;; The error is caused by a problem in the test syntax, not the code.
;(expect (helper-movie-object-has-director? "PI:NAME:<NAME>END_PI") (get-movie-object
; "12 Years a Slave"))
;(expect (movie-object-has-director? "PI:NAME:<NAME>END_PI") (get-movie-object
; "12 Years a Slave"))
;#########################################################################
;; If you are expecting a piece of code to throw an exception, you can ###
;; test for it like this: ###
;#########################################################################
;(expect ClassCastException (+ :one :two))
;(expect Exception ((helper-movie-object-has-director? "PI:NAME:<NAME>END_PI")
; (get-movie-object "12 Years a Slave")))
;#################################################################################
;; More is a macro and can be used to combine multiple checks into one assert. ###
;#################################################################################
;(expect (more vector? not-empty) movie-collection)
;(expect (more vector? not-empty #(= 9 (count %))) movie-collection)
;; This will fail
;(expect (more set? not-empty #(= 9 (count %))) movie-collection)
;##############################################################################
;; However, when you want to check things that take more than one argument, ###
;; you can use more->. ###
;##############################################################################
;(expect (more-> (get-movie-object "The Ring") first
; (get-movie-object "The Big Lebowski") last)
; movie-collection)
;(expect (more-> "The Hunger Games" :title
; "PI:NAME:<NAME>END_PI" :director
; 2012 :year
; "Adventure" :genre
; 142 :length
; "PG-13" :rating)
; (get-movie-object "The Hunger Games"))
;##################################################################
;; However, you must be careful because order is very specific. ###
;; Here, we've just switched :title and "The Hunger Games". ###
;##################################################################
;; This will throw an error
;(expect (more-> :title "The Hunger Games"
; "PI:NAME:<NAME>END_PI" :director
; 2012 :year
; "Adventure" :genre
; 142 :length
; "PG-13" :rating)
; (get-movie-object "The Hunger Games"))
;#############################################################################
;; If you'd like to give a name to the object you're testing, then more-of ###
;; should be used: ###
;#############################################################################
;(expect (more-of x
; vector? x
; not-empty x)
; movie-collection)
;(expect (more-of x
; vector? x
; not-empty x
; #(= 9 (count %)) x)
; movie-collection)
;#################################################################
;; More-of is especially nice when your x is more complicated: ###
;#################################################################
;(expect (more-of x
; #(= (:title %) "The Hunger Games") x ;can do predicate of x
; #(= (:director %) "PI:NAME:<NAME>END_PI") x
; #(= (:year %) 2012) x
; "Adventure" (:genre x) ;or can check that two things are equal
; 142 (:length x)
; "PG-13" (:rating x))
; (get-movie-object "The Hunger Games"))
;###########################################################################
;; Using from-each, we can loop over the elements of some collection and ###
;; check that all of the elements pass an assertion: ###
;###########################################################################
;(expect map?
; (from-each [movie-object movie-collection]
; movie-object))
;###########################################################################
;; From-each can be combined with :when and :let to narrow down what you ###
;; want to examine: ###
;###########################################################################
;(expect even? (from-each [val (vals (get-movie-object "Argo"))
; :when (number? val)]
; val))
;(expect odd? (from-each [val (vals (get-movie-object "Argo"))
; :when (number? val)
; :let [val-increment (inc val)]]
; val-increment))
;##################################################################################
;; This below test is the same thing as above, but just with the :when removed. ###
;##################################################################################
;; This will throw an error
;(expect odd? (from-each [val (vals (get-movie-object "Argo"))
; :let [val-increment (inc val)]]
; val-increment))
;##############################################################################
;; Using a variety of more, more->, more-of, and from-each, you can combine ###
;; parts together to create more elaborate tests: ###
;##############################################################################
;(expect (more map? #(= 6 (count %)))
; (from-each [movie-object movie-collection]
; movie-object))
;################################################################################
;; Expect-focused is a way to ensure that only those tests (the ones declared ###
;; with expect-focused) are ran. All others are ignored. ###
;################################################################################
;(expect-focused 9 (count movie-collection))
|
[
{
"context": " (-> (migrate-system {:db (assoc-if {} :username username :password password :database-name database)})\n ",
"end": 1593,
"score": 0.6612657308578491,
"start": 1585,
"tag": "USERNAME",
"value": "username"
},
{
"context": "tem {:db (assoc-if {} :username username :password password :database-name database)})\n component/st",
"end": 1612,
"score": 0.9740931987762451,
"start": 1604,
"tag": "PASSWORD",
"value": "password"
}
] | src/template/system.clj | dahlie/compojure-project-template | 0 | (ns template.system
(:require [com.stuartsierra.component :as component :refer [using]]
[taoensso.timbre :as timbre]
[potpuri.core :refer [assoc-if]]
[template.components.http-kit :refer [start-http-kit]]
[template.components.env :refer [create-env]]
[template.components.handler :refer [create-handler]]
[template.components.postgres :refer [connect-postgres]]
[template.components.flyway :refer [check-flyway]]
[template.env :as env]
[template.migrate.cli :as mcli]
[template.migrate :refer [migrate!]]))
(def schemas ["template"])
(defn base-system [& [config]]
(component/system-map
:env (create-env env/prefix (or config {}))
:db (using (connect-postgres) [:env])
:flyway-status (using (check-flyway {:schemas schemas}) [:db])
:handler (using (create-handler 'template.api/app) [:env])
:http-server (using (start-http-kit) [:handler :env])))
; Used when migrations are run from CLI
(defn migrate-system [& [config]]
(component/system-map
:env (create-env env/prefix (or config {}))))
(defn migrate [system & [m]]
(migrate! system (assoc m :schemas schemas)))
; ------------------------------
; Main stuf
(defn start-base-system [& [opts]]
(timbre/info "starting system")
(component/start (base-system opts)))
(defn migrate-main [args]
(mcli/main
args
(fn [{:keys [clean target-version username password database] :as opts}]
(-> (migrate-system {:db (assoc-if {} :username username :password password :database-name database)})
component/start
(migrate (select-keys opts [:clean :target-version]))
component/stop))))
| 65918 | (ns template.system
(:require [com.stuartsierra.component :as component :refer [using]]
[taoensso.timbre :as timbre]
[potpuri.core :refer [assoc-if]]
[template.components.http-kit :refer [start-http-kit]]
[template.components.env :refer [create-env]]
[template.components.handler :refer [create-handler]]
[template.components.postgres :refer [connect-postgres]]
[template.components.flyway :refer [check-flyway]]
[template.env :as env]
[template.migrate.cli :as mcli]
[template.migrate :refer [migrate!]]))
(def schemas ["template"])
(defn base-system [& [config]]
(component/system-map
:env (create-env env/prefix (or config {}))
:db (using (connect-postgres) [:env])
:flyway-status (using (check-flyway {:schemas schemas}) [:db])
:handler (using (create-handler 'template.api/app) [:env])
:http-server (using (start-http-kit) [:handler :env])))
; Used when migrations are run from CLI
(defn migrate-system [& [config]]
(component/system-map
:env (create-env env/prefix (or config {}))))
(defn migrate [system & [m]]
(migrate! system (assoc m :schemas schemas)))
; ------------------------------
; Main stuf
(defn start-base-system [& [opts]]
(timbre/info "starting system")
(component/start (base-system opts)))
(defn migrate-main [args]
(mcli/main
args
(fn [{:keys [clean target-version username password database] :as opts}]
(-> (migrate-system {:db (assoc-if {} :username username :password <PASSWORD> :database-name database)})
component/start
(migrate (select-keys opts [:clean :target-version]))
component/stop))))
| true | (ns template.system
(:require [com.stuartsierra.component :as component :refer [using]]
[taoensso.timbre :as timbre]
[potpuri.core :refer [assoc-if]]
[template.components.http-kit :refer [start-http-kit]]
[template.components.env :refer [create-env]]
[template.components.handler :refer [create-handler]]
[template.components.postgres :refer [connect-postgres]]
[template.components.flyway :refer [check-flyway]]
[template.env :as env]
[template.migrate.cli :as mcli]
[template.migrate :refer [migrate!]]))
(def schemas ["template"])
(defn base-system [& [config]]
(component/system-map
:env (create-env env/prefix (or config {}))
:db (using (connect-postgres) [:env])
:flyway-status (using (check-flyway {:schemas schemas}) [:db])
:handler (using (create-handler 'template.api/app) [:env])
:http-server (using (start-http-kit) [:handler :env])))
; Used when migrations are run from CLI
(defn migrate-system [& [config]]
(component/system-map
:env (create-env env/prefix (or config {}))))
(defn migrate [system & [m]]
(migrate! system (assoc m :schemas schemas)))
; ------------------------------
; Main stuf
(defn start-base-system [& [opts]]
(timbre/info "starting system")
(component/start (base-system opts)))
(defn migrate-main [args]
(mcli/main
args
(fn [{:keys [clean target-version username password database] :as opts}]
(-> (migrate-system {:db (assoc-if {} :username username :password PI:PASSWORD:<PASSWORD>END_PI :database-name database)})
component/start
(migrate (select-keys opts [:clean :target-version]))
component/stop))))
|
[
{
"context": "; Copyright (c) Rich Hickey. All rights reserved.\r\n; The use and distributi",
"end": 30,
"score": 0.9997777938842773,
"start": 19,
"tag": "NAME",
"value": "Rich Hickey"
}
] | Source/clojure/uuid.clj | pjago/Arcadia | 0 | ; Copyright (c) Rich Hickey. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns clojure.uuid)
(defn- default-uuid-reader [form]
{:pre [(string? form)]}
(System.Guid. form)) ;;; (java.util.UUID/fromString form)
(defmethod print-method System.Guid [uuid ^System.IO.TextWriter w] ;;; java.util.UUID ^java.io.Writer
(.Write w (str "#uuid \"" (str uuid) "\""))) ;;; .write
(defmethod print-dup System.Guid [o w] ;;; java.util.UUID
(print-method o w)) | 97918 | ; Copyright (c) <NAME>. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns clojure.uuid)
(defn- default-uuid-reader [form]
{:pre [(string? form)]}
(System.Guid. form)) ;;; (java.util.UUID/fromString form)
(defmethod print-method System.Guid [uuid ^System.IO.TextWriter w] ;;; java.util.UUID ^java.io.Writer
(.Write w (str "#uuid \"" (str uuid) "\""))) ;;; .write
(defmethod print-dup System.Guid [o w] ;;; java.util.UUID
(print-method o w)) | true | ; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns clojure.uuid)
(defn- default-uuid-reader [form]
{:pre [(string? form)]}
(System.Guid. form)) ;;; (java.util.UUID/fromString form)
(defmethod print-method System.Guid [uuid ^System.IO.TextWriter w] ;;; java.util.UUID ^java.io.Writer
(.Write w (str "#uuid \"" (str uuid) "\""))) ;;; .write
(defmethod print-dup System.Guid [o w] ;;; java.util.UUID
(print-method o w)) |
[
{
"context": ".\n :user \"sysdba\"\n :password \"tiger\"})\n\n\t(with-connection db\n\t\t(with-query-results rs",
"end": 766,
"score": 0.9989653825759888,
"start": 761,
"tag": "PASSWORD",
"value": "tiger"
}
] | firebird/clojure/read/firebird_read.clj | ekzemplaro/data_base_language | 3 | ; -----------------------------------------------------------------
;
; firebird_read.clj
;
; Feb/17/2011
;
; -----------------------------------------------------------------
(load-file "/var/www/data_base/common/clojure_common/sql_manipulate.clj")
; -----------------------------------------------------------------
(use 'clojure.contrib.sql)
(println "*** 開始 ***")
(let [db-host "localhost"
db-name "/var/tmp/firebird/cities.fdb"]
(def db {:classname "org.firebirdsql.jdbc.FBDriver" ; must be in classpath
:subprotocol "firebirdsql"
:subname (str "" db-host ":" db-name)
; Any additional keys are passed to the driver
; as driver-specific properties.
:user "sysdba"
:password "tiger"})
(with-connection db
(with-query-results rs ["select * from cities"]
(display_proc rs)
)))
(println "*** 終了 ***")
;; (dorun (map #(println (:language :iso_code %)) rs)))))
; -----------------------------------------------------------------
| 6509 | ; -----------------------------------------------------------------
;
; firebird_read.clj
;
; Feb/17/2011
;
; -----------------------------------------------------------------
(load-file "/var/www/data_base/common/clojure_common/sql_manipulate.clj")
; -----------------------------------------------------------------
(use 'clojure.contrib.sql)
(println "*** 開始 ***")
(let [db-host "localhost"
db-name "/var/tmp/firebird/cities.fdb"]
(def db {:classname "org.firebirdsql.jdbc.FBDriver" ; must be in classpath
:subprotocol "firebirdsql"
:subname (str "" db-host ":" db-name)
; Any additional keys are passed to the driver
; as driver-specific properties.
:user "sysdba"
:password "<PASSWORD>"})
(with-connection db
(with-query-results rs ["select * from cities"]
(display_proc rs)
)))
(println "*** 終了 ***")
;; (dorun (map #(println (:language :iso_code %)) rs)))))
; -----------------------------------------------------------------
| true | ; -----------------------------------------------------------------
;
; firebird_read.clj
;
; Feb/17/2011
;
; -----------------------------------------------------------------
(load-file "/var/www/data_base/common/clojure_common/sql_manipulate.clj")
; -----------------------------------------------------------------
(use 'clojure.contrib.sql)
(println "*** 開始 ***")
(let [db-host "localhost"
db-name "/var/tmp/firebird/cities.fdb"]
(def db {:classname "org.firebirdsql.jdbc.FBDriver" ; must be in classpath
:subprotocol "firebirdsql"
:subname (str "" db-host ":" db-name)
; Any additional keys are passed to the driver
; as driver-specific properties.
:user "sysdba"
:password "PI:PASSWORD:<PASSWORD>END_PI"})
(with-connection db
(with-query-results rs ["select * from cities"]
(display_proc rs)
)))
(println "*** 終了 ***")
;; (dorun (map #(println (:language :iso_code %)) rs)))))
; -----------------------------------------------------------------
|
[
{
"context": ";; Copyright 2021 Zane Littrell\n;;\n;; Licensed under the Apache License, Version ",
"end": 31,
"score": 0.9998735785484314,
"start": 18,
"tag": "NAME",
"value": "Zane Littrell"
}
] | src/app/stats.cljc | CapitalistLepton/nomenclature | 0 | ;; Copyright 2021 Zane Littrell
;;
;; 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 app.stats
(:require [app.lib :as lib]))
; NOTE: This file is strictly for observing the property of names
; Any code in this file should not be referenced by any other file
(def strong-letters
[:1
:3
:5
:7
:8
:9
:B])
(def weak-letters
[:0
:2
:4
:6
:A])
(def all-names
(apply concat
(mapcat concat
(for [i (range 12)]
(for [j (range 12)]
(for [k (range 12)]
[(nth lib/letters i)
(nth lib/letters j)
(nth lib/letters k)]))))))
(def weak-names
(apply concat
(mapcat concat
(for [i (range (count weak-letters))]
(for [j (range (count weak-letters))]
(for [k (range (count weak-letters))]
[(nth weak-letters i)
(nth weak-letters j)
(nth weak-letters k)]))))))
(def sorted-power (sort-by (fn [x]
(+ (first x) (second x)))
(map (fn [name]
(list (lib/strength name) (lib/health name) name))
all-names)))
(def sorted-weak (sort-by (fn [x]
(+ (first x) (second x)))
(map (fn [name]
(list (lib/strength name) (lib/health name) name))
weak-names)))
(take-last 12 sorted-weak)
(count (filter (fn [x]
(and (>= (+ (first x) (second x)) 10)
(or (>= (first x) 5)
(>= (second x) 5))))
sorted-power))
(filter (fn [x]
(= (+ (first x) (second x)) 18))
sorted-power)
| 121513 | ;; Copyright 2021 <NAME>
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns app.stats
(:require [app.lib :as lib]))
; NOTE: This file is strictly for observing the property of names
; Any code in this file should not be referenced by any other file
(def strong-letters
[:1
:3
:5
:7
:8
:9
:B])
(def weak-letters
[:0
:2
:4
:6
:A])
(def all-names
(apply concat
(mapcat concat
(for [i (range 12)]
(for [j (range 12)]
(for [k (range 12)]
[(nth lib/letters i)
(nth lib/letters j)
(nth lib/letters k)]))))))
(def weak-names
(apply concat
(mapcat concat
(for [i (range (count weak-letters))]
(for [j (range (count weak-letters))]
(for [k (range (count weak-letters))]
[(nth weak-letters i)
(nth weak-letters j)
(nth weak-letters k)]))))))
(def sorted-power (sort-by (fn [x]
(+ (first x) (second x)))
(map (fn [name]
(list (lib/strength name) (lib/health name) name))
all-names)))
(def sorted-weak (sort-by (fn [x]
(+ (first x) (second x)))
(map (fn [name]
(list (lib/strength name) (lib/health name) name))
weak-names)))
(take-last 12 sorted-weak)
(count (filter (fn [x]
(and (>= (+ (first x) (second x)) 10)
(or (>= (first x) 5)
(>= (second x) 5))))
sorted-power))
(filter (fn [x]
(= (+ (first x) (second x)) 18))
sorted-power)
| true | ;; Copyright 2021 PI:NAME:<NAME>END_PI
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns app.stats
(:require [app.lib :as lib]))
; NOTE: This file is strictly for observing the property of names
; Any code in this file should not be referenced by any other file
(def strong-letters
[:1
:3
:5
:7
:8
:9
:B])
(def weak-letters
[:0
:2
:4
:6
:A])
(def all-names
(apply concat
(mapcat concat
(for [i (range 12)]
(for [j (range 12)]
(for [k (range 12)]
[(nth lib/letters i)
(nth lib/letters j)
(nth lib/letters k)]))))))
(def weak-names
(apply concat
(mapcat concat
(for [i (range (count weak-letters))]
(for [j (range (count weak-letters))]
(for [k (range (count weak-letters))]
[(nth weak-letters i)
(nth weak-letters j)
(nth weak-letters k)]))))))
(def sorted-power (sort-by (fn [x]
(+ (first x) (second x)))
(map (fn [name]
(list (lib/strength name) (lib/health name) name))
all-names)))
(def sorted-weak (sort-by (fn [x]
(+ (first x) (second x)))
(map (fn [name]
(list (lib/strength name) (lib/health name) name))
weak-names)))
(take-last 12 sorted-weak)
(count (filter (fn [x]
(and (>= (+ (first x) (second x)) 10)
(or (>= (first x) 5)
(>= (second x) 5))))
sorted-power))
(filter (fn [x]
(= (+ (first x) (second x)) 18))
sorted-power)
|
[
{
"context": "f \"Memento\"\n [:a5 :type :Person]\n [:a5 :name \"Christopher Nolan\"]\n\n ;; The movie \"The Usual Suspects\"\n [:a6 :",
"end": 668,
"score": 0.9998872876167297,
"start": 651,
"tag": "NAME",
"value": "Christopher Nolan"
},
{
"context": "l Suspects\"\n [:a8 :type :Person]\n [:a8 :name \"Bryan Singer\"]])\n\n(defn make-relations\n [graph studio-name di",
"end": 1000,
"score": 0.9998899698257446,
"start": 988,
"tag": "NAME",
"value": "Bryan Singer"
}
] | src/logic_tut/book.clj | oubiwann/hackday-logic-tutorial | 0 | (ns logic-tut.book
(:require [clojure.core.logic :as logic]
[clojure.tools.logging :as log]))
(def movie-graph
[;; The "NewMarket Films" studio
[:a1 :type :FilmStudio]
[:a1 :name "Newmarket Films"]
[:a1 :filmsCollection :a2]
;; Collection of films made by Newmarket Films
[:a2 :type :FilmCollection]
[:a2 :film :a3]
[:a2 :film :a6]
;; The movie "Memento"
[:a3 :type :Film]
[:a3 :name "Memento"]
[:a3 :cast :a4]
;; Connects the film to its cast (actors/director/producer etc.)
[:a4 :type :FilmCast]
[:a4 :director :a5]
;; The director of "Memento"
[:a5 :type :Person]
[:a5 :name "Christopher Nolan"]
;; The movie "The Usual Suspects"
[:a6 :type :Film]
[:a6 :filmName "The Usual Suspects"]
[:a6 :cast :a7]
;; Connects the film to its cast (actors/director/producer etc.)
[:a7 :type :FilmCast]
[:a7 :director :a8]
;; The director of "The Usual Suspects"
[:a8 :type :Person]
[:a8 :name "Bryan Singer"]])
(defn make-relations
[graph studio-name director-name]
(logic/fresh [studio film-coll film cast director]
;; Relate the original studio-name to a film collection - from the
;; core.logic docs:
;;
;; "When you unify two lvars, the operation constrains each lvar
;; to have the same set of possible values. A mental shortcut is
;; to consider unification to be the intersection of the two sets
;; lvar values."
;;
;; This means that below, we're saying:
;; *
(logic/membero [studio :name studio-name] graph)
(logic/membero [studio :type :FilmStudio] graph)
(logic/membero [studio :filmsCollection film-coll] graph)
;; Relate any film collections to their individual films
(logic/membero [film-coll :type :FilmCollection] graph)
(logic/membero [film-coll :film film] graph)
;; Then from film to cast members
(logic/membero [film :type :Film] graph)
(logic/membero [film :cast cast] graph)
;; Grounding to cast members of type :director
(logic/membero [cast :type :FilmCast] graph)
(logic/membero [cast :director director] graph)
;; Finally, attach to the director-name
(logic/membero [director :type :Person] graph)
(logic/membero [director :name director-name] graph)))
(defn directors-at
"Find all of the directors that have directed at a given studio."
[graph studio-name]
(logic/run* [director-name]
(make-relations graph studio-name director-name)))
| 120877 | (ns logic-tut.book
(:require [clojure.core.logic :as logic]
[clojure.tools.logging :as log]))
(def movie-graph
[;; The "NewMarket Films" studio
[:a1 :type :FilmStudio]
[:a1 :name "Newmarket Films"]
[:a1 :filmsCollection :a2]
;; Collection of films made by Newmarket Films
[:a2 :type :FilmCollection]
[:a2 :film :a3]
[:a2 :film :a6]
;; The movie "Memento"
[:a3 :type :Film]
[:a3 :name "Memento"]
[:a3 :cast :a4]
;; Connects the film to its cast (actors/director/producer etc.)
[:a4 :type :FilmCast]
[:a4 :director :a5]
;; The director of "Memento"
[:a5 :type :Person]
[:a5 :name "<NAME>"]
;; The movie "The Usual Suspects"
[:a6 :type :Film]
[:a6 :filmName "The Usual Suspects"]
[:a6 :cast :a7]
;; Connects the film to its cast (actors/director/producer etc.)
[:a7 :type :FilmCast]
[:a7 :director :a8]
;; The director of "The Usual Suspects"
[:a8 :type :Person]
[:a8 :name "<NAME>"]])
(defn make-relations
[graph studio-name director-name]
(logic/fresh [studio film-coll film cast director]
;; Relate the original studio-name to a film collection - from the
;; core.logic docs:
;;
;; "When you unify two lvars, the operation constrains each lvar
;; to have the same set of possible values. A mental shortcut is
;; to consider unification to be the intersection of the two sets
;; lvar values."
;;
;; This means that below, we're saying:
;; *
(logic/membero [studio :name studio-name] graph)
(logic/membero [studio :type :FilmStudio] graph)
(logic/membero [studio :filmsCollection film-coll] graph)
;; Relate any film collections to their individual films
(logic/membero [film-coll :type :FilmCollection] graph)
(logic/membero [film-coll :film film] graph)
;; Then from film to cast members
(logic/membero [film :type :Film] graph)
(logic/membero [film :cast cast] graph)
;; Grounding to cast members of type :director
(logic/membero [cast :type :FilmCast] graph)
(logic/membero [cast :director director] graph)
;; Finally, attach to the director-name
(logic/membero [director :type :Person] graph)
(logic/membero [director :name director-name] graph)))
(defn directors-at
"Find all of the directors that have directed at a given studio."
[graph studio-name]
(logic/run* [director-name]
(make-relations graph studio-name director-name)))
| true | (ns logic-tut.book
(:require [clojure.core.logic :as logic]
[clojure.tools.logging :as log]))
(def movie-graph
[;; The "NewMarket Films" studio
[:a1 :type :FilmStudio]
[:a1 :name "Newmarket Films"]
[:a1 :filmsCollection :a2]
;; Collection of films made by Newmarket Films
[:a2 :type :FilmCollection]
[:a2 :film :a3]
[:a2 :film :a6]
;; The movie "Memento"
[:a3 :type :Film]
[:a3 :name "Memento"]
[:a3 :cast :a4]
;; Connects the film to its cast (actors/director/producer etc.)
[:a4 :type :FilmCast]
[:a4 :director :a5]
;; The director of "Memento"
[:a5 :type :Person]
[:a5 :name "PI:NAME:<NAME>END_PI"]
;; The movie "The Usual Suspects"
[:a6 :type :Film]
[:a6 :filmName "The Usual Suspects"]
[:a6 :cast :a7]
;; Connects the film to its cast (actors/director/producer etc.)
[:a7 :type :FilmCast]
[:a7 :director :a8]
;; The director of "The Usual Suspects"
[:a8 :type :Person]
[:a8 :name "PI:NAME:<NAME>END_PI"]])
(defn make-relations
[graph studio-name director-name]
(logic/fresh [studio film-coll film cast director]
;; Relate the original studio-name to a film collection - from the
;; core.logic docs:
;;
;; "When you unify two lvars, the operation constrains each lvar
;; to have the same set of possible values. A mental shortcut is
;; to consider unification to be the intersection of the two sets
;; lvar values."
;;
;; This means that below, we're saying:
;; *
(logic/membero [studio :name studio-name] graph)
(logic/membero [studio :type :FilmStudio] graph)
(logic/membero [studio :filmsCollection film-coll] graph)
;; Relate any film collections to their individual films
(logic/membero [film-coll :type :FilmCollection] graph)
(logic/membero [film-coll :film film] graph)
;; Then from film to cast members
(logic/membero [film :type :Film] graph)
(logic/membero [film :cast cast] graph)
;; Grounding to cast members of type :director
(logic/membero [cast :type :FilmCast] graph)
(logic/membero [cast :director director] graph)
;; Finally, attach to the director-name
(logic/membero [director :type :Person] graph)
(logic/membero [director :name director-name] graph)))
(defn directors-at
"Find all of the directors that have directed at a given studio."
[graph studio-name]
(logic/run* [director-name]
(make-relations graph studio-name director-name)))
|
[
{
"context": "fn add-event\n [{id :id provider \"provider\" user \"username\" target \"target-username\" keyword \"keyword\" conte",
"end": 659,
"score": 0.9933452606201172,
"start": 651,
"tag": "USERNAME",
"value": "username"
},
{
"context": " :as event}]\n (let [current-user (get-in @auth [\"twitter\" \"username\"])]\n (.log js/console (str \"Event U",
"end": 778,
"score": 0.6502708792686462,
"start": 771,
"tag": "USERNAME",
"value": "twitter"
},
{
"context": "}]\n (let [current-user (get-in @auth [\"twitter\" \"username\"])]\n (.log js/console (str \"Event User: \" user",
"end": 789,
"score": 0.974445104598999,
"start": 781,
"tag": "USERNAME",
"value": "username"
},
{
"context": " teach you to keep your mouth shut.\"]\n\t [:i \"- Ernest Hemmingway\"]\n\t [:br]\n\t [:br]\n\t [:div.btn-group.b",
"end": 1893,
"score": 0.9998959898948669,
"start": 1876,
"tag": "NAME",
"value": "Ernest Hemmingway"
}
] | data/test/clojure/e747af7ce49d0d1276a6233e5270e9d01fcd58b2manage.cljs | harshp8l/deep-learning-lang-detection | 84 | (ns bmihw.manage
(:require [reagent.core :as reagent :refer [atom]]
[reagent.session :as session]
[secretary.core :as secretary :include-macros true]
[goog.events :as events]
[goog.history.EventType :as EventType]
[ajax.core :refer [GET POST]]
[bmihw.common :refer [auth fb]]
[cljsjs.firebase :as firebase])
(:import goog.History))
(def events (reagent/atom []))
(def current-event (reagent/atom nil))
(defn drunk?
[{drunk "drunk" :as event}]
(or (nil? drunk) (= drunk "true") drunk))
(defn add-event
[{id :id provider "provider" user "username" target "target-username" keyword "keyword" content "content" :as event}]
(let [current-user (get-in @auth ["twitter" "username"])]
(.log js/console (str "Event User: " user ", Current User:" current-user))
#_(if (= user current-user))
(swap! events conj {:id id
:provider provider
:user user
:keyword keyword
:target target
:drunk (drunk? event)
:content content})));;)
(defn handle-childsnapshot
[snapshot]
(let [key (.key snapshot)
val (.val snapshot)]
(if val
(add-event (merge {:id key} (js->clj val))))))
(defn handle-childsnapshot-remove
[snapshot]
(let [id (.key snapshot)
clean-events (filter (fn [e] (not (= id (:id e)))) @events)]
(reset! events clean-events)))
(declare manage-page)
(defn delete-page
[]
(if-let [drunk (:drunk @current-event)]
[:div.panel.panel-default
[:div.panel-heading
[:h3.panel-title "NOPE!!!!"]]
[:div.panel-body
[:p "Always do sober what you said you'd do drunk. That will teach you to keep your mouth shut."]
[:i "- Ernest Hemmingway"]
[:br]
[:br]
[:div.btn-group.btn-group-justified
[:a.btn.btn-default {:href "#/manage"
:on-click (fn [e]
(reset! current-event nil)
(session/put! :current-page #'manage-page))} "Back To Manage Submissions"]]]]
[:div.panel.panel-default
[:div.panel-heading
[:h3.panel-title "Really???"]]
[:div.panel-body
[:p "Are you sure you want to hide the evidence?"]
[:div.btn-group.btn-group-justified
[:a.btn.btn-default {:href "#/manage"
:on-click (fn [e]
(let [id (:id @current-event)
ref (.child fb id)]
(.remove ref)
(reset! current-event nil)
(session/put! :current-page #'manage-page)))} "Yes, I'm a pussy."]
[:a.btn.btn-default {:href "#/manage"
:on-click (fn [e]
(reset! current-event nil)
(session/put! :current-page #'manage-page))} "Hell No!."]]]]))
(defn manage-page
[]
(let [who (get-in auth ["uid"])]
[:div
[:h3.panel-title "Manage Your Insults To Those Deserving Bastards!"]
[:div.panel-body
[:table#manage.table {:style {:width "100%"}}
[:tr
[:th "Service"] [:th "Drunk"] [:th "Target Person"] [:th "Target Keyword"] [:th "Insult"] [:td who]]
(for [event @events]
[:tr {:key (:id event)}
[:td (:provider event)]
[:td (or (and (:drunk event) "Yep") "Nope")]
[:td (:target event)]
[:td (:keyword event)]
[:td (:content event)]
[:td [:button.btn.btn-default {:type "button"
:on-click (fn [e]
(reset! current-event event)
(session/put! :current-page #'delete-page))} "Delete"]]])]]
[:div.btn-group.btn-group-justified
[:a.btn.btn-default {:href "#/submit"} "Add Another"]]]))
(.on fb "child_added" handle-childsnapshot)
(.on fb "child_removed" handle-childsnapshot-remove)
(secretary/defroute "/manage" []
(session/put! :current-page #'manage-page))
| 99398 | (ns bmihw.manage
(:require [reagent.core :as reagent :refer [atom]]
[reagent.session :as session]
[secretary.core :as secretary :include-macros true]
[goog.events :as events]
[goog.history.EventType :as EventType]
[ajax.core :refer [GET POST]]
[bmihw.common :refer [auth fb]]
[cljsjs.firebase :as firebase])
(:import goog.History))
(def events (reagent/atom []))
(def current-event (reagent/atom nil))
(defn drunk?
[{drunk "drunk" :as event}]
(or (nil? drunk) (= drunk "true") drunk))
(defn add-event
[{id :id provider "provider" user "username" target "target-username" keyword "keyword" content "content" :as event}]
(let [current-user (get-in @auth ["twitter" "username"])]
(.log js/console (str "Event User: " user ", Current User:" current-user))
#_(if (= user current-user))
(swap! events conj {:id id
:provider provider
:user user
:keyword keyword
:target target
:drunk (drunk? event)
:content content})));;)
(defn handle-childsnapshot
[snapshot]
(let [key (.key snapshot)
val (.val snapshot)]
(if val
(add-event (merge {:id key} (js->clj val))))))
(defn handle-childsnapshot-remove
[snapshot]
(let [id (.key snapshot)
clean-events (filter (fn [e] (not (= id (:id e)))) @events)]
(reset! events clean-events)))
(declare manage-page)
(defn delete-page
[]
(if-let [drunk (:drunk @current-event)]
[:div.panel.panel-default
[:div.panel-heading
[:h3.panel-title "NOPE!!!!"]]
[:div.panel-body
[:p "Always do sober what you said you'd do drunk. That will teach you to keep your mouth shut."]
[:i "- <NAME>"]
[:br]
[:br]
[:div.btn-group.btn-group-justified
[:a.btn.btn-default {:href "#/manage"
:on-click (fn [e]
(reset! current-event nil)
(session/put! :current-page #'manage-page))} "Back To Manage Submissions"]]]]
[:div.panel.panel-default
[:div.panel-heading
[:h3.panel-title "Really???"]]
[:div.panel-body
[:p "Are you sure you want to hide the evidence?"]
[:div.btn-group.btn-group-justified
[:a.btn.btn-default {:href "#/manage"
:on-click (fn [e]
(let [id (:id @current-event)
ref (.child fb id)]
(.remove ref)
(reset! current-event nil)
(session/put! :current-page #'manage-page)))} "Yes, I'm a pussy."]
[:a.btn.btn-default {:href "#/manage"
:on-click (fn [e]
(reset! current-event nil)
(session/put! :current-page #'manage-page))} "Hell No!."]]]]))
(defn manage-page
[]
(let [who (get-in auth ["uid"])]
[:div
[:h3.panel-title "Manage Your Insults To Those Deserving Bastards!"]
[:div.panel-body
[:table#manage.table {:style {:width "100%"}}
[:tr
[:th "Service"] [:th "Drunk"] [:th "Target Person"] [:th "Target Keyword"] [:th "Insult"] [:td who]]
(for [event @events]
[:tr {:key (:id event)}
[:td (:provider event)]
[:td (or (and (:drunk event) "Yep") "Nope")]
[:td (:target event)]
[:td (:keyword event)]
[:td (:content event)]
[:td [:button.btn.btn-default {:type "button"
:on-click (fn [e]
(reset! current-event event)
(session/put! :current-page #'delete-page))} "Delete"]]])]]
[:div.btn-group.btn-group-justified
[:a.btn.btn-default {:href "#/submit"} "Add Another"]]]))
(.on fb "child_added" handle-childsnapshot)
(.on fb "child_removed" handle-childsnapshot-remove)
(secretary/defroute "/manage" []
(session/put! :current-page #'manage-page))
| true | (ns bmihw.manage
(:require [reagent.core :as reagent :refer [atom]]
[reagent.session :as session]
[secretary.core :as secretary :include-macros true]
[goog.events :as events]
[goog.history.EventType :as EventType]
[ajax.core :refer [GET POST]]
[bmihw.common :refer [auth fb]]
[cljsjs.firebase :as firebase])
(:import goog.History))
(def events (reagent/atom []))
(def current-event (reagent/atom nil))
(defn drunk?
[{drunk "drunk" :as event}]
(or (nil? drunk) (= drunk "true") drunk))
(defn add-event
[{id :id provider "provider" user "username" target "target-username" keyword "keyword" content "content" :as event}]
(let [current-user (get-in @auth ["twitter" "username"])]
(.log js/console (str "Event User: " user ", Current User:" current-user))
#_(if (= user current-user))
(swap! events conj {:id id
:provider provider
:user user
:keyword keyword
:target target
:drunk (drunk? event)
:content content})));;)
(defn handle-childsnapshot
[snapshot]
(let [key (.key snapshot)
val (.val snapshot)]
(if val
(add-event (merge {:id key} (js->clj val))))))
(defn handle-childsnapshot-remove
[snapshot]
(let [id (.key snapshot)
clean-events (filter (fn [e] (not (= id (:id e)))) @events)]
(reset! events clean-events)))
(declare manage-page)
(defn delete-page
[]
(if-let [drunk (:drunk @current-event)]
[:div.panel.panel-default
[:div.panel-heading
[:h3.panel-title "NOPE!!!!"]]
[:div.panel-body
[:p "Always do sober what you said you'd do drunk. That will teach you to keep your mouth shut."]
[:i "- PI:NAME:<NAME>END_PI"]
[:br]
[:br]
[:div.btn-group.btn-group-justified
[:a.btn.btn-default {:href "#/manage"
:on-click (fn [e]
(reset! current-event nil)
(session/put! :current-page #'manage-page))} "Back To Manage Submissions"]]]]
[:div.panel.panel-default
[:div.panel-heading
[:h3.panel-title "Really???"]]
[:div.panel-body
[:p "Are you sure you want to hide the evidence?"]
[:div.btn-group.btn-group-justified
[:a.btn.btn-default {:href "#/manage"
:on-click (fn [e]
(let [id (:id @current-event)
ref (.child fb id)]
(.remove ref)
(reset! current-event nil)
(session/put! :current-page #'manage-page)))} "Yes, I'm a pussy."]
[:a.btn.btn-default {:href "#/manage"
:on-click (fn [e]
(reset! current-event nil)
(session/put! :current-page #'manage-page))} "Hell No!."]]]]))
(defn manage-page
[]
(let [who (get-in auth ["uid"])]
[:div
[:h3.panel-title "Manage Your Insults To Those Deserving Bastards!"]
[:div.panel-body
[:table#manage.table {:style {:width "100%"}}
[:tr
[:th "Service"] [:th "Drunk"] [:th "Target Person"] [:th "Target Keyword"] [:th "Insult"] [:td who]]
(for [event @events]
[:tr {:key (:id event)}
[:td (:provider event)]
[:td (or (and (:drunk event) "Yep") "Nope")]
[:td (:target event)]
[:td (:keyword event)]
[:td (:content event)]
[:td [:button.btn.btn-default {:type "button"
:on-click (fn [e]
(reset! current-event event)
(session/put! :current-page #'delete-page))} "Delete"]]])]]
[:div.btn-group.btn-group-justified
[:a.btn.btn-default {:href "#/submit"} "Add Another"]]]))
(.on fb "child_added" handle-childsnapshot)
(.on fb "child_removed" handle-childsnapshot-remove)
(secretary/defroute "/manage" []
(session/put! :current-page #'manage-page))
|
[
{
"context": "or db namespace.\n;; Copyright 2011-2012, Vixu.com, F.M. (Filip) de Waard <fmw@vixu.com>.\n;;\n;; Licensed und",
"end": 85,
"score": 0.9978172183036804,
"start": 82,
"tag": "NAME",
"value": "F.M"
},
{
"context": "amespace.\n;; Copyright 2011-2012, Vixu.com, F.M. (Filip) de Waard <fmw@vixu.com>.\n;;\n;; Licensed under the Apache L",
"end": 103,
"score": 0.9469515085220337,
"start": 88,
"tag": "NAME",
"value": "Filip) de Waard"
},
{
"context": "right 2011-2012, Vixu.com, F.M. (Filip) de Waard <fmw@vixu.com>.\n;;\n;; Licensed under the Apache License, Versio",
"end": 117,
"score": 0.9999321699142456,
"start": 105,
"tag": "EMAIL",
"value": "fmw@vixu.com"
},
{
"context": "g\"\n :subtitle \"Another Weblog!\"\n :name \"another-blog\"\n :language \"en\"\n :default-slug-format ",
"end": 18826,
"score": 0.9942910075187683,
"start": 18814,
"tag": "USERNAME",
"value": "another-blog"
},
{
"context": " :action :create\n :name \"foobar\"\n :language \"en\"\n ",
"end": 24015,
"score": 0.9380124807357788,
"start": 24009,
"tag": "USERNAME",
"value": "foobar"
},
{
"context": " :action :create\n :name \"foobar\"\n :language \"en\"\n ",
"end": 24510,
"score": 0.9611988067626953,
"start": 24504,
"tag": "USERNAME",
"value": "foobar"
},
{
"context": "b+ \"en\" \"foobar\")))\n :name \"foobar\"\n :language \"en\"\n ",
"end": 25059,
"score": 0.991756021976471,
"start": 25053,
"tag": "USERNAME",
"value": "foobar"
},
{
"context": " :action :create\n :name \"foobar\"\n :language \"en\"\n ",
"end": 25521,
"score": 0.8680334091186523,
"start": 25515,
"tag": "USERNAME",
"value": "foobar"
},
{
"context": " :title\n \"Tomasz Stańko Middelburg\"\n :slug\n ",
"end": 62856,
"score": 0.9828464388847351,
"start": 62832,
"tag": "NAME",
"value": "Tomasz Stańko Middelburg"
},
{
"context": ":content\n (str \"Gwilym Simcock, Mike Walker, \"\n ",
"end": 64188,
"score": 0.9998000860214233,
"start": 64174,
"tag": "NAME",
"value": "Gwilym Simcock"
},
{
"context": " (str \"Gwilym Simcock, Mike Walker, \"\n \"Adam ",
"end": 64201,
"score": 0.9998661875724792,
"start": 64190,
"tag": "NAME",
"value": "Mike Walker"
},
{
"context": "alker, \"\n \"Adam Nussbaum, Steve Swallow \"\n ",
"end": 64259,
"score": 0.999886155128479,
"start": 64246,
"tag": "NAME",
"value": "Adam Nussbaum"
},
{
"context": " \"Adam Nussbaum, Steve Swallow \"\n \"will b",
"end": 64274,
"score": 0.9998793601989746,
"start": 64261,
"tag": "NAME",
"value": "Steve Swallow"
},
{
"context": " :title\n \"Yuri Honing\"\n :slug\n ",
"end": 65101,
"score": 0.9997472167015076,
"start": 65090,
"tag": "NAME",
"value": "Yuri Honing"
},
{
"context": "winner \"\n \"Yuri Honing will be playing at \"\n ",
"end": 65379,
"score": 0.9995579123497009,
"start": 65368,
"tag": "NAME",
"value": "Yuri Honing"
}
] | test/clj/vix/test/db.clj | fmw/vix | 22 | ;; test/vix/test/db.clj tests for db namespace.
;; Copyright 2011-2012, Vixu.com, F.M. (Filip) de Waard <fmw@vixu.com>.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns vix.test.db
(:use [vix.db] :reload
[vix.test.test]
[slingshot.test]
[clojure.test]
[clojure.data.json :only [read-json]])
(:require [com.ashafa.clutch :as clutch]
[clj-http.client :as http]
[vix.util :as util])
(:import [org.apache.commons.codec.binary Base64]))
(defn couchdb-id? [s]
(re-matches #"^[a-z0-9]{32}$" s))
(defn couchdb-rev?
([s]
(couchdb-rev? 1 s))
([rev-num s]
(re-matches (re-pattern (str "^" rev-num "-[a-z0-9]{32}$")) s)))
(defn iso-date? [s]
(re-matches
#"^[\d]{4}-[\d]{2}-[\d]{2}T[\d]{2}:[\d]{2}:[\d]{2}\.[\d]{1,4}Z"
s))
(defn random-lower-case-string [length]
;; to include uppercase
;; (let [ascii-codes (concat (range 48 58) (range 66 91) (range 97 123))])
(let [ascii-codes (concat (range 48 58) (range 97 123))]
(apply str (repeatedly length #(char (rand-nth ascii-codes))))))
(def +test-db+ (str "vix-test-" (random-lower-case-string 20)))
(def +test-server+ "http://localhost:5984/")
(defn database-fixture [f]
(clutch/get-database +test-db+)
(f)
(clutch/delete-database +test-db+))
(use-fixtures :each database-fixture)
(deftest test-load-view
(is (= (load-view "database-views/map_newsletter_subscribers.js")
(str "function(doc) {\n"
" if(doc.type === \"newsletter-subscriber\") {\n"
" emit([doc.language, doc.email], doc);\n"
" }\n}\n"))))
(deftest test-create-views
(create-views +test-db+ "views" views)
(let [view-doc (read-json (:body (http/get
(str +test-server+
+test-db+
"/_design/views"))))]
(is (= (count (:views view-doc)) 9))
(is (= (:map (:feeds (:views view-doc)))
(str "function(feed) {\n"
" if(feed.type === \"feed\") {\n"
" emit([feed.language, feed.name, feed.datestamp]"
", feed);\n }\n}\n")))
(is (= (:map (:feeds_by_default_document_type (:views view-doc)))
(str "function(feed) {\n"
" if(feed.type === \"feed\" &&\n"
" feed[\"current-state\"] === true &&\n"
" feed.action !== \"delete\") {\n"
" emit([feed[\"default-document-type\"],\n"
" feed[\"language\"],\n"
" feed[\"name\"]],\n"
" feed);\n"
" }\n}\n")))
(is (= (:map (:feeds_overview (:views view-doc)))
(str "function(feed) {\n"
" if(feed.type === \"feed\" &&\n"
" feed[\"current-state\"] === true &&\n"
" feed.action !== \"delete\") {\n"
" emit([feed.language, feed.name, feed.datestamp],"
" feed);\n"
" }\n}\n")))
(is (= (:map (:by_slug (:views view-doc)))
(str "function(doc) {\n"
" if(doc.type === \"document\") {\n"
" emit([doc.slug, doc.datestamp], doc);\n"
" }\n}\n")))
(is (= (:map (:by_feed (:views view-doc)))
(str "function(doc) {\n"
" if(doc.type === \"document\" &&\n"
" doc[\"current-state\"] === true &&\n"
" doc.action !== \"delete\") {\n"
" emit([[doc.language, doc.feed], doc.published], "
"doc);\n"
" }\n}\n")))
(is (= (:map (:by_username (:views view-doc)))
(str "function(doc) {\n"
" if(doc.type === \"user\") {\n"
" emit(doc.username, doc);\n"
" }\n"
"}\n")))
(is (= (:map (:events_by_feed (:views view-doc)))
(str "function(doc) {\n"
" if(doc.type === \"document\" &&\n"
" doc[\"end-time-rfc3339\"] &&\n"
" doc[\"current-state\"] === true) {\n"
" emit([[doc.language, doc.feed], "
"doc[\"end-time-rfc3339\"]], doc);\n }\n}\n")))
(is (= (:map (:subscribers (:views view-doc)))
(str "function(doc) {\n"
" if(doc.type === \"newsletter-subscriber\") {\n"
" emit([doc.language, doc.email], doc);\n"
" }\n}\n")))
(is (= (:map (:languages (:views view-doc)))
(str "function(feed) {\n"
" if(feed.type === \"feed\" &&\n"
" feed[\"current-state\"] === true &&\n"
" feed.action !== \"delete\") {\n"
" emit(feed.language, null);\n"
" }\n}\n")))
(is (= (:reduce (:languages (:views view-doc)))
"function(k,v) {\n return null;\n}\n")))
(is (thrown+? (partial check-exc :vix.db/database-socket-error)
(create-views "http://localhost:9999/foo" "bar" views))))
(deftest test-get-attachment-as-base64-string
(let [gif (str "R0lGODlhAQABA++/vQAAAAAAAAAA77+9AQIAAAAh77+9BAQUA++/"
"vQAsAAAAAAEAAQAAAgJEAQA7")
document (append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:attachment {:type "image/gif"
:data gif}
:feed "images"
:language "en"
:title "a single black pixel!"
:slug "pixel.gif"
:content ""
:draft false})]
(is (= (get-attachment-as-base64-string +test-db+
(:_id (first document))
:original)
gif))))
(deftest test-get-document
(is (nil? (get-document +test-db+ "/blog/foo")))
(is (nil? (get-document +test-db+ "/blog/foo" {:limit 100000})))
(with-redefs [util/now-rfc3339 #(str "2012-09-15T23:48:58.050Z")]
(append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:title "foo"
:slug "/blog/foo"
:language "en"
:feed "blog"
:content "bar"
:draft true})
(append-to-document +test-db+
"Europe/Amsterdam"
{:action :update
:previous-id (:_id
(first
(get-document
+test-db+
"/blog/foo")))
:title "foo"
:slug "/blog/foo"
:language "en"
:feed "blog"
:content "bar"
:draft false}))
;; The view isn't created manually; successful execution of
;; this test also implies that it is created automatically.
(is (couchdb-id? (:_id (first (get-document +test-db+ "/blog/foo")))))
(is (couchdb-rev? (:_rev (first (get-document +test-db+ "/blog/foo")))))
(is (= (vec (map #(dissoc % :_id :_rev :previous-id)
(get-document +test-db+ "/blog/foo")))
[{:slug "/blog/foo"
:content "bar"
:action :update
:language "en"
:title "foo"
:published "2012-09-15T23:48:58.050Z"
:datestamp "2012-09-15T23:48:58.050Z"
:created "2012-09-15T23:48:58.050Z"
:type "document"
:feed "blog"
:draft false}
{:slug "/blog/foo"
:content "bar"
:action :create
:language "en"
:title "foo"
:published "2012-09-15T23:48:58.050Z"
:datestamp "2012-09-15T23:48:58.050Z"
:created "2012-09-15T23:48:58.050Z"
:type "document"
:feed "blog"
:draft true}]))
(is (= (vec (map #(dissoc % :_id :_rev :previous-id)
(get-document +test-db+ "/blog/foo" {:limit 1})))
[{:slug "/blog/foo"
:content "bar"
:action :update
:language "en"
:title "foo"
:published "2012-09-15T23:48:58.050Z"
:datestamp "2012-09-15T23:48:58.050Z"
:created "2012-09-15T23:48:58.050Z"
:type "document"
:feed "blog"
:draft false}]))
(testing "Test if attachments are handled correctly."
(let [gif (str "R0lGODlhAQABA++/vQAAAAAAAAAA77+9AQIAAAAh77+9BAQUA++/"
"vQAsAAAAAAEAAQAAAgJEAQA7")]
(do
(append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:attachment {:type "image/gif" :data gif}
:title "a single black pixel!"
:slug "/images/white-pixel.gif"
:language "en"
:feed "images"
:content ""
:draft false})
(append-to-document +test-db+
"Europe/Amsterdam"
{:action :update
:previous-id (:_id
(first
(get-document
+test-db+
"/images/white-pixel.gif")))
:attachment {:type "image/gif" :data gif}
:title "a single black pixel!"
:slug "/images/white-pixel.gif"
:language "en"
:feed "images"
:content ""
:draft false})
(append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:title "not a single black pixel!"
:slug "/images/not-a-white-pixel.gif"
:language "en"
:feed "images"
:content ""
:draft false}))
(is (= (get-in (get-document +test-db+ "/images/white-pixel.gif")
[0 :attachments :original])
(get-in (get-document +test-db+ "/images/white-pixel.gif")
[1 :attachments :original])
{:type "image/gif" :data gif :length 57})))))
(deftest test-get-feed
(with-redefs [util/now-rfc3339 #(str "2012-09-04T03:46:52.096Z")]
(let [en-feed (append-to-feed
+test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "en"})
nl-feed (append-to-feed
+test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "nl"})
nl-feed-update-0 (with-redefs
[util/now-rfc3339
#(str "2012-09-04T03:50:52.096Z")]
(append-to-feed
+test-db+
{:action :update
:previous-id (:_id (first nl-feed))
:title "B1"
:subtitle "b1!"
:name "blog"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "nl"}))
nl-feed-update-1 (with-redefs
[util/now-rfc3339
#(str "2012-09-04T03:55:52.096Z")]
(append-to-feed
+test-db+
{:action :update
:previous-id (:_id (first nl-feed-update-0))
:title "B2"
:subtitle "b2!"
:name "blog"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "nl"}))]
(is (= (map #(dissoc % :_id :_rev) (get-feed +test-db+ "en" "blog"))
[{:subtitle "Vix Weblog!"
:action :create
:name "blog"
:language "en"
:title "Weblog"
:datestamp "2012-09-04T03:46:52.096Z"
:created "2012-09-04T03:46:52.096Z"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"}]))
(is (couchdb-id? (:_id (first (get-feed +test-db+ "en" "blog")))))
(is (couchdb-rev? (:_rev (first (get-feed +test-db+ "en" "blog")))))
(is (= (map #(dissoc % :_id :_rev :previous-id)
(get-feed +test-db+ "nl" "blog"))
[{:subtitle "b2!"
:action :update
:name "blog"
:language "nl"
:title "B2"
:datestamp "2012-09-04T03:55:52.096Z"
:created "2012-09-04T03:46:52.096Z"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"}
{:subtitle "b1!"
:action :update
:name "blog"
:language "nl"
:title "B1"
:datestamp "2012-09-04T03:50:52.096Z"
:created "2012-09-04T03:46:52.096Z"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"}
{:subtitle "Vix Weblog!"
:action :create
:name "blog"
:language "nl"
:title "Weblog"
:datestamp "2012-09-04T03:46:52.096Z"
:created "2012-09-04T03:46:52.096Z"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"}]))
(is (= (map #(dissoc % :_id :_rev :previous-id)
(get-feed +test-db+ "nl" "blog" 1))
[{:subtitle "b2!"
:action :update
:name "blog"
:language "nl"
:title "B2"
:datestamp "2012-09-04T03:55:52.096Z"
:created "2012-09-04T03:46:52.096Z"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"}]))
(let [blog-states (get-feed +test-db+ "nl" "blog")]
(are [n]
(couchdb-id? (:_id (nth blog-states n)))
0 1 2)
(are [rev-number n]
(couchdb-rev? rev-number (:_rev (nth blog-states n)))
1 0
2 1
2 2)))))
(deftest test-append-to-feed
(let [blog-feed (with-redefs [util/now-rfc3339
#(str "2012-09-04T04:30:17.872Z")]
(first
(append-to-feed
+test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:language "en"
:default-slug-format "/{document-title}"
:default-document-type "with-description"})))]
(testing "test create action"
(is (= (:type blog-feed) "feed"))
(is (couchdb-id? (:_id blog-feed)))
(is (couchdb-rev? (:_rev blog-feed)))
(is (iso-date? (:created blog-feed)))
(is (= (:title blog-feed) "Weblog"))
(is (= (:subtitle blog-feed) "Vix Weblog!"))
(is (= (:name blog-feed) "blog"))
(is (= (:language blog-feed) "en"))
(is (= (:default-slug-format blog-feed) "/{document-title}"))
(is (= (:default-document-type blog-feed) "with-description")))
;; make sure that invalid actions aren't allowed
(is (thrown+? (partial check-exc :vix.db/invalid-action)
(append-to-feed
+test-db+
(assoc blog-feed
:action :invalid
:previous-id (:_id blog-feed)
:title "Updated Weblog Feed"
:default-document-type "standard"
:searchable true))))
(is (thrown+? (partial check-exc :vix.db/invalid-action)
(append-to-feed
+test-db+
(dissoc (assoc blog-feed
:previous-id (:_id blog-feed)
:title "Updated Weblog Feed"
:default-document-type "standard"
:searchable true)
:action))))
;; a non-keyword action should work:
(append-to-feed
+test-db+
{:action :create
:title "Weblog"
:subtitle "Another Weblog!"
:name "another-blog"
:language "en"
:default-slug-format "/{document-title}"
:default-document-type "with-description"})
(let [blog-feed-updated (with-redefs [util/now-rfc3339
#(str "2012-09-04T04:30:17.930Z")]
(first
(append-to-feed
+test-db+
(assoc blog-feed
:action :update
:previous-id (:_id blog-feed)
:title "Updated Weblog Feed"
:default-document-type "standard"
:searchable true))))]
(testing "test update action"
(is (= (first (get-feed +test-db+ "en" "blog")) blog-feed-updated))
(is (couchdb-rev? (:_rev blog-feed-updated)))
(is (iso-date? (:datestamp blog-feed-updated)))
(is (= (:created blog-feed) (:created blog-feed-updated)))
(is (= (:title blog-feed-updated) "Updated Weblog Feed"))
(is (= (:subtitle blog-feed-updated) "Vix Weblog!"))
(is (= (:language blog-feed-updated) "en"))
(is (= (:name blog-feed-updated) "blog")) ; NB: not updated!
(is (= (:default-slug-format blog-feed-updated) "/{document-title}"))
(is (= (:default-document-type blog-feed-updated) "standard"))
(is (= (:searchable blog-feed-updated) true))
(is (thrown+? (partial check-exc :vix.db/feed-update-conflict)
(append-to-feed
+test-db+
(assoc blog-feed
:action :update))))
(is (thrown+? (partial check-exc :vix.db/feed-update-conflict)
(append-to-feed
+test-db+
(assoc blog-feed
:action :update
:previous-id (:previous-id blog-feed))))))
(testing "test delete action"
(is (not (nil? (get-feed +test-db+ "en" "blog")))
"Assure the feed exists before it is deleted.")
(is (thrown+? (partial check-exc :vix.db/feed-update-conflict)
(append-to-feed
+test-db+
(assoc (dissoc blog-feed-updated :previous-id)
:action :delete))))
(is (thrown+? (partial check-exc :vix.db/feed-update-conflict)
(append-to-feed
+test-db+
(assoc blog-feed-updated
:action :delete
:previous-id (:previous-id blog-feed)))))
(let [deleted-feed (with-redefs [util/now-rfc3339
#(str "2012-09-04T04:30:18.010Z")]
(append-to-feed
+test-db+
(assoc blog-feed-updated
:action
:delete
:previous-id
(:_id blog-feed-updated))))]
(is (= (map #(dissoc % :_id :_rev :previous-id) deleted-feed)
[{:subtitle "Vix Weblog!"
:action :delete
:name "blog"
:language "en"
:title "Updated Weblog Feed"
:datestamp "2012-09-04T04:30:18.010Z"
:searchable true
:created "2012-09-04T04:30:17.872Z"
:type "feed"
:default-document-type "standard"
:default-slug-format "/{document-title}"}
{:subtitle "Vix Weblog!"
:action :update
:name "blog"
:language "en"
:title "Updated Weblog Feed"
:datestamp "2012-09-04T04:30:17.930Z"
:searchable true
:created "2012-09-04T04:30:17.872Z"
:type "feed"
:default-document-type "standard"
:default-slug-format "/{document-title}"}
{:subtitle "Vix Weblog!"
:action :create
:name "blog"
:language "en"
:title "Weblog"
:datestamp "2012-09-04T04:30:17.872Z"
:created "2012-09-04T04:30:17.872Z"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"}]))
(is (thrown+? (partial check-exc :vix.db/feed-already-deleted)
(append-to-feed
+test-db+
(assoc (first deleted-feed)
:action :delete
:previous-id (:_id (first deleted-feed))))))))))
(testing "test feed-already-exists-conflict"
(do
(append-to-feed +test-db+
{:subtitle "bar"
:action :create
:name "foobar"
:language "en"
:title "Foobar"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"}))
(is (thrown+? (partial check-exc :vix.db/feed-already-exists-conflict)
(append-to-feed
+test-db+
{:subtitle "bar"
:action :create
:name "foobar"
:language "en"
:title "Foobar"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"})))
(do
(append-to-feed +test-db+
{:subtitle "bar"
:action :delete
:previous-id (:_id
(first
(get-feed +test-db+ "en" "foobar")))
:name "foobar"
:language "en"
:title "Foobar"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"})
;; once the feed is deleted, it should be possible to recreate
(append-to-feed +test-db+
{:subtitle "bar"
:action :create
:name "foobar"
:language "en"
:title "Foobar"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"}))))
(deftest test-get-documents-for-feed
(let [doc-1 (append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/foo-0"
:content "bar"
:draft true})
doc-2 (append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/foo-1"
:content "bar"
:draft true})
doc-3 (append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "nl"
:feed "blog"
:title "foo"
:slug "/blog/foo-nl"
:content "bar"
:draft true})
feed (get-documents-for-feed +test-db+ "en" "blog")]
;; FIXME: should also test other possible argument combinations!
(is (= (count (:documents feed)) 2))
(is (= (:next feed) nil))
(is (some #{(first doc-1)} (:documents feed)))
(is (some #{(first doc-2)} (:documents feed))))
(testing "test pagination"
(let [now "2011-09-06T12:56:16.322Z"]
(dotimes [n 21]
(let [my-now (if (< n 7) ;; mix identical and unique datestamps
now
(util/now-rfc3339))]
(clutch/put-document +test-db+
{:action :create
:current-state true
:type "document"
:title (str "doc " n)
:slug (str "/pages/doc-" n)
:content ""
:draft false
:language "en"
:feed "pages"
:published my-now
:created my-now
:datestamp my-now}))))
(is (= (count (:documents (get-documents-for-feed +test-db+
"en"
"pages")))
21))
(let [first-five (get-documents-for-feed +test-db+ "en" "pages" 5)]
(is (= (count (:documents first-five)) 5))
(is (= (:title (nth (:documents first-five) 0)) "doc 20"))
(is (= (:title (nth (:documents first-five) 1)) "doc 19"))
(is (= (:title (nth (:documents first-five) 2)) "doc 18"))
(is (= (:title (nth (:documents first-five) 3)) "doc 17"))
(is (= (:title (nth (:documents first-five) 4)) "doc 16"))
(let [next-five (get-documents-for-feed +test-db+
"en"
"pages"
5
(:published (:next first-five))
(:startkey_docid
(:next first-five)))]
(is (= (count (:documents next-five)) 5))
(is (= (:title (nth (:documents next-five) 0)) "doc 15"))
(is (= (:title (nth (:documents next-five) 1)) "doc 14"))
(is (= (:title (nth (:documents next-five) 2)) "doc 13"))
(is (= (:title (nth (:documents next-five) 3)) "doc 12"))
(is (= (:title (nth (:documents next-five) 4)) "doc 11"))
(let [next-ten (get-documents-for-feed +test-db+
"en"
"pages"
10
(:published (:next next-five))
(:startkey_docid
(:next next-five)))]
(is (= (count (:documents next-ten)) 10))
(is (= (:title (nth (:documents next-ten) 0)) "doc 10"))
(is (= (:title (nth (:documents next-ten) 1)) "doc 9"))
(is (= (:title (nth (:documents next-ten) 2)) "doc 8"))
(is (= (:title (nth (:documents next-ten) 3)) "doc 7"))
(is (= (:title (nth (:documents next-ten) 4)) "doc 6"))
(is (= (:title (nth (:documents next-ten) 5)) "doc 5"))
(is (= (:title (nth (:documents next-ten) 6)) "doc 4"))
(is (= (:title (nth (:documents next-ten) 7)) "doc 3"))
(is (= (:title (nth (:documents next-ten) 8)) "doc 2"))
(is (= (:title (nth (:documents next-ten) 9)) "doc 1"))
(is (= (:published (nth (:documents next-ten) 4))
(:published (nth (:documents next-ten) 5))
(:published (nth (:documents next-ten) 6))
(:published (nth (:documents next-ten) 7))
(:published (nth (:documents next-ten) 7))
(:published (nth (:documents next-ten) 9))
"2011-09-06T12:56:16.322Z"))
(let [last-doc (get-documents-for-feed +test-db+
"en"
"pages"
1
(:published
(:next next-ten))
(:startkey_docid
(:next next-ten)))
x2 (get-documents-for-feed +test-db+
"en"
"pages"
10
(:published
(:next next-ten))
(:startkey_docid
(:next next-ten)))]
(is (= last-doc x2))
(is (nil? (:next last-doc)))
(is (= (:published (nth (:documents last-doc) 0))
"2011-09-06T12:56:16.322Z"))
(is (= (:title (nth (:documents last-doc) 0)) "doc 0"))))))))
(deftest test-list-feeds-and-list-feeds-by-default-document-type
(let [blog-feed (first
(append-to-feed
+test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:language "en"
:name "blog"
:default-slug-format
"/{feed-name}/{document-title}"
:default-document-type "with-description"}))
pages-feed (first
(append-to-feed
+test-db+
{:action :create
:title "Pages"
:subtitle "Web Pages"
:language "en"
:name "pages"
:default-slug-format "/{document-title}"
:default-document-type "standard"}))
images-feed (first
(append-to-feed
+test-db+
{:action :create
:title "Images"
:subtitle "Internal feed with images"
:language "en"
:name "images"
:default-slug-format
"/media/{document-title}"
:default-document-type "image"}))
blog-feed-nl (first
(append-to-feed
+test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:language "nl"
:name "blog"
:default-slug-format
"/{feed-name}/{document-title}"
:default-document-type
"with-description"}))
pages-feed-nl (first
(append-to-feed
+test-db+
{:action :create
:title "Pages"
:subtitle "Web Pages"
:language "nl"
:name "pages"
:default-slug-format "/{document-title}"
:default-document-type "standard"}))
;; do an update, to make sure only the most recent version is used
images-feed-nl (first
(append-to-feed
+test-db+
(let [images-feed-nl-0
(first
(append-to-feed
+test-db+
{:action :create
:title "Images"
:subtitle "Internal feed with images"
:language "nl"
:name "images"
:default-slug-format
"/media/{document-title}"
:default-document-type "image"}))]
(assoc images-feed-nl-0
:action :update
:previous-id (:_id images-feed-nl-0)))))]
(do
;; create and remove a feed, to make sure it isn't included
(append-to-feed
+test-db+
(let [feed-0
(first
(append-to-feed
+test-db+
{:action :create
:title "Images (deleted)"
:subtitle "Internal feed with images"
:language "en"
:name "images-delete"
:default-slug-format
"/media/{document-title}"
:default-document-type "image"}))]
(assoc feed-0
:action :delete
:previous-id (:_id feed-0)))))
(testing "test without providing a language"
(is (= [pages-feed-nl
images-feed-nl
blog-feed-nl
pages-feed
images-feed
blog-feed]
(list-feeds +test-db+))))
(testing "test with a language argument"
(is (= [pages-feed
images-feed
blog-feed]
(list-feeds +test-db+ "en")))
(is (= [pages-feed-nl
images-feed-nl
blog-feed-nl]
(list-feeds +test-db+ "nl"))))
(testing "test with default-document-type without a language argument"
(is (= (list-feeds-by-default-document-type +test-db+
"image")
[images-feed-nl images-feed])))
(testing "test with default-document-type and a language argument"
(is (= (list-feeds-by-default-document-type +test-db+
"image"
"en")
[images-feed]))
(is (= (list-feeds-by-default-document-type +test-db+
"image"
"nl")
[images-feed-nl])))))
(deftest test-append-to-document-create
(with-redefs [util/now-rfc3339 #(str "2012-09-16T00:17:30.722Z")]
(let [document (append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/foo"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})]
(is (couchdb-id? (:_id (first document))))
(is (couchdb-rev? (:_rev (first document))))
(is (= (vec (map #(dissoc % :_id :_rev) document))
[{:slug "/blog/foo"
:content "bar"
:action :create
:language "en"
:title "foo"
:start-time-rfc3339 "2012-02-21T00:19:00.000Z"
:published "2012-09-16T00:17:30.722Z"
:datestamp "2012-09-16T00:17:30.722Z"
:created "2012-09-16T00:17:30.722Z"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:type "document"
:feed "blog"
:draft false
:end-time-rfc3339 "2012-02-21T09:00:00.000Z"}]))))
;; make sure valid actions are enforced
(is (thrown+? (partial check-exc :vix.db/invalid-action)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :invalid
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/foo-action"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})))
(is (thrown+? (partial check-exc :vix.db/invalid-action)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:language "en"
:feed "blog"
:title "foo"
:slug "/blog/foo-action"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})))
;; non-keyword actions should work:
(append-to-document +test-db+
"Europe/Amsterdam"
{:action "create"
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/foo-action"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})
;; make sure existing documents don't get overwritten
(is (thrown+? (partial check-exc :vix.db/document-already-exists-conflict)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/foo"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})))
;; test without a :language key
(is (thrown+? (partial check-exc :vix.db/document-missing-required-keys)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:feed "blog"
:title "foo"
:slug "/blog/foobar"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})))
;; test without a :feed key
(is (thrown+? (partial check-exc :vix.db/document-missing-required-keys)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:title "foo"
:slug "/blog/foobar"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})))
;; test without a :slug key
(is (thrown+? (partial check-exc :vix.db/document-missing-required-keys)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})))
;; test without a :title key
(is (thrown+? (partial check-exc :vix.db/document-missing-required-keys)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:slug "/blog/foobar"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})))
(testing "Test if attachments are handled correctly."
(let [gif (str "R0lGODlhAQABA++/vQAAAAAAAAAA77+9AQIAAAAh77+9BAQUA++/"
"vQAsAAAAAAEAAQAAAgJEAQA7")
document (first
(append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:attachment {:type "image/gif"
:data gif}
:title "a single black pixel!"
:language "en"
:feed "images"
:slug "pixel.gif"
:content ""
:draft false}))]
(is (= (:original (:attachments document))
{:type "image/gif"
:length 57
:data (str "R0lGODlhAQABA++/vQAAAAAAAAAA77+9AQIAAAAh77+"
"9BAQUA++/vQAsAAAAAAEAAQAAAgJEAQA7")}))
(is (= (get-attachment-as-base64-string +test-db+
(:_id document)
:original)
gif)))))
(deftest test-append-to-document-update
(with-redefs [util/now-rfc3339 #(str "2012-09-16T02:51:47.588Z")]
(let [new-doc (append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:subtitle ""
:slug "/blog/bar"
:content "bar"
:description ""
:draft false
:icon nil
:related-pages []
:related-images []})
updated-doc (append-to-document
+test-db+
"Europe/Amsterdam"
{:action :update
:previous-id (:_id (first new-doc))
:language "en"
:feed "blog"
:slug "/blog/bar"
:title "hic sunt dracones"
:subtitle "old maps are cool!"
:description "hey!"
:draft true
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:icon {:title "cat" :slug "/cat.png"}
:related-pages [{:title "foo" :slug "bar"}]
:related-images [{:title "cat" :slug "cat.png"}]})]
(is (= (get-document +test-db+ "/blog/bar") updated-doc))
(is (couchdb-rev? 1 (:_rev (first updated-doc))))
(is (couchdb-id? (:previous-id (first updated-doc))))
(is (= (map #(dissoc % :_id :_rev :previous-id) updated-doc)
[{:subtitle "old maps are cool!"
:slug "/blog/bar"
:icon {:slug "/cat.png"
:title "cat"}
:action :update
:related-images [{:slug "cat.png"
:title "cat"}]
:language "en"
:title "hic sunt dracones"
:start-time-rfc3339 "2012-02-21T00:19:00.000Z"
:published "2012-09-16T02:51:47.588Z"
:datestamp "2012-09-16T02:51:47.588Z"
:created "2012-09-16T02:51:47.588Z"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:type "document"
:feed "blog"
:draft true
:related-pages [{:slug "bar"
:title "foo"}]
:description "hey!"
:end-time-rfc3339 "2012-02-21T09:00:00.000Z"}
{:subtitle ""
:slug "/blog/bar"
:icon nil
:content "bar"
:action :create
:related-images []
:language "en"
:title "foo"
:published "2012-09-16T02:51:47.588Z"
:datestamp "2012-09-16T02:51:47.588Z"
:created "2012-09-16T02:51:47.588Z"
:type "document"
:feed "blog"
:draft false
:related-pages []
:description ""}]))
;; make sure that the internal current-state flag is removed
;; from non-current document states (this non-public flag is
;; used for overview views that show e.g. the most recent states
;; for documents in a specific feed).
(is (= (:current-state
(clutch/get-document +test-db+ (get-in updated-doc [0 :_id])))
true))
(is (= (:current-state
(clutch/get-document +test-db+ (get-in updated-doc [1 :_id])))
false))
;; test with expired :previous-id
(is (thrown+? (partial check-exc :vix.db/document-update-conflict)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :update
:previous-id (:_id (first new-doc))
:language "en"
:feed "blog"
:slug "/blog/bar"
:title "hic sunt dracones"
:subtitle "old maps are cool!"
:description "hey!"
:draft true
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:icon {:title "cat" :slug "/cat.png"}
:related-pages [{:title "foo" :slug "bar"}]
:related-images [{:title "cat" :slug "cat.png"}]})))
;; test without :previous-id
(is (thrown+? (partial check-exc :vix.db/document-update-conflict)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :update
:language "en"
:feed "blog"
:slug "/blog/bar"
:title "hic sunt dracones"
:subtitle "old maps are cool!"
:description "hey!"
:draft true
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:icon {:title "cat" :slug "/cat.png"}
:related-pages [{:title "foo" :slug "bar"}]
:related-images [{:title "cat" :slug "cat.png"}]})))
;; make sure that passing couchdb-options works (useful for
;; limiting returned states on frequently updated image
;; documents).
(is (= (map #(dissoc % :_rev :_id :previous-id)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :update
:previous-id (:_id (first (get-document +test-db+
"/blog/bar")))
:language "en"
:feed "blog"
:slug "/blog/bar"
:title "here be dragons"
:subtitle "old maps are cool!"
:description "hey!"
:draft true
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:icon {:title "cat" :slug "/cat.png"}
:related-pages [{:title "foo" :slug "bar"}]
:related-images [{:title "cat" :slug "cat.png"}]}
{:limit 1}))
[{:subtitle "old maps are cool!"
:slug "/blog/bar"
:icon {:slug "/cat.png"
:title "cat"}
:action :update
:related-images [{:slug "cat.png"
:title "cat"}]
:language "en"
:title "here be dragons"
:start-time-rfc3339 "2012-02-21T00:19:00.000Z"
:datestamp "2012-09-16T02:51:47.588Z"
:created "2012-09-16T02:51:47.588Z"
:published "2012-09-16T02:51:47.588Z"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:type "document"
:feed "blog"
:draft true
:related-pages [{:slug "bar"
:title "foo"}]
:description "hey!"
:end-time-rfc3339 "2012-02-21T09:00:00.000Z"}]))))
(testing "Test if attachments are handled correctly."
(let [black-pixel
(str "R0lGODlhAQABA++/vQAAAAAAAAAA77+9AQIAAAAh77+9BAQU"
"A++/vQAsAAAAAAEAAQAAAgJEAQA7")
white-pixel
(str "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJ"
"CQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcp"
"LDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwh"
"MjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy"
"MjIyMjIyMjIyMjIyMjL/wAARCAABAAEDASIAAhEBAxEB/8QA"
"HwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAA"
"AgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKB"
"kaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6"
"Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWG"
"h4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXG"
"x8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QA"
"HwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREA"
"AgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEI"
"FEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5"
"OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOE"
"hYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPE"
"xcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oA"
"DAMBAAIRAxEAPwD3+iiigD//2Q==")
new-doc
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:attachment {:type "image/jpeg" :data white-pixel}
:language "en"
:feed "images"
:slug "/pixel.jpeg"
:title "a single white pixel!"
:content ""
:draft false})
updated-doc
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :update
:attachment {:type "image/gif" :data black-pixel}
:previous-id (:_id (first new-doc))
:language "en"
:feed "images"
:slug "/pixel.jpeg"
:title "a single black pixel!"
:content ""
:draft false})]
;; check if the image has actually been updated:
(is (= (get-in updated-doc [0 :attachments])
{:original {:type "image/gif"
:length 57
:data black-pixel}}))
;; The attachment for the previous state should also be included
;; in the result of the update action.
(is (= (get-in updated-doc [1 :attachments])
{:original {:type "image/jpeg"
:length 631
:data white-pixel}}))
(is (= (get-attachment-as-base64-string +test-db+
(:_id (first updated-doc))
:original)
black-pixel)))))
(deftest test-append-to-document-delete
(with-redefs [util/now-rfc3339 #(str "2012-09-16T03:43:20.953Z")]
(let [doc (append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:slug "/blog/bar"
:title "foo"
:content "bar"
:draft false})]
(is (not (nil? (first (get-document +test-db+ "/blog/bar"))))
"Assure the document exists before it is deleted.")
(is (= (map #(dissoc % :_id :_rev :previous-id)
(append-to-document +test-db+
"Europe/Amsterdam"
{:action :delete
:previous-id (:_id (first doc))
:language "en"
:feed "blog"
:slug "/blog/bar"
:title "foo"
:content "bar"
:draft false}))
[{:slug "/blog/bar"
:content "bar"
:action :delete
:language "en"
:title "foo"
:published "2012-09-16T03:43:20.953Z"
:datestamp "2012-09-16T03:43:20.953Z"
:created "2012-09-16T03:43:20.953Z"
:type "document"
:feed "blog"
:draft false}
{:slug "/blog/bar"
:content "bar"
:action :create
:language "en"
:title "foo"
:published "2012-09-16T03:43:20.953Z"
:datestamp "2012-09-16T03:43:20.953Z"
:created "2012-09-16T03:43:20.953Z"
:type "document"
:feed "blog"
:draft false}]))
;; make sure documents can't be deleted twice
(is (thrown+? (partial check-exc :vix.db/document-already-deleted)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :delete
:previous-id (:_id
(first
(get-document +test-db+
"/blog/bar")))
:language "en"
:feed "blog"
:slug "/blog/bar"
:title "foo"
:content "bar"
:draft false}))))))
(deftest test-get-available-languages
(do
(append-to-feed +test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:language "en"
:searchable true})
(append-to-feed +test-db+
{:action :create
:title "Images"
:subtitle "Images"
:name "images"
:language "en"
:searchable true})
(append-to-feed +test-db+
{:action :create
:title "Menu"
:subtitle "Menu"
:name "menu"
:language "en"
:searchable false})
(append-to-feed +test-db+
{:action :create
:title "Weblog"
:name "blog"
:language "nl"
:searchable true})
(append-to-feed +test-db+
{:action :create
:title "Weblog"
:name "blog"
:language "de"
:searchable true})
(append-to-feed +test-db+
{:action :delete
:previous-id (:_id
(first
(get-feed +test-db+ "de" "blog")))
:title "Weblog"
:name "blog"
:language "de"
:searchable true}))
(is (= (get-available-languages +test-db+) ["en" "nl"])))
(deftest test-get-languages
(do
(append-to-feed +test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:language "en"
:searchable true})
(append-to-feed +test-db+
{:action :create
:title "Images"
:subtitle "Images"
:name "images"
:language "en"
:searchable true})
(append-to-feed +test-db+
{:action :create
:title "Menu"
:subtitle "Menu"
:name "menu"
:language "en"
:searchable false})
(append-to-feed +test-db+
{:action :create
:title "Weblog"
:name "blog"
:language "nl"
:searchable true})
(append-to-feed +test-db+
{:action :create
:title "Weblog"
:name "blog"
:language "de"
:searchable true})
(append-to-feed +test-db+
{:action :delete
:previous-id (:_id
(first
(get-feed +test-db+ "de" "blog")))
:title "Weblog"
:name "blog"
:language "de"
:searchable true}))
(is (= (get-languages (list-feeds +test-db+)) #{"en" "nl"})))
(deftest test-get-searchable-feeds
(do
(append-to-feed +test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:language "en"
:searchable true})
(append-to-feed +test-db+
{:action :create
:title "Images"
:subtitle "Images"
:name "images"
:language "en"
:searchable true})
(append-to-feed +test-db+
{:action :create
:title "Menu"
:subtitle "Menu"
:name "menu"
:language "en"
:searchable false})
(append-to-feed +test-db+
{:action :create
:title "Weblog"
:name "blog"
:language "nl"
:searchable true}))
(is (= (get-searchable-feeds (list-feeds +test-db+))
{"nl" ["blog"]
"en" ["images" "blog"]})))
(deftest test-get-most-recent-event-documents
(let [doc-1 (append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"events"
:title
"Tomasz Stańko Middelburg"
:slug
"/en/events/stanko-middelburg"
:content
(str "The legendary Polish trumpet "
"player Stańko will be playing "
"in Middelburg.")
:start-time
"2012-04-25 20:30"
:end-time
"2012-04-25 23:59"
:draft false})
doc-2 (append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"events"
:title
"The Impossible Gentlemen"
:slug
(str "/en/events/impossible-gentlemen"
"-amsterdam")
:content
(str "Gwilym Simcock, Mike Walker, "
"Adam Nussbaum, Steve Swallow "
"will be playing at the Bimhuis "
"in Amsterdam.")
:start-time
"2012-07-06 20:30"
:end-time
"2012-07-06 23:59"
:draft false})
doc-3 (append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"events"
:title
"Yuri Honing"
:slug
"/en/events/yuri-honing-tilburg"
:content
(str "VPRO/Boy Edgar prize winner "
"Yuri Honing will be playing at "
"the Paradox venue in Tilburg.")
:start-time
"2013-02-01 20:30"
:end-time
"2013-02-01 23:59"
:draft false})]
(is (= (get-most-recent-event-documents +test-db+
"en"
"events")
(get-most-recent-event-documents +test-db+
"en"
"events"
nil)
(map first [doc-3 doc-2 doc-1])))
;; when limited, the fn retrieves (inc limit)
(is (= (get-most-recent-event-documents +test-db+
"en"
"events"
1)
[(first doc-3)])))) | 24698 | ;; test/vix/test/db.clj tests for db namespace.
;; Copyright 2011-2012, Vixu.com, <NAME>. (<NAME> <<EMAIL>>.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns vix.test.db
(:use [vix.db] :reload
[vix.test.test]
[slingshot.test]
[clojure.test]
[clojure.data.json :only [read-json]])
(:require [com.ashafa.clutch :as clutch]
[clj-http.client :as http]
[vix.util :as util])
(:import [org.apache.commons.codec.binary Base64]))
(defn couchdb-id? [s]
(re-matches #"^[a-z0-9]{32}$" s))
(defn couchdb-rev?
([s]
(couchdb-rev? 1 s))
([rev-num s]
(re-matches (re-pattern (str "^" rev-num "-[a-z0-9]{32}$")) s)))
(defn iso-date? [s]
(re-matches
#"^[\d]{4}-[\d]{2}-[\d]{2}T[\d]{2}:[\d]{2}:[\d]{2}\.[\d]{1,4}Z"
s))
(defn random-lower-case-string [length]
;; to include uppercase
;; (let [ascii-codes (concat (range 48 58) (range 66 91) (range 97 123))])
(let [ascii-codes (concat (range 48 58) (range 97 123))]
(apply str (repeatedly length #(char (rand-nth ascii-codes))))))
(def +test-db+ (str "vix-test-" (random-lower-case-string 20)))
(def +test-server+ "http://localhost:5984/")
(defn database-fixture [f]
(clutch/get-database +test-db+)
(f)
(clutch/delete-database +test-db+))
(use-fixtures :each database-fixture)
(deftest test-load-view
(is (= (load-view "database-views/map_newsletter_subscribers.js")
(str "function(doc) {\n"
" if(doc.type === \"newsletter-subscriber\") {\n"
" emit([doc.language, doc.email], doc);\n"
" }\n}\n"))))
(deftest test-create-views
(create-views +test-db+ "views" views)
(let [view-doc (read-json (:body (http/get
(str +test-server+
+test-db+
"/_design/views"))))]
(is (= (count (:views view-doc)) 9))
(is (= (:map (:feeds (:views view-doc)))
(str "function(feed) {\n"
" if(feed.type === \"feed\") {\n"
" emit([feed.language, feed.name, feed.datestamp]"
", feed);\n }\n}\n")))
(is (= (:map (:feeds_by_default_document_type (:views view-doc)))
(str "function(feed) {\n"
" if(feed.type === \"feed\" &&\n"
" feed[\"current-state\"] === true &&\n"
" feed.action !== \"delete\") {\n"
" emit([feed[\"default-document-type\"],\n"
" feed[\"language\"],\n"
" feed[\"name\"]],\n"
" feed);\n"
" }\n}\n")))
(is (= (:map (:feeds_overview (:views view-doc)))
(str "function(feed) {\n"
" if(feed.type === \"feed\" &&\n"
" feed[\"current-state\"] === true &&\n"
" feed.action !== \"delete\") {\n"
" emit([feed.language, feed.name, feed.datestamp],"
" feed);\n"
" }\n}\n")))
(is (= (:map (:by_slug (:views view-doc)))
(str "function(doc) {\n"
" if(doc.type === \"document\") {\n"
" emit([doc.slug, doc.datestamp], doc);\n"
" }\n}\n")))
(is (= (:map (:by_feed (:views view-doc)))
(str "function(doc) {\n"
" if(doc.type === \"document\" &&\n"
" doc[\"current-state\"] === true &&\n"
" doc.action !== \"delete\") {\n"
" emit([[doc.language, doc.feed], doc.published], "
"doc);\n"
" }\n}\n")))
(is (= (:map (:by_username (:views view-doc)))
(str "function(doc) {\n"
" if(doc.type === \"user\") {\n"
" emit(doc.username, doc);\n"
" }\n"
"}\n")))
(is (= (:map (:events_by_feed (:views view-doc)))
(str "function(doc) {\n"
" if(doc.type === \"document\" &&\n"
" doc[\"end-time-rfc3339\"] &&\n"
" doc[\"current-state\"] === true) {\n"
" emit([[doc.language, doc.feed], "
"doc[\"end-time-rfc3339\"]], doc);\n }\n}\n")))
(is (= (:map (:subscribers (:views view-doc)))
(str "function(doc) {\n"
" if(doc.type === \"newsletter-subscriber\") {\n"
" emit([doc.language, doc.email], doc);\n"
" }\n}\n")))
(is (= (:map (:languages (:views view-doc)))
(str "function(feed) {\n"
" if(feed.type === \"feed\" &&\n"
" feed[\"current-state\"] === true &&\n"
" feed.action !== \"delete\") {\n"
" emit(feed.language, null);\n"
" }\n}\n")))
(is (= (:reduce (:languages (:views view-doc)))
"function(k,v) {\n return null;\n}\n")))
(is (thrown+? (partial check-exc :vix.db/database-socket-error)
(create-views "http://localhost:9999/foo" "bar" views))))
(deftest test-get-attachment-as-base64-string
(let [gif (str "R0lGODlhAQABA++/vQAAAAAAAAAA77+9AQIAAAAh77+9BAQUA++/"
"vQAsAAAAAAEAAQAAAgJEAQA7")
document (append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:attachment {:type "image/gif"
:data gif}
:feed "images"
:language "en"
:title "a single black pixel!"
:slug "pixel.gif"
:content ""
:draft false})]
(is (= (get-attachment-as-base64-string +test-db+
(:_id (first document))
:original)
gif))))
(deftest test-get-document
(is (nil? (get-document +test-db+ "/blog/foo")))
(is (nil? (get-document +test-db+ "/blog/foo" {:limit 100000})))
(with-redefs [util/now-rfc3339 #(str "2012-09-15T23:48:58.050Z")]
(append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:title "foo"
:slug "/blog/foo"
:language "en"
:feed "blog"
:content "bar"
:draft true})
(append-to-document +test-db+
"Europe/Amsterdam"
{:action :update
:previous-id (:_id
(first
(get-document
+test-db+
"/blog/foo")))
:title "foo"
:slug "/blog/foo"
:language "en"
:feed "blog"
:content "bar"
:draft false}))
;; The view isn't created manually; successful execution of
;; this test also implies that it is created automatically.
(is (couchdb-id? (:_id (first (get-document +test-db+ "/blog/foo")))))
(is (couchdb-rev? (:_rev (first (get-document +test-db+ "/blog/foo")))))
(is (= (vec (map #(dissoc % :_id :_rev :previous-id)
(get-document +test-db+ "/blog/foo")))
[{:slug "/blog/foo"
:content "bar"
:action :update
:language "en"
:title "foo"
:published "2012-09-15T23:48:58.050Z"
:datestamp "2012-09-15T23:48:58.050Z"
:created "2012-09-15T23:48:58.050Z"
:type "document"
:feed "blog"
:draft false}
{:slug "/blog/foo"
:content "bar"
:action :create
:language "en"
:title "foo"
:published "2012-09-15T23:48:58.050Z"
:datestamp "2012-09-15T23:48:58.050Z"
:created "2012-09-15T23:48:58.050Z"
:type "document"
:feed "blog"
:draft true}]))
(is (= (vec (map #(dissoc % :_id :_rev :previous-id)
(get-document +test-db+ "/blog/foo" {:limit 1})))
[{:slug "/blog/foo"
:content "bar"
:action :update
:language "en"
:title "foo"
:published "2012-09-15T23:48:58.050Z"
:datestamp "2012-09-15T23:48:58.050Z"
:created "2012-09-15T23:48:58.050Z"
:type "document"
:feed "blog"
:draft false}]))
(testing "Test if attachments are handled correctly."
(let [gif (str "R0lGODlhAQABA++/vQAAAAAAAAAA77+9AQIAAAAh77+9BAQUA++/"
"vQAsAAAAAAEAAQAAAgJEAQA7")]
(do
(append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:attachment {:type "image/gif" :data gif}
:title "a single black pixel!"
:slug "/images/white-pixel.gif"
:language "en"
:feed "images"
:content ""
:draft false})
(append-to-document +test-db+
"Europe/Amsterdam"
{:action :update
:previous-id (:_id
(first
(get-document
+test-db+
"/images/white-pixel.gif")))
:attachment {:type "image/gif" :data gif}
:title "a single black pixel!"
:slug "/images/white-pixel.gif"
:language "en"
:feed "images"
:content ""
:draft false})
(append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:title "not a single black pixel!"
:slug "/images/not-a-white-pixel.gif"
:language "en"
:feed "images"
:content ""
:draft false}))
(is (= (get-in (get-document +test-db+ "/images/white-pixel.gif")
[0 :attachments :original])
(get-in (get-document +test-db+ "/images/white-pixel.gif")
[1 :attachments :original])
{:type "image/gif" :data gif :length 57})))))
(deftest test-get-feed
(with-redefs [util/now-rfc3339 #(str "2012-09-04T03:46:52.096Z")]
(let [en-feed (append-to-feed
+test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "en"})
nl-feed (append-to-feed
+test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "nl"})
nl-feed-update-0 (with-redefs
[util/now-rfc3339
#(str "2012-09-04T03:50:52.096Z")]
(append-to-feed
+test-db+
{:action :update
:previous-id (:_id (first nl-feed))
:title "B1"
:subtitle "b1!"
:name "blog"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "nl"}))
nl-feed-update-1 (with-redefs
[util/now-rfc3339
#(str "2012-09-04T03:55:52.096Z")]
(append-to-feed
+test-db+
{:action :update
:previous-id (:_id (first nl-feed-update-0))
:title "B2"
:subtitle "b2!"
:name "blog"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "nl"}))]
(is (= (map #(dissoc % :_id :_rev) (get-feed +test-db+ "en" "blog"))
[{:subtitle "Vix Weblog!"
:action :create
:name "blog"
:language "en"
:title "Weblog"
:datestamp "2012-09-04T03:46:52.096Z"
:created "2012-09-04T03:46:52.096Z"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"}]))
(is (couchdb-id? (:_id (first (get-feed +test-db+ "en" "blog")))))
(is (couchdb-rev? (:_rev (first (get-feed +test-db+ "en" "blog")))))
(is (= (map #(dissoc % :_id :_rev :previous-id)
(get-feed +test-db+ "nl" "blog"))
[{:subtitle "b2!"
:action :update
:name "blog"
:language "nl"
:title "B2"
:datestamp "2012-09-04T03:55:52.096Z"
:created "2012-09-04T03:46:52.096Z"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"}
{:subtitle "b1!"
:action :update
:name "blog"
:language "nl"
:title "B1"
:datestamp "2012-09-04T03:50:52.096Z"
:created "2012-09-04T03:46:52.096Z"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"}
{:subtitle "Vix Weblog!"
:action :create
:name "blog"
:language "nl"
:title "Weblog"
:datestamp "2012-09-04T03:46:52.096Z"
:created "2012-09-04T03:46:52.096Z"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"}]))
(is (= (map #(dissoc % :_id :_rev :previous-id)
(get-feed +test-db+ "nl" "blog" 1))
[{:subtitle "b2!"
:action :update
:name "blog"
:language "nl"
:title "B2"
:datestamp "2012-09-04T03:55:52.096Z"
:created "2012-09-04T03:46:52.096Z"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"}]))
(let [blog-states (get-feed +test-db+ "nl" "blog")]
(are [n]
(couchdb-id? (:_id (nth blog-states n)))
0 1 2)
(are [rev-number n]
(couchdb-rev? rev-number (:_rev (nth blog-states n)))
1 0
2 1
2 2)))))
(deftest test-append-to-feed
(let [blog-feed (with-redefs [util/now-rfc3339
#(str "2012-09-04T04:30:17.872Z")]
(first
(append-to-feed
+test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:language "en"
:default-slug-format "/{document-title}"
:default-document-type "with-description"})))]
(testing "test create action"
(is (= (:type blog-feed) "feed"))
(is (couchdb-id? (:_id blog-feed)))
(is (couchdb-rev? (:_rev blog-feed)))
(is (iso-date? (:created blog-feed)))
(is (= (:title blog-feed) "Weblog"))
(is (= (:subtitle blog-feed) "Vix Weblog!"))
(is (= (:name blog-feed) "blog"))
(is (= (:language blog-feed) "en"))
(is (= (:default-slug-format blog-feed) "/{document-title}"))
(is (= (:default-document-type blog-feed) "with-description")))
;; make sure that invalid actions aren't allowed
(is (thrown+? (partial check-exc :vix.db/invalid-action)
(append-to-feed
+test-db+
(assoc blog-feed
:action :invalid
:previous-id (:_id blog-feed)
:title "Updated Weblog Feed"
:default-document-type "standard"
:searchable true))))
(is (thrown+? (partial check-exc :vix.db/invalid-action)
(append-to-feed
+test-db+
(dissoc (assoc blog-feed
:previous-id (:_id blog-feed)
:title "Updated Weblog Feed"
:default-document-type "standard"
:searchable true)
:action))))
;; a non-keyword action should work:
(append-to-feed
+test-db+
{:action :create
:title "Weblog"
:subtitle "Another Weblog!"
:name "another-blog"
:language "en"
:default-slug-format "/{document-title}"
:default-document-type "with-description"})
(let [blog-feed-updated (with-redefs [util/now-rfc3339
#(str "2012-09-04T04:30:17.930Z")]
(first
(append-to-feed
+test-db+
(assoc blog-feed
:action :update
:previous-id (:_id blog-feed)
:title "Updated Weblog Feed"
:default-document-type "standard"
:searchable true))))]
(testing "test update action"
(is (= (first (get-feed +test-db+ "en" "blog")) blog-feed-updated))
(is (couchdb-rev? (:_rev blog-feed-updated)))
(is (iso-date? (:datestamp blog-feed-updated)))
(is (= (:created blog-feed) (:created blog-feed-updated)))
(is (= (:title blog-feed-updated) "Updated Weblog Feed"))
(is (= (:subtitle blog-feed-updated) "Vix Weblog!"))
(is (= (:language blog-feed-updated) "en"))
(is (= (:name blog-feed-updated) "blog")) ; NB: not updated!
(is (= (:default-slug-format blog-feed-updated) "/{document-title}"))
(is (= (:default-document-type blog-feed-updated) "standard"))
(is (= (:searchable blog-feed-updated) true))
(is (thrown+? (partial check-exc :vix.db/feed-update-conflict)
(append-to-feed
+test-db+
(assoc blog-feed
:action :update))))
(is (thrown+? (partial check-exc :vix.db/feed-update-conflict)
(append-to-feed
+test-db+
(assoc blog-feed
:action :update
:previous-id (:previous-id blog-feed))))))
(testing "test delete action"
(is (not (nil? (get-feed +test-db+ "en" "blog")))
"Assure the feed exists before it is deleted.")
(is (thrown+? (partial check-exc :vix.db/feed-update-conflict)
(append-to-feed
+test-db+
(assoc (dissoc blog-feed-updated :previous-id)
:action :delete))))
(is (thrown+? (partial check-exc :vix.db/feed-update-conflict)
(append-to-feed
+test-db+
(assoc blog-feed-updated
:action :delete
:previous-id (:previous-id blog-feed)))))
(let [deleted-feed (with-redefs [util/now-rfc3339
#(str "2012-09-04T04:30:18.010Z")]
(append-to-feed
+test-db+
(assoc blog-feed-updated
:action
:delete
:previous-id
(:_id blog-feed-updated))))]
(is (= (map #(dissoc % :_id :_rev :previous-id) deleted-feed)
[{:subtitle "Vix Weblog!"
:action :delete
:name "blog"
:language "en"
:title "Updated Weblog Feed"
:datestamp "2012-09-04T04:30:18.010Z"
:searchable true
:created "2012-09-04T04:30:17.872Z"
:type "feed"
:default-document-type "standard"
:default-slug-format "/{document-title}"}
{:subtitle "Vix Weblog!"
:action :update
:name "blog"
:language "en"
:title "Updated Weblog Feed"
:datestamp "2012-09-04T04:30:17.930Z"
:searchable true
:created "2012-09-04T04:30:17.872Z"
:type "feed"
:default-document-type "standard"
:default-slug-format "/{document-title}"}
{:subtitle "Vix Weblog!"
:action :create
:name "blog"
:language "en"
:title "Weblog"
:datestamp "2012-09-04T04:30:17.872Z"
:created "2012-09-04T04:30:17.872Z"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"}]))
(is (thrown+? (partial check-exc :vix.db/feed-already-deleted)
(append-to-feed
+test-db+
(assoc (first deleted-feed)
:action :delete
:previous-id (:_id (first deleted-feed))))))))))
(testing "test feed-already-exists-conflict"
(do
(append-to-feed +test-db+
{:subtitle "bar"
:action :create
:name "foobar"
:language "en"
:title "Foobar"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"}))
(is (thrown+? (partial check-exc :vix.db/feed-already-exists-conflict)
(append-to-feed
+test-db+
{:subtitle "bar"
:action :create
:name "foobar"
:language "en"
:title "Foobar"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"})))
(do
(append-to-feed +test-db+
{:subtitle "bar"
:action :delete
:previous-id (:_id
(first
(get-feed +test-db+ "en" "foobar")))
:name "foobar"
:language "en"
:title "Foobar"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"})
;; once the feed is deleted, it should be possible to recreate
(append-to-feed +test-db+
{:subtitle "bar"
:action :create
:name "foobar"
:language "en"
:title "Foobar"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"}))))
(deftest test-get-documents-for-feed
(let [doc-1 (append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/foo-0"
:content "bar"
:draft true})
doc-2 (append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/foo-1"
:content "bar"
:draft true})
doc-3 (append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "nl"
:feed "blog"
:title "foo"
:slug "/blog/foo-nl"
:content "bar"
:draft true})
feed (get-documents-for-feed +test-db+ "en" "blog")]
;; FIXME: should also test other possible argument combinations!
(is (= (count (:documents feed)) 2))
(is (= (:next feed) nil))
(is (some #{(first doc-1)} (:documents feed)))
(is (some #{(first doc-2)} (:documents feed))))
(testing "test pagination"
(let [now "2011-09-06T12:56:16.322Z"]
(dotimes [n 21]
(let [my-now (if (< n 7) ;; mix identical and unique datestamps
now
(util/now-rfc3339))]
(clutch/put-document +test-db+
{:action :create
:current-state true
:type "document"
:title (str "doc " n)
:slug (str "/pages/doc-" n)
:content ""
:draft false
:language "en"
:feed "pages"
:published my-now
:created my-now
:datestamp my-now}))))
(is (= (count (:documents (get-documents-for-feed +test-db+
"en"
"pages")))
21))
(let [first-five (get-documents-for-feed +test-db+ "en" "pages" 5)]
(is (= (count (:documents first-five)) 5))
(is (= (:title (nth (:documents first-five) 0)) "doc 20"))
(is (= (:title (nth (:documents first-five) 1)) "doc 19"))
(is (= (:title (nth (:documents first-five) 2)) "doc 18"))
(is (= (:title (nth (:documents first-five) 3)) "doc 17"))
(is (= (:title (nth (:documents first-five) 4)) "doc 16"))
(let [next-five (get-documents-for-feed +test-db+
"en"
"pages"
5
(:published (:next first-five))
(:startkey_docid
(:next first-five)))]
(is (= (count (:documents next-five)) 5))
(is (= (:title (nth (:documents next-five) 0)) "doc 15"))
(is (= (:title (nth (:documents next-five) 1)) "doc 14"))
(is (= (:title (nth (:documents next-five) 2)) "doc 13"))
(is (= (:title (nth (:documents next-five) 3)) "doc 12"))
(is (= (:title (nth (:documents next-five) 4)) "doc 11"))
(let [next-ten (get-documents-for-feed +test-db+
"en"
"pages"
10
(:published (:next next-five))
(:startkey_docid
(:next next-five)))]
(is (= (count (:documents next-ten)) 10))
(is (= (:title (nth (:documents next-ten) 0)) "doc 10"))
(is (= (:title (nth (:documents next-ten) 1)) "doc 9"))
(is (= (:title (nth (:documents next-ten) 2)) "doc 8"))
(is (= (:title (nth (:documents next-ten) 3)) "doc 7"))
(is (= (:title (nth (:documents next-ten) 4)) "doc 6"))
(is (= (:title (nth (:documents next-ten) 5)) "doc 5"))
(is (= (:title (nth (:documents next-ten) 6)) "doc 4"))
(is (= (:title (nth (:documents next-ten) 7)) "doc 3"))
(is (= (:title (nth (:documents next-ten) 8)) "doc 2"))
(is (= (:title (nth (:documents next-ten) 9)) "doc 1"))
(is (= (:published (nth (:documents next-ten) 4))
(:published (nth (:documents next-ten) 5))
(:published (nth (:documents next-ten) 6))
(:published (nth (:documents next-ten) 7))
(:published (nth (:documents next-ten) 7))
(:published (nth (:documents next-ten) 9))
"2011-09-06T12:56:16.322Z"))
(let [last-doc (get-documents-for-feed +test-db+
"en"
"pages"
1
(:published
(:next next-ten))
(:startkey_docid
(:next next-ten)))
x2 (get-documents-for-feed +test-db+
"en"
"pages"
10
(:published
(:next next-ten))
(:startkey_docid
(:next next-ten)))]
(is (= last-doc x2))
(is (nil? (:next last-doc)))
(is (= (:published (nth (:documents last-doc) 0))
"2011-09-06T12:56:16.322Z"))
(is (= (:title (nth (:documents last-doc) 0)) "doc 0"))))))))
(deftest test-list-feeds-and-list-feeds-by-default-document-type
(let [blog-feed (first
(append-to-feed
+test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:language "en"
:name "blog"
:default-slug-format
"/{feed-name}/{document-title}"
:default-document-type "with-description"}))
pages-feed (first
(append-to-feed
+test-db+
{:action :create
:title "Pages"
:subtitle "Web Pages"
:language "en"
:name "pages"
:default-slug-format "/{document-title}"
:default-document-type "standard"}))
images-feed (first
(append-to-feed
+test-db+
{:action :create
:title "Images"
:subtitle "Internal feed with images"
:language "en"
:name "images"
:default-slug-format
"/media/{document-title}"
:default-document-type "image"}))
blog-feed-nl (first
(append-to-feed
+test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:language "nl"
:name "blog"
:default-slug-format
"/{feed-name}/{document-title}"
:default-document-type
"with-description"}))
pages-feed-nl (first
(append-to-feed
+test-db+
{:action :create
:title "Pages"
:subtitle "Web Pages"
:language "nl"
:name "pages"
:default-slug-format "/{document-title}"
:default-document-type "standard"}))
;; do an update, to make sure only the most recent version is used
images-feed-nl (first
(append-to-feed
+test-db+
(let [images-feed-nl-0
(first
(append-to-feed
+test-db+
{:action :create
:title "Images"
:subtitle "Internal feed with images"
:language "nl"
:name "images"
:default-slug-format
"/media/{document-title}"
:default-document-type "image"}))]
(assoc images-feed-nl-0
:action :update
:previous-id (:_id images-feed-nl-0)))))]
(do
;; create and remove a feed, to make sure it isn't included
(append-to-feed
+test-db+
(let [feed-0
(first
(append-to-feed
+test-db+
{:action :create
:title "Images (deleted)"
:subtitle "Internal feed with images"
:language "en"
:name "images-delete"
:default-slug-format
"/media/{document-title}"
:default-document-type "image"}))]
(assoc feed-0
:action :delete
:previous-id (:_id feed-0)))))
(testing "test without providing a language"
(is (= [pages-feed-nl
images-feed-nl
blog-feed-nl
pages-feed
images-feed
blog-feed]
(list-feeds +test-db+))))
(testing "test with a language argument"
(is (= [pages-feed
images-feed
blog-feed]
(list-feeds +test-db+ "en")))
(is (= [pages-feed-nl
images-feed-nl
blog-feed-nl]
(list-feeds +test-db+ "nl"))))
(testing "test with default-document-type without a language argument"
(is (= (list-feeds-by-default-document-type +test-db+
"image")
[images-feed-nl images-feed])))
(testing "test with default-document-type and a language argument"
(is (= (list-feeds-by-default-document-type +test-db+
"image"
"en")
[images-feed]))
(is (= (list-feeds-by-default-document-type +test-db+
"image"
"nl")
[images-feed-nl])))))
(deftest test-append-to-document-create
(with-redefs [util/now-rfc3339 #(str "2012-09-16T00:17:30.722Z")]
(let [document (append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/foo"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})]
(is (couchdb-id? (:_id (first document))))
(is (couchdb-rev? (:_rev (first document))))
(is (= (vec (map #(dissoc % :_id :_rev) document))
[{:slug "/blog/foo"
:content "bar"
:action :create
:language "en"
:title "foo"
:start-time-rfc3339 "2012-02-21T00:19:00.000Z"
:published "2012-09-16T00:17:30.722Z"
:datestamp "2012-09-16T00:17:30.722Z"
:created "2012-09-16T00:17:30.722Z"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:type "document"
:feed "blog"
:draft false
:end-time-rfc3339 "2012-02-21T09:00:00.000Z"}]))))
;; make sure valid actions are enforced
(is (thrown+? (partial check-exc :vix.db/invalid-action)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :invalid
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/foo-action"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})))
(is (thrown+? (partial check-exc :vix.db/invalid-action)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:language "en"
:feed "blog"
:title "foo"
:slug "/blog/foo-action"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})))
;; non-keyword actions should work:
(append-to-document +test-db+
"Europe/Amsterdam"
{:action "create"
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/foo-action"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})
;; make sure existing documents don't get overwritten
(is (thrown+? (partial check-exc :vix.db/document-already-exists-conflict)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/foo"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})))
;; test without a :language key
(is (thrown+? (partial check-exc :vix.db/document-missing-required-keys)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:feed "blog"
:title "foo"
:slug "/blog/foobar"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})))
;; test without a :feed key
(is (thrown+? (partial check-exc :vix.db/document-missing-required-keys)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:title "foo"
:slug "/blog/foobar"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})))
;; test without a :slug key
(is (thrown+? (partial check-exc :vix.db/document-missing-required-keys)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})))
;; test without a :title key
(is (thrown+? (partial check-exc :vix.db/document-missing-required-keys)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:slug "/blog/foobar"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})))
(testing "Test if attachments are handled correctly."
(let [gif (str "R0lGODlhAQABA++/vQAAAAAAAAAA77+9AQIAAAAh77+9BAQUA++/"
"vQAsAAAAAAEAAQAAAgJEAQA7")
document (first
(append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:attachment {:type "image/gif"
:data gif}
:title "a single black pixel!"
:language "en"
:feed "images"
:slug "pixel.gif"
:content ""
:draft false}))]
(is (= (:original (:attachments document))
{:type "image/gif"
:length 57
:data (str "R0lGODlhAQABA++/vQAAAAAAAAAA77+9AQIAAAAh77+"
"9BAQUA++/vQAsAAAAAAEAAQAAAgJEAQA7")}))
(is (= (get-attachment-as-base64-string +test-db+
(:_id document)
:original)
gif)))))
(deftest test-append-to-document-update
(with-redefs [util/now-rfc3339 #(str "2012-09-16T02:51:47.588Z")]
(let [new-doc (append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:subtitle ""
:slug "/blog/bar"
:content "bar"
:description ""
:draft false
:icon nil
:related-pages []
:related-images []})
updated-doc (append-to-document
+test-db+
"Europe/Amsterdam"
{:action :update
:previous-id (:_id (first new-doc))
:language "en"
:feed "blog"
:slug "/blog/bar"
:title "hic sunt dracones"
:subtitle "old maps are cool!"
:description "hey!"
:draft true
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:icon {:title "cat" :slug "/cat.png"}
:related-pages [{:title "foo" :slug "bar"}]
:related-images [{:title "cat" :slug "cat.png"}]})]
(is (= (get-document +test-db+ "/blog/bar") updated-doc))
(is (couchdb-rev? 1 (:_rev (first updated-doc))))
(is (couchdb-id? (:previous-id (first updated-doc))))
(is (= (map #(dissoc % :_id :_rev :previous-id) updated-doc)
[{:subtitle "old maps are cool!"
:slug "/blog/bar"
:icon {:slug "/cat.png"
:title "cat"}
:action :update
:related-images [{:slug "cat.png"
:title "cat"}]
:language "en"
:title "hic sunt dracones"
:start-time-rfc3339 "2012-02-21T00:19:00.000Z"
:published "2012-09-16T02:51:47.588Z"
:datestamp "2012-09-16T02:51:47.588Z"
:created "2012-09-16T02:51:47.588Z"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:type "document"
:feed "blog"
:draft true
:related-pages [{:slug "bar"
:title "foo"}]
:description "hey!"
:end-time-rfc3339 "2012-02-21T09:00:00.000Z"}
{:subtitle ""
:slug "/blog/bar"
:icon nil
:content "bar"
:action :create
:related-images []
:language "en"
:title "foo"
:published "2012-09-16T02:51:47.588Z"
:datestamp "2012-09-16T02:51:47.588Z"
:created "2012-09-16T02:51:47.588Z"
:type "document"
:feed "blog"
:draft false
:related-pages []
:description ""}]))
;; make sure that the internal current-state flag is removed
;; from non-current document states (this non-public flag is
;; used for overview views that show e.g. the most recent states
;; for documents in a specific feed).
(is (= (:current-state
(clutch/get-document +test-db+ (get-in updated-doc [0 :_id])))
true))
(is (= (:current-state
(clutch/get-document +test-db+ (get-in updated-doc [1 :_id])))
false))
;; test with expired :previous-id
(is (thrown+? (partial check-exc :vix.db/document-update-conflict)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :update
:previous-id (:_id (first new-doc))
:language "en"
:feed "blog"
:slug "/blog/bar"
:title "hic sunt dracones"
:subtitle "old maps are cool!"
:description "hey!"
:draft true
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:icon {:title "cat" :slug "/cat.png"}
:related-pages [{:title "foo" :slug "bar"}]
:related-images [{:title "cat" :slug "cat.png"}]})))
;; test without :previous-id
(is (thrown+? (partial check-exc :vix.db/document-update-conflict)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :update
:language "en"
:feed "blog"
:slug "/blog/bar"
:title "hic sunt dracones"
:subtitle "old maps are cool!"
:description "hey!"
:draft true
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:icon {:title "cat" :slug "/cat.png"}
:related-pages [{:title "foo" :slug "bar"}]
:related-images [{:title "cat" :slug "cat.png"}]})))
;; make sure that passing couchdb-options works (useful for
;; limiting returned states on frequently updated image
;; documents).
(is (= (map #(dissoc % :_rev :_id :previous-id)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :update
:previous-id (:_id (first (get-document +test-db+
"/blog/bar")))
:language "en"
:feed "blog"
:slug "/blog/bar"
:title "here be dragons"
:subtitle "old maps are cool!"
:description "hey!"
:draft true
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:icon {:title "cat" :slug "/cat.png"}
:related-pages [{:title "foo" :slug "bar"}]
:related-images [{:title "cat" :slug "cat.png"}]}
{:limit 1}))
[{:subtitle "old maps are cool!"
:slug "/blog/bar"
:icon {:slug "/cat.png"
:title "cat"}
:action :update
:related-images [{:slug "cat.png"
:title "cat"}]
:language "en"
:title "here be dragons"
:start-time-rfc3339 "2012-02-21T00:19:00.000Z"
:datestamp "2012-09-16T02:51:47.588Z"
:created "2012-09-16T02:51:47.588Z"
:published "2012-09-16T02:51:47.588Z"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:type "document"
:feed "blog"
:draft true
:related-pages [{:slug "bar"
:title "foo"}]
:description "hey!"
:end-time-rfc3339 "2012-02-21T09:00:00.000Z"}]))))
(testing "Test if attachments are handled correctly."
(let [black-pixel
(str "R0lGODlhAQABA++/vQAAAAAAAAAA77+9AQIAAAAh77+9BAQU"
"A++/vQAsAAAAAAEAAQAAAgJEAQA7")
white-pixel
(str "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJ"
"CQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcp"
"LDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwh"
"MjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy"
"MjIyMjIyMjIyMjIyMjL/wAARCAABAAEDASIAAhEBAxEB/8QA"
"HwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAA"
"AgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKB"
"kaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6"
"Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWG"
"h4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXG"
"x8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QA"
"HwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREA"
"AgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEI"
"FEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5"
"OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOE"
"hYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPE"
"xcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oA"
"DAMBAAIRAxEAPwD3+iiigD//2Q==")
new-doc
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:attachment {:type "image/jpeg" :data white-pixel}
:language "en"
:feed "images"
:slug "/pixel.jpeg"
:title "a single white pixel!"
:content ""
:draft false})
updated-doc
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :update
:attachment {:type "image/gif" :data black-pixel}
:previous-id (:_id (first new-doc))
:language "en"
:feed "images"
:slug "/pixel.jpeg"
:title "a single black pixel!"
:content ""
:draft false})]
;; check if the image has actually been updated:
(is (= (get-in updated-doc [0 :attachments])
{:original {:type "image/gif"
:length 57
:data black-pixel}}))
;; The attachment for the previous state should also be included
;; in the result of the update action.
(is (= (get-in updated-doc [1 :attachments])
{:original {:type "image/jpeg"
:length 631
:data white-pixel}}))
(is (= (get-attachment-as-base64-string +test-db+
(:_id (first updated-doc))
:original)
black-pixel)))))
(deftest test-append-to-document-delete
(with-redefs [util/now-rfc3339 #(str "2012-09-16T03:43:20.953Z")]
(let [doc (append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:slug "/blog/bar"
:title "foo"
:content "bar"
:draft false})]
(is (not (nil? (first (get-document +test-db+ "/blog/bar"))))
"Assure the document exists before it is deleted.")
(is (= (map #(dissoc % :_id :_rev :previous-id)
(append-to-document +test-db+
"Europe/Amsterdam"
{:action :delete
:previous-id (:_id (first doc))
:language "en"
:feed "blog"
:slug "/blog/bar"
:title "foo"
:content "bar"
:draft false}))
[{:slug "/blog/bar"
:content "bar"
:action :delete
:language "en"
:title "foo"
:published "2012-09-16T03:43:20.953Z"
:datestamp "2012-09-16T03:43:20.953Z"
:created "2012-09-16T03:43:20.953Z"
:type "document"
:feed "blog"
:draft false}
{:slug "/blog/bar"
:content "bar"
:action :create
:language "en"
:title "foo"
:published "2012-09-16T03:43:20.953Z"
:datestamp "2012-09-16T03:43:20.953Z"
:created "2012-09-16T03:43:20.953Z"
:type "document"
:feed "blog"
:draft false}]))
;; make sure documents can't be deleted twice
(is (thrown+? (partial check-exc :vix.db/document-already-deleted)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :delete
:previous-id (:_id
(first
(get-document +test-db+
"/blog/bar")))
:language "en"
:feed "blog"
:slug "/blog/bar"
:title "foo"
:content "bar"
:draft false}))))))
(deftest test-get-available-languages
(do
(append-to-feed +test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:language "en"
:searchable true})
(append-to-feed +test-db+
{:action :create
:title "Images"
:subtitle "Images"
:name "images"
:language "en"
:searchable true})
(append-to-feed +test-db+
{:action :create
:title "Menu"
:subtitle "Menu"
:name "menu"
:language "en"
:searchable false})
(append-to-feed +test-db+
{:action :create
:title "Weblog"
:name "blog"
:language "nl"
:searchable true})
(append-to-feed +test-db+
{:action :create
:title "Weblog"
:name "blog"
:language "de"
:searchable true})
(append-to-feed +test-db+
{:action :delete
:previous-id (:_id
(first
(get-feed +test-db+ "de" "blog")))
:title "Weblog"
:name "blog"
:language "de"
:searchable true}))
(is (= (get-available-languages +test-db+) ["en" "nl"])))
(deftest test-get-languages
(do
(append-to-feed +test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:language "en"
:searchable true})
(append-to-feed +test-db+
{:action :create
:title "Images"
:subtitle "Images"
:name "images"
:language "en"
:searchable true})
(append-to-feed +test-db+
{:action :create
:title "Menu"
:subtitle "Menu"
:name "menu"
:language "en"
:searchable false})
(append-to-feed +test-db+
{:action :create
:title "Weblog"
:name "blog"
:language "nl"
:searchable true})
(append-to-feed +test-db+
{:action :create
:title "Weblog"
:name "blog"
:language "de"
:searchable true})
(append-to-feed +test-db+
{:action :delete
:previous-id (:_id
(first
(get-feed +test-db+ "de" "blog")))
:title "Weblog"
:name "blog"
:language "de"
:searchable true}))
(is (= (get-languages (list-feeds +test-db+)) #{"en" "nl"})))
(deftest test-get-searchable-feeds
(do
(append-to-feed +test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:language "en"
:searchable true})
(append-to-feed +test-db+
{:action :create
:title "Images"
:subtitle "Images"
:name "images"
:language "en"
:searchable true})
(append-to-feed +test-db+
{:action :create
:title "Menu"
:subtitle "Menu"
:name "menu"
:language "en"
:searchable false})
(append-to-feed +test-db+
{:action :create
:title "Weblog"
:name "blog"
:language "nl"
:searchable true}))
(is (= (get-searchable-feeds (list-feeds +test-db+))
{"nl" ["blog"]
"en" ["images" "blog"]})))
(deftest test-get-most-recent-event-documents
(let [doc-1 (append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"events"
:title
"<NAME>"
:slug
"/en/events/stanko-middelburg"
:content
(str "The legendary Polish trumpet "
"player Stańko will be playing "
"in Middelburg.")
:start-time
"2012-04-25 20:30"
:end-time
"2012-04-25 23:59"
:draft false})
doc-2 (append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"events"
:title
"The Impossible Gentlemen"
:slug
(str "/en/events/impossible-gentlemen"
"-amsterdam")
:content
(str "<NAME>, <NAME>, "
"<NAME>, <NAME> "
"will be playing at the Bimhuis "
"in Amsterdam.")
:start-time
"2012-07-06 20:30"
:end-time
"2012-07-06 23:59"
:draft false})
doc-3 (append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"events"
:title
"<NAME>"
:slug
"/en/events/yuri-honing-tilburg"
:content
(str "VPRO/Boy Edgar prize winner "
"<NAME> will be playing at "
"the Paradox venue in Tilburg.")
:start-time
"2013-02-01 20:30"
:end-time
"2013-02-01 23:59"
:draft false})]
(is (= (get-most-recent-event-documents +test-db+
"en"
"events")
(get-most-recent-event-documents +test-db+
"en"
"events"
nil)
(map first [doc-3 doc-2 doc-1])))
;; when limited, the fn retrieves (inc limit)
(is (= (get-most-recent-event-documents +test-db+
"en"
"events"
1)
[(first doc-3)])))) | true | ;; test/vix/test/db.clj tests for db namespace.
;; Copyright 2011-2012, Vixu.com, PI:NAME:<NAME>END_PI. (PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>.
;;
;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
(ns vix.test.db
(:use [vix.db] :reload
[vix.test.test]
[slingshot.test]
[clojure.test]
[clojure.data.json :only [read-json]])
(:require [com.ashafa.clutch :as clutch]
[clj-http.client :as http]
[vix.util :as util])
(:import [org.apache.commons.codec.binary Base64]))
(defn couchdb-id? [s]
(re-matches #"^[a-z0-9]{32}$" s))
(defn couchdb-rev?
([s]
(couchdb-rev? 1 s))
([rev-num s]
(re-matches (re-pattern (str "^" rev-num "-[a-z0-9]{32}$")) s)))
(defn iso-date? [s]
(re-matches
#"^[\d]{4}-[\d]{2}-[\d]{2}T[\d]{2}:[\d]{2}:[\d]{2}\.[\d]{1,4}Z"
s))
(defn random-lower-case-string [length]
;; to include uppercase
;; (let [ascii-codes (concat (range 48 58) (range 66 91) (range 97 123))])
(let [ascii-codes (concat (range 48 58) (range 97 123))]
(apply str (repeatedly length #(char (rand-nth ascii-codes))))))
(def +test-db+ (str "vix-test-" (random-lower-case-string 20)))
(def +test-server+ "http://localhost:5984/")
(defn database-fixture [f]
(clutch/get-database +test-db+)
(f)
(clutch/delete-database +test-db+))
(use-fixtures :each database-fixture)
(deftest test-load-view
(is (= (load-view "database-views/map_newsletter_subscribers.js")
(str "function(doc) {\n"
" if(doc.type === \"newsletter-subscriber\") {\n"
" emit([doc.language, doc.email], doc);\n"
" }\n}\n"))))
(deftest test-create-views
(create-views +test-db+ "views" views)
(let [view-doc (read-json (:body (http/get
(str +test-server+
+test-db+
"/_design/views"))))]
(is (= (count (:views view-doc)) 9))
(is (= (:map (:feeds (:views view-doc)))
(str "function(feed) {\n"
" if(feed.type === \"feed\") {\n"
" emit([feed.language, feed.name, feed.datestamp]"
", feed);\n }\n}\n")))
(is (= (:map (:feeds_by_default_document_type (:views view-doc)))
(str "function(feed) {\n"
" if(feed.type === \"feed\" &&\n"
" feed[\"current-state\"] === true &&\n"
" feed.action !== \"delete\") {\n"
" emit([feed[\"default-document-type\"],\n"
" feed[\"language\"],\n"
" feed[\"name\"]],\n"
" feed);\n"
" }\n}\n")))
(is (= (:map (:feeds_overview (:views view-doc)))
(str "function(feed) {\n"
" if(feed.type === \"feed\" &&\n"
" feed[\"current-state\"] === true &&\n"
" feed.action !== \"delete\") {\n"
" emit([feed.language, feed.name, feed.datestamp],"
" feed);\n"
" }\n}\n")))
(is (= (:map (:by_slug (:views view-doc)))
(str "function(doc) {\n"
" if(doc.type === \"document\") {\n"
" emit([doc.slug, doc.datestamp], doc);\n"
" }\n}\n")))
(is (= (:map (:by_feed (:views view-doc)))
(str "function(doc) {\n"
" if(doc.type === \"document\" &&\n"
" doc[\"current-state\"] === true &&\n"
" doc.action !== \"delete\") {\n"
" emit([[doc.language, doc.feed], doc.published], "
"doc);\n"
" }\n}\n")))
(is (= (:map (:by_username (:views view-doc)))
(str "function(doc) {\n"
" if(doc.type === \"user\") {\n"
" emit(doc.username, doc);\n"
" }\n"
"}\n")))
(is (= (:map (:events_by_feed (:views view-doc)))
(str "function(doc) {\n"
" if(doc.type === \"document\" &&\n"
" doc[\"end-time-rfc3339\"] &&\n"
" doc[\"current-state\"] === true) {\n"
" emit([[doc.language, doc.feed], "
"doc[\"end-time-rfc3339\"]], doc);\n }\n}\n")))
(is (= (:map (:subscribers (:views view-doc)))
(str "function(doc) {\n"
" if(doc.type === \"newsletter-subscriber\") {\n"
" emit([doc.language, doc.email], doc);\n"
" }\n}\n")))
(is (= (:map (:languages (:views view-doc)))
(str "function(feed) {\n"
" if(feed.type === \"feed\" &&\n"
" feed[\"current-state\"] === true &&\n"
" feed.action !== \"delete\") {\n"
" emit(feed.language, null);\n"
" }\n}\n")))
(is (= (:reduce (:languages (:views view-doc)))
"function(k,v) {\n return null;\n}\n")))
(is (thrown+? (partial check-exc :vix.db/database-socket-error)
(create-views "http://localhost:9999/foo" "bar" views))))
(deftest test-get-attachment-as-base64-string
(let [gif (str "R0lGODlhAQABA++/vQAAAAAAAAAA77+9AQIAAAAh77+9BAQUA++/"
"vQAsAAAAAAEAAQAAAgJEAQA7")
document (append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:attachment {:type "image/gif"
:data gif}
:feed "images"
:language "en"
:title "a single black pixel!"
:slug "pixel.gif"
:content ""
:draft false})]
(is (= (get-attachment-as-base64-string +test-db+
(:_id (first document))
:original)
gif))))
(deftest test-get-document
(is (nil? (get-document +test-db+ "/blog/foo")))
(is (nil? (get-document +test-db+ "/blog/foo" {:limit 100000})))
(with-redefs [util/now-rfc3339 #(str "2012-09-15T23:48:58.050Z")]
(append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:title "foo"
:slug "/blog/foo"
:language "en"
:feed "blog"
:content "bar"
:draft true})
(append-to-document +test-db+
"Europe/Amsterdam"
{:action :update
:previous-id (:_id
(first
(get-document
+test-db+
"/blog/foo")))
:title "foo"
:slug "/blog/foo"
:language "en"
:feed "blog"
:content "bar"
:draft false}))
;; The view isn't created manually; successful execution of
;; this test also implies that it is created automatically.
(is (couchdb-id? (:_id (first (get-document +test-db+ "/blog/foo")))))
(is (couchdb-rev? (:_rev (first (get-document +test-db+ "/blog/foo")))))
(is (= (vec (map #(dissoc % :_id :_rev :previous-id)
(get-document +test-db+ "/blog/foo")))
[{:slug "/blog/foo"
:content "bar"
:action :update
:language "en"
:title "foo"
:published "2012-09-15T23:48:58.050Z"
:datestamp "2012-09-15T23:48:58.050Z"
:created "2012-09-15T23:48:58.050Z"
:type "document"
:feed "blog"
:draft false}
{:slug "/blog/foo"
:content "bar"
:action :create
:language "en"
:title "foo"
:published "2012-09-15T23:48:58.050Z"
:datestamp "2012-09-15T23:48:58.050Z"
:created "2012-09-15T23:48:58.050Z"
:type "document"
:feed "blog"
:draft true}]))
(is (= (vec (map #(dissoc % :_id :_rev :previous-id)
(get-document +test-db+ "/blog/foo" {:limit 1})))
[{:slug "/blog/foo"
:content "bar"
:action :update
:language "en"
:title "foo"
:published "2012-09-15T23:48:58.050Z"
:datestamp "2012-09-15T23:48:58.050Z"
:created "2012-09-15T23:48:58.050Z"
:type "document"
:feed "blog"
:draft false}]))
(testing "Test if attachments are handled correctly."
(let [gif (str "R0lGODlhAQABA++/vQAAAAAAAAAA77+9AQIAAAAh77+9BAQUA++/"
"vQAsAAAAAAEAAQAAAgJEAQA7")]
(do
(append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:attachment {:type "image/gif" :data gif}
:title "a single black pixel!"
:slug "/images/white-pixel.gif"
:language "en"
:feed "images"
:content ""
:draft false})
(append-to-document +test-db+
"Europe/Amsterdam"
{:action :update
:previous-id (:_id
(first
(get-document
+test-db+
"/images/white-pixel.gif")))
:attachment {:type "image/gif" :data gif}
:title "a single black pixel!"
:slug "/images/white-pixel.gif"
:language "en"
:feed "images"
:content ""
:draft false})
(append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:title "not a single black pixel!"
:slug "/images/not-a-white-pixel.gif"
:language "en"
:feed "images"
:content ""
:draft false}))
(is (= (get-in (get-document +test-db+ "/images/white-pixel.gif")
[0 :attachments :original])
(get-in (get-document +test-db+ "/images/white-pixel.gif")
[1 :attachments :original])
{:type "image/gif" :data gif :length 57})))))
(deftest test-get-feed
(with-redefs [util/now-rfc3339 #(str "2012-09-04T03:46:52.096Z")]
(let [en-feed (append-to-feed
+test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "en"})
nl-feed (append-to-feed
+test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "nl"})
nl-feed-update-0 (with-redefs
[util/now-rfc3339
#(str "2012-09-04T03:50:52.096Z")]
(append-to-feed
+test-db+
{:action :update
:previous-id (:_id (first nl-feed))
:title "B1"
:subtitle "b1!"
:name "blog"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "nl"}))
nl-feed-update-1 (with-redefs
[util/now-rfc3339
#(str "2012-09-04T03:55:52.096Z")]
(append-to-feed
+test-db+
{:action :update
:previous-id (:_id (first nl-feed-update-0))
:title "B2"
:subtitle "b2!"
:name "blog"
:default-slug-format "/{document-title}"
:default-document-type "with-description"
:language "nl"}))]
(is (= (map #(dissoc % :_id :_rev) (get-feed +test-db+ "en" "blog"))
[{:subtitle "Vix Weblog!"
:action :create
:name "blog"
:language "en"
:title "Weblog"
:datestamp "2012-09-04T03:46:52.096Z"
:created "2012-09-04T03:46:52.096Z"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"}]))
(is (couchdb-id? (:_id (first (get-feed +test-db+ "en" "blog")))))
(is (couchdb-rev? (:_rev (first (get-feed +test-db+ "en" "blog")))))
(is (= (map #(dissoc % :_id :_rev :previous-id)
(get-feed +test-db+ "nl" "blog"))
[{:subtitle "b2!"
:action :update
:name "blog"
:language "nl"
:title "B2"
:datestamp "2012-09-04T03:55:52.096Z"
:created "2012-09-04T03:46:52.096Z"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"}
{:subtitle "b1!"
:action :update
:name "blog"
:language "nl"
:title "B1"
:datestamp "2012-09-04T03:50:52.096Z"
:created "2012-09-04T03:46:52.096Z"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"}
{:subtitle "Vix Weblog!"
:action :create
:name "blog"
:language "nl"
:title "Weblog"
:datestamp "2012-09-04T03:46:52.096Z"
:created "2012-09-04T03:46:52.096Z"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"}]))
(is (= (map #(dissoc % :_id :_rev :previous-id)
(get-feed +test-db+ "nl" "blog" 1))
[{:subtitle "b2!"
:action :update
:name "blog"
:language "nl"
:title "B2"
:datestamp "2012-09-04T03:55:52.096Z"
:created "2012-09-04T03:46:52.096Z"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"}]))
(let [blog-states (get-feed +test-db+ "nl" "blog")]
(are [n]
(couchdb-id? (:_id (nth blog-states n)))
0 1 2)
(are [rev-number n]
(couchdb-rev? rev-number (:_rev (nth blog-states n)))
1 0
2 1
2 2)))))
(deftest test-append-to-feed
(let [blog-feed (with-redefs [util/now-rfc3339
#(str "2012-09-04T04:30:17.872Z")]
(first
(append-to-feed
+test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:language "en"
:default-slug-format "/{document-title}"
:default-document-type "with-description"})))]
(testing "test create action"
(is (= (:type blog-feed) "feed"))
(is (couchdb-id? (:_id blog-feed)))
(is (couchdb-rev? (:_rev blog-feed)))
(is (iso-date? (:created blog-feed)))
(is (= (:title blog-feed) "Weblog"))
(is (= (:subtitle blog-feed) "Vix Weblog!"))
(is (= (:name blog-feed) "blog"))
(is (= (:language blog-feed) "en"))
(is (= (:default-slug-format blog-feed) "/{document-title}"))
(is (= (:default-document-type blog-feed) "with-description")))
;; make sure that invalid actions aren't allowed
(is (thrown+? (partial check-exc :vix.db/invalid-action)
(append-to-feed
+test-db+
(assoc blog-feed
:action :invalid
:previous-id (:_id blog-feed)
:title "Updated Weblog Feed"
:default-document-type "standard"
:searchable true))))
(is (thrown+? (partial check-exc :vix.db/invalid-action)
(append-to-feed
+test-db+
(dissoc (assoc blog-feed
:previous-id (:_id blog-feed)
:title "Updated Weblog Feed"
:default-document-type "standard"
:searchable true)
:action))))
;; a non-keyword action should work:
(append-to-feed
+test-db+
{:action :create
:title "Weblog"
:subtitle "Another Weblog!"
:name "another-blog"
:language "en"
:default-slug-format "/{document-title}"
:default-document-type "with-description"})
(let [blog-feed-updated (with-redefs [util/now-rfc3339
#(str "2012-09-04T04:30:17.930Z")]
(first
(append-to-feed
+test-db+
(assoc blog-feed
:action :update
:previous-id (:_id blog-feed)
:title "Updated Weblog Feed"
:default-document-type "standard"
:searchable true))))]
(testing "test update action"
(is (= (first (get-feed +test-db+ "en" "blog")) blog-feed-updated))
(is (couchdb-rev? (:_rev blog-feed-updated)))
(is (iso-date? (:datestamp blog-feed-updated)))
(is (= (:created blog-feed) (:created blog-feed-updated)))
(is (= (:title blog-feed-updated) "Updated Weblog Feed"))
(is (= (:subtitle blog-feed-updated) "Vix Weblog!"))
(is (= (:language blog-feed-updated) "en"))
(is (= (:name blog-feed-updated) "blog")) ; NB: not updated!
(is (= (:default-slug-format blog-feed-updated) "/{document-title}"))
(is (= (:default-document-type blog-feed-updated) "standard"))
(is (= (:searchable blog-feed-updated) true))
(is (thrown+? (partial check-exc :vix.db/feed-update-conflict)
(append-to-feed
+test-db+
(assoc blog-feed
:action :update))))
(is (thrown+? (partial check-exc :vix.db/feed-update-conflict)
(append-to-feed
+test-db+
(assoc blog-feed
:action :update
:previous-id (:previous-id blog-feed))))))
(testing "test delete action"
(is (not (nil? (get-feed +test-db+ "en" "blog")))
"Assure the feed exists before it is deleted.")
(is (thrown+? (partial check-exc :vix.db/feed-update-conflict)
(append-to-feed
+test-db+
(assoc (dissoc blog-feed-updated :previous-id)
:action :delete))))
(is (thrown+? (partial check-exc :vix.db/feed-update-conflict)
(append-to-feed
+test-db+
(assoc blog-feed-updated
:action :delete
:previous-id (:previous-id blog-feed)))))
(let [deleted-feed (with-redefs [util/now-rfc3339
#(str "2012-09-04T04:30:18.010Z")]
(append-to-feed
+test-db+
(assoc blog-feed-updated
:action
:delete
:previous-id
(:_id blog-feed-updated))))]
(is (= (map #(dissoc % :_id :_rev :previous-id) deleted-feed)
[{:subtitle "Vix Weblog!"
:action :delete
:name "blog"
:language "en"
:title "Updated Weblog Feed"
:datestamp "2012-09-04T04:30:18.010Z"
:searchable true
:created "2012-09-04T04:30:17.872Z"
:type "feed"
:default-document-type "standard"
:default-slug-format "/{document-title}"}
{:subtitle "Vix Weblog!"
:action :update
:name "blog"
:language "en"
:title "Updated Weblog Feed"
:datestamp "2012-09-04T04:30:17.930Z"
:searchable true
:created "2012-09-04T04:30:17.872Z"
:type "feed"
:default-document-type "standard"
:default-slug-format "/{document-title}"}
{:subtitle "Vix Weblog!"
:action :create
:name "blog"
:language "en"
:title "Weblog"
:datestamp "2012-09-04T04:30:17.872Z"
:created "2012-09-04T04:30:17.872Z"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"}]))
(is (thrown+? (partial check-exc :vix.db/feed-already-deleted)
(append-to-feed
+test-db+
(assoc (first deleted-feed)
:action :delete
:previous-id (:_id (first deleted-feed))))))))))
(testing "test feed-already-exists-conflict"
(do
(append-to-feed +test-db+
{:subtitle "bar"
:action :create
:name "foobar"
:language "en"
:title "Foobar"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"}))
(is (thrown+? (partial check-exc :vix.db/feed-already-exists-conflict)
(append-to-feed
+test-db+
{:subtitle "bar"
:action :create
:name "foobar"
:language "en"
:title "Foobar"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"})))
(do
(append-to-feed +test-db+
{:subtitle "bar"
:action :delete
:previous-id (:_id
(first
(get-feed +test-db+ "en" "foobar")))
:name "foobar"
:language "en"
:title "Foobar"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"})
;; once the feed is deleted, it should be possible to recreate
(append-to-feed +test-db+
{:subtitle "bar"
:action :create
:name "foobar"
:language "en"
:title "Foobar"
:type "feed"
:default-document-type "with-description"
:default-slug-format "/{document-title}"}))))
(deftest test-get-documents-for-feed
(let [doc-1 (append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/foo-0"
:content "bar"
:draft true})
doc-2 (append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/foo-1"
:content "bar"
:draft true})
doc-3 (append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "nl"
:feed "blog"
:title "foo"
:slug "/blog/foo-nl"
:content "bar"
:draft true})
feed (get-documents-for-feed +test-db+ "en" "blog")]
;; FIXME: should also test other possible argument combinations!
(is (= (count (:documents feed)) 2))
(is (= (:next feed) nil))
(is (some #{(first doc-1)} (:documents feed)))
(is (some #{(first doc-2)} (:documents feed))))
(testing "test pagination"
(let [now "2011-09-06T12:56:16.322Z"]
(dotimes [n 21]
(let [my-now (if (< n 7) ;; mix identical and unique datestamps
now
(util/now-rfc3339))]
(clutch/put-document +test-db+
{:action :create
:current-state true
:type "document"
:title (str "doc " n)
:slug (str "/pages/doc-" n)
:content ""
:draft false
:language "en"
:feed "pages"
:published my-now
:created my-now
:datestamp my-now}))))
(is (= (count (:documents (get-documents-for-feed +test-db+
"en"
"pages")))
21))
(let [first-five (get-documents-for-feed +test-db+ "en" "pages" 5)]
(is (= (count (:documents first-five)) 5))
(is (= (:title (nth (:documents first-five) 0)) "doc 20"))
(is (= (:title (nth (:documents first-five) 1)) "doc 19"))
(is (= (:title (nth (:documents first-five) 2)) "doc 18"))
(is (= (:title (nth (:documents first-five) 3)) "doc 17"))
(is (= (:title (nth (:documents first-five) 4)) "doc 16"))
(let [next-five (get-documents-for-feed +test-db+
"en"
"pages"
5
(:published (:next first-five))
(:startkey_docid
(:next first-five)))]
(is (= (count (:documents next-five)) 5))
(is (= (:title (nth (:documents next-five) 0)) "doc 15"))
(is (= (:title (nth (:documents next-five) 1)) "doc 14"))
(is (= (:title (nth (:documents next-five) 2)) "doc 13"))
(is (= (:title (nth (:documents next-five) 3)) "doc 12"))
(is (= (:title (nth (:documents next-five) 4)) "doc 11"))
(let [next-ten (get-documents-for-feed +test-db+
"en"
"pages"
10
(:published (:next next-five))
(:startkey_docid
(:next next-five)))]
(is (= (count (:documents next-ten)) 10))
(is (= (:title (nth (:documents next-ten) 0)) "doc 10"))
(is (= (:title (nth (:documents next-ten) 1)) "doc 9"))
(is (= (:title (nth (:documents next-ten) 2)) "doc 8"))
(is (= (:title (nth (:documents next-ten) 3)) "doc 7"))
(is (= (:title (nth (:documents next-ten) 4)) "doc 6"))
(is (= (:title (nth (:documents next-ten) 5)) "doc 5"))
(is (= (:title (nth (:documents next-ten) 6)) "doc 4"))
(is (= (:title (nth (:documents next-ten) 7)) "doc 3"))
(is (= (:title (nth (:documents next-ten) 8)) "doc 2"))
(is (= (:title (nth (:documents next-ten) 9)) "doc 1"))
(is (= (:published (nth (:documents next-ten) 4))
(:published (nth (:documents next-ten) 5))
(:published (nth (:documents next-ten) 6))
(:published (nth (:documents next-ten) 7))
(:published (nth (:documents next-ten) 7))
(:published (nth (:documents next-ten) 9))
"2011-09-06T12:56:16.322Z"))
(let [last-doc (get-documents-for-feed +test-db+
"en"
"pages"
1
(:published
(:next next-ten))
(:startkey_docid
(:next next-ten)))
x2 (get-documents-for-feed +test-db+
"en"
"pages"
10
(:published
(:next next-ten))
(:startkey_docid
(:next next-ten)))]
(is (= last-doc x2))
(is (nil? (:next last-doc)))
(is (= (:published (nth (:documents last-doc) 0))
"2011-09-06T12:56:16.322Z"))
(is (= (:title (nth (:documents last-doc) 0)) "doc 0"))))))))
(deftest test-list-feeds-and-list-feeds-by-default-document-type
(let [blog-feed (first
(append-to-feed
+test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:language "en"
:name "blog"
:default-slug-format
"/{feed-name}/{document-title}"
:default-document-type "with-description"}))
pages-feed (first
(append-to-feed
+test-db+
{:action :create
:title "Pages"
:subtitle "Web Pages"
:language "en"
:name "pages"
:default-slug-format "/{document-title}"
:default-document-type "standard"}))
images-feed (first
(append-to-feed
+test-db+
{:action :create
:title "Images"
:subtitle "Internal feed with images"
:language "en"
:name "images"
:default-slug-format
"/media/{document-title}"
:default-document-type "image"}))
blog-feed-nl (first
(append-to-feed
+test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:language "nl"
:name "blog"
:default-slug-format
"/{feed-name}/{document-title}"
:default-document-type
"with-description"}))
pages-feed-nl (first
(append-to-feed
+test-db+
{:action :create
:title "Pages"
:subtitle "Web Pages"
:language "nl"
:name "pages"
:default-slug-format "/{document-title}"
:default-document-type "standard"}))
;; do an update, to make sure only the most recent version is used
images-feed-nl (first
(append-to-feed
+test-db+
(let [images-feed-nl-0
(first
(append-to-feed
+test-db+
{:action :create
:title "Images"
:subtitle "Internal feed with images"
:language "nl"
:name "images"
:default-slug-format
"/media/{document-title}"
:default-document-type "image"}))]
(assoc images-feed-nl-0
:action :update
:previous-id (:_id images-feed-nl-0)))))]
(do
;; create and remove a feed, to make sure it isn't included
(append-to-feed
+test-db+
(let [feed-0
(first
(append-to-feed
+test-db+
{:action :create
:title "Images (deleted)"
:subtitle "Internal feed with images"
:language "en"
:name "images-delete"
:default-slug-format
"/media/{document-title}"
:default-document-type "image"}))]
(assoc feed-0
:action :delete
:previous-id (:_id feed-0)))))
(testing "test without providing a language"
(is (= [pages-feed-nl
images-feed-nl
blog-feed-nl
pages-feed
images-feed
blog-feed]
(list-feeds +test-db+))))
(testing "test with a language argument"
(is (= [pages-feed
images-feed
blog-feed]
(list-feeds +test-db+ "en")))
(is (= [pages-feed-nl
images-feed-nl
blog-feed-nl]
(list-feeds +test-db+ "nl"))))
(testing "test with default-document-type without a language argument"
(is (= (list-feeds-by-default-document-type +test-db+
"image")
[images-feed-nl images-feed])))
(testing "test with default-document-type and a language argument"
(is (= (list-feeds-by-default-document-type +test-db+
"image"
"en")
[images-feed]))
(is (= (list-feeds-by-default-document-type +test-db+
"image"
"nl")
[images-feed-nl])))))
(deftest test-append-to-document-create
(with-redefs [util/now-rfc3339 #(str "2012-09-16T00:17:30.722Z")]
(let [document (append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/foo"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})]
(is (couchdb-id? (:_id (first document))))
(is (couchdb-rev? (:_rev (first document))))
(is (= (vec (map #(dissoc % :_id :_rev) document))
[{:slug "/blog/foo"
:content "bar"
:action :create
:language "en"
:title "foo"
:start-time-rfc3339 "2012-02-21T00:19:00.000Z"
:published "2012-09-16T00:17:30.722Z"
:datestamp "2012-09-16T00:17:30.722Z"
:created "2012-09-16T00:17:30.722Z"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:type "document"
:feed "blog"
:draft false
:end-time-rfc3339 "2012-02-21T09:00:00.000Z"}]))))
;; make sure valid actions are enforced
(is (thrown+? (partial check-exc :vix.db/invalid-action)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :invalid
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/foo-action"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})))
(is (thrown+? (partial check-exc :vix.db/invalid-action)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:language "en"
:feed "blog"
:title "foo"
:slug "/blog/foo-action"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})))
;; non-keyword actions should work:
(append-to-document +test-db+
"Europe/Amsterdam"
{:action "create"
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/foo-action"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})
;; make sure existing documents don't get overwritten
(is (thrown+? (partial check-exc :vix.db/document-already-exists-conflict)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:slug "/blog/foo"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})))
;; test without a :language key
(is (thrown+? (partial check-exc :vix.db/document-missing-required-keys)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:feed "blog"
:title "foo"
:slug "/blog/foobar"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})))
;; test without a :feed key
(is (thrown+? (partial check-exc :vix.db/document-missing-required-keys)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:title "foo"
:slug "/blog/foobar"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})))
;; test without a :slug key
(is (thrown+? (partial check-exc :vix.db/document-missing-required-keys)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})))
;; test without a :title key
(is (thrown+? (partial check-exc :vix.db/document-missing-required-keys)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:slug "/blog/foobar"
:content "bar"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:draft false})))
(testing "Test if attachments are handled correctly."
(let [gif (str "R0lGODlhAQABA++/vQAAAAAAAAAA77+9AQIAAAAh77+9BAQUA++/"
"vQAsAAAAAAEAAQAAAgJEAQA7")
document (first
(append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:attachment {:type "image/gif"
:data gif}
:title "a single black pixel!"
:language "en"
:feed "images"
:slug "pixel.gif"
:content ""
:draft false}))]
(is (= (:original (:attachments document))
{:type "image/gif"
:length 57
:data (str "R0lGODlhAQABA++/vQAAAAAAAAAA77+9AQIAAAAh77+"
"9BAQUA++/vQAsAAAAAAEAAQAAAgJEAQA7")}))
(is (= (get-attachment-as-base64-string +test-db+
(:_id document)
:original)
gif)))))
(deftest test-append-to-document-update
(with-redefs [util/now-rfc3339 #(str "2012-09-16T02:51:47.588Z")]
(let [new-doc (append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:title "foo"
:subtitle ""
:slug "/blog/bar"
:content "bar"
:description ""
:draft false
:icon nil
:related-pages []
:related-images []})
updated-doc (append-to-document
+test-db+
"Europe/Amsterdam"
{:action :update
:previous-id (:_id (first new-doc))
:language "en"
:feed "blog"
:slug "/blog/bar"
:title "hic sunt dracones"
:subtitle "old maps are cool!"
:description "hey!"
:draft true
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:icon {:title "cat" :slug "/cat.png"}
:related-pages [{:title "foo" :slug "bar"}]
:related-images [{:title "cat" :slug "cat.png"}]})]
(is (= (get-document +test-db+ "/blog/bar") updated-doc))
(is (couchdb-rev? 1 (:_rev (first updated-doc))))
(is (couchdb-id? (:previous-id (first updated-doc))))
(is (= (map #(dissoc % :_id :_rev :previous-id) updated-doc)
[{:subtitle "old maps are cool!"
:slug "/blog/bar"
:icon {:slug "/cat.png"
:title "cat"}
:action :update
:related-images [{:slug "cat.png"
:title "cat"}]
:language "en"
:title "hic sunt dracones"
:start-time-rfc3339 "2012-02-21T00:19:00.000Z"
:published "2012-09-16T02:51:47.588Z"
:datestamp "2012-09-16T02:51:47.588Z"
:created "2012-09-16T02:51:47.588Z"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:type "document"
:feed "blog"
:draft true
:related-pages [{:slug "bar"
:title "foo"}]
:description "hey!"
:end-time-rfc3339 "2012-02-21T09:00:00.000Z"}
{:subtitle ""
:slug "/blog/bar"
:icon nil
:content "bar"
:action :create
:related-images []
:language "en"
:title "foo"
:published "2012-09-16T02:51:47.588Z"
:datestamp "2012-09-16T02:51:47.588Z"
:created "2012-09-16T02:51:47.588Z"
:type "document"
:feed "blog"
:draft false
:related-pages []
:description ""}]))
;; make sure that the internal current-state flag is removed
;; from non-current document states (this non-public flag is
;; used for overview views that show e.g. the most recent states
;; for documents in a specific feed).
(is (= (:current-state
(clutch/get-document +test-db+ (get-in updated-doc [0 :_id])))
true))
(is (= (:current-state
(clutch/get-document +test-db+ (get-in updated-doc [1 :_id])))
false))
;; test with expired :previous-id
(is (thrown+? (partial check-exc :vix.db/document-update-conflict)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :update
:previous-id (:_id (first new-doc))
:language "en"
:feed "blog"
:slug "/blog/bar"
:title "hic sunt dracones"
:subtitle "old maps are cool!"
:description "hey!"
:draft true
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:icon {:title "cat" :slug "/cat.png"}
:related-pages [{:title "foo" :slug "bar"}]
:related-images [{:title "cat" :slug "cat.png"}]})))
;; test without :previous-id
(is (thrown+? (partial check-exc :vix.db/document-update-conflict)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :update
:language "en"
:feed "blog"
:slug "/blog/bar"
:title "hic sunt dracones"
:subtitle "old maps are cool!"
:description "hey!"
:draft true
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:icon {:title "cat" :slug "/cat.png"}
:related-pages [{:title "foo" :slug "bar"}]
:related-images [{:title "cat" :slug "cat.png"}]})))
;; make sure that passing couchdb-options works (useful for
;; limiting returned states on frequently updated image
;; documents).
(is (= (map #(dissoc % :_rev :_id :previous-id)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :update
:previous-id (:_id (first (get-document +test-db+
"/blog/bar")))
:language "en"
:feed "blog"
:slug "/blog/bar"
:title "here be dragons"
:subtitle "old maps are cool!"
:description "hey!"
:draft true
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:icon {:title "cat" :slug "/cat.png"}
:related-pages [{:title "foo" :slug "bar"}]
:related-images [{:title "cat" :slug "cat.png"}]}
{:limit 1}))
[{:subtitle "old maps are cool!"
:slug "/blog/bar"
:icon {:slug "/cat.png"
:title "cat"}
:action :update
:related-images [{:slug "cat.png"
:title "cat"}]
:language "en"
:title "here be dragons"
:start-time-rfc3339 "2012-02-21T00:19:00.000Z"
:datestamp "2012-09-16T02:51:47.588Z"
:created "2012-09-16T02:51:47.588Z"
:published "2012-09-16T02:51:47.588Z"
:start-time "2012-02-21 01:19"
:end-time "2012-02-21 10:00"
:type "document"
:feed "blog"
:draft true
:related-pages [{:slug "bar"
:title "foo"}]
:description "hey!"
:end-time-rfc3339 "2012-02-21T09:00:00.000Z"}]))))
(testing "Test if attachments are handled correctly."
(let [black-pixel
(str "R0lGODlhAQABA++/vQAAAAAAAAAA77+9AQIAAAAh77+9BAQU"
"A++/vQAsAAAAAAEAAQAAAgJEAQA7")
white-pixel
(str "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJ"
"CQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcp"
"LDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwh"
"MjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIy"
"MjIyMjIyMjIyMjIyMjL/wAARCAABAAEDASIAAhEBAxEB/8QA"
"HwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAA"
"AgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKB"
"kaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6"
"Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWG"
"h4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXG"
"x8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QA"
"HwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREA"
"AgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEI"
"FEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5"
"OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOE"
"hYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPE"
"xcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oA"
"DAMBAAIRAxEAPwD3+iiigD//2Q==")
new-doc
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :create
:attachment {:type "image/jpeg" :data white-pixel}
:language "en"
:feed "images"
:slug "/pixel.jpeg"
:title "a single white pixel!"
:content ""
:draft false})
updated-doc
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :update
:attachment {:type "image/gif" :data black-pixel}
:previous-id (:_id (first new-doc))
:language "en"
:feed "images"
:slug "/pixel.jpeg"
:title "a single black pixel!"
:content ""
:draft false})]
;; check if the image has actually been updated:
(is (= (get-in updated-doc [0 :attachments])
{:original {:type "image/gif"
:length 57
:data black-pixel}}))
;; The attachment for the previous state should also be included
;; in the result of the update action.
(is (= (get-in updated-doc [1 :attachments])
{:original {:type "image/jpeg"
:length 631
:data white-pixel}}))
(is (= (get-attachment-as-base64-string +test-db+
(:_id (first updated-doc))
:original)
black-pixel)))))
(deftest test-append-to-document-delete
(with-redefs [util/now-rfc3339 #(str "2012-09-16T03:43:20.953Z")]
(let [doc (append-to-document +test-db+
"Europe/Amsterdam"
{:action :create
:language "en"
:feed "blog"
:slug "/blog/bar"
:title "foo"
:content "bar"
:draft false})]
(is (not (nil? (first (get-document +test-db+ "/blog/bar"))))
"Assure the document exists before it is deleted.")
(is (= (map #(dissoc % :_id :_rev :previous-id)
(append-to-document +test-db+
"Europe/Amsterdam"
{:action :delete
:previous-id (:_id (first doc))
:language "en"
:feed "blog"
:slug "/blog/bar"
:title "foo"
:content "bar"
:draft false}))
[{:slug "/blog/bar"
:content "bar"
:action :delete
:language "en"
:title "foo"
:published "2012-09-16T03:43:20.953Z"
:datestamp "2012-09-16T03:43:20.953Z"
:created "2012-09-16T03:43:20.953Z"
:type "document"
:feed "blog"
:draft false}
{:slug "/blog/bar"
:content "bar"
:action :create
:language "en"
:title "foo"
:published "2012-09-16T03:43:20.953Z"
:datestamp "2012-09-16T03:43:20.953Z"
:created "2012-09-16T03:43:20.953Z"
:type "document"
:feed "blog"
:draft false}]))
;; make sure documents can't be deleted twice
(is (thrown+? (partial check-exc :vix.db/document-already-deleted)
(append-to-document
+test-db+
"Europe/Amsterdam"
{:action :delete
:previous-id (:_id
(first
(get-document +test-db+
"/blog/bar")))
:language "en"
:feed "blog"
:slug "/blog/bar"
:title "foo"
:content "bar"
:draft false}))))))
(deftest test-get-available-languages
(do
(append-to-feed +test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:language "en"
:searchable true})
(append-to-feed +test-db+
{:action :create
:title "Images"
:subtitle "Images"
:name "images"
:language "en"
:searchable true})
(append-to-feed +test-db+
{:action :create
:title "Menu"
:subtitle "Menu"
:name "menu"
:language "en"
:searchable false})
(append-to-feed +test-db+
{:action :create
:title "Weblog"
:name "blog"
:language "nl"
:searchable true})
(append-to-feed +test-db+
{:action :create
:title "Weblog"
:name "blog"
:language "de"
:searchable true})
(append-to-feed +test-db+
{:action :delete
:previous-id (:_id
(first
(get-feed +test-db+ "de" "blog")))
:title "Weblog"
:name "blog"
:language "de"
:searchable true}))
(is (= (get-available-languages +test-db+) ["en" "nl"])))
(deftest test-get-languages
(do
(append-to-feed +test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:language "en"
:searchable true})
(append-to-feed +test-db+
{:action :create
:title "Images"
:subtitle "Images"
:name "images"
:language "en"
:searchable true})
(append-to-feed +test-db+
{:action :create
:title "Menu"
:subtitle "Menu"
:name "menu"
:language "en"
:searchable false})
(append-to-feed +test-db+
{:action :create
:title "Weblog"
:name "blog"
:language "nl"
:searchable true})
(append-to-feed +test-db+
{:action :create
:title "Weblog"
:name "blog"
:language "de"
:searchable true})
(append-to-feed +test-db+
{:action :delete
:previous-id (:_id
(first
(get-feed +test-db+ "de" "blog")))
:title "Weblog"
:name "blog"
:language "de"
:searchable true}))
(is (= (get-languages (list-feeds +test-db+)) #{"en" "nl"})))
(deftest test-get-searchable-feeds
(do
(append-to-feed +test-db+
{:action :create
:title "Weblog"
:subtitle "Vix Weblog!"
:name "blog"
:language "en"
:searchable true})
(append-to-feed +test-db+
{:action :create
:title "Images"
:subtitle "Images"
:name "images"
:language "en"
:searchable true})
(append-to-feed +test-db+
{:action :create
:title "Menu"
:subtitle "Menu"
:name "menu"
:language "en"
:searchable false})
(append-to-feed +test-db+
{:action :create
:title "Weblog"
:name "blog"
:language "nl"
:searchable true}))
(is (= (get-searchable-feeds (list-feeds +test-db+))
{"nl" ["blog"]
"en" ["images" "blog"]})))
(deftest test-get-most-recent-event-documents
(let [doc-1 (append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"events"
:title
"PI:NAME:<NAME>END_PI"
:slug
"/en/events/stanko-middelburg"
:content
(str "The legendary Polish trumpet "
"player Stańko will be playing "
"in Middelburg.")
:start-time
"2012-04-25 20:30"
:end-time
"2012-04-25 23:59"
:draft false})
doc-2 (append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"events"
:title
"The Impossible Gentlemen"
:slug
(str "/en/events/impossible-gentlemen"
"-amsterdam")
:content
(str "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, "
"PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI "
"will be playing at the Bimhuis "
"in Amsterdam.")
:start-time
"2012-07-06 20:30"
:end-time
"2012-07-06 23:59"
:draft false})
doc-3 (append-to-document +test-db+
"Europe/Amsterdam"
{:action
:create
:language
"en"
:feed
"events"
:title
"PI:NAME:<NAME>END_PI"
:slug
"/en/events/yuri-honing-tilburg"
:content
(str "VPRO/Boy Edgar prize winner "
"PI:NAME:<NAME>END_PI will be playing at "
"the Paradox venue in Tilburg.")
:start-time
"2013-02-01 20:30"
:end-time
"2013-02-01 23:59"
:draft false})]
(is (= (get-most-recent-event-documents +test-db+
"en"
"events")
(get-most-recent-event-documents +test-db+
"en"
"events"
nil)
(map first [doc-3 doc-2 doc-1])))
;; when limited, the fn retrieves (inc limit)
(is (= (get-most-recent-event-documents +test-db+
"en"
"events"
1)
[(first doc-3)])))) |
[
{
"context": "; Written by Raju\n; Run using following command\n; clojure memoizati",
"end": 17,
"score": 0.9998331069946289,
"start": 13,
"tag": "NAME",
"value": "Raju"
}
] | Chapter09/memoization.clj | PacktPublishing/Learning-Functional-Data-Structures-and-Algorithms | 31 | ; Written by Raju
; Run using following command
; clojure memoization.clj
;Memoization in Clojure
(defn simpleFactFun [n]
(if (or (= n 1) (= n 0)) 1
( do
(println "Calculating Factorial")
( * n (simpleFactFun (dec n))))
)
)
(println (simpleFactFun 5))
(def memoizedFactFun (memoize simpleFactFun))
(println (memoizedFactFun 5))
(println (memoizedFactFun 5))
| 56108 | ; Written by <NAME>
; Run using following command
; clojure memoization.clj
;Memoization in Clojure
(defn simpleFactFun [n]
(if (or (= n 1) (= n 0)) 1
( do
(println "Calculating Factorial")
( * n (simpleFactFun (dec n))))
)
)
(println (simpleFactFun 5))
(def memoizedFactFun (memoize simpleFactFun))
(println (memoizedFactFun 5))
(println (memoizedFactFun 5))
| true | ; Written by PI:NAME:<NAME>END_PI
; Run using following command
; clojure memoization.clj
;Memoization in Clojure
(defn simpleFactFun [n]
(if (or (= n 1) (= n 0)) 1
( do
(println "Calculating Factorial")
( * n (simpleFactFun (dec n))))
)
)
(println (simpleFactFun 5))
(def memoizedFactFun (memoize simpleFactFun))
(println (memoizedFactFun 5))
(println (memoizedFactFun 5))
|
[
{
"context": "\n(defn footer-component []\n [:div.footer\n [:p \"Chloe Wohlgemuth (cbw975@gmail.com) \\t Sung Kwak (skwak22@amherst.",
"end": 18690,
"score": 0.9998646378517151,
"start": 18674,
"tag": "NAME",
"value": "Chloe Wohlgemuth"
},
{
"context": "onent []\n [:div.footer\n [:p \"Chloe Wohlgemuth (cbw975@gmail.com) \\t Sung Kwak (skwak22@amherst.edu) \\t Lee Specto",
"end": 18708,
"score": 0.9999333620071411,
"start": 18692,
"tag": "EMAIL",
"value": "cbw975@gmail.com"
},
{
"context": "ter\n [:p \"Chloe Wohlgemuth (cbw975@gmail.com) \\t Sung Kwak (skwak22@amherst.edu) \\t Lee Spector (lspector@am",
"end": 18722,
"score": 0.999862015247345,
"start": 18713,
"tag": "NAME",
"value": "Sung Kwak"
},
{
"context": "Chloe Wohlgemuth (cbw975@gmail.com) \\t Sung Kwak (skwak22@amherst.edu) \\t Lee Spector (lspector@amherst.edu) (MORE TO B",
"end": 18743,
"score": 0.9999344348907471,
"start": 18724,
"tag": "EMAIL",
"value": "skwak22@amherst.edu"
},
{
"context": "5@gmail.com) \\t Sung Kwak (skwak22@amherst.edu) \\t Lee Spector (lspector@amherst.edu) (MORE TO BE ADDED)\"]])\n\n(d",
"end": 18759,
"score": 0.9998824596405029,
"start": 18748,
"tag": "NAME",
"value": "Lee Spector"
},
{
"context": "t Sung Kwak (skwak22@amherst.edu) \\t Lee Spector (lspector@amherst.edu) (MORE TO BE ADDED)\"]])\n\n(defn home-page []\n [:d",
"end": 18781,
"score": 0.9999334812164307,
"start": 18761,
"tag": "EMAIL",
"value": "lspector@amherst.edu"
}
] | src/propeller_site/core.cljs | cbw975/propeller-site | 0 | (ns propeller-site.core
(:require
[reagent.core :as r]
[reagent.dom :as d]
[quil.core :as q :include-macros true]
[quil.middleware :as m]
[propeller-site.propeller :as propel]
[propeller-site.scatter :as scatter]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; STYLES & PARAMETERS ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def param-input-style {:border "#555555"
:font-size "15px"
:height "15px"
:line-height "1px"
:width "60px"})
(def evolve-button-style {:width "100px"
:color "#ccff00" :font-size "20px"})
(def disabled-style {:width "100px"
:color "#666666"
:font-size "20px"
:border "#999999"
:background-color "#cccccc"})
(def reports (r/atom []))
(def result (r/atom []))
(def evolved? (r/atom false))
(def gp-gen (r/atom 0))
(def gp-pop (r/atom []))
(def error-function (r/atom "regression"))
(def generations (r/atom 10))
(def population-size (r/atom 10))
(def max-initial-plushy-size (r/atom 50))
(def step-limit (r/atom 100))
(def parent-selection (r/atom :lexicase))
(def tournament-size (r/atom 5))
(def umad-rate (r/atom 0.1))
(def umad (r/atom 0.5))
(def crossover (r/atom 0.5))
(def elitism (r/atom false))
(def error-functions {"regression" propel/regression-error-function
"string-classification" propel/string-classification-error-function})
(def param-max {:generations 300
:population-size 500
:max-initial-plushy-size 100
:step-limit 200
:tournament-size @population-size
:umad-rate 1.0
:umad 1.0
:crossover 1.0})
(def param-min {:generations 0
:population-size 1
:max-initial-plushy-size 1
:step-limit 1
:tournament-size 1
:umad-rate (double 0)
:umad (double 0)
:crossover (double 0)})
;;;;;;;;;;;;;;;;;;;;;;
;; GENOME VISUALS ;;
;;;;;;;;;;;;;;;;;;;;;;
(def gDisplayed? (r/atom false))
(def glength 1000) ; length for genome visual
(def gheight 50) ; height for genome visual
(def gene-colors (r/atom {})) ; gene (push instruction) color (visual representation) map
(def genomes (r/atom [])) ; genomes that are being displayed
(def index (r/atom 0)) ; genome visualization we are displaying
(def test-genome '("" "A" "A" :string_drop false :boolean_and :boolean_and 0))
(defn update-gene-map
"Returns the gene (push instruction) color (visual representation) map
for a coll of given plushies/genomes"
[coll-of-plushies]
(let [genes (distinct (reduce concat coll-of-plushies)) ; instructions/genes that could display
count (count genes)
get-color (fn []
(into [] (take 3 (repeatedly #(rand-int 256)))))
colors (into [] (take count (repeatedly #(get-color))))]
; TODO: Change get-color to be generate more distinctive colors based on which stack, etc
(reset! gDisplayed? true)
(reset! gene-colors (zipmap genes colors))
(reset! genomes []))) ; Assign RGB values (colors) to genes in gene-colors map
(defn get-genome-colors
"Converts a genome of instructions to vector of colors. Each gene replaced with its color (RGB values)"
[genome]
(into [] (map #(get @gene-colors %) genome)))
(defn setup []
(q/frame-rate 30) ; FPS
(q/color-mode :hsb) ; HSB (HSV) rather than default RGB
{:color 0 :angle 0 :gene-count 0}) ; setup returns initial state, containing the circle color and position
(defn update-state
"Update the sketch state by changing the (current) gene color and position"
[state]
(if @gDisplayed?
state
(let [curr-genome (get @genomes @index)
n-genes (count curr-genome)
gene-width (/ glength n-genes)] ; to convert bin index to pixel offset in the x-dimension
(if (= (:gene-count state) n-genes)
(do (if (< @index (count @genomes))
(swap! index inc)
(swap! gDisplayed? not))
{:color (nth (get @genomes @index) 0)
:pos 0
:gene-count 0})
{:color (nth curr-genome (:gene-count state))
:pos (* (:gene-count state) gene-width)
:gene-count (inc (:gene-count state))}))))
(defn draw-state
"(Quil) Sketch a genome (rectangular row) of color-coded genes."
[state]
(q/background 240) ; Clear the sketch by filling it with light-grey color.
(q/fill (:color state) 255 255) ; Set circle color.
(let [curr-genome (get @genomes @index)
n-genes (count curr-genome)
gene-width (/ glength n-genes) ; to convert bin index to pixel offset in the x-dimension
x-pos (* (:gene-count state) gene-width)]
(q/rect x-pos 0 gene-width gheight)))
(q/defsketch display-genomes
:host "display-genomes"
:size [glength gheight]
:setup setup ; setup function called only once, during sketch initialization
:update update-state ; update-state is called on each iteration before draw-state
:draw draw-state
:middleware [m/fun-mode])
;;;;;;;;;;;;;;;;;;;;
;; PLOT VISUALS ;;
;;;;;;;;;;;;;;;;;;;;
(def curr-best-program (r/atom []))
(def curr-best-errors (r/atom []))
(defn get-generation-data
"Collects population data each generation"
[pop gen]
(let [; data from evaluated population
best (if (contains? (first pop) :total-error)
(first pop)
(throw (js/Error. (str "Called when total-error was not calculated"))))
best-errors (:errors best)
best-plushy (:plushy best)
best-program (propel/plushy->push (:plushy best))]
(reset! curr-best-program best-program)
(reset! curr-best-errors best-errors)
(scatter/update-plot-data pop gen)
{:best-program best-program
:best-plushy best-plushy
:best-errors best-errors}))
;;;;;;;;;;;;;;;;;;;;;;
;; GP FUNCTION(S) ;;
;;;;;;;;;;;;;;;;;;;;;;
(defn report-start [argmap]
(swap! reports conj (str "***************************"))
(swap! reports conj (str " ~ Error function: " @error-function " for " (:max-generations argmap) " generations with " (:population-size argmap) " individuals"))
(swap! reports conj (str " ~ Max Initial Plushy Size of " (:max-initial-plushy-size argmap) " with a step limit of " (:step-limit argmap)))
(swap! reports conj (str " ~ Parent Selection via " (:parent-selection argmap) " with tournament size of " (:tournament-size argmap)))
(swap! reports conj (str " ~ Umad-rate: " (:umad-rate argmap) " , umad: " (get-in argmap [:variation :umad]) " , crossover: " (get-in argmap [:variation :crossover]) " , elitism " (:elitism argmap)))
(swap! reports conj (str "RUNNING PROPELLER GP!"))
(swap! reports conj (str " ***************************")))
(defn make-population [instr mips]
(repeatedly (int @population-size)
#(hash-map :plushy
(propel/make-random-plushy instr mips))))
(defn evaluate-pop [argmap]
(map (partial (:error-function argmap) argmap)
@gp-pop))
(defn sort-pop
"Returns the curent population of items sorted by their :total-error's"
[argmap]
(sort-by :total-error (evaluate-pop argmap)))
(defn propel-gp
"Runs genetic programming to solve, or approximately solve, a problem in the
context (error-function, gp) of the given population-size, # generations, etc."
[{:keys [population-size max-generations error-function
instructions max-initial-plushy-size] :as argmap}]
(let [evaluated-pop (sort-pop argmap)
curr-best (first evaluated-pop)]
(swap! reports conj (propel/report evaluated-pop (int @gp-gen)))
(if (or (< (:total-error curr-best) 0.1)
(>= (int @gp-gen) max-generations))
(do (get-generation-data evaluated-pop @gp-gen)
; (get-genomes evaluated-pop)
(swap! result conj "Ended")
(swap! result conj (str "Best genome: " (:plushy curr-best)
", Total error: " (int (:total-error curr-best)))))
(do (get-generation-data evaluated-pop @gp-gen)
; (get-genomes evaluated-pop)
(reset! gp-pop (repeatedly population-size
#(propel/new-individual evaluated-pop argmap)))
(swap! gp-gen inc)))))
;;;;;;;;;;;;;;;;;;;;;
;; USER CONTROLS ;;
;;;;;;;;;;;;;;;;;;;;;
(def anFrame (r/atom {}))
(defn param-change
"Returns the parameter (<str> name) value <int> inputted, corrected if out-of-bounds or casted if non-int"
[param-name param-value]
(cond (< param-value (get param-min param-name))
(get param-min param-name)
(> param-value (get param-max param-name))
(get param-max param-name)
:else
param-value))
(defn get-argmap []
{:instructions propel/default-instructions
:error-function (get error-functions @error-function)
:max-generations (param-change :generations (int @generations))
:population-size (param-change :population-size (int @population-size))
:max-initial-plushy-size (param-change :max-initial-plushy-size (int @max-initial-plushy-size))
:step-limit (param-change :step-limit (int @step-limit))
:parent-selection (keyword @parent-selection)
:tournament-size (param-change :tournament-size (int @tournament-size))
:umad-rate (param-change :umad-rate (double @umad-rate))
:variation {:umad (param-change :umad (double @umad))
:crossover (param-change :crossover (double @crossover))}
:elitism (boolean @elitism)})
(defn beginning [argmap]
(report-start argmap)
(scatter/set-maxes (:max-generations argmap))
(assoc scatter/yscale-max ".scatter__length" (:max-initial-plushy-size argmap))
(reset! gp-pop (make-population (:instructions argmap)
(:max-initial-plushy-size argmap))))
(defn step-evolve []
(let [argmap (get-argmap)]
(if (= (int @gp-gen) 0)
(beginning argmap))
(propel-gp argmap)
(if (or (< (:total-error (first (sort-pop argmap))) 0.1)
(>= (int @gp-gen) (:max-generations argmap)))
(do (propel-gp argmap)
(reset! evolved? true)))))
(defn run-evolve []
(let [argmap (get-argmap)]
(if (= (int @gp-gen) 0)
(beginning argmap))
(propel-gp argmap)
(if (or (< (:total-error (first (sort-pop argmap))) 0.1)
(>= (int @gp-gen) (:max-generations argmap)))
(do (propel-gp argmap)
(reset! evolved? true))
(reset! anFrame (.requestAnimationFrame js/window run-evolve)))))
(defn stop-evolve []
(.cancelAnimationFrame js/window @anFrame))
;;;;;;;;;;;;;;;;;;;;;;;;;;
;; COMPONENT BUILDING ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn output-report []
(vec (cons :div (mapv #((fn [n] [:div (str n)]) %) @reports))))
(defn output-result []
(vec (cons :div (mapv #((fn [n] [:div [:b (str n)]]) %) @result))))
(defn error-function-input []
[:select {:value @error-function :style (assoc param-input-style :width "150px" :height "18px")
:on-change #(reset! error-function (-> % .-target .-value))}
[:option {:value "regression"} "Regression"]
[:option {:value "string-classification"} "String Classification"]])
(defn parent-selection-input []
[:select {:value @parent-selection :style (assoc param-input-style :width "150px" :height "18px")
:on-change #(reset! parent-selection (-> % .-target .-value))}
[:option {:value :tournament} "Tournament"]
[:option {:value :lexicase} "Lexicase"]])
(defn elitism-input []
[:select {:value @elitism :style (assoc param-input-style :height "18px")
:on-change #(reset! elitism (-> % .-target .-value))}
[:option {:value true} "True"]
[:option {:value false} "False"]])
(defn generations-input []
[:input {:type "number" :value @generations :style param-input-style
:min (get param-min :generations) :max (get param-max :generations)
:disabled (not= (int @gp-gen) 0)
:on-change #(reset! generations (-> % .-target .-value))}])
(defn population-size-input []
[:input {:type "number" :value @population-size :style param-input-style
:min (get param-min :population-size) :max (get param-max :population-size)
:disabled (not= (int @gp-gen) 0)
:on-change #(reset! population-size (-> % .-target .-value))}])
(defn max-initial-plushy-size-input []
[:input {:type "number" :value @max-initial-plushy-size :style param-input-style
:min (get param-min :max-initial-plushy-size) :max (get param-max :max-initial-plushy-size)
:disabled (not= (int @gp-gen) 0)
:on-change #(reset! max-initial-plushy-size (-> % .-target .-value))}])
(defn step-limit-input []
[:input {:type "number" :value @step-limit :style param-input-style
:min (get param-min :step-limit) :max (get param-max :step-limit)
:disabled (not= (int @gp-gen) 0)
:on-change #(reset! step-limit (-> % .-target .-value))}])
(defn tournament-size-input []
[:input {:type "number" :value @tournament-size :style param-input-style
:min (get param-min :tournament-size) :max (get param-max :tournament-size)
:disabled (not= (int @gp-gen) 0)
:on-change #(reset! tournament-size (-> % .-target .-value))}])
(defn umad-rate-input []
[:input {:type "number" :value @umad-rate :style param-input-style
:min (get param-min :umad-rate) :max (get param-max :umad-rate)
:disabled (not= (int @gp-gen) 0)
:on-change #(reset! umad-rate (-> % .-target .-value))}])
(defn umad-input []
[:input {:type "number" :value @umad :style param-input-style
:min (get param-min :umad) :max (get param-max :umad)
:disabled (not= (int @gp-gen) 0)
:on-change #(reset! umad (-> % .-target .-value))}])
(defn crossover-input []
[:input {:type "number" :value @crossover :style param-input-style
:min (get param-min :crossover) :max (get param-max :crossover)
:disabled (not= (int @gp-gen) 0)
:on-change #(reset! crossover (-> % .-target .-value))}])
(defn run-button []
[:input {:type "button" :value "Run" :disabled @evolved?
:style (if @evolved? disabled-style evolve-button-style)
:on-click #(run-evolve)}])
(defn pause-button []
[:input {:type "button" :value "Pause" :disabled @evolved?
:style (if @evolved? disabled-style evolve-button-style)
:on-click #(stop-evolve)}])
(defn step-button []
[:input {:type "button" :value "Step" :disabled @evolved?
:style (if @evolved? disabled-style evolve-button-style)
:on-click #(step-evolve)}])
(defn reset-button []
[:input {:type "button" :value "Reset" :style evolve-button-style
:on-click #(do (reset! reports [])
(reset! gp-gen 0)
(reset! result [])
(reset! evolved? false)
(scatter/reset-plot-data)
(stop-evolve))}])
;;;;;;;;;;;;;
;; Views ;;
;;;;;;;;;;;;;
(defn inputs-component []
[:div
[:table [:tbody
[:tr [:td.parameter "Error function = " [error-function-input]] [:td "the evaluation of performance with a behavior"]]
[:tr [:td.parameter "Max generations = " [generations-input]] [:td "the number of generations for which it will run evolution"]]
[:tr [:td.parameter "Population size = " [population-size-input]] [:td "the number of individuals in the population"]]
[:tr [:td.parameter "Max initial plushy size = " [max-initial-plushy-size-input]] [:td "the limit on how large the program plushy/genome can become"]]
[:tr [:td.parameter "Step limit = " [step-limit-input]] [:td "the limit on how long steps, i.e. due to loop structures, may go"]]
[:tr [:td.parameter "Parent selection = " [parent-selection-input]] [:td "the process/method by which individuals/programs are chosen to reproduce"]]
[:tr [:td.parameter "Tournament size = " [tournament-size-input]] [:td "the number of individuals per tournament bracket"]]
[:tr [:td.parameter "UMAD rate = " [umad-rate-input]] [:td " "]]
[:tr [:td.parameter "Variation: umad = " [umad-input]] [:td " "]]
[:tr [:td.parameter "Variation: crossover = " [crossover-input]] [:td " "]]
[:tr [:td.parameter "Elitism = " [elitism-input]] [:td " "]]]]])
(defn plots-component
"Generates and updates plots as evolution progresses with each generation"
[]
[:table.vis [:tbody
[:tr.header
[:td {:colSpan 2}
[:h3 "Plots"]]]
[:tr
[:td
[:h4 "Best Total Error vs Generation"]
[scatter/scatter-error]]
[:td
[:h4 "Genotypic diversity vs Generation"]
[scatter/scatter-diversity]]]
[:tr
[:td [:h4 "Average genome length vs Generation"]
[scatter/scatter-length]]
[:td]]]])
(defn buttons-component []
[:div
[:table.center {:height "35px"}
[:tbody
[:tr
[:td [run-button] [:spacer-button]]
[:td [pause-button] [:spacer-button]]
[:td [step-button] [:spacer-button]]
[:td [reset-button] [:spacer-button]]]]]])
(defn report-component
"Displays generational reports in <text> format
(Same as whne run on the terminal)"
[]
[:table.vis [:tbody
[:tr.header
[:td [:h3 "Textual Report"]]]
[:tr
[:td [:div.scroll-container
[output-result]
[output-report]]]]]])
(defn population-component
"Visualizes the first INSERT genomes/plushies of the population with
the genes as color-coded segments"
[]
[:table.vis [:tbody
[:tr.header [:td [:h3 "Population"]]]
[:tr
[:td [:div
[:canvas#display-genomes]
;; [:canvas#display-genomes]
]]]]])
(defn push-component
"Generates and updates plots as evolution progresses with each generation"
[]
[:table.vis [:tbody
[:tr.header
[:td
[:h3 "Push Program Interpreter"]]]
[:tr
[:td "COMING SOON"]]]])
(defn footer-component []
[:div.footer
[:p "Chloe Wohlgemuth (cbw975@gmail.com) \t Sung Kwak (skwak22@amherst.edu) \t Lee Spector (lspector@amherst.edu) (MORE TO BE ADDED)"]])
(defn home-page []
[:div
[:div.header
[:h1 "Propeller!"]
[:h2 "INSERT DESCRIPTION HERE"]]
[inputs-component]
[:div.spacer-vertical]
[buttons-component]
[report-component]
[population-component]
[plots-component]
[push-component]
[footer-component]])
;;;;;;;;;;;;;;;;;;;;;;
;; Initialize app ;;
;;;;;;;;;;;;;;;;;;;;;;
(defn mount-root []
(d/render [home-page] (.getElementById js/document "app")))
(defn init! []
(mount-root))
| 9916 | (ns propeller-site.core
(:require
[reagent.core :as r]
[reagent.dom :as d]
[quil.core :as q :include-macros true]
[quil.middleware :as m]
[propeller-site.propeller :as propel]
[propeller-site.scatter :as scatter]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; STYLES & PARAMETERS ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def param-input-style {:border "#555555"
:font-size "15px"
:height "15px"
:line-height "1px"
:width "60px"})
(def evolve-button-style {:width "100px"
:color "#ccff00" :font-size "20px"})
(def disabled-style {:width "100px"
:color "#666666"
:font-size "20px"
:border "#999999"
:background-color "#cccccc"})
(def reports (r/atom []))
(def result (r/atom []))
(def evolved? (r/atom false))
(def gp-gen (r/atom 0))
(def gp-pop (r/atom []))
(def error-function (r/atom "regression"))
(def generations (r/atom 10))
(def population-size (r/atom 10))
(def max-initial-plushy-size (r/atom 50))
(def step-limit (r/atom 100))
(def parent-selection (r/atom :lexicase))
(def tournament-size (r/atom 5))
(def umad-rate (r/atom 0.1))
(def umad (r/atom 0.5))
(def crossover (r/atom 0.5))
(def elitism (r/atom false))
(def error-functions {"regression" propel/regression-error-function
"string-classification" propel/string-classification-error-function})
(def param-max {:generations 300
:population-size 500
:max-initial-plushy-size 100
:step-limit 200
:tournament-size @population-size
:umad-rate 1.0
:umad 1.0
:crossover 1.0})
(def param-min {:generations 0
:population-size 1
:max-initial-plushy-size 1
:step-limit 1
:tournament-size 1
:umad-rate (double 0)
:umad (double 0)
:crossover (double 0)})
;;;;;;;;;;;;;;;;;;;;;;
;; GENOME VISUALS ;;
;;;;;;;;;;;;;;;;;;;;;;
(def gDisplayed? (r/atom false))
(def glength 1000) ; length for genome visual
(def gheight 50) ; height for genome visual
(def gene-colors (r/atom {})) ; gene (push instruction) color (visual representation) map
(def genomes (r/atom [])) ; genomes that are being displayed
(def index (r/atom 0)) ; genome visualization we are displaying
(def test-genome '("" "A" "A" :string_drop false :boolean_and :boolean_and 0))
(defn update-gene-map
"Returns the gene (push instruction) color (visual representation) map
for a coll of given plushies/genomes"
[coll-of-plushies]
(let [genes (distinct (reduce concat coll-of-plushies)) ; instructions/genes that could display
count (count genes)
get-color (fn []
(into [] (take 3 (repeatedly #(rand-int 256)))))
colors (into [] (take count (repeatedly #(get-color))))]
; TODO: Change get-color to be generate more distinctive colors based on which stack, etc
(reset! gDisplayed? true)
(reset! gene-colors (zipmap genes colors))
(reset! genomes []))) ; Assign RGB values (colors) to genes in gene-colors map
(defn get-genome-colors
"Converts a genome of instructions to vector of colors. Each gene replaced with its color (RGB values)"
[genome]
(into [] (map #(get @gene-colors %) genome)))
(defn setup []
(q/frame-rate 30) ; FPS
(q/color-mode :hsb) ; HSB (HSV) rather than default RGB
{:color 0 :angle 0 :gene-count 0}) ; setup returns initial state, containing the circle color and position
(defn update-state
"Update the sketch state by changing the (current) gene color and position"
[state]
(if @gDisplayed?
state
(let [curr-genome (get @genomes @index)
n-genes (count curr-genome)
gene-width (/ glength n-genes)] ; to convert bin index to pixel offset in the x-dimension
(if (= (:gene-count state) n-genes)
(do (if (< @index (count @genomes))
(swap! index inc)
(swap! gDisplayed? not))
{:color (nth (get @genomes @index) 0)
:pos 0
:gene-count 0})
{:color (nth curr-genome (:gene-count state))
:pos (* (:gene-count state) gene-width)
:gene-count (inc (:gene-count state))}))))
(defn draw-state
"(Quil) Sketch a genome (rectangular row) of color-coded genes."
[state]
(q/background 240) ; Clear the sketch by filling it with light-grey color.
(q/fill (:color state) 255 255) ; Set circle color.
(let [curr-genome (get @genomes @index)
n-genes (count curr-genome)
gene-width (/ glength n-genes) ; to convert bin index to pixel offset in the x-dimension
x-pos (* (:gene-count state) gene-width)]
(q/rect x-pos 0 gene-width gheight)))
(q/defsketch display-genomes
:host "display-genomes"
:size [glength gheight]
:setup setup ; setup function called only once, during sketch initialization
:update update-state ; update-state is called on each iteration before draw-state
:draw draw-state
:middleware [m/fun-mode])
;;;;;;;;;;;;;;;;;;;;
;; PLOT VISUALS ;;
;;;;;;;;;;;;;;;;;;;;
(def curr-best-program (r/atom []))
(def curr-best-errors (r/atom []))
(defn get-generation-data
"Collects population data each generation"
[pop gen]
(let [; data from evaluated population
best (if (contains? (first pop) :total-error)
(first pop)
(throw (js/Error. (str "Called when total-error was not calculated"))))
best-errors (:errors best)
best-plushy (:plushy best)
best-program (propel/plushy->push (:plushy best))]
(reset! curr-best-program best-program)
(reset! curr-best-errors best-errors)
(scatter/update-plot-data pop gen)
{:best-program best-program
:best-plushy best-plushy
:best-errors best-errors}))
;;;;;;;;;;;;;;;;;;;;;;
;; GP FUNCTION(S) ;;
;;;;;;;;;;;;;;;;;;;;;;
(defn report-start [argmap]
(swap! reports conj (str "***************************"))
(swap! reports conj (str " ~ Error function: " @error-function " for " (:max-generations argmap) " generations with " (:population-size argmap) " individuals"))
(swap! reports conj (str " ~ Max Initial Plushy Size of " (:max-initial-plushy-size argmap) " with a step limit of " (:step-limit argmap)))
(swap! reports conj (str " ~ Parent Selection via " (:parent-selection argmap) " with tournament size of " (:tournament-size argmap)))
(swap! reports conj (str " ~ Umad-rate: " (:umad-rate argmap) " , umad: " (get-in argmap [:variation :umad]) " , crossover: " (get-in argmap [:variation :crossover]) " , elitism " (:elitism argmap)))
(swap! reports conj (str "RUNNING PROPELLER GP!"))
(swap! reports conj (str " ***************************")))
(defn make-population [instr mips]
(repeatedly (int @population-size)
#(hash-map :plushy
(propel/make-random-plushy instr mips))))
(defn evaluate-pop [argmap]
(map (partial (:error-function argmap) argmap)
@gp-pop))
(defn sort-pop
"Returns the curent population of items sorted by their :total-error's"
[argmap]
(sort-by :total-error (evaluate-pop argmap)))
(defn propel-gp
"Runs genetic programming to solve, or approximately solve, a problem in the
context (error-function, gp) of the given population-size, # generations, etc."
[{:keys [population-size max-generations error-function
instructions max-initial-plushy-size] :as argmap}]
(let [evaluated-pop (sort-pop argmap)
curr-best (first evaluated-pop)]
(swap! reports conj (propel/report evaluated-pop (int @gp-gen)))
(if (or (< (:total-error curr-best) 0.1)
(>= (int @gp-gen) max-generations))
(do (get-generation-data evaluated-pop @gp-gen)
; (get-genomes evaluated-pop)
(swap! result conj "Ended")
(swap! result conj (str "Best genome: " (:plushy curr-best)
", Total error: " (int (:total-error curr-best)))))
(do (get-generation-data evaluated-pop @gp-gen)
; (get-genomes evaluated-pop)
(reset! gp-pop (repeatedly population-size
#(propel/new-individual evaluated-pop argmap)))
(swap! gp-gen inc)))))
;;;;;;;;;;;;;;;;;;;;;
;; USER CONTROLS ;;
;;;;;;;;;;;;;;;;;;;;;
(def anFrame (r/atom {}))
(defn param-change
"Returns the parameter (<str> name) value <int> inputted, corrected if out-of-bounds or casted if non-int"
[param-name param-value]
(cond (< param-value (get param-min param-name))
(get param-min param-name)
(> param-value (get param-max param-name))
(get param-max param-name)
:else
param-value))
(defn get-argmap []
{:instructions propel/default-instructions
:error-function (get error-functions @error-function)
:max-generations (param-change :generations (int @generations))
:population-size (param-change :population-size (int @population-size))
:max-initial-plushy-size (param-change :max-initial-plushy-size (int @max-initial-plushy-size))
:step-limit (param-change :step-limit (int @step-limit))
:parent-selection (keyword @parent-selection)
:tournament-size (param-change :tournament-size (int @tournament-size))
:umad-rate (param-change :umad-rate (double @umad-rate))
:variation {:umad (param-change :umad (double @umad))
:crossover (param-change :crossover (double @crossover))}
:elitism (boolean @elitism)})
(defn beginning [argmap]
(report-start argmap)
(scatter/set-maxes (:max-generations argmap))
(assoc scatter/yscale-max ".scatter__length" (:max-initial-plushy-size argmap))
(reset! gp-pop (make-population (:instructions argmap)
(:max-initial-plushy-size argmap))))
(defn step-evolve []
(let [argmap (get-argmap)]
(if (= (int @gp-gen) 0)
(beginning argmap))
(propel-gp argmap)
(if (or (< (:total-error (first (sort-pop argmap))) 0.1)
(>= (int @gp-gen) (:max-generations argmap)))
(do (propel-gp argmap)
(reset! evolved? true)))))
(defn run-evolve []
(let [argmap (get-argmap)]
(if (= (int @gp-gen) 0)
(beginning argmap))
(propel-gp argmap)
(if (or (< (:total-error (first (sort-pop argmap))) 0.1)
(>= (int @gp-gen) (:max-generations argmap)))
(do (propel-gp argmap)
(reset! evolved? true))
(reset! anFrame (.requestAnimationFrame js/window run-evolve)))))
(defn stop-evolve []
(.cancelAnimationFrame js/window @anFrame))
;;;;;;;;;;;;;;;;;;;;;;;;;;
;; COMPONENT BUILDING ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn output-report []
(vec (cons :div (mapv #((fn [n] [:div (str n)]) %) @reports))))
(defn output-result []
(vec (cons :div (mapv #((fn [n] [:div [:b (str n)]]) %) @result))))
(defn error-function-input []
[:select {:value @error-function :style (assoc param-input-style :width "150px" :height "18px")
:on-change #(reset! error-function (-> % .-target .-value))}
[:option {:value "regression"} "Regression"]
[:option {:value "string-classification"} "String Classification"]])
(defn parent-selection-input []
[:select {:value @parent-selection :style (assoc param-input-style :width "150px" :height "18px")
:on-change #(reset! parent-selection (-> % .-target .-value))}
[:option {:value :tournament} "Tournament"]
[:option {:value :lexicase} "Lexicase"]])
(defn elitism-input []
[:select {:value @elitism :style (assoc param-input-style :height "18px")
:on-change #(reset! elitism (-> % .-target .-value))}
[:option {:value true} "True"]
[:option {:value false} "False"]])
(defn generations-input []
[:input {:type "number" :value @generations :style param-input-style
:min (get param-min :generations) :max (get param-max :generations)
:disabled (not= (int @gp-gen) 0)
:on-change #(reset! generations (-> % .-target .-value))}])
(defn population-size-input []
[:input {:type "number" :value @population-size :style param-input-style
:min (get param-min :population-size) :max (get param-max :population-size)
:disabled (not= (int @gp-gen) 0)
:on-change #(reset! population-size (-> % .-target .-value))}])
(defn max-initial-plushy-size-input []
[:input {:type "number" :value @max-initial-plushy-size :style param-input-style
:min (get param-min :max-initial-plushy-size) :max (get param-max :max-initial-plushy-size)
:disabled (not= (int @gp-gen) 0)
:on-change #(reset! max-initial-plushy-size (-> % .-target .-value))}])
(defn step-limit-input []
[:input {:type "number" :value @step-limit :style param-input-style
:min (get param-min :step-limit) :max (get param-max :step-limit)
:disabled (not= (int @gp-gen) 0)
:on-change #(reset! step-limit (-> % .-target .-value))}])
(defn tournament-size-input []
[:input {:type "number" :value @tournament-size :style param-input-style
:min (get param-min :tournament-size) :max (get param-max :tournament-size)
:disabled (not= (int @gp-gen) 0)
:on-change #(reset! tournament-size (-> % .-target .-value))}])
(defn umad-rate-input []
[:input {:type "number" :value @umad-rate :style param-input-style
:min (get param-min :umad-rate) :max (get param-max :umad-rate)
:disabled (not= (int @gp-gen) 0)
:on-change #(reset! umad-rate (-> % .-target .-value))}])
(defn umad-input []
[:input {:type "number" :value @umad :style param-input-style
:min (get param-min :umad) :max (get param-max :umad)
:disabled (not= (int @gp-gen) 0)
:on-change #(reset! umad (-> % .-target .-value))}])
(defn crossover-input []
[:input {:type "number" :value @crossover :style param-input-style
:min (get param-min :crossover) :max (get param-max :crossover)
:disabled (not= (int @gp-gen) 0)
:on-change #(reset! crossover (-> % .-target .-value))}])
(defn run-button []
[:input {:type "button" :value "Run" :disabled @evolved?
:style (if @evolved? disabled-style evolve-button-style)
:on-click #(run-evolve)}])
(defn pause-button []
[:input {:type "button" :value "Pause" :disabled @evolved?
:style (if @evolved? disabled-style evolve-button-style)
:on-click #(stop-evolve)}])
(defn step-button []
[:input {:type "button" :value "Step" :disabled @evolved?
:style (if @evolved? disabled-style evolve-button-style)
:on-click #(step-evolve)}])
(defn reset-button []
[:input {:type "button" :value "Reset" :style evolve-button-style
:on-click #(do (reset! reports [])
(reset! gp-gen 0)
(reset! result [])
(reset! evolved? false)
(scatter/reset-plot-data)
(stop-evolve))}])
;;;;;;;;;;;;;
;; Views ;;
;;;;;;;;;;;;;
(defn inputs-component []
[:div
[:table [:tbody
[:tr [:td.parameter "Error function = " [error-function-input]] [:td "the evaluation of performance with a behavior"]]
[:tr [:td.parameter "Max generations = " [generations-input]] [:td "the number of generations for which it will run evolution"]]
[:tr [:td.parameter "Population size = " [population-size-input]] [:td "the number of individuals in the population"]]
[:tr [:td.parameter "Max initial plushy size = " [max-initial-plushy-size-input]] [:td "the limit on how large the program plushy/genome can become"]]
[:tr [:td.parameter "Step limit = " [step-limit-input]] [:td "the limit on how long steps, i.e. due to loop structures, may go"]]
[:tr [:td.parameter "Parent selection = " [parent-selection-input]] [:td "the process/method by which individuals/programs are chosen to reproduce"]]
[:tr [:td.parameter "Tournament size = " [tournament-size-input]] [:td "the number of individuals per tournament bracket"]]
[:tr [:td.parameter "UMAD rate = " [umad-rate-input]] [:td " "]]
[:tr [:td.parameter "Variation: umad = " [umad-input]] [:td " "]]
[:tr [:td.parameter "Variation: crossover = " [crossover-input]] [:td " "]]
[:tr [:td.parameter "Elitism = " [elitism-input]] [:td " "]]]]])
(defn plots-component
"Generates and updates plots as evolution progresses with each generation"
[]
[:table.vis [:tbody
[:tr.header
[:td {:colSpan 2}
[:h3 "Plots"]]]
[:tr
[:td
[:h4 "Best Total Error vs Generation"]
[scatter/scatter-error]]
[:td
[:h4 "Genotypic diversity vs Generation"]
[scatter/scatter-diversity]]]
[:tr
[:td [:h4 "Average genome length vs Generation"]
[scatter/scatter-length]]
[:td]]]])
(defn buttons-component []
[:div
[:table.center {:height "35px"}
[:tbody
[:tr
[:td [run-button] [:spacer-button]]
[:td [pause-button] [:spacer-button]]
[:td [step-button] [:spacer-button]]
[:td [reset-button] [:spacer-button]]]]]])
(defn report-component
"Displays generational reports in <text> format
(Same as whne run on the terminal)"
[]
[:table.vis [:tbody
[:tr.header
[:td [:h3 "Textual Report"]]]
[:tr
[:td [:div.scroll-container
[output-result]
[output-report]]]]]])
(defn population-component
"Visualizes the first INSERT genomes/plushies of the population with
the genes as color-coded segments"
[]
[:table.vis [:tbody
[:tr.header [:td [:h3 "Population"]]]
[:tr
[:td [:div
[:canvas#display-genomes]
;; [:canvas#display-genomes]
]]]]])
(defn push-component
"Generates and updates plots as evolution progresses with each generation"
[]
[:table.vis [:tbody
[:tr.header
[:td
[:h3 "Push Program Interpreter"]]]
[:tr
[:td "COMING SOON"]]]])
(defn footer-component []
[:div.footer
[:p "<NAME> (<EMAIL>) \t <NAME> (<EMAIL>) \t <NAME> (<EMAIL>) (MORE TO BE ADDED)"]])
(defn home-page []
[:div
[:div.header
[:h1 "Propeller!"]
[:h2 "INSERT DESCRIPTION HERE"]]
[inputs-component]
[:div.spacer-vertical]
[buttons-component]
[report-component]
[population-component]
[plots-component]
[push-component]
[footer-component]])
;;;;;;;;;;;;;;;;;;;;;;
;; Initialize app ;;
;;;;;;;;;;;;;;;;;;;;;;
(defn mount-root []
(d/render [home-page] (.getElementById js/document "app")))
(defn init! []
(mount-root))
| true | (ns propeller-site.core
(:require
[reagent.core :as r]
[reagent.dom :as d]
[quil.core :as q :include-macros true]
[quil.middleware :as m]
[propeller-site.propeller :as propel]
[propeller-site.scatter :as scatter]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; STYLES & PARAMETERS ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def param-input-style {:border "#555555"
:font-size "15px"
:height "15px"
:line-height "1px"
:width "60px"})
(def evolve-button-style {:width "100px"
:color "#ccff00" :font-size "20px"})
(def disabled-style {:width "100px"
:color "#666666"
:font-size "20px"
:border "#999999"
:background-color "#cccccc"})
(def reports (r/atom []))
(def result (r/atom []))
(def evolved? (r/atom false))
(def gp-gen (r/atom 0))
(def gp-pop (r/atom []))
(def error-function (r/atom "regression"))
(def generations (r/atom 10))
(def population-size (r/atom 10))
(def max-initial-plushy-size (r/atom 50))
(def step-limit (r/atom 100))
(def parent-selection (r/atom :lexicase))
(def tournament-size (r/atom 5))
(def umad-rate (r/atom 0.1))
(def umad (r/atom 0.5))
(def crossover (r/atom 0.5))
(def elitism (r/atom false))
(def error-functions {"regression" propel/regression-error-function
"string-classification" propel/string-classification-error-function})
(def param-max {:generations 300
:population-size 500
:max-initial-plushy-size 100
:step-limit 200
:tournament-size @population-size
:umad-rate 1.0
:umad 1.0
:crossover 1.0})
(def param-min {:generations 0
:population-size 1
:max-initial-plushy-size 1
:step-limit 1
:tournament-size 1
:umad-rate (double 0)
:umad (double 0)
:crossover (double 0)})
;;;;;;;;;;;;;;;;;;;;;;
;; GENOME VISUALS ;;
;;;;;;;;;;;;;;;;;;;;;;
(def gDisplayed? (r/atom false))
(def glength 1000) ; length for genome visual
(def gheight 50) ; height for genome visual
(def gene-colors (r/atom {})) ; gene (push instruction) color (visual representation) map
(def genomes (r/atom [])) ; genomes that are being displayed
(def index (r/atom 0)) ; genome visualization we are displaying
(def test-genome '("" "A" "A" :string_drop false :boolean_and :boolean_and 0))
(defn update-gene-map
"Returns the gene (push instruction) color (visual representation) map
for a coll of given plushies/genomes"
[coll-of-plushies]
(let [genes (distinct (reduce concat coll-of-plushies)) ; instructions/genes that could display
count (count genes)
get-color (fn []
(into [] (take 3 (repeatedly #(rand-int 256)))))
colors (into [] (take count (repeatedly #(get-color))))]
; TODO: Change get-color to be generate more distinctive colors based on which stack, etc
(reset! gDisplayed? true)
(reset! gene-colors (zipmap genes colors))
(reset! genomes []))) ; Assign RGB values (colors) to genes in gene-colors map
(defn get-genome-colors
"Converts a genome of instructions to vector of colors. Each gene replaced with its color (RGB values)"
[genome]
(into [] (map #(get @gene-colors %) genome)))
(defn setup []
(q/frame-rate 30) ; FPS
(q/color-mode :hsb) ; HSB (HSV) rather than default RGB
{:color 0 :angle 0 :gene-count 0}) ; setup returns initial state, containing the circle color and position
(defn update-state
"Update the sketch state by changing the (current) gene color and position"
[state]
(if @gDisplayed?
state
(let [curr-genome (get @genomes @index)
n-genes (count curr-genome)
gene-width (/ glength n-genes)] ; to convert bin index to pixel offset in the x-dimension
(if (= (:gene-count state) n-genes)
(do (if (< @index (count @genomes))
(swap! index inc)
(swap! gDisplayed? not))
{:color (nth (get @genomes @index) 0)
:pos 0
:gene-count 0})
{:color (nth curr-genome (:gene-count state))
:pos (* (:gene-count state) gene-width)
:gene-count (inc (:gene-count state))}))))
(defn draw-state
"(Quil) Sketch a genome (rectangular row) of color-coded genes."
[state]
(q/background 240) ; Clear the sketch by filling it with light-grey color.
(q/fill (:color state) 255 255) ; Set circle color.
(let [curr-genome (get @genomes @index)
n-genes (count curr-genome)
gene-width (/ glength n-genes) ; to convert bin index to pixel offset in the x-dimension
x-pos (* (:gene-count state) gene-width)]
(q/rect x-pos 0 gene-width gheight)))
(q/defsketch display-genomes
:host "display-genomes"
:size [glength gheight]
:setup setup ; setup function called only once, during sketch initialization
:update update-state ; update-state is called on each iteration before draw-state
:draw draw-state
:middleware [m/fun-mode])
;;;;;;;;;;;;;;;;;;;;
;; PLOT VISUALS ;;
;;;;;;;;;;;;;;;;;;;;
(def curr-best-program (r/atom []))
(def curr-best-errors (r/atom []))
(defn get-generation-data
"Collects population data each generation"
[pop gen]
(let [; data from evaluated population
best (if (contains? (first pop) :total-error)
(first pop)
(throw (js/Error. (str "Called when total-error was not calculated"))))
best-errors (:errors best)
best-plushy (:plushy best)
best-program (propel/plushy->push (:plushy best))]
(reset! curr-best-program best-program)
(reset! curr-best-errors best-errors)
(scatter/update-plot-data pop gen)
{:best-program best-program
:best-plushy best-plushy
:best-errors best-errors}))
;;;;;;;;;;;;;;;;;;;;;;
;; GP FUNCTION(S) ;;
;;;;;;;;;;;;;;;;;;;;;;
(defn report-start [argmap]
(swap! reports conj (str "***************************"))
(swap! reports conj (str " ~ Error function: " @error-function " for " (:max-generations argmap) " generations with " (:population-size argmap) " individuals"))
(swap! reports conj (str " ~ Max Initial Plushy Size of " (:max-initial-plushy-size argmap) " with a step limit of " (:step-limit argmap)))
(swap! reports conj (str " ~ Parent Selection via " (:parent-selection argmap) " with tournament size of " (:tournament-size argmap)))
(swap! reports conj (str " ~ Umad-rate: " (:umad-rate argmap) " , umad: " (get-in argmap [:variation :umad]) " , crossover: " (get-in argmap [:variation :crossover]) " , elitism " (:elitism argmap)))
(swap! reports conj (str "RUNNING PROPELLER GP!"))
(swap! reports conj (str " ***************************")))
(defn make-population [instr mips]
(repeatedly (int @population-size)
#(hash-map :plushy
(propel/make-random-plushy instr mips))))
(defn evaluate-pop [argmap]
(map (partial (:error-function argmap) argmap)
@gp-pop))
(defn sort-pop
"Returns the curent population of items sorted by their :total-error's"
[argmap]
(sort-by :total-error (evaluate-pop argmap)))
(defn propel-gp
"Runs genetic programming to solve, or approximately solve, a problem in the
context (error-function, gp) of the given population-size, # generations, etc."
[{:keys [population-size max-generations error-function
instructions max-initial-plushy-size] :as argmap}]
(let [evaluated-pop (sort-pop argmap)
curr-best (first evaluated-pop)]
(swap! reports conj (propel/report evaluated-pop (int @gp-gen)))
(if (or (< (:total-error curr-best) 0.1)
(>= (int @gp-gen) max-generations))
(do (get-generation-data evaluated-pop @gp-gen)
; (get-genomes evaluated-pop)
(swap! result conj "Ended")
(swap! result conj (str "Best genome: " (:plushy curr-best)
", Total error: " (int (:total-error curr-best)))))
(do (get-generation-data evaluated-pop @gp-gen)
; (get-genomes evaluated-pop)
(reset! gp-pop (repeatedly population-size
#(propel/new-individual evaluated-pop argmap)))
(swap! gp-gen inc)))))
;;;;;;;;;;;;;;;;;;;;;
;; USER CONTROLS ;;
;;;;;;;;;;;;;;;;;;;;;
(def anFrame (r/atom {}))
(defn param-change
"Returns the parameter (<str> name) value <int> inputted, corrected if out-of-bounds or casted if non-int"
[param-name param-value]
(cond (< param-value (get param-min param-name))
(get param-min param-name)
(> param-value (get param-max param-name))
(get param-max param-name)
:else
param-value))
(defn get-argmap []
{:instructions propel/default-instructions
:error-function (get error-functions @error-function)
:max-generations (param-change :generations (int @generations))
:population-size (param-change :population-size (int @population-size))
:max-initial-plushy-size (param-change :max-initial-plushy-size (int @max-initial-plushy-size))
:step-limit (param-change :step-limit (int @step-limit))
:parent-selection (keyword @parent-selection)
:tournament-size (param-change :tournament-size (int @tournament-size))
:umad-rate (param-change :umad-rate (double @umad-rate))
:variation {:umad (param-change :umad (double @umad))
:crossover (param-change :crossover (double @crossover))}
:elitism (boolean @elitism)})
(defn beginning [argmap]
(report-start argmap)
(scatter/set-maxes (:max-generations argmap))
(assoc scatter/yscale-max ".scatter__length" (:max-initial-plushy-size argmap))
(reset! gp-pop (make-population (:instructions argmap)
(:max-initial-plushy-size argmap))))
(defn step-evolve []
(let [argmap (get-argmap)]
(if (= (int @gp-gen) 0)
(beginning argmap))
(propel-gp argmap)
(if (or (< (:total-error (first (sort-pop argmap))) 0.1)
(>= (int @gp-gen) (:max-generations argmap)))
(do (propel-gp argmap)
(reset! evolved? true)))))
(defn run-evolve []
(let [argmap (get-argmap)]
(if (= (int @gp-gen) 0)
(beginning argmap))
(propel-gp argmap)
(if (or (< (:total-error (first (sort-pop argmap))) 0.1)
(>= (int @gp-gen) (:max-generations argmap)))
(do (propel-gp argmap)
(reset! evolved? true))
(reset! anFrame (.requestAnimationFrame js/window run-evolve)))))
(defn stop-evolve []
(.cancelAnimationFrame js/window @anFrame))
;;;;;;;;;;;;;;;;;;;;;;;;;;
;; COMPONENT BUILDING ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn output-report []
(vec (cons :div (mapv #((fn [n] [:div (str n)]) %) @reports))))
(defn output-result []
(vec (cons :div (mapv #((fn [n] [:div [:b (str n)]]) %) @result))))
(defn error-function-input []
[:select {:value @error-function :style (assoc param-input-style :width "150px" :height "18px")
:on-change #(reset! error-function (-> % .-target .-value))}
[:option {:value "regression"} "Regression"]
[:option {:value "string-classification"} "String Classification"]])
(defn parent-selection-input []
[:select {:value @parent-selection :style (assoc param-input-style :width "150px" :height "18px")
:on-change #(reset! parent-selection (-> % .-target .-value))}
[:option {:value :tournament} "Tournament"]
[:option {:value :lexicase} "Lexicase"]])
(defn elitism-input []
[:select {:value @elitism :style (assoc param-input-style :height "18px")
:on-change #(reset! elitism (-> % .-target .-value))}
[:option {:value true} "True"]
[:option {:value false} "False"]])
(defn generations-input []
[:input {:type "number" :value @generations :style param-input-style
:min (get param-min :generations) :max (get param-max :generations)
:disabled (not= (int @gp-gen) 0)
:on-change #(reset! generations (-> % .-target .-value))}])
(defn population-size-input []
[:input {:type "number" :value @population-size :style param-input-style
:min (get param-min :population-size) :max (get param-max :population-size)
:disabled (not= (int @gp-gen) 0)
:on-change #(reset! population-size (-> % .-target .-value))}])
(defn max-initial-plushy-size-input []
[:input {:type "number" :value @max-initial-plushy-size :style param-input-style
:min (get param-min :max-initial-plushy-size) :max (get param-max :max-initial-plushy-size)
:disabled (not= (int @gp-gen) 0)
:on-change #(reset! max-initial-plushy-size (-> % .-target .-value))}])
(defn step-limit-input []
[:input {:type "number" :value @step-limit :style param-input-style
:min (get param-min :step-limit) :max (get param-max :step-limit)
:disabled (not= (int @gp-gen) 0)
:on-change #(reset! step-limit (-> % .-target .-value))}])
(defn tournament-size-input []
[:input {:type "number" :value @tournament-size :style param-input-style
:min (get param-min :tournament-size) :max (get param-max :tournament-size)
:disabled (not= (int @gp-gen) 0)
:on-change #(reset! tournament-size (-> % .-target .-value))}])
(defn umad-rate-input []
[:input {:type "number" :value @umad-rate :style param-input-style
:min (get param-min :umad-rate) :max (get param-max :umad-rate)
:disabled (not= (int @gp-gen) 0)
:on-change #(reset! umad-rate (-> % .-target .-value))}])
(defn umad-input []
[:input {:type "number" :value @umad :style param-input-style
:min (get param-min :umad) :max (get param-max :umad)
:disabled (not= (int @gp-gen) 0)
:on-change #(reset! umad (-> % .-target .-value))}])
(defn crossover-input []
[:input {:type "number" :value @crossover :style param-input-style
:min (get param-min :crossover) :max (get param-max :crossover)
:disabled (not= (int @gp-gen) 0)
:on-change #(reset! crossover (-> % .-target .-value))}])
(defn run-button []
[:input {:type "button" :value "Run" :disabled @evolved?
:style (if @evolved? disabled-style evolve-button-style)
:on-click #(run-evolve)}])
(defn pause-button []
[:input {:type "button" :value "Pause" :disabled @evolved?
:style (if @evolved? disabled-style evolve-button-style)
:on-click #(stop-evolve)}])
(defn step-button []
[:input {:type "button" :value "Step" :disabled @evolved?
:style (if @evolved? disabled-style evolve-button-style)
:on-click #(step-evolve)}])
(defn reset-button []
[:input {:type "button" :value "Reset" :style evolve-button-style
:on-click #(do (reset! reports [])
(reset! gp-gen 0)
(reset! result [])
(reset! evolved? false)
(scatter/reset-plot-data)
(stop-evolve))}])
;;;;;;;;;;;;;
;; Views ;;
;;;;;;;;;;;;;
(defn inputs-component []
[:div
[:table [:tbody
[:tr [:td.parameter "Error function = " [error-function-input]] [:td "the evaluation of performance with a behavior"]]
[:tr [:td.parameter "Max generations = " [generations-input]] [:td "the number of generations for which it will run evolution"]]
[:tr [:td.parameter "Population size = " [population-size-input]] [:td "the number of individuals in the population"]]
[:tr [:td.parameter "Max initial plushy size = " [max-initial-plushy-size-input]] [:td "the limit on how large the program plushy/genome can become"]]
[:tr [:td.parameter "Step limit = " [step-limit-input]] [:td "the limit on how long steps, i.e. due to loop structures, may go"]]
[:tr [:td.parameter "Parent selection = " [parent-selection-input]] [:td "the process/method by which individuals/programs are chosen to reproduce"]]
[:tr [:td.parameter "Tournament size = " [tournament-size-input]] [:td "the number of individuals per tournament bracket"]]
[:tr [:td.parameter "UMAD rate = " [umad-rate-input]] [:td " "]]
[:tr [:td.parameter "Variation: umad = " [umad-input]] [:td " "]]
[:tr [:td.parameter "Variation: crossover = " [crossover-input]] [:td " "]]
[:tr [:td.parameter "Elitism = " [elitism-input]] [:td " "]]]]])
(defn plots-component
"Generates and updates plots as evolution progresses with each generation"
[]
[:table.vis [:tbody
[:tr.header
[:td {:colSpan 2}
[:h3 "Plots"]]]
[:tr
[:td
[:h4 "Best Total Error vs Generation"]
[scatter/scatter-error]]
[:td
[:h4 "Genotypic diversity vs Generation"]
[scatter/scatter-diversity]]]
[:tr
[:td [:h4 "Average genome length vs Generation"]
[scatter/scatter-length]]
[:td]]]])
(defn buttons-component []
[:div
[:table.center {:height "35px"}
[:tbody
[:tr
[:td [run-button] [:spacer-button]]
[:td [pause-button] [:spacer-button]]
[:td [step-button] [:spacer-button]]
[:td [reset-button] [:spacer-button]]]]]])
(defn report-component
"Displays generational reports in <text> format
(Same as whne run on the terminal)"
[]
[:table.vis [:tbody
[:tr.header
[:td [:h3 "Textual Report"]]]
[:tr
[:td [:div.scroll-container
[output-result]
[output-report]]]]]])
(defn population-component
"Visualizes the first INSERT genomes/plushies of the population with
the genes as color-coded segments"
[]
[:table.vis [:tbody
[:tr.header [:td [:h3 "Population"]]]
[:tr
[:td [:div
[:canvas#display-genomes]
;; [:canvas#display-genomes]
]]]]])
(defn push-component
"Generates and updates plots as evolution progresses with each generation"
[]
[:table.vis [:tbody
[:tr.header
[:td
[:h3 "Push Program Interpreter"]]]
[:tr
[:td "COMING SOON"]]]])
(defn footer-component []
[:div.footer
[:p "PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) \t PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) \t PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) (MORE TO BE ADDED)"]])
(defn home-page []
[:div
[:div.header
[:h1 "Propeller!"]
[:h2 "INSERT DESCRIPTION HERE"]]
[inputs-component]
[:div.spacer-vertical]
[buttons-component]
[report-component]
[population-component]
[plots-component]
[push-component]
[footer-component]])
;;;;;;;;;;;;;;;;;;;;;;
;; Initialize app ;;
;;;;;;;;;;;;;;;;;;;;;;
(defn mount-root []
(d/render [home-page] (.getElementById js/document "app")))
(defn init! []
(mount-root))
|
[
{
"context": "-encoding \"utf-8\"\n :remote-addr \"127.0.0.1\"\n :server-port 8080\n :con",
"end": 6926,
"score": 0.9997774958610535,
"start": 6917,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " \"dev-resources/keystore.jks\"\n :key-password \"password\")\n (let [response (http/get \"https://localhost:8",
"end": 9261,
"score": 0.9986942410469055,
"start": 9253,
"tag": "PASSWORD",
"value": "password"
}
] | web/test/immutant/web_test.clj | kfowler/immutant | 0 | ;; Copyright 2014-2015 Red Hat, Inc, and individual contributors.
;;
;; 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 immutant.web-test
(:require [clojure.test :refer :all]
[clojure.set :refer :all]
[immutant.util :as u]
[immutant.web :refer :all]
[immutant.web.internal.wunderboss :refer [create-defaults register-defaults]]
[immutant.web.middleware :refer (wrap-session)]
[testing.web :refer [get-body get-response hello handler]]
[testing.app]
[testing.hello.service :as pedestal]
[ring.middleware.resource :refer [wrap-resource]]
[ring.util.response :refer (charset)]
[clj-http.client :as http]
[immutant.web.undertow :as undertow])
(:import clojure.lang.ExceptionInfo
java.net.ConnectException))
(u/set-log-level! (or (System/getenv "LOG_LEVEL") :ERROR))
(use-fixtures :each u/reset-fixture)
(def url "http://localhost:8080/")
(def url2 "http://localhost:8081/")
(defn pause-on-windows []
;; windows is slow to release closed ports, so we pause to allow that to happen
(when (re-find #"(?i)^windows" (System/getProperty "os.name"))
(Thread/sleep 100)))
(deftest mount-and-remount-pedestal-service
(run pedestal/servlet)
(is (= "Hello World!" (get-body url)))
(run pedestal/servlet)
(is (= "Hello World!" (get-body url))))
(deftest nil-body
(run (constantly {:status 200 :body nil}))
(is (nil? (get-body url))))
(deftest run-takes-kwargs
(run hello :path "/kwarg")
(is (= "hello" (get-body (str url "kwarg")))))
(deftest run-returns-default-opts
(let [opts (run hello)]
(is (subset? (-> (merge register-defaults create-defaults) keys set)
(-> opts keys set)))))
(deftest run-accepts-a-var
(run #'hello)
(is (= "hello" (get-body url))))
(deftest run-accepts-an-http-handler
(run (immutant.web.internal.undertow/create-http-handler hello))
(is (= "hello" (get-body url))))
(deftest run-returns-passed-opts-with-defaults
(let [opts (run hello {:path "/abc"})]
(is (subset? (-> (merge register-defaults create-defaults) keys set)
(-> opts keys set)))
(is (= "/abc" (:path opts)))))
(deftest run-should-throw-with-invalid-options
(is (thrown? IllegalArgumentException (run hello {:invalid true}))))
(deftest stop-should-throw-with-invalid-options
(is (thrown? IllegalArgumentException (stop {:invalid true}))))
(deftest stop-without-args-stops-default-context
(run hello)
(is (= "hello" (get-body url)))
(run (handler "howdy") {:path "/howdy"})
(is (= "howdy" (get-body (str url "howdy"))))
(stop)
(is (= "howdy" (get-body (str url "howdy"))))
(is (= 404 (get-body url))))
(deftest stop-with-context-stops-that-context
(run hello)
(is (= "hello" (get-body url)))
(run (handler "howdy") {:path "/howdy"})
(is (= "howdy" (get-body (str url "howdy"))))
(stop {:path "/howdy"})
(is (= "hello" (get-body url)))
(is (= "hello" (get-body (str url "howdy")))))
(deftest stop-should-accept-kwargs
(run hello)
(is (stop :path "/")))
(deftest stopping-last-handler-stops-the-server
(let [root-opts (run hello)]
(is (= "hello" (get-body url)))
(stop root-opts))
(is (thrown? ConnectException (get-body url))))
(deftest stop-stops-the-requested-server
(run hello)
(is (= "hello" (get-body url)))
(run hello {:port 8081})
(is (= "hello" (get-body url2)))
(stop {:port 8081})
(is (= "hello" (get-body url)))
(is (thrown? ConnectException (get-body url2))))
(deftest stop-stops-the-default-server-even-with-explicit-opts
(run hello)
(is (= "hello" (get-body url)))
(stop {:port 8080})
(is (thrown? ConnectException (get-body url))))
(deftest string-args-to-run-should-work
(run hello {"port" "8081"})
(is (= "hello" (get-body url2))))
(deftest string-args-to-stop-should-work
(run hello)
(run (handler "howdy") {"path" "/howdy"})
(is (= "hello" (get-body url)))
(is (= "howdy" (get-body (str url "howdy"))))
(stop {"path" "/howdy"})
(is (= "hello" (get-body (str url "howdy")))))
(deftest run-with-threading
(-> (run hello)
(assoc :path "/howdy")
(->> (run (handler "howdy")))
(assoc :port 8081)
(->> (run (handler "howdy"))))
(is (= "hello" (get-body url)))
(is (= "howdy" (get-body (str url "howdy"))))
(is (= "howdy" (get-body (str url2 "howdy")))))
(deftest stop-should-stop-all-threaded-apps
(let [everything (-> (run hello)
(assoc :path "/howdy")
(->> (run (handler "howdy")))
(merge {:path "/" :port 8081})
(->> (run (handler "howdy"))))]
(is (true? (stop everything)))
(is (thrown? ConnectException (get-body url)))
(is (thrown? ConnectException (get-body url2)))
(is (not (stop everything)))))
(deftest run-dmc-should-work
(let [called (promise)]
(with-redefs [clojure.java.browse/browse-url (fn [u] (deliver called u))]
(let [result (run-dmc hello :path "/hello")
uri (str url "hello")]
(is (= "hello" (get-body uri)))
(is (= uri (deref called 1 false)))
(is (= (run hello :path "/hello") result))))))
(deftest run-dmc-should-take-kwargs
(let [called (promise)]
(with-redefs [clojure.java.browse/browse-url (fn [_] (deliver called true))]
(run-dmc hello :path "/foo")
(is (= "hello" (get-body (str url "foo"))))
(is (deref called 1 false)))))
(deftest run-dmc-with-threading
(let [call-count (atom 0)]
(with-redefs [clojure.java.browse/browse-url (fn [_] (swap! call-count inc))]
(-> (run-dmc hello)
(assoc :path "/howdy")
(->> (run-dmc (handler "howdy")))
(assoc :port 8081)
(->> (run-dmc (handler "howdy"))))
(is (= 3 @call-count))
(is (= "hello" (get-body url)))
(is (= "howdy" (get-body (str url "howdy"))))
(is (= "howdy" (get-body (str url2 "howdy")))))))
(deftest request-map-entries
(let [request (atom {})
handler (comp hello #(swap! request into %))
server (run handler)]
(get-body (str url "?query=help") :headers {:content-type "text/html; charset=utf-8"})
(are [x expected] (= expected (x @request))
:content-type "text/html; charset=utf-8"
:character-encoding "utf-8"
:remote-addr "127.0.0.1"
:server-port 8080
:content-length -1
:uri "/"
:server-name "localhost"
:query-string "query=help"
:scheme :http
:request-method :get)
(is (:body @request))
(is (map? (:headers @request)))
(is (< 3 (count (:headers @request))))))
;; IMMUTANT-533
(deftest find-should-work-on-request-map
(run (fn [req] {:status 200 :body (pr-str (find req :scheme))}))
(is (= [:scheme :http] (read-string (get-body url)))))
(deftest virtual-hosts
(let [all (-> (run hello :virtual-host ["integ-app1.torquebox.org" "integ-app2.torquebox.org"])
(assoc :virtual-host "integ-app3.torquebox.org")
(->> (run (handler "howdy"))))]
(is (= "hello" (get-body "http://integ-app1.torquebox.org:8080/")))
(is (= "hello" (get-body "http://integ-app2.torquebox.org:8080/")))
(is (= "howdy" (get-body "http://integ-app3.torquebox.org:8080/")))
(is (= 404 (get-body url)))
(is (true? (stop :virtual-host "integ-app1.torquebox.org")))
(is (= 404 (get-body "http://integ-app1.torquebox.org:8080/")))
(is (= "hello" (get-body "http://integ-app2.torquebox.org:8080/")))
(is (= "howdy" (get-body "http://integ-app3.torquebox.org:8080/")))
(is (true? (stop all)))
(is (thrown? ConnectException (get-body "http://integ-app2.torquebox.org:8080/")))
(is (thrown? ConnectException (get-body "http://integ-app3.torquebox.org:8080/")))
(is (nil? (stop all)))))
(deftest relative-resource-paths
(run (-> hello (wrap-resource "public")))
(is (= "foo" (get-body (str url "foo.html"))))
(stop)
(pause-on-windows)
(run (-> hello (wrap-resource "public")) :path "/foo")
(is (= "foo" (get-body (str url "foo/foo.html"))))
(is (= "hello" (get-body (str url "foo")))))
(deftest servers
(let [srv (server)]
(is (every? (partial identical? srv)
[(server :port 8080)
(server {:port 8080})
(server (run hello))]))
(is (.isRunning srv))
(.stop srv)
(is (not (.isRunning srv)))
(pause-on-windows)
(.start srv)
(is (.isRunning srv))
(is (= "hello" (get-body url)))))
(deftest https
(run hello
:ssl-port 8443
:keystore "dev-resources/keystore.jks"
:key-password "password")
(let [response (http/get "https://localhost:8443" {:insecure? true})]
(is (= (:status response) 200))
(is (= (:body response) "hello"))))
(deftest encoding
(run (fn [r] (charset ((handler "ɮѪϴ") r) "UTF-16")))
(is (= "ɮѪϴ" (:body (http/get url {:as :auto})))))
(deftest session-sans-web-context
(let [request {:uri "/" :request-method :get}]
(is (= "0" (:body (testing.app/routes request))))
(is (= "0" (:body ((-> testing.app/routes wrap-session) request))))
(is (get-in ((-> testing.app/routes wrap-session) request) [:headers "Set-Cookie"]))))
(deftest cookie-attributes
(run (-> (fn [r] (:session r) (hello {}))
(wrap-session {:cookie-name "foo"
:cookie-attrs {:path "/foo" :domain "foo.com" :max-age 20 :http-only true}})))
(get-response url :cookies nil)
(let [c @testing.web/cookies]
(is (= 1 (count c)))
(is (= "foo" (-> c first :name)))
(is (= "/foo" (-> c first :path)))
(is (= "foo.com" (-> c first :domain)))
(is (= "20" (-> c first :Max-Age)))))
(deftest zero-for-available-port
(let [x1 (run (handler "one") :port 0)
x2 (run (handler "two") :port 0)
p1 (:port x1)
p2 (:port x2)]
(is (not= p1 p2))
(is (not-any? zero? [p1 p2]))
(is (= "one" (get-body (str "http://localhost:" p1))))
(is (= "two" (get-body (str "http://localhost:" p2))))))
| 21617 | ;; Copyright 2014-2015 Red Hat, Inc, and individual contributors.
;;
;; 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 immutant.web-test
(:require [clojure.test :refer :all]
[clojure.set :refer :all]
[immutant.util :as u]
[immutant.web :refer :all]
[immutant.web.internal.wunderboss :refer [create-defaults register-defaults]]
[immutant.web.middleware :refer (wrap-session)]
[testing.web :refer [get-body get-response hello handler]]
[testing.app]
[testing.hello.service :as pedestal]
[ring.middleware.resource :refer [wrap-resource]]
[ring.util.response :refer (charset)]
[clj-http.client :as http]
[immutant.web.undertow :as undertow])
(:import clojure.lang.ExceptionInfo
java.net.ConnectException))
(u/set-log-level! (or (System/getenv "LOG_LEVEL") :ERROR))
(use-fixtures :each u/reset-fixture)
(def url "http://localhost:8080/")
(def url2 "http://localhost:8081/")
(defn pause-on-windows []
;; windows is slow to release closed ports, so we pause to allow that to happen
(when (re-find #"(?i)^windows" (System/getProperty "os.name"))
(Thread/sleep 100)))
(deftest mount-and-remount-pedestal-service
(run pedestal/servlet)
(is (= "Hello World!" (get-body url)))
(run pedestal/servlet)
(is (= "Hello World!" (get-body url))))
(deftest nil-body
(run (constantly {:status 200 :body nil}))
(is (nil? (get-body url))))
(deftest run-takes-kwargs
(run hello :path "/kwarg")
(is (= "hello" (get-body (str url "kwarg")))))
(deftest run-returns-default-opts
(let [opts (run hello)]
(is (subset? (-> (merge register-defaults create-defaults) keys set)
(-> opts keys set)))))
(deftest run-accepts-a-var
(run #'hello)
(is (= "hello" (get-body url))))
(deftest run-accepts-an-http-handler
(run (immutant.web.internal.undertow/create-http-handler hello))
(is (= "hello" (get-body url))))
(deftest run-returns-passed-opts-with-defaults
(let [opts (run hello {:path "/abc"})]
(is (subset? (-> (merge register-defaults create-defaults) keys set)
(-> opts keys set)))
(is (= "/abc" (:path opts)))))
(deftest run-should-throw-with-invalid-options
(is (thrown? IllegalArgumentException (run hello {:invalid true}))))
(deftest stop-should-throw-with-invalid-options
(is (thrown? IllegalArgumentException (stop {:invalid true}))))
(deftest stop-without-args-stops-default-context
(run hello)
(is (= "hello" (get-body url)))
(run (handler "howdy") {:path "/howdy"})
(is (= "howdy" (get-body (str url "howdy"))))
(stop)
(is (= "howdy" (get-body (str url "howdy"))))
(is (= 404 (get-body url))))
(deftest stop-with-context-stops-that-context
(run hello)
(is (= "hello" (get-body url)))
(run (handler "howdy") {:path "/howdy"})
(is (= "howdy" (get-body (str url "howdy"))))
(stop {:path "/howdy"})
(is (= "hello" (get-body url)))
(is (= "hello" (get-body (str url "howdy")))))
(deftest stop-should-accept-kwargs
(run hello)
(is (stop :path "/")))
(deftest stopping-last-handler-stops-the-server
(let [root-opts (run hello)]
(is (= "hello" (get-body url)))
(stop root-opts))
(is (thrown? ConnectException (get-body url))))
(deftest stop-stops-the-requested-server
(run hello)
(is (= "hello" (get-body url)))
(run hello {:port 8081})
(is (= "hello" (get-body url2)))
(stop {:port 8081})
(is (= "hello" (get-body url)))
(is (thrown? ConnectException (get-body url2))))
(deftest stop-stops-the-default-server-even-with-explicit-opts
(run hello)
(is (= "hello" (get-body url)))
(stop {:port 8080})
(is (thrown? ConnectException (get-body url))))
(deftest string-args-to-run-should-work
(run hello {"port" "8081"})
(is (= "hello" (get-body url2))))
(deftest string-args-to-stop-should-work
(run hello)
(run (handler "howdy") {"path" "/howdy"})
(is (= "hello" (get-body url)))
(is (= "howdy" (get-body (str url "howdy"))))
(stop {"path" "/howdy"})
(is (= "hello" (get-body (str url "howdy")))))
(deftest run-with-threading
(-> (run hello)
(assoc :path "/howdy")
(->> (run (handler "howdy")))
(assoc :port 8081)
(->> (run (handler "howdy"))))
(is (= "hello" (get-body url)))
(is (= "howdy" (get-body (str url "howdy"))))
(is (= "howdy" (get-body (str url2 "howdy")))))
(deftest stop-should-stop-all-threaded-apps
(let [everything (-> (run hello)
(assoc :path "/howdy")
(->> (run (handler "howdy")))
(merge {:path "/" :port 8081})
(->> (run (handler "howdy"))))]
(is (true? (stop everything)))
(is (thrown? ConnectException (get-body url)))
(is (thrown? ConnectException (get-body url2)))
(is (not (stop everything)))))
(deftest run-dmc-should-work
(let [called (promise)]
(with-redefs [clojure.java.browse/browse-url (fn [u] (deliver called u))]
(let [result (run-dmc hello :path "/hello")
uri (str url "hello")]
(is (= "hello" (get-body uri)))
(is (= uri (deref called 1 false)))
(is (= (run hello :path "/hello") result))))))
(deftest run-dmc-should-take-kwargs
(let [called (promise)]
(with-redefs [clojure.java.browse/browse-url (fn [_] (deliver called true))]
(run-dmc hello :path "/foo")
(is (= "hello" (get-body (str url "foo"))))
(is (deref called 1 false)))))
(deftest run-dmc-with-threading
(let [call-count (atom 0)]
(with-redefs [clojure.java.browse/browse-url (fn [_] (swap! call-count inc))]
(-> (run-dmc hello)
(assoc :path "/howdy")
(->> (run-dmc (handler "howdy")))
(assoc :port 8081)
(->> (run-dmc (handler "howdy"))))
(is (= 3 @call-count))
(is (= "hello" (get-body url)))
(is (= "howdy" (get-body (str url "howdy"))))
(is (= "howdy" (get-body (str url2 "howdy")))))))
(deftest request-map-entries
(let [request (atom {})
handler (comp hello #(swap! request into %))
server (run handler)]
(get-body (str url "?query=help") :headers {:content-type "text/html; charset=utf-8"})
(are [x expected] (= expected (x @request))
:content-type "text/html; charset=utf-8"
:character-encoding "utf-8"
:remote-addr "127.0.0.1"
:server-port 8080
:content-length -1
:uri "/"
:server-name "localhost"
:query-string "query=help"
:scheme :http
:request-method :get)
(is (:body @request))
(is (map? (:headers @request)))
(is (< 3 (count (:headers @request))))))
;; IMMUTANT-533
(deftest find-should-work-on-request-map
(run (fn [req] {:status 200 :body (pr-str (find req :scheme))}))
(is (= [:scheme :http] (read-string (get-body url)))))
(deftest virtual-hosts
(let [all (-> (run hello :virtual-host ["integ-app1.torquebox.org" "integ-app2.torquebox.org"])
(assoc :virtual-host "integ-app3.torquebox.org")
(->> (run (handler "howdy"))))]
(is (= "hello" (get-body "http://integ-app1.torquebox.org:8080/")))
(is (= "hello" (get-body "http://integ-app2.torquebox.org:8080/")))
(is (= "howdy" (get-body "http://integ-app3.torquebox.org:8080/")))
(is (= 404 (get-body url)))
(is (true? (stop :virtual-host "integ-app1.torquebox.org")))
(is (= 404 (get-body "http://integ-app1.torquebox.org:8080/")))
(is (= "hello" (get-body "http://integ-app2.torquebox.org:8080/")))
(is (= "howdy" (get-body "http://integ-app3.torquebox.org:8080/")))
(is (true? (stop all)))
(is (thrown? ConnectException (get-body "http://integ-app2.torquebox.org:8080/")))
(is (thrown? ConnectException (get-body "http://integ-app3.torquebox.org:8080/")))
(is (nil? (stop all)))))
(deftest relative-resource-paths
(run (-> hello (wrap-resource "public")))
(is (= "foo" (get-body (str url "foo.html"))))
(stop)
(pause-on-windows)
(run (-> hello (wrap-resource "public")) :path "/foo")
(is (= "foo" (get-body (str url "foo/foo.html"))))
(is (= "hello" (get-body (str url "foo")))))
(deftest servers
(let [srv (server)]
(is (every? (partial identical? srv)
[(server :port 8080)
(server {:port 8080})
(server (run hello))]))
(is (.isRunning srv))
(.stop srv)
(is (not (.isRunning srv)))
(pause-on-windows)
(.start srv)
(is (.isRunning srv))
(is (= "hello" (get-body url)))))
(deftest https
(run hello
:ssl-port 8443
:keystore "dev-resources/keystore.jks"
:key-password "<PASSWORD>")
(let [response (http/get "https://localhost:8443" {:insecure? true})]
(is (= (:status response) 200))
(is (= (:body response) "hello"))))
(deftest encoding
(run (fn [r] (charset ((handler "ɮѪϴ") r) "UTF-16")))
(is (= "ɮѪϴ" (:body (http/get url {:as :auto})))))
(deftest session-sans-web-context
(let [request {:uri "/" :request-method :get}]
(is (= "0" (:body (testing.app/routes request))))
(is (= "0" (:body ((-> testing.app/routes wrap-session) request))))
(is (get-in ((-> testing.app/routes wrap-session) request) [:headers "Set-Cookie"]))))
(deftest cookie-attributes
(run (-> (fn [r] (:session r) (hello {}))
(wrap-session {:cookie-name "foo"
:cookie-attrs {:path "/foo" :domain "foo.com" :max-age 20 :http-only true}})))
(get-response url :cookies nil)
(let [c @testing.web/cookies]
(is (= 1 (count c)))
(is (= "foo" (-> c first :name)))
(is (= "/foo" (-> c first :path)))
(is (= "foo.com" (-> c first :domain)))
(is (= "20" (-> c first :Max-Age)))))
(deftest zero-for-available-port
(let [x1 (run (handler "one") :port 0)
x2 (run (handler "two") :port 0)
p1 (:port x1)
p2 (:port x2)]
(is (not= p1 p2))
(is (not-any? zero? [p1 p2]))
(is (= "one" (get-body (str "http://localhost:" p1))))
(is (= "two" (get-body (str "http://localhost:" p2))))))
| true | ;; Copyright 2014-2015 Red Hat, Inc, and individual contributors.
;;
;; 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 immutant.web-test
(:require [clojure.test :refer :all]
[clojure.set :refer :all]
[immutant.util :as u]
[immutant.web :refer :all]
[immutant.web.internal.wunderboss :refer [create-defaults register-defaults]]
[immutant.web.middleware :refer (wrap-session)]
[testing.web :refer [get-body get-response hello handler]]
[testing.app]
[testing.hello.service :as pedestal]
[ring.middleware.resource :refer [wrap-resource]]
[ring.util.response :refer (charset)]
[clj-http.client :as http]
[immutant.web.undertow :as undertow])
(:import clojure.lang.ExceptionInfo
java.net.ConnectException))
(u/set-log-level! (or (System/getenv "LOG_LEVEL") :ERROR))
(use-fixtures :each u/reset-fixture)
(def url "http://localhost:8080/")
(def url2 "http://localhost:8081/")
(defn pause-on-windows []
;; windows is slow to release closed ports, so we pause to allow that to happen
(when (re-find #"(?i)^windows" (System/getProperty "os.name"))
(Thread/sleep 100)))
(deftest mount-and-remount-pedestal-service
(run pedestal/servlet)
(is (= "Hello World!" (get-body url)))
(run pedestal/servlet)
(is (= "Hello World!" (get-body url))))
(deftest nil-body
(run (constantly {:status 200 :body nil}))
(is (nil? (get-body url))))
(deftest run-takes-kwargs
(run hello :path "/kwarg")
(is (= "hello" (get-body (str url "kwarg")))))
(deftest run-returns-default-opts
(let [opts (run hello)]
(is (subset? (-> (merge register-defaults create-defaults) keys set)
(-> opts keys set)))))
(deftest run-accepts-a-var
(run #'hello)
(is (= "hello" (get-body url))))
(deftest run-accepts-an-http-handler
(run (immutant.web.internal.undertow/create-http-handler hello))
(is (= "hello" (get-body url))))
(deftest run-returns-passed-opts-with-defaults
(let [opts (run hello {:path "/abc"})]
(is (subset? (-> (merge register-defaults create-defaults) keys set)
(-> opts keys set)))
(is (= "/abc" (:path opts)))))
(deftest run-should-throw-with-invalid-options
(is (thrown? IllegalArgumentException (run hello {:invalid true}))))
(deftest stop-should-throw-with-invalid-options
(is (thrown? IllegalArgumentException (stop {:invalid true}))))
(deftest stop-without-args-stops-default-context
(run hello)
(is (= "hello" (get-body url)))
(run (handler "howdy") {:path "/howdy"})
(is (= "howdy" (get-body (str url "howdy"))))
(stop)
(is (= "howdy" (get-body (str url "howdy"))))
(is (= 404 (get-body url))))
(deftest stop-with-context-stops-that-context
(run hello)
(is (= "hello" (get-body url)))
(run (handler "howdy") {:path "/howdy"})
(is (= "howdy" (get-body (str url "howdy"))))
(stop {:path "/howdy"})
(is (= "hello" (get-body url)))
(is (= "hello" (get-body (str url "howdy")))))
(deftest stop-should-accept-kwargs
(run hello)
(is (stop :path "/")))
(deftest stopping-last-handler-stops-the-server
(let [root-opts (run hello)]
(is (= "hello" (get-body url)))
(stop root-opts))
(is (thrown? ConnectException (get-body url))))
(deftest stop-stops-the-requested-server
(run hello)
(is (= "hello" (get-body url)))
(run hello {:port 8081})
(is (= "hello" (get-body url2)))
(stop {:port 8081})
(is (= "hello" (get-body url)))
(is (thrown? ConnectException (get-body url2))))
(deftest stop-stops-the-default-server-even-with-explicit-opts
(run hello)
(is (= "hello" (get-body url)))
(stop {:port 8080})
(is (thrown? ConnectException (get-body url))))
(deftest string-args-to-run-should-work
(run hello {"port" "8081"})
(is (= "hello" (get-body url2))))
(deftest string-args-to-stop-should-work
(run hello)
(run (handler "howdy") {"path" "/howdy"})
(is (= "hello" (get-body url)))
(is (= "howdy" (get-body (str url "howdy"))))
(stop {"path" "/howdy"})
(is (= "hello" (get-body (str url "howdy")))))
(deftest run-with-threading
(-> (run hello)
(assoc :path "/howdy")
(->> (run (handler "howdy")))
(assoc :port 8081)
(->> (run (handler "howdy"))))
(is (= "hello" (get-body url)))
(is (= "howdy" (get-body (str url "howdy"))))
(is (= "howdy" (get-body (str url2 "howdy")))))
(deftest stop-should-stop-all-threaded-apps
(let [everything (-> (run hello)
(assoc :path "/howdy")
(->> (run (handler "howdy")))
(merge {:path "/" :port 8081})
(->> (run (handler "howdy"))))]
(is (true? (stop everything)))
(is (thrown? ConnectException (get-body url)))
(is (thrown? ConnectException (get-body url2)))
(is (not (stop everything)))))
(deftest run-dmc-should-work
(let [called (promise)]
(with-redefs [clojure.java.browse/browse-url (fn [u] (deliver called u))]
(let [result (run-dmc hello :path "/hello")
uri (str url "hello")]
(is (= "hello" (get-body uri)))
(is (= uri (deref called 1 false)))
(is (= (run hello :path "/hello") result))))))
(deftest run-dmc-should-take-kwargs
(let [called (promise)]
(with-redefs [clojure.java.browse/browse-url (fn [_] (deliver called true))]
(run-dmc hello :path "/foo")
(is (= "hello" (get-body (str url "foo"))))
(is (deref called 1 false)))))
(deftest run-dmc-with-threading
(let [call-count (atom 0)]
(with-redefs [clojure.java.browse/browse-url (fn [_] (swap! call-count inc))]
(-> (run-dmc hello)
(assoc :path "/howdy")
(->> (run-dmc (handler "howdy")))
(assoc :port 8081)
(->> (run-dmc (handler "howdy"))))
(is (= 3 @call-count))
(is (= "hello" (get-body url)))
(is (= "howdy" (get-body (str url "howdy"))))
(is (= "howdy" (get-body (str url2 "howdy")))))))
(deftest request-map-entries
(let [request (atom {})
handler (comp hello #(swap! request into %))
server (run handler)]
(get-body (str url "?query=help") :headers {:content-type "text/html; charset=utf-8"})
(are [x expected] (= expected (x @request))
:content-type "text/html; charset=utf-8"
:character-encoding "utf-8"
:remote-addr "127.0.0.1"
:server-port 8080
:content-length -1
:uri "/"
:server-name "localhost"
:query-string "query=help"
:scheme :http
:request-method :get)
(is (:body @request))
(is (map? (:headers @request)))
(is (< 3 (count (:headers @request))))))
;; IMMUTANT-533
(deftest find-should-work-on-request-map
(run (fn [req] {:status 200 :body (pr-str (find req :scheme))}))
(is (= [:scheme :http] (read-string (get-body url)))))
(deftest virtual-hosts
(let [all (-> (run hello :virtual-host ["integ-app1.torquebox.org" "integ-app2.torquebox.org"])
(assoc :virtual-host "integ-app3.torquebox.org")
(->> (run (handler "howdy"))))]
(is (= "hello" (get-body "http://integ-app1.torquebox.org:8080/")))
(is (= "hello" (get-body "http://integ-app2.torquebox.org:8080/")))
(is (= "howdy" (get-body "http://integ-app3.torquebox.org:8080/")))
(is (= 404 (get-body url)))
(is (true? (stop :virtual-host "integ-app1.torquebox.org")))
(is (= 404 (get-body "http://integ-app1.torquebox.org:8080/")))
(is (= "hello" (get-body "http://integ-app2.torquebox.org:8080/")))
(is (= "howdy" (get-body "http://integ-app3.torquebox.org:8080/")))
(is (true? (stop all)))
(is (thrown? ConnectException (get-body "http://integ-app2.torquebox.org:8080/")))
(is (thrown? ConnectException (get-body "http://integ-app3.torquebox.org:8080/")))
(is (nil? (stop all)))))
(deftest relative-resource-paths
(run (-> hello (wrap-resource "public")))
(is (= "foo" (get-body (str url "foo.html"))))
(stop)
(pause-on-windows)
(run (-> hello (wrap-resource "public")) :path "/foo")
(is (= "foo" (get-body (str url "foo/foo.html"))))
(is (= "hello" (get-body (str url "foo")))))
(deftest servers
(let [srv (server)]
(is (every? (partial identical? srv)
[(server :port 8080)
(server {:port 8080})
(server (run hello))]))
(is (.isRunning srv))
(.stop srv)
(is (not (.isRunning srv)))
(pause-on-windows)
(.start srv)
(is (.isRunning srv))
(is (= "hello" (get-body url)))))
(deftest https
(run hello
:ssl-port 8443
:keystore "dev-resources/keystore.jks"
:key-password "PI:PASSWORD:<PASSWORD>END_PI")
(let [response (http/get "https://localhost:8443" {:insecure? true})]
(is (= (:status response) 200))
(is (= (:body response) "hello"))))
(deftest encoding
(run (fn [r] (charset ((handler "ɮѪϴ") r) "UTF-16")))
(is (= "ɮѪϴ" (:body (http/get url {:as :auto})))))
(deftest session-sans-web-context
(let [request {:uri "/" :request-method :get}]
(is (= "0" (:body (testing.app/routes request))))
(is (= "0" (:body ((-> testing.app/routes wrap-session) request))))
(is (get-in ((-> testing.app/routes wrap-session) request) [:headers "Set-Cookie"]))))
(deftest cookie-attributes
(run (-> (fn [r] (:session r) (hello {}))
(wrap-session {:cookie-name "foo"
:cookie-attrs {:path "/foo" :domain "foo.com" :max-age 20 :http-only true}})))
(get-response url :cookies nil)
(let [c @testing.web/cookies]
(is (= 1 (count c)))
(is (= "foo" (-> c first :name)))
(is (= "/foo" (-> c first :path)))
(is (= "foo.com" (-> c first :domain)))
(is (= "20" (-> c first :Max-Age)))))
(deftest zero-for-available-port
(let [x1 (run (handler "one") :port 0)
x2 (run (handler "two") :port 0)
p1 (:port x1)
p2 (:port x2)]
(is (not= p1 p2))
(is (not-any? zero? [p1 p2]))
(is (= "one" (get-body (str "http://localhost:" p1))))
(is (= "two" (get-body (str "http://localhost:" p2))))))
|
[
{
"context": "(def m ^{:createdDate \"20171226\"} {:name \"john\" :age 99})\n\n(println m)\n(meta m)\n\n;(def m (with-",
"end": 46,
"score": 0.997797429561615,
"start": 42,
"tag": "NAME",
"value": "john"
},
{
"context": "f m2 ^:private ^{:createdDate \"20171226\"} {:name \"jonny\" :age 77})\n\n(println m2)\n(meta m2)\n\n(def m2 (with",
"end": 260,
"score": 0.9871306419372559,
"start": 255,
"tag": "NAME",
"value": "jonny"
}
] | basic_clojure_stuff/metadata.clj | travism26/random_clojure_stuff | 0 | (def m ^{:createdDate "20171226"} {:name "john" :age 99})
(println m)
(meta m)
;(def m (with-meta m {:more "info"}))
(meta m)
(def m (with-meta m (assoc (meta m) :more "info")))
(println (meta m))
(def m2 ^:private ^{:createdDate "20171226"} {:name "jonny" :age 77})
(println m2)
(meta m2)
(def m2 (with-meta m2 (assoc (meta m2) :more "data stuff")))
(meta m2)
(defn ^{:doc "this is function doc string"} f [] 10)
(doc f)
(defn #^{:test (fn [](assert true))} some-fn [] nil)
(test #'some-fn)
| 28161 | (def m ^{:createdDate "20171226"} {:name "<NAME>" :age 99})
(println m)
(meta m)
;(def m (with-meta m {:more "info"}))
(meta m)
(def m (with-meta m (assoc (meta m) :more "info")))
(println (meta m))
(def m2 ^:private ^{:createdDate "20171226"} {:name "<NAME>" :age 77})
(println m2)
(meta m2)
(def m2 (with-meta m2 (assoc (meta m2) :more "data stuff")))
(meta m2)
(defn ^{:doc "this is function doc string"} f [] 10)
(doc f)
(defn #^{:test (fn [](assert true))} some-fn [] nil)
(test #'some-fn)
| true | (def m ^{:createdDate "20171226"} {:name "PI:NAME:<NAME>END_PI" :age 99})
(println m)
(meta m)
;(def m (with-meta m {:more "info"}))
(meta m)
(def m (with-meta m (assoc (meta m) :more "info")))
(println (meta m))
(def m2 ^:private ^{:createdDate "20171226"} {:name "PI:NAME:<NAME>END_PI" :age 77})
(println m2)
(meta m2)
(def m2 (with-meta m2 (assoc (meta m2) :more "data stuff")))
(meta m2)
(defn ^{:doc "this is function doc string"} f [] 10)
(doc f)
(defn #^{:test (fn [](assert true))} some-fn [] nil)
(test #'some-fn)
|
[
{
"context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio",
"end": 30,
"score": 0.9997676610946655,
"start": 19,
"tag": "NAME",
"value": "Rich Hickey"
}
] | Neptune/bin/Debug/clojure/core/protocols.clj | yasir2000/Neptune- | 2 | ; Copyright (c) Rich Hickey. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns clojure.core.protocols)
(defprotocol InternalReduce
"Protocol for concrete seq types that can reduce themselves
faster than first/next recursion. Called by clojure.core/reduce."
(internal-reduce [seq f start]))
(extend-protocol InternalReduce
nil
(internal-reduce
[s f val]
val)
;; handles vectors and ranges
clojure.lang.IChunkedSeq
(internal-reduce
[s f val]
(if-let [s (seq s)]
(if (chunked-seq? s)
(recur (chunk-next s)
f
(.reduce (chunk-first s) f val))
(internal-reduce s f val))
val))
clojure.lang.StringSeq
(internal-reduce
[str-seq f val]
(let [s (.S str-seq)] ;;; .s
(loop [i (.I str-seq) ;;; .i
val val]
(if (< i (.Length s)) ;;; .length
(recur (inc i) (f val (.get_Chars s i))) ;;; .charAt
val))))
clojure.lang.UntypedArraySeq ;;; ArraySeq
(internal-reduce
[a-seq f val]
(let [^objects arr (.Array a-seq)] ;;; .array
(loop [i (.Index a-seq) ;;; .index
val val]
(if (< i (alength arr))
(recur (inc i) (f val (aget arr i)))
val))))
Object ;;;java.lang.Object
(internal-reduce
[s f val]
(loop [cls (class s)
s s
f f
val val]
(if-let [s (seq s)]
;; roll over to faster implementation if underlying seq changes type
(if (identical? (class s) cls)
(recur cls (next s) f (f val (first s)))
(internal-reduce s f val))
val))))
(def arr-impl
'(internal-reduce
[a-seq f val]
(let [arr (.Array a-seq)] ;;; .array
(loop [i (.Index a-seq) ;;; .index
val val]
(if (< i (alength arr))
(recur (inc i) (f val (aget arr i)))
val)))))
(defn- emit-array-impls*
[syms]
(apply
concat
(map
(fn [s]
[(symbol (str "clojure.lang.TypedArraySeq`1[" s "]")) ;;; (str "clojure.lang.ArraySeq$ArraySeq_" s)
arr-impl])
syms)))
(defmacro emit-array-impls
[& syms]
`(extend-protocol InternalReduce
~@(emit-array-impls* syms)))
;(emit-array-impls int long float double byte char boolean)
(emit-array-impls System.Int32 System.Int64 System.Single System.Double System.Byte System.SByte System.Char System.Boolean
System.Int16 System.UInt16 System.UInt32 System.UInt64)
| 24222 | ; Copyright (c) <NAME>. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns clojure.core.protocols)
(defprotocol InternalReduce
"Protocol for concrete seq types that can reduce themselves
faster than first/next recursion. Called by clojure.core/reduce."
(internal-reduce [seq f start]))
(extend-protocol InternalReduce
nil
(internal-reduce
[s f val]
val)
;; handles vectors and ranges
clojure.lang.IChunkedSeq
(internal-reduce
[s f val]
(if-let [s (seq s)]
(if (chunked-seq? s)
(recur (chunk-next s)
f
(.reduce (chunk-first s) f val))
(internal-reduce s f val))
val))
clojure.lang.StringSeq
(internal-reduce
[str-seq f val]
(let [s (.S str-seq)] ;;; .s
(loop [i (.I str-seq) ;;; .i
val val]
(if (< i (.Length s)) ;;; .length
(recur (inc i) (f val (.get_Chars s i))) ;;; .charAt
val))))
clojure.lang.UntypedArraySeq ;;; ArraySeq
(internal-reduce
[a-seq f val]
(let [^objects arr (.Array a-seq)] ;;; .array
(loop [i (.Index a-seq) ;;; .index
val val]
(if (< i (alength arr))
(recur (inc i) (f val (aget arr i)))
val))))
Object ;;;java.lang.Object
(internal-reduce
[s f val]
(loop [cls (class s)
s s
f f
val val]
(if-let [s (seq s)]
;; roll over to faster implementation if underlying seq changes type
(if (identical? (class s) cls)
(recur cls (next s) f (f val (first s)))
(internal-reduce s f val))
val))))
(def arr-impl
'(internal-reduce
[a-seq f val]
(let [arr (.Array a-seq)] ;;; .array
(loop [i (.Index a-seq) ;;; .index
val val]
(if (< i (alength arr))
(recur (inc i) (f val (aget arr i)))
val)))))
(defn- emit-array-impls*
[syms]
(apply
concat
(map
(fn [s]
[(symbol (str "clojure.lang.TypedArraySeq`1[" s "]")) ;;; (str "clojure.lang.ArraySeq$ArraySeq_" s)
arr-impl])
syms)))
(defmacro emit-array-impls
[& syms]
`(extend-protocol InternalReduce
~@(emit-array-impls* syms)))
;(emit-array-impls int long float double byte char boolean)
(emit-array-impls System.Int32 System.Int64 System.Single System.Double System.Byte System.SByte System.Char System.Boolean
System.Int16 System.UInt16 System.UInt32 System.UInt64)
| true | ; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns clojure.core.protocols)
(defprotocol InternalReduce
"Protocol for concrete seq types that can reduce themselves
faster than first/next recursion. Called by clojure.core/reduce."
(internal-reduce [seq f start]))
(extend-protocol InternalReduce
nil
(internal-reduce
[s f val]
val)
;; handles vectors and ranges
clojure.lang.IChunkedSeq
(internal-reduce
[s f val]
(if-let [s (seq s)]
(if (chunked-seq? s)
(recur (chunk-next s)
f
(.reduce (chunk-first s) f val))
(internal-reduce s f val))
val))
clojure.lang.StringSeq
(internal-reduce
[str-seq f val]
(let [s (.S str-seq)] ;;; .s
(loop [i (.I str-seq) ;;; .i
val val]
(if (< i (.Length s)) ;;; .length
(recur (inc i) (f val (.get_Chars s i))) ;;; .charAt
val))))
clojure.lang.UntypedArraySeq ;;; ArraySeq
(internal-reduce
[a-seq f val]
(let [^objects arr (.Array a-seq)] ;;; .array
(loop [i (.Index a-seq) ;;; .index
val val]
(if (< i (alength arr))
(recur (inc i) (f val (aget arr i)))
val))))
Object ;;;java.lang.Object
(internal-reduce
[s f val]
(loop [cls (class s)
s s
f f
val val]
(if-let [s (seq s)]
;; roll over to faster implementation if underlying seq changes type
(if (identical? (class s) cls)
(recur cls (next s) f (f val (first s)))
(internal-reduce s f val))
val))))
(def arr-impl
'(internal-reduce
[a-seq f val]
(let [arr (.Array a-seq)] ;;; .array
(loop [i (.Index a-seq) ;;; .index
val val]
(if (< i (alength arr))
(recur (inc i) (f val (aget arr i)))
val)))))
(defn- emit-array-impls*
[syms]
(apply
concat
(map
(fn [s]
[(symbol (str "clojure.lang.TypedArraySeq`1[" s "]")) ;;; (str "clojure.lang.ArraySeq$ArraySeq_" s)
arr-impl])
syms)))
(defmacro emit-array-impls
[& syms]
`(extend-protocol InternalReduce
~@(emit-array-impls* syms)))
;(emit-array-impls int long float double byte char boolean)
(emit-array-impls System.Int32 System.Int64 System.Single System.Double System.Byte System.SByte System.Char System.Boolean
System.Int16 System.UInt16 System.UInt32 System.UInt64)
|
[
{
"context": " testing\n\n(def books\n [{:title \"2001\" :author \"Clarke\" :copies 21}\n {:title \"Emma\" :author \"Austen\"",
"end": 330,
"score": 0.999722957611084,
"start": 324,
"tag": "NAME",
"value": "Clarke"
},
{
"context": "\"2001\" :author \"Clarke\" :copies 21}\n {:title \"Emma\" :author \"Austen\" :copies 10}\n {:title \"Miser",
"end": 362,
"score": 0.974702000617981,
"start": 358,
"tag": "NAME",
"value": "Emma"
},
{
"context": "\"Clarke\" :copies 21}\n {:title \"Emma\" :author \"Austen\" :copies 10}\n {:title \"Misery\" :author \"King\"",
"end": 379,
"score": 0.9997040629386902,
"start": 373,
"tag": "NAME",
"value": "Austen"
},
{
"context": "\"Emma\" :author \"Austen\" :copies 10}\n {:title \"Misery\" :author \"King\" :copies 101}])\n\n(deftest test-fin",
"end": 413,
"score": 0.8742708563804626,
"start": 407,
"tag": "NAME",
"value": "Misery"
},
{
"context": "usten\" :copies 10}\n {:title \"Misery\" :author \"King\" :copies 101}])\n\n(deftest test-finding-books\n ",
"end": 428,
"score": 0.9989265203475952,
"start": 424,
"tag": "NAME",
"value": "King"
},
{
"context": "inding-books\n (is (not (nil? (i/find-by-title \"Emma\" books)))))\n\n(deftest test-finding-books-better\n ",
"end": 515,
"score": 0.9532301425933838,
"start": 511,
"tag": "NAME",
"value": "Emma"
},
{
"context": "books-better\n (is (not (nil? (i/find-by-title \"Emma\" books))))\n (is (nil? (i/find-by-title \"XYZZY\"",
"end": 605,
"score": 0.9686973690986633,
"start": 601,
"tag": "NAME",
"value": "Emma"
},
{
"context": "g books\"\n (is (not (nil? (i/find-by-title \"Emma\" books))))\n (is (nil? (i/find-by-title \"XY",
"end": 771,
"score": 0.9532936811447144,
"start": 767,
"tag": "NAME",
"value": "Emma"
},
{
"context": "entory\"\n (is (= 10 (i/number-of-copies-of \"Emma\" books)))))\n\n;; Property-based testing\n\n(def titl",
"end": 917,
"score": 0.699799656867981,
"start": 913,
"tag": "NAME",
"value": "Emma"
}
] | chapter14/inventory/test/inventory/core_test.clj | will-i-amv-books/getting-clojure | 0 | (ns inventory.core-test
(:require [clojure.test :refer :all])
(:require [inventory.core :as i])
(:require [clojure.test.check.properties :as prop])
(:require [clojure.test.check.generators :as gen])
(:require [clojure.test.check :as tc]))
;; Traditional testing
(def books
[{:title "2001" :author "Clarke" :copies 21}
{:title "Emma" :author "Austen" :copies 10}
{:title "Misery" :author "King" :copies 101}])
(deftest test-finding-books
(is (not (nil? (i/find-by-title "Emma" books)))))
(deftest test-finding-books-better
(is (not (nil? (i/find-by-title "Emma" books))))
(is (nil? (i/find-by-title "XYZZY" books))))
(deftest test-basic-inventory
(testing "Finding books"
(is (not (nil? (i/find-by-title "Emma" books))))
(is (nil? (i/find-by-title "XYZZY" books))))
(testing "Copies in inventory"
(is (= 10 (i/number-of-copies-of "Emma" books)))))
;; Property-based testing
(def title-gen (gen/such-that not-empty gen/string-alphanumeric))
(def author-gen (gen/such-that not-empty gen/string-alphanumeric))
(def copies-gen (gen/such-that (complement zero?) gen/pos-int))
(def book-gen
(gen/hash-map :title title-gen :author author-gen :copies copies-gen))
(def inventory-gen
(gen/not-empty (gen/vector book-gen)))
(def inventory-and-book-gen
(gen/let [inventory inventory-gen
book (gen/elements inventory)]
{:inventory inventory :book book}))
(defn my-property-test []
(tc/quick-check 50
(prop/for-all [i-and-b inventory-and-book-gen]
(= (i/find-by-title (-> i-and-b :book :title) (:inventory i-and-b)) (:book i-and-b)))))
| 64100 | (ns inventory.core-test
(:require [clojure.test :refer :all])
(:require [inventory.core :as i])
(:require [clojure.test.check.properties :as prop])
(:require [clojure.test.check.generators :as gen])
(:require [clojure.test.check :as tc]))
;; Traditional testing
(def books
[{:title "2001" :author "<NAME>" :copies 21}
{:title "<NAME>" :author "<NAME>" :copies 10}
{:title "<NAME>" :author "<NAME>" :copies 101}])
(deftest test-finding-books
(is (not (nil? (i/find-by-title "<NAME>" books)))))
(deftest test-finding-books-better
(is (not (nil? (i/find-by-title "<NAME>" books))))
(is (nil? (i/find-by-title "XYZZY" books))))
(deftest test-basic-inventory
(testing "Finding books"
(is (not (nil? (i/find-by-title "<NAME>" books))))
(is (nil? (i/find-by-title "XYZZY" books))))
(testing "Copies in inventory"
(is (= 10 (i/number-of-copies-of "<NAME>" books)))))
;; Property-based testing
(def title-gen (gen/such-that not-empty gen/string-alphanumeric))
(def author-gen (gen/such-that not-empty gen/string-alphanumeric))
(def copies-gen (gen/such-that (complement zero?) gen/pos-int))
(def book-gen
(gen/hash-map :title title-gen :author author-gen :copies copies-gen))
(def inventory-gen
(gen/not-empty (gen/vector book-gen)))
(def inventory-and-book-gen
(gen/let [inventory inventory-gen
book (gen/elements inventory)]
{:inventory inventory :book book}))
(defn my-property-test []
(tc/quick-check 50
(prop/for-all [i-and-b inventory-and-book-gen]
(= (i/find-by-title (-> i-and-b :book :title) (:inventory i-and-b)) (:book i-and-b)))))
| true | (ns inventory.core-test
(:require [clojure.test :refer :all])
(:require [inventory.core :as i])
(:require [clojure.test.check.properties :as prop])
(:require [clojure.test.check.generators :as gen])
(:require [clojure.test.check :as tc]))
;; Traditional testing
(def books
[{:title "2001" :author "PI:NAME:<NAME>END_PI" :copies 21}
{:title "PI:NAME:<NAME>END_PI" :author "PI:NAME:<NAME>END_PI" :copies 10}
{:title "PI:NAME:<NAME>END_PI" :author "PI:NAME:<NAME>END_PI" :copies 101}])
(deftest test-finding-books
(is (not (nil? (i/find-by-title "PI:NAME:<NAME>END_PI" books)))))
(deftest test-finding-books-better
(is (not (nil? (i/find-by-title "PI:NAME:<NAME>END_PI" books))))
(is (nil? (i/find-by-title "XYZZY" books))))
(deftest test-basic-inventory
(testing "Finding books"
(is (not (nil? (i/find-by-title "PI:NAME:<NAME>END_PI" books))))
(is (nil? (i/find-by-title "XYZZY" books))))
(testing "Copies in inventory"
(is (= 10 (i/number-of-copies-of "PI:NAME:<NAME>END_PI" books)))))
;; Property-based testing
(def title-gen (gen/such-that not-empty gen/string-alphanumeric))
(def author-gen (gen/such-that not-empty gen/string-alphanumeric))
(def copies-gen (gen/such-that (complement zero?) gen/pos-int))
(def book-gen
(gen/hash-map :title title-gen :author author-gen :copies copies-gen))
(def inventory-gen
(gen/not-empty (gen/vector book-gen)))
(def inventory-and-book-gen
(gen/let [inventory inventory-gen
book (gen/elements inventory)]
{:inventory inventory :book book}))
(defn my-property-test []
(tc/quick-check 50
(prop/for-all [i-and-b inventory-and-book-gen]
(= (i/find-by-title (-> i-and-b :book :title) (:inventory i-and-b)) (:book i-and-b)))))
|
[
{
"context": "nfig\n {:db {:engine :postgres\n :username \"zanmi\"\n :password \"zanmi-password\"\n :host",
"end": 86,
"score": 0.9996247291564941,
"start": 81,
"tag": "USERNAME",
"value": "zanmi"
},
{
"context": "gres\n :username \"zanmi\"\n :password \"zanmi-password\"\n :host \"localhost\"\n :db-name \"zanm",
"end": 121,
"score": 0.9993599057197571,
"start": 107,
"tag": "PASSWORD",
"value": "zanmi-password"
},
{
"context": "me-length 32\n :password-length 64\n :password-score 1}\n\n :secre",
"end": 260,
"score": 0.9869773983955383,
"start": 258,
"tag": "PASSWORD",
"value": "64"
}
] | test/zanmi/test_config.clj | zonotope/zanmi | 35 | (ns zanmi.test-config)
(def config
{:db {:engine :postgres
:username "zanmi"
:password "zanmi-password"
:host "localhost"
:db-name "zanmi_test"}
:profile-schema {:username-length 32
:password-length 64
:password-score 1}
:secret "nobody knows this!"})
| 119537 | (ns zanmi.test-config)
(def config
{:db {:engine :postgres
:username "zanmi"
:password "<PASSWORD>"
:host "localhost"
:db-name "zanmi_test"}
:profile-schema {:username-length 32
:password-length <PASSWORD>
:password-score 1}
:secret "nobody knows this!"})
| true | (ns zanmi.test-config)
(def config
{:db {:engine :postgres
:username "zanmi"
:password "PI:PASSWORD:<PASSWORD>END_PI"
:host "localhost"
:db-name "zanmi_test"}
:profile-schema {:username-length 32
:password-length PI:PASSWORD:<PASSWORD>END_PI
:password-score 1}
:secret "nobody knows this!"})
|
[
{
"context": "on\"]]\n #\"(?i).*\\balanna\\b.*\" [\"alanna\" [\"contribution\"]]\n #\"(?i).*\\b(rob(ert)?|rjb)\\",
"end": 411,
"score": 0.9896713495254517,
"start": 405,
"tag": "NAME",
"value": "alanna"
},
{
"context": "on\"]]\n #\"(?i).*\\b(rob(ert)?|rjb)\\b.*\" [\"robert\" [\"contribution\"]]\n #\"(?i)cash dep.*\\b(belmont",
"end": 481,
"score": 0.9804123640060425,
"start": 475,
"tag": "NAME",
"value": "robert"
}
] | src/jjAgglomerator/classifier.clj | s5b/jjAgglomerator | 0 | (ns jjAgglomerator.classifier)
; An attempt at classifying the transactions by applying rules.
(def unknown ["-unknown-" []])
(def source-admin "admin")
(def source-bank "bank")
(def source-classic "classic")
(defn- classify-savings-credit [description]
(condp re-matches description
#"(?i)Transfer from xx2181 NetBank.*" ["stuart" ["contribution"]]
#"(?i).*\balanna\b.*" ["alanna" ["contribution"]]
#"(?i).*\b(rob(ert)?|rjb)\b.*" ["robert" ["contribution"]]
#"(?i)cash dep.*\b(belmont|mark)\b.*" ["mark" ["contribution"]]
#"(?i)Credit Interest" [source-bank ["interest"]]
unknown))
(defn- classify-savings-debit [description]
(condp re-matches description
#"(?i)Transfer to xx0721 NetBank.*interest.*" [source-admin ["repayment"]]
unknown))
(defn- classify-savings [description amount]
(condp = (.signum amount)
-1 (classify-savings-debit description)
0 unknown
1 (classify-savings-credit description)
unknown))
(defn- classify-varidian-credit [description]
(condp re-matches description
#"(?i)NETBANK TFR .*Interest.*" [source-admin ["repayment"]]
#"(?i)Transfer from xx1826 .*Interest.*" [source-admin ["repayment"]]
unknown))
(defn- classify-varidian-debit [description]
(condp re-matches description
#"DEBIT INT TO \d+ (JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)" [source-bank ["interest"]]
#"(?i)Debit Interest" [source-bank ["interest"]]
#".*BL BCR MANAGEMEN .*" [source-classic ["bodycorp"]]
#".*BRIGHTON CLASSIC.*" [source-classic ["bodycorp"]]
unknown))
(defn- classify-viridian [description amount]
(condp = (.signum amount)
-1 (classify-varidian-debit description)
0 unknown
1 (classify-varidian-credit description)
unknown))
(defn classify [^String account ^String description ^BigDecimal amount]
(condp = account
"savings" (classify-savings description amount)
"viridian" (classify-viridian description amount)
unknown))
| 118553 | (ns jjAgglomerator.classifier)
; An attempt at classifying the transactions by applying rules.
(def unknown ["-unknown-" []])
(def source-admin "admin")
(def source-bank "bank")
(def source-classic "classic")
(defn- classify-savings-credit [description]
(condp re-matches description
#"(?i)Transfer from xx2181 NetBank.*" ["stuart" ["contribution"]]
#"(?i).*\balanna\b.*" ["<NAME>" ["contribution"]]
#"(?i).*\b(rob(ert)?|rjb)\b.*" ["<NAME>" ["contribution"]]
#"(?i)cash dep.*\b(belmont|mark)\b.*" ["mark" ["contribution"]]
#"(?i)Credit Interest" [source-bank ["interest"]]
unknown))
(defn- classify-savings-debit [description]
(condp re-matches description
#"(?i)Transfer to xx0721 NetBank.*interest.*" [source-admin ["repayment"]]
unknown))
(defn- classify-savings [description amount]
(condp = (.signum amount)
-1 (classify-savings-debit description)
0 unknown
1 (classify-savings-credit description)
unknown))
(defn- classify-varidian-credit [description]
(condp re-matches description
#"(?i)NETBANK TFR .*Interest.*" [source-admin ["repayment"]]
#"(?i)Transfer from xx1826 .*Interest.*" [source-admin ["repayment"]]
unknown))
(defn- classify-varidian-debit [description]
(condp re-matches description
#"DEBIT INT TO \d+ (JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)" [source-bank ["interest"]]
#"(?i)Debit Interest" [source-bank ["interest"]]
#".*BL BCR MANAGEMEN .*" [source-classic ["bodycorp"]]
#".*BRIGHTON CLASSIC.*" [source-classic ["bodycorp"]]
unknown))
(defn- classify-viridian [description amount]
(condp = (.signum amount)
-1 (classify-varidian-debit description)
0 unknown
1 (classify-varidian-credit description)
unknown))
(defn classify [^String account ^String description ^BigDecimal amount]
(condp = account
"savings" (classify-savings description amount)
"viridian" (classify-viridian description amount)
unknown))
| true | (ns jjAgglomerator.classifier)
; An attempt at classifying the transactions by applying rules.
(def unknown ["-unknown-" []])
(def source-admin "admin")
(def source-bank "bank")
(def source-classic "classic")
(defn- classify-savings-credit [description]
(condp re-matches description
#"(?i)Transfer from xx2181 NetBank.*" ["stuart" ["contribution"]]
#"(?i).*\balanna\b.*" ["PI:NAME:<NAME>END_PI" ["contribution"]]
#"(?i).*\b(rob(ert)?|rjb)\b.*" ["PI:NAME:<NAME>END_PI" ["contribution"]]
#"(?i)cash dep.*\b(belmont|mark)\b.*" ["mark" ["contribution"]]
#"(?i)Credit Interest" [source-bank ["interest"]]
unknown))
(defn- classify-savings-debit [description]
(condp re-matches description
#"(?i)Transfer to xx0721 NetBank.*interest.*" [source-admin ["repayment"]]
unknown))
(defn- classify-savings [description amount]
(condp = (.signum amount)
-1 (classify-savings-debit description)
0 unknown
1 (classify-savings-credit description)
unknown))
(defn- classify-varidian-credit [description]
(condp re-matches description
#"(?i)NETBANK TFR .*Interest.*" [source-admin ["repayment"]]
#"(?i)Transfer from xx1826 .*Interest.*" [source-admin ["repayment"]]
unknown))
(defn- classify-varidian-debit [description]
(condp re-matches description
#"DEBIT INT TO \d+ (JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)" [source-bank ["interest"]]
#"(?i)Debit Interest" [source-bank ["interest"]]
#".*BL BCR MANAGEMEN .*" [source-classic ["bodycorp"]]
#".*BRIGHTON CLASSIC.*" [source-classic ["bodycorp"]]
unknown))
(defn- classify-viridian [description amount]
(condp = (.signum amount)
-1 (classify-varidian-debit description)
0 unknown
1 (classify-varidian-credit description)
unknown))
(defn classify [^String account ^String description ^BigDecimal amount]
(condp = account
"savings" (classify-savings description amount)
"viridian" (classify-viridian description amount)
unknown))
|
[
{
"context": " for set intersection testing.\"\n :author \"palisades dot lakes at gmail dot com\"\n :since \"2017-08-19\"\n :version \"2017-09-02\"}",
"end": 317,
"score": 0.8660796880722046,
"start": 281,
"tag": "EMAIL",
"value": "palisades dot lakes at gmail dot com"
}
] | src/main/clojure/palisades/lakes/multix/sets/dynalin.clj | palisades-lakes/multimethod-experiments | 5 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.multix.sets.dynalin
{:doc "palisades.lakes.dynalin.core/dynafun
for set intersection testing."
:author "palisades dot lakes at gmail dot com"
:since "2017-08-19"
:version "2017-09-02"}
(:refer-clojure :exclude [contains?])
(:require [palisades.lakes.dynalin.core :as d])
(:import [java.util Collections]
[palisades.lakes.bench.java.sets
Contains Diameter Intersects Set Sets
ByteInterval DoubleInterval FloatInterval
IntegerInterval LongInterval ShortInterval]))
;;----------------------------------------------------------------
;; diameter 2 methods primitive return value
;;----------------------------------------------------------------
(d/dynafun ^Double/TYPE diameter
{:doc "Max distance between elements."})
;;----------------------------------------------------------------
(d/defmethod diameter ^double [^Set s] (.diameter s))
;(d/defmethod diameter ^double [^ByteInterval s] (.diameter s))
;(d/defmethod diameter ^double [^DoubleInterval s] (.diameter s))
;(d/defmethod diameter ^double [^FloatInterval s] (.diameter s))
;(d/defmethod diameter ^double [^IntegerInterval s] (.diameter s))
;(d/defmethod diameter ^double [^LongInterval s] (.diameter s))
;(d/defmethod diameter ^double [^ShortInterval s] (.diameter s))
;(d/defmethod diameter ^double [^ByteInterval s] (double (- (.max s) (.min s))))
;(d/defmethod diameter ^double [^DoubleInterval s] (- (.max s) (.min s)))
;(d/defmethod diameter ^double [^FloatInterval s] (- (.max s) (.min s)))
;(d/defmethod diameter ^double [^IntegerInterval s] (double (- (.max s) (.min s))))
;(d/defmethod diameter ^double [^LongInterval s] (double (- (.max s) (.min s))))
;(d/defmethod diameter ^double [^ShortInterval s] (double (- (.max s) (.min s))))
;;----------------------------------------------------------------
(d/defmethod diameter ^double [^java.util.Set s]
(Diameter/diameter s))
;;----------------------------------------------------------------
;; intersects? 9 methods
;;----------------------------------------------------------------
(d/dynafun intersects?
{:doc "Test for general set intersection. 9 methods."})
;;----------------------------------------------------------------
(d/defmethod intersects? [^IntegerInterval s0 ^IntegerInterval s1]
(.intersects s0 s1))
(d/defmethod intersects? [^IntegerInterval s0 ^DoubleInterval s1]
(.intersects s0 s1))
(d/defmethod intersects? [^IntegerInterval s0 ^java.util.Set s1]
(.intersects s0 s1))
;;----------------------------------------------------------------
(d/defmethod intersects? [^DoubleInterval s0 ^IntegerInterval s1]
(.intersects s1 s0))
(d/defmethod intersects? [^DoubleInterval s0 ^DoubleInterval s1]
(.intersects s0 s1))
(d/defmethod intersects? [^DoubleInterval s0 ^java.util.Set s1]
(.intersects s0 s1))
;;----------------------------------------------------------------
(d/defmethod intersects? [^java.util.Set s0 ^IntegerInterval s1]
(.intersects s1 s0))
(d/defmethod intersects? [^java.util.Set s0 ^DoubleInterval s1]
(.intersects s1 s0))
(d/defmethod intersects? [^java.util.Set s0 ^java.util.Set s1]
(not (Collections/disjoint s0 s1)))
;;----------------------------------------------------------------
;; contains? 43 methods
;;----------------------------------------------------------------
(d/dynafun contains? {:doc "Test for general set containment."})
;;----------------------------------------------------------------
(d/defmethod contains? [^java.util.Set s ^Object x] (.contains s x))
;;----------------------------------------------------------------
(d/defmethod contains? [^ByteInterval s ^Byte x] (.contains s x))
(d/defmethod contains? [^ByteInterval s ^Double x] (.contains s x))
(d/defmethod contains? [^ByteInterval s ^Float x] (.contains s x))
(d/defmethod contains? [^ByteInterval s ^Integer x] (.contains s x))
(d/defmethod contains? [^ByteInterval s ^Long x] (.contains s x))
(d/defmethod contains? [^ByteInterval s ^Short x] (.contains s x))
(d/defmethod contains? [^ByteInterval s ^Object x] false)
;;----------------------------------------------------------------
(d/defmethod contains? [^DoubleInterval s ^Byte x] (.contains s x))
(d/defmethod contains? [^DoubleInterval s ^Double x] (.contains s x))
(d/defmethod contains? [^DoubleInterval s ^Float x] (.contains s x))
(d/defmethod contains? [^DoubleInterval s ^Integer x] (.contains s x))
(d/defmethod contains? [^DoubleInterval s ^Long x] (.contains s x))
(d/defmethod contains? [^DoubleInterval s ^Short x] (.contains s x))
(d/defmethod contains? [^DoubleInterval s ^Object x] false)
;;----------------------------------------------------------------
(d/defmethod contains? [^FloatInterval s ^Byte x] (.contains s x))
(d/defmethod contains? [^FloatInterval s ^Double x] (.contains s x))
(d/defmethod contains? [^FloatInterval s ^Float x] (.contains s x))
(d/defmethod contains? [^FloatInterval s ^Integer x] (.contains s x))
(d/defmethod contains? [^FloatInterval s ^Long x] (.contains s x))
(d/defmethod contains? [^FloatInterval s ^Short x] (.contains s x))
(d/defmethod contains? [^FloatInterval s ^Object x] false)
;;----------------------------------------------------------------
(d/defmethod contains? [^IntegerInterval s ^Byte x] (.contains s x))
(d/defmethod contains? [^IntegerInterval s ^Double x] (.contains s x))
(d/defmethod contains? [^IntegerInterval s ^Float x] (.contains s x))
(d/defmethod contains? [^IntegerInterval s ^Integer x] (.contains s x))
(d/defmethod contains? [^IntegerInterval s ^Long x] (.contains s x))
(d/defmethod contains? [^IntegerInterval s ^Short x] (.contains s x))
(d/defmethod contains? [^IntegerInterval s ^Object x] false)
;;----------------------------------------------------------------
(d/defmethod contains? [^LongInterval s ^Byte x] (.contains s x))
(d/defmethod contains? [^LongInterval s ^Double x] (.contains s x))
(d/defmethod contains? [^LongInterval s ^Float x] (.contains s x))
(d/defmethod contains? [^LongInterval s ^Integer x] (.contains s x))
(d/defmethod contains? [^LongInterval s ^Long x] (.contains s x))
(d/defmethod contains? [^LongInterval s ^Short x] (.contains s x))
(d/defmethod contains? [^LongInterval s ^Object x] false)
;;----------------------------------------------------------------
(d/defmethod contains? [^ShortInterval s ^Byte x] (.contains s x))
(d/defmethod contains? [^ShortInterval s ^Double x] (.contains s x))
(d/defmethod contains? [^ShortInterval s ^Float x] (.contains s x))
(d/defmethod contains? [^ShortInterval s ^Integer x] (.contains s x))
(d/defmethod contains? [^ShortInterval s ^Long x] (.contains s x))
(d/defmethod contains? [^ShortInterval s ^Short x] (.contains s x))
(d/defmethod contains? [^ShortInterval s ^Object x] false)
;;----------------------------------------------------------------
| 38495 | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.multix.sets.dynalin
{:doc "palisades.lakes.dynalin.core/dynafun
for set intersection testing."
:author "<EMAIL>"
:since "2017-08-19"
:version "2017-09-02"}
(:refer-clojure :exclude [contains?])
(:require [palisades.lakes.dynalin.core :as d])
(:import [java.util Collections]
[palisades.lakes.bench.java.sets
Contains Diameter Intersects Set Sets
ByteInterval DoubleInterval FloatInterval
IntegerInterval LongInterval ShortInterval]))
;;----------------------------------------------------------------
;; diameter 2 methods primitive return value
;;----------------------------------------------------------------
(d/dynafun ^Double/TYPE diameter
{:doc "Max distance between elements."})
;;----------------------------------------------------------------
(d/defmethod diameter ^double [^Set s] (.diameter s))
;(d/defmethod diameter ^double [^ByteInterval s] (.diameter s))
;(d/defmethod diameter ^double [^DoubleInterval s] (.diameter s))
;(d/defmethod diameter ^double [^FloatInterval s] (.diameter s))
;(d/defmethod diameter ^double [^IntegerInterval s] (.diameter s))
;(d/defmethod diameter ^double [^LongInterval s] (.diameter s))
;(d/defmethod diameter ^double [^ShortInterval s] (.diameter s))
;(d/defmethod diameter ^double [^ByteInterval s] (double (- (.max s) (.min s))))
;(d/defmethod diameter ^double [^DoubleInterval s] (- (.max s) (.min s)))
;(d/defmethod diameter ^double [^FloatInterval s] (- (.max s) (.min s)))
;(d/defmethod diameter ^double [^IntegerInterval s] (double (- (.max s) (.min s))))
;(d/defmethod diameter ^double [^LongInterval s] (double (- (.max s) (.min s))))
;(d/defmethod diameter ^double [^ShortInterval s] (double (- (.max s) (.min s))))
;;----------------------------------------------------------------
(d/defmethod diameter ^double [^java.util.Set s]
(Diameter/diameter s))
;;----------------------------------------------------------------
;; intersects? 9 methods
;;----------------------------------------------------------------
(d/dynafun intersects?
{:doc "Test for general set intersection. 9 methods."})
;;----------------------------------------------------------------
(d/defmethod intersects? [^IntegerInterval s0 ^IntegerInterval s1]
(.intersects s0 s1))
(d/defmethod intersects? [^IntegerInterval s0 ^DoubleInterval s1]
(.intersects s0 s1))
(d/defmethod intersects? [^IntegerInterval s0 ^java.util.Set s1]
(.intersects s0 s1))
;;----------------------------------------------------------------
(d/defmethod intersects? [^DoubleInterval s0 ^IntegerInterval s1]
(.intersects s1 s0))
(d/defmethod intersects? [^DoubleInterval s0 ^DoubleInterval s1]
(.intersects s0 s1))
(d/defmethod intersects? [^DoubleInterval s0 ^java.util.Set s1]
(.intersects s0 s1))
;;----------------------------------------------------------------
(d/defmethod intersects? [^java.util.Set s0 ^IntegerInterval s1]
(.intersects s1 s0))
(d/defmethod intersects? [^java.util.Set s0 ^DoubleInterval s1]
(.intersects s1 s0))
(d/defmethod intersects? [^java.util.Set s0 ^java.util.Set s1]
(not (Collections/disjoint s0 s1)))
;;----------------------------------------------------------------
;; contains? 43 methods
;;----------------------------------------------------------------
(d/dynafun contains? {:doc "Test for general set containment."})
;;----------------------------------------------------------------
(d/defmethod contains? [^java.util.Set s ^Object x] (.contains s x))
;;----------------------------------------------------------------
(d/defmethod contains? [^ByteInterval s ^Byte x] (.contains s x))
(d/defmethod contains? [^ByteInterval s ^Double x] (.contains s x))
(d/defmethod contains? [^ByteInterval s ^Float x] (.contains s x))
(d/defmethod contains? [^ByteInterval s ^Integer x] (.contains s x))
(d/defmethod contains? [^ByteInterval s ^Long x] (.contains s x))
(d/defmethod contains? [^ByteInterval s ^Short x] (.contains s x))
(d/defmethod contains? [^ByteInterval s ^Object x] false)
;;----------------------------------------------------------------
(d/defmethod contains? [^DoubleInterval s ^Byte x] (.contains s x))
(d/defmethod contains? [^DoubleInterval s ^Double x] (.contains s x))
(d/defmethod contains? [^DoubleInterval s ^Float x] (.contains s x))
(d/defmethod contains? [^DoubleInterval s ^Integer x] (.contains s x))
(d/defmethod contains? [^DoubleInterval s ^Long x] (.contains s x))
(d/defmethod contains? [^DoubleInterval s ^Short x] (.contains s x))
(d/defmethod contains? [^DoubleInterval s ^Object x] false)
;;----------------------------------------------------------------
(d/defmethod contains? [^FloatInterval s ^Byte x] (.contains s x))
(d/defmethod contains? [^FloatInterval s ^Double x] (.contains s x))
(d/defmethod contains? [^FloatInterval s ^Float x] (.contains s x))
(d/defmethod contains? [^FloatInterval s ^Integer x] (.contains s x))
(d/defmethod contains? [^FloatInterval s ^Long x] (.contains s x))
(d/defmethod contains? [^FloatInterval s ^Short x] (.contains s x))
(d/defmethod contains? [^FloatInterval s ^Object x] false)
;;----------------------------------------------------------------
(d/defmethod contains? [^IntegerInterval s ^Byte x] (.contains s x))
(d/defmethod contains? [^IntegerInterval s ^Double x] (.contains s x))
(d/defmethod contains? [^IntegerInterval s ^Float x] (.contains s x))
(d/defmethod contains? [^IntegerInterval s ^Integer x] (.contains s x))
(d/defmethod contains? [^IntegerInterval s ^Long x] (.contains s x))
(d/defmethod contains? [^IntegerInterval s ^Short x] (.contains s x))
(d/defmethod contains? [^IntegerInterval s ^Object x] false)
;;----------------------------------------------------------------
(d/defmethod contains? [^LongInterval s ^Byte x] (.contains s x))
(d/defmethod contains? [^LongInterval s ^Double x] (.contains s x))
(d/defmethod contains? [^LongInterval s ^Float x] (.contains s x))
(d/defmethod contains? [^LongInterval s ^Integer x] (.contains s x))
(d/defmethod contains? [^LongInterval s ^Long x] (.contains s x))
(d/defmethod contains? [^LongInterval s ^Short x] (.contains s x))
(d/defmethod contains? [^LongInterval s ^Object x] false)
;;----------------------------------------------------------------
(d/defmethod contains? [^ShortInterval s ^Byte x] (.contains s x))
(d/defmethod contains? [^ShortInterval s ^Double x] (.contains s x))
(d/defmethod contains? [^ShortInterval s ^Float x] (.contains s x))
(d/defmethod contains? [^ShortInterval s ^Integer x] (.contains s x))
(d/defmethod contains? [^ShortInterval s ^Long x] (.contains s x))
(d/defmethod contains? [^ShortInterval s ^Short x] (.contains s x))
(d/defmethod contains? [^ShortInterval s ^Object x] false)
;;----------------------------------------------------------------
| true | (set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
;;----------------------------------------------------------------
(ns palisades.lakes.multix.sets.dynalin
{:doc "palisades.lakes.dynalin.core/dynafun
for set intersection testing."
:author "PI:EMAIL:<EMAIL>END_PI"
:since "2017-08-19"
:version "2017-09-02"}
(:refer-clojure :exclude [contains?])
(:require [palisades.lakes.dynalin.core :as d])
(:import [java.util Collections]
[palisades.lakes.bench.java.sets
Contains Diameter Intersects Set Sets
ByteInterval DoubleInterval FloatInterval
IntegerInterval LongInterval ShortInterval]))
;;----------------------------------------------------------------
;; diameter 2 methods primitive return value
;;----------------------------------------------------------------
(d/dynafun ^Double/TYPE diameter
{:doc "Max distance between elements."})
;;----------------------------------------------------------------
(d/defmethod diameter ^double [^Set s] (.diameter s))
;(d/defmethod diameter ^double [^ByteInterval s] (.diameter s))
;(d/defmethod diameter ^double [^DoubleInterval s] (.diameter s))
;(d/defmethod diameter ^double [^FloatInterval s] (.diameter s))
;(d/defmethod diameter ^double [^IntegerInterval s] (.diameter s))
;(d/defmethod diameter ^double [^LongInterval s] (.diameter s))
;(d/defmethod diameter ^double [^ShortInterval s] (.diameter s))
;(d/defmethod diameter ^double [^ByteInterval s] (double (- (.max s) (.min s))))
;(d/defmethod diameter ^double [^DoubleInterval s] (- (.max s) (.min s)))
;(d/defmethod diameter ^double [^FloatInterval s] (- (.max s) (.min s)))
;(d/defmethod diameter ^double [^IntegerInterval s] (double (- (.max s) (.min s))))
;(d/defmethod diameter ^double [^LongInterval s] (double (- (.max s) (.min s))))
;(d/defmethod diameter ^double [^ShortInterval s] (double (- (.max s) (.min s))))
;;----------------------------------------------------------------
(d/defmethod diameter ^double [^java.util.Set s]
(Diameter/diameter s))
;;----------------------------------------------------------------
;; intersects? 9 methods
;;----------------------------------------------------------------
(d/dynafun intersects?
{:doc "Test for general set intersection. 9 methods."})
;;----------------------------------------------------------------
(d/defmethod intersects? [^IntegerInterval s0 ^IntegerInterval s1]
(.intersects s0 s1))
(d/defmethod intersects? [^IntegerInterval s0 ^DoubleInterval s1]
(.intersects s0 s1))
(d/defmethod intersects? [^IntegerInterval s0 ^java.util.Set s1]
(.intersects s0 s1))
;;----------------------------------------------------------------
(d/defmethod intersects? [^DoubleInterval s0 ^IntegerInterval s1]
(.intersects s1 s0))
(d/defmethod intersects? [^DoubleInterval s0 ^DoubleInterval s1]
(.intersects s0 s1))
(d/defmethod intersects? [^DoubleInterval s0 ^java.util.Set s1]
(.intersects s0 s1))
;;----------------------------------------------------------------
(d/defmethod intersects? [^java.util.Set s0 ^IntegerInterval s1]
(.intersects s1 s0))
(d/defmethod intersects? [^java.util.Set s0 ^DoubleInterval s1]
(.intersects s1 s0))
(d/defmethod intersects? [^java.util.Set s0 ^java.util.Set s1]
(not (Collections/disjoint s0 s1)))
;;----------------------------------------------------------------
;; contains? 43 methods
;;----------------------------------------------------------------
(d/dynafun contains? {:doc "Test for general set containment."})
;;----------------------------------------------------------------
(d/defmethod contains? [^java.util.Set s ^Object x] (.contains s x))
;;----------------------------------------------------------------
(d/defmethod contains? [^ByteInterval s ^Byte x] (.contains s x))
(d/defmethod contains? [^ByteInterval s ^Double x] (.contains s x))
(d/defmethod contains? [^ByteInterval s ^Float x] (.contains s x))
(d/defmethod contains? [^ByteInterval s ^Integer x] (.contains s x))
(d/defmethod contains? [^ByteInterval s ^Long x] (.contains s x))
(d/defmethod contains? [^ByteInterval s ^Short x] (.contains s x))
(d/defmethod contains? [^ByteInterval s ^Object x] false)
;;----------------------------------------------------------------
(d/defmethod contains? [^DoubleInterval s ^Byte x] (.contains s x))
(d/defmethod contains? [^DoubleInterval s ^Double x] (.contains s x))
(d/defmethod contains? [^DoubleInterval s ^Float x] (.contains s x))
(d/defmethod contains? [^DoubleInterval s ^Integer x] (.contains s x))
(d/defmethod contains? [^DoubleInterval s ^Long x] (.contains s x))
(d/defmethod contains? [^DoubleInterval s ^Short x] (.contains s x))
(d/defmethod contains? [^DoubleInterval s ^Object x] false)
;;----------------------------------------------------------------
(d/defmethod contains? [^FloatInterval s ^Byte x] (.contains s x))
(d/defmethod contains? [^FloatInterval s ^Double x] (.contains s x))
(d/defmethod contains? [^FloatInterval s ^Float x] (.contains s x))
(d/defmethod contains? [^FloatInterval s ^Integer x] (.contains s x))
(d/defmethod contains? [^FloatInterval s ^Long x] (.contains s x))
(d/defmethod contains? [^FloatInterval s ^Short x] (.contains s x))
(d/defmethod contains? [^FloatInterval s ^Object x] false)
;;----------------------------------------------------------------
(d/defmethod contains? [^IntegerInterval s ^Byte x] (.contains s x))
(d/defmethod contains? [^IntegerInterval s ^Double x] (.contains s x))
(d/defmethod contains? [^IntegerInterval s ^Float x] (.contains s x))
(d/defmethod contains? [^IntegerInterval s ^Integer x] (.contains s x))
(d/defmethod contains? [^IntegerInterval s ^Long x] (.contains s x))
(d/defmethod contains? [^IntegerInterval s ^Short x] (.contains s x))
(d/defmethod contains? [^IntegerInterval s ^Object x] false)
;;----------------------------------------------------------------
(d/defmethod contains? [^LongInterval s ^Byte x] (.contains s x))
(d/defmethod contains? [^LongInterval s ^Double x] (.contains s x))
(d/defmethod contains? [^LongInterval s ^Float x] (.contains s x))
(d/defmethod contains? [^LongInterval s ^Integer x] (.contains s x))
(d/defmethod contains? [^LongInterval s ^Long x] (.contains s x))
(d/defmethod contains? [^LongInterval s ^Short x] (.contains s x))
(d/defmethod contains? [^LongInterval s ^Object x] false)
;;----------------------------------------------------------------
(d/defmethod contains? [^ShortInterval s ^Byte x] (.contains s x))
(d/defmethod contains? [^ShortInterval s ^Double x] (.contains s x))
(d/defmethod contains? [^ShortInterval s ^Float x] (.contains s x))
(d/defmethod contains? [^ShortInterval s ^Integer x] (.contains s x))
(d/defmethod contains? [^ShortInterval s ^Long x] (.contains s x))
(d/defmethod contains? [^ShortInterval s ^Short x] (.contains s x))
(d/defmethod contains? [^ShortInterval s ^Object x] false)
;;----------------------------------------------------------------
|
[
{
"context": "merit scores\"\n (let [users '({:value 10 :name \"made tea\" :first_name \"Emile\"}\n {:value 10",
"end": 258,
"score": 0.8213878870010376,
"start": 250,
"tag": "USERNAME",
"value": "made tea"
},
{
"context": "[users '({:value 10 :name \"made tea\" :first_name \"Emile\"}\n {:value 10 :name \"blog post on",
"end": 278,
"score": 0.9998021721839905,
"start": 273,
"tag": "NAME",
"value": "Emile"
},
{
"context": "{:value 10 :name \"blog post on time\" :first_name \"Emile\"}\n {:value 9 :name \"made coffee\" ",
"end": 353,
"score": 0.9998217821121216,
"start": 348,
"tag": "NAME",
"value": "Emile"
},
{
"context": " {:value 9 :name \"made coffee\" :first_name \"Alex\"})\n\n expected-result '({:first_name \"Emi",
"end": 420,
"score": 0.9998641014099121,
"start": 416,
"tag": "NAME",
"value": "Alex"
},
{
"context": "lex\"})\n\n expected-result '({:first_name \"Emile\" :score 20 :merits [{:value 10 :name \"made tea\"}\n",
"end": 472,
"score": 0.9998005628585815,
"start": 467,
"tag": "NAME",
"value": "Emile"
},
{
"context": "time\"}]}\n {:first_name \"Alex\" :score 9 :merits [{:value 9 :name \"made coffee\"}",
"end": 675,
"score": 0.9998315572738647,
"start": 671,
"tag": "NAME",
"value": "Alex"
}
] | test/clj/made_merits/test/service/score_calculator.clj | cob16/made-merits | 0 | (ns made-merits.test.service.score-calculator
(:require [clojure.test :refer :all]
[made-merits.service.score-calculator :refer :all]))
(deftest with-score-test
(testing "Sum up user merit scores"
(let [users '({:value 10 :name "made tea" :first_name "Emile"}
{:value 10 :name "blog post on time" :first_name "Emile"}
{:value 9 :name "made coffee" :first_name "Alex"})
expected-result '({:first_name "Emile" :score 20 :merits [{:value 10 :name "made tea"}
{:value 10 :name "blog post on time"}]}
{:first_name "Alex" :score 9 :merits [{:value 9 :name "made coffee"}]})]
(is (= expected-result (with-score users))))))
| 104164 | (ns made-merits.test.service.score-calculator
(:require [clojure.test :refer :all]
[made-merits.service.score-calculator :refer :all]))
(deftest with-score-test
(testing "Sum up user merit scores"
(let [users '({:value 10 :name "made tea" :first_name "<NAME>"}
{:value 10 :name "blog post on time" :first_name "<NAME>"}
{:value 9 :name "made coffee" :first_name "<NAME>"})
expected-result '({:first_name "<NAME>" :score 20 :merits [{:value 10 :name "made tea"}
{:value 10 :name "blog post on time"}]}
{:first_name "<NAME>" :score 9 :merits [{:value 9 :name "made coffee"}]})]
(is (= expected-result (with-score users))))))
| true | (ns made-merits.test.service.score-calculator
(:require [clojure.test :refer :all]
[made-merits.service.score-calculator :refer :all]))
(deftest with-score-test
(testing "Sum up user merit scores"
(let [users '({:value 10 :name "made tea" :first_name "PI:NAME:<NAME>END_PI"}
{:value 10 :name "blog post on time" :first_name "PI:NAME:<NAME>END_PI"}
{:value 9 :name "made coffee" :first_name "PI:NAME:<NAME>END_PI"})
expected-result '({:first_name "PI:NAME:<NAME>END_PI" :score 20 :merits [{:value 10 :name "made tea"}
{:value 10 :name "blog post on time"}]}
{:first_name "PI:NAME:<NAME>END_PI" :score 9 :merits [{:value 9 :name "made coffee"}]})]
(is (= expected-result (with-score users))))))
|
[
{
"context": " prop-testing-schema-test-check.core\n ^{:author \"Leeor Engel\"}\n (:require [schema.core :as s]))\n\n(def REST-NO",
"end": 64,
"score": 0.9998882412910461,
"start": 53,
"tag": "NAME",
"value": "Leeor Engel"
}
] | src/prop_testing_schema_test_check/core.clj | leeorengel/clojure-prop-testing-schema-test.check | 1 | (ns prop-testing-schema-test-check.core
^{:author "Leeor Engel"}
(:require [schema.core :as s]))
(def REST-NOTE-NUMBER -1)
(def MIN-NOTE 0)
(def MAX-NOTE 127)
(def Rest (s/eq REST-NOTE-NUMBER))
(def Note (s/constrained s/Int #(<= MIN-NOTE % MAX-NOTE)))
(def NoteOrRest (s/either Note Rest))
(s/defrecord Melody [notes :- [NoteOrRest]])
(s/defn rest? :- s/Bool [n :- NoteOrRest] (neg? n))
(s/defn note-count :- s/Int [notes :- [NoteOrRest]] (count (remove rest? notes)))
(s/defn with-new-notes :- Melody
[melody :- Melody new-notes :- [Note]]
{:pre [(= (count new-notes) (note-count (:notes melody)))]}
(let [notes (first (reduce (fn [[updated-notes new-notes] note]
(if (rest? note)
[(conj updated-notes note) new-notes]
[(conj updated-notes (first new-notes)) (rest new-notes)]))
[[] new-notes] (:notes melody)))]
(->Melody notes))) | 67978 | (ns prop-testing-schema-test-check.core
^{:author "<NAME>"}
(:require [schema.core :as s]))
(def REST-NOTE-NUMBER -1)
(def MIN-NOTE 0)
(def MAX-NOTE 127)
(def Rest (s/eq REST-NOTE-NUMBER))
(def Note (s/constrained s/Int #(<= MIN-NOTE % MAX-NOTE)))
(def NoteOrRest (s/either Note Rest))
(s/defrecord Melody [notes :- [NoteOrRest]])
(s/defn rest? :- s/Bool [n :- NoteOrRest] (neg? n))
(s/defn note-count :- s/Int [notes :- [NoteOrRest]] (count (remove rest? notes)))
(s/defn with-new-notes :- Melody
[melody :- Melody new-notes :- [Note]]
{:pre [(= (count new-notes) (note-count (:notes melody)))]}
(let [notes (first (reduce (fn [[updated-notes new-notes] note]
(if (rest? note)
[(conj updated-notes note) new-notes]
[(conj updated-notes (first new-notes)) (rest new-notes)]))
[[] new-notes] (:notes melody)))]
(->Melody notes))) | true | (ns prop-testing-schema-test-check.core
^{:author "PI:NAME:<NAME>END_PI"}
(:require [schema.core :as s]))
(def REST-NOTE-NUMBER -1)
(def MIN-NOTE 0)
(def MAX-NOTE 127)
(def Rest (s/eq REST-NOTE-NUMBER))
(def Note (s/constrained s/Int #(<= MIN-NOTE % MAX-NOTE)))
(def NoteOrRest (s/either Note Rest))
(s/defrecord Melody [notes :- [NoteOrRest]])
(s/defn rest? :- s/Bool [n :- NoteOrRest] (neg? n))
(s/defn note-count :- s/Int [notes :- [NoteOrRest]] (count (remove rest? notes)))
(s/defn with-new-notes :- Melody
[melody :- Melody new-notes :- [Note]]
{:pre [(= (count new-notes) (note-count (:notes melody)))]}
(let [notes (first (reduce (fn [[updated-notes new-notes] note]
(if (rest? note)
[(conj updated-notes note) new-notes]
[(conj updated-notes (first new-notes)) (rest new-notes)]))
[[] new-notes] (:notes melody)))]
(->Melody notes))) |
[
{
"context": ";; Copyright (C) 2018, 2019 by Vlad Kozin\n\n(ns generic-example\n (:require [medley.core :re",
"end": 41,
"score": 0.999841034412384,
"start": 31,
"tag": "NAME",
"value": "Vlad Kozin"
}
] | src/exch/generic_example.clj | vkz/bot | 1 | ;; Copyright (C) 2018, 2019 by Vlad Kozin
(ns generic-example
(:require [medley.core :refer :all]
[manifold.stream :as s]
[aleph.http :as http]
[cheshire.core :as json]
[clojure.string :as string]
[clojure.pprint :refer [pprint]]
[clojure.core.async :as async]
[taoensso.timbre :as log]))
(require '[exch :refer :all] :reload)
(require '[generic :as ge] :reload)
(defn -main []
(def tick (ticker :usd/btc))
(def c (ge/create-connection))
(log/info "Connected?" (connected? c))
(connect c)
(log/info "Connected?" (connected? c))
(log/info "Attempting to subscribe")
(send-out c [:subscribe tick])
(def e (create-exch c))
(start-standard-msg-handlers e tick)
(send-in c [:subscribed {:ticker tick}])
(book-watch (get-book e tick)
:logger
(fn [_ new-state]
(println "Book updated:")
(pprint new-state)))
;; snapshot
(send-in c
[:snapshot
{:ticker tick
:snapshot
'{:asks ([7.59M 23.39216286M] [6.96M 7.23746288M] [5.5M 12.3M])
:bids ([5M 65.64632441M] [2.51M 0.93194317M] [4M 0.93194317M])}}])
;; update
(send-in c
[:update
{:ticker tick
:update
'{:asks ([7.59M 23M] [6.96M 7M] [5.5M 0M])
:bids ([5M 0M] [2.51M 1M])}}])
;; unsubscribed
(send-in c
[:unsubscribed {:ticker tick}])
;; pong
(send-in c [:pong {:cid 1234 :ts (timestamp)}])
(Thread/sleep 5000)
(System/exit 0))
| 112238 | ;; Copyright (C) 2018, 2019 by <NAME>
(ns generic-example
(:require [medley.core :refer :all]
[manifold.stream :as s]
[aleph.http :as http]
[cheshire.core :as json]
[clojure.string :as string]
[clojure.pprint :refer [pprint]]
[clojure.core.async :as async]
[taoensso.timbre :as log]))
(require '[exch :refer :all] :reload)
(require '[generic :as ge] :reload)
(defn -main []
(def tick (ticker :usd/btc))
(def c (ge/create-connection))
(log/info "Connected?" (connected? c))
(connect c)
(log/info "Connected?" (connected? c))
(log/info "Attempting to subscribe")
(send-out c [:subscribe tick])
(def e (create-exch c))
(start-standard-msg-handlers e tick)
(send-in c [:subscribed {:ticker tick}])
(book-watch (get-book e tick)
:logger
(fn [_ new-state]
(println "Book updated:")
(pprint new-state)))
;; snapshot
(send-in c
[:snapshot
{:ticker tick
:snapshot
'{:asks ([7.59M 23.39216286M] [6.96M 7.23746288M] [5.5M 12.3M])
:bids ([5M 65.64632441M] [2.51M 0.93194317M] [4M 0.93194317M])}}])
;; update
(send-in c
[:update
{:ticker tick
:update
'{:asks ([7.59M 23M] [6.96M 7M] [5.5M 0M])
:bids ([5M 0M] [2.51M 1M])}}])
;; unsubscribed
(send-in c
[:unsubscribed {:ticker tick}])
;; pong
(send-in c [:pong {:cid 1234 :ts (timestamp)}])
(Thread/sleep 5000)
(System/exit 0))
| true | ;; Copyright (C) 2018, 2019 by PI:NAME:<NAME>END_PI
(ns generic-example
(:require [medley.core :refer :all]
[manifold.stream :as s]
[aleph.http :as http]
[cheshire.core :as json]
[clojure.string :as string]
[clojure.pprint :refer [pprint]]
[clojure.core.async :as async]
[taoensso.timbre :as log]))
(require '[exch :refer :all] :reload)
(require '[generic :as ge] :reload)
(defn -main []
(def tick (ticker :usd/btc))
(def c (ge/create-connection))
(log/info "Connected?" (connected? c))
(connect c)
(log/info "Connected?" (connected? c))
(log/info "Attempting to subscribe")
(send-out c [:subscribe tick])
(def e (create-exch c))
(start-standard-msg-handlers e tick)
(send-in c [:subscribed {:ticker tick}])
(book-watch (get-book e tick)
:logger
(fn [_ new-state]
(println "Book updated:")
(pprint new-state)))
;; snapshot
(send-in c
[:snapshot
{:ticker tick
:snapshot
'{:asks ([7.59M 23.39216286M] [6.96M 7.23746288M] [5.5M 12.3M])
:bids ([5M 65.64632441M] [2.51M 0.93194317M] [4M 0.93194317M])}}])
;; update
(send-in c
[:update
{:ticker tick
:update
'{:asks ([7.59M 23M] [6.96M 7M] [5.5M 0M])
:bids ([5M 0M] [2.51M 1M])}}])
;; unsubscribed
(send-in c
[:unsubscribed {:ticker tick}])
;; pong
(send-in c [:pong {:cid 1234 :ts (timestamp)}])
(Thread/sleep 5000)
(System/exit 0))
|
[
{
"context": " (messager %1 %2)))\n data [[:ok 0] [:brian -1] [:corey 10326] [:gary -3]]]\n (critiquer da",
"end": 3337,
"score": 0.6496241092681885,
"start": 3332,
"tag": "NAME",
"value": "brian"
}
] | test/such/f_function_makers.clj | marick/suchwow | 70 | (ns such.f-function-makers
(:require [such.function-makers :as mkfn])
(:use midje.sweet))
(fact "pred:any?"
((mkfn/pred:any? odd? even?) 1) => true
((mkfn/pred:any? pos? neg?) 0) => false
((mkfn/pred:any? :key :word) {:key false}) => false
((mkfn/pred:any? :key :word) {:key false :word 3}) => true
((mkfn/pred:any? #{1 2} #{3 4}) 3) => true
;; stops at first match
((mkfn/pred:any? (partial = 3) (fn[_](throw (new Error "boom!")))) 3) => true
;; Any empty list means that everything matches
((mkfn/pred:any?) 3) => true)
(fact "pred:not-any? and pred:none-of?"
((mkfn/pred:not-any? odd? even?) 1) => false
((mkfn/pred:not-any? pos? neg?) 0) => true
((mkfn/pred:none-of? :key :word) {:key false}) => true
((mkfn/pred:none-of? :key :word) {:key false :word 3}) => false
((mkfn/pred:not-any? #{1 2} #{3 4}) 3) => false
;; stops at first match
((mkfn/pred:not-any? (partial = 3) (fn[_](throw (new Error "boom!")))) 3) => false
;; Any empty list means that everything matches
((mkfn/pred:not-any?) 3) => false)
(fact pred:exception->false
(let [wrapped (mkfn/pred:exception->false even?)]
(wrapped 2) => true
(wrapped 3) => false
(even? nil) => (throws)
(wrapped nil) => false))
(fact "`lazyseq:x->abc` converts (possibly optionally) each element of a lazyseq and replaces it with N results"
(fact "one arg form processes each element"
( (mkfn/lazyseq:x->abc #(repeat % %)) [1 2 3]) => [1 2 2 3 3 3])
(fact "two arg form processes only elements that match predicate"
( (mkfn/lazyseq:x->abc #(repeat % %) even?) [1 2 3 4]) => [1 2 2 3 4 4 4 4])
(fact "empty sequences are handled"
( (mkfn/lazyseq:x->abc #(repeat % %) even?) []) => empty?)
(fact "it is indeed lazy"
(let [made (mkfn/lazyseq:x->abc #(repeat % %) even?)]
(take 2 (made [0])) => empty?
(take 2 (made [0 1])) => [1]
(take 2 (made [0 1 2])) => [1 2]
(take 2 (made [0 1 2 3])) => [1 2]
(take 2 (made [0 1 2 3 4])) => [1 2]
(take 2 (made (range))) => [ 1 2 ]
(count (take 100000 (made (range)))) => 100000)))
(fact "`lazyseq:x->xabc` converts (possibly optionally) each element of a lazyseq and replaces it
with N results. The first argument is preserved"
(fact "one arg form processes each element"
( (mkfn/lazyseq:x->xabc #(repeat % (- %))) [1 2 3]) => [1 -1 2 -2 -2 3 -3 -3 -3])
(fact "two arg form processes only elements that match predicate"
( (mkfn/lazyseq:x->xabc #(repeat % (- %)) even?) [1 2 3 4]) => [1 2 -2 -2 3 4 -4 -4 -4 -4]))
(fact "`lazyseq:x->y` converts (possibly optionally) each element of a lazyseq and replaces it
with 1 result."
(fact "one arg form processes each element"
( (mkfn/lazyseq:x->y -) [1 2 3]) => [-1 -2 -3 ])
(fact "two arg form processes only elements that match predicate"
( (mkfn/lazyseq:x->y - even?) [1 2 3 4]) => [1 -2 3 -4]))
(fact lazyseq:criticize-deviationism
(let [recorder (atom [])
messager #(format "%s - %s" %1 %2)
critiquer (mkfn/lazyseq:criticize-deviationism (comp neg? second)
#(swap! recorder
conj
(messager %1 %2)))
data [[:ok 0] [:brian -1] [:corey 10326] [:gary -3]]]
(critiquer data) => data
@recorder => [(format "%s - %s" data [:brian -1])
(format "%s - %s" data [:gary -3])]))
| 19882 | (ns such.f-function-makers
(:require [such.function-makers :as mkfn])
(:use midje.sweet))
(fact "pred:any?"
((mkfn/pred:any? odd? even?) 1) => true
((mkfn/pred:any? pos? neg?) 0) => false
((mkfn/pred:any? :key :word) {:key false}) => false
((mkfn/pred:any? :key :word) {:key false :word 3}) => true
((mkfn/pred:any? #{1 2} #{3 4}) 3) => true
;; stops at first match
((mkfn/pred:any? (partial = 3) (fn[_](throw (new Error "boom!")))) 3) => true
;; Any empty list means that everything matches
((mkfn/pred:any?) 3) => true)
(fact "pred:not-any? and pred:none-of?"
((mkfn/pred:not-any? odd? even?) 1) => false
((mkfn/pred:not-any? pos? neg?) 0) => true
((mkfn/pred:none-of? :key :word) {:key false}) => true
((mkfn/pred:none-of? :key :word) {:key false :word 3}) => false
((mkfn/pred:not-any? #{1 2} #{3 4}) 3) => false
;; stops at first match
((mkfn/pred:not-any? (partial = 3) (fn[_](throw (new Error "boom!")))) 3) => false
;; Any empty list means that everything matches
((mkfn/pred:not-any?) 3) => false)
(fact pred:exception->false
(let [wrapped (mkfn/pred:exception->false even?)]
(wrapped 2) => true
(wrapped 3) => false
(even? nil) => (throws)
(wrapped nil) => false))
(fact "`lazyseq:x->abc` converts (possibly optionally) each element of a lazyseq and replaces it with N results"
(fact "one arg form processes each element"
( (mkfn/lazyseq:x->abc #(repeat % %)) [1 2 3]) => [1 2 2 3 3 3])
(fact "two arg form processes only elements that match predicate"
( (mkfn/lazyseq:x->abc #(repeat % %) even?) [1 2 3 4]) => [1 2 2 3 4 4 4 4])
(fact "empty sequences are handled"
( (mkfn/lazyseq:x->abc #(repeat % %) even?) []) => empty?)
(fact "it is indeed lazy"
(let [made (mkfn/lazyseq:x->abc #(repeat % %) even?)]
(take 2 (made [0])) => empty?
(take 2 (made [0 1])) => [1]
(take 2 (made [0 1 2])) => [1 2]
(take 2 (made [0 1 2 3])) => [1 2]
(take 2 (made [0 1 2 3 4])) => [1 2]
(take 2 (made (range))) => [ 1 2 ]
(count (take 100000 (made (range)))) => 100000)))
(fact "`lazyseq:x->xabc` converts (possibly optionally) each element of a lazyseq and replaces it
with N results. The first argument is preserved"
(fact "one arg form processes each element"
( (mkfn/lazyseq:x->xabc #(repeat % (- %))) [1 2 3]) => [1 -1 2 -2 -2 3 -3 -3 -3])
(fact "two arg form processes only elements that match predicate"
( (mkfn/lazyseq:x->xabc #(repeat % (- %)) even?) [1 2 3 4]) => [1 2 -2 -2 3 4 -4 -4 -4 -4]))
(fact "`lazyseq:x->y` converts (possibly optionally) each element of a lazyseq and replaces it
with 1 result."
(fact "one arg form processes each element"
( (mkfn/lazyseq:x->y -) [1 2 3]) => [-1 -2 -3 ])
(fact "two arg form processes only elements that match predicate"
( (mkfn/lazyseq:x->y - even?) [1 2 3 4]) => [1 -2 3 -4]))
(fact lazyseq:criticize-deviationism
(let [recorder (atom [])
messager #(format "%s - %s" %1 %2)
critiquer (mkfn/lazyseq:criticize-deviationism (comp neg? second)
#(swap! recorder
conj
(messager %1 %2)))
data [[:ok 0] [:<NAME> -1] [:corey 10326] [:gary -3]]]
(critiquer data) => data
@recorder => [(format "%s - %s" data [:brian -1])
(format "%s - %s" data [:gary -3])]))
| true | (ns such.f-function-makers
(:require [such.function-makers :as mkfn])
(:use midje.sweet))
(fact "pred:any?"
((mkfn/pred:any? odd? even?) 1) => true
((mkfn/pred:any? pos? neg?) 0) => false
((mkfn/pred:any? :key :word) {:key false}) => false
((mkfn/pred:any? :key :word) {:key false :word 3}) => true
((mkfn/pred:any? #{1 2} #{3 4}) 3) => true
;; stops at first match
((mkfn/pred:any? (partial = 3) (fn[_](throw (new Error "boom!")))) 3) => true
;; Any empty list means that everything matches
((mkfn/pred:any?) 3) => true)
(fact "pred:not-any? and pred:none-of?"
((mkfn/pred:not-any? odd? even?) 1) => false
((mkfn/pred:not-any? pos? neg?) 0) => true
((mkfn/pred:none-of? :key :word) {:key false}) => true
((mkfn/pred:none-of? :key :word) {:key false :word 3}) => false
((mkfn/pred:not-any? #{1 2} #{3 4}) 3) => false
;; stops at first match
((mkfn/pred:not-any? (partial = 3) (fn[_](throw (new Error "boom!")))) 3) => false
;; Any empty list means that everything matches
((mkfn/pred:not-any?) 3) => false)
(fact pred:exception->false
(let [wrapped (mkfn/pred:exception->false even?)]
(wrapped 2) => true
(wrapped 3) => false
(even? nil) => (throws)
(wrapped nil) => false))
(fact "`lazyseq:x->abc` converts (possibly optionally) each element of a lazyseq and replaces it with N results"
(fact "one arg form processes each element"
( (mkfn/lazyseq:x->abc #(repeat % %)) [1 2 3]) => [1 2 2 3 3 3])
(fact "two arg form processes only elements that match predicate"
( (mkfn/lazyseq:x->abc #(repeat % %) even?) [1 2 3 4]) => [1 2 2 3 4 4 4 4])
(fact "empty sequences are handled"
( (mkfn/lazyseq:x->abc #(repeat % %) even?) []) => empty?)
(fact "it is indeed lazy"
(let [made (mkfn/lazyseq:x->abc #(repeat % %) even?)]
(take 2 (made [0])) => empty?
(take 2 (made [0 1])) => [1]
(take 2 (made [0 1 2])) => [1 2]
(take 2 (made [0 1 2 3])) => [1 2]
(take 2 (made [0 1 2 3 4])) => [1 2]
(take 2 (made (range))) => [ 1 2 ]
(count (take 100000 (made (range)))) => 100000)))
(fact "`lazyseq:x->xabc` converts (possibly optionally) each element of a lazyseq and replaces it
with N results. The first argument is preserved"
(fact "one arg form processes each element"
( (mkfn/lazyseq:x->xabc #(repeat % (- %))) [1 2 3]) => [1 -1 2 -2 -2 3 -3 -3 -3])
(fact "two arg form processes only elements that match predicate"
( (mkfn/lazyseq:x->xabc #(repeat % (- %)) even?) [1 2 3 4]) => [1 2 -2 -2 3 4 -4 -4 -4 -4]))
(fact "`lazyseq:x->y` converts (possibly optionally) each element of a lazyseq and replaces it
with 1 result."
(fact "one arg form processes each element"
( (mkfn/lazyseq:x->y -) [1 2 3]) => [-1 -2 -3 ])
(fact "two arg form processes only elements that match predicate"
( (mkfn/lazyseq:x->y - even?) [1 2 3 4]) => [1 -2 3 -4]))
(fact lazyseq:criticize-deviationism
(let [recorder (atom [])
messager #(format "%s - %s" %1 %2)
critiquer (mkfn/lazyseq:criticize-deviationism (comp neg? second)
#(swap! recorder
conj
(messager %1 %2)))
data [[:ok 0] [:PI:NAME:<NAME>END_PI -1] [:corey 10326] [:gary -3]]]
(critiquer data) => data
@recorder => [(format "%s - %s" data [:brian -1])
(format "%s - %s" data [:gary -3])]))
|
[
{
"context": "on\n {:region \"us-west-2\"\n :access-key \"AKIAJIMN7IBTFMNRLSZA\"\n :secret-key \"0cDUzKX6WdChzPIPPaFrMzV7PUoz",
"end": 4700,
"score": 0.9996915459632874,
"start": 4680,
"tag": "KEY",
"value": "AKIAJIMN7IBTFMNRLSZA"
},
{
"context": "ss-key \"AKIAJIMN7IBTFMNRLSZA\"\n :secret-key \"0cDUzKX6WdChzPIPPaFrMzV7PUoz6k9wcun1/Dfc\"}\n {:functionName \"dummy-fn\"\n :code {:",
"end": 4762,
"score": 0.9997721314430237,
"start": 4722,
"tag": "KEY",
"value": "0cDUzKX6WdChzPIPPaFrMzV7PUoz6k9wcun1/Dfc"
},
{
"context": "on\n {:region \"us-west-2\"\n :access-key \"AKIAJIMN7IBTFMNRLSZA\"\n :secret-key \"0cDUzKX6WdChzPIPPaFrMzV7PUoz",
"end": 5319,
"score": 0.9996252059936523,
"start": 5299,
"tag": "KEY",
"value": "AKIAJIMN7IBTFMNRLSZA"
},
{
"context": "ss-key \"AKIAJIMN7IBTFMNRLSZA\"\n :secret-key \"0cDUzKX6WdChzPIPPaFrMzV7PUoz6k9wcun1/Dfc\"}\n {:functionName \"dummy-fn\"}))\n\n ;; not fo",
"end": 5381,
"score": 0.9997726082801819,
"start": 5341,
"tag": "KEY",
"value": "0cDUzKX6WdChzPIPPaFrMzV7PUoz6k9wcun1/Dfc"
},
{
"context": "on\n {:region \"us-west-2\"\n :access-key \"AKIAJIMN7IBTFMNRLSZA\"\n :secret-key \"0cDUzKX6WdChzPIPPaFrMzV7PUoz",
"end": 5529,
"score": 0.9996505379676819,
"start": 5509,
"tag": "KEY",
"value": "AKIAJIMN7IBTFMNRLSZA"
},
{
"context": "ss-key \"AKIAJIMN7IBTFMNRLSZA\"\n :secret-key \"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\"}\n {:functionName \"not-found\"}))\n\n ;; good\n",
"end": 5591,
"score": 0.9997715950012207,
"start": 5551,
"tag": "KEY",
"value": "0cDUzKX6WdChzPIPPaFrMzV7PUoz6k9wcun1/Dfc"
},
{
"context": "de\n {:region \"us-west-2\"\n :access-key \"AKIAJIMN7IBTFMNRLSZA\"\n :secret-key \"0cDUzKX6WdChzPIPPaFrMzV7PUoz",
"end": 5743,
"score": 0.9997019171714783,
"start": 5723,
"tag": "KEY",
"value": "AKIAJIMN7IBTFMNRLSZA"
},
{
"context": "ss-key \"AKIAJIMN7IBTFMNRLSZA\"\n :secret-key \"0cDUzKX6WdChzPIPPaFrMzV7PUoz6k9wcun1/Dfc\"}\n {:functionName \"dummy-fn\"\n :zipFile",
"end": 5805,
"score": 0.9997727274894714,
"start": 5765,
"tag": "KEY",
"value": "0cDUzKX6WdChzPIPPaFrMzV7PUoz6k9wcun1/Dfc"
},
{
"context": "de\n {:region \"us-west-2\"\n :access-key \"AKIAJIMN7IBTFMNRLSZA\"\n :secret-key \"0cDUzKX6WdChzPIPPaFrMzV7PUoz",
"end": 6028,
"score": 0.9997135996818542,
"start": 6008,
"tag": "KEY",
"value": "AKIAJIMN7IBTFMNRLSZA"
},
{
"context": "ss-key \"AKIAJIMN7IBTFMNRLSZA\"\n :secret-key \"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\"}\n {:functionName \"not-found\"}))\n\n ;; not f",
"end": 6090,
"score": 0.9997700452804565,
"start": 6050,
"tag": "KEY",
"value": "0cDUzKX6WdChzPIPPaFrMzV7PUoz6k9wcun1/Dfc"
},
{
"context": "de\n {:region \"us-west-2\"\n :access-key \"AKIAJIMN7IBTFMNRLSZA\"\n :secret-key \"0cDUzKX6WdChzPIPPaFrMzV7PUoz",
"end": 6247,
"score": 0.9997209906578064,
"start": 6227,
"tag": "KEY",
"value": "AKIAJIMN7IBTFMNRLSZA"
},
{
"context": "ss-key \"AKIAJIMN7IBTFMNRLSZA\"\n :secret-key \"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\"}\n {:functionName \"not-found\"\n :zipFil",
"end": 6309,
"score": 0.999769926071167,
"start": 6269,
"tag": "KEY",
"value": "0cDUzKX6WdChzPIPPaFrMzV7PUoz6k9wcun1/Dfc"
},
{
"context": "ke\n {:region \"us-west-2\"\n :access-key \"AKIAJIMN7IBTFMNRLSZA\"\n :secret-key \"0cDUzKX6WdChzPIPPaFrMzV7PUoz",
"end": 6519,
"score": 0.9997302889823914,
"start": 6499,
"tag": "KEY",
"value": "AKIAJIMN7IBTFMNRLSZA"
},
{
"context": "ss-key \"AKIAJIMN7IBTFMNRLSZA\"\n :secret-key \"0cDUzKX6WdChzPIPPaFrMzV7PUoz6k9wcun1/Dfc\"}\n {:functionName \"dummy-fn\"\n :logType",
"end": 6581,
"score": 0.9997702240943909,
"start": 6541,
"tag": "KEY",
"value": "0cDUzKX6WdChzPIPPaFrMzV7PUoz6k9wcun1/Dfc"
},
{
"context": "ke\n {:region \"us-west-2\"\n :access-key \"AKIAJIMN7IBTFMNRLSZA\"\n :secret-key \"0cDUzKX6WdChzPIPPaFrMzV7PUoz",
"end": 6798,
"score": 0.9997339844703674,
"start": 6778,
"tag": "KEY",
"value": "AKIAJIMN7IBTFMNRLSZA"
},
{
"context": "ss-key \"AKIAJIMN7IBTFMNRLSZA\"\n :secret-key \"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\"}\n {:functionName \"not-found\"\n :logTyp",
"end": 6860,
"score": 0.9997729659080505,
"start": 6820,
"tag": "KEY",
"value": "0cDUzKX6WdChzPIPPaFrMzV7PUoz6k9wcun1/Dfc"
},
{
"context": "ke\n {:region \"us-west-2\"\n :access-key \"AKIAJIMN7IBTFMNRLSZA\"\n :secret-key \"0cDUzKX6WdChzPIPPaFrMzV7PUoz",
"end": 7077,
"score": 0.9789209365844727,
"start": 7057,
"tag": "KEY",
"value": "AKIAJIMN7IBTFMNRLSZA"
},
{
"context": "ss-key \"AKIAJIMN7IBTFMNRLSZA\"\n :secret-key \"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\"}\n {:functionName nil\n :logType \"Tail\"",
"end": 7139,
"score": 0.9997650980949402,
"start": 7099,
"tag": "KEY",
"value": "0cDUzKX6WdChzPIPPaFrMzV7PUoz6k9wcun1/Dfc"
}
] | src/clj/rx/aws.clj | zk/rx-lib | 0 | (ns rx.aws
(:require [rx.kitchen-sink :as ks]
[clojure.string :as str]
[byte-streams :as bs]
[clojure.java.io :as io]
[clojure.java.data :as jd])
(:import [com.amazonaws.auth
AWSStaticCredentialsProvider
BasicAWSCredentials]
[com.amazonaws.services.lambda
AWSLambdaClient
AWSLambdaClientBuilder]
[com.amazonaws.services.lambda.model
VpcConfig
TracingConfig
FunctionCode
Environment
CreateFunctionRequest
UpdateFunctionCodeRequest
UpdateFunctionConfigurationRequest
GetFunctionRequest
InvokeRequest
ResourceConflictException
ResourceNotFoundException
InvalidParameterValueException
AWSLambdaException]))
(defn credentials [access-key secret-key]
(BasicAWSCredentials. access-key secret-key))
(defn lambda-client [c]
(let [access-id (or (:access-id c)
(::access-id c))
secret-key (or (:secret-key c)
(::secret-key c))
region (or (:region c)
(::region c))]
(-> (AWSLambdaClientBuilder/standard)
(.withCredentials (AWSStaticCredentialsProvider.
(credentials
access-id
secret-key)))
(.withRegion region)
(.build))))
(defmethod jd/to-java
[java.util.Map clojure.lang.PersistentArrayMap]
[clazz m]
(->> m
(map (fn [[k v]]
[(name k) v]))
(into {})))
(defmethod jd/from-java java.nio.ByteBuffer [b]
(bs/convert b String))
(defn validation-exception? [e]
(str/includes?
(.getMessage e)
"ValidationException"))
(defn create-function [client-config payload]
(try
(when-let [zipFile (-> payload :code :zipFile)]
(when (or (string? zipFile))
(ks/throw-str "Zipfile must be type java.nio.Buffer")))
[(jd/from-java
(.createFunction
(lambda-client client-config)
(jd/to-java
CreateFunctionRequest
payload)))]
(catch ResourceConflictException e
[nil {:error-code :function-exists} e])
(catch AWSLambdaException e
(cond
(validation-exception? e)
[nil {:error-code :validation-failed} e]
:else [nil {:error-code :unknown} e]))
(catch Exception e
(cond
(validation-exception? e)
[nil {:error-code :validation-failed} e]
:else [nil {:error-code :unknown} e]))))
(defn path->zipfile [path]
(bs/convert
(io/file path)
java.nio.ByteBuffer))
(defn get-function [client-config payload]
(try
[(jd/from-java
(.getFunction
(lambda-client client-config)
(jd/to-java
GetFunctionRequest
payload)))]
(catch ResourceNotFoundException e
[nil {:error-code :resource-not-found}])))
(defn update-function-code [client-config payload]
(try
[{:success? true
:update-result
(jd/from-java
(.updateFunctionCode
(lambda-client client-config)
(jd/to-java
UpdateFunctionCodeRequest
payload)))}]
(catch ResourceNotFoundException e
[nil {:error-code :resource-not-found} e])
(catch InvalidParameterValueException e
[nil {:error-code :validation-failed} e])
(catch Exception e
[nil {:error-code :unknown} e])))
(defn update-function-configuration [client-config payload]
(try
[{:success? true
:update-result
(jd/from-java
(.updateFunctionConfiguration
(lambda-client client-config)
(jd/to-java
UpdateFunctionConfigurationRequest
payload)))}]
(catch ResourceNotFoundException e
[nil {:error-code :resource-not-found} e])
(catch InvalidParameterValueException e
[nil {:error-code :validation-failed} e])
(catch Exception e
[nil {:error-code :unknown} e])))
(defn invoke [client-config payload]
(try
[(-> (jd/from-java
(.invoke
(lambda-client client-config)
(doto (jd/to-java
InvokeRequest
payload))))
(update :logResult ks/from-base64-str))]
(catch ResourceNotFoundException e
[nil {:error-code :resource-not-found} e])
(catch Exception e
[nil {:error-code :unknown} e])))
(defn prep-invoke-payload [m]
(bs/convert
(ks/to-json m)
java.nio.ByteBuffer))
(comment
(ks/pp
(create-function
{:region "us-west-2"
:access-key "AKIAJIMN7IBTFMNRLSZA"
:secret-key "0cDUzKX6WdChzPIPPaFrMzV7PUoz6k9wcun1/Dfc"}
{:functionName "dummy-fn"
:code {:zipFile (path->zipfile "test/resources/echo.zip")}
:description "Dummy test functin, echo."
:environment {:variables {:envkey "envval"}}
:handler "run.echo"
:memorySize 128
:publish true
:role "arn:aws:iam::753209818049:role/lambda-exec"
:runtime "nodejs8.10"
:tags {:tagkey "tagval"}
:timeout 10
:tracingConfig {:mode "Active"}}))
;; good
(ks/pp
(get-function
{:region "us-west-2"
:access-key "AKIAJIMN7IBTFMNRLSZA"
:secret-key "0cDUzKX6WdChzPIPPaFrMzV7PUoz6k9wcun1/Dfc"}
{:functionName "dummy-fn"}))
;; not found
(ks/pp
(get-function
{:region "us-west-2"
:access-key "AKIAJIMN7IBTFMNRLSZA"
:secret-key "0cDUzKX6WdChzPIPPaFrMzV7PUoz6k9wcun1/Dfc"}
{:functionName "not-found"}))
;; good
(ks/pp
(update-function-code
{:region "us-west-2"
:access-key "AKIAJIMN7IBTFMNRLSZA"
:secret-key "0cDUzKX6WdChzPIPPaFrMzV7PUoz6k9wcun1/Dfc"}
{:functionName "dummy-fn"
:zipFile (path->zipfile "test/resources/echo.zip")}))
;; failed validation
(ks/pp
(update-function-code
{:region "us-west-2"
:access-key "AKIAJIMN7IBTFMNRLSZA"
:secret-key "0cDUzKX6WdChzPIPPaFrMzV7PUoz6k9wcun1/Dfc"}
{:functionName "not-found"}))
;; not found
(ks/pp
(update-function-code
{:region "us-west-2"
:access-key "AKIAJIMN7IBTFMNRLSZA"
:secret-key "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"}
{:functionName "not-found"
:zipFile (path->zipfile "test/resources/echo.zip")}))
;; INVOKE
;; good
(ks/pp
(invoke
{:region "us-west-2"
:access-key "AKIAJIMN7IBTFMNRLSZA"
:secret-key "0cDUzKX6WdChzPIPPaFrMzV7PUoz6k9wcun1/Dfc"}
{:functionName "dummy-fn"
:logType "Tail"
:payload (prep-invoke-payload {:foo "bar"})}))
;; not found
(ks/pp
(invoke
{:region "us-west-2"
:access-key "AKIAJIMN7IBTFMNRLSZA"
:secret-key "0cDUzKX6WdChzPIPPaFrMzV7PUoz6k9wcun1/Dfc"}
{:functionName "not-found"
:logType "Tail"
:payload (prep-invoke-payload {:foo "bar"})}))
;; unknown
(ks/pp
(invoke
{:region "us-west-2"
:access-key "AKIAJIMN7IBTFMNRLSZA"
:secret-key "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"}
{:functionName nil
:logType "Tail"
:payload (prep-invoke-payload {:foo "bar"})})))
| 77095 | (ns rx.aws
(:require [rx.kitchen-sink :as ks]
[clojure.string :as str]
[byte-streams :as bs]
[clojure.java.io :as io]
[clojure.java.data :as jd])
(:import [com.amazonaws.auth
AWSStaticCredentialsProvider
BasicAWSCredentials]
[com.amazonaws.services.lambda
AWSLambdaClient
AWSLambdaClientBuilder]
[com.amazonaws.services.lambda.model
VpcConfig
TracingConfig
FunctionCode
Environment
CreateFunctionRequest
UpdateFunctionCodeRequest
UpdateFunctionConfigurationRequest
GetFunctionRequest
InvokeRequest
ResourceConflictException
ResourceNotFoundException
InvalidParameterValueException
AWSLambdaException]))
(defn credentials [access-key secret-key]
(BasicAWSCredentials. access-key secret-key))
(defn lambda-client [c]
(let [access-id (or (:access-id c)
(::access-id c))
secret-key (or (:secret-key c)
(::secret-key c))
region (or (:region c)
(::region c))]
(-> (AWSLambdaClientBuilder/standard)
(.withCredentials (AWSStaticCredentialsProvider.
(credentials
access-id
secret-key)))
(.withRegion region)
(.build))))
(defmethod jd/to-java
[java.util.Map clojure.lang.PersistentArrayMap]
[clazz m]
(->> m
(map (fn [[k v]]
[(name k) v]))
(into {})))
(defmethod jd/from-java java.nio.ByteBuffer [b]
(bs/convert b String))
(defn validation-exception? [e]
(str/includes?
(.getMessage e)
"ValidationException"))
(defn create-function [client-config payload]
(try
(when-let [zipFile (-> payload :code :zipFile)]
(when (or (string? zipFile))
(ks/throw-str "Zipfile must be type java.nio.Buffer")))
[(jd/from-java
(.createFunction
(lambda-client client-config)
(jd/to-java
CreateFunctionRequest
payload)))]
(catch ResourceConflictException e
[nil {:error-code :function-exists} e])
(catch AWSLambdaException e
(cond
(validation-exception? e)
[nil {:error-code :validation-failed} e]
:else [nil {:error-code :unknown} e]))
(catch Exception e
(cond
(validation-exception? e)
[nil {:error-code :validation-failed} e]
:else [nil {:error-code :unknown} e]))))
(defn path->zipfile [path]
(bs/convert
(io/file path)
java.nio.ByteBuffer))
(defn get-function [client-config payload]
(try
[(jd/from-java
(.getFunction
(lambda-client client-config)
(jd/to-java
GetFunctionRequest
payload)))]
(catch ResourceNotFoundException e
[nil {:error-code :resource-not-found}])))
(defn update-function-code [client-config payload]
(try
[{:success? true
:update-result
(jd/from-java
(.updateFunctionCode
(lambda-client client-config)
(jd/to-java
UpdateFunctionCodeRequest
payload)))}]
(catch ResourceNotFoundException e
[nil {:error-code :resource-not-found} e])
(catch InvalidParameterValueException e
[nil {:error-code :validation-failed} e])
(catch Exception e
[nil {:error-code :unknown} e])))
(defn update-function-configuration [client-config payload]
(try
[{:success? true
:update-result
(jd/from-java
(.updateFunctionConfiguration
(lambda-client client-config)
(jd/to-java
UpdateFunctionConfigurationRequest
payload)))}]
(catch ResourceNotFoundException e
[nil {:error-code :resource-not-found} e])
(catch InvalidParameterValueException e
[nil {:error-code :validation-failed} e])
(catch Exception e
[nil {:error-code :unknown} e])))
(defn invoke [client-config payload]
(try
[(-> (jd/from-java
(.invoke
(lambda-client client-config)
(doto (jd/to-java
InvokeRequest
payload))))
(update :logResult ks/from-base64-str))]
(catch ResourceNotFoundException e
[nil {:error-code :resource-not-found} e])
(catch Exception e
[nil {:error-code :unknown} e])))
(defn prep-invoke-payload [m]
(bs/convert
(ks/to-json m)
java.nio.ByteBuffer))
(comment
(ks/pp
(create-function
{:region "us-west-2"
:access-key "<KEY>"
:secret-key "<KEY>"}
{:functionName "dummy-fn"
:code {:zipFile (path->zipfile "test/resources/echo.zip")}
:description "Dummy test functin, echo."
:environment {:variables {:envkey "envval"}}
:handler "run.echo"
:memorySize 128
:publish true
:role "arn:aws:iam::753209818049:role/lambda-exec"
:runtime "nodejs8.10"
:tags {:tagkey "tagval"}
:timeout 10
:tracingConfig {:mode "Active"}}))
;; good
(ks/pp
(get-function
{:region "us-west-2"
:access-key "<KEY>"
:secret-key "<KEY>"}
{:functionName "dummy-fn"}))
;; not found
(ks/pp
(get-function
{:region "us-west-2"
:access-key "<KEY>"
:secret-key "<KEY>"}
{:functionName "not-found"}))
;; good
(ks/pp
(update-function-code
{:region "us-west-2"
:access-key "<KEY>"
:secret-key "<KEY>"}
{:functionName "dummy-fn"
:zipFile (path->zipfile "test/resources/echo.zip")}))
;; failed validation
(ks/pp
(update-function-code
{:region "us-west-2"
:access-key "<KEY>"
:secret-key "<KEY>"}
{:functionName "not-found"}))
;; not found
(ks/pp
(update-function-code
{:region "us-west-2"
:access-key "<KEY>"
:secret-key "<KEY>"}
{:functionName "not-found"
:zipFile (path->zipfile "test/resources/echo.zip")}))
;; INVOKE
;; good
(ks/pp
(invoke
{:region "us-west-2"
:access-key "<KEY>"
:secret-key "<KEY>"}
{:functionName "dummy-fn"
:logType "Tail"
:payload (prep-invoke-payload {:foo "bar"})}))
;; not found
(ks/pp
(invoke
{:region "us-west-2"
:access-key "<KEY>"
:secret-key "<KEY>"}
{:functionName "not-found"
:logType "Tail"
:payload (prep-invoke-payload {:foo "bar"})}))
;; unknown
(ks/pp
(invoke
{:region "us-west-2"
:access-key "<KEY>"
:secret-key "<KEY>"}
{:functionName nil
:logType "Tail"
:payload (prep-invoke-payload {:foo "bar"})})))
| true | (ns rx.aws
(:require [rx.kitchen-sink :as ks]
[clojure.string :as str]
[byte-streams :as bs]
[clojure.java.io :as io]
[clojure.java.data :as jd])
(:import [com.amazonaws.auth
AWSStaticCredentialsProvider
BasicAWSCredentials]
[com.amazonaws.services.lambda
AWSLambdaClient
AWSLambdaClientBuilder]
[com.amazonaws.services.lambda.model
VpcConfig
TracingConfig
FunctionCode
Environment
CreateFunctionRequest
UpdateFunctionCodeRequest
UpdateFunctionConfigurationRequest
GetFunctionRequest
InvokeRequest
ResourceConflictException
ResourceNotFoundException
InvalidParameterValueException
AWSLambdaException]))
(defn credentials [access-key secret-key]
(BasicAWSCredentials. access-key secret-key))
(defn lambda-client [c]
(let [access-id (or (:access-id c)
(::access-id c))
secret-key (or (:secret-key c)
(::secret-key c))
region (or (:region c)
(::region c))]
(-> (AWSLambdaClientBuilder/standard)
(.withCredentials (AWSStaticCredentialsProvider.
(credentials
access-id
secret-key)))
(.withRegion region)
(.build))))
(defmethod jd/to-java
[java.util.Map clojure.lang.PersistentArrayMap]
[clazz m]
(->> m
(map (fn [[k v]]
[(name k) v]))
(into {})))
(defmethod jd/from-java java.nio.ByteBuffer [b]
(bs/convert b String))
(defn validation-exception? [e]
(str/includes?
(.getMessage e)
"ValidationException"))
(defn create-function [client-config payload]
(try
(when-let [zipFile (-> payload :code :zipFile)]
(when (or (string? zipFile))
(ks/throw-str "Zipfile must be type java.nio.Buffer")))
[(jd/from-java
(.createFunction
(lambda-client client-config)
(jd/to-java
CreateFunctionRequest
payload)))]
(catch ResourceConflictException e
[nil {:error-code :function-exists} e])
(catch AWSLambdaException e
(cond
(validation-exception? e)
[nil {:error-code :validation-failed} e]
:else [nil {:error-code :unknown} e]))
(catch Exception e
(cond
(validation-exception? e)
[nil {:error-code :validation-failed} e]
:else [nil {:error-code :unknown} e]))))
(defn path->zipfile [path]
(bs/convert
(io/file path)
java.nio.ByteBuffer))
(defn get-function [client-config payload]
(try
[(jd/from-java
(.getFunction
(lambda-client client-config)
(jd/to-java
GetFunctionRequest
payload)))]
(catch ResourceNotFoundException e
[nil {:error-code :resource-not-found}])))
(defn update-function-code [client-config payload]
(try
[{:success? true
:update-result
(jd/from-java
(.updateFunctionCode
(lambda-client client-config)
(jd/to-java
UpdateFunctionCodeRequest
payload)))}]
(catch ResourceNotFoundException e
[nil {:error-code :resource-not-found} e])
(catch InvalidParameterValueException e
[nil {:error-code :validation-failed} e])
(catch Exception e
[nil {:error-code :unknown} e])))
(defn update-function-configuration [client-config payload]
(try
[{:success? true
:update-result
(jd/from-java
(.updateFunctionConfiguration
(lambda-client client-config)
(jd/to-java
UpdateFunctionConfigurationRequest
payload)))}]
(catch ResourceNotFoundException e
[nil {:error-code :resource-not-found} e])
(catch InvalidParameterValueException e
[nil {:error-code :validation-failed} e])
(catch Exception e
[nil {:error-code :unknown} e])))
(defn invoke [client-config payload]
(try
[(-> (jd/from-java
(.invoke
(lambda-client client-config)
(doto (jd/to-java
InvokeRequest
payload))))
(update :logResult ks/from-base64-str))]
(catch ResourceNotFoundException e
[nil {:error-code :resource-not-found} e])
(catch Exception e
[nil {:error-code :unknown} e])))
(defn prep-invoke-payload [m]
(bs/convert
(ks/to-json m)
java.nio.ByteBuffer))
(comment
(ks/pp
(create-function
{:region "us-west-2"
:access-key "PI:KEY:<KEY>END_PI"
:secret-key "PI:KEY:<KEY>END_PI"}
{:functionName "dummy-fn"
:code {:zipFile (path->zipfile "test/resources/echo.zip")}
:description "Dummy test functin, echo."
:environment {:variables {:envkey "envval"}}
:handler "run.echo"
:memorySize 128
:publish true
:role "arn:aws:iam::753209818049:role/lambda-exec"
:runtime "nodejs8.10"
:tags {:tagkey "tagval"}
:timeout 10
:tracingConfig {:mode "Active"}}))
;; good
(ks/pp
(get-function
{:region "us-west-2"
:access-key "PI:KEY:<KEY>END_PI"
:secret-key "PI:KEY:<KEY>END_PI"}
{:functionName "dummy-fn"}))
;; not found
(ks/pp
(get-function
{:region "us-west-2"
:access-key "PI:KEY:<KEY>END_PI"
:secret-key "PI:KEY:<KEY>END_PI"}
{:functionName "not-found"}))
;; good
(ks/pp
(update-function-code
{:region "us-west-2"
:access-key "PI:KEY:<KEY>END_PI"
:secret-key "PI:KEY:<KEY>END_PI"}
{:functionName "dummy-fn"
:zipFile (path->zipfile "test/resources/echo.zip")}))
;; failed validation
(ks/pp
(update-function-code
{:region "us-west-2"
:access-key "PI:KEY:<KEY>END_PI"
:secret-key "PI:KEY:<KEY>END_PI"}
{:functionName "not-found"}))
;; not found
(ks/pp
(update-function-code
{:region "us-west-2"
:access-key "PI:KEY:<KEY>END_PI"
:secret-key "PI:KEY:<KEY>END_PI"}
{:functionName "not-found"
:zipFile (path->zipfile "test/resources/echo.zip")}))
;; INVOKE
;; good
(ks/pp
(invoke
{:region "us-west-2"
:access-key "PI:KEY:<KEY>END_PI"
:secret-key "PI:KEY:<KEY>END_PI"}
{:functionName "dummy-fn"
:logType "Tail"
:payload (prep-invoke-payload {:foo "bar"})}))
;; not found
(ks/pp
(invoke
{:region "us-west-2"
:access-key "PI:KEY:<KEY>END_PI"
:secret-key "PI:KEY:<KEY>END_PI"}
{:functionName "not-found"
:logType "Tail"
:payload (prep-invoke-payload {:foo "bar"})}))
;; unknown
(ks/pp
(invoke
{:region "us-west-2"
:access-key "PI:KEY:<KEY>END_PI"
:secret-key "PI:KEY:<KEY>END_PI"}
{:functionName nil
:logType "Tail"
:payload (prep-invoke-payload {:foo "bar"})})))
|
[
{
"context": "{ :doc \"Thrift Protocol Wrappers\"\n :author \"Yannick Scherer\" }\n thrift-clj.protocol.core\n (:import [org.apa",
"end": 70,
"score": 0.9998540282249451,
"start": 55,
"tag": "NAME",
"value": "Yannick Scherer"
}
] | src/thrift_clj/protocol/core.clj | ipostelnik/thrift-clj | 35 | (ns ^{ :doc "Thrift Protocol Wrappers"
:author "Yannick Scherer" }
thrift-clj.protocol.core
(:import [org.apache.thrift.protocol
TProtocol TProtocolFactory
TBinaryProtocol$Factory TCompactProtocol$Factory
TJSONProtocol$Factory TSimpleJSONProtocol$Factory TTupleProtocol$Factory]
[org.apache.thrift.transport TTransport]))
;; ## Protocol Multimethod
(defmulti ^TProtocolFactory protocol-factory*
"Create Protocol Factory of the given Type with the given Options."
(fn [id _] id)
:default nil)
(defmethod protocol-factory* nil
[id _]
(throw (Exception. (str "Unknown Protocol: " id))))
(defn ^TProtocolFactory protocol-factory
"Create Protocol Factory of the given Type with the given Options."
[id & args]
(protocol-factory* id (apply hash-map args)))
(defn ^TProtocol protocol
"Create Protocol of the given Type with the given Options."
[id ^TTransport transport & args]
(when-let [^TProtocolFactory factory (apply protocol-factory id args)]
(.getProtocol factory transport)))
;; ## Protocol Implementations
(defmethod protocol-factory* :binary
[_ {:keys[strict-read strict-write]}]
(TBinaryProtocol$Factory.
(boolean strict-read)
(boolean strict-write)))
(defmethod protocol-factory* :compact
[_ {:keys[max-network-bytes]}]
(TCompactProtocol$Factory.
(long (or max-network-bytes -1))))
(let [json-factory (TJSONProtocol$Factory.)]
(defmethod protocol-factory* :json
[_ _]
json-factory))
(let [simple-json-factory (TSimpleJSONProtocol$Factory.)]
(defmethod protocol-factory* :simple-json
[_ _]
simple-json-factory))
(let [tuple-factory (TTupleProtocol$Factory.)]
(defmethod protocol-factory* :tuple
[_ _]
tuple-factory))
| 49340 | (ns ^{ :doc "Thrift Protocol Wrappers"
:author "<NAME>" }
thrift-clj.protocol.core
(:import [org.apache.thrift.protocol
TProtocol TProtocolFactory
TBinaryProtocol$Factory TCompactProtocol$Factory
TJSONProtocol$Factory TSimpleJSONProtocol$Factory TTupleProtocol$Factory]
[org.apache.thrift.transport TTransport]))
;; ## Protocol Multimethod
(defmulti ^TProtocolFactory protocol-factory*
"Create Protocol Factory of the given Type with the given Options."
(fn [id _] id)
:default nil)
(defmethod protocol-factory* nil
[id _]
(throw (Exception. (str "Unknown Protocol: " id))))
(defn ^TProtocolFactory protocol-factory
"Create Protocol Factory of the given Type with the given Options."
[id & args]
(protocol-factory* id (apply hash-map args)))
(defn ^TProtocol protocol
"Create Protocol of the given Type with the given Options."
[id ^TTransport transport & args]
(when-let [^TProtocolFactory factory (apply protocol-factory id args)]
(.getProtocol factory transport)))
;; ## Protocol Implementations
(defmethod protocol-factory* :binary
[_ {:keys[strict-read strict-write]}]
(TBinaryProtocol$Factory.
(boolean strict-read)
(boolean strict-write)))
(defmethod protocol-factory* :compact
[_ {:keys[max-network-bytes]}]
(TCompactProtocol$Factory.
(long (or max-network-bytes -1))))
(let [json-factory (TJSONProtocol$Factory.)]
(defmethod protocol-factory* :json
[_ _]
json-factory))
(let [simple-json-factory (TSimpleJSONProtocol$Factory.)]
(defmethod protocol-factory* :simple-json
[_ _]
simple-json-factory))
(let [tuple-factory (TTupleProtocol$Factory.)]
(defmethod protocol-factory* :tuple
[_ _]
tuple-factory))
| true | (ns ^{ :doc "Thrift Protocol Wrappers"
:author "PI:NAME:<NAME>END_PI" }
thrift-clj.protocol.core
(:import [org.apache.thrift.protocol
TProtocol TProtocolFactory
TBinaryProtocol$Factory TCompactProtocol$Factory
TJSONProtocol$Factory TSimpleJSONProtocol$Factory TTupleProtocol$Factory]
[org.apache.thrift.transport TTransport]))
;; ## Protocol Multimethod
(defmulti ^TProtocolFactory protocol-factory*
"Create Protocol Factory of the given Type with the given Options."
(fn [id _] id)
:default nil)
(defmethod protocol-factory* nil
[id _]
(throw (Exception. (str "Unknown Protocol: " id))))
(defn ^TProtocolFactory protocol-factory
"Create Protocol Factory of the given Type with the given Options."
[id & args]
(protocol-factory* id (apply hash-map args)))
(defn ^TProtocol protocol
"Create Protocol of the given Type with the given Options."
[id ^TTransport transport & args]
(when-let [^TProtocolFactory factory (apply protocol-factory id args)]
(.getProtocol factory transport)))
;; ## Protocol Implementations
(defmethod protocol-factory* :binary
[_ {:keys[strict-read strict-write]}]
(TBinaryProtocol$Factory.
(boolean strict-read)
(boolean strict-write)))
(defmethod protocol-factory* :compact
[_ {:keys[max-network-bytes]}]
(TCompactProtocol$Factory.
(long (or max-network-bytes -1))))
(let [json-factory (TJSONProtocol$Factory.)]
(defmethod protocol-factory* :json
[_ _]
json-factory))
(let [simple-json-factory (TSimpleJSONProtocol$Factory.)]
(defmethod protocol-factory* :simple-json
[_ _]
simple-json-factory))
(let [tuple-factory (TTupleProtocol$Factory.)]
(defmethod protocol-factory* :tuple
[_ _]
tuple-factory))
|
[
{
"context": "\"\n order-details-invalid\n {:name \"Mitchard Blimmons\"\n :email \"mitchard.blimmonsgmail.com\"}\n ",
"end": 331,
"score": 0.9998967051506042,
"start": 314,
"tag": "NAME",
"value": "Mitchard Blimmons"
},
{
"context": " {:name \"Mitchard Blimmons\"\n :email \"mitchard.blimmonsgmail.com\"}\n order-details-valid\n {:name \"M",
"end": 377,
"score": 0.7921046018600464,
"start": 354,
"tag": "EMAIL",
"value": "chard.blimmonsgmail.com"
},
{
"context": "m\"}\n order-details-valid\n {:name \"Mitchard Blimmons\"\n :email \"mitchard.blimmons@gmail.com\"}\n",
"end": 443,
"score": 0.9998940825462341,
"start": 426,
"tag": "NAME",
"value": "Mitchard Blimmons"
},
{
"context": " {:name \"Mitchard Blimmons\"\n :email \"mitchard.blimmons@gmail.com\"}\n order-details-validations\n {:n",
"end": 490,
"score": 0.9997865557670593,
"start": 463,
"tag": "EMAIL",
"value": "mitchard.blimmons@gmail.com"
}
] | test/clj_brave_and_true/chapter08_test.clj | artemy/clj-brave-and-true-exercises | 0 | (ns clj-brave-and-true.chapter08-test
(:require [clojure.test :refer [deftest testing is]]
[clj-brave-and-true.chapter08 :refer [when-valid custom-or defattrs]]))
(deftest when-valid-test
(testing
(let [valid-output "It's a success!\n:success\n"
order-details-invalid
{:name "Mitchard Blimmons"
:email "mitchard.blimmonsgmail.com"}
order-details-valid
{:name "Mitchard Blimmons"
:email "mitchard.blimmons@gmail.com"}
order-details-validations
{:name
["Please enter a name" not-empty]
:email
["Please enter an email address" not-empty
"Your email address doesn't look like an email address"
#(or (empty? %) (re-seq #"@" %))]}]
(is (= valid-output (with-out-str (when-valid order-details-valid order-details-validations
(println "It's a success!")
(println :success)))))
(is (= "" (with-out-str (when-valid order-details-invalid order-details-validations
(println "It's a success!")
(println :success))))))))
(deftest custom-or-test
(testing
(is (= true (custom-or false false false false true)))
(is (= false (custom-or false false false false false)))
(is (= true (custom-or true)))))
(deftest defattrs-test
(testing
(let [expected '(do
(def clj-brave-and-true.chapter08-test/c-int :intelligence)
(def clj-brave-and-true.chapter08-test/c-str :strength)
(def clj-brave-and-true.chapter08-test/c-dex :dexterity))]
(is (= expected (macroexpand `(defattrs c-int :intelligence
c-str :strength
c-dex :dexterity))))))) | 91899 | (ns clj-brave-and-true.chapter08-test
(:require [clojure.test :refer [deftest testing is]]
[clj-brave-and-true.chapter08 :refer [when-valid custom-or defattrs]]))
(deftest when-valid-test
(testing
(let [valid-output "It's a success!\n:success\n"
order-details-invalid
{:name "<NAME>"
:email "mit<EMAIL>"}
order-details-valid
{:name "<NAME>"
:email "<EMAIL>"}
order-details-validations
{:name
["Please enter a name" not-empty]
:email
["Please enter an email address" not-empty
"Your email address doesn't look like an email address"
#(or (empty? %) (re-seq #"@" %))]}]
(is (= valid-output (with-out-str (when-valid order-details-valid order-details-validations
(println "It's a success!")
(println :success)))))
(is (= "" (with-out-str (when-valid order-details-invalid order-details-validations
(println "It's a success!")
(println :success))))))))
(deftest custom-or-test
(testing
(is (= true (custom-or false false false false true)))
(is (= false (custom-or false false false false false)))
(is (= true (custom-or true)))))
(deftest defattrs-test
(testing
(let [expected '(do
(def clj-brave-and-true.chapter08-test/c-int :intelligence)
(def clj-brave-and-true.chapter08-test/c-str :strength)
(def clj-brave-and-true.chapter08-test/c-dex :dexterity))]
(is (= expected (macroexpand `(defattrs c-int :intelligence
c-str :strength
c-dex :dexterity))))))) | true | (ns clj-brave-and-true.chapter08-test
(:require [clojure.test :refer [deftest testing is]]
[clj-brave-and-true.chapter08 :refer [when-valid custom-or defattrs]]))
(deftest when-valid-test
(testing
(let [valid-output "It's a success!\n:success\n"
order-details-invalid
{:name "PI:NAME:<NAME>END_PI"
:email "mitPI:EMAIL:<EMAIL>END_PI"}
order-details-valid
{:name "PI:NAME:<NAME>END_PI"
:email "PI:EMAIL:<EMAIL>END_PI"}
order-details-validations
{:name
["Please enter a name" not-empty]
:email
["Please enter an email address" not-empty
"Your email address doesn't look like an email address"
#(or (empty? %) (re-seq #"@" %))]}]
(is (= valid-output (with-out-str (when-valid order-details-valid order-details-validations
(println "It's a success!")
(println :success)))))
(is (= "" (with-out-str (when-valid order-details-invalid order-details-validations
(println "It's a success!")
(println :success))))))))
(deftest custom-or-test
(testing
(is (= true (custom-or false false false false true)))
(is (= false (custom-or false false false false false)))
(is (= true (custom-or true)))))
(deftest defattrs-test
(testing
(let [expected '(do
(def clj-brave-and-true.chapter08-test/c-int :intelligence)
(def clj-brave-and-true.chapter08-test/c-str :strength)
(def clj-brave-and-true.chapter08-test/c-dex :dexterity))]
(is (= expected (macroexpand `(defattrs c-int :intelligence
c-str :strength
c-dex :dexterity))))))) |
[
{
"context": "icy.com/\n ;; See also: https://github.com/pedestal/pedestal/issues/499\n ;;::http/secure-header",
"end": 2932,
"score": 0.9996134638786316,
"start": 2924,
"tag": "USERNAME",
"value": "pedestal"
},
{
"context": "\n ::http/type :immutant\n ::http/host \"0.0.0.0\"\n ::http/port 8080\n ;; Options to pas",
"end": 3651,
"score": 0.99891197681427,
"start": 3644,
"tag": "IP_ADDRESS",
"value": "0.0.0.0"
},
{
"context": "\n ;:key-password \"password\"\n ;:ssl-port 8443",
"end": 3940,
"score": 0.5677328109741211,
"start": 3932,
"tag": "KEY",
"value": "password"
}
] | src/jcpsantiago/sagemaker_multimodel_clj/service.clj | jcpsantiago/sagemaker-multimodel-clj | 4 | (ns jcpsantiago.sagemaker-multimodel-clj.service
(:require [io.pedestal.http :as http]
[io.pedestal.http.route :as route]
[io.pedestal.http.body-params :as body-params]
[io.pedestal.interceptor.helpers :as interceptor]
[ring.util.response :as ring-resp]
[jcpsantiago.sagemaker-multimodel-clj.handlers :as handlers]
[jsonista.core :as json]))
(def common-interceptors [(body-params/body-params) http/html-body])
(def json-body
"Set the Content-Type header to \"application/json\" and convert the body to
JSON if the body is a collection and a type has not been set."
(interceptor/on-response
::json-body
(fn [response]
(let [body (:body response)
content-type (get-in response [:headers "Content-Type"])]
(if (and (coll? body) (not content-type))
(-> response
(ring-resp/content-type "application/json;charset=UTF-8")
(assoc :body (json/write-value-as-string body)))
response)))))
;; Tabular routes
(def routes #{["/ping" :get (conj common-interceptors `handlers/ping)]
["/models" :get (conj common-interceptors `handlers/list-models)]
["/models" :post (conj common-interceptors `handlers/load-model!)]
["/models/:model-name" :delete (conj common-interceptors
`handlers/unload-model!)]
["/models/:model-name/invoke" :post (conj common-interceptors
`handlers/invoke-model)]})
;; Map-based routes
;(def routes `{"/" {:interceptors [(body-params/body-params) http/html-body]
; :get home-page
; "/about" {:get about-page}}})
;; Terse/Vector-based routes
;(def routes
; `[[["/" {:get home-page}
; ^:interceptors [(body-params/body-params) http/html-body]
; ["/about" {:get about-page}]]]])
;; Consumed by sagemaker-multimodel-clj.server/create-server
;; See http/default-interceptors for additional options you can configure
(def service
(-> {:env :prod
;; You can bring your own non-default interceptors. Make
;; sure you include routing and set it up right for
;; dev-mode. If you do, many other keys for configuring
;; default interceptors will be ignored.
;; ::http/interceptors []
::http/routes routes
;; Uncomment next line to enable CORS support, add
;; string(s) specifying scheme, host and port for
;; allowed source(s):
;;
;; "http://localhost:8080"
;;
;;::http/allowed-origins ["scheme://host:port"]
;; Tune the Secure Headers
;; and specifically the Content Security Policy appropriate to your service/application
;; For more information, see: https://content-security-policy.com/
;; See also: https://github.com/pedestal/pedestal/issues/499
;;::http/secure-headers {:content-security-policy-settings {:object-src "'none'"
;; :script-src "'unsafe-inline' 'unsafe-eval' 'strict-dynamic' https: http:"
;; :frame-ancestors "'none'"}}
;; Root for resource interceptor that is available by default.
::http/resource-path "/public"
;; Either :jetty, :immutant or :tomcat (see comments in project.clj)
;; This can also be your own chain provider/server-fn -- http://pedestal.io/reference/architecture-overview#_chain_provider
::http/type :immutant
::http/host "0.0.0.0"
::http/port 8080
;; Options to pass to the container (Jetty)
::http/container-options {:h2c? true
:h2? false
;:keystore "test/hp/keystore.jks"
;:key-password "password"
;:ssl-port 8443
:ssl? false}}
;; Alternatively, You can specify you're own Jetty HTTPConfiguration
;; via the `:io.pedestal.http.jetty/http-configuration` container option.
;:io.pedestal.http.jetty/http-configuration (org.eclipse.jetty.server.HttpConfiguration.)
http/default-interceptors
(update ::http/interceptors conj json-body)))
| 70096 | (ns jcpsantiago.sagemaker-multimodel-clj.service
(:require [io.pedestal.http :as http]
[io.pedestal.http.route :as route]
[io.pedestal.http.body-params :as body-params]
[io.pedestal.interceptor.helpers :as interceptor]
[ring.util.response :as ring-resp]
[jcpsantiago.sagemaker-multimodel-clj.handlers :as handlers]
[jsonista.core :as json]))
(def common-interceptors [(body-params/body-params) http/html-body])
(def json-body
"Set the Content-Type header to \"application/json\" and convert the body to
JSON if the body is a collection and a type has not been set."
(interceptor/on-response
::json-body
(fn [response]
(let [body (:body response)
content-type (get-in response [:headers "Content-Type"])]
(if (and (coll? body) (not content-type))
(-> response
(ring-resp/content-type "application/json;charset=UTF-8")
(assoc :body (json/write-value-as-string body)))
response)))))
;; Tabular routes
(def routes #{["/ping" :get (conj common-interceptors `handlers/ping)]
["/models" :get (conj common-interceptors `handlers/list-models)]
["/models" :post (conj common-interceptors `handlers/load-model!)]
["/models/:model-name" :delete (conj common-interceptors
`handlers/unload-model!)]
["/models/:model-name/invoke" :post (conj common-interceptors
`handlers/invoke-model)]})
;; Map-based routes
;(def routes `{"/" {:interceptors [(body-params/body-params) http/html-body]
; :get home-page
; "/about" {:get about-page}}})
;; Terse/Vector-based routes
;(def routes
; `[[["/" {:get home-page}
; ^:interceptors [(body-params/body-params) http/html-body]
; ["/about" {:get about-page}]]]])
;; Consumed by sagemaker-multimodel-clj.server/create-server
;; See http/default-interceptors for additional options you can configure
(def service
(-> {:env :prod
;; You can bring your own non-default interceptors. Make
;; sure you include routing and set it up right for
;; dev-mode. If you do, many other keys for configuring
;; default interceptors will be ignored.
;; ::http/interceptors []
::http/routes routes
;; Uncomment next line to enable CORS support, add
;; string(s) specifying scheme, host and port for
;; allowed source(s):
;;
;; "http://localhost:8080"
;;
;;::http/allowed-origins ["scheme://host:port"]
;; Tune the Secure Headers
;; and specifically the Content Security Policy appropriate to your service/application
;; For more information, see: https://content-security-policy.com/
;; See also: https://github.com/pedestal/pedestal/issues/499
;;::http/secure-headers {:content-security-policy-settings {:object-src "'none'"
;; :script-src "'unsafe-inline' 'unsafe-eval' 'strict-dynamic' https: http:"
;; :frame-ancestors "'none'"}}
;; Root for resource interceptor that is available by default.
::http/resource-path "/public"
;; Either :jetty, :immutant or :tomcat (see comments in project.clj)
;; This can also be your own chain provider/server-fn -- http://pedestal.io/reference/architecture-overview#_chain_provider
::http/type :immutant
::http/host "0.0.0.0"
::http/port 8080
;; Options to pass to the container (Jetty)
::http/container-options {:h2c? true
:h2? false
;:keystore "test/hp/keystore.jks"
;:key-password "<KEY>"
;:ssl-port 8443
:ssl? false}}
;; Alternatively, You can specify you're own Jetty HTTPConfiguration
;; via the `:io.pedestal.http.jetty/http-configuration` container option.
;:io.pedestal.http.jetty/http-configuration (org.eclipse.jetty.server.HttpConfiguration.)
http/default-interceptors
(update ::http/interceptors conj json-body)))
| true | (ns jcpsantiago.sagemaker-multimodel-clj.service
(:require [io.pedestal.http :as http]
[io.pedestal.http.route :as route]
[io.pedestal.http.body-params :as body-params]
[io.pedestal.interceptor.helpers :as interceptor]
[ring.util.response :as ring-resp]
[jcpsantiago.sagemaker-multimodel-clj.handlers :as handlers]
[jsonista.core :as json]))
(def common-interceptors [(body-params/body-params) http/html-body])
(def json-body
"Set the Content-Type header to \"application/json\" and convert the body to
JSON if the body is a collection and a type has not been set."
(interceptor/on-response
::json-body
(fn [response]
(let [body (:body response)
content-type (get-in response [:headers "Content-Type"])]
(if (and (coll? body) (not content-type))
(-> response
(ring-resp/content-type "application/json;charset=UTF-8")
(assoc :body (json/write-value-as-string body)))
response)))))
;; Tabular routes
(def routes #{["/ping" :get (conj common-interceptors `handlers/ping)]
["/models" :get (conj common-interceptors `handlers/list-models)]
["/models" :post (conj common-interceptors `handlers/load-model!)]
["/models/:model-name" :delete (conj common-interceptors
`handlers/unload-model!)]
["/models/:model-name/invoke" :post (conj common-interceptors
`handlers/invoke-model)]})
;; Map-based routes
;(def routes `{"/" {:interceptors [(body-params/body-params) http/html-body]
; :get home-page
; "/about" {:get about-page}}})
;; Terse/Vector-based routes
;(def routes
; `[[["/" {:get home-page}
; ^:interceptors [(body-params/body-params) http/html-body]
; ["/about" {:get about-page}]]]])
;; Consumed by sagemaker-multimodel-clj.server/create-server
;; See http/default-interceptors for additional options you can configure
(def service
(-> {:env :prod
;; You can bring your own non-default interceptors. Make
;; sure you include routing and set it up right for
;; dev-mode. If you do, many other keys for configuring
;; default interceptors will be ignored.
;; ::http/interceptors []
::http/routes routes
;; Uncomment next line to enable CORS support, add
;; string(s) specifying scheme, host and port for
;; allowed source(s):
;;
;; "http://localhost:8080"
;;
;;::http/allowed-origins ["scheme://host:port"]
;; Tune the Secure Headers
;; and specifically the Content Security Policy appropriate to your service/application
;; For more information, see: https://content-security-policy.com/
;; See also: https://github.com/pedestal/pedestal/issues/499
;;::http/secure-headers {:content-security-policy-settings {:object-src "'none'"
;; :script-src "'unsafe-inline' 'unsafe-eval' 'strict-dynamic' https: http:"
;; :frame-ancestors "'none'"}}
;; Root for resource interceptor that is available by default.
::http/resource-path "/public"
;; Either :jetty, :immutant or :tomcat (see comments in project.clj)
;; This can also be your own chain provider/server-fn -- http://pedestal.io/reference/architecture-overview#_chain_provider
::http/type :immutant
::http/host "0.0.0.0"
::http/port 8080
;; Options to pass to the container (Jetty)
::http/container-options {:h2c? true
:h2? false
;:keystore "test/hp/keystore.jks"
;:key-password "PI:KEY:<KEY>END_PI"
;:ssl-port 8443
:ssl? false}}
;; Alternatively, You can specify you're own Jetty HTTPConfiguration
;; via the `:io.pedestal.http.jetty/http-configuration` container option.
;:io.pedestal.http.jetty/http-configuration (org.eclipse.jetty.server.HttpConfiguration.)
http/default-interceptors
(update ::http/interceptors conj json-body)))
|
[
{
"context": "assword group-guids]\n (let [token-info {:token {:username username\n :password pa",
"end": 1493,
"score": 0.7737597823143005,
"start": 1485,
"tag": "USERNAME",
"value": "username"
},
{
"context": "group-guids]\n (let [token-info {:token {:username username\n :password password\n ",
"end": 1502,
"score": 0.8750481009483337,
"start": 1494,
"tag": "USERNAME",
"value": "username"
},
{
"context": "ame username\n :password password\n :client_id \"CMR Inter",
"end": 1549,
"score": 0.9988355040550232,
"start": 1541,
"tag": "PASSWORD",
"value": "password"
},
{
"context": "al\"\n :user_ip_address \"127.0.0.1\"\n :group_guids group-g",
"end": 1659,
"score": 0.9997236728668213,
"start": 1650,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
}
] | mock-echo-app/src/cmr/mock_echo/client/mock_echo_client.clj | sxu123/Common-Metadata-Repository | 0 | (ns cmr.mock-echo.client.mock-echo-client
"Contains functions for communicating with the mock echo api that aren't normal echo-rest
operations"
(:require [cmr.transmit.echo.rest :as r]
[cmr.transmit.echo.conversion :as c]))
(defn reset
"Clears out all data in mock echo"
[context]
(r/rest-post context "/reset" nil))
(defn create-providers
"Creates the providers in mock echo given a provider-guid-to-id-map"
[context provider-guid-to-id-map]
(let [providers (for [[guid provider-id] provider-guid-to-id-map]
{:provider {:id guid
:provider_id provider-id}})
[status] (r/rest-post context "/providers" providers)]
(when-not (= status 201)
(r/unexpected-status-error! status nil))))
(defn create-acl
"Creates an ACL in mock echo. Takes cmr style acls. Returns the acl with the guid"
[context acl]
(let [[status acl body] (r/rest-post context "/acls" (c/cmr-acl->echo-acl acl))]
(if (= status 201)
acl
(r/unexpected-status-error! status body))))
(defn delete-acl
[context guid]
(let [[status body] (r/rest-delete context (str "/acls/" guid))]
(when-not (= status 200)
(r/unexpected-status-error! status body))))
(defn login-with-group-access
"Logs into mock echo and returns the token. The group guids passed in will be returned as a part
of the current_sids of the user"
[context username password group-guids]
(let [token-info {:token {:username username
:password password
:client_id "CMR Internal"
:user_ip_address "127.0.0.1"
:group_guids group-guids}}
[status parsed body] (r/rest-post context "/tokens" token-info)]
(if (= 201 status)
(get-in parsed [:token :id])
(r/unexpected-status-error! status body)))) | 119662 | (ns cmr.mock-echo.client.mock-echo-client
"Contains functions for communicating with the mock echo api that aren't normal echo-rest
operations"
(:require [cmr.transmit.echo.rest :as r]
[cmr.transmit.echo.conversion :as c]))
(defn reset
"Clears out all data in mock echo"
[context]
(r/rest-post context "/reset" nil))
(defn create-providers
"Creates the providers in mock echo given a provider-guid-to-id-map"
[context provider-guid-to-id-map]
(let [providers (for [[guid provider-id] provider-guid-to-id-map]
{:provider {:id guid
:provider_id provider-id}})
[status] (r/rest-post context "/providers" providers)]
(when-not (= status 201)
(r/unexpected-status-error! status nil))))
(defn create-acl
"Creates an ACL in mock echo. Takes cmr style acls. Returns the acl with the guid"
[context acl]
(let [[status acl body] (r/rest-post context "/acls" (c/cmr-acl->echo-acl acl))]
(if (= status 201)
acl
(r/unexpected-status-error! status body))))
(defn delete-acl
[context guid]
(let [[status body] (r/rest-delete context (str "/acls/" guid))]
(when-not (= status 200)
(r/unexpected-status-error! status body))))
(defn login-with-group-access
"Logs into mock echo and returns the token. The group guids passed in will be returned as a part
of the current_sids of the user"
[context username password group-guids]
(let [token-info {:token {:username username
:password <PASSWORD>
:client_id "CMR Internal"
:user_ip_address "127.0.0.1"
:group_guids group-guids}}
[status parsed body] (r/rest-post context "/tokens" token-info)]
(if (= 201 status)
(get-in parsed [:token :id])
(r/unexpected-status-error! status body)))) | true | (ns cmr.mock-echo.client.mock-echo-client
"Contains functions for communicating with the mock echo api that aren't normal echo-rest
operations"
(:require [cmr.transmit.echo.rest :as r]
[cmr.transmit.echo.conversion :as c]))
(defn reset
"Clears out all data in mock echo"
[context]
(r/rest-post context "/reset" nil))
(defn create-providers
"Creates the providers in mock echo given a provider-guid-to-id-map"
[context provider-guid-to-id-map]
(let [providers (for [[guid provider-id] provider-guid-to-id-map]
{:provider {:id guid
:provider_id provider-id}})
[status] (r/rest-post context "/providers" providers)]
(when-not (= status 201)
(r/unexpected-status-error! status nil))))
(defn create-acl
"Creates an ACL in mock echo. Takes cmr style acls. Returns the acl with the guid"
[context acl]
(let [[status acl body] (r/rest-post context "/acls" (c/cmr-acl->echo-acl acl))]
(if (= status 201)
acl
(r/unexpected-status-error! status body))))
(defn delete-acl
[context guid]
(let [[status body] (r/rest-delete context (str "/acls/" guid))]
(when-not (= status 200)
(r/unexpected-status-error! status body))))
(defn login-with-group-access
"Logs into mock echo and returns the token. The group guids passed in will be returned as a part
of the current_sids of the user"
[context username password group-guids]
(let [token-info {:token {:username username
:password PI:PASSWORD:<PASSWORD>END_PI
:client_id "CMR Internal"
:user_ip_address "127.0.0.1"
:group_guids group-guids}}
[status parsed body] (r/rest-post context "/tokens" token-info)]
(if (= 201 status)
(get-in parsed [:token :id])
(r/unexpected-status-error! status body)))) |
[
{
"context": ".Driver\"\n :subprotocol \"mysql\"\n :subname \"//127.0.0.1:3306/hello_world\"\n :user \"benchmarkdbuser\"\n ",
"end": 868,
"score": 0.9990853071212769,
"start": 859,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": "subname \"//127.0.0.1:3306/hello_world\"\n :user \"benchmarkdbuser\"\n :password \"benchmarkdbpass\"\n ;;OPTIONAL K",
"end": 913,
"score": 0.9970278739929199,
"start": 898,
"tag": "USERNAME",
"value": "benchmarkdbuser"
},
{
"context": "world\"\n :user \"benchmarkdbuser\"\n :password \"benchmarkdbpass\"\n ;;OPTIONAL KEYS\n :delimiters \"\" ;; remove",
"end": 945,
"score": 0.9993815422058105,
"start": 930,
"tag": "PASSWORD",
"value": "benchmarkdbpass"
}
] | frameworks/Clojure/http-kit/hello/src/hello/handler.clj | greg-hellings/FrameworkBenchmarks | 6 | (ns hello.handler
(:gen-class)
(:import com.mchange.v2.c3p0.ComboPooledDataSource)
(:use compojure.core
ring.middleware.json
org.httpkit.server
[clojure.tools.cli :only [cli]]
korma.db
korma.core
hiccup.core
hiccup.util
hiccup.page)
(:require [compojure.handler :as handler]
[compojure.route :as route]
[ring.util.response :as ring-resp]
[clojure.data.json :as json]
[clojure.java.jdbc :as jdbc]))
(defn parse-port [s]
"Convert stringy port number int. Defaults to 8080."
(cond
(string? s) (Integer/parseInt s)
(instance? Integer s) s
(instance? Long s) (.intValue ^Long s)
:else 8080))
;; MySQL connection
(defdb mysql-db
(mysql {
:classname "com.mysql.jdbc.Driver"
:subprotocol "mysql"
:subname "//127.0.0.1:3306/hello_world"
:user "benchmarkdbuser"
:password "benchmarkdbpass"
;;OPTIONAL KEYS
:delimiters "" ;; remove delimiters
:maximum-pool-size 256}))
;; Set up entity World and the database representation
(defentity world
(pk :id)
(table :world)
(entity-fields :id :randomNumber) ;; Default fields for select
(database mysql-db))
(defn sanitize-queries-param
"Sanitizes the `queries` parameter. Caps the value between 1 and 500.
Invalid (stringy) values become 1"
[queries]
(let [n (try (Integer/parseInt queries)
(catch Exception e 1))] ; default to 1 on parse failure
(cond
(< n 1) 1
(> n 500) 500
:else n)))
(defn random-world
"Query a random World record from the database"
[]
(let [id (inc (rand-int 9999))] ; Num between 1 and 10,000
(select world
(where {:id id }))))
(defn run-queries
"Run query repeatedly -- Always returns an array"
[queries]
(flatten (take queries (repeatedly random-world))))
; Set up entity Fortune and the database representation
(defentity fortune
(pk :id)
(table :fortune)
(entity-fields :id :message)
(database mysql-db))
(defn get-all-fortunes
"Query all Fortune records from the database."
[]
(select fortune
(fields :id :message)))
(defn get-fortunes
"Fetch the full list of Fortunes from the database, sort them by the fortune
message text, and then return the results."
[]
(sort-by #(:message %)
(conj
(get-all-fortunes)
{ :id 0 :message "Additional fortune added at request time." })))
(defn fortunes-hiccup
"Render the given fortunes to simple HTML using Hiccup."
[fortunes]
(html5
[:head
[:title "Fortunes"]]
[:body
[:table
[:tr
[:th "id"]
[:th "message"]]
(for [x fortunes]
[:tr
[:td (:id x)]
[:td (escape-html (:message x))]])
]]))
(defn update-and-persist
"Changes the :randomNumber of a number of world entities.
Persists the changes to sql then returns the updated entities"
[queries]
(let [results (-> queries
(sanitize-queries-param)
(run-queries))]
(for [w results]
(update-in w [:randomNumber (inc (rand-int 9999))]
(update world
(set-fields {:randomNumber (:randomNumber w)})
(where {:id [:id w]}))))
results))
(def json-serialization
"Test 1: JSON serialization"
(ring-resp/response {:message "Hello, World!"}))
(def single-query-test
"Test 2: Single database query"
(ring-resp/response (first (run-queries 1))))
(defn multiple-queries-test
"Test 3: Multiple database queries"
[queries]
(-> queries
(sanitize-queries-param)
(run-queries)
(ring-resp/response)
(ring-resp/content-type "application/json")))
(def fortune-test
"Test 4: Fortunes"
(->
(get-fortunes)
(fortunes-hiccup)
(ring-resp/response)
(ring-resp/content-type "text/html")))
(defn db-updates
"Test 5: Database updates"
[queries]
(-> queries
(update-and-persist)
(ring-resp/response)))
(def plaintext
"Test 6: Plaintext"
(->
(ring-resp/response "Hello, World!")
(ring-resp/content-type "text/plain")))
;; Define route handlers
(defroutes app-routes
(GET "/" [] "Hello, World!")
(GET "/json" [] json-serialization)
(GET "/db" [] single-query-test)
(GET "/queries/:queries" [queries] (multiple-queries-test queries))
(GET "/fortunes" [] fortune-test)
(GET "/updates/:queries" [queries] (db-updates queries))
(GET "/plaintext" [] plaintext)
(route/not-found "Not Found"))
(defn start-server [{:keys [port]}]
;; Format responses as JSON
(let [handler (wrap-json-response app-routes)
cpu (.availableProcessors (Runtime/getRuntime))]
;; double worker threads should increase database access performance
(run-server handler {:port port
:thread (* 2 cpu)})
(println (str "http-kit server listens at :" port))))
(defn -main [& args]
(let [[options _ banner]
(cli args
["-p" "--port" "Port to listen" :default 8080 :parse-fn parse-port]
["--[no-]help" "Print this help"])]
(when (:help options)
(println banner)
(System/exit 0))
(start-server options)))
| 80535 | (ns hello.handler
(:gen-class)
(:import com.mchange.v2.c3p0.ComboPooledDataSource)
(:use compojure.core
ring.middleware.json
org.httpkit.server
[clojure.tools.cli :only [cli]]
korma.db
korma.core
hiccup.core
hiccup.util
hiccup.page)
(:require [compojure.handler :as handler]
[compojure.route :as route]
[ring.util.response :as ring-resp]
[clojure.data.json :as json]
[clojure.java.jdbc :as jdbc]))
(defn parse-port [s]
"Convert stringy port number int. Defaults to 8080."
(cond
(string? s) (Integer/parseInt s)
(instance? Integer s) s
(instance? Long s) (.intValue ^Long s)
:else 8080))
;; MySQL connection
(defdb mysql-db
(mysql {
:classname "com.mysql.jdbc.Driver"
:subprotocol "mysql"
:subname "//127.0.0.1:3306/hello_world"
:user "benchmarkdbuser"
:password "<PASSWORD>"
;;OPTIONAL KEYS
:delimiters "" ;; remove delimiters
:maximum-pool-size 256}))
;; Set up entity World and the database representation
(defentity world
(pk :id)
(table :world)
(entity-fields :id :randomNumber) ;; Default fields for select
(database mysql-db))
(defn sanitize-queries-param
"Sanitizes the `queries` parameter. Caps the value between 1 and 500.
Invalid (stringy) values become 1"
[queries]
(let [n (try (Integer/parseInt queries)
(catch Exception e 1))] ; default to 1 on parse failure
(cond
(< n 1) 1
(> n 500) 500
:else n)))
(defn random-world
"Query a random World record from the database"
[]
(let [id (inc (rand-int 9999))] ; Num between 1 and 10,000
(select world
(where {:id id }))))
(defn run-queries
"Run query repeatedly -- Always returns an array"
[queries]
(flatten (take queries (repeatedly random-world))))
; Set up entity Fortune and the database representation
(defentity fortune
(pk :id)
(table :fortune)
(entity-fields :id :message)
(database mysql-db))
(defn get-all-fortunes
"Query all Fortune records from the database."
[]
(select fortune
(fields :id :message)))
(defn get-fortunes
"Fetch the full list of Fortunes from the database, sort them by the fortune
message text, and then return the results."
[]
(sort-by #(:message %)
(conj
(get-all-fortunes)
{ :id 0 :message "Additional fortune added at request time." })))
(defn fortunes-hiccup
"Render the given fortunes to simple HTML using Hiccup."
[fortunes]
(html5
[:head
[:title "Fortunes"]]
[:body
[:table
[:tr
[:th "id"]
[:th "message"]]
(for [x fortunes]
[:tr
[:td (:id x)]
[:td (escape-html (:message x))]])
]]))
(defn update-and-persist
"Changes the :randomNumber of a number of world entities.
Persists the changes to sql then returns the updated entities"
[queries]
(let [results (-> queries
(sanitize-queries-param)
(run-queries))]
(for [w results]
(update-in w [:randomNumber (inc (rand-int 9999))]
(update world
(set-fields {:randomNumber (:randomNumber w)})
(where {:id [:id w]}))))
results))
(def json-serialization
"Test 1: JSON serialization"
(ring-resp/response {:message "Hello, World!"}))
(def single-query-test
"Test 2: Single database query"
(ring-resp/response (first (run-queries 1))))
(defn multiple-queries-test
"Test 3: Multiple database queries"
[queries]
(-> queries
(sanitize-queries-param)
(run-queries)
(ring-resp/response)
(ring-resp/content-type "application/json")))
(def fortune-test
"Test 4: Fortunes"
(->
(get-fortunes)
(fortunes-hiccup)
(ring-resp/response)
(ring-resp/content-type "text/html")))
(defn db-updates
"Test 5: Database updates"
[queries]
(-> queries
(update-and-persist)
(ring-resp/response)))
(def plaintext
"Test 6: Plaintext"
(->
(ring-resp/response "Hello, World!")
(ring-resp/content-type "text/plain")))
;; Define route handlers
(defroutes app-routes
(GET "/" [] "Hello, World!")
(GET "/json" [] json-serialization)
(GET "/db" [] single-query-test)
(GET "/queries/:queries" [queries] (multiple-queries-test queries))
(GET "/fortunes" [] fortune-test)
(GET "/updates/:queries" [queries] (db-updates queries))
(GET "/plaintext" [] plaintext)
(route/not-found "Not Found"))
(defn start-server [{:keys [port]}]
;; Format responses as JSON
(let [handler (wrap-json-response app-routes)
cpu (.availableProcessors (Runtime/getRuntime))]
;; double worker threads should increase database access performance
(run-server handler {:port port
:thread (* 2 cpu)})
(println (str "http-kit server listens at :" port))))
(defn -main [& args]
(let [[options _ banner]
(cli args
["-p" "--port" "Port to listen" :default 8080 :parse-fn parse-port]
["--[no-]help" "Print this help"])]
(when (:help options)
(println banner)
(System/exit 0))
(start-server options)))
| true | (ns hello.handler
(:gen-class)
(:import com.mchange.v2.c3p0.ComboPooledDataSource)
(:use compojure.core
ring.middleware.json
org.httpkit.server
[clojure.tools.cli :only [cli]]
korma.db
korma.core
hiccup.core
hiccup.util
hiccup.page)
(:require [compojure.handler :as handler]
[compojure.route :as route]
[ring.util.response :as ring-resp]
[clojure.data.json :as json]
[clojure.java.jdbc :as jdbc]))
(defn parse-port [s]
"Convert stringy port number int. Defaults to 8080."
(cond
(string? s) (Integer/parseInt s)
(instance? Integer s) s
(instance? Long s) (.intValue ^Long s)
:else 8080))
;; MySQL connection
(defdb mysql-db
(mysql {
:classname "com.mysql.jdbc.Driver"
:subprotocol "mysql"
:subname "//127.0.0.1:3306/hello_world"
:user "benchmarkdbuser"
:password "PI:PASSWORD:<PASSWORD>END_PI"
;;OPTIONAL KEYS
:delimiters "" ;; remove delimiters
:maximum-pool-size 256}))
;; Set up entity World and the database representation
(defentity world
(pk :id)
(table :world)
(entity-fields :id :randomNumber) ;; Default fields for select
(database mysql-db))
(defn sanitize-queries-param
"Sanitizes the `queries` parameter. Caps the value between 1 and 500.
Invalid (stringy) values become 1"
[queries]
(let [n (try (Integer/parseInt queries)
(catch Exception e 1))] ; default to 1 on parse failure
(cond
(< n 1) 1
(> n 500) 500
:else n)))
(defn random-world
"Query a random World record from the database"
[]
(let [id (inc (rand-int 9999))] ; Num between 1 and 10,000
(select world
(where {:id id }))))
(defn run-queries
"Run query repeatedly -- Always returns an array"
[queries]
(flatten (take queries (repeatedly random-world))))
; Set up entity Fortune and the database representation
(defentity fortune
(pk :id)
(table :fortune)
(entity-fields :id :message)
(database mysql-db))
(defn get-all-fortunes
"Query all Fortune records from the database."
[]
(select fortune
(fields :id :message)))
(defn get-fortunes
"Fetch the full list of Fortunes from the database, sort them by the fortune
message text, and then return the results."
[]
(sort-by #(:message %)
(conj
(get-all-fortunes)
{ :id 0 :message "Additional fortune added at request time." })))
(defn fortunes-hiccup
"Render the given fortunes to simple HTML using Hiccup."
[fortunes]
(html5
[:head
[:title "Fortunes"]]
[:body
[:table
[:tr
[:th "id"]
[:th "message"]]
(for [x fortunes]
[:tr
[:td (:id x)]
[:td (escape-html (:message x))]])
]]))
(defn update-and-persist
"Changes the :randomNumber of a number of world entities.
Persists the changes to sql then returns the updated entities"
[queries]
(let [results (-> queries
(sanitize-queries-param)
(run-queries))]
(for [w results]
(update-in w [:randomNumber (inc (rand-int 9999))]
(update world
(set-fields {:randomNumber (:randomNumber w)})
(where {:id [:id w]}))))
results))
(def json-serialization
"Test 1: JSON serialization"
(ring-resp/response {:message "Hello, World!"}))
(def single-query-test
"Test 2: Single database query"
(ring-resp/response (first (run-queries 1))))
(defn multiple-queries-test
"Test 3: Multiple database queries"
[queries]
(-> queries
(sanitize-queries-param)
(run-queries)
(ring-resp/response)
(ring-resp/content-type "application/json")))
(def fortune-test
"Test 4: Fortunes"
(->
(get-fortunes)
(fortunes-hiccup)
(ring-resp/response)
(ring-resp/content-type "text/html")))
(defn db-updates
"Test 5: Database updates"
[queries]
(-> queries
(update-and-persist)
(ring-resp/response)))
(def plaintext
"Test 6: Plaintext"
(->
(ring-resp/response "Hello, World!")
(ring-resp/content-type "text/plain")))
;; Define route handlers
(defroutes app-routes
(GET "/" [] "Hello, World!")
(GET "/json" [] json-serialization)
(GET "/db" [] single-query-test)
(GET "/queries/:queries" [queries] (multiple-queries-test queries))
(GET "/fortunes" [] fortune-test)
(GET "/updates/:queries" [queries] (db-updates queries))
(GET "/plaintext" [] plaintext)
(route/not-found "Not Found"))
(defn start-server [{:keys [port]}]
;; Format responses as JSON
(let [handler (wrap-json-response app-routes)
cpu (.availableProcessors (Runtime/getRuntime))]
;; double worker threads should increase database access performance
(run-server handler {:port port
:thread (* 2 cpu)})
(println (str "http-kit server listens at :" port))))
(defn -main [& args]
(let [[options _ banner]
(cli args
["-p" "--port" "Port to listen" :default 8080 :parse-fn parse-port]
["--[no-]help" "Print this help"])]
(when (:help options)
(println banner)
(System/exit 0))
(start-server options)))
|
[
{
"context": "tom-positive '()}\n actual (sentiment \"Sgt Emile Cilliers charged over wife's parachute fall\")]\n (is (",
"end": 7364,
"score": 0.9219369888305664,
"start": 7350,
"tag": "NAME",
"value": "Emile Cilliers"
}
] | test/clj_subjectivity/core_test.clj | markwoodhall/clj-subjectivity | 1 | (ns clj-subjectivity.core-test
(:require [clojure.test :refer [deftest testing is]]
[clj-subjectivity.core :refer [sentiment]]))
(deftest sentiment-test
(testing "test sentiment with weak negative word as func returns correct result."
(let [expected {:difference -0.5
:negative 0.5
:neutral 0
:positive 0
:top-negative '("fire")
:top-neutral '()
:top-positive '()
:bottom-negative '("fire")
:bottom-neutral '()
:bottom-positive '()}
actual (sentiment (fn [] ["fire"]))]
(is (= expected actual))))
(testing "test sentiment with weak negative word returns correct result."
(let [expected {:difference -0.5
:negative 0.5
:neutral 0
:positive 0
:top-negative '("fire")
:top-neutral '()
:top-positive '()
:bottom-negative '("fire")
:bottom-neutral '()
:bottom-positive '()}
actual (sentiment ["fire"])]
(is (= expected actual))))
(testing "test sentiment with strong negative word returns correct result."
(let [expected {:difference -1
:negative 1
:neutral 0
:positive 0
:top-negative '("filthy")
:top-neutral '()
:top-positive '()
:bottom-negative '("filthy")
:bottom-neutral '()
:bottom-positive '()}
actual (sentiment ["filthy"])]
(is (= expected actual))))
(testing "test sentiment with weak positive word returns correct result."
(let [expected {:difference 0.5
:negative 0
:neutral 0
:positive 0.5
:top-negative '()
:top-neutral '()
:top-positive '("fine")
:bottom-negative '()
:bottom-neutral '()
:bottom-positive '("fine")}
actual (sentiment ["fine"])]
(is (= expected actual))))
(testing "test sentiment with strong positive word returns correct result."
(let [expected {:difference 1
:negative 0
:neutral 0
:positive 1
:top-negative '()
:top-neutral '()
:top-positive '("happy")
:bottom-negative '()
:bottom-neutral '()
:bottom-positive '("happy")}
actual (sentiment ["happy"])]
(is (= expected actual))))
(testing "test sentiment with positive word negated returns correct result."
(doseq [negation ["not" "never"]]
(let [expected {:difference -1
:negative 1
:neutral 0
:positive 0
:top-negative '("happy")
:top-neutral '()
:top-positive '()
:bottom-negative '("happy")
:bottom-neutral '()
:bottom-positive '()}
actual (sentiment [negation "happy"])]
(is (= expected actual) (str negation " should negate a positive word. e.g Not happy should reverse the positive sentiment of happy.")))))
(testing "test sentiment with positive word negated in chain of words returns correct result."
(doseq [negation ["not" "never"]]
(let [expected {:difference -2
:negative 2
:neutral 0
:positive 0
:top-negative '("happy" "sad")
:top-neutral '()
:top-positive '()
:bottom-negative '("sad" "happy")
:bottom-neutral '()
:bottom-positive '()}
actual (sentiment ["sad" negation "happy"])]
(is (= expected actual) (str negation " should negate a positive word. e.g Not happy should reverse the positive sentiment of happy.")))))
(testing "test sentiment with negative word negated has no effect and returns correct result."
(doseq [negation ["not" "never"]]
(let [expected {:difference -1
:negative 1
:neutral 0
:positive 0
:top-negative '("sad")
:top-neutral '()
:top-positive '()
:bottom-negative '("sad")
:bottom-neutral '()
:bottom-positive '()}
actual (sentiment [negation "sad"])]
(is (= expected actual) (str negation " should not have any effect on a word already considered to have negative sentiment.")))))
(testing "test sentiment with a collection of words."
(let [expected {:difference 0.0
:negative 1.5
:neutral 0
:positive 1.5
:top-negative '("filthy" "fire")
:top-neutral '()
:top-positive '("fine" "happy")
:bottom-negative '("fire" "filthy")
:bottom-neutral '()
:bottom-positive '("happy" "fine")}
actual (sentiment ["happy" "fire" "fine" "filthy"])]
(is (= expected actual))))
(testing "test sentiment with a sequence of positive words increments each sequential word by an additional .5."
(let [expected {:difference 3.5
:negative 0
:neutral 0
:positive 3.5
:top-negative '()
:top-neutral '()
:top-positive '("dreams" "happy" "love")
:bottom-negative '()
:bottom-neutral '()
:bottom-positive '("love" "happy" "dreams")}
actual (sentiment "Mark love happy dreams")]
(is (= expected actual))))
(testing "test sentiment with a sequence of negative words increments each sequential word by an additional .5."
(let [expected {:difference -4.0
:negative 4.0
:neutral 0
:positive 0
:top-negative '("hate" "fear" "anger")
:top-neutral '()
:top-positive '()
:bottom-negative '("anger" "fear" "hate")
:bottom-neutral '()
:bottom-positive '()}
actual (sentiment "anger fear hate")]
(is (= expected actual))))
(testing "test sentiment with a sentence."
(let [expected {:difference -0.5
:negative 0.5
:neutral 0
:positive 0
:top-negative '("fall")
:top-neutral '()
:top-positive '()
:bottom-negative '("fall")
:bottom-neutral '()
:bottom-positive '()}
actual (sentiment "Sgt Emile Cilliers charged over wife's parachute fall")]
(is (= expected actual)))))
| 5855 | (ns clj-subjectivity.core-test
(:require [clojure.test :refer [deftest testing is]]
[clj-subjectivity.core :refer [sentiment]]))
(deftest sentiment-test
(testing "test sentiment with weak negative word as func returns correct result."
(let [expected {:difference -0.5
:negative 0.5
:neutral 0
:positive 0
:top-negative '("fire")
:top-neutral '()
:top-positive '()
:bottom-negative '("fire")
:bottom-neutral '()
:bottom-positive '()}
actual (sentiment (fn [] ["fire"]))]
(is (= expected actual))))
(testing "test sentiment with weak negative word returns correct result."
(let [expected {:difference -0.5
:negative 0.5
:neutral 0
:positive 0
:top-negative '("fire")
:top-neutral '()
:top-positive '()
:bottom-negative '("fire")
:bottom-neutral '()
:bottom-positive '()}
actual (sentiment ["fire"])]
(is (= expected actual))))
(testing "test sentiment with strong negative word returns correct result."
(let [expected {:difference -1
:negative 1
:neutral 0
:positive 0
:top-negative '("filthy")
:top-neutral '()
:top-positive '()
:bottom-negative '("filthy")
:bottom-neutral '()
:bottom-positive '()}
actual (sentiment ["filthy"])]
(is (= expected actual))))
(testing "test sentiment with weak positive word returns correct result."
(let [expected {:difference 0.5
:negative 0
:neutral 0
:positive 0.5
:top-negative '()
:top-neutral '()
:top-positive '("fine")
:bottom-negative '()
:bottom-neutral '()
:bottom-positive '("fine")}
actual (sentiment ["fine"])]
(is (= expected actual))))
(testing "test sentiment with strong positive word returns correct result."
(let [expected {:difference 1
:negative 0
:neutral 0
:positive 1
:top-negative '()
:top-neutral '()
:top-positive '("happy")
:bottom-negative '()
:bottom-neutral '()
:bottom-positive '("happy")}
actual (sentiment ["happy"])]
(is (= expected actual))))
(testing "test sentiment with positive word negated returns correct result."
(doseq [negation ["not" "never"]]
(let [expected {:difference -1
:negative 1
:neutral 0
:positive 0
:top-negative '("happy")
:top-neutral '()
:top-positive '()
:bottom-negative '("happy")
:bottom-neutral '()
:bottom-positive '()}
actual (sentiment [negation "happy"])]
(is (= expected actual) (str negation " should negate a positive word. e.g Not happy should reverse the positive sentiment of happy.")))))
(testing "test sentiment with positive word negated in chain of words returns correct result."
(doseq [negation ["not" "never"]]
(let [expected {:difference -2
:negative 2
:neutral 0
:positive 0
:top-negative '("happy" "sad")
:top-neutral '()
:top-positive '()
:bottom-negative '("sad" "happy")
:bottom-neutral '()
:bottom-positive '()}
actual (sentiment ["sad" negation "happy"])]
(is (= expected actual) (str negation " should negate a positive word. e.g Not happy should reverse the positive sentiment of happy.")))))
(testing "test sentiment with negative word negated has no effect and returns correct result."
(doseq [negation ["not" "never"]]
(let [expected {:difference -1
:negative 1
:neutral 0
:positive 0
:top-negative '("sad")
:top-neutral '()
:top-positive '()
:bottom-negative '("sad")
:bottom-neutral '()
:bottom-positive '()}
actual (sentiment [negation "sad"])]
(is (= expected actual) (str negation " should not have any effect on a word already considered to have negative sentiment.")))))
(testing "test sentiment with a collection of words."
(let [expected {:difference 0.0
:negative 1.5
:neutral 0
:positive 1.5
:top-negative '("filthy" "fire")
:top-neutral '()
:top-positive '("fine" "happy")
:bottom-negative '("fire" "filthy")
:bottom-neutral '()
:bottom-positive '("happy" "fine")}
actual (sentiment ["happy" "fire" "fine" "filthy"])]
(is (= expected actual))))
(testing "test sentiment with a sequence of positive words increments each sequential word by an additional .5."
(let [expected {:difference 3.5
:negative 0
:neutral 0
:positive 3.5
:top-negative '()
:top-neutral '()
:top-positive '("dreams" "happy" "love")
:bottom-negative '()
:bottom-neutral '()
:bottom-positive '("love" "happy" "dreams")}
actual (sentiment "Mark love happy dreams")]
(is (= expected actual))))
(testing "test sentiment with a sequence of negative words increments each sequential word by an additional .5."
(let [expected {:difference -4.0
:negative 4.0
:neutral 0
:positive 0
:top-negative '("hate" "fear" "anger")
:top-neutral '()
:top-positive '()
:bottom-negative '("anger" "fear" "hate")
:bottom-neutral '()
:bottom-positive '()}
actual (sentiment "anger fear hate")]
(is (= expected actual))))
(testing "test sentiment with a sentence."
(let [expected {:difference -0.5
:negative 0.5
:neutral 0
:positive 0
:top-negative '("fall")
:top-neutral '()
:top-positive '()
:bottom-negative '("fall")
:bottom-neutral '()
:bottom-positive '()}
actual (sentiment "Sgt <NAME> charged over wife's parachute fall")]
(is (= expected actual)))))
| true | (ns clj-subjectivity.core-test
(:require [clojure.test :refer [deftest testing is]]
[clj-subjectivity.core :refer [sentiment]]))
(deftest sentiment-test
(testing "test sentiment with weak negative word as func returns correct result."
(let [expected {:difference -0.5
:negative 0.5
:neutral 0
:positive 0
:top-negative '("fire")
:top-neutral '()
:top-positive '()
:bottom-negative '("fire")
:bottom-neutral '()
:bottom-positive '()}
actual (sentiment (fn [] ["fire"]))]
(is (= expected actual))))
(testing "test sentiment with weak negative word returns correct result."
(let [expected {:difference -0.5
:negative 0.5
:neutral 0
:positive 0
:top-negative '("fire")
:top-neutral '()
:top-positive '()
:bottom-negative '("fire")
:bottom-neutral '()
:bottom-positive '()}
actual (sentiment ["fire"])]
(is (= expected actual))))
(testing "test sentiment with strong negative word returns correct result."
(let [expected {:difference -1
:negative 1
:neutral 0
:positive 0
:top-negative '("filthy")
:top-neutral '()
:top-positive '()
:bottom-negative '("filthy")
:bottom-neutral '()
:bottom-positive '()}
actual (sentiment ["filthy"])]
(is (= expected actual))))
(testing "test sentiment with weak positive word returns correct result."
(let [expected {:difference 0.5
:negative 0
:neutral 0
:positive 0.5
:top-negative '()
:top-neutral '()
:top-positive '("fine")
:bottom-negative '()
:bottom-neutral '()
:bottom-positive '("fine")}
actual (sentiment ["fine"])]
(is (= expected actual))))
(testing "test sentiment with strong positive word returns correct result."
(let [expected {:difference 1
:negative 0
:neutral 0
:positive 1
:top-negative '()
:top-neutral '()
:top-positive '("happy")
:bottom-negative '()
:bottom-neutral '()
:bottom-positive '("happy")}
actual (sentiment ["happy"])]
(is (= expected actual))))
(testing "test sentiment with positive word negated returns correct result."
(doseq [negation ["not" "never"]]
(let [expected {:difference -1
:negative 1
:neutral 0
:positive 0
:top-negative '("happy")
:top-neutral '()
:top-positive '()
:bottom-negative '("happy")
:bottom-neutral '()
:bottom-positive '()}
actual (sentiment [negation "happy"])]
(is (= expected actual) (str negation " should negate a positive word. e.g Not happy should reverse the positive sentiment of happy.")))))
(testing "test sentiment with positive word negated in chain of words returns correct result."
(doseq [negation ["not" "never"]]
(let [expected {:difference -2
:negative 2
:neutral 0
:positive 0
:top-negative '("happy" "sad")
:top-neutral '()
:top-positive '()
:bottom-negative '("sad" "happy")
:bottom-neutral '()
:bottom-positive '()}
actual (sentiment ["sad" negation "happy"])]
(is (= expected actual) (str negation " should negate a positive word. e.g Not happy should reverse the positive sentiment of happy.")))))
(testing "test sentiment with negative word negated has no effect and returns correct result."
(doseq [negation ["not" "never"]]
(let [expected {:difference -1
:negative 1
:neutral 0
:positive 0
:top-negative '("sad")
:top-neutral '()
:top-positive '()
:bottom-negative '("sad")
:bottom-neutral '()
:bottom-positive '()}
actual (sentiment [negation "sad"])]
(is (= expected actual) (str negation " should not have any effect on a word already considered to have negative sentiment.")))))
(testing "test sentiment with a collection of words."
(let [expected {:difference 0.0
:negative 1.5
:neutral 0
:positive 1.5
:top-negative '("filthy" "fire")
:top-neutral '()
:top-positive '("fine" "happy")
:bottom-negative '("fire" "filthy")
:bottom-neutral '()
:bottom-positive '("happy" "fine")}
actual (sentiment ["happy" "fire" "fine" "filthy"])]
(is (= expected actual))))
(testing "test sentiment with a sequence of positive words increments each sequential word by an additional .5."
(let [expected {:difference 3.5
:negative 0
:neutral 0
:positive 3.5
:top-negative '()
:top-neutral '()
:top-positive '("dreams" "happy" "love")
:bottom-negative '()
:bottom-neutral '()
:bottom-positive '("love" "happy" "dreams")}
actual (sentiment "Mark love happy dreams")]
(is (= expected actual))))
(testing "test sentiment with a sequence of negative words increments each sequential word by an additional .5."
(let [expected {:difference -4.0
:negative 4.0
:neutral 0
:positive 0
:top-negative '("hate" "fear" "anger")
:top-neutral '()
:top-positive '()
:bottom-negative '("anger" "fear" "hate")
:bottom-neutral '()
:bottom-positive '()}
actual (sentiment "anger fear hate")]
(is (= expected actual))))
(testing "test sentiment with a sentence."
(let [expected {:difference -0.5
:negative 0.5
:neutral 0
:positive 0
:top-negative '("fall")
:top-neutral '()
:top-positive '()
:bottom-negative '("fall")
:bottom-neutral '()
:bottom-positive '()}
actual (sentiment "Sgt PI:NAME:<NAME>END_PI charged over wife's parachute fall")]
(is (= expected actual)))))
|
[
{
"context": " is structured\n;; according to the form defined by Scott Peckham. This is: <object>_<quantity>.\n(defrecord Measure",
"end": 10675,
"score": 0.9997907876968384,
"start": 10662,
"tag": "NAME",
"value": "Scott Peckham"
}
] | umm-spec-lib/src/cmr/umm_spec/models/umm_variable_models.clj | cgokey/Common-Metadata-Repository | 0 | ;; WARNING: This file was generated from umm-var-json-schema.json. Do not manually modify.
(ns cmr.umm-spec.models.umm-variable-models
"Defines UMM-Var clojure records."
(:require [cmr.common.dev.record-pretty-printer :as record-pretty-printer]))
(defrecord UMM-Var
[
;; Valid ranges of variable data values.
ValidRanges
;; A variable consists of one or more dimensions. An example of a dimension name is 'XDim'. An
;; example of a dimension size is '1200'. Variables are rarely one dimensional.
Dimensions
;; Any additional identifiers of a variable.
AdditionalIdentifiers
;; The scale is the numerical factor by which all values in the stored data field are multiplied
;; in order to obtain the original values. May be used together with Offset. An example of a
;; scale factor is '0.002'
Scale
;; This element describes the x and y dimension ranges for this variable. Typically these values
;; are 2 latitude and longitude ranges, but they don't necessarily have to be.
IndexRanges
;; The offset is the value which is either added to or subtracted from all values in the stored
;; data field in order to obtain the original values. May be used together with Scale. An example
;; of an offset is '0.49'.
Offset
;; The set information of a variable. The variable is grouped within a set. The set is defined by
;; the name, type, size and index. For example, Name: 'Data_Fields', Type: 'General', Size: '15',
;; Index: '7' for the case of the variable named 'LST_Day_1km'.
Sets
;; The units associated with a variable.
Units
;; The sampling information of a variable.
SamplingIdentifiers
;; The fill value of the variable in the data file. It is generally a value which falls outside
;; the valid range. For example, if the valid range is '0, 360', the fill value may be '-1'. The
;; fill value type is data provider-defined. For example, 'Out of Valid Range'.
FillValues
;; The definition of the variable.
Definition
;; Controlled Science Keywords describing the measurements/variables. The controlled vocabulary
;; for Science Keywords is maintained in the Keyword Management System (KMS).
ScienceKeywords
;; The name of a variable.
Name
;; Specify basic type of a variable.
VariableType
;; A described URL associated with the a web resource, or interface. e.g., the home page for the
;; variable provider.
RelatedURLs
;; Specifies the sub type of a variable.
VariableSubType
;; The measurement information of a variable.
MeasurementIdentifiers
;; The expanded or long name related to the variable Name.
LongName
;; Requires the client, or user, to add in schema information into every variable record. It
;; includes the schema's name, version, and URL location. The information is controlled through
;; enumerations at the end of this schema.
MetadataSpecification
;; This is the more formal or scientific name, .e.g., the CF Standard Name.
StandardName
;; Specify data type of a variable. These types can be either: uint8, uint16, etc.
DataType
])
(record-pretty-printer/enable-record-pretty-printing UMM-Var)
;; The elements of this section apply to an additional identifier.
(defrecord AdditionalIdentifierType
[
;; The actual identifier.
Identifier
;; This element describes to a person or machine what the identifier is called. e.g., if the
;; identifier is 1057.2345/asfb then the Description should be DOI or Digital Object Identifier.
Description
])
(record-pretty-printer/enable-record-pretty-printing AdditionalIdentifierType)
;; The fill value, fill value type and fill value description of the variable in the data file. The
;; fill value is generally a value which falls outside the valid range. For example, if the valid
;; range is '0, 360', the fill value may be '-1'. The elements of this section apply to the fill
;; value of a variable.
(defrecord FillValueType
[
;; The fill value of the variable in the data file.
Value
;; Type of the fill value of the variable in the data file.
Type
;; Description of the fill value of the variable in the data file.
Description
])
(record-pretty-printer/enable-record-pretty-printing FillValueType)
;; This object requires any metadata record that is validated by this schema to provide information
;; about the schema.
(defrecord MetadataSpecificationType
[
;; This element represents the URL where the schema lives. The schema can be downloaded.
URL
;; This element represents the name of the schema.
Name
;; This element represents the version of the schema.
Version
])
(record-pretty-printer/enable-record-pretty-printing MetadataSpecificationType)
;; The elements of this section apply to a measurement.
(defrecord SamplingIdentifierType
[
;; The name of the sampling method used for the measurement. For example, 'radiometric detection
;; within the visible and infra-red ranges of the electromagnetic spectrum.
SamplingMethod
;; The measurement conditions of the variable. For example, 'Sampled Particle Size Range: 90 -
;; 600 nm'.
MeasurementConditions
;; The reporting conditions of the variable. The conditions over which the measurements of the
;; variable are valid. For example, 'STP: 1013 mb and 273 K'.
ReportingConditions
])
(record-pretty-printer/enable-record-pretty-printing SamplingIdentifierType)
;; Enables specification of Earth science keywords related to the collection. The Earth Science
;; keywords are chosen from a controlled keyword hierarchy maintained in the Keyword Management
;; System (KMS). The valid values can be found at the KMS website:
;; https://gcmdservices.gsfc.nasa.gov/kms/concepts/concept_scheme/sciencekeywords?format=csv.
(defrecord ScienceKeywordType
[
Category
Topic
Term
VariableLevel1
VariableLevel2
VariableLevel3
DetailedVariable
])
(record-pretty-printer/enable-record-pretty-printing ScienceKeywordType)
;; Valid range data value of a variable: minimum and maximum values. For example, '-100, 5000'.
(defrecord ValidRangeType
[
;; Minimum data value of a variable. For example, '-100'.
Min
;; Maximum data value of a variable. For example, '5000'.
Max
;; This element can be used to specify a code system identifier meaning. For example, 'Open
;; Shrubland' corresponds to '7'.
CodeSystemIdentifierMeaning
;; The code system identifier value is the textual or numerical value assigned to each meaning.
CodeSystemIdentifierValue
])
(record-pretty-printer/enable-record-pretty-printing ValidRangeType)
;; Represents Internet sites that contain information related to the data, as well as related
;; Internet sites such as project home pages, variable colormaps, metadata extensions, etc.
(defrecord RelatedURLType
[
;; Description of the web resource at this URL.
Description
;; A keyword describing the distinct content type of the online resource to this resource. (e.g.,
;; 'DATACENTER URL', 'DATA CONTACT URL', 'Visualization URL'). The valid values are contained in
;; the KMS System:
;; https://gcmd.earthdata.nasa.gov/KeywordViewer/scheme/all/8759ab63-ac04-4136-bc25-0c00eece1096
URLContentType
;; A keyword describing the type of the online resource to this resource. This helps the GUI to
;; know what to do with this resource. (e.g., 'COLORMAP', 'GET VISUALIZATION'). The valid values
;; are contained in the KMS System and are dependent on the URLContentType:
;; https://gcmd.earthdata.nasa.gov/KeywordViewer/scheme/all/8759ab63-ac04-4136-bc25-0c00eece1096
Type
;; A keyword describing the subtype of the online resource to this resource. This further helps
;; the GUI to know what to do with this resource. (e.g., 'MEDIA', 'BROWSE', 'OPENDAP',
;; 'OPENSEARCH', 'GITC', etc. ). The valid values are contained in the KMS System and are
;; dependent on the Type:
;; https://gcmd.earthdata.nasa.gov/KeywordViewer/scheme/all/8759ab63-ac04-4136-bc25-0c00eece1096
Subtype
;; The URL for the relevant web page (e.g., the URL of the responsible organization's home page,
;; the URL of the colormap server, etc.).
URL
;; The format of the data. The controlled vocabulary for formats is maintained in the Keyword
;; Management System (KMS)
Format
;; The mime type of the resource.
MimeType
])
(record-pretty-printer/enable-record-pretty-printing RelatedURLType)
;; The elements of this section allow authors to provide community sourced words or phrases to
;; further describe the variable data.
(defrecord MeasurementIdentifierType
[
;; This element describes the context/medium within which the measurement was made.
MeasurementContextMedium
;; This element contains the URI for the context/medium.
MeasurementContextMediumURI
;; This element describes the object which was measured.
MeasurementObject
;; This element contains the URI for the object which was measured.
MeasurementObjectURI
;; This element contains the quantity or quantities which was/were measured.
MeasurementQuantities
])
(record-pretty-printer/enable-record-pretty-printing MeasurementIdentifierType)
;; A variable consists of one or more dimensions. An example of a dimension name is 'XDim'. An
;; example of a dimension size is '1200'. Variables are rarely one dimensional.
(defrecord DimensionType
[
;; The name of the dimension of the variable represented in the data field. For example, 'XDim.
Name
;; The size of the dimension of the variable represented in the data field. For example, '1200'.
Size
;; The type of the dimension of the variable represented in the data field. For example, if the
;; dimension has a special meaning, i.e., a latitude, longitude, pressure, height (or depth) or
;; time, then the type should be set to either 'LATITUDE_DIMENSION', 'LONGITUDE_DIMENSION',
;; 'PRESSURE_DIMENSION', 'HEIGHT_DIMENSION', 'DEPTH_DIMENSION' or 'TIME_DIMENSION', otherwise it
;; should be set to 'OTHER'.
Type
])
(record-pretty-printer/enable-record-pretty-printing DimensionType)
;; The index ranges consist of a LatRange and a LonRange.
(defrecord IndexRangesType
[
;; The LatRange consists of an index range for latitude.
LatRange
;; The LonRange consists of an index range for longitude.
LonRange
])
(record-pretty-printer/enable-record-pretty-printing IndexRangesType)
;; The elements of this section apply to a measurement name. The measurement name is structured
;; according to the form defined by Scott Peckham. This is: <object>_<quantity>.
(defrecord MeasurementQuantityType
[
;; This element describes the value for the quantity which was measured.
Value
;; This element contains the URI for the quantity which was measured.
MeasurementQuantityURI
])
(record-pretty-printer/enable-record-pretty-printing MeasurementQuantityType)
;; The elements of this section apply to variable sets.
(defrecord SetType
[
;; This element enables specification of set name. For example, 'Data_Fields'.
Name
;; This element enables specification of set type. For example, if the variables have been
;; grouped together based on a particular theme, such as wavelength, then the type should be set
;; to that theme, otherwise it should be set to 'General'.
Type
;; This element specifies the number of variables in the set. For example, if the number of
;; variables in the set is fifteen, the size should be set to '15'.
Size
;; This element specifies the index value within the set for this variable, For example, if this
;; varible is the third variable in the set, the index value should be set to '3'.
Index
])
(record-pretty-printer/enable-record-pretty-printing SetType) | 18917 | ;; WARNING: This file was generated from umm-var-json-schema.json. Do not manually modify.
(ns cmr.umm-spec.models.umm-variable-models
"Defines UMM-Var clojure records."
(:require [cmr.common.dev.record-pretty-printer :as record-pretty-printer]))
(defrecord UMM-Var
[
;; Valid ranges of variable data values.
ValidRanges
;; A variable consists of one or more dimensions. An example of a dimension name is 'XDim'. An
;; example of a dimension size is '1200'. Variables are rarely one dimensional.
Dimensions
;; Any additional identifiers of a variable.
AdditionalIdentifiers
;; The scale is the numerical factor by which all values in the stored data field are multiplied
;; in order to obtain the original values. May be used together with Offset. An example of a
;; scale factor is '0.002'
Scale
;; This element describes the x and y dimension ranges for this variable. Typically these values
;; are 2 latitude and longitude ranges, but they don't necessarily have to be.
IndexRanges
;; The offset is the value which is either added to or subtracted from all values in the stored
;; data field in order to obtain the original values. May be used together with Scale. An example
;; of an offset is '0.49'.
Offset
;; The set information of a variable. The variable is grouped within a set. The set is defined by
;; the name, type, size and index. For example, Name: 'Data_Fields', Type: 'General', Size: '15',
;; Index: '7' for the case of the variable named 'LST_Day_1km'.
Sets
;; The units associated with a variable.
Units
;; The sampling information of a variable.
SamplingIdentifiers
;; The fill value of the variable in the data file. It is generally a value which falls outside
;; the valid range. For example, if the valid range is '0, 360', the fill value may be '-1'. The
;; fill value type is data provider-defined. For example, 'Out of Valid Range'.
FillValues
;; The definition of the variable.
Definition
;; Controlled Science Keywords describing the measurements/variables. The controlled vocabulary
;; for Science Keywords is maintained in the Keyword Management System (KMS).
ScienceKeywords
;; The name of a variable.
Name
;; Specify basic type of a variable.
VariableType
;; A described URL associated with the a web resource, or interface. e.g., the home page for the
;; variable provider.
RelatedURLs
;; Specifies the sub type of a variable.
VariableSubType
;; The measurement information of a variable.
MeasurementIdentifiers
;; The expanded or long name related to the variable Name.
LongName
;; Requires the client, or user, to add in schema information into every variable record. It
;; includes the schema's name, version, and URL location. The information is controlled through
;; enumerations at the end of this schema.
MetadataSpecification
;; This is the more formal or scientific name, .e.g., the CF Standard Name.
StandardName
;; Specify data type of a variable. These types can be either: uint8, uint16, etc.
DataType
])
(record-pretty-printer/enable-record-pretty-printing UMM-Var)
;; The elements of this section apply to an additional identifier.
(defrecord AdditionalIdentifierType
[
;; The actual identifier.
Identifier
;; This element describes to a person or machine what the identifier is called. e.g., if the
;; identifier is 1057.2345/asfb then the Description should be DOI or Digital Object Identifier.
Description
])
(record-pretty-printer/enable-record-pretty-printing AdditionalIdentifierType)
;; The fill value, fill value type and fill value description of the variable in the data file. The
;; fill value is generally a value which falls outside the valid range. For example, if the valid
;; range is '0, 360', the fill value may be '-1'. The elements of this section apply to the fill
;; value of a variable.
(defrecord FillValueType
[
;; The fill value of the variable in the data file.
Value
;; Type of the fill value of the variable in the data file.
Type
;; Description of the fill value of the variable in the data file.
Description
])
(record-pretty-printer/enable-record-pretty-printing FillValueType)
;; This object requires any metadata record that is validated by this schema to provide information
;; about the schema.
(defrecord MetadataSpecificationType
[
;; This element represents the URL where the schema lives. The schema can be downloaded.
URL
;; This element represents the name of the schema.
Name
;; This element represents the version of the schema.
Version
])
(record-pretty-printer/enable-record-pretty-printing MetadataSpecificationType)
;; The elements of this section apply to a measurement.
(defrecord SamplingIdentifierType
[
;; The name of the sampling method used for the measurement. For example, 'radiometric detection
;; within the visible and infra-red ranges of the electromagnetic spectrum.
SamplingMethod
;; The measurement conditions of the variable. For example, 'Sampled Particle Size Range: 90 -
;; 600 nm'.
MeasurementConditions
;; The reporting conditions of the variable. The conditions over which the measurements of the
;; variable are valid. For example, 'STP: 1013 mb and 273 K'.
ReportingConditions
])
(record-pretty-printer/enable-record-pretty-printing SamplingIdentifierType)
;; Enables specification of Earth science keywords related to the collection. The Earth Science
;; keywords are chosen from a controlled keyword hierarchy maintained in the Keyword Management
;; System (KMS). The valid values can be found at the KMS website:
;; https://gcmdservices.gsfc.nasa.gov/kms/concepts/concept_scheme/sciencekeywords?format=csv.
(defrecord ScienceKeywordType
[
Category
Topic
Term
VariableLevel1
VariableLevel2
VariableLevel3
DetailedVariable
])
(record-pretty-printer/enable-record-pretty-printing ScienceKeywordType)
;; Valid range data value of a variable: minimum and maximum values. For example, '-100, 5000'.
(defrecord ValidRangeType
[
;; Minimum data value of a variable. For example, '-100'.
Min
;; Maximum data value of a variable. For example, '5000'.
Max
;; This element can be used to specify a code system identifier meaning. For example, 'Open
;; Shrubland' corresponds to '7'.
CodeSystemIdentifierMeaning
;; The code system identifier value is the textual or numerical value assigned to each meaning.
CodeSystemIdentifierValue
])
(record-pretty-printer/enable-record-pretty-printing ValidRangeType)
;; Represents Internet sites that contain information related to the data, as well as related
;; Internet sites such as project home pages, variable colormaps, metadata extensions, etc.
(defrecord RelatedURLType
[
;; Description of the web resource at this URL.
Description
;; A keyword describing the distinct content type of the online resource to this resource. (e.g.,
;; 'DATACENTER URL', 'DATA CONTACT URL', 'Visualization URL'). The valid values are contained in
;; the KMS System:
;; https://gcmd.earthdata.nasa.gov/KeywordViewer/scheme/all/8759ab63-ac04-4136-bc25-0c00eece1096
URLContentType
;; A keyword describing the type of the online resource to this resource. This helps the GUI to
;; know what to do with this resource. (e.g., 'COLORMAP', 'GET VISUALIZATION'). The valid values
;; are contained in the KMS System and are dependent on the URLContentType:
;; https://gcmd.earthdata.nasa.gov/KeywordViewer/scheme/all/8759ab63-ac04-4136-bc25-0c00eece1096
Type
;; A keyword describing the subtype of the online resource to this resource. This further helps
;; the GUI to know what to do with this resource. (e.g., 'MEDIA', 'BROWSE', 'OPENDAP',
;; 'OPENSEARCH', 'GITC', etc. ). The valid values are contained in the KMS System and are
;; dependent on the Type:
;; https://gcmd.earthdata.nasa.gov/KeywordViewer/scheme/all/8759ab63-ac04-4136-bc25-0c00eece1096
Subtype
;; The URL for the relevant web page (e.g., the URL of the responsible organization's home page,
;; the URL of the colormap server, etc.).
URL
;; The format of the data. The controlled vocabulary for formats is maintained in the Keyword
;; Management System (KMS)
Format
;; The mime type of the resource.
MimeType
])
(record-pretty-printer/enable-record-pretty-printing RelatedURLType)
;; The elements of this section allow authors to provide community sourced words or phrases to
;; further describe the variable data.
(defrecord MeasurementIdentifierType
[
;; This element describes the context/medium within which the measurement was made.
MeasurementContextMedium
;; This element contains the URI for the context/medium.
MeasurementContextMediumURI
;; This element describes the object which was measured.
MeasurementObject
;; This element contains the URI for the object which was measured.
MeasurementObjectURI
;; This element contains the quantity or quantities which was/were measured.
MeasurementQuantities
])
(record-pretty-printer/enable-record-pretty-printing MeasurementIdentifierType)
;; A variable consists of one or more dimensions. An example of a dimension name is 'XDim'. An
;; example of a dimension size is '1200'. Variables are rarely one dimensional.
(defrecord DimensionType
[
;; The name of the dimension of the variable represented in the data field. For example, 'XDim.
Name
;; The size of the dimension of the variable represented in the data field. For example, '1200'.
Size
;; The type of the dimension of the variable represented in the data field. For example, if the
;; dimension has a special meaning, i.e., a latitude, longitude, pressure, height (or depth) or
;; time, then the type should be set to either 'LATITUDE_DIMENSION', 'LONGITUDE_DIMENSION',
;; 'PRESSURE_DIMENSION', 'HEIGHT_DIMENSION', 'DEPTH_DIMENSION' or 'TIME_DIMENSION', otherwise it
;; should be set to 'OTHER'.
Type
])
(record-pretty-printer/enable-record-pretty-printing DimensionType)
;; The index ranges consist of a LatRange and a LonRange.
(defrecord IndexRangesType
[
;; The LatRange consists of an index range for latitude.
LatRange
;; The LonRange consists of an index range for longitude.
LonRange
])
(record-pretty-printer/enable-record-pretty-printing IndexRangesType)
;; The elements of this section apply to a measurement name. The measurement name is structured
;; according to the form defined by <NAME>. This is: <object>_<quantity>.
(defrecord MeasurementQuantityType
[
;; This element describes the value for the quantity which was measured.
Value
;; This element contains the URI for the quantity which was measured.
MeasurementQuantityURI
])
(record-pretty-printer/enable-record-pretty-printing MeasurementQuantityType)
;; The elements of this section apply to variable sets.
(defrecord SetType
[
;; This element enables specification of set name. For example, 'Data_Fields'.
Name
;; This element enables specification of set type. For example, if the variables have been
;; grouped together based on a particular theme, such as wavelength, then the type should be set
;; to that theme, otherwise it should be set to 'General'.
Type
;; This element specifies the number of variables in the set. For example, if the number of
;; variables in the set is fifteen, the size should be set to '15'.
Size
;; This element specifies the index value within the set for this variable, For example, if this
;; varible is the third variable in the set, the index value should be set to '3'.
Index
])
(record-pretty-printer/enable-record-pretty-printing SetType) | true | ;; WARNING: This file was generated from umm-var-json-schema.json. Do not manually modify.
(ns cmr.umm-spec.models.umm-variable-models
"Defines UMM-Var clojure records."
(:require [cmr.common.dev.record-pretty-printer :as record-pretty-printer]))
(defrecord UMM-Var
[
;; Valid ranges of variable data values.
ValidRanges
;; A variable consists of one or more dimensions. An example of a dimension name is 'XDim'. An
;; example of a dimension size is '1200'. Variables are rarely one dimensional.
Dimensions
;; Any additional identifiers of a variable.
AdditionalIdentifiers
;; The scale is the numerical factor by which all values in the stored data field are multiplied
;; in order to obtain the original values. May be used together with Offset. An example of a
;; scale factor is '0.002'
Scale
;; This element describes the x and y dimension ranges for this variable. Typically these values
;; are 2 latitude and longitude ranges, but they don't necessarily have to be.
IndexRanges
;; The offset is the value which is either added to or subtracted from all values in the stored
;; data field in order to obtain the original values. May be used together with Scale. An example
;; of an offset is '0.49'.
Offset
;; The set information of a variable. The variable is grouped within a set. The set is defined by
;; the name, type, size and index. For example, Name: 'Data_Fields', Type: 'General', Size: '15',
;; Index: '7' for the case of the variable named 'LST_Day_1km'.
Sets
;; The units associated with a variable.
Units
;; The sampling information of a variable.
SamplingIdentifiers
;; The fill value of the variable in the data file. It is generally a value which falls outside
;; the valid range. For example, if the valid range is '0, 360', the fill value may be '-1'. The
;; fill value type is data provider-defined. For example, 'Out of Valid Range'.
FillValues
;; The definition of the variable.
Definition
;; Controlled Science Keywords describing the measurements/variables. The controlled vocabulary
;; for Science Keywords is maintained in the Keyword Management System (KMS).
ScienceKeywords
;; The name of a variable.
Name
;; Specify basic type of a variable.
VariableType
;; A described URL associated with the a web resource, or interface. e.g., the home page for the
;; variable provider.
RelatedURLs
;; Specifies the sub type of a variable.
VariableSubType
;; The measurement information of a variable.
MeasurementIdentifiers
;; The expanded or long name related to the variable Name.
LongName
;; Requires the client, or user, to add in schema information into every variable record. It
;; includes the schema's name, version, and URL location. The information is controlled through
;; enumerations at the end of this schema.
MetadataSpecification
;; This is the more formal or scientific name, .e.g., the CF Standard Name.
StandardName
;; Specify data type of a variable. These types can be either: uint8, uint16, etc.
DataType
])
(record-pretty-printer/enable-record-pretty-printing UMM-Var)
;; The elements of this section apply to an additional identifier.
(defrecord AdditionalIdentifierType
[
;; The actual identifier.
Identifier
;; This element describes to a person or machine what the identifier is called. e.g., if the
;; identifier is 1057.2345/asfb then the Description should be DOI or Digital Object Identifier.
Description
])
(record-pretty-printer/enable-record-pretty-printing AdditionalIdentifierType)
;; The fill value, fill value type and fill value description of the variable in the data file. The
;; fill value is generally a value which falls outside the valid range. For example, if the valid
;; range is '0, 360', the fill value may be '-1'. The elements of this section apply to the fill
;; value of a variable.
(defrecord FillValueType
[
;; The fill value of the variable in the data file.
Value
;; Type of the fill value of the variable in the data file.
Type
;; Description of the fill value of the variable in the data file.
Description
])
(record-pretty-printer/enable-record-pretty-printing FillValueType)
;; This object requires any metadata record that is validated by this schema to provide information
;; about the schema.
(defrecord MetadataSpecificationType
[
;; This element represents the URL where the schema lives. The schema can be downloaded.
URL
;; This element represents the name of the schema.
Name
;; This element represents the version of the schema.
Version
])
(record-pretty-printer/enable-record-pretty-printing MetadataSpecificationType)
;; The elements of this section apply to a measurement.
(defrecord SamplingIdentifierType
[
;; The name of the sampling method used for the measurement. For example, 'radiometric detection
;; within the visible and infra-red ranges of the electromagnetic spectrum.
SamplingMethod
;; The measurement conditions of the variable. For example, 'Sampled Particle Size Range: 90 -
;; 600 nm'.
MeasurementConditions
;; The reporting conditions of the variable. The conditions over which the measurements of the
;; variable are valid. For example, 'STP: 1013 mb and 273 K'.
ReportingConditions
])
(record-pretty-printer/enable-record-pretty-printing SamplingIdentifierType)
;; Enables specification of Earth science keywords related to the collection. The Earth Science
;; keywords are chosen from a controlled keyword hierarchy maintained in the Keyword Management
;; System (KMS). The valid values can be found at the KMS website:
;; https://gcmdservices.gsfc.nasa.gov/kms/concepts/concept_scheme/sciencekeywords?format=csv.
(defrecord ScienceKeywordType
[
Category
Topic
Term
VariableLevel1
VariableLevel2
VariableLevel3
DetailedVariable
])
(record-pretty-printer/enable-record-pretty-printing ScienceKeywordType)
;; Valid range data value of a variable: minimum and maximum values. For example, '-100, 5000'.
(defrecord ValidRangeType
[
;; Minimum data value of a variable. For example, '-100'.
Min
;; Maximum data value of a variable. For example, '5000'.
Max
;; This element can be used to specify a code system identifier meaning. For example, 'Open
;; Shrubland' corresponds to '7'.
CodeSystemIdentifierMeaning
;; The code system identifier value is the textual or numerical value assigned to each meaning.
CodeSystemIdentifierValue
])
(record-pretty-printer/enable-record-pretty-printing ValidRangeType)
;; Represents Internet sites that contain information related to the data, as well as related
;; Internet sites such as project home pages, variable colormaps, metadata extensions, etc.
(defrecord RelatedURLType
[
;; Description of the web resource at this URL.
Description
;; A keyword describing the distinct content type of the online resource to this resource. (e.g.,
;; 'DATACENTER URL', 'DATA CONTACT URL', 'Visualization URL'). The valid values are contained in
;; the KMS System:
;; https://gcmd.earthdata.nasa.gov/KeywordViewer/scheme/all/8759ab63-ac04-4136-bc25-0c00eece1096
URLContentType
;; A keyword describing the type of the online resource to this resource. This helps the GUI to
;; know what to do with this resource. (e.g., 'COLORMAP', 'GET VISUALIZATION'). The valid values
;; are contained in the KMS System and are dependent on the URLContentType:
;; https://gcmd.earthdata.nasa.gov/KeywordViewer/scheme/all/8759ab63-ac04-4136-bc25-0c00eece1096
Type
;; A keyword describing the subtype of the online resource to this resource. This further helps
;; the GUI to know what to do with this resource. (e.g., 'MEDIA', 'BROWSE', 'OPENDAP',
;; 'OPENSEARCH', 'GITC', etc. ). The valid values are contained in the KMS System and are
;; dependent on the Type:
;; https://gcmd.earthdata.nasa.gov/KeywordViewer/scheme/all/8759ab63-ac04-4136-bc25-0c00eece1096
Subtype
;; The URL for the relevant web page (e.g., the URL of the responsible organization's home page,
;; the URL of the colormap server, etc.).
URL
;; The format of the data. The controlled vocabulary for formats is maintained in the Keyword
;; Management System (KMS)
Format
;; The mime type of the resource.
MimeType
])
(record-pretty-printer/enable-record-pretty-printing RelatedURLType)
;; The elements of this section allow authors to provide community sourced words or phrases to
;; further describe the variable data.
(defrecord MeasurementIdentifierType
[
;; This element describes the context/medium within which the measurement was made.
MeasurementContextMedium
;; This element contains the URI for the context/medium.
MeasurementContextMediumURI
;; This element describes the object which was measured.
MeasurementObject
;; This element contains the URI for the object which was measured.
MeasurementObjectURI
;; This element contains the quantity or quantities which was/were measured.
MeasurementQuantities
])
(record-pretty-printer/enable-record-pretty-printing MeasurementIdentifierType)
;; A variable consists of one or more dimensions. An example of a dimension name is 'XDim'. An
;; example of a dimension size is '1200'. Variables are rarely one dimensional.
(defrecord DimensionType
[
;; The name of the dimension of the variable represented in the data field. For example, 'XDim.
Name
;; The size of the dimension of the variable represented in the data field. For example, '1200'.
Size
;; The type of the dimension of the variable represented in the data field. For example, if the
;; dimension has a special meaning, i.e., a latitude, longitude, pressure, height (or depth) or
;; time, then the type should be set to either 'LATITUDE_DIMENSION', 'LONGITUDE_DIMENSION',
;; 'PRESSURE_DIMENSION', 'HEIGHT_DIMENSION', 'DEPTH_DIMENSION' or 'TIME_DIMENSION', otherwise it
;; should be set to 'OTHER'.
Type
])
(record-pretty-printer/enable-record-pretty-printing DimensionType)
;; The index ranges consist of a LatRange and a LonRange.
(defrecord IndexRangesType
[
;; The LatRange consists of an index range for latitude.
LatRange
;; The LonRange consists of an index range for longitude.
LonRange
])
(record-pretty-printer/enable-record-pretty-printing IndexRangesType)
;; The elements of this section apply to a measurement name. The measurement name is structured
;; according to the form defined by PI:NAME:<NAME>END_PI. This is: <object>_<quantity>.
(defrecord MeasurementQuantityType
[
;; This element describes the value for the quantity which was measured.
Value
;; This element contains the URI for the quantity which was measured.
MeasurementQuantityURI
])
(record-pretty-printer/enable-record-pretty-printing MeasurementQuantityType)
;; The elements of this section apply to variable sets.
(defrecord SetType
[
;; This element enables specification of set name. For example, 'Data_Fields'.
Name
;; This element enables specification of set type. For example, if the variables have been
;; grouped together based on a particular theme, such as wavelength, then the type should be set
;; to that theme, otherwise it should be set to 'General'.
Type
;; This element specifies the number of variables in the set. For example, if the number of
;; variables in the set is fifteen, the size should be set to '15'.
Size
;; This element specifies the index value within the set for this variable, For example, if this
;; varible is the third variable in the set, the index value should be set to '3'.
Index
])
(record-pretty-printer/enable-record-pretty-printing SetType) |
[
{
"context": ";; Copyright (c) Stephen C. Gilardi. All rights reserved. The use and\n;; distributi",
"end": 36,
"score": 0.9998722076416016,
"start": 18,
"tag": "NAME",
"value": "Stephen C. Gilardi"
},
{
"context": ";;\n;; test/example for clojure.contrib.sql\n;;\n;; scgilardi (gmail)\n;; Created 13 September 2008\n\n(ns clojur",
"end": 549,
"score": 0.9620141983032227,
"start": 540,
"tag": "USERNAME",
"value": "scgilardi"
},
{
"context": "\"\n []\n (sql/insert-records\n :fruit\n {:name \"Pomegranate\" :appearance \"fresh\" :cost 585}\n {:name \"Kiwifr",
"end": 1637,
"score": 0.8668375015258789,
"start": 1626,
"tag": "NAME",
"value": "Pomegranate"
},
{
"context": "ranate\" :appearance \"fresh\" :cost 585}\n {:name \"Kiwifruit\" :grade 93}))\n\n(defn db-write\n \"Write initial va",
"end": 1690,
"score": 0.9771698117256165,
"start": 1681,
"tag": "NAME",
"value": "Kiwifruit"
}
] | ThirdParty/clojure-contrib-1.1.0/src/clojure/contrib/sql/test.clj | allertonm/Couverjure | 3 | ;; Copyright (c) Stephen C. Gilardi. All rights reserved. The use and
;; distribution terms for this software are covered by the Eclipse Public
;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can
;; be found in the file epl-v10.html at the root of this distribution. By
;; using this software in any fashion, you are agreeing to be bound by the
;; terms of this license. You must not remove this notice, or any other,
;; from this software.
;;
;; test.clj
;;
;; test/example for clojure.contrib.sql
;;
;; scgilardi (gmail)
;; Created 13 September 2008
(ns clojure.contrib.sql.test
(:use [clojure.contrib.sql :as sql :only ()]))
(def db {:classname "org.apache.derby.jdbc.EmbeddedDriver"
:subprotocol "derby"
:subname "/tmp/clojure.contrib.sql.test.db"
:create true})
(defn create-fruit
"Create a table"
[]
(sql/create-table
:fruit
[:name "varchar(32)" "PRIMARY KEY"]
[:appearance "varchar(32)"]
[:cost :int]
[:grade :real]))
(defn drop-fruit
"Drop a table"
[]
(try
(sql/drop-table :fruit)
(catch Exception _)))
(defn insert-rows-fruit
"Insert complete rows"
[]
(sql/insert-rows
:fruit
["Apple" "red" 59 87]
["Banana" "yellow" 29 92.2]
["Peach" "fuzzy" 139 90.0]
["Orange" "juicy" 89 88.6]))
(defn insert-values-fruit
"Insert rows with values for only specific columns"
[]
(sql/insert-values
:fruit
[:name :cost]
["Mango" 722]
["Feijoa" 441]))
(defn insert-records-fruit
"Insert records, maps from keys specifying columns to values"
[]
(sql/insert-records
:fruit
{:name "Pomegranate" :appearance "fresh" :cost 585}
{:name "Kiwifruit" :grade 93}))
(defn db-write
"Write initial values to the database as a transaction"
[]
(sql/with-connection db
(sql/transaction
(drop-fruit)
(create-fruit)
(insert-rows-fruit)
(insert-values-fruit)
(insert-records-fruit)))
nil)
(defn db-read
"Read the entire fruit table"
[]
(sql/with-connection db
(sql/with-query-results res
["SELECT * FROM fruit"]
(doseq [rec res]
(println rec)))))
(defn db-update-appearance-cost
"Update the appearance and cost of the named fruit"
[name appearance cost]
(sql/update-values
:fruit
["name=?" name]
{:appearance appearance :cost cost}))
(defn db-update
"Update two fruits as a transaction"
[]
(sql/with-connection db
(sql/transaction
(db-update-appearance-cost "Banana" "bruised" 14)
(db-update-appearance-cost "Feijoa" "green" 400)))
nil)
(defn db-update-or-insert
"Updates or inserts a fruit"
[record]
(sql/with-connection db
(sql/update-or-insert-values
:fruit
["name=?" (:name record)]
record)))
(defn db-read-all
"Return all the rows of the fruit table as a vector"
[]
(sql/with-connection db
(sql/with-query-results res
["SELECT * FROM fruit"]
(into [] res))))
(defn db-grade-range
"Print rows describing fruit that are within a grade range"
[min max]
(sql/with-connection db
(sql/with-query-results res
[(str "SELECT name, cost, grade "
"FROM fruit "
"WHERE grade >= ? AND grade <= ?")
min max]
(doseq [rec res]
(println rec)))))
(defn db-grade-a
"Print rows describing all grade a fruit (grade between 90 and 100)"
[]
(db-grade-range 90 100))
(defn db-get-tables
"Demonstrate getting table info"
[]
(sql/with-connection db
(into []
(resultset-seq
(-> (sql/connection)
(.getMetaData)
(.getTables nil nil nil (into-array ["TABLE" "VIEW"])))))))
(defn db-exception
"Demonstrate rolling back a partially completed transaction on exception"
[]
(sql/with-connection db
(sql/transaction
(sql/insert-values
:fruit
[:name :appearance]
["Grape" "yummy"]
["Pear" "bruised"])
;; at this point the insert-values call is complete, but the transaction
;; is not. the exception will cause it to roll back leaving the database
;; untouched.
(throw (Exception. "sql/test exception")))))
(defn db-sql-exception
"Demonstrate an sql exception"
[]
(sql/with-connection db
(sql/transaction
(sql/insert-values
:fruit
[:name :appearance]
["Grape" "yummy"]
["Pear" "bruised"]
["Apple" "strange" "whoops"]))))
(defn db-batchupdate-exception
"Demonstrate a batch update exception"
[]
(sql/with-connection db
(sql/transaction
(sql/do-commands
"DROP TABLE fruit"
"DROP TABLE fruit"))))
(defn db-rollback
"Demonstrate a rollback-only trasaction"
[]
(sql/with-connection db
(sql/transaction
(prn "is-rollback-only" (sql/is-rollback-only))
(sql/set-rollback-only)
(sql/insert-values
:fruit
[:name :appearance]
["Grape" "yummy"]
["Pear" "bruised"])
(prn "is-rollback-only" (sql/is-rollback-only))
(sql/with-query-results res
["SELECT * FROM fruit"]
(doseq [rec res]
(println rec))))
(prn)
(sql/with-query-results res
["SELECT * FROM fruit"]
(doseq [rec res]
(println rec)))))
| 39109 | ;; Copyright (c) <NAME>. All rights reserved. The use and
;; distribution terms for this software are covered by the Eclipse Public
;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can
;; be found in the file epl-v10.html at the root of this distribution. By
;; using this software in any fashion, you are agreeing to be bound by the
;; terms of this license. You must not remove this notice, or any other,
;; from this software.
;;
;; test.clj
;;
;; test/example for clojure.contrib.sql
;;
;; scgilardi (gmail)
;; Created 13 September 2008
(ns clojure.contrib.sql.test
(:use [clojure.contrib.sql :as sql :only ()]))
(def db {:classname "org.apache.derby.jdbc.EmbeddedDriver"
:subprotocol "derby"
:subname "/tmp/clojure.contrib.sql.test.db"
:create true})
(defn create-fruit
"Create a table"
[]
(sql/create-table
:fruit
[:name "varchar(32)" "PRIMARY KEY"]
[:appearance "varchar(32)"]
[:cost :int]
[:grade :real]))
(defn drop-fruit
"Drop a table"
[]
(try
(sql/drop-table :fruit)
(catch Exception _)))
(defn insert-rows-fruit
"Insert complete rows"
[]
(sql/insert-rows
:fruit
["Apple" "red" 59 87]
["Banana" "yellow" 29 92.2]
["Peach" "fuzzy" 139 90.0]
["Orange" "juicy" 89 88.6]))
(defn insert-values-fruit
"Insert rows with values for only specific columns"
[]
(sql/insert-values
:fruit
[:name :cost]
["Mango" 722]
["Feijoa" 441]))
(defn insert-records-fruit
"Insert records, maps from keys specifying columns to values"
[]
(sql/insert-records
:fruit
{:name "<NAME>" :appearance "fresh" :cost 585}
{:name "<NAME>" :grade 93}))
(defn db-write
"Write initial values to the database as a transaction"
[]
(sql/with-connection db
(sql/transaction
(drop-fruit)
(create-fruit)
(insert-rows-fruit)
(insert-values-fruit)
(insert-records-fruit)))
nil)
(defn db-read
"Read the entire fruit table"
[]
(sql/with-connection db
(sql/with-query-results res
["SELECT * FROM fruit"]
(doseq [rec res]
(println rec)))))
(defn db-update-appearance-cost
"Update the appearance and cost of the named fruit"
[name appearance cost]
(sql/update-values
:fruit
["name=?" name]
{:appearance appearance :cost cost}))
(defn db-update
"Update two fruits as a transaction"
[]
(sql/with-connection db
(sql/transaction
(db-update-appearance-cost "Banana" "bruised" 14)
(db-update-appearance-cost "Feijoa" "green" 400)))
nil)
(defn db-update-or-insert
"Updates or inserts a fruit"
[record]
(sql/with-connection db
(sql/update-or-insert-values
:fruit
["name=?" (:name record)]
record)))
(defn db-read-all
"Return all the rows of the fruit table as a vector"
[]
(sql/with-connection db
(sql/with-query-results res
["SELECT * FROM fruit"]
(into [] res))))
(defn db-grade-range
"Print rows describing fruit that are within a grade range"
[min max]
(sql/with-connection db
(sql/with-query-results res
[(str "SELECT name, cost, grade "
"FROM fruit "
"WHERE grade >= ? AND grade <= ?")
min max]
(doseq [rec res]
(println rec)))))
(defn db-grade-a
"Print rows describing all grade a fruit (grade between 90 and 100)"
[]
(db-grade-range 90 100))
(defn db-get-tables
"Demonstrate getting table info"
[]
(sql/with-connection db
(into []
(resultset-seq
(-> (sql/connection)
(.getMetaData)
(.getTables nil nil nil (into-array ["TABLE" "VIEW"])))))))
(defn db-exception
"Demonstrate rolling back a partially completed transaction on exception"
[]
(sql/with-connection db
(sql/transaction
(sql/insert-values
:fruit
[:name :appearance]
["Grape" "yummy"]
["Pear" "bruised"])
;; at this point the insert-values call is complete, but the transaction
;; is not. the exception will cause it to roll back leaving the database
;; untouched.
(throw (Exception. "sql/test exception")))))
(defn db-sql-exception
"Demonstrate an sql exception"
[]
(sql/with-connection db
(sql/transaction
(sql/insert-values
:fruit
[:name :appearance]
["Grape" "yummy"]
["Pear" "bruised"]
["Apple" "strange" "whoops"]))))
(defn db-batchupdate-exception
"Demonstrate a batch update exception"
[]
(sql/with-connection db
(sql/transaction
(sql/do-commands
"DROP TABLE fruit"
"DROP TABLE fruit"))))
(defn db-rollback
"Demonstrate a rollback-only trasaction"
[]
(sql/with-connection db
(sql/transaction
(prn "is-rollback-only" (sql/is-rollback-only))
(sql/set-rollback-only)
(sql/insert-values
:fruit
[:name :appearance]
["Grape" "yummy"]
["Pear" "bruised"])
(prn "is-rollback-only" (sql/is-rollback-only))
(sql/with-query-results res
["SELECT * FROM fruit"]
(doseq [rec res]
(println rec))))
(prn)
(sql/with-query-results res
["SELECT * FROM fruit"]
(doseq [rec res]
(println rec)))))
| true | ;; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. The use and
;; distribution terms for this software are covered by the Eclipse Public
;; License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which can
;; be found in the file epl-v10.html at the root of this distribution. By
;; using this software in any fashion, you are agreeing to be bound by the
;; terms of this license. You must not remove this notice, or any other,
;; from this software.
;;
;; test.clj
;;
;; test/example for clojure.contrib.sql
;;
;; scgilardi (gmail)
;; Created 13 September 2008
(ns clojure.contrib.sql.test
(:use [clojure.contrib.sql :as sql :only ()]))
(def db {:classname "org.apache.derby.jdbc.EmbeddedDriver"
:subprotocol "derby"
:subname "/tmp/clojure.contrib.sql.test.db"
:create true})
(defn create-fruit
"Create a table"
[]
(sql/create-table
:fruit
[:name "varchar(32)" "PRIMARY KEY"]
[:appearance "varchar(32)"]
[:cost :int]
[:grade :real]))
(defn drop-fruit
"Drop a table"
[]
(try
(sql/drop-table :fruit)
(catch Exception _)))
(defn insert-rows-fruit
"Insert complete rows"
[]
(sql/insert-rows
:fruit
["Apple" "red" 59 87]
["Banana" "yellow" 29 92.2]
["Peach" "fuzzy" 139 90.0]
["Orange" "juicy" 89 88.6]))
(defn insert-values-fruit
"Insert rows with values for only specific columns"
[]
(sql/insert-values
:fruit
[:name :cost]
["Mango" 722]
["Feijoa" 441]))
(defn insert-records-fruit
"Insert records, maps from keys specifying columns to values"
[]
(sql/insert-records
:fruit
{:name "PI:NAME:<NAME>END_PI" :appearance "fresh" :cost 585}
{:name "PI:NAME:<NAME>END_PI" :grade 93}))
(defn db-write
"Write initial values to the database as a transaction"
[]
(sql/with-connection db
(sql/transaction
(drop-fruit)
(create-fruit)
(insert-rows-fruit)
(insert-values-fruit)
(insert-records-fruit)))
nil)
(defn db-read
"Read the entire fruit table"
[]
(sql/with-connection db
(sql/with-query-results res
["SELECT * FROM fruit"]
(doseq [rec res]
(println rec)))))
(defn db-update-appearance-cost
"Update the appearance and cost of the named fruit"
[name appearance cost]
(sql/update-values
:fruit
["name=?" name]
{:appearance appearance :cost cost}))
(defn db-update
"Update two fruits as a transaction"
[]
(sql/with-connection db
(sql/transaction
(db-update-appearance-cost "Banana" "bruised" 14)
(db-update-appearance-cost "Feijoa" "green" 400)))
nil)
(defn db-update-or-insert
"Updates or inserts a fruit"
[record]
(sql/with-connection db
(sql/update-or-insert-values
:fruit
["name=?" (:name record)]
record)))
(defn db-read-all
"Return all the rows of the fruit table as a vector"
[]
(sql/with-connection db
(sql/with-query-results res
["SELECT * FROM fruit"]
(into [] res))))
(defn db-grade-range
"Print rows describing fruit that are within a grade range"
[min max]
(sql/with-connection db
(sql/with-query-results res
[(str "SELECT name, cost, grade "
"FROM fruit "
"WHERE grade >= ? AND grade <= ?")
min max]
(doseq [rec res]
(println rec)))))
(defn db-grade-a
"Print rows describing all grade a fruit (grade between 90 and 100)"
[]
(db-grade-range 90 100))
(defn db-get-tables
"Demonstrate getting table info"
[]
(sql/with-connection db
(into []
(resultset-seq
(-> (sql/connection)
(.getMetaData)
(.getTables nil nil nil (into-array ["TABLE" "VIEW"])))))))
(defn db-exception
"Demonstrate rolling back a partially completed transaction on exception"
[]
(sql/with-connection db
(sql/transaction
(sql/insert-values
:fruit
[:name :appearance]
["Grape" "yummy"]
["Pear" "bruised"])
;; at this point the insert-values call is complete, but the transaction
;; is not. the exception will cause it to roll back leaving the database
;; untouched.
(throw (Exception. "sql/test exception")))))
(defn db-sql-exception
"Demonstrate an sql exception"
[]
(sql/with-connection db
(sql/transaction
(sql/insert-values
:fruit
[:name :appearance]
["Grape" "yummy"]
["Pear" "bruised"]
["Apple" "strange" "whoops"]))))
(defn db-batchupdate-exception
"Demonstrate a batch update exception"
[]
(sql/with-connection db
(sql/transaction
(sql/do-commands
"DROP TABLE fruit"
"DROP TABLE fruit"))))
(defn db-rollback
"Demonstrate a rollback-only trasaction"
[]
(sql/with-connection db
(sql/transaction
(prn "is-rollback-only" (sql/is-rollback-only))
(sql/set-rollback-only)
(sql/insert-values
:fruit
[:name :appearance]
["Grape" "yummy"]
["Pear" "bruised"])
(prn "is-rollback-only" (sql/is-rollback-only))
(sql/with-query-results res
["SELECT * FROM fruit"]
(doseq [rec res]
(println rec))))
(prn)
(sql/with-query-results res
["SELECT * FROM fruit"]
(doseq [rec res]
(println rec)))))
|
[
{
"context": "ns under the License.\n;;\n;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.\n\n(ns czlab.twisty.core\n\n \"",
"end": 597,
"score": 0.9998583793640137,
"start": 584,
"tag": "NAME",
"value": "Kenneth Leung"
}
] | src/main/clojure/czlab/twisty/core.clj | llnek/crypto | 0 | ;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.
(ns czlab.twisty.core
"Crypto functions."
(:require [clojure.java.io :as io]
[clojure.string :as cs]
[czlab.basal.io :as i]
[czlab.basal.util :as u]
[czlab.basal.core :as c]
[czlab.basal.dates :as d])
(:import [javax.activation DataHandler CommandMap MailcapCommandMap]
[javax.mail BodyPart MessagingException Multipart Session]
[org.bouncycastle.jce.provider BouncyCastleProvider]
[org.apache.commons.mail DefaultAuthenticator]
[javax.net.ssl X509TrustManager TrustManager]
[org.bouncycastle.util.encoders Hex Base64]
[org.bouncycastle.asn1.pkcs PrivateKeyInfo]
[org.bouncycastle.asn1 ASN1EncodableVector]
[org.bouncycastle.asn1.x500 X500Name]
[clojure.lang APersistentVector]
[org.bouncycastle.pkcs.jcajce
JcaPKCS10CertificationRequestBuilder]
[org.bouncycastle.pkcs.bc
BcPKCS12PBEInputDecryptorProviderBuilder]
[org.bouncycastle.operator
DigestCalculatorProvider
ContentSigner
OperatorCreationException]
[org.bouncycastle.asn1.x509
X509Extension
SubjectPublicKeyInfo]
[org.bouncycastle.asn1.cms
AttributeTable
ContentInfo
IssuerAndSerialNumber]
[org.bouncycastle.pkcs
PKCS8EncryptedPrivateKeyInfo]
[org.bouncycastle.openssl
X509TrustedCertificateBlock
PEMKeyPair
PEMEncryptedKeyPair]
[org.bouncycastle.cert
X509CRLHolder
X509CertificateHolder
X509AttributeCertificateHolder]
[org.bouncycastle.openssl.jcajce
JcePEMDecryptorProviderBuilder
JcePEMEncryptorBuilder
JcaMiscPEMGenerator
JcaPEMKeyConverter]
[java.security
Policy
PermissionCollection
Permissions
KeyPair
KeyPairGenerator
KeyStore
MessageDigest
PrivateKey
Provider
PublicKey
AllPermission
SecureRandom
Security
KeyStore$PasswordProtection
GeneralSecurityException
KeyStore$PrivateKeyEntry
KeyStore$TrustedCertificateEntry]
[java.security.cert
CertificateFactory
Certificate
X509Certificate]
[org.bouncycastle.cms
CMSSignedDataGenerator
CMSProcessableFile
CMSProcessable
CMSSignedGenerator
CMSProcessableByteArray]
[org.bouncycastle.cms.jcajce
JcaSignerInfoGeneratorBuilder]
[org.bouncycastle.operator.jcajce
JcaContentSignerBuilder
JcaDigestCalculatorProviderBuilder]
[javax.security.auth.x500 X500Principal]
[javax.crypto.spec SecretKeySpec]
[org.bouncycastle.cert.jcajce
JcaCertStore
JcaX509CertificateConverter
JcaX509ExtensionUtils
JcaX509v1CertificateBuilder
JcaX509v3CertificateBuilder]
[org.bouncycastle.openssl
PEMWriter
PEMParser
PEMEncryptor]
[org.bouncycastle.pkcs
PKCS10CertificationRequest
PKCS10CertificationRequestBuilder]
[javax.crypto
Mac
SecretKey
Cipher
KeyGenerator]
[java.io
StringWriter
PrintStream
File
InputStream
IOException
FileInputStream
InputStreamReader
ByteArrayInputStream
ByteArrayOutputStream]
[java.math BigInteger]
[java.net URL]
[java.util Random Date]
[javax.mail.internet
ContentType
MimeBodyPart
MimeMessage
MimeMultipart
MimeUtility]
[java.lang Math]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* true)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/def- ^String def-algo "SHA1WithRSAEncryption")
(c/def- ^String def-mac "HmacSHA512")
(c/def- enc-algos
#{"AES-128-CBC" "AES-128-CFB" "AES-128-ECB" "AES-128-OFB"
"AES-192-CBC" "AES-192-CFB" "AES-192-ECB" "AES-192-OFB"
"AES-256-CBC" "AES-256-CFB" "AES-256-ECB" "AES-256-OFB"
"BF-CBC" "BF-CFB" "BF-ECB" "BF-OFB"
"DES-CBC" "DES-CFB" "DES-ECB" "DES-OFB"
"DES-EDE" "DES-EDE-CBC" "DES-EDE-CFB" "DES-EDE-ECB"
"DES-EDE-OFB" "DES-EDE3" "DES-EDE3-CBC" "DES-EDE3-CFB"
"DES-EDE3-ECB" "DES-EDE3-OFB"
"RC2-CBC" "RC2-CFB" "RC2-ECB" "RC2-OFB"
"RC2-40-CBC" "RC2-64-CBC" })
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^String sha-512-rsa "SHA512withRSA")
(def ^String sha-256-rsa "SHA256withRSA")
(def ^String sha1-rsa "SHA1withRSA")
(def ^String md5-rsa "MD5withRSA")
(def ^String blow-fish "BlowFish")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^{:dynamic true
:tag Provider} *-bc-* (BouncyCastleProvider.))
(Security/addProvider *-bc-*)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/defenum exform 1 pem der)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord CertGist [issuer subj notBefore notAfter])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord PKeyGist [chain cert pkey])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn alias<>
"A new random name."
{:tag String
:arglists '([])}
[]
(format "%s#%04d" (-> (u/jid<>) (subs 0 6)) (u/seqint)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn pkcs12<>
"Create a PKCS12 key store."
{:tag KeyStore
:arglists '([])}
[]
(doto
(KeyStore/getInstance "PKCS12" *-bc-*) (.load nil nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn jks<>
"Create a JKS key store."
{:tag KeyStore
:arglists '([])}
[]
(doto
(KeyStore/getInstance
"JKS" (Security/getProvider "SUN")) (.load nil nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn x->keystore<>
"Create a key store from input."
{:tag KeyStore
:arglists '([c pk pwd certs]
[c pk pwd certs options])}
([c pk pwd certs]
(x->keystore<> c pk pwd certs nil))
([cert pk pwd certs options]
(let [{:keys [ktype]
:or {ktype :pkcs12}} options]
(doto (if (= :jks ktype) (jks<>) (pkcs12<>))
(.setKeyEntry (alias<>)
^PrivateKey pk
(i/x->chars pwd)
(c/vargs Certificate
(cons cert (or certs []))))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn asym-key-pair*
"Generate a KeyPair."
{:tag KeyPair
:arglists '([algo]
[algo keylen])}
([algo]
(asym-key-pair* algo nil))
([algo keylen]
{:pre [(string? algo)]}
(let [len (c/num?? keylen 1024)]
(-> (doto
(KeyPairGenerator/getInstance ^String algo *-bc-*)
(.initialize (int len) (u/rand<> true)))
.generateKeyPair))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn asym-key-pair<>
"Generate a public & private key."
{:arglists '([algo]
[algo keylen])}
([algo] (asym-key-pair<> algo nil))
([algo keylen]
(let [kp (asym-key-pair* algo keylen)]
[(.getPublic kp) (.getPrivate kp)])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-encrypted?
"Does content-type indicate *encrypted*?"
{:arglists '([s])}
[s]
{:pre [(string? s)]}
(c/if-some+ [ct (c/lcase s)]
(and (c/embeds? ct "enveloped-data")
(c/embeds? ct "application/x-pkcs7-mime"))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-compressed?
"Does content-type indicate *compressed*?"
{:arglists '([s])}
[s]
{:pre [(string? s)]}
(c/if-some+ [ct (c/lcase s)]
(and (c/embeds? ct "compressed-data")
(c/embeds? ct "application/pkcs7-mime"))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-signed?
"Does content-type indicate *signed*?"
{:arglists '([s])}
[s]
{:pre [(string? s)]}
(c/if-some+ [ct (c/lcase s)]
(or (c/embeds? ct "multipart/signed")
(and (c/embeds? ct "signed-data")
(c/embeds? ct "application/x-pkcs7-mime")))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn assert-jce
"This function should fail if the
non-restricted (unlimited-strength)
jce files are missing in jre-home.
**** Not needed after jdk10+"
{:arglists '([])}
[]
(let
[kgen (doto
(KeyGenerator/getInstance blow-fish)
(.init 256))]
(-> (doto
(Cipher/getInstance blow-fish)
(.init Cipher/ENCRYPT_MODE
(SecretKeySpec. (.. kgen
generateKey
getEncoded) blow-fish)))
(.doFinal (i/x->bytes "yo")))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(assert-jce)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(doto
^MailcapCommandMap
(CommandMap/getDefaultCommandMap)
(.addMailcap (str "application/pkcs7-signature;; "
"x-java-content-handler="
"org.bouncycastle.mail.smime.handlers.pkcs7_signature"))
(.addMailcap (str "application/pkcs7-mime;; "
"x-java-content-handler="
"org.bouncycastle.mail.smime.handlers.pkcs7_mime"))
(.addMailcap (str "application/x-pkcs7-signature;; "
"x-java-content-handler="
"org.bouncycastle.mail.smime.handlers.x_pkcs7_signature"))
(.addMailcap (str "application/x-pkcs7-mime;; "
"x-java-content-handler="
"org.bouncycastle.mail.smime.handlers.x_pkcs7_mime"))
(.addMailcap (str "multipart/signed;; "
"x-java-content-handler="
"org.bouncycastle.mail.smime.handlers.multipart_signed")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro with-BC1
"BC as provider - part of ctor(arg)."
{:arglists '([cz p1]
[cz p1 pv])}
([cz p1]
`(with-BC1 ~cz ~p1 nil))
([cz p1 pv]
`(-> (new ~cz ~p1)
(.setProvider (or ~pv czlab.twisty.core/*-bc-*)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro with-BC
"BC as provider - part of ctor."
{:arglists '([cz]
[cz pv])}
([cz]
`(with-BC ~cz nil))
([cz pv]
`(-> (new ~cz)
(.setProvider (or ~pv czlab.twisty.core/*-bc-*)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- to-xcert
^X509Certificate
[^X509CertificateHolder h]
(-> JcaX509CertificateConverter with-BC (.getCertificate h)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- pemencr<>
^PEMEncryptor
[^chars pwd]
(if-not (empty? pwd)
(-> (->> (rand-nth (seq enc-algos))
(with-BC1 JcePEMEncryptorBuilder ))
(.setSecureRandom (u/rand<>)) (.build pwd))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-jks?
"Is url pointing to a JKS key file?"
{:arglists '([keyUrl])}
[keyUrl]
(some-> keyUrl io/as-url .getFile c/lcase (cs/ends-with? ".jks")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn msg-digest<>
"Get a message digest instance:
MD5, SHA-1, SHA-256, SHA-384, SHA-512."
{:arglists '([algo])
:tag MessageDigest}
[algo]
(-> algo c/kw->str c/ucase
(c/stror "SHA-512")
(MessageDigest/getInstance *-bc-*)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn next-serial
"A random Big Integer."
{:arglists '([])
:tag BigInteger}
[]
(BigInteger/valueOf
(Math/abs (-> (Random. (u/system-time)) .nextLong))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn dbg-provider
"List all BC algos."
{:arglists '([os])}
[os]
(c/try! (.list *-bc-* ^PrintStream os)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- ksinit
"Initialize a keystore."
[^KeyStore store arg pwd2]
(let [[d? inp]
(i/input-stream?? arg)]
(try (.load store
^InputStream inp
(i/x->chars pwd2))
(finally (if d? (i/klose inp)))) store))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmulti pkey-gist<>
"Create a PKeyGist object."
{:arglists '([arg _ _])} (fn [a _ _] (class a)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod pkey-gist<>
PrivateKey
[pkey cert listOfCerts]
(PKeyGist. (c/vec-> listOfCerts) cert pkey))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod pkey-gist<>
KeyStore
[ks alias pwd]
(if-some [e (->> pwd
i/x->chars
KeyStore$PasswordProtection.
(.getEntry ^KeyStore ks
^String alias)
(c/cast? KeyStore$PrivateKeyEntry))]
(pkey-gist<> (.getPrivateKey e)
(.getCertificate e)
(.getCertificateChain e))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn spit-keystore
"Write keystore out to file."
{:tag File
:arglists '([ks fout pwd2])}
[ks fout pwd2]
{:pre [(c/is? KeyStore ks)]}
(let [out (i/baos<>)]
(.store ^KeyStore ks
out (i/x->chars pwd2))
(i/x->file (i/x->bytes out) (io/file fout))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn tcert<>
"Get a trusted certificate from store."
{:tag Certificate
:arglists '([ks alias])}
[ks alias]
{:pre [(c/is? KeyStore ks)]}
(if-some
[e (->> (.getEntry ^KeyStore ks
^String alias nil)
(c/cast? KeyStore$TrustedCertificateEntry))]
(.getTrustedCertificate e)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn filter-entries
"Select entries from the store."
{:arglists '([ks entryType])}
[ks entryType]
{:pre [(c/is? KeyStore ks)]}
(loop [out (c/tvec*)
en (.aliases ^KeyStore ks)]
(if-not (.hasMoreElements en)
(c/persist! out)
(let [n (.nextElement en)]
(recur (if (cond
(= :keys entryType)
(.isKeyEntry ^KeyStore ks n)
(= :certs entryType)
(.isCertificateEntry ^KeyStore ks n))
(conj! out n) out) en)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn pkcs12*
"Create and initialize a PKCS12 key store."
{:tag KeyStore
:arglists '([arg]
[arg pwd2])}
([arg]
(pkcs12* arg nil))
([arg pwd2]
(ksinit (pkcs12<>) arg pwd2)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn jks*
"Create and initialize a JKS key store."
{:tag KeyStore
:arglists '([arg]
[arg pwd2])}
([arg]
(jks* arg nil))
([arg pwd2]
(ksinit (jks<>) arg pwd2)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn spit-pem
"Export object out in PEM format."
{:tag String
:arglists '([obj]
[obj pwd])}
([obj]
(spit-pem obj nil))
([obj pwd]
(c/do-with-str [sw (StringWriter.)]
(let [pw (PEMWriter. sw)
ec (pemencr<> ^chars pwd)]
(.writeObject pw
(if (nil? ec)
(JcaMiscPEMGenerator. obj)
(JcaMiscPEMGenerator. obj ec)))
(.flush pw)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn spit-der
"Export object out in DER format."
{:tag "[B"
:arglists '([obj])}
[obj]
(c/condp?? instance? obj
PrivateKey (.getEncoded ^PrivateKey obj)
PublicKey (.getEncoded ^PublicKey obj)
X509Certificate (.getEncoded ^X509Certificate obj)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn x->certs
"Parse input and generate a cert chain."
{:arglists '([arg])}
[arg]
(let [[d? inp]
(i/input-stream?? arg)]
(try (-> (CertificateFactory/getInstance "X.509")
(.generateCertificates ^InputStream inp))
(finally (if d? (i/klose inp))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn x->cert
"Parse input and generate a cert."
{:arglists '([arg])}
[arg]
(let [[d? inp]
(i/input-stream?? arg)]
(try (-> (CertificateFactory/getInstance "X.509")
(.generateCertificate ^InputStream inp))
(finally (if d? (i/klose inp))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn x->pkey
"Parse input and generate a PKeyGist object."
{:arglists '([arg pwd]
[arg pwd pwdStore])}
([arg pwd]
(x->pkey arg pwd nil))
([arg pwd pwdStore]
(let [ks (pkcs12* arg pwdStore)]
(c/if-some+
[n (c/_1
(filter-entries ks :keys))]
(pkey-gist<> ks n pwd)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn easy-policy<>
"Enables all permissions."
{:tag Policy
:arglists '([])}
[]
(proxy [Policy] []
(getPermissions [cs]
(doto (Permissions.) (.add (AllPermission.))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn gen-mac
"Create Message Auth Code."
{:tag String
:arglists '([skey data]
[skey data algo])}
([skey data]
(gen-mac skey data nil))
([skey data algo]
{:pre [(some? skey) (some? data)]}
(let
[algo (-> algo c/kw->str
c/ucase (c/stror def-mac))
flag (c/mu-long)
mac (Mac/getInstance algo *-bc-*)]
(->> (SecretKeySpec.
(i/x->bytes skey) algo) (.init mac))
(i/chunk-read-stream data
(fn [buf offset len end?]
(when (pos? len)
(c/mu-long flag + len)
(.update mac buf offset len))))
(str (some->
(if (c/spos?
(c/mu-long flag)) (.doFinal mac)) Hex/toHexString)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gen-digest*
[data algo]
(let [flag (c/mu-long)
d (msg-digest<> algo)]
(i/chunk-read-stream data
(fn [buf offset len end?]
(when (pos? len)
(c/mu-long flag + len)
(.update d buf offset len))))
(if (c/spos? (c/mu-long flag)) (.digest d))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn gen-digest
"Create Message Digest."
{:tag String
:arglists '([data]
[data options])}
([data]
(gen-digest data nil))
([data options]
(let [{:keys [algo fmt]
:or {fmt :base64}} options
x (gen-digest* data algo)]
(str
(if x
(if (= fmt :hex)
(Hex/toHexString x)
(Base64/toBase64String x)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- scert<>
"Sign a cert, issuer is self is nil."
([args]
(scert<> nil args))
([{^PrivateKey pkey :pkey
^X509Certificate rootc :cert :as issuer}
{:keys [^String dn algo
start end
validity keylen style]
:or {style "RSA" keylen 1024} :as args}]
(let [^Date end (or end (-> (or validity 12)
d/add-months .getTime))
^Date start (or start (u/date<>))
subject (X500Principal. dn)
[^PublicKey pub ^PrivateKey prv]
(asym-key-pair<> (or (some->
pkey .getAlgorithm) style) keylen)
[^JcaX509ExtensionUtils exu bdr]
(if issuer
[(JcaX509ExtensionUtils.)
(JcaX509v3CertificateBuilder.
rootc (next-serial) start end subject pub)]
[nil (JcaX509v1CertificateBuilder.
(X500Principal. dn)
(next-serial) start end subject pub)])
cs (->> (if issuer pkey prv)
(.build (with-BC1 JcaContentSignerBuilder algo *-bc-*)))]
(if issuer
(doto ^JcaX509v3CertificateBuilder bdr
(.addExtension
X509Extension/authorityKeyIdentifier false
(.createAuthorityKeyIdentifier exu rootc))
(.addExtension
X509Extension/subjectKeyIdentifier false
(.createSubjectKeyIdentifier exu pub))))
(try
[prv
(doto (to-xcert (if issuer
(.build ^JcaX509v3CertificateBuilder bdr cs)
(.build ^JcaX509v1CertificateBuilder bdr cs)))
(.checkValidity (u/date<>))
(.verify (if issuer (.getPublicKey rootc) pub)))]
(finally
(c/debug (str "signed-cert: dn= %s "
",algo= %s,start= %s" ",end=%s") dn algo start end))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn gen-cert
"Create a Certificate from the DN."
{:tag KeyStore
:arglists '([dnStr pwd args]
[dnStr issuer pwd args])}
([dnStr pwd args]
(gen-cert dnStr nil pwd args))
([dnStr issuer pwd args]
(let [{:keys [ktype]} args
;; JKS uses SUN and hence needs to use DSA
[pkey cert]
(scert<> issuer
(merge (if (not= :jks ktype)
{:algo def-algo}
{:style "DSA" :algo "SHA1withDSA"})
{:dn dnStr} args))]
(x->keystore<> cert pkey pwd
(if issuer
(c/vec-> (:chain issuer)) []) args))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn csreq<>
"Generate a Certificate Signing Request."
{:arglists '([dnStr]
[dnStr keylen]
[dnStr keylen pwd])}
([dnStr keylen]
(csreq<> dnStr keylen nil))
([dnStr]
(csreq<> dnStr 1024 nil))
([dnStr keylen pwd]
{:pre [(string? dnStr)]}
(let [csb (with-BC1 JcaContentSignerBuilder def-algo)
len (c/num?? keylen 1024)
[pu pv] (asym-key-pair<> "RSA" len)
rbr (JcaPKCS10CertificationRequestBuilder.
(X500Principal. ^String dnStr) ^PublicKey pu)
rc (->> (.build csb pv) (.build rbr))]
(c/debug "csr: dnStr= %s, key-len= %d" dnStr len)
[(spit-pem rc)
(spit-pem pv pwd)])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- pemparse2
[obj ^JcaPEMKeyConverter pc]
(condp = (class obj)
PEMKeyPair
(.getKeyPair pc ^PEMKeyPair obj)
KeyPair obj
PrivateKeyInfo
(.getPrivateKey pc ^PrivateKeyInfo obj)
ContentInfo obj
X509AttributeCertificateHolder
(to-xcert obj)
X509TrustedCertificateBlock
(-> ^X509TrustedCertificateBlock obj .getCertificateHolder to-xcert)
SubjectPublicKeyInfo
(.getPublicKey pc ^SubjectPublicKeyInfo obj)
X509CertificateHolder
(to-xcert obj)
X509CRLHolder obj
PKCS10CertificationRequest obj
obj))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- pemparse
"PEM encoded streams may contain
X509 certificates,
PKCS8 encoded keys and PKCS7 objs.
PKCS7 objs => a CMS ContentInfo object.
PubKeys => well formed SubjectPublicKeyInfo objs
PrvKeys => well formed PrivateKeyInfo obj.
=> PEMKeyPair if contains both private and public key.
CRLs, Certificates,
PKCS#10 requests,
and Attribute Certificates => appropriate holder class"
[^InputStream inp ^chars pwd]
(c/wo* [rdr (InputStreamReader. inp)]
(let [obj (-> (PEMParser. rdr) .readObject)
pc (with-BC JcaPEMKeyConverter)
dc (.build (JcePEMDecryptorProviderBuilder.) pwd)
dp (.build (BcPKCS12PBEInputDecryptorProviderBuilder.) pwd)]
(pemparse2 (condp = (class obj)
PKCS8EncryptedPrivateKeyInfo
(-> ^PKCS8EncryptedPrivateKeyInfo obj
(.decryptPrivateKeyInfo dp))
PEMEncryptedKeyPair
(->> (-> ^PEMEncryptedKeyPair obj
(.decryptKeyPair dc))
(.getKeyPair pc))
obj)
pc))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-cert-valid?
"Test if cert is valid?"
{:arglists '([c])}
[c]
(c/try! (.checkValidity ^X509Certificate c (u/date<>)) true))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn cert-gist<>
"Create a gist from the cert."
{:arglists '([c])}
[c]
{:pre [(c/is? X509Certificate c)]}
(let [x509 (c/cast? X509Certificate c)]
(CertGist. (.getIssuerX500Principal x509)
(.getSubjectX500Principal x509)
(.getNotBefore x509)
(.getNotAfter x509))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn spit-pkcs7
"Generate PKCS7 from the private-key."
{:tag "[B"
:arglists '([pkeyGist])}
[pkeyGist]
(let [xxx (CMSProcessableByteArray. (i/x->bytes "?"))
gen (CMSSignedDataGenerator.)
{:keys [^X509Certificate cert
^PrivateKey pkey chain]} pkeyGist
bdr (JcaSignerInfoGeneratorBuilder.
(.build (with-BC JcaDigestCalculatorProviderBuilder)))
;; "SHA1withRSA"
cs (.build (with-BC1 JcaContentSignerBuilder sha-512-rsa) pkey)]
(.addSignerInfoGenerator gen (.build bdr cs cert))
(.addCertificates gen (JcaCertStore. chain))
(.getEncoded (.generate gen xxx))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn session<>
"Create a new java-mail session."
{:tag Session
:arglists '([]
[user]
[user pwd])}
([user]
(session<> user nil))
([]
(session<> nil nil))
([user pwd]
(Session/getInstance
(System/getProperties)
(if (c/hgl? user)
(->> (if pwd (i/x->str pwd))
(DefaultAuthenticator. ^String user))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn mime-msg<>
"Create a new MIME Message."
{:tag MimeMessage
:arglists '([]
[inp]
[user pwd]
[user pwd inp])}
([^String user pwd ^InputStream inp]
(let [s (session<> user pwd)]
(if (nil? inp)
(MimeMessage. s)
(MimeMessage. s inp))))
([inp]
(mime-msg<> "" nil inp))
([]
(mime-msg<> "" nil nil))
([user pwd]
(mime-msg<> user pwd nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- is-data-xxx?
[obj tst?]
(if-some [[d? inp] (i/input-stream?? obj)]
(try (tst? (.getContentType
(mime-msg<> "" nil inp)))
(finally (if d? (i/klose inp))))
(condp instance? obj
Multipart (tst? (.getContentType (c/cast? Multipart obj)))
BodyPart (tst? (.getContentType (c/cast? BodyPart obj)))
(u/throw-IOE "Invalid content: %s." (u/gczn obj)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-data-encrypted?
"Test if object is *encrypted*?"
{:arglists '([obj])}
[obj]
(is-data-xxx? obj is-encrypted?))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-data-signed?
"Test if object is *signed*?"
{:arglists '([obj])}
[obj]
(is-data-xxx? obj is-signed?))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-data-compressed?
"Test if object is *compressed*?"
{:arglists '([obj])}
[obj]
(is-data-xxx? obj is-compressed?))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn charset??
"Charset from content-type."
{:tag String
:arglists '([cType]
[cType dft])}
([cType]
(charset?? cType nil))
([cType dft]
(c/stror
(if (c/hgl? cType)
(c/try! (-> (ContentType. ^String cType)
(.getParameter "charset")
MimeUtility/javaCharset )))
(if (c/hgl? dft)
(MimeUtility/javaCharset ^String dft)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
| 104947 | ;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; Copyright © 2013-2022, <NAME>. All rights reserved.
(ns czlab.twisty.core
"Crypto functions."
(:require [clojure.java.io :as io]
[clojure.string :as cs]
[czlab.basal.io :as i]
[czlab.basal.util :as u]
[czlab.basal.core :as c]
[czlab.basal.dates :as d])
(:import [javax.activation DataHandler CommandMap MailcapCommandMap]
[javax.mail BodyPart MessagingException Multipart Session]
[org.bouncycastle.jce.provider BouncyCastleProvider]
[org.apache.commons.mail DefaultAuthenticator]
[javax.net.ssl X509TrustManager TrustManager]
[org.bouncycastle.util.encoders Hex Base64]
[org.bouncycastle.asn1.pkcs PrivateKeyInfo]
[org.bouncycastle.asn1 ASN1EncodableVector]
[org.bouncycastle.asn1.x500 X500Name]
[clojure.lang APersistentVector]
[org.bouncycastle.pkcs.jcajce
JcaPKCS10CertificationRequestBuilder]
[org.bouncycastle.pkcs.bc
BcPKCS12PBEInputDecryptorProviderBuilder]
[org.bouncycastle.operator
DigestCalculatorProvider
ContentSigner
OperatorCreationException]
[org.bouncycastle.asn1.x509
X509Extension
SubjectPublicKeyInfo]
[org.bouncycastle.asn1.cms
AttributeTable
ContentInfo
IssuerAndSerialNumber]
[org.bouncycastle.pkcs
PKCS8EncryptedPrivateKeyInfo]
[org.bouncycastle.openssl
X509TrustedCertificateBlock
PEMKeyPair
PEMEncryptedKeyPair]
[org.bouncycastle.cert
X509CRLHolder
X509CertificateHolder
X509AttributeCertificateHolder]
[org.bouncycastle.openssl.jcajce
JcePEMDecryptorProviderBuilder
JcePEMEncryptorBuilder
JcaMiscPEMGenerator
JcaPEMKeyConverter]
[java.security
Policy
PermissionCollection
Permissions
KeyPair
KeyPairGenerator
KeyStore
MessageDigest
PrivateKey
Provider
PublicKey
AllPermission
SecureRandom
Security
KeyStore$PasswordProtection
GeneralSecurityException
KeyStore$PrivateKeyEntry
KeyStore$TrustedCertificateEntry]
[java.security.cert
CertificateFactory
Certificate
X509Certificate]
[org.bouncycastle.cms
CMSSignedDataGenerator
CMSProcessableFile
CMSProcessable
CMSSignedGenerator
CMSProcessableByteArray]
[org.bouncycastle.cms.jcajce
JcaSignerInfoGeneratorBuilder]
[org.bouncycastle.operator.jcajce
JcaContentSignerBuilder
JcaDigestCalculatorProviderBuilder]
[javax.security.auth.x500 X500Principal]
[javax.crypto.spec SecretKeySpec]
[org.bouncycastle.cert.jcajce
JcaCertStore
JcaX509CertificateConverter
JcaX509ExtensionUtils
JcaX509v1CertificateBuilder
JcaX509v3CertificateBuilder]
[org.bouncycastle.openssl
PEMWriter
PEMParser
PEMEncryptor]
[org.bouncycastle.pkcs
PKCS10CertificationRequest
PKCS10CertificationRequestBuilder]
[javax.crypto
Mac
SecretKey
Cipher
KeyGenerator]
[java.io
StringWriter
PrintStream
File
InputStream
IOException
FileInputStream
InputStreamReader
ByteArrayInputStream
ByteArrayOutputStream]
[java.math BigInteger]
[java.net URL]
[java.util Random Date]
[javax.mail.internet
ContentType
MimeBodyPart
MimeMessage
MimeMultipart
MimeUtility]
[java.lang Math]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* true)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/def- ^String def-algo "SHA1WithRSAEncryption")
(c/def- ^String def-mac "HmacSHA512")
(c/def- enc-algos
#{"AES-128-CBC" "AES-128-CFB" "AES-128-ECB" "AES-128-OFB"
"AES-192-CBC" "AES-192-CFB" "AES-192-ECB" "AES-192-OFB"
"AES-256-CBC" "AES-256-CFB" "AES-256-ECB" "AES-256-OFB"
"BF-CBC" "BF-CFB" "BF-ECB" "BF-OFB"
"DES-CBC" "DES-CFB" "DES-ECB" "DES-OFB"
"DES-EDE" "DES-EDE-CBC" "DES-EDE-CFB" "DES-EDE-ECB"
"DES-EDE-OFB" "DES-EDE3" "DES-EDE3-CBC" "DES-EDE3-CFB"
"DES-EDE3-ECB" "DES-EDE3-OFB"
"RC2-CBC" "RC2-CFB" "RC2-ECB" "RC2-OFB"
"RC2-40-CBC" "RC2-64-CBC" })
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^String sha-512-rsa "SHA512withRSA")
(def ^String sha-256-rsa "SHA256withRSA")
(def ^String sha1-rsa "SHA1withRSA")
(def ^String md5-rsa "MD5withRSA")
(def ^String blow-fish "BlowFish")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^{:dynamic true
:tag Provider} *-bc-* (BouncyCastleProvider.))
(Security/addProvider *-bc-*)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/defenum exform 1 pem der)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord CertGist [issuer subj notBefore notAfter])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord PKeyGist [chain cert pkey])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn alias<>
"A new random name."
{:tag String
:arglists '([])}
[]
(format "%s#%04d" (-> (u/jid<>) (subs 0 6)) (u/seqint)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn pkcs12<>
"Create a PKCS12 key store."
{:tag KeyStore
:arglists '([])}
[]
(doto
(KeyStore/getInstance "PKCS12" *-bc-*) (.load nil nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn jks<>
"Create a JKS key store."
{:tag KeyStore
:arglists '([])}
[]
(doto
(KeyStore/getInstance
"JKS" (Security/getProvider "SUN")) (.load nil nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn x->keystore<>
"Create a key store from input."
{:tag KeyStore
:arglists '([c pk pwd certs]
[c pk pwd certs options])}
([c pk pwd certs]
(x->keystore<> c pk pwd certs nil))
([cert pk pwd certs options]
(let [{:keys [ktype]
:or {ktype :pkcs12}} options]
(doto (if (= :jks ktype) (jks<>) (pkcs12<>))
(.setKeyEntry (alias<>)
^PrivateKey pk
(i/x->chars pwd)
(c/vargs Certificate
(cons cert (or certs []))))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn asym-key-pair*
"Generate a KeyPair."
{:tag KeyPair
:arglists '([algo]
[algo keylen])}
([algo]
(asym-key-pair* algo nil))
([algo keylen]
{:pre [(string? algo)]}
(let [len (c/num?? keylen 1024)]
(-> (doto
(KeyPairGenerator/getInstance ^String algo *-bc-*)
(.initialize (int len) (u/rand<> true)))
.generateKeyPair))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn asym-key-pair<>
"Generate a public & private key."
{:arglists '([algo]
[algo keylen])}
([algo] (asym-key-pair<> algo nil))
([algo keylen]
(let [kp (asym-key-pair* algo keylen)]
[(.getPublic kp) (.getPrivate kp)])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-encrypted?
"Does content-type indicate *encrypted*?"
{:arglists '([s])}
[s]
{:pre [(string? s)]}
(c/if-some+ [ct (c/lcase s)]
(and (c/embeds? ct "enveloped-data")
(c/embeds? ct "application/x-pkcs7-mime"))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-compressed?
"Does content-type indicate *compressed*?"
{:arglists '([s])}
[s]
{:pre [(string? s)]}
(c/if-some+ [ct (c/lcase s)]
(and (c/embeds? ct "compressed-data")
(c/embeds? ct "application/pkcs7-mime"))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-signed?
"Does content-type indicate *signed*?"
{:arglists '([s])}
[s]
{:pre [(string? s)]}
(c/if-some+ [ct (c/lcase s)]
(or (c/embeds? ct "multipart/signed")
(and (c/embeds? ct "signed-data")
(c/embeds? ct "application/x-pkcs7-mime")))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn assert-jce
"This function should fail if the
non-restricted (unlimited-strength)
jce files are missing in jre-home.
**** Not needed after jdk10+"
{:arglists '([])}
[]
(let
[kgen (doto
(KeyGenerator/getInstance blow-fish)
(.init 256))]
(-> (doto
(Cipher/getInstance blow-fish)
(.init Cipher/ENCRYPT_MODE
(SecretKeySpec. (.. kgen
generateKey
getEncoded) blow-fish)))
(.doFinal (i/x->bytes "yo")))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(assert-jce)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(doto
^MailcapCommandMap
(CommandMap/getDefaultCommandMap)
(.addMailcap (str "application/pkcs7-signature;; "
"x-java-content-handler="
"org.bouncycastle.mail.smime.handlers.pkcs7_signature"))
(.addMailcap (str "application/pkcs7-mime;; "
"x-java-content-handler="
"org.bouncycastle.mail.smime.handlers.pkcs7_mime"))
(.addMailcap (str "application/x-pkcs7-signature;; "
"x-java-content-handler="
"org.bouncycastle.mail.smime.handlers.x_pkcs7_signature"))
(.addMailcap (str "application/x-pkcs7-mime;; "
"x-java-content-handler="
"org.bouncycastle.mail.smime.handlers.x_pkcs7_mime"))
(.addMailcap (str "multipart/signed;; "
"x-java-content-handler="
"org.bouncycastle.mail.smime.handlers.multipart_signed")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro with-BC1
"BC as provider - part of ctor(arg)."
{:arglists '([cz p1]
[cz p1 pv])}
([cz p1]
`(with-BC1 ~cz ~p1 nil))
([cz p1 pv]
`(-> (new ~cz ~p1)
(.setProvider (or ~pv czlab.twisty.core/*-bc-*)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro with-BC
"BC as provider - part of ctor."
{:arglists '([cz]
[cz pv])}
([cz]
`(with-BC ~cz nil))
([cz pv]
`(-> (new ~cz)
(.setProvider (or ~pv czlab.twisty.core/*-bc-*)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- to-xcert
^X509Certificate
[^X509CertificateHolder h]
(-> JcaX509CertificateConverter with-BC (.getCertificate h)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- pemencr<>
^PEMEncryptor
[^chars pwd]
(if-not (empty? pwd)
(-> (->> (rand-nth (seq enc-algos))
(with-BC1 JcePEMEncryptorBuilder ))
(.setSecureRandom (u/rand<>)) (.build pwd))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-jks?
"Is url pointing to a JKS key file?"
{:arglists '([keyUrl])}
[keyUrl]
(some-> keyUrl io/as-url .getFile c/lcase (cs/ends-with? ".jks")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn msg-digest<>
"Get a message digest instance:
MD5, SHA-1, SHA-256, SHA-384, SHA-512."
{:arglists '([algo])
:tag MessageDigest}
[algo]
(-> algo c/kw->str c/ucase
(c/stror "SHA-512")
(MessageDigest/getInstance *-bc-*)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn next-serial
"A random Big Integer."
{:arglists '([])
:tag BigInteger}
[]
(BigInteger/valueOf
(Math/abs (-> (Random. (u/system-time)) .nextLong))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn dbg-provider
"List all BC algos."
{:arglists '([os])}
[os]
(c/try! (.list *-bc-* ^PrintStream os)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- ksinit
"Initialize a keystore."
[^KeyStore store arg pwd2]
(let [[d? inp]
(i/input-stream?? arg)]
(try (.load store
^InputStream inp
(i/x->chars pwd2))
(finally (if d? (i/klose inp)))) store))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmulti pkey-gist<>
"Create a PKeyGist object."
{:arglists '([arg _ _])} (fn [a _ _] (class a)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod pkey-gist<>
PrivateKey
[pkey cert listOfCerts]
(PKeyGist. (c/vec-> listOfCerts) cert pkey))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod pkey-gist<>
KeyStore
[ks alias pwd]
(if-some [e (->> pwd
i/x->chars
KeyStore$PasswordProtection.
(.getEntry ^KeyStore ks
^String alias)
(c/cast? KeyStore$PrivateKeyEntry))]
(pkey-gist<> (.getPrivateKey e)
(.getCertificate e)
(.getCertificateChain e))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn spit-keystore
"Write keystore out to file."
{:tag File
:arglists '([ks fout pwd2])}
[ks fout pwd2]
{:pre [(c/is? KeyStore ks)]}
(let [out (i/baos<>)]
(.store ^KeyStore ks
out (i/x->chars pwd2))
(i/x->file (i/x->bytes out) (io/file fout))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn tcert<>
"Get a trusted certificate from store."
{:tag Certificate
:arglists '([ks alias])}
[ks alias]
{:pre [(c/is? KeyStore ks)]}
(if-some
[e (->> (.getEntry ^KeyStore ks
^String alias nil)
(c/cast? KeyStore$TrustedCertificateEntry))]
(.getTrustedCertificate e)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn filter-entries
"Select entries from the store."
{:arglists '([ks entryType])}
[ks entryType]
{:pre [(c/is? KeyStore ks)]}
(loop [out (c/tvec*)
en (.aliases ^KeyStore ks)]
(if-not (.hasMoreElements en)
(c/persist! out)
(let [n (.nextElement en)]
(recur (if (cond
(= :keys entryType)
(.isKeyEntry ^KeyStore ks n)
(= :certs entryType)
(.isCertificateEntry ^KeyStore ks n))
(conj! out n) out) en)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn pkcs12*
"Create and initialize a PKCS12 key store."
{:tag KeyStore
:arglists '([arg]
[arg pwd2])}
([arg]
(pkcs12* arg nil))
([arg pwd2]
(ksinit (pkcs12<>) arg pwd2)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn jks*
"Create and initialize a JKS key store."
{:tag KeyStore
:arglists '([arg]
[arg pwd2])}
([arg]
(jks* arg nil))
([arg pwd2]
(ksinit (jks<>) arg pwd2)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn spit-pem
"Export object out in PEM format."
{:tag String
:arglists '([obj]
[obj pwd])}
([obj]
(spit-pem obj nil))
([obj pwd]
(c/do-with-str [sw (StringWriter.)]
(let [pw (PEMWriter. sw)
ec (pemencr<> ^chars pwd)]
(.writeObject pw
(if (nil? ec)
(JcaMiscPEMGenerator. obj)
(JcaMiscPEMGenerator. obj ec)))
(.flush pw)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn spit-der
"Export object out in DER format."
{:tag "[B"
:arglists '([obj])}
[obj]
(c/condp?? instance? obj
PrivateKey (.getEncoded ^PrivateKey obj)
PublicKey (.getEncoded ^PublicKey obj)
X509Certificate (.getEncoded ^X509Certificate obj)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn x->certs
"Parse input and generate a cert chain."
{:arglists '([arg])}
[arg]
(let [[d? inp]
(i/input-stream?? arg)]
(try (-> (CertificateFactory/getInstance "X.509")
(.generateCertificates ^InputStream inp))
(finally (if d? (i/klose inp))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn x->cert
"Parse input and generate a cert."
{:arglists '([arg])}
[arg]
(let [[d? inp]
(i/input-stream?? arg)]
(try (-> (CertificateFactory/getInstance "X.509")
(.generateCertificate ^InputStream inp))
(finally (if d? (i/klose inp))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn x->pkey
"Parse input and generate a PKeyGist object."
{:arglists '([arg pwd]
[arg pwd pwdStore])}
([arg pwd]
(x->pkey arg pwd nil))
([arg pwd pwdStore]
(let [ks (pkcs12* arg pwdStore)]
(c/if-some+
[n (c/_1
(filter-entries ks :keys))]
(pkey-gist<> ks n pwd)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn easy-policy<>
"Enables all permissions."
{:tag Policy
:arglists '([])}
[]
(proxy [Policy] []
(getPermissions [cs]
(doto (Permissions.) (.add (AllPermission.))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn gen-mac
"Create Message Auth Code."
{:tag String
:arglists '([skey data]
[skey data algo])}
([skey data]
(gen-mac skey data nil))
([skey data algo]
{:pre [(some? skey) (some? data)]}
(let
[algo (-> algo c/kw->str
c/ucase (c/stror def-mac))
flag (c/mu-long)
mac (Mac/getInstance algo *-bc-*)]
(->> (SecretKeySpec.
(i/x->bytes skey) algo) (.init mac))
(i/chunk-read-stream data
(fn [buf offset len end?]
(when (pos? len)
(c/mu-long flag + len)
(.update mac buf offset len))))
(str (some->
(if (c/spos?
(c/mu-long flag)) (.doFinal mac)) Hex/toHexString)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gen-digest*
[data algo]
(let [flag (c/mu-long)
d (msg-digest<> algo)]
(i/chunk-read-stream data
(fn [buf offset len end?]
(when (pos? len)
(c/mu-long flag + len)
(.update d buf offset len))))
(if (c/spos? (c/mu-long flag)) (.digest d))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn gen-digest
"Create Message Digest."
{:tag String
:arglists '([data]
[data options])}
([data]
(gen-digest data nil))
([data options]
(let [{:keys [algo fmt]
:or {fmt :base64}} options
x (gen-digest* data algo)]
(str
(if x
(if (= fmt :hex)
(Hex/toHexString x)
(Base64/toBase64String x)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- scert<>
"Sign a cert, issuer is self is nil."
([args]
(scert<> nil args))
([{^PrivateKey pkey :pkey
^X509Certificate rootc :cert :as issuer}
{:keys [^String dn algo
start end
validity keylen style]
:or {style "RSA" keylen 1024} :as args}]
(let [^Date end (or end (-> (or validity 12)
d/add-months .getTime))
^Date start (or start (u/date<>))
subject (X500Principal. dn)
[^PublicKey pub ^PrivateKey prv]
(asym-key-pair<> (or (some->
pkey .getAlgorithm) style) keylen)
[^JcaX509ExtensionUtils exu bdr]
(if issuer
[(JcaX509ExtensionUtils.)
(JcaX509v3CertificateBuilder.
rootc (next-serial) start end subject pub)]
[nil (JcaX509v1CertificateBuilder.
(X500Principal. dn)
(next-serial) start end subject pub)])
cs (->> (if issuer pkey prv)
(.build (with-BC1 JcaContentSignerBuilder algo *-bc-*)))]
(if issuer
(doto ^JcaX509v3CertificateBuilder bdr
(.addExtension
X509Extension/authorityKeyIdentifier false
(.createAuthorityKeyIdentifier exu rootc))
(.addExtension
X509Extension/subjectKeyIdentifier false
(.createSubjectKeyIdentifier exu pub))))
(try
[prv
(doto (to-xcert (if issuer
(.build ^JcaX509v3CertificateBuilder bdr cs)
(.build ^JcaX509v1CertificateBuilder bdr cs)))
(.checkValidity (u/date<>))
(.verify (if issuer (.getPublicKey rootc) pub)))]
(finally
(c/debug (str "signed-cert: dn= %s "
",algo= %s,start= %s" ",end=%s") dn algo start end))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn gen-cert
"Create a Certificate from the DN."
{:tag KeyStore
:arglists '([dnStr pwd args]
[dnStr issuer pwd args])}
([dnStr pwd args]
(gen-cert dnStr nil pwd args))
([dnStr issuer pwd args]
(let [{:keys [ktype]} args
;; JKS uses SUN and hence needs to use DSA
[pkey cert]
(scert<> issuer
(merge (if (not= :jks ktype)
{:algo def-algo}
{:style "DSA" :algo "SHA1withDSA"})
{:dn dnStr} args))]
(x->keystore<> cert pkey pwd
(if issuer
(c/vec-> (:chain issuer)) []) args))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn csreq<>
"Generate a Certificate Signing Request."
{:arglists '([dnStr]
[dnStr keylen]
[dnStr keylen pwd])}
([dnStr keylen]
(csreq<> dnStr keylen nil))
([dnStr]
(csreq<> dnStr 1024 nil))
([dnStr keylen pwd]
{:pre [(string? dnStr)]}
(let [csb (with-BC1 JcaContentSignerBuilder def-algo)
len (c/num?? keylen 1024)
[pu pv] (asym-key-pair<> "RSA" len)
rbr (JcaPKCS10CertificationRequestBuilder.
(X500Principal. ^String dnStr) ^PublicKey pu)
rc (->> (.build csb pv) (.build rbr))]
(c/debug "csr: dnStr= %s, key-len= %d" dnStr len)
[(spit-pem rc)
(spit-pem pv pwd)])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- pemparse2
[obj ^JcaPEMKeyConverter pc]
(condp = (class obj)
PEMKeyPair
(.getKeyPair pc ^PEMKeyPair obj)
KeyPair obj
PrivateKeyInfo
(.getPrivateKey pc ^PrivateKeyInfo obj)
ContentInfo obj
X509AttributeCertificateHolder
(to-xcert obj)
X509TrustedCertificateBlock
(-> ^X509TrustedCertificateBlock obj .getCertificateHolder to-xcert)
SubjectPublicKeyInfo
(.getPublicKey pc ^SubjectPublicKeyInfo obj)
X509CertificateHolder
(to-xcert obj)
X509CRLHolder obj
PKCS10CertificationRequest obj
obj))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- pemparse
"PEM encoded streams may contain
X509 certificates,
PKCS8 encoded keys and PKCS7 objs.
PKCS7 objs => a CMS ContentInfo object.
PubKeys => well formed SubjectPublicKeyInfo objs
PrvKeys => well formed PrivateKeyInfo obj.
=> PEMKeyPair if contains both private and public key.
CRLs, Certificates,
PKCS#10 requests,
and Attribute Certificates => appropriate holder class"
[^InputStream inp ^chars pwd]
(c/wo* [rdr (InputStreamReader. inp)]
(let [obj (-> (PEMParser. rdr) .readObject)
pc (with-BC JcaPEMKeyConverter)
dc (.build (JcePEMDecryptorProviderBuilder.) pwd)
dp (.build (BcPKCS12PBEInputDecryptorProviderBuilder.) pwd)]
(pemparse2 (condp = (class obj)
PKCS8EncryptedPrivateKeyInfo
(-> ^PKCS8EncryptedPrivateKeyInfo obj
(.decryptPrivateKeyInfo dp))
PEMEncryptedKeyPair
(->> (-> ^PEMEncryptedKeyPair obj
(.decryptKeyPair dc))
(.getKeyPair pc))
obj)
pc))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-cert-valid?
"Test if cert is valid?"
{:arglists '([c])}
[c]
(c/try! (.checkValidity ^X509Certificate c (u/date<>)) true))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn cert-gist<>
"Create a gist from the cert."
{:arglists '([c])}
[c]
{:pre [(c/is? X509Certificate c)]}
(let [x509 (c/cast? X509Certificate c)]
(CertGist. (.getIssuerX500Principal x509)
(.getSubjectX500Principal x509)
(.getNotBefore x509)
(.getNotAfter x509))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn spit-pkcs7
"Generate PKCS7 from the private-key."
{:tag "[B"
:arglists '([pkeyGist])}
[pkeyGist]
(let [xxx (CMSProcessableByteArray. (i/x->bytes "?"))
gen (CMSSignedDataGenerator.)
{:keys [^X509Certificate cert
^PrivateKey pkey chain]} pkeyGist
bdr (JcaSignerInfoGeneratorBuilder.
(.build (with-BC JcaDigestCalculatorProviderBuilder)))
;; "SHA1withRSA"
cs (.build (with-BC1 JcaContentSignerBuilder sha-512-rsa) pkey)]
(.addSignerInfoGenerator gen (.build bdr cs cert))
(.addCertificates gen (JcaCertStore. chain))
(.getEncoded (.generate gen xxx))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn session<>
"Create a new java-mail session."
{:tag Session
:arglists '([]
[user]
[user pwd])}
([user]
(session<> user nil))
([]
(session<> nil nil))
([user pwd]
(Session/getInstance
(System/getProperties)
(if (c/hgl? user)
(->> (if pwd (i/x->str pwd))
(DefaultAuthenticator. ^String user))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn mime-msg<>
"Create a new MIME Message."
{:tag MimeMessage
:arglists '([]
[inp]
[user pwd]
[user pwd inp])}
([^String user pwd ^InputStream inp]
(let [s (session<> user pwd)]
(if (nil? inp)
(MimeMessage. s)
(MimeMessage. s inp))))
([inp]
(mime-msg<> "" nil inp))
([]
(mime-msg<> "" nil nil))
([user pwd]
(mime-msg<> user pwd nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- is-data-xxx?
[obj tst?]
(if-some [[d? inp] (i/input-stream?? obj)]
(try (tst? (.getContentType
(mime-msg<> "" nil inp)))
(finally (if d? (i/klose inp))))
(condp instance? obj
Multipart (tst? (.getContentType (c/cast? Multipart obj)))
BodyPart (tst? (.getContentType (c/cast? BodyPart obj)))
(u/throw-IOE "Invalid content: %s." (u/gczn obj)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-data-encrypted?
"Test if object is *encrypted*?"
{:arglists '([obj])}
[obj]
(is-data-xxx? obj is-encrypted?))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-data-signed?
"Test if object is *signed*?"
{:arglists '([obj])}
[obj]
(is-data-xxx? obj is-signed?))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-data-compressed?
"Test if object is *compressed*?"
{:arglists '([obj])}
[obj]
(is-data-xxx? obj is-compressed?))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn charset??
"Charset from content-type."
{:tag String
:arglists '([cType]
[cType dft])}
([cType]
(charset?? cType nil))
([cType dft]
(c/stror
(if (c/hgl? cType)
(c/try! (-> (ContentType. ^String cType)
(.getParameter "charset")
MimeUtility/javaCharset )))
(if (c/hgl? dft)
(MimeUtility/javaCharset ^String dft)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
| true | ;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; Copyright © 2013-2022, PI:NAME:<NAME>END_PI. All rights reserved.
(ns czlab.twisty.core
"Crypto functions."
(:require [clojure.java.io :as io]
[clojure.string :as cs]
[czlab.basal.io :as i]
[czlab.basal.util :as u]
[czlab.basal.core :as c]
[czlab.basal.dates :as d])
(:import [javax.activation DataHandler CommandMap MailcapCommandMap]
[javax.mail BodyPart MessagingException Multipart Session]
[org.bouncycastle.jce.provider BouncyCastleProvider]
[org.apache.commons.mail DefaultAuthenticator]
[javax.net.ssl X509TrustManager TrustManager]
[org.bouncycastle.util.encoders Hex Base64]
[org.bouncycastle.asn1.pkcs PrivateKeyInfo]
[org.bouncycastle.asn1 ASN1EncodableVector]
[org.bouncycastle.asn1.x500 X500Name]
[clojure.lang APersistentVector]
[org.bouncycastle.pkcs.jcajce
JcaPKCS10CertificationRequestBuilder]
[org.bouncycastle.pkcs.bc
BcPKCS12PBEInputDecryptorProviderBuilder]
[org.bouncycastle.operator
DigestCalculatorProvider
ContentSigner
OperatorCreationException]
[org.bouncycastle.asn1.x509
X509Extension
SubjectPublicKeyInfo]
[org.bouncycastle.asn1.cms
AttributeTable
ContentInfo
IssuerAndSerialNumber]
[org.bouncycastle.pkcs
PKCS8EncryptedPrivateKeyInfo]
[org.bouncycastle.openssl
X509TrustedCertificateBlock
PEMKeyPair
PEMEncryptedKeyPair]
[org.bouncycastle.cert
X509CRLHolder
X509CertificateHolder
X509AttributeCertificateHolder]
[org.bouncycastle.openssl.jcajce
JcePEMDecryptorProviderBuilder
JcePEMEncryptorBuilder
JcaMiscPEMGenerator
JcaPEMKeyConverter]
[java.security
Policy
PermissionCollection
Permissions
KeyPair
KeyPairGenerator
KeyStore
MessageDigest
PrivateKey
Provider
PublicKey
AllPermission
SecureRandom
Security
KeyStore$PasswordProtection
GeneralSecurityException
KeyStore$PrivateKeyEntry
KeyStore$TrustedCertificateEntry]
[java.security.cert
CertificateFactory
Certificate
X509Certificate]
[org.bouncycastle.cms
CMSSignedDataGenerator
CMSProcessableFile
CMSProcessable
CMSSignedGenerator
CMSProcessableByteArray]
[org.bouncycastle.cms.jcajce
JcaSignerInfoGeneratorBuilder]
[org.bouncycastle.operator.jcajce
JcaContentSignerBuilder
JcaDigestCalculatorProviderBuilder]
[javax.security.auth.x500 X500Principal]
[javax.crypto.spec SecretKeySpec]
[org.bouncycastle.cert.jcajce
JcaCertStore
JcaX509CertificateConverter
JcaX509ExtensionUtils
JcaX509v1CertificateBuilder
JcaX509v3CertificateBuilder]
[org.bouncycastle.openssl
PEMWriter
PEMParser
PEMEncryptor]
[org.bouncycastle.pkcs
PKCS10CertificationRequest
PKCS10CertificationRequestBuilder]
[javax.crypto
Mac
SecretKey
Cipher
KeyGenerator]
[java.io
StringWriter
PrintStream
File
InputStream
IOException
FileInputStream
InputStreamReader
ByteArrayInputStream
ByteArrayOutputStream]
[java.math BigInteger]
[java.net URL]
[java.util Random Date]
[javax.mail.internet
ContentType
MimeBodyPart
MimeMessage
MimeMultipart
MimeUtility]
[java.lang Math]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* true)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/def- ^String def-algo "SHA1WithRSAEncryption")
(c/def- ^String def-mac "HmacSHA512")
(c/def- enc-algos
#{"AES-128-CBC" "AES-128-CFB" "AES-128-ECB" "AES-128-OFB"
"AES-192-CBC" "AES-192-CFB" "AES-192-ECB" "AES-192-OFB"
"AES-256-CBC" "AES-256-CFB" "AES-256-ECB" "AES-256-OFB"
"BF-CBC" "BF-CFB" "BF-ECB" "BF-OFB"
"DES-CBC" "DES-CFB" "DES-ECB" "DES-OFB"
"DES-EDE" "DES-EDE-CBC" "DES-EDE-CFB" "DES-EDE-ECB"
"DES-EDE-OFB" "DES-EDE3" "DES-EDE3-CBC" "DES-EDE3-CFB"
"DES-EDE3-ECB" "DES-EDE3-OFB"
"RC2-CBC" "RC2-CFB" "RC2-ECB" "RC2-OFB"
"RC2-40-CBC" "RC2-64-CBC" })
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^String sha-512-rsa "SHA512withRSA")
(def ^String sha-256-rsa "SHA256withRSA")
(def ^String sha1-rsa "SHA1withRSA")
(def ^String md5-rsa "MD5withRSA")
(def ^String blow-fish "BlowFish")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^{:dynamic true
:tag Provider} *-bc-* (BouncyCastleProvider.))
(Security/addProvider *-bc-*)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/defenum exform 1 pem der)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord CertGist [issuer subj notBefore notAfter])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord PKeyGist [chain cert pkey])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn alias<>
"A new random name."
{:tag String
:arglists '([])}
[]
(format "%s#%04d" (-> (u/jid<>) (subs 0 6)) (u/seqint)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn pkcs12<>
"Create a PKCS12 key store."
{:tag KeyStore
:arglists '([])}
[]
(doto
(KeyStore/getInstance "PKCS12" *-bc-*) (.load nil nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn jks<>
"Create a JKS key store."
{:tag KeyStore
:arglists '([])}
[]
(doto
(KeyStore/getInstance
"JKS" (Security/getProvider "SUN")) (.load nil nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn x->keystore<>
"Create a key store from input."
{:tag KeyStore
:arglists '([c pk pwd certs]
[c pk pwd certs options])}
([c pk pwd certs]
(x->keystore<> c pk pwd certs nil))
([cert pk pwd certs options]
(let [{:keys [ktype]
:or {ktype :pkcs12}} options]
(doto (if (= :jks ktype) (jks<>) (pkcs12<>))
(.setKeyEntry (alias<>)
^PrivateKey pk
(i/x->chars pwd)
(c/vargs Certificate
(cons cert (or certs []))))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn asym-key-pair*
"Generate a KeyPair."
{:tag KeyPair
:arglists '([algo]
[algo keylen])}
([algo]
(asym-key-pair* algo nil))
([algo keylen]
{:pre [(string? algo)]}
(let [len (c/num?? keylen 1024)]
(-> (doto
(KeyPairGenerator/getInstance ^String algo *-bc-*)
(.initialize (int len) (u/rand<> true)))
.generateKeyPair))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn asym-key-pair<>
"Generate a public & private key."
{:arglists '([algo]
[algo keylen])}
([algo] (asym-key-pair<> algo nil))
([algo keylen]
(let [kp (asym-key-pair* algo keylen)]
[(.getPublic kp) (.getPrivate kp)])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-encrypted?
"Does content-type indicate *encrypted*?"
{:arglists '([s])}
[s]
{:pre [(string? s)]}
(c/if-some+ [ct (c/lcase s)]
(and (c/embeds? ct "enveloped-data")
(c/embeds? ct "application/x-pkcs7-mime"))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-compressed?
"Does content-type indicate *compressed*?"
{:arglists '([s])}
[s]
{:pre [(string? s)]}
(c/if-some+ [ct (c/lcase s)]
(and (c/embeds? ct "compressed-data")
(c/embeds? ct "application/pkcs7-mime"))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-signed?
"Does content-type indicate *signed*?"
{:arglists '([s])}
[s]
{:pre [(string? s)]}
(c/if-some+ [ct (c/lcase s)]
(or (c/embeds? ct "multipart/signed")
(and (c/embeds? ct "signed-data")
(c/embeds? ct "application/x-pkcs7-mime")))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn assert-jce
"This function should fail if the
non-restricted (unlimited-strength)
jce files are missing in jre-home.
**** Not needed after jdk10+"
{:arglists '([])}
[]
(let
[kgen (doto
(KeyGenerator/getInstance blow-fish)
(.init 256))]
(-> (doto
(Cipher/getInstance blow-fish)
(.init Cipher/ENCRYPT_MODE
(SecretKeySpec. (.. kgen
generateKey
getEncoded) blow-fish)))
(.doFinal (i/x->bytes "yo")))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(assert-jce)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(doto
^MailcapCommandMap
(CommandMap/getDefaultCommandMap)
(.addMailcap (str "application/pkcs7-signature;; "
"x-java-content-handler="
"org.bouncycastle.mail.smime.handlers.pkcs7_signature"))
(.addMailcap (str "application/pkcs7-mime;; "
"x-java-content-handler="
"org.bouncycastle.mail.smime.handlers.pkcs7_mime"))
(.addMailcap (str "application/x-pkcs7-signature;; "
"x-java-content-handler="
"org.bouncycastle.mail.smime.handlers.x_pkcs7_signature"))
(.addMailcap (str "application/x-pkcs7-mime;; "
"x-java-content-handler="
"org.bouncycastle.mail.smime.handlers.x_pkcs7_mime"))
(.addMailcap (str "multipart/signed;; "
"x-java-content-handler="
"org.bouncycastle.mail.smime.handlers.multipart_signed")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro with-BC1
"BC as provider - part of ctor(arg)."
{:arglists '([cz p1]
[cz p1 pv])}
([cz p1]
`(with-BC1 ~cz ~p1 nil))
([cz p1 pv]
`(-> (new ~cz ~p1)
(.setProvider (or ~pv czlab.twisty.core/*-bc-*)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmacro with-BC
"BC as provider - part of ctor."
{:arglists '([cz]
[cz pv])}
([cz]
`(with-BC ~cz nil))
([cz pv]
`(-> (new ~cz)
(.setProvider (or ~pv czlab.twisty.core/*-bc-*)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- to-xcert
^X509Certificate
[^X509CertificateHolder h]
(-> JcaX509CertificateConverter with-BC (.getCertificate h)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- pemencr<>
^PEMEncryptor
[^chars pwd]
(if-not (empty? pwd)
(-> (->> (rand-nth (seq enc-algos))
(with-BC1 JcePEMEncryptorBuilder ))
(.setSecureRandom (u/rand<>)) (.build pwd))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-jks?
"Is url pointing to a JKS key file?"
{:arglists '([keyUrl])}
[keyUrl]
(some-> keyUrl io/as-url .getFile c/lcase (cs/ends-with? ".jks")))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn msg-digest<>
"Get a message digest instance:
MD5, SHA-1, SHA-256, SHA-384, SHA-512."
{:arglists '([algo])
:tag MessageDigest}
[algo]
(-> algo c/kw->str c/ucase
(c/stror "SHA-512")
(MessageDigest/getInstance *-bc-*)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn next-serial
"A random Big Integer."
{:arglists '([])
:tag BigInteger}
[]
(BigInteger/valueOf
(Math/abs (-> (Random. (u/system-time)) .nextLong))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn dbg-provider
"List all BC algos."
{:arglists '([os])}
[os]
(c/try! (.list *-bc-* ^PrintStream os)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- ksinit
"Initialize a keystore."
[^KeyStore store arg pwd2]
(let [[d? inp]
(i/input-stream?? arg)]
(try (.load store
^InputStream inp
(i/x->chars pwd2))
(finally (if d? (i/klose inp)))) store))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmulti pkey-gist<>
"Create a PKeyGist object."
{:arglists '([arg _ _])} (fn [a _ _] (class a)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod pkey-gist<>
PrivateKey
[pkey cert listOfCerts]
(PKeyGist. (c/vec-> listOfCerts) cert pkey))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defmethod pkey-gist<>
KeyStore
[ks alias pwd]
(if-some [e (->> pwd
i/x->chars
KeyStore$PasswordProtection.
(.getEntry ^KeyStore ks
^String alias)
(c/cast? KeyStore$PrivateKeyEntry))]
(pkey-gist<> (.getPrivateKey e)
(.getCertificate e)
(.getCertificateChain e))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn spit-keystore
"Write keystore out to file."
{:tag File
:arglists '([ks fout pwd2])}
[ks fout pwd2]
{:pre [(c/is? KeyStore ks)]}
(let [out (i/baos<>)]
(.store ^KeyStore ks
out (i/x->chars pwd2))
(i/x->file (i/x->bytes out) (io/file fout))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn tcert<>
"Get a trusted certificate from store."
{:tag Certificate
:arglists '([ks alias])}
[ks alias]
{:pre [(c/is? KeyStore ks)]}
(if-some
[e (->> (.getEntry ^KeyStore ks
^String alias nil)
(c/cast? KeyStore$TrustedCertificateEntry))]
(.getTrustedCertificate e)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn filter-entries
"Select entries from the store."
{:arglists '([ks entryType])}
[ks entryType]
{:pre [(c/is? KeyStore ks)]}
(loop [out (c/tvec*)
en (.aliases ^KeyStore ks)]
(if-not (.hasMoreElements en)
(c/persist! out)
(let [n (.nextElement en)]
(recur (if (cond
(= :keys entryType)
(.isKeyEntry ^KeyStore ks n)
(= :certs entryType)
(.isCertificateEntry ^KeyStore ks n))
(conj! out n) out) en)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn pkcs12*
"Create and initialize a PKCS12 key store."
{:tag KeyStore
:arglists '([arg]
[arg pwd2])}
([arg]
(pkcs12* arg nil))
([arg pwd2]
(ksinit (pkcs12<>) arg pwd2)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn jks*
"Create and initialize a JKS key store."
{:tag KeyStore
:arglists '([arg]
[arg pwd2])}
([arg]
(jks* arg nil))
([arg pwd2]
(ksinit (jks<>) arg pwd2)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn spit-pem
"Export object out in PEM format."
{:tag String
:arglists '([obj]
[obj pwd])}
([obj]
(spit-pem obj nil))
([obj pwd]
(c/do-with-str [sw (StringWriter.)]
(let [pw (PEMWriter. sw)
ec (pemencr<> ^chars pwd)]
(.writeObject pw
(if (nil? ec)
(JcaMiscPEMGenerator. obj)
(JcaMiscPEMGenerator. obj ec)))
(.flush pw)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn spit-der
"Export object out in DER format."
{:tag "[B"
:arglists '([obj])}
[obj]
(c/condp?? instance? obj
PrivateKey (.getEncoded ^PrivateKey obj)
PublicKey (.getEncoded ^PublicKey obj)
X509Certificate (.getEncoded ^X509Certificate obj)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn x->certs
"Parse input and generate a cert chain."
{:arglists '([arg])}
[arg]
(let [[d? inp]
(i/input-stream?? arg)]
(try (-> (CertificateFactory/getInstance "X.509")
(.generateCertificates ^InputStream inp))
(finally (if d? (i/klose inp))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn x->cert
"Parse input and generate a cert."
{:arglists '([arg])}
[arg]
(let [[d? inp]
(i/input-stream?? arg)]
(try (-> (CertificateFactory/getInstance "X.509")
(.generateCertificate ^InputStream inp))
(finally (if d? (i/klose inp))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn x->pkey
"Parse input and generate a PKeyGist object."
{:arglists '([arg pwd]
[arg pwd pwdStore])}
([arg pwd]
(x->pkey arg pwd nil))
([arg pwd pwdStore]
(let [ks (pkcs12* arg pwdStore)]
(c/if-some+
[n (c/_1
(filter-entries ks :keys))]
(pkey-gist<> ks n pwd)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn easy-policy<>
"Enables all permissions."
{:tag Policy
:arglists '([])}
[]
(proxy [Policy] []
(getPermissions [cs]
(doto (Permissions.) (.add (AllPermission.))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn gen-mac
"Create Message Auth Code."
{:tag String
:arglists '([skey data]
[skey data algo])}
([skey data]
(gen-mac skey data nil))
([skey data algo]
{:pre [(some? skey) (some? data)]}
(let
[algo (-> algo c/kw->str
c/ucase (c/stror def-mac))
flag (c/mu-long)
mac (Mac/getInstance algo *-bc-*)]
(->> (SecretKeySpec.
(i/x->bytes skey) algo) (.init mac))
(i/chunk-read-stream data
(fn [buf offset len end?]
(when (pos? len)
(c/mu-long flag + len)
(.update mac buf offset len))))
(str (some->
(if (c/spos?
(c/mu-long flag)) (.doFinal mac)) Hex/toHexString)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- gen-digest*
[data algo]
(let [flag (c/mu-long)
d (msg-digest<> algo)]
(i/chunk-read-stream data
(fn [buf offset len end?]
(when (pos? len)
(c/mu-long flag + len)
(.update d buf offset len))))
(if (c/spos? (c/mu-long flag)) (.digest d))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn gen-digest
"Create Message Digest."
{:tag String
:arglists '([data]
[data options])}
([data]
(gen-digest data nil))
([data options]
(let [{:keys [algo fmt]
:or {fmt :base64}} options
x (gen-digest* data algo)]
(str
(if x
(if (= fmt :hex)
(Hex/toHexString x)
(Base64/toBase64String x)))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- scert<>
"Sign a cert, issuer is self is nil."
([args]
(scert<> nil args))
([{^PrivateKey pkey :pkey
^X509Certificate rootc :cert :as issuer}
{:keys [^String dn algo
start end
validity keylen style]
:or {style "RSA" keylen 1024} :as args}]
(let [^Date end (or end (-> (or validity 12)
d/add-months .getTime))
^Date start (or start (u/date<>))
subject (X500Principal. dn)
[^PublicKey pub ^PrivateKey prv]
(asym-key-pair<> (or (some->
pkey .getAlgorithm) style) keylen)
[^JcaX509ExtensionUtils exu bdr]
(if issuer
[(JcaX509ExtensionUtils.)
(JcaX509v3CertificateBuilder.
rootc (next-serial) start end subject pub)]
[nil (JcaX509v1CertificateBuilder.
(X500Principal. dn)
(next-serial) start end subject pub)])
cs (->> (if issuer pkey prv)
(.build (with-BC1 JcaContentSignerBuilder algo *-bc-*)))]
(if issuer
(doto ^JcaX509v3CertificateBuilder bdr
(.addExtension
X509Extension/authorityKeyIdentifier false
(.createAuthorityKeyIdentifier exu rootc))
(.addExtension
X509Extension/subjectKeyIdentifier false
(.createSubjectKeyIdentifier exu pub))))
(try
[prv
(doto (to-xcert (if issuer
(.build ^JcaX509v3CertificateBuilder bdr cs)
(.build ^JcaX509v1CertificateBuilder bdr cs)))
(.checkValidity (u/date<>))
(.verify (if issuer (.getPublicKey rootc) pub)))]
(finally
(c/debug (str "signed-cert: dn= %s "
",algo= %s,start= %s" ",end=%s") dn algo start end))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn gen-cert
"Create a Certificate from the DN."
{:tag KeyStore
:arglists '([dnStr pwd args]
[dnStr issuer pwd args])}
([dnStr pwd args]
(gen-cert dnStr nil pwd args))
([dnStr issuer pwd args]
(let [{:keys [ktype]} args
;; JKS uses SUN and hence needs to use DSA
[pkey cert]
(scert<> issuer
(merge (if (not= :jks ktype)
{:algo def-algo}
{:style "DSA" :algo "SHA1withDSA"})
{:dn dnStr} args))]
(x->keystore<> cert pkey pwd
(if issuer
(c/vec-> (:chain issuer)) []) args))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn csreq<>
"Generate a Certificate Signing Request."
{:arglists '([dnStr]
[dnStr keylen]
[dnStr keylen pwd])}
([dnStr keylen]
(csreq<> dnStr keylen nil))
([dnStr]
(csreq<> dnStr 1024 nil))
([dnStr keylen pwd]
{:pre [(string? dnStr)]}
(let [csb (with-BC1 JcaContentSignerBuilder def-algo)
len (c/num?? keylen 1024)
[pu pv] (asym-key-pair<> "RSA" len)
rbr (JcaPKCS10CertificationRequestBuilder.
(X500Principal. ^String dnStr) ^PublicKey pu)
rc (->> (.build csb pv) (.build rbr))]
(c/debug "csr: dnStr= %s, key-len= %d" dnStr len)
[(spit-pem rc)
(spit-pem pv pwd)])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- pemparse2
[obj ^JcaPEMKeyConverter pc]
(condp = (class obj)
PEMKeyPair
(.getKeyPair pc ^PEMKeyPair obj)
KeyPair obj
PrivateKeyInfo
(.getPrivateKey pc ^PrivateKeyInfo obj)
ContentInfo obj
X509AttributeCertificateHolder
(to-xcert obj)
X509TrustedCertificateBlock
(-> ^X509TrustedCertificateBlock obj .getCertificateHolder to-xcert)
SubjectPublicKeyInfo
(.getPublicKey pc ^SubjectPublicKeyInfo obj)
X509CertificateHolder
(to-xcert obj)
X509CRLHolder obj
PKCS10CertificationRequest obj
obj))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- pemparse
"PEM encoded streams may contain
X509 certificates,
PKCS8 encoded keys and PKCS7 objs.
PKCS7 objs => a CMS ContentInfo object.
PubKeys => well formed SubjectPublicKeyInfo objs
PrvKeys => well formed PrivateKeyInfo obj.
=> PEMKeyPair if contains both private and public key.
CRLs, Certificates,
PKCS#10 requests,
and Attribute Certificates => appropriate holder class"
[^InputStream inp ^chars pwd]
(c/wo* [rdr (InputStreamReader. inp)]
(let [obj (-> (PEMParser. rdr) .readObject)
pc (with-BC JcaPEMKeyConverter)
dc (.build (JcePEMDecryptorProviderBuilder.) pwd)
dp (.build (BcPKCS12PBEInputDecryptorProviderBuilder.) pwd)]
(pemparse2 (condp = (class obj)
PKCS8EncryptedPrivateKeyInfo
(-> ^PKCS8EncryptedPrivateKeyInfo obj
(.decryptPrivateKeyInfo dp))
PEMEncryptedKeyPair
(->> (-> ^PEMEncryptedKeyPair obj
(.decryptKeyPair dc))
(.getKeyPair pc))
obj)
pc))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-cert-valid?
"Test if cert is valid?"
{:arglists '([c])}
[c]
(c/try! (.checkValidity ^X509Certificate c (u/date<>)) true))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn cert-gist<>
"Create a gist from the cert."
{:arglists '([c])}
[c]
{:pre [(c/is? X509Certificate c)]}
(let [x509 (c/cast? X509Certificate c)]
(CertGist. (.getIssuerX500Principal x509)
(.getSubjectX500Principal x509)
(.getNotBefore x509)
(.getNotAfter x509))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn spit-pkcs7
"Generate PKCS7 from the private-key."
{:tag "[B"
:arglists '([pkeyGist])}
[pkeyGist]
(let [xxx (CMSProcessableByteArray. (i/x->bytes "?"))
gen (CMSSignedDataGenerator.)
{:keys [^X509Certificate cert
^PrivateKey pkey chain]} pkeyGist
bdr (JcaSignerInfoGeneratorBuilder.
(.build (with-BC JcaDigestCalculatorProviderBuilder)))
;; "SHA1withRSA"
cs (.build (with-BC1 JcaContentSignerBuilder sha-512-rsa) pkey)]
(.addSignerInfoGenerator gen (.build bdr cs cert))
(.addCertificates gen (JcaCertStore. chain))
(.getEncoded (.generate gen xxx))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn session<>
"Create a new java-mail session."
{:tag Session
:arglists '([]
[user]
[user pwd])}
([user]
(session<> user nil))
([]
(session<> nil nil))
([user pwd]
(Session/getInstance
(System/getProperties)
(if (c/hgl? user)
(->> (if pwd (i/x->str pwd))
(DefaultAuthenticator. ^String user))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn mime-msg<>
"Create a new MIME Message."
{:tag MimeMessage
:arglists '([]
[inp]
[user pwd]
[user pwd inp])}
([^String user pwd ^InputStream inp]
(let [s (session<> user pwd)]
(if (nil? inp)
(MimeMessage. s)
(MimeMessage. s inp))))
([inp]
(mime-msg<> "" nil inp))
([]
(mime-msg<> "" nil nil))
([user pwd]
(mime-msg<> user pwd nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- is-data-xxx?
[obj tst?]
(if-some [[d? inp] (i/input-stream?? obj)]
(try (tst? (.getContentType
(mime-msg<> "" nil inp)))
(finally (if d? (i/klose inp))))
(condp instance? obj
Multipart (tst? (.getContentType (c/cast? Multipart obj)))
BodyPart (tst? (.getContentType (c/cast? BodyPart obj)))
(u/throw-IOE "Invalid content: %s." (u/gczn obj)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-data-encrypted?
"Test if object is *encrypted*?"
{:arglists '([obj])}
[obj]
(is-data-xxx? obj is-encrypted?))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-data-signed?
"Test if object is *signed*?"
{:arglists '([obj])}
[obj]
(is-data-xxx? obj is-signed?))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-data-compressed?
"Test if object is *compressed*?"
{:arglists '([obj])}
[obj]
(is-data-xxx? obj is-compressed?))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn charset??
"Charset from content-type."
{:tag String
:arglists '([cType]
[cType dft])}
([cType]
(charset?? cType nil))
([cType dft]
(c/stror
(if (c/hgl? cType)
(c/try! (-> (ContentType. ^String cType)
(.getParameter "charset")
MimeUtility/javaCharset )))
(if (c/hgl? dft)
(MimeUtility/javaCharset ^String dft)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
|
[
{
"context": "afire.samples)\n\n; Adapted from https://github.com/jonase/learndatalogtoday/blob/master/resources/db/data.e",
"end": 63,
"score": 0.9995688199996948,
"start": 57,
"tag": "USERNAME",
"value": "jonase"
},
{
"context": "ue}})\n(def data\n [{:db/id -100\n :person/name \"James Cameron\"\n :person/born \"1954-08-16\"}\n\n {:db/id -101\n",
"end": 629,
"score": 0.9998782873153687,
"start": 616,
"tag": "NAME",
"value": "James Cameron"
},
{
"context": " \"1954-08-16\"}\n\n {:db/id -101\n :person/name \"Arnold Schwarzenegger\"\n :person/born \"1947-07-30\"}\n\n {:db/id -102\n",
"end": 718,
"score": 0.999886155128479,
"start": 697,
"tag": "NAME",
"value": "Arnold Schwarzenegger"
},
{
"context": " \"1947-07-30\"}\n\n {:db/id -102\n :person/name \"Linda Hamilton\"\n :person/born \"1956-09-26\"}\n\n {:db/id -103\n",
"end": 800,
"score": 0.9998646974563599,
"start": 786,
"tag": "NAME",
"value": "Linda Hamilton"
},
{
"context": " \"1956-09-26\"}\n\n {:db/id -103\n :person/name \"Michael Biehn\"\n :person/born \"1956-07-31\"}\n\n {:db/id -104\n",
"end": 881,
"score": 0.9998655319213867,
"start": 868,
"tag": "NAME",
"value": "Michael Biehn"
},
{
"context": " \"1956-07-31\"}\n\n {:db/id -104\n :person/name \"Ted Kotcheff\"\n :person/born \"1931-04-07\"}\n\n {:db/id -105\n",
"end": 961,
"score": 0.9998593926429749,
"start": 949,
"tag": "NAME",
"value": "Ted Kotcheff"
},
{
"context": " \"1931-04-07\"}\n\n {:db/id -105\n :person/name \"Sylvester Stallone\"\n :person/born \"1946-07-06\"}\n\n {:db/id -106\n",
"end": 1047,
"score": 0.9998681545257568,
"start": 1029,
"tag": "NAME",
"value": "Sylvester Stallone"
},
{
"context": " \"1946-07-06\"}\n\n {:db/id -106\n :person/name \"Richard Crenna\"\n :person/born \"1926-11-30\"\n :person/death ",
"end": 1129,
"score": 0.9998592138290405,
"start": 1115,
"tag": "NAME",
"value": "Richard Crenna"
},
{
"context": " \"2003-01-17\"}\n\n {:db/id -107\n :person/name \"Brian Dennehy\"\n :person/born \"1938-07-09\"}\n\n {:db/id -108\n",
"end": 1241,
"score": 0.9998722076416016,
"start": 1228,
"tag": "NAME",
"value": "Brian Dennehy"
},
{
"context": " \"1938-07-09\"}\n\n {:db/id -108\n :person/name \"John McTiernan\"\n :person/born \"1951-01-08\"}\n\n {:db/id -109\n",
"end": 1323,
"score": 0.999843955039978,
"start": 1309,
"tag": "NAME",
"value": "John McTiernan"
},
{
"context": " \"1951-01-08\"}\n\n {:db/id -109\n :person/name \"Elpidia Carrillo\"\n :person/born \"1961-08-16\"}\n\n {:db/id -110\n",
"end": 1407,
"score": 0.9998839497566223,
"start": 1391,
"tag": "NAME",
"value": "Elpidia Carrillo"
},
{
"context": " \"1961-08-16\"}\n\n {:db/id -110\n :person/name \"Carl Weathers\"\n :person/born \"1948-01-14\"}\n\n {:db/id -111\n",
"end": 1488,
"score": 0.9998750686645508,
"start": 1475,
"tag": "NAME",
"value": "Carl Weathers"
},
{
"context": " \"1948-01-14\"}\n\n {:db/id -111\n :person/name \"Richard Donner\"\n :person/born \"1930-04-24\"}\n\n {:db/id -112\n",
"end": 1570,
"score": 0.9998668432235718,
"start": 1556,
"tag": "NAME",
"value": "Richard Donner"
},
{
"context": " \"1930-04-24\"}\n\n {:db/id -112\n :person/name \"Mel Gibson\"\n :person/born \"1956-01-03\"}\n\n {:db/id -113\n",
"end": 1648,
"score": 0.9998747110366821,
"start": 1638,
"tag": "NAME",
"value": "Mel Gibson"
},
{
"context": " \"1956-01-03\"}\n\n {:db/id -113\n :person/name \"Danny Glover\"\n :person/born \"1946-07-22\"}\n\n {:db/id -114\n",
"end": 1728,
"score": 0.999879002571106,
"start": 1716,
"tag": "NAME",
"value": "Danny Glover"
},
{
"context": " \"1946-07-22\"}\n\n {:db/id -114\n :person/name \"Gary Busey\"\n :person/born \"1944-07-29\"}\n\n {:db/id -115\n",
"end": 1806,
"score": 0.9998741149902344,
"start": 1796,
"tag": "NAME",
"value": "Gary Busey"
},
{
"context": " \"1944-07-29\"}\n\n {:db/id -115\n :person/name \"Paul Verhoeven\"\n :person/born \"1938-07-18\"}\n\n {:db/id -116\n",
"end": 1888,
"score": 0.9998728036880493,
"start": 1874,
"tag": "NAME",
"value": "Paul Verhoeven"
},
{
"context": " \"1938-07-18\"}\n\n {:db/id -116\n :person/name \"Peter Weller\"\n :person/born \"1947-06-24\"}\n\n {:db/id -117\n",
"end": 1968,
"score": 0.9998441338539124,
"start": 1956,
"tag": "NAME",
"value": "Peter Weller"
},
{
"context": " \"1947-06-24\"}\n\n {:db/id -117\n :person/name \"Nancy Allen\"\n :person/born \"1950-06-24\"}\n\n {:db/id -118\n",
"end": 2047,
"score": 0.9998455047607422,
"start": 2036,
"tag": "NAME",
"value": "Nancy Allen"
},
{
"context": " \"1950-06-24\"}\n\n {:db/id -118\n :person/name \"Ronny Cox\"\n :person/born \"1938-07-23\"}\n\n {:db/id -119\n",
"end": 2124,
"score": 0.9998716115951538,
"start": 2115,
"tag": "NAME",
"value": "Ronny Cox"
},
{
"context": " \"1938-07-23\"}\n\n {:db/id -119\n :person/name \"Mark L. Lester\"\n :person/born \"1946-11-26\"}\n\n {:db/id -120\n",
"end": 2206,
"score": 0.9998718500137329,
"start": 2192,
"tag": "NAME",
"value": "Mark L. Lester"
},
{
"context": " \"1946-11-26\"}\n\n {:db/id -120\n :person/name \"Rae Dawn Chong\"\n :person/born \"1961-02-28\"}\n\n {:db/id -121\n",
"end": 2288,
"score": 0.999880313873291,
"start": 2274,
"tag": "NAME",
"value": "Rae Dawn Chong"
},
{
"context": " \"1961-02-28\"}\n\n {:db/id -121\n :person/name \"Alyssa Milano\"\n :person/born \"1972-12-19\"}\n\n {:db/id -122\n",
"end": 2369,
"score": 0.9998688697814941,
"start": 2356,
"tag": "NAME",
"value": "Alyssa Milano"
},
{
"context": " \"1972-12-19\"}\n\n {:db/id -122\n :person/name \"Bruce Willis\"\n :person/born \"1955-03-19\"}\n\n {:db/id -123\n",
"end": 2449,
"score": 0.9998424649238586,
"start": 2437,
"tag": "NAME",
"value": "Bruce Willis"
},
{
"context": " \"1955-03-19\"}\n\n {:db/id -123\n :person/name \"Alan Rickman\"\n :person/born \"1946-02-21\"}\n\n {:db/id -124\n",
"end": 2529,
"score": 0.9998706579208374,
"start": 2517,
"tag": "NAME",
"value": "Alan Rickman"
},
{
"context": " \"1946-02-21\"}\n\n {:db/id -124\n :person/name \"Alexander Godunov\"\n :person/born \"1949-11-28\"\n :person/death ",
"end": 2614,
"score": 0.999872088432312,
"start": 2597,
"tag": "NAME",
"value": "Alexander Godunov"
},
{
"context": " \"1995-05-18\"}\n\n {:db/id -125\n :person/name \"Robert Patrick\"\n :person/born \"1958-11-05\"}\n\n {:db/id -126\n",
"end": 2727,
"score": 0.9998571276664734,
"start": 2713,
"tag": "NAME",
"value": "Robert Patrick"
},
{
"context": " \"1958-11-05\"}\n\n {:db/id -126\n :person/name \"Edward Furlong\"\n :person/born \"1977-08-02\"}\n\n {:db/id -127\n",
"end": 2809,
"score": 0.9998750686645508,
"start": 2795,
"tag": "NAME",
"value": "Edward Furlong"
},
{
"context": " \"1977-08-02\"}\n\n {:db/id -127\n :person/name \"Jonathan Mostow\"\n :person/born \"1961-11-28\"}\n\n {:db/id -128\n",
"end": 2892,
"score": 0.9998620748519897,
"start": 2877,
"tag": "NAME",
"value": "Jonathan Mostow"
},
{
"context": " \"1961-11-28\"}\n\n {:db/id -128\n :person/name \"Nick Stahl\"\n :person/born \"1979-12-05\"}\n\n {:db/id -129\n",
"end": 2970,
"score": 0.9998631477355957,
"start": 2960,
"tag": "NAME",
"value": "Nick Stahl"
},
{
"context": " \"1979-12-05\"}\n\n {:db/id -129\n :person/name \"Claire Danes\"\n :person/born \"1979-04-12\"}\n\n {:db/id -130\n",
"end": 3050,
"score": 0.9998551607131958,
"start": 3038,
"tag": "NAME",
"value": "Claire Danes"
},
{
"context": " \"1979-04-12\"}\n\n {:db/id -130\n :person/name \"George P. Cosmatos\"\n :person/born \"1941-01-04\"\n :person/death ",
"end": 3136,
"score": 0.9998504519462585,
"start": 3118,
"tag": "NAME",
"value": "George P. Cosmatos"
},
{
"context": " \"2005-04-19\"}\n\n {:db/id -131\n :person/name \"Charles Napier\"\n :person/born \"1936-04-12\"\n :person/death ",
"end": 3249,
"score": 0.9998663067817688,
"start": 3235,
"tag": "NAME",
"value": "Charles Napier"
},
{
"context": " \"2011-10-05\"}\n\n {:db/id -132\n :person/name \"Peter MacDonald\"}\n\n {:db/id -133\n :person/name \"Marc de Jong",
"end": 3363,
"score": 0.9998759627342224,
"start": 3348,
"tag": "NAME",
"value": "Peter MacDonald"
},
{
"context": "er MacDonald\"}\n\n {:db/id -133\n :person/name \"Marc de Jonge\"\n :person/born \"1949-02-16\"\n :person/death ",
"end": 3414,
"score": 0.9998795390129089,
"start": 3401,
"tag": "NAME",
"value": "Marc de Jonge"
},
{
"context": " \"1996-06-06\"}\n\n {:db/id -134\n :person/name \"Stephen Hopkins\"}\n\n {:db/id -135\n :person/name \"Ruben Blades",
"end": 3528,
"score": 0.9998698830604553,
"start": 3513,
"tag": "NAME",
"value": "Stephen Hopkins"
},
{
"context": "phen Hopkins\"}\n\n {:db/id -135\n :person/name \"Ruben Blades\"\n :person/born \"1948-07-16\"}\n\n {:db/id -136\n",
"end": 3578,
"score": 0.9998751878738403,
"start": 3566,
"tag": "NAME",
"value": "Ruben Blades"
},
{
"context": " \"1948-07-16\"}\n\n {:db/id -136\n :person/name \"Joe Pesci\"\n :person/born \"1943-02-09\"}\n\n {:db/id -137\n",
"end": 3655,
"score": 0.9998685717582703,
"start": 3646,
"tag": "NAME",
"value": "Joe Pesci"
},
{
"context": " \"1943-02-09\"}\n\n {:db/id -137\n :person/name \"Ridley Scott\"\n :person/born \"1937-11-30\"}\n\n {:db/id -138\n",
"end": 3735,
"score": 0.9998788833618164,
"start": 3723,
"tag": "NAME",
"value": "Ridley Scott"
},
{
"context": " \"1937-11-30\"}\n\n {:db/id -138\n :person/name \"Tom Skerritt\"\n :person/born \"1933-08-25\"}\n\n {:db/id -139\n",
"end": 3815,
"score": 0.9998785853385925,
"start": 3803,
"tag": "NAME",
"value": "Tom Skerritt"
},
{
"context": " \"1933-08-25\"}\n\n {:db/id -139\n :person/name \"Sigourney Weaver\"\n :person/born \"1949-10-08\"}\n\n {:db/id -140\n",
"end": 3899,
"score": 0.9998809695243835,
"start": 3883,
"tag": "NAME",
"value": "Sigourney Weaver"
},
{
"context": " \"1949-10-08\"}\n\n {:db/id -140\n :person/name \"Veronica Cartwright\"\n :person/born \"1949-04-20\"}\n\n {:db/id -141\n",
"end": 3986,
"score": 0.9998612403869629,
"start": 3967,
"tag": "NAME",
"value": "Veronica Cartwright"
},
{
"context": " \"1949-04-20\"}\n\n {:db/id -141\n :person/name \"Carrie Henn\"}\n\n {:db/id -142\n :person/name \"George Mille",
"end": 4065,
"score": 0.9998631477355957,
"start": 4054,
"tag": "NAME",
"value": "Carrie Henn"
},
{
"context": "\"Carrie Henn\"}\n\n {:db/id -142\n :person/name \"George Miller\"\n :person/born \"1945-03-03\"}\n\n {:db/id -143\n",
"end": 4116,
"score": 0.9998297691345215,
"start": 4103,
"tag": "NAME",
"value": "George Miller"
},
{
"context": " \"1945-03-03\"}\n\n {:db/id -143\n :person/name \"Steve Bisley\"\n :person/born \"1951-12-26\"}\n\n {:db/id -144\n",
"end": 4196,
"score": 0.999855637550354,
"start": 4184,
"tag": "NAME",
"value": "Steve Bisley"
},
{
"context": " \"1951-12-26\"}\n\n {:db/id -144\n :person/name \"Joanne Samuel\"}\n\n {:db/id -145\n :person/name \"Michael Pres",
"end": 4277,
"score": 0.9998273849487305,
"start": 4264,
"tag": "NAME",
"value": "Joanne Samuel"
},
{
"context": "oanne Samuel\"}\n\n {:db/id -145\n :person/name \"Michael Preston\"\n :person/born \"1938-05-14\"}\n\n {:db/id -146\n",
"end": 4330,
"score": 0.999851644039154,
"start": 4315,
"tag": "NAME",
"value": "Michael Preston"
},
{
"context": " \"1938-05-14\"}\n\n {:db/id -146\n :person/name \"Bruce Spence\"\n :person/born \"1945-09-17\"}\n\n {:db/id -147\n",
"end": 4410,
"score": 0.9998614192008972,
"start": 4398,
"tag": "NAME",
"value": "Bruce Spence"
},
{
"context": " \"1945-09-17\"}\n\n {:db/id -147\n :person/name \"George Ogilvie\"\n :person/born \"1931-03-05\"}\n\n {:db/id -148\n",
"end": 4492,
"score": 0.9998520016670227,
"start": 4478,
"tag": "NAME",
"value": "George Ogilvie"
},
{
"context": " \"1931-03-05\"}\n\n {:db/id -148\n :person/name \"Tina Turner\"\n :person/born \"1939-11-26\"}\n\n {:db/id -149\n",
"end": 4571,
"score": 0.9998461008071899,
"start": 4560,
"tag": "NAME",
"value": "Tina Turner"
},
{
"context": " \"1939-11-26\"}\n\n {:db/id -149\n :person/name \"Sophie Marceau\"\n :person/born \"1966-11-17\"}\n\n {:db/id -200\n",
"end": 4653,
"score": 0.9998413920402527,
"start": 4639,
"tag": "NAME",
"value": "Sophie Marceau"
},
{
"context": "th a new central character,\n eventually played by Bruce Willis, and became Die Hard\"}\n \n {:db/id -206\n :m",
"end": 6001,
"score": 0.9998782277107239,
"start": 5989,
"tag": "NAME",
"value": "Bruce Willis"
}
] | src/test/datafire/samples.cljs | filipesilva/datascript-firebase | 53 | (ns datafire.samples)
; Adapted from https://github.com/jonase/learndatalogtoday/blob/master/resources/db/data.edn
(def schema {:movie/director {:db/valueType :db.type/ref
:db/cardinality :db.cardinality/many
:db/isComponent true}
:movie/cast {:db/valueType :db.type/ref
:db/cardinality :db.cardinality/many
:db/isComponent true}
:movie/sequel {:db/valueType :db.type/ref
:db/isComponent true}})
(def data
[{:db/id -100
:person/name "James Cameron"
:person/born "1954-08-16"}
{:db/id -101
:person/name "Arnold Schwarzenegger"
:person/born "1947-07-30"}
{:db/id -102
:person/name "Linda Hamilton"
:person/born "1956-09-26"}
{:db/id -103
:person/name "Michael Biehn"
:person/born "1956-07-31"}
{:db/id -104
:person/name "Ted Kotcheff"
:person/born "1931-04-07"}
{:db/id -105
:person/name "Sylvester Stallone"
:person/born "1946-07-06"}
{:db/id -106
:person/name "Richard Crenna"
:person/born "1926-11-30"
:person/death "2003-01-17"}
{:db/id -107
:person/name "Brian Dennehy"
:person/born "1938-07-09"}
{:db/id -108
:person/name "John McTiernan"
:person/born "1951-01-08"}
{:db/id -109
:person/name "Elpidia Carrillo"
:person/born "1961-08-16"}
{:db/id -110
:person/name "Carl Weathers"
:person/born "1948-01-14"}
{:db/id -111
:person/name "Richard Donner"
:person/born "1930-04-24"}
{:db/id -112
:person/name "Mel Gibson"
:person/born "1956-01-03"}
{:db/id -113
:person/name "Danny Glover"
:person/born "1946-07-22"}
{:db/id -114
:person/name "Gary Busey"
:person/born "1944-07-29"}
{:db/id -115
:person/name "Paul Verhoeven"
:person/born "1938-07-18"}
{:db/id -116
:person/name "Peter Weller"
:person/born "1947-06-24"}
{:db/id -117
:person/name "Nancy Allen"
:person/born "1950-06-24"}
{:db/id -118
:person/name "Ronny Cox"
:person/born "1938-07-23"}
{:db/id -119
:person/name "Mark L. Lester"
:person/born "1946-11-26"}
{:db/id -120
:person/name "Rae Dawn Chong"
:person/born "1961-02-28"}
{:db/id -121
:person/name "Alyssa Milano"
:person/born "1972-12-19"}
{:db/id -122
:person/name "Bruce Willis"
:person/born "1955-03-19"}
{:db/id -123
:person/name "Alan Rickman"
:person/born "1946-02-21"}
{:db/id -124
:person/name "Alexander Godunov"
:person/born "1949-11-28"
:person/death "1995-05-18"}
{:db/id -125
:person/name "Robert Patrick"
:person/born "1958-11-05"}
{:db/id -126
:person/name "Edward Furlong"
:person/born "1977-08-02"}
{:db/id -127
:person/name "Jonathan Mostow"
:person/born "1961-11-28"}
{:db/id -128
:person/name "Nick Stahl"
:person/born "1979-12-05"}
{:db/id -129
:person/name "Claire Danes"
:person/born "1979-04-12"}
{:db/id -130
:person/name "George P. Cosmatos"
:person/born "1941-01-04"
:person/death "2005-04-19"}
{:db/id -131
:person/name "Charles Napier"
:person/born "1936-04-12"
:person/death "2011-10-05"}
{:db/id -132
:person/name "Peter MacDonald"}
{:db/id -133
:person/name "Marc de Jonge"
:person/born "1949-02-16"
:person/death "1996-06-06"}
{:db/id -134
:person/name "Stephen Hopkins"}
{:db/id -135
:person/name "Ruben Blades"
:person/born "1948-07-16"}
{:db/id -136
:person/name "Joe Pesci"
:person/born "1943-02-09"}
{:db/id -137
:person/name "Ridley Scott"
:person/born "1937-11-30"}
{:db/id -138
:person/name "Tom Skerritt"
:person/born "1933-08-25"}
{:db/id -139
:person/name "Sigourney Weaver"
:person/born "1949-10-08"}
{:db/id -140
:person/name "Veronica Cartwright"
:person/born "1949-04-20"}
{:db/id -141
:person/name "Carrie Henn"}
{:db/id -142
:person/name "George Miller"
:person/born "1945-03-03"}
{:db/id -143
:person/name "Steve Bisley"
:person/born "1951-12-26"}
{:db/id -144
:person/name "Joanne Samuel"}
{:db/id -145
:person/name "Michael Preston"
:person/born "1938-05-14"}
{:db/id -146
:person/name "Bruce Spence"
:person/born "1945-09-17"}
{:db/id -147
:person/name "George Ogilvie"
:person/born "1931-03-05"}
{:db/id -148
:person/name "Tina Turner"
:person/born "1939-11-26"}
{:db/id -149
:person/name "Sophie Marceau"
:person/born "1966-11-17"}
{:db/id -200
:movie/title "The Terminator"
:movie/year 1984
:movie/director -100
:movie/cast [-101
-102
-103]
:movie/sequel -207}
{:db/id -201
:movie/title "First Blood"
:movie/year 1982
:movie/director -104
:movie/cast [-105
-106
-107]
:movie/sequel -209}
{:db/id -202
:movie/title "Predator"
:movie/year 1987
:movie/director -108
:movie/cast [-101
-109
-110]
:movie/sequel -211}
{:db/id -203
:movie/title "Lethal Weapon"
:movie/year 1987
:movie/director -111
:movie/cast [-112
-113
-114]
:movie/sequel -212}
{:db/id -204
:movie/title "RoboCop"
:movie/year 1987
:movie/director -115
:movie/cast [-116
-117
-118]}
{:db/id -205
:movie/title "Commando"
:movie/year 1985
:movie/director -119
:movie/cast [-101
-120
-121]
:trivia "In 1986, a sequel was written with an eye to having
John McTiernan direct. Schwarzenegger wasn't interested in reprising
the role. The script was then reworked with a new central character,
eventually played by Bruce Willis, and became Die Hard"}
{:db/id -206
:movie/title "Die Hard"
:movie/year 1988
:movie/director -108
:movie/cast [-122
-123
-124]}
{:db/id -207
:movie/title "Terminator 2: Judgment Day"
:movie/year 1991
:movie/director -100
:movie/cast [-101
-102
-125
-126]
:movie/sequel -208}
{:db/id -208
:movie/title "Terminator 3: Rise of the Machines"
:movie/year 2003
:movie/director -127
:movie/cast [-101
-128
-129]}
{:db/id -209
:movie/title "Rambo: First Blood Part II"
:movie/year 1985
:movie/director -130
:movie/cast [-105
-106
-131]
:movie/sequel -210}
{:db/id -210
:movie/title "Rambo III"
:movie/year 1988
:movie/director -132
:movie/cast [-105
-106
-133]}
{:db/id -211
:movie/title "Predator 2"
:movie/year 1990
:movie/director -134
:movie/cast [-113
-114
-135]}
{:db/id -212
:movie/title "Lethal Weapon 2"
:movie/year 1989
:movie/director -111
:movie/cast [-112
-113
-136]
:movie/sequel -213}
{:db/id -213
:movie/title "Lethal Weapon 3"
:movie/year 1992
:movie/director -111
:movie/cast [-112
-113
-136]}
{:db/id -214
:movie/title "Alien"
:movie/year 1979
:movie/director -137
:movie/cast [-138
-139
-140]
:movie/sequel -215}
{:db/id -215
:movie/title "Aliens"
:movie/year 1986
:movie/director -100
:movie/cast [-139
-141
-103]}
{:db/id -216
:movie/title "Mad Max"
:movie/year 1979
:movie/director -142
:movie/cast [-112
-143
-144]
:movie/sequel -217}
{:db/id -217
:movie/title "Mad Max 2"
:movie/year 1981
:movie/director -142
:movie/cast [-112
-145
-146]
:movie/sequel -218}
{:db/id -218
:movie/title "Mad Max Beyond Thunderdome"
:movie/year 1985
:movie/director [-142
-147]
:movie/cast [-112
-148]}
{:db/id -219
:movie/title "Braveheart"
:movie/year 1995
:movie/director [-112]
:movie/cast [-112
-149]}
]) | 115324 | (ns datafire.samples)
; Adapted from https://github.com/jonase/learndatalogtoday/blob/master/resources/db/data.edn
(def schema {:movie/director {:db/valueType :db.type/ref
:db/cardinality :db.cardinality/many
:db/isComponent true}
:movie/cast {:db/valueType :db.type/ref
:db/cardinality :db.cardinality/many
:db/isComponent true}
:movie/sequel {:db/valueType :db.type/ref
:db/isComponent true}})
(def data
[{:db/id -100
:person/name "<NAME>"
:person/born "1954-08-16"}
{:db/id -101
:person/name "<NAME>"
:person/born "1947-07-30"}
{:db/id -102
:person/name "<NAME>"
:person/born "1956-09-26"}
{:db/id -103
:person/name "<NAME>"
:person/born "1956-07-31"}
{:db/id -104
:person/name "<NAME>"
:person/born "1931-04-07"}
{:db/id -105
:person/name "<NAME>"
:person/born "1946-07-06"}
{:db/id -106
:person/name "<NAME>"
:person/born "1926-11-30"
:person/death "2003-01-17"}
{:db/id -107
:person/name "<NAME>"
:person/born "1938-07-09"}
{:db/id -108
:person/name "<NAME>"
:person/born "1951-01-08"}
{:db/id -109
:person/name "<NAME>"
:person/born "1961-08-16"}
{:db/id -110
:person/name "<NAME>"
:person/born "1948-01-14"}
{:db/id -111
:person/name "<NAME>"
:person/born "1930-04-24"}
{:db/id -112
:person/name "<NAME>"
:person/born "1956-01-03"}
{:db/id -113
:person/name "<NAME>"
:person/born "1946-07-22"}
{:db/id -114
:person/name "<NAME>"
:person/born "1944-07-29"}
{:db/id -115
:person/name "<NAME>"
:person/born "1938-07-18"}
{:db/id -116
:person/name "<NAME>"
:person/born "1947-06-24"}
{:db/id -117
:person/name "<NAME>"
:person/born "1950-06-24"}
{:db/id -118
:person/name "<NAME>"
:person/born "1938-07-23"}
{:db/id -119
:person/name "<NAME>"
:person/born "1946-11-26"}
{:db/id -120
:person/name "<NAME>"
:person/born "1961-02-28"}
{:db/id -121
:person/name "<NAME>"
:person/born "1972-12-19"}
{:db/id -122
:person/name "<NAME>"
:person/born "1955-03-19"}
{:db/id -123
:person/name "<NAME>"
:person/born "1946-02-21"}
{:db/id -124
:person/name "<NAME>"
:person/born "1949-11-28"
:person/death "1995-05-18"}
{:db/id -125
:person/name "<NAME>"
:person/born "1958-11-05"}
{:db/id -126
:person/name "<NAME>"
:person/born "1977-08-02"}
{:db/id -127
:person/name "<NAME>"
:person/born "1961-11-28"}
{:db/id -128
:person/name "<NAME>"
:person/born "1979-12-05"}
{:db/id -129
:person/name "<NAME>"
:person/born "1979-04-12"}
{:db/id -130
:person/name "<NAME>"
:person/born "1941-01-04"
:person/death "2005-04-19"}
{:db/id -131
:person/name "<NAME>"
:person/born "1936-04-12"
:person/death "2011-10-05"}
{:db/id -132
:person/name "<NAME>"}
{:db/id -133
:person/name "<NAME>"
:person/born "1949-02-16"
:person/death "1996-06-06"}
{:db/id -134
:person/name "<NAME>"}
{:db/id -135
:person/name "<NAME>"
:person/born "1948-07-16"}
{:db/id -136
:person/name "<NAME>"
:person/born "1943-02-09"}
{:db/id -137
:person/name "<NAME>"
:person/born "1937-11-30"}
{:db/id -138
:person/name "<NAME>"
:person/born "1933-08-25"}
{:db/id -139
:person/name "<NAME>"
:person/born "1949-10-08"}
{:db/id -140
:person/name "<NAME>"
:person/born "1949-04-20"}
{:db/id -141
:person/name "<NAME>"}
{:db/id -142
:person/name "<NAME>"
:person/born "1945-03-03"}
{:db/id -143
:person/name "<NAME>"
:person/born "1951-12-26"}
{:db/id -144
:person/name "<NAME>"}
{:db/id -145
:person/name "<NAME>"
:person/born "1938-05-14"}
{:db/id -146
:person/name "<NAME>"
:person/born "1945-09-17"}
{:db/id -147
:person/name "<NAME>"
:person/born "1931-03-05"}
{:db/id -148
:person/name "<NAME>"
:person/born "1939-11-26"}
{:db/id -149
:person/name "<NAME>"
:person/born "1966-11-17"}
{:db/id -200
:movie/title "The Terminator"
:movie/year 1984
:movie/director -100
:movie/cast [-101
-102
-103]
:movie/sequel -207}
{:db/id -201
:movie/title "First Blood"
:movie/year 1982
:movie/director -104
:movie/cast [-105
-106
-107]
:movie/sequel -209}
{:db/id -202
:movie/title "Predator"
:movie/year 1987
:movie/director -108
:movie/cast [-101
-109
-110]
:movie/sequel -211}
{:db/id -203
:movie/title "Lethal Weapon"
:movie/year 1987
:movie/director -111
:movie/cast [-112
-113
-114]
:movie/sequel -212}
{:db/id -204
:movie/title "RoboCop"
:movie/year 1987
:movie/director -115
:movie/cast [-116
-117
-118]}
{:db/id -205
:movie/title "Commando"
:movie/year 1985
:movie/director -119
:movie/cast [-101
-120
-121]
:trivia "In 1986, a sequel was written with an eye to having
John McTiernan direct. Schwarzenegger wasn't interested in reprising
the role. The script was then reworked with a new central character,
eventually played by <NAME>, and became Die Hard"}
{:db/id -206
:movie/title "Die Hard"
:movie/year 1988
:movie/director -108
:movie/cast [-122
-123
-124]}
{:db/id -207
:movie/title "Terminator 2: Judgment Day"
:movie/year 1991
:movie/director -100
:movie/cast [-101
-102
-125
-126]
:movie/sequel -208}
{:db/id -208
:movie/title "Terminator 3: Rise of the Machines"
:movie/year 2003
:movie/director -127
:movie/cast [-101
-128
-129]}
{:db/id -209
:movie/title "Rambo: First Blood Part II"
:movie/year 1985
:movie/director -130
:movie/cast [-105
-106
-131]
:movie/sequel -210}
{:db/id -210
:movie/title "Rambo III"
:movie/year 1988
:movie/director -132
:movie/cast [-105
-106
-133]}
{:db/id -211
:movie/title "Predator 2"
:movie/year 1990
:movie/director -134
:movie/cast [-113
-114
-135]}
{:db/id -212
:movie/title "Lethal Weapon 2"
:movie/year 1989
:movie/director -111
:movie/cast [-112
-113
-136]
:movie/sequel -213}
{:db/id -213
:movie/title "Lethal Weapon 3"
:movie/year 1992
:movie/director -111
:movie/cast [-112
-113
-136]}
{:db/id -214
:movie/title "Alien"
:movie/year 1979
:movie/director -137
:movie/cast [-138
-139
-140]
:movie/sequel -215}
{:db/id -215
:movie/title "Aliens"
:movie/year 1986
:movie/director -100
:movie/cast [-139
-141
-103]}
{:db/id -216
:movie/title "Mad Max"
:movie/year 1979
:movie/director -142
:movie/cast [-112
-143
-144]
:movie/sequel -217}
{:db/id -217
:movie/title "Mad Max 2"
:movie/year 1981
:movie/director -142
:movie/cast [-112
-145
-146]
:movie/sequel -218}
{:db/id -218
:movie/title "Mad Max Beyond Thunderdome"
:movie/year 1985
:movie/director [-142
-147]
:movie/cast [-112
-148]}
{:db/id -219
:movie/title "Braveheart"
:movie/year 1995
:movie/director [-112]
:movie/cast [-112
-149]}
]) | true | (ns datafire.samples)
; Adapted from https://github.com/jonase/learndatalogtoday/blob/master/resources/db/data.edn
(def schema {:movie/director {:db/valueType :db.type/ref
:db/cardinality :db.cardinality/many
:db/isComponent true}
:movie/cast {:db/valueType :db.type/ref
:db/cardinality :db.cardinality/many
:db/isComponent true}
:movie/sequel {:db/valueType :db.type/ref
:db/isComponent true}})
(def data
[{:db/id -100
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1954-08-16"}
{:db/id -101
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1947-07-30"}
{:db/id -102
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1956-09-26"}
{:db/id -103
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1956-07-31"}
{:db/id -104
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1931-04-07"}
{:db/id -105
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1946-07-06"}
{:db/id -106
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1926-11-30"
:person/death "2003-01-17"}
{:db/id -107
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1938-07-09"}
{:db/id -108
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1951-01-08"}
{:db/id -109
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1961-08-16"}
{:db/id -110
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1948-01-14"}
{:db/id -111
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1930-04-24"}
{:db/id -112
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1956-01-03"}
{:db/id -113
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1946-07-22"}
{:db/id -114
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1944-07-29"}
{:db/id -115
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1938-07-18"}
{:db/id -116
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1947-06-24"}
{:db/id -117
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1950-06-24"}
{:db/id -118
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1938-07-23"}
{:db/id -119
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1946-11-26"}
{:db/id -120
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1961-02-28"}
{:db/id -121
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1972-12-19"}
{:db/id -122
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1955-03-19"}
{:db/id -123
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1946-02-21"}
{:db/id -124
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1949-11-28"
:person/death "1995-05-18"}
{:db/id -125
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1958-11-05"}
{:db/id -126
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1977-08-02"}
{:db/id -127
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1961-11-28"}
{:db/id -128
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1979-12-05"}
{:db/id -129
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1979-04-12"}
{:db/id -130
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1941-01-04"
:person/death "2005-04-19"}
{:db/id -131
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1936-04-12"
:person/death "2011-10-05"}
{:db/id -132
:person/name "PI:NAME:<NAME>END_PI"}
{:db/id -133
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1949-02-16"
:person/death "1996-06-06"}
{:db/id -134
:person/name "PI:NAME:<NAME>END_PI"}
{:db/id -135
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1948-07-16"}
{:db/id -136
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1943-02-09"}
{:db/id -137
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1937-11-30"}
{:db/id -138
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1933-08-25"}
{:db/id -139
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1949-10-08"}
{:db/id -140
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1949-04-20"}
{:db/id -141
:person/name "PI:NAME:<NAME>END_PI"}
{:db/id -142
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1945-03-03"}
{:db/id -143
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1951-12-26"}
{:db/id -144
:person/name "PI:NAME:<NAME>END_PI"}
{:db/id -145
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1938-05-14"}
{:db/id -146
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1945-09-17"}
{:db/id -147
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1931-03-05"}
{:db/id -148
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1939-11-26"}
{:db/id -149
:person/name "PI:NAME:<NAME>END_PI"
:person/born "1966-11-17"}
{:db/id -200
:movie/title "The Terminator"
:movie/year 1984
:movie/director -100
:movie/cast [-101
-102
-103]
:movie/sequel -207}
{:db/id -201
:movie/title "First Blood"
:movie/year 1982
:movie/director -104
:movie/cast [-105
-106
-107]
:movie/sequel -209}
{:db/id -202
:movie/title "Predator"
:movie/year 1987
:movie/director -108
:movie/cast [-101
-109
-110]
:movie/sequel -211}
{:db/id -203
:movie/title "Lethal Weapon"
:movie/year 1987
:movie/director -111
:movie/cast [-112
-113
-114]
:movie/sequel -212}
{:db/id -204
:movie/title "RoboCop"
:movie/year 1987
:movie/director -115
:movie/cast [-116
-117
-118]}
{:db/id -205
:movie/title "Commando"
:movie/year 1985
:movie/director -119
:movie/cast [-101
-120
-121]
:trivia "In 1986, a sequel was written with an eye to having
John McTiernan direct. Schwarzenegger wasn't interested in reprising
the role. The script was then reworked with a new central character,
eventually played by PI:NAME:<NAME>END_PI, and became Die Hard"}
{:db/id -206
:movie/title "Die Hard"
:movie/year 1988
:movie/director -108
:movie/cast [-122
-123
-124]}
{:db/id -207
:movie/title "Terminator 2: Judgment Day"
:movie/year 1991
:movie/director -100
:movie/cast [-101
-102
-125
-126]
:movie/sequel -208}
{:db/id -208
:movie/title "Terminator 3: Rise of the Machines"
:movie/year 2003
:movie/director -127
:movie/cast [-101
-128
-129]}
{:db/id -209
:movie/title "Rambo: First Blood Part II"
:movie/year 1985
:movie/director -130
:movie/cast [-105
-106
-131]
:movie/sequel -210}
{:db/id -210
:movie/title "Rambo III"
:movie/year 1988
:movie/director -132
:movie/cast [-105
-106
-133]}
{:db/id -211
:movie/title "Predator 2"
:movie/year 1990
:movie/director -134
:movie/cast [-113
-114
-135]}
{:db/id -212
:movie/title "Lethal Weapon 2"
:movie/year 1989
:movie/director -111
:movie/cast [-112
-113
-136]
:movie/sequel -213}
{:db/id -213
:movie/title "Lethal Weapon 3"
:movie/year 1992
:movie/director -111
:movie/cast [-112
-113
-136]}
{:db/id -214
:movie/title "Alien"
:movie/year 1979
:movie/director -137
:movie/cast [-138
-139
-140]
:movie/sequel -215}
{:db/id -215
:movie/title "Aliens"
:movie/year 1986
:movie/director -100
:movie/cast [-139
-141
-103]}
{:db/id -216
:movie/title "Mad Max"
:movie/year 1979
:movie/director -142
:movie/cast [-112
-143
-144]
:movie/sequel -217}
{:db/id -217
:movie/title "Mad Max 2"
:movie/year 1981
:movie/director -142
:movie/cast [-112
-145
-146]
:movie/sequel -218}
{:db/id -218
:movie/title "Mad Max Beyond Thunderdome"
:movie/year 1985
:movie/director [-142
-147]
:movie/cast [-112
-148]}
{:db/id -219
:movie/title "Braveheart"
:movie/year 1995
:movie/director [-112]
:movie/cast [-112
-149]}
]) |
[
{
"context": "(ns kindergarten-garden)\n\n(def children [:alice :bob :charlie :david :eve :fred :ginny :harriet :",
"end": 47,
"score": 0.9964421391487122,
"start": 42,
"tag": "NAME",
"value": "alice"
},
{
"context": "(ns kindergarten-garden)\n\n(def children [:alice :bob :charlie :david :eve :fred :ginny :harriet :ilean",
"end": 52,
"score": 0.9980283379554749,
"start": 49,
"tag": "NAME",
"value": "bob"
},
{
"context": "kindergarten-garden)\n\n(def children [:alice :bob :charlie :david :eve :fred :ginny :harriet :ileana :joseph",
"end": 61,
"score": 0.9996901750564575,
"start": 54,
"tag": "NAME",
"value": "charlie"
},
{
"context": "ten-garden)\n\n(def children [:alice :bob :charlie :david :eve :fred :ginny :harriet :ileana :joseph :kinca",
"end": 68,
"score": 0.9994326233863831,
"start": 63,
"tag": "NAME",
"value": "david"
},
{
"context": "den)\n\n(def children [:alice :bob :charlie :david :eve :fred :ginny :harriet :ileana :joseph :kincaid :l",
"end": 73,
"score": 0.9995739459991455,
"start": 70,
"tag": "NAME",
"value": "eve"
},
{
"context": "\n(def children [:alice :bob :charlie :david :eve :fred :ginny :harriet :ileana :joseph :kincaid :larry])",
"end": 79,
"score": 0.9997416734695435,
"start": 75,
"tag": "NAME",
"value": "fred"
},
{
"context": "children [:alice :bob :charlie :david :eve :fred :ginny :harriet :ileana :joseph :kincaid :larry])\n(def p",
"end": 86,
"score": 0.999746561050415,
"start": 81,
"tag": "NAME",
"value": "ginny"
},
{
"context": "n [:alice :bob :charlie :david :eve :fred :ginny :harriet :ileana :joseph :kincaid :larry])\n(def plant { \\G",
"end": 95,
"score": 0.9997995495796204,
"start": 88,
"tag": "NAME",
"value": "harriet"
},
{
"context": " :bob :charlie :david :eve :fred :ginny :harriet :ileana :joseph :kincaid :larry])\n(def plant { \\G :grass ",
"end": 103,
"score": 0.9995418190956116,
"start": 97,
"tag": "NAME",
"value": "ileana"
},
{
"context": "harlie :david :eve :fred :ginny :harriet :ileana :joseph :kincaid :larry])\n(def plant { \\G :grass \\C :clov",
"end": 111,
"score": 0.9997704029083252,
"start": 105,
"tag": "NAME",
"value": "joseph"
},
{
"context": "david :eve :fred :ginny :harriet :ileana :joseph :kincaid :larry])\n(def plant { \\G :grass \\C :clover \\R :ra",
"end": 120,
"score": 0.9997474551200867,
"start": 113,
"tag": "NAME",
"value": "kincaid"
},
{
"context": "e :fred :ginny :harriet :ileana :joseph :kincaid :larry])\n(def plant { \\G :grass \\C :clover \\R :radishes ",
"end": 127,
"score": 0.9996018409729004,
"start": 122,
"tag": "NAME",
"value": "larry"
}
] | clojure/kindergarten-garden/src/kindergarten_garden.clj | ErikSchierboom/exercism | 23 | (ns kindergarten-garden)
(def children [:alice :bob :charlie :david :eve :fred :ginny :harriet :ileana :joseph :kincaid :larry])
(def plant { \G :grass \C :clover \R :radishes \V :violets })
(defn garden [rows]
(let [plants (keep plant rows)
[first-row second-row] (partition (/ (count plants) 2) plants)]
(zipmap children (map concat (partition 2 first-row) (partition 2 second-row))))) | 66576 | (ns kindergarten-garden)
(def children [:<NAME> :<NAME> :<NAME> :<NAME> :<NAME> :<NAME> :<NAME> :<NAME> :<NAME> :<NAME> :<NAME> :<NAME>])
(def plant { \G :grass \C :clover \R :radishes \V :violets })
(defn garden [rows]
(let [plants (keep plant rows)
[first-row second-row] (partition (/ (count plants) 2) plants)]
(zipmap children (map concat (partition 2 first-row) (partition 2 second-row))))) | true | (ns kindergarten-garden)
(def children [:PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI :PI:NAME:<NAME>END_PI])
(def plant { \G :grass \C :clover \R :radishes \V :violets })
(defn garden [rows]
(let [plants (keep plant rows)
[first-row second-row] (partition (/ (count plants) 2) plants)]
(zipmap children (map concat (partition 2 first-row) (partition 2 second-row))))) |
[
{
"context": " the pretty printer for Clojure\n\n; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio",
"end": 88,
"score": 0.9998761415481567,
"start": 77,
"tag": "NAME",
"value": "Rich Hickey"
},
{
"context": "ice, or any other, from this software.\n\n;; Author: Tom Faulhaber\n;; April 3, 2009\n\n\n;; This module implements the ",
"end": 547,
"score": 0.9998965263366699,
"start": 534,
"tag": "NAME",
"value": "Tom Faulhaber"
}
] | src/clj/clojure/pprint/dispatch.clj | lorettahe/clojure | 1 | ;; dispatch.clj -- part of the pretty printer for Clojure
; Copyright (c) Rich Hickey. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
;; Author: Tom Faulhaber
;; April 3, 2009
;; This module implements the default dispatch tables for pretty printing code and
;; data.
(in-ns 'clojure.pprint)
(defn- use-method
"Installs a function as a new method of multimethod associated with dispatch-value. "
[multifn dispatch-val func]
(. multifn addMethod dispatch-val func))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Implementations of specific dispatch table entries
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Handle forms that can be "back-translated" to reader macros
;;; Not all reader macros can be dealt with this way or at all.
;;; Macros that we can't deal with at all are:
;;; ; - The comment character is absorbed by the reader and never is part of the form
;;; ` - Is fully processed at read time into a lisp expression (which will contain concats
;;; and regular quotes).
;;; ~@ - Also fully eaten by the processing of ` and can't be used outside.
;;; , - is whitespace and is lost (like all other whitespace). Formats can generate commas
;;; where they deem them useful to help readability.
;;; ^ - Adding metadata completely disappears at read time and the data appears to be
;;; completely lost.
;;;
;;; Most other syntax stuff is dealt with directly by the formats (like (), [], {}, and #{})
;;; or directly by printing the objects using Clojure's built-in print functions (like
;;; :keyword, \char, or ""). The notable exception is #() which is special-cased.
(def ^{:private true} reader-macros
{'quote "'", 'clojure.core/deref "@",
'var "#'", 'clojure.core/unquote "~"})
(defn- pprint-reader-macro [alis]
(let [^String macro-char (reader-macros (first alis))]
(when (and macro-char (= 2 (count alis)))
(.write ^java.io.Writer *out* macro-char)
(write-out (second alis))
true)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Dispatch for the basic data types when interpreted
;; as data (as opposed to code).
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; TODO: inline these formatter statements into funcs so that we
;;; are a little easier on the stack. (Or, do "real" compilation, a
;;; la Common Lisp)
;;; (def pprint-simple-list (formatter-out "~:<~@{~w~^ ~_~}~:>"))
(defn- pprint-simple-list [alis]
(pprint-logical-block :prefix "(" :suffix ")"
(print-length-loop [alis (seq alis)]
(when alis
(write-out (first alis))
(when (next alis)
(.write ^java.io.Writer *out* " ")
(pprint-newline :linear)
(recur (next alis)))))))
(defn- pprint-list [alis]
(if-not (pprint-reader-macro alis)
(pprint-simple-list alis)))
;;; (def pprint-vector (formatter-out "~<[~;~@{~w~^ ~_~}~;]~:>"))
(defn- pprint-vector [avec]
(pprint-logical-block :prefix "[" :suffix "]"
(print-length-loop [aseq (seq avec)]
(when aseq
(write-out (first aseq))
(when (next aseq)
(.write ^java.io.Writer *out* " ")
(pprint-newline :linear)
(recur (next aseq)))))))
(def ^{:private true} pprint-array (formatter-out "~<[~;~@{~w~^, ~:_~}~;]~:>"))
;;; (def pprint-map (formatter-out "~<{~;~@{~<~w~^ ~_~w~:>~^, ~_~}~;}~:>"))
(defn- pprint-map [amap]
(pprint-logical-block :prefix "{" :suffix "}"
(print-length-loop [aseq (seq amap)]
(when aseq
(pprint-logical-block
(write-out (ffirst aseq))
(.write ^java.io.Writer *out* " ")
(pprint-newline :linear)
(set! *current-length* 0) ; always print both parts of the [k v] pair
(write-out (fnext (first aseq))))
(when (next aseq)
(.write ^java.io.Writer *out* ", ")
(pprint-newline :linear)
(recur (next aseq)))))))
(def ^{:private true} pprint-set (formatter-out "~<#{~;~@{~w~^ ~:_~}~;}~:>"))
(def ^{:private true}
type-map {"core$future_call" "Future",
"core$promise" "Promise"})
(defn- map-ref-type
"Map ugly type names to something simpler"
[name]
(or (when-let [match (re-find #"^[^$]+\$[^$]+" name)]
(type-map match))
name))
(defn- pprint-ideref [o]
(let [prefix (format "#<%s@%x%s: "
(map-ref-type (.getSimpleName (class o)))
(System/identityHashCode o)
(if (and (instance? clojure.lang.Agent o)
(agent-error o))
" FAILED"
""))]
(pprint-logical-block :prefix prefix :suffix ">"
(pprint-indent :block (-> (count prefix) (- 2) -))
(pprint-newline :linear)
(write-out (cond
(and (future? o) (not (future-done? o))) :pending
(and (instance? clojure.lang.IPending o) (not (.isRealized o))) :not-delivered
:else @o)))))
(def ^{:private true} pprint-pqueue (formatter-out "~<<-(~;~@{~w~^ ~_~}~;)-<~:>"))
(defn- pprint-simple-default [obj]
(cond
(.isArray (class obj)) (pprint-array obj)
(and *print-suppress-namespaces* (symbol? obj)) (print (name obj))
:else (pr obj)))
(defmulti
simple-dispatch
"The pretty print dispatch function for simple data structure format."
{:added "1.2" :arglists '[[object]]}
class)
(use-method simple-dispatch clojure.lang.ISeq pprint-list)
(use-method simple-dispatch clojure.lang.IPersistentVector pprint-vector)
(use-method simple-dispatch clojure.lang.IPersistentMap pprint-map)
(use-method simple-dispatch clojure.lang.IPersistentSet pprint-set)
(use-method simple-dispatch clojure.lang.PersistentQueue pprint-pqueue)
(use-method simple-dispatch clojure.lang.IDeref pprint-ideref)
(use-method simple-dispatch nil pr)
(use-method simple-dispatch :default pprint-simple-default)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Dispatch for the code table
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(declare pprint-simple-code-list)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Format the namespace ("ns") macro. This is quite complicated because of all the
;;; different forms supported and because programmers can choose lists or vectors
;;; in various places.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- brackets
"Figure out which kind of brackets to use"
[form]
(if (vector? form)
["[" "]"]
["(" ")"]))
(defn- pprint-ns-reference
"Pretty print a single reference (import, use, etc.) from a namespace decl"
[reference]
(if (sequential? reference)
(let [[start end] (brackets reference)
[keyw & args] reference]
(pprint-logical-block :prefix start :suffix end
((formatter-out "~w~:i") keyw)
(loop [args args]
(when (seq args)
((formatter-out " "))
(let [arg (first args)]
(if (sequential? arg)
(let [[start end] (brackets arg)]
(pprint-logical-block :prefix start :suffix end
(if (and (= (count arg) 3) (keyword? (second arg)))
(let [[ns kw lis] arg]
((formatter-out "~w ~w ") ns kw)
(if (sequential? lis)
((formatter-out (if (vector? lis)
"~<[~;~@{~w~^ ~:_~}~;]~:>"
"~<(~;~@{~w~^ ~:_~}~;)~:>"))
lis)
(write-out lis)))
(apply (formatter-out "~w ~:i~@{~w~^ ~:_~}") arg)))
(when (next args)
((formatter-out "~_"))))
(do
(write-out arg)
(when (next args)
((formatter-out "~:_"))))))
(recur (next args))))))
(write-out reference)))
(defn- pprint-ns
"The pretty print dispatch chunk for the ns macro"
[alis]
(if (next alis)
(let [[ns-sym ns-name & stuff] alis
[doc-str stuff] (if (string? (first stuff))
[(first stuff) (next stuff)]
[nil stuff])
[attr-map references] (if (map? (first stuff))
[(first stuff) (next stuff)]
[nil stuff])]
(pprint-logical-block :prefix "(" :suffix ")"
((formatter-out "~w ~1I~@_~w") ns-sym ns-name)
(when (or doc-str attr-map (seq references))
((formatter-out "~@:_")))
(when doc-str
(cl-format true "\"~a\"~:[~;~:@_~]" doc-str (or attr-map (seq references))))
(when attr-map
((formatter-out "~w~:[~;~:@_~]") attr-map (seq references)))
(loop [references references]
(pprint-ns-reference (first references))
(when-let [references (next references)]
(pprint-newline :linear)
(recur references)))))
(write-out alis)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Format something that looks like a simple def (sans metadata, since the reader
;;; won't give it to us now).
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^{:private true} pprint-hold-first (formatter-out "~:<~w~^ ~@_~w~^ ~_~@{~w~^ ~_~}~:>"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Format something that looks like a defn or defmacro
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Format the params and body of a defn with a single arity
(defn- single-defn [alis has-doc-str?]
(if (seq alis)
(do
(if has-doc-str?
((formatter-out " ~_"))
((formatter-out " ~@_")))
((formatter-out "~{~w~^ ~_~}") alis))))
;;; Format the param and body sublists of a defn with multiple arities
(defn- multi-defn [alis has-doc-str?]
(if (seq alis)
((formatter-out " ~_~{~w~^ ~_~}") alis)))
;;; TODO: figure out how to support capturing metadata in defns (we might need a
;;; special reader)
(defn- pprint-defn [alis]
(if (next alis)
(let [[defn-sym defn-name & stuff] alis
[doc-str stuff] (if (string? (first stuff))
[(first stuff) (next stuff)]
[nil stuff])
[attr-map stuff] (if (map? (first stuff))
[(first stuff) (next stuff)]
[nil stuff])]
(pprint-logical-block :prefix "(" :suffix ")"
((formatter-out "~w ~1I~@_~w") defn-sym defn-name)
(if doc-str
((formatter-out " ~_~w") doc-str))
(if attr-map
((formatter-out " ~_~w") attr-map))
;; Note: the multi-defn case will work OK for malformed defns too
(cond
(vector? (first stuff)) (single-defn stuff (or doc-str attr-map))
:else (multi-defn stuff (or doc-str attr-map)))))
(pprint-simple-code-list alis)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Format something with a binding form
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- pprint-binding-form [binding-vec]
(pprint-logical-block :prefix "[" :suffix "]"
(print-length-loop [binding binding-vec]
(when (seq binding)
(pprint-logical-block binding
(write-out (first binding))
(when (next binding)
(.write ^java.io.Writer *out* " ")
(pprint-newline :miser)
(write-out (second binding))))
(when (next (rest binding))
(.write ^java.io.Writer *out* " ")
(pprint-newline :linear)
(recur (next (rest binding))))))))
(defn- pprint-let [alis]
(let [base-sym (first alis)]
(pprint-logical-block :prefix "(" :suffix ")"
(if (and (next alis) (vector? (second alis)))
(do
((formatter-out "~w ~1I~@_") base-sym)
(pprint-binding-form (second alis))
((formatter-out " ~_~{~w~^ ~_~}") (next (rest alis))))
(pprint-simple-code-list alis)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Format something that looks like "if"
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^{:private true} pprint-if (formatter-out "~:<~1I~w~^ ~@_~w~@{ ~_~w~}~:>"))
(defn- pprint-cond [alis]
(pprint-logical-block :prefix "(" :suffix ")"
(pprint-indent :block 1)
(write-out (first alis))
(when (next alis)
(.write ^java.io.Writer *out* " ")
(pprint-newline :linear)
(print-length-loop [alis (next alis)]
(when alis
(pprint-logical-block alis
(write-out (first alis))
(when (next alis)
(.write ^java.io.Writer *out* " ")
(pprint-newline :miser)
(write-out (second alis))))
(when (next (rest alis))
(.write ^java.io.Writer *out* " ")
(pprint-newline :linear)
(recur (next (rest alis)))))))))
(defn- pprint-condp [alis]
(if (> (count alis) 3)
(pprint-logical-block :prefix "(" :suffix ")"
(pprint-indent :block 1)
(apply (formatter-out "~w ~@_~w ~@_~w ~_") alis)
(print-length-loop [alis (seq (drop 3 alis))]
(when alis
(pprint-logical-block alis
(write-out (first alis))
(when (next alis)
(.write ^java.io.Writer *out* " ")
(pprint-newline :miser)
(write-out (second alis))))
(when (next (rest alis))
(.write ^java.io.Writer *out* " ")
(pprint-newline :linear)
(recur (next (rest alis)))))))
(pprint-simple-code-list alis)))
;;; The map of symbols that are defined in an enclosing #() anonymous function
(def ^:dynamic ^{:private true} *symbol-map* {})
(defn- pprint-anon-func [alis]
(let [args (second alis)
nlis (first (rest (rest alis)))]
(if (vector? args)
(binding [*symbol-map* (if (= 1 (count args))
{(first args) "%"}
(into {}
(map
#(vector %1 (str \% %2))
args
(range 1 (inc (count args))))))]
((formatter-out "~<#(~;~@{~w~^ ~_~}~;)~:>") nlis))
(pprint-simple-code-list alis))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The master definitions for formatting lists in code (that is, (fn args...) or
;;; special forms).
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; This is the equivalent of (formatter-out "~:<~1I~@{~w~^ ~_~}~:>"), but is
;;; easier on the stack.
(defn- pprint-simple-code-list [alis]
(pprint-logical-block :prefix "(" :suffix ")"
(pprint-indent :block 1)
(print-length-loop [alis (seq alis)]
(when alis
(write-out (first alis))
(when (next alis)
(.write ^java.io.Writer *out* " ")
(pprint-newline :linear)
(recur (next alis)))))))
;;; Take a map with symbols as keys and add versions with no namespace.
;;; That is, if ns/sym->val is in the map, add sym->val to the result.
(defn- two-forms [amap]
(into {}
(mapcat
identity
(for [x amap]
[x [(symbol (name (first x))) (second x)]]))))
(defn- add-core-ns [amap]
(let [core "clojure.core"]
(into {}
(map #(let [[s f] %]
(if (not (or (namespace s) (special-symbol? s)))
[(symbol core (name s)) f]
%))
amap))))
(def ^:dynamic ^{:private true} *code-table*
(two-forms
(add-core-ns
{'def pprint-hold-first, 'defonce pprint-hold-first,
'defn pprint-defn, 'defn- pprint-defn, 'defmacro pprint-defn, 'fn pprint-defn,
'let pprint-let, 'loop pprint-let, 'binding pprint-let,
'with-local-vars pprint-let, 'with-open pprint-let, 'when-let pprint-let,
'if-let pprint-let, 'doseq pprint-let, 'dotimes pprint-let,
'when-first pprint-let,
'if pprint-if, 'if-not pprint-if, 'when pprint-if, 'when-not pprint-if,
'cond pprint-cond, 'condp pprint-condp,
'fn* pprint-anon-func,
'. pprint-hold-first, '.. pprint-hold-first, '-> pprint-hold-first,
'locking pprint-hold-first, 'struct pprint-hold-first,
'struct-map pprint-hold-first, 'ns pprint-ns
})))
(defn- pprint-code-list [alis]
(if-not (pprint-reader-macro alis)
(if-let [special-form (*code-table* (first alis))]
(special-form alis)
(pprint-simple-code-list alis))))
(defn- pprint-code-symbol [sym]
(if-let [arg-num (sym *symbol-map*)]
(print arg-num)
(if *print-suppress-namespaces*
(print (name sym))
(pr sym))))
(defmulti
code-dispatch
"The pretty print dispatch function for pretty printing Clojure code."
{:added "1.2" :arglists '[[object]]}
class)
(use-method code-dispatch clojure.lang.ISeq pprint-code-list)
(use-method code-dispatch clojure.lang.Symbol pprint-code-symbol)
;; The following are all exact copies of simple-dispatch
(use-method code-dispatch clojure.lang.IPersistentVector pprint-vector)
(use-method code-dispatch clojure.lang.IPersistentMap pprint-map)
(use-method code-dispatch clojure.lang.IPersistentSet pprint-set)
(use-method code-dispatch clojure.lang.PersistentQueue pprint-pqueue)
(use-method code-dispatch clojure.lang.IDeref pprint-ideref)
(use-method code-dispatch nil pr)
(use-method code-dispatch :default pprint-simple-default)
(set-pprint-dispatch simple-dispatch)
;;; For testing
(comment
(with-pprint-dispatch code-dispatch
(pprint
'(defn cl-format
"An implementation of a Common Lisp compatible format function"
[stream format-in & args]
(let [compiled-format (if (string? format-in) (compile-format format-in) format-in)
navigator (init-navigator args)]
(execute-format stream compiled-format navigator)))))
(with-pprint-dispatch code-dispatch
(pprint
'(defn cl-format
[stream format-in & args]
(let [compiled-format (if (string? format-in) (compile-format format-in) format-in)
navigator (init-navigator args)]
(execute-format stream compiled-format navigator)))))
(with-pprint-dispatch code-dispatch
(pprint
'(defn- -write
([this x]
(condp = (class x)
String
(let [s0 (write-initial-lines this x)
s (.replaceFirst s0 "\\s+$" "")
white-space (.substring s0 (count s))
mode (getf :mode)]
(if (= mode :writing)
(dosync
(write-white-space this)
(.col_write this s)
(setf :trailing-white-space white-space))
(add-to-buffer this (make-buffer-blob s white-space))))
Integer
(let [c ^Character x]
(if (= (getf :mode) :writing)
(do
(write-white-space this)
(.col_write this x))
(if (= c (int \newline))
(write-initial-lines this "\n")
(add-to-buffer this (make-buffer-blob (str (char c)) nil))))))))))
(with-pprint-dispatch code-dispatch
(pprint
'(defn pprint-defn [writer alis]
(if (next alis)
(let [[defn-sym defn-name & stuff] alis
[doc-str stuff] (if (string? (first stuff))
[(first stuff) (next stuff)]
[nil stuff])
[attr-map stuff] (if (map? (first stuff))
[(first stuff) (next stuff)]
[nil stuff])]
(pprint-logical-block writer :prefix "(" :suffix ")"
(cl-format true "~w ~1I~@_~w" defn-sym defn-name)
(if doc-str
(cl-format true " ~_~w" doc-str))
(if attr-map
(cl-format true " ~_~w" attr-map))
;; Note: the multi-defn case will work OK for malformed defns too
(cond
(vector? (first stuff)) (single-defn stuff (or doc-str attr-map))
:else (multi-defn stuff (or doc-str attr-map)))))
(pprint-simple-code-list writer alis)))))
)
nil
| 25194 | ;; dispatch.clj -- part of the pretty printer for Clojure
; Copyright (c) <NAME>. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
;; Author: <NAME>
;; April 3, 2009
;; This module implements the default dispatch tables for pretty printing code and
;; data.
(in-ns 'clojure.pprint)
(defn- use-method
"Installs a function as a new method of multimethod associated with dispatch-value. "
[multifn dispatch-val func]
(. multifn addMethod dispatch-val func))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Implementations of specific dispatch table entries
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Handle forms that can be "back-translated" to reader macros
;;; Not all reader macros can be dealt with this way or at all.
;;; Macros that we can't deal with at all are:
;;; ; - The comment character is absorbed by the reader and never is part of the form
;;; ` - Is fully processed at read time into a lisp expression (which will contain concats
;;; and regular quotes).
;;; ~@ - Also fully eaten by the processing of ` and can't be used outside.
;;; , - is whitespace and is lost (like all other whitespace). Formats can generate commas
;;; where they deem them useful to help readability.
;;; ^ - Adding metadata completely disappears at read time and the data appears to be
;;; completely lost.
;;;
;;; Most other syntax stuff is dealt with directly by the formats (like (), [], {}, and #{})
;;; or directly by printing the objects using Clojure's built-in print functions (like
;;; :keyword, \char, or ""). The notable exception is #() which is special-cased.
(def ^{:private true} reader-macros
{'quote "'", 'clojure.core/deref "@",
'var "#'", 'clojure.core/unquote "~"})
(defn- pprint-reader-macro [alis]
(let [^String macro-char (reader-macros (first alis))]
(when (and macro-char (= 2 (count alis)))
(.write ^java.io.Writer *out* macro-char)
(write-out (second alis))
true)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Dispatch for the basic data types when interpreted
;; as data (as opposed to code).
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; TODO: inline these formatter statements into funcs so that we
;;; are a little easier on the stack. (Or, do "real" compilation, a
;;; la Common Lisp)
;;; (def pprint-simple-list (formatter-out "~:<~@{~w~^ ~_~}~:>"))
(defn- pprint-simple-list [alis]
(pprint-logical-block :prefix "(" :suffix ")"
(print-length-loop [alis (seq alis)]
(when alis
(write-out (first alis))
(when (next alis)
(.write ^java.io.Writer *out* " ")
(pprint-newline :linear)
(recur (next alis)))))))
(defn- pprint-list [alis]
(if-not (pprint-reader-macro alis)
(pprint-simple-list alis)))
;;; (def pprint-vector (formatter-out "~<[~;~@{~w~^ ~_~}~;]~:>"))
(defn- pprint-vector [avec]
(pprint-logical-block :prefix "[" :suffix "]"
(print-length-loop [aseq (seq avec)]
(when aseq
(write-out (first aseq))
(when (next aseq)
(.write ^java.io.Writer *out* " ")
(pprint-newline :linear)
(recur (next aseq)))))))
(def ^{:private true} pprint-array (formatter-out "~<[~;~@{~w~^, ~:_~}~;]~:>"))
;;; (def pprint-map (formatter-out "~<{~;~@{~<~w~^ ~_~w~:>~^, ~_~}~;}~:>"))
(defn- pprint-map [amap]
(pprint-logical-block :prefix "{" :suffix "}"
(print-length-loop [aseq (seq amap)]
(when aseq
(pprint-logical-block
(write-out (ffirst aseq))
(.write ^java.io.Writer *out* " ")
(pprint-newline :linear)
(set! *current-length* 0) ; always print both parts of the [k v] pair
(write-out (fnext (first aseq))))
(when (next aseq)
(.write ^java.io.Writer *out* ", ")
(pprint-newline :linear)
(recur (next aseq)))))))
(def ^{:private true} pprint-set (formatter-out "~<#{~;~@{~w~^ ~:_~}~;}~:>"))
(def ^{:private true}
type-map {"core$future_call" "Future",
"core$promise" "Promise"})
(defn- map-ref-type
"Map ugly type names to something simpler"
[name]
(or (when-let [match (re-find #"^[^$]+\$[^$]+" name)]
(type-map match))
name))
(defn- pprint-ideref [o]
(let [prefix (format "#<%s@%x%s: "
(map-ref-type (.getSimpleName (class o)))
(System/identityHashCode o)
(if (and (instance? clojure.lang.Agent o)
(agent-error o))
" FAILED"
""))]
(pprint-logical-block :prefix prefix :suffix ">"
(pprint-indent :block (-> (count prefix) (- 2) -))
(pprint-newline :linear)
(write-out (cond
(and (future? o) (not (future-done? o))) :pending
(and (instance? clojure.lang.IPending o) (not (.isRealized o))) :not-delivered
:else @o)))))
(def ^{:private true} pprint-pqueue (formatter-out "~<<-(~;~@{~w~^ ~_~}~;)-<~:>"))
(defn- pprint-simple-default [obj]
(cond
(.isArray (class obj)) (pprint-array obj)
(and *print-suppress-namespaces* (symbol? obj)) (print (name obj))
:else (pr obj)))
(defmulti
simple-dispatch
"The pretty print dispatch function for simple data structure format."
{:added "1.2" :arglists '[[object]]}
class)
(use-method simple-dispatch clojure.lang.ISeq pprint-list)
(use-method simple-dispatch clojure.lang.IPersistentVector pprint-vector)
(use-method simple-dispatch clojure.lang.IPersistentMap pprint-map)
(use-method simple-dispatch clojure.lang.IPersistentSet pprint-set)
(use-method simple-dispatch clojure.lang.PersistentQueue pprint-pqueue)
(use-method simple-dispatch clojure.lang.IDeref pprint-ideref)
(use-method simple-dispatch nil pr)
(use-method simple-dispatch :default pprint-simple-default)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Dispatch for the code table
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(declare pprint-simple-code-list)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Format the namespace ("ns") macro. This is quite complicated because of all the
;;; different forms supported and because programmers can choose lists or vectors
;;; in various places.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- brackets
"Figure out which kind of brackets to use"
[form]
(if (vector? form)
["[" "]"]
["(" ")"]))
(defn- pprint-ns-reference
"Pretty print a single reference (import, use, etc.) from a namespace decl"
[reference]
(if (sequential? reference)
(let [[start end] (brackets reference)
[keyw & args] reference]
(pprint-logical-block :prefix start :suffix end
((formatter-out "~w~:i") keyw)
(loop [args args]
(when (seq args)
((formatter-out " "))
(let [arg (first args)]
(if (sequential? arg)
(let [[start end] (brackets arg)]
(pprint-logical-block :prefix start :suffix end
(if (and (= (count arg) 3) (keyword? (second arg)))
(let [[ns kw lis] arg]
((formatter-out "~w ~w ") ns kw)
(if (sequential? lis)
((formatter-out (if (vector? lis)
"~<[~;~@{~w~^ ~:_~}~;]~:>"
"~<(~;~@{~w~^ ~:_~}~;)~:>"))
lis)
(write-out lis)))
(apply (formatter-out "~w ~:i~@{~w~^ ~:_~}") arg)))
(when (next args)
((formatter-out "~_"))))
(do
(write-out arg)
(when (next args)
((formatter-out "~:_"))))))
(recur (next args))))))
(write-out reference)))
(defn- pprint-ns
"The pretty print dispatch chunk for the ns macro"
[alis]
(if (next alis)
(let [[ns-sym ns-name & stuff] alis
[doc-str stuff] (if (string? (first stuff))
[(first stuff) (next stuff)]
[nil stuff])
[attr-map references] (if (map? (first stuff))
[(first stuff) (next stuff)]
[nil stuff])]
(pprint-logical-block :prefix "(" :suffix ")"
((formatter-out "~w ~1I~@_~w") ns-sym ns-name)
(when (or doc-str attr-map (seq references))
((formatter-out "~@:_")))
(when doc-str
(cl-format true "\"~a\"~:[~;~:@_~]" doc-str (or attr-map (seq references))))
(when attr-map
((formatter-out "~w~:[~;~:@_~]") attr-map (seq references)))
(loop [references references]
(pprint-ns-reference (first references))
(when-let [references (next references)]
(pprint-newline :linear)
(recur references)))))
(write-out alis)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Format something that looks like a simple def (sans metadata, since the reader
;;; won't give it to us now).
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^{:private true} pprint-hold-first (formatter-out "~:<~w~^ ~@_~w~^ ~_~@{~w~^ ~_~}~:>"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Format something that looks like a defn or defmacro
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Format the params and body of a defn with a single arity
(defn- single-defn [alis has-doc-str?]
(if (seq alis)
(do
(if has-doc-str?
((formatter-out " ~_"))
((formatter-out " ~@_")))
((formatter-out "~{~w~^ ~_~}") alis))))
;;; Format the param and body sublists of a defn with multiple arities
(defn- multi-defn [alis has-doc-str?]
(if (seq alis)
((formatter-out " ~_~{~w~^ ~_~}") alis)))
;;; TODO: figure out how to support capturing metadata in defns (we might need a
;;; special reader)
(defn- pprint-defn [alis]
(if (next alis)
(let [[defn-sym defn-name & stuff] alis
[doc-str stuff] (if (string? (first stuff))
[(first stuff) (next stuff)]
[nil stuff])
[attr-map stuff] (if (map? (first stuff))
[(first stuff) (next stuff)]
[nil stuff])]
(pprint-logical-block :prefix "(" :suffix ")"
((formatter-out "~w ~1I~@_~w") defn-sym defn-name)
(if doc-str
((formatter-out " ~_~w") doc-str))
(if attr-map
((formatter-out " ~_~w") attr-map))
;; Note: the multi-defn case will work OK for malformed defns too
(cond
(vector? (first stuff)) (single-defn stuff (or doc-str attr-map))
:else (multi-defn stuff (or doc-str attr-map)))))
(pprint-simple-code-list alis)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Format something with a binding form
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- pprint-binding-form [binding-vec]
(pprint-logical-block :prefix "[" :suffix "]"
(print-length-loop [binding binding-vec]
(when (seq binding)
(pprint-logical-block binding
(write-out (first binding))
(when (next binding)
(.write ^java.io.Writer *out* " ")
(pprint-newline :miser)
(write-out (second binding))))
(when (next (rest binding))
(.write ^java.io.Writer *out* " ")
(pprint-newline :linear)
(recur (next (rest binding))))))))
(defn- pprint-let [alis]
(let [base-sym (first alis)]
(pprint-logical-block :prefix "(" :suffix ")"
(if (and (next alis) (vector? (second alis)))
(do
((formatter-out "~w ~1I~@_") base-sym)
(pprint-binding-form (second alis))
((formatter-out " ~_~{~w~^ ~_~}") (next (rest alis))))
(pprint-simple-code-list alis)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Format something that looks like "if"
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^{:private true} pprint-if (formatter-out "~:<~1I~w~^ ~@_~w~@{ ~_~w~}~:>"))
(defn- pprint-cond [alis]
(pprint-logical-block :prefix "(" :suffix ")"
(pprint-indent :block 1)
(write-out (first alis))
(when (next alis)
(.write ^java.io.Writer *out* " ")
(pprint-newline :linear)
(print-length-loop [alis (next alis)]
(when alis
(pprint-logical-block alis
(write-out (first alis))
(when (next alis)
(.write ^java.io.Writer *out* " ")
(pprint-newline :miser)
(write-out (second alis))))
(when (next (rest alis))
(.write ^java.io.Writer *out* " ")
(pprint-newline :linear)
(recur (next (rest alis)))))))))
(defn- pprint-condp [alis]
(if (> (count alis) 3)
(pprint-logical-block :prefix "(" :suffix ")"
(pprint-indent :block 1)
(apply (formatter-out "~w ~@_~w ~@_~w ~_") alis)
(print-length-loop [alis (seq (drop 3 alis))]
(when alis
(pprint-logical-block alis
(write-out (first alis))
(when (next alis)
(.write ^java.io.Writer *out* " ")
(pprint-newline :miser)
(write-out (second alis))))
(when (next (rest alis))
(.write ^java.io.Writer *out* " ")
(pprint-newline :linear)
(recur (next (rest alis)))))))
(pprint-simple-code-list alis)))
;;; The map of symbols that are defined in an enclosing #() anonymous function
(def ^:dynamic ^{:private true} *symbol-map* {})
(defn- pprint-anon-func [alis]
(let [args (second alis)
nlis (first (rest (rest alis)))]
(if (vector? args)
(binding [*symbol-map* (if (= 1 (count args))
{(first args) "%"}
(into {}
(map
#(vector %1 (str \% %2))
args
(range 1 (inc (count args))))))]
((formatter-out "~<#(~;~@{~w~^ ~_~}~;)~:>") nlis))
(pprint-simple-code-list alis))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The master definitions for formatting lists in code (that is, (fn args...) or
;;; special forms).
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; This is the equivalent of (formatter-out "~:<~1I~@{~w~^ ~_~}~:>"), but is
;;; easier on the stack.
(defn- pprint-simple-code-list [alis]
(pprint-logical-block :prefix "(" :suffix ")"
(pprint-indent :block 1)
(print-length-loop [alis (seq alis)]
(when alis
(write-out (first alis))
(when (next alis)
(.write ^java.io.Writer *out* " ")
(pprint-newline :linear)
(recur (next alis)))))))
;;; Take a map with symbols as keys and add versions with no namespace.
;;; That is, if ns/sym->val is in the map, add sym->val to the result.
(defn- two-forms [amap]
(into {}
(mapcat
identity
(for [x amap]
[x [(symbol (name (first x))) (second x)]]))))
(defn- add-core-ns [amap]
(let [core "clojure.core"]
(into {}
(map #(let [[s f] %]
(if (not (or (namespace s) (special-symbol? s)))
[(symbol core (name s)) f]
%))
amap))))
(def ^:dynamic ^{:private true} *code-table*
(two-forms
(add-core-ns
{'def pprint-hold-first, 'defonce pprint-hold-first,
'defn pprint-defn, 'defn- pprint-defn, 'defmacro pprint-defn, 'fn pprint-defn,
'let pprint-let, 'loop pprint-let, 'binding pprint-let,
'with-local-vars pprint-let, 'with-open pprint-let, 'when-let pprint-let,
'if-let pprint-let, 'doseq pprint-let, 'dotimes pprint-let,
'when-first pprint-let,
'if pprint-if, 'if-not pprint-if, 'when pprint-if, 'when-not pprint-if,
'cond pprint-cond, 'condp pprint-condp,
'fn* pprint-anon-func,
'. pprint-hold-first, '.. pprint-hold-first, '-> pprint-hold-first,
'locking pprint-hold-first, 'struct pprint-hold-first,
'struct-map pprint-hold-first, 'ns pprint-ns
})))
(defn- pprint-code-list [alis]
(if-not (pprint-reader-macro alis)
(if-let [special-form (*code-table* (first alis))]
(special-form alis)
(pprint-simple-code-list alis))))
(defn- pprint-code-symbol [sym]
(if-let [arg-num (sym *symbol-map*)]
(print arg-num)
(if *print-suppress-namespaces*
(print (name sym))
(pr sym))))
(defmulti
code-dispatch
"The pretty print dispatch function for pretty printing Clojure code."
{:added "1.2" :arglists '[[object]]}
class)
(use-method code-dispatch clojure.lang.ISeq pprint-code-list)
(use-method code-dispatch clojure.lang.Symbol pprint-code-symbol)
;; The following are all exact copies of simple-dispatch
(use-method code-dispatch clojure.lang.IPersistentVector pprint-vector)
(use-method code-dispatch clojure.lang.IPersistentMap pprint-map)
(use-method code-dispatch clojure.lang.IPersistentSet pprint-set)
(use-method code-dispatch clojure.lang.PersistentQueue pprint-pqueue)
(use-method code-dispatch clojure.lang.IDeref pprint-ideref)
(use-method code-dispatch nil pr)
(use-method code-dispatch :default pprint-simple-default)
(set-pprint-dispatch simple-dispatch)
;;; For testing
(comment
(with-pprint-dispatch code-dispatch
(pprint
'(defn cl-format
"An implementation of a Common Lisp compatible format function"
[stream format-in & args]
(let [compiled-format (if (string? format-in) (compile-format format-in) format-in)
navigator (init-navigator args)]
(execute-format stream compiled-format navigator)))))
(with-pprint-dispatch code-dispatch
(pprint
'(defn cl-format
[stream format-in & args]
(let [compiled-format (if (string? format-in) (compile-format format-in) format-in)
navigator (init-navigator args)]
(execute-format stream compiled-format navigator)))))
(with-pprint-dispatch code-dispatch
(pprint
'(defn- -write
([this x]
(condp = (class x)
String
(let [s0 (write-initial-lines this x)
s (.replaceFirst s0 "\\s+$" "")
white-space (.substring s0 (count s))
mode (getf :mode)]
(if (= mode :writing)
(dosync
(write-white-space this)
(.col_write this s)
(setf :trailing-white-space white-space))
(add-to-buffer this (make-buffer-blob s white-space))))
Integer
(let [c ^Character x]
(if (= (getf :mode) :writing)
(do
(write-white-space this)
(.col_write this x))
(if (= c (int \newline))
(write-initial-lines this "\n")
(add-to-buffer this (make-buffer-blob (str (char c)) nil))))))))))
(with-pprint-dispatch code-dispatch
(pprint
'(defn pprint-defn [writer alis]
(if (next alis)
(let [[defn-sym defn-name & stuff] alis
[doc-str stuff] (if (string? (first stuff))
[(first stuff) (next stuff)]
[nil stuff])
[attr-map stuff] (if (map? (first stuff))
[(first stuff) (next stuff)]
[nil stuff])]
(pprint-logical-block writer :prefix "(" :suffix ")"
(cl-format true "~w ~1I~@_~w" defn-sym defn-name)
(if doc-str
(cl-format true " ~_~w" doc-str))
(if attr-map
(cl-format true " ~_~w" attr-map))
;; Note: the multi-defn case will work OK for malformed defns too
(cond
(vector? (first stuff)) (single-defn stuff (or doc-str attr-map))
:else (multi-defn stuff (or doc-str attr-map)))))
(pprint-simple-code-list writer alis)))))
)
nil
| true | ;; dispatch.clj -- part of the pretty printer for Clojure
; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
;; Author: PI:NAME:<NAME>END_PI
;; April 3, 2009
;; This module implements the default dispatch tables for pretty printing code and
;; data.
(in-ns 'clojure.pprint)
(defn- use-method
"Installs a function as a new method of multimethod associated with dispatch-value. "
[multifn dispatch-val func]
(. multifn addMethod dispatch-val func))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Implementations of specific dispatch table entries
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Handle forms that can be "back-translated" to reader macros
;;; Not all reader macros can be dealt with this way or at all.
;;; Macros that we can't deal with at all are:
;;; ; - The comment character is absorbed by the reader and never is part of the form
;;; ` - Is fully processed at read time into a lisp expression (which will contain concats
;;; and regular quotes).
;;; ~@ - Also fully eaten by the processing of ` and can't be used outside.
;;; , - is whitespace and is lost (like all other whitespace). Formats can generate commas
;;; where they deem them useful to help readability.
;;; ^ - Adding metadata completely disappears at read time and the data appears to be
;;; completely lost.
;;;
;;; Most other syntax stuff is dealt with directly by the formats (like (), [], {}, and #{})
;;; or directly by printing the objects using Clojure's built-in print functions (like
;;; :keyword, \char, or ""). The notable exception is #() which is special-cased.
(def ^{:private true} reader-macros
{'quote "'", 'clojure.core/deref "@",
'var "#'", 'clojure.core/unquote "~"})
(defn- pprint-reader-macro [alis]
(let [^String macro-char (reader-macros (first alis))]
(when (and macro-char (= 2 (count alis)))
(.write ^java.io.Writer *out* macro-char)
(write-out (second alis))
true)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Dispatch for the basic data types when interpreted
;; as data (as opposed to code).
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; TODO: inline these formatter statements into funcs so that we
;;; are a little easier on the stack. (Or, do "real" compilation, a
;;; la Common Lisp)
;;; (def pprint-simple-list (formatter-out "~:<~@{~w~^ ~_~}~:>"))
(defn- pprint-simple-list [alis]
(pprint-logical-block :prefix "(" :suffix ")"
(print-length-loop [alis (seq alis)]
(when alis
(write-out (first alis))
(when (next alis)
(.write ^java.io.Writer *out* " ")
(pprint-newline :linear)
(recur (next alis)))))))
(defn- pprint-list [alis]
(if-not (pprint-reader-macro alis)
(pprint-simple-list alis)))
;;; (def pprint-vector (formatter-out "~<[~;~@{~w~^ ~_~}~;]~:>"))
(defn- pprint-vector [avec]
(pprint-logical-block :prefix "[" :suffix "]"
(print-length-loop [aseq (seq avec)]
(when aseq
(write-out (first aseq))
(when (next aseq)
(.write ^java.io.Writer *out* " ")
(pprint-newline :linear)
(recur (next aseq)))))))
(def ^{:private true} pprint-array (formatter-out "~<[~;~@{~w~^, ~:_~}~;]~:>"))
;;; (def pprint-map (formatter-out "~<{~;~@{~<~w~^ ~_~w~:>~^, ~_~}~;}~:>"))
(defn- pprint-map [amap]
(pprint-logical-block :prefix "{" :suffix "}"
(print-length-loop [aseq (seq amap)]
(when aseq
(pprint-logical-block
(write-out (ffirst aseq))
(.write ^java.io.Writer *out* " ")
(pprint-newline :linear)
(set! *current-length* 0) ; always print both parts of the [k v] pair
(write-out (fnext (first aseq))))
(when (next aseq)
(.write ^java.io.Writer *out* ", ")
(pprint-newline :linear)
(recur (next aseq)))))))
(def ^{:private true} pprint-set (formatter-out "~<#{~;~@{~w~^ ~:_~}~;}~:>"))
(def ^{:private true}
type-map {"core$future_call" "Future",
"core$promise" "Promise"})
(defn- map-ref-type
"Map ugly type names to something simpler"
[name]
(or (when-let [match (re-find #"^[^$]+\$[^$]+" name)]
(type-map match))
name))
(defn- pprint-ideref [o]
(let [prefix (format "#<%s@%x%s: "
(map-ref-type (.getSimpleName (class o)))
(System/identityHashCode o)
(if (and (instance? clojure.lang.Agent o)
(agent-error o))
" FAILED"
""))]
(pprint-logical-block :prefix prefix :suffix ">"
(pprint-indent :block (-> (count prefix) (- 2) -))
(pprint-newline :linear)
(write-out (cond
(and (future? o) (not (future-done? o))) :pending
(and (instance? clojure.lang.IPending o) (not (.isRealized o))) :not-delivered
:else @o)))))
(def ^{:private true} pprint-pqueue (formatter-out "~<<-(~;~@{~w~^ ~_~}~;)-<~:>"))
(defn- pprint-simple-default [obj]
(cond
(.isArray (class obj)) (pprint-array obj)
(and *print-suppress-namespaces* (symbol? obj)) (print (name obj))
:else (pr obj)))
(defmulti
simple-dispatch
"The pretty print dispatch function for simple data structure format."
{:added "1.2" :arglists '[[object]]}
class)
(use-method simple-dispatch clojure.lang.ISeq pprint-list)
(use-method simple-dispatch clojure.lang.IPersistentVector pprint-vector)
(use-method simple-dispatch clojure.lang.IPersistentMap pprint-map)
(use-method simple-dispatch clojure.lang.IPersistentSet pprint-set)
(use-method simple-dispatch clojure.lang.PersistentQueue pprint-pqueue)
(use-method simple-dispatch clojure.lang.IDeref pprint-ideref)
(use-method simple-dispatch nil pr)
(use-method simple-dispatch :default pprint-simple-default)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Dispatch for the code table
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(declare pprint-simple-code-list)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Format the namespace ("ns") macro. This is quite complicated because of all the
;;; different forms supported and because programmers can choose lists or vectors
;;; in various places.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- brackets
"Figure out which kind of brackets to use"
[form]
(if (vector? form)
["[" "]"]
["(" ")"]))
(defn- pprint-ns-reference
"Pretty print a single reference (import, use, etc.) from a namespace decl"
[reference]
(if (sequential? reference)
(let [[start end] (brackets reference)
[keyw & args] reference]
(pprint-logical-block :prefix start :suffix end
((formatter-out "~w~:i") keyw)
(loop [args args]
(when (seq args)
((formatter-out " "))
(let [arg (first args)]
(if (sequential? arg)
(let [[start end] (brackets arg)]
(pprint-logical-block :prefix start :suffix end
(if (and (= (count arg) 3) (keyword? (second arg)))
(let [[ns kw lis] arg]
((formatter-out "~w ~w ") ns kw)
(if (sequential? lis)
((formatter-out (if (vector? lis)
"~<[~;~@{~w~^ ~:_~}~;]~:>"
"~<(~;~@{~w~^ ~:_~}~;)~:>"))
lis)
(write-out lis)))
(apply (formatter-out "~w ~:i~@{~w~^ ~:_~}") arg)))
(when (next args)
((formatter-out "~_"))))
(do
(write-out arg)
(when (next args)
((formatter-out "~:_"))))))
(recur (next args))))))
(write-out reference)))
(defn- pprint-ns
"The pretty print dispatch chunk for the ns macro"
[alis]
(if (next alis)
(let [[ns-sym ns-name & stuff] alis
[doc-str stuff] (if (string? (first stuff))
[(first stuff) (next stuff)]
[nil stuff])
[attr-map references] (if (map? (first stuff))
[(first stuff) (next stuff)]
[nil stuff])]
(pprint-logical-block :prefix "(" :suffix ")"
((formatter-out "~w ~1I~@_~w") ns-sym ns-name)
(when (or doc-str attr-map (seq references))
((formatter-out "~@:_")))
(when doc-str
(cl-format true "\"~a\"~:[~;~:@_~]" doc-str (or attr-map (seq references))))
(when attr-map
((formatter-out "~w~:[~;~:@_~]") attr-map (seq references)))
(loop [references references]
(pprint-ns-reference (first references))
(when-let [references (next references)]
(pprint-newline :linear)
(recur references)))))
(write-out alis)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Format something that looks like a simple def (sans metadata, since the reader
;;; won't give it to us now).
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^{:private true} pprint-hold-first (formatter-out "~:<~w~^ ~@_~w~^ ~_~@{~w~^ ~_~}~:>"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Format something that looks like a defn or defmacro
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Format the params and body of a defn with a single arity
(defn- single-defn [alis has-doc-str?]
(if (seq alis)
(do
(if has-doc-str?
((formatter-out " ~_"))
((formatter-out " ~@_")))
((formatter-out "~{~w~^ ~_~}") alis))))
;;; Format the param and body sublists of a defn with multiple arities
(defn- multi-defn [alis has-doc-str?]
(if (seq alis)
((formatter-out " ~_~{~w~^ ~_~}") alis)))
;;; TODO: figure out how to support capturing metadata in defns (we might need a
;;; special reader)
(defn- pprint-defn [alis]
(if (next alis)
(let [[defn-sym defn-name & stuff] alis
[doc-str stuff] (if (string? (first stuff))
[(first stuff) (next stuff)]
[nil stuff])
[attr-map stuff] (if (map? (first stuff))
[(first stuff) (next stuff)]
[nil stuff])]
(pprint-logical-block :prefix "(" :suffix ")"
((formatter-out "~w ~1I~@_~w") defn-sym defn-name)
(if doc-str
((formatter-out " ~_~w") doc-str))
(if attr-map
((formatter-out " ~_~w") attr-map))
;; Note: the multi-defn case will work OK for malformed defns too
(cond
(vector? (first stuff)) (single-defn stuff (or doc-str attr-map))
:else (multi-defn stuff (or doc-str attr-map)))))
(pprint-simple-code-list alis)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Format something with a binding form
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- pprint-binding-form [binding-vec]
(pprint-logical-block :prefix "[" :suffix "]"
(print-length-loop [binding binding-vec]
(when (seq binding)
(pprint-logical-block binding
(write-out (first binding))
(when (next binding)
(.write ^java.io.Writer *out* " ")
(pprint-newline :miser)
(write-out (second binding))))
(when (next (rest binding))
(.write ^java.io.Writer *out* " ")
(pprint-newline :linear)
(recur (next (rest binding))))))))
(defn- pprint-let [alis]
(let [base-sym (first alis)]
(pprint-logical-block :prefix "(" :suffix ")"
(if (and (next alis) (vector? (second alis)))
(do
((formatter-out "~w ~1I~@_") base-sym)
(pprint-binding-form (second alis))
((formatter-out " ~_~{~w~^ ~_~}") (next (rest alis))))
(pprint-simple-code-list alis)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Format something that looks like "if"
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^{:private true} pprint-if (formatter-out "~:<~1I~w~^ ~@_~w~@{ ~_~w~}~:>"))
(defn- pprint-cond [alis]
(pprint-logical-block :prefix "(" :suffix ")"
(pprint-indent :block 1)
(write-out (first alis))
(when (next alis)
(.write ^java.io.Writer *out* " ")
(pprint-newline :linear)
(print-length-loop [alis (next alis)]
(when alis
(pprint-logical-block alis
(write-out (first alis))
(when (next alis)
(.write ^java.io.Writer *out* " ")
(pprint-newline :miser)
(write-out (second alis))))
(when (next (rest alis))
(.write ^java.io.Writer *out* " ")
(pprint-newline :linear)
(recur (next (rest alis)))))))))
(defn- pprint-condp [alis]
(if (> (count alis) 3)
(pprint-logical-block :prefix "(" :suffix ")"
(pprint-indent :block 1)
(apply (formatter-out "~w ~@_~w ~@_~w ~_") alis)
(print-length-loop [alis (seq (drop 3 alis))]
(when alis
(pprint-logical-block alis
(write-out (first alis))
(when (next alis)
(.write ^java.io.Writer *out* " ")
(pprint-newline :miser)
(write-out (second alis))))
(when (next (rest alis))
(.write ^java.io.Writer *out* " ")
(pprint-newline :linear)
(recur (next (rest alis)))))))
(pprint-simple-code-list alis)))
;;; The map of symbols that are defined in an enclosing #() anonymous function
(def ^:dynamic ^{:private true} *symbol-map* {})
(defn- pprint-anon-func [alis]
(let [args (second alis)
nlis (first (rest (rest alis)))]
(if (vector? args)
(binding [*symbol-map* (if (= 1 (count args))
{(first args) "%"}
(into {}
(map
#(vector %1 (str \% %2))
args
(range 1 (inc (count args))))))]
((formatter-out "~<#(~;~@{~w~^ ~_~}~;)~:>") nlis))
(pprint-simple-code-list alis))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The master definitions for formatting lists in code (that is, (fn args...) or
;;; special forms).
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; This is the equivalent of (formatter-out "~:<~1I~@{~w~^ ~_~}~:>"), but is
;;; easier on the stack.
(defn- pprint-simple-code-list [alis]
(pprint-logical-block :prefix "(" :suffix ")"
(pprint-indent :block 1)
(print-length-loop [alis (seq alis)]
(when alis
(write-out (first alis))
(when (next alis)
(.write ^java.io.Writer *out* " ")
(pprint-newline :linear)
(recur (next alis)))))))
;;; Take a map with symbols as keys and add versions with no namespace.
;;; That is, if ns/sym->val is in the map, add sym->val to the result.
(defn- two-forms [amap]
(into {}
(mapcat
identity
(for [x amap]
[x [(symbol (name (first x))) (second x)]]))))
(defn- add-core-ns [amap]
(let [core "clojure.core"]
(into {}
(map #(let [[s f] %]
(if (not (or (namespace s) (special-symbol? s)))
[(symbol core (name s)) f]
%))
amap))))
(def ^:dynamic ^{:private true} *code-table*
(two-forms
(add-core-ns
{'def pprint-hold-first, 'defonce pprint-hold-first,
'defn pprint-defn, 'defn- pprint-defn, 'defmacro pprint-defn, 'fn pprint-defn,
'let pprint-let, 'loop pprint-let, 'binding pprint-let,
'with-local-vars pprint-let, 'with-open pprint-let, 'when-let pprint-let,
'if-let pprint-let, 'doseq pprint-let, 'dotimes pprint-let,
'when-first pprint-let,
'if pprint-if, 'if-not pprint-if, 'when pprint-if, 'when-not pprint-if,
'cond pprint-cond, 'condp pprint-condp,
'fn* pprint-anon-func,
'. pprint-hold-first, '.. pprint-hold-first, '-> pprint-hold-first,
'locking pprint-hold-first, 'struct pprint-hold-first,
'struct-map pprint-hold-first, 'ns pprint-ns
})))
(defn- pprint-code-list [alis]
(if-not (pprint-reader-macro alis)
(if-let [special-form (*code-table* (first alis))]
(special-form alis)
(pprint-simple-code-list alis))))
(defn- pprint-code-symbol [sym]
(if-let [arg-num (sym *symbol-map*)]
(print arg-num)
(if *print-suppress-namespaces*
(print (name sym))
(pr sym))))
(defmulti
code-dispatch
"The pretty print dispatch function for pretty printing Clojure code."
{:added "1.2" :arglists '[[object]]}
class)
(use-method code-dispatch clojure.lang.ISeq pprint-code-list)
(use-method code-dispatch clojure.lang.Symbol pprint-code-symbol)
;; The following are all exact copies of simple-dispatch
(use-method code-dispatch clojure.lang.IPersistentVector pprint-vector)
(use-method code-dispatch clojure.lang.IPersistentMap pprint-map)
(use-method code-dispatch clojure.lang.IPersistentSet pprint-set)
(use-method code-dispatch clojure.lang.PersistentQueue pprint-pqueue)
(use-method code-dispatch clojure.lang.IDeref pprint-ideref)
(use-method code-dispatch nil pr)
(use-method code-dispatch :default pprint-simple-default)
(set-pprint-dispatch simple-dispatch)
;;; For testing
(comment
(with-pprint-dispatch code-dispatch
(pprint
'(defn cl-format
"An implementation of a Common Lisp compatible format function"
[stream format-in & args]
(let [compiled-format (if (string? format-in) (compile-format format-in) format-in)
navigator (init-navigator args)]
(execute-format stream compiled-format navigator)))))
(with-pprint-dispatch code-dispatch
(pprint
'(defn cl-format
[stream format-in & args]
(let [compiled-format (if (string? format-in) (compile-format format-in) format-in)
navigator (init-navigator args)]
(execute-format stream compiled-format navigator)))))
(with-pprint-dispatch code-dispatch
(pprint
'(defn- -write
([this x]
(condp = (class x)
String
(let [s0 (write-initial-lines this x)
s (.replaceFirst s0 "\\s+$" "")
white-space (.substring s0 (count s))
mode (getf :mode)]
(if (= mode :writing)
(dosync
(write-white-space this)
(.col_write this s)
(setf :trailing-white-space white-space))
(add-to-buffer this (make-buffer-blob s white-space))))
Integer
(let [c ^Character x]
(if (= (getf :mode) :writing)
(do
(write-white-space this)
(.col_write this x))
(if (= c (int \newline))
(write-initial-lines this "\n")
(add-to-buffer this (make-buffer-blob (str (char c)) nil))))))))))
(with-pprint-dispatch code-dispatch
(pprint
'(defn pprint-defn [writer alis]
(if (next alis)
(let [[defn-sym defn-name & stuff] alis
[doc-str stuff] (if (string? (first stuff))
[(first stuff) (next stuff)]
[nil stuff])
[attr-map stuff] (if (map? (first stuff))
[(first stuff) (next stuff)]
[nil stuff])]
(pprint-logical-block writer :prefix "(" :suffix ")"
(cl-format true "~w ~1I~@_~w" defn-sym defn-name)
(if doc-str
(cl-format true " ~_~w" doc-str))
(if attr-map
(cl-format true " ~_~w" attr-map))
;; Note: the multi-defn case will work OK for malformed defns too
(cond
(vector? (first stuff)) (single-defn stuff (or doc-str attr-map))
:else (multi-defn stuff (or doc-str attr-map)))))
(pprint-simple-code-list writer alis)))))
)
nil
|
[
{
"context": "; Copyright (c) Rich Hickey. All rights reserved.\n; The use and distributio",
"end": 29,
"score": 0.9998069405555725,
"start": 18,
"tag": "NAME",
"value": "Rich Hickey"
}
] | clojure-tools/src/clojure/tools/deps/alpha/extensions/pom.clj | FundingCircle/ein.alpha | 5 | ; Copyright (c) Rich Hickey. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns clojure.tools.deps.alpha.extensions.pom
(:require
[clojure.java.io :as jio]
[clojure.string :as str]
[clojure.tools.deps.alpha.extensions :as ext]
[clojure.tools.deps.alpha.util.maven :as maven])
(:import
[java.io File]
[java.util List]
;; maven-model
[org.apache.maven.model Model Dependency Exclusion]
;; maven-model-builder
[org.apache.maven.model.building DefaultModelBuildingRequest DefaultModelBuilderFactory ModelSource FileModelSource]
[org.apache.maven.model.resolution ModelResolver]
;; maven-aether-provider
[org.apache.maven.repository.internal DefaultModelResolver DefaultVersionRangeResolver]
;; maven-resolver-api
[org.eclipse.aether RepositorySystemSession RequestTrace]
;; maven-resolver-impl
[org.eclipse.aether.impl ArtifactResolver VersionRangeResolver RemoteRepositoryManager]
[org.eclipse.aether.internal.impl DefaultRemoteRepositoryManager]
;; maven-resolver-spi
[org.eclipse.aether.spi.locator ServiceLocator]))
(set! *warn-on-reflection* true)
(defn- model-resolver
^ModelResolver [{:keys [mvn/repos mvn/local-repo]}]
(let [local-repo (or local-repo maven/default-local-repo)
locator ^ServiceLocator @maven/the-locator
system (maven/make-system)
session (maven/make-session system local-repo)
artifact-resolver (.getService locator ArtifactResolver)
version-range-resolver (doto (DefaultVersionRangeResolver.) (.initService locator))
repo-mgr (doto (DefaultRemoteRepositoryManager.) (.initService locator))
repos (mapv maven/remote-repo repos)
ct (.getConstructor org.apache.maven.repository.internal.DefaultModelResolver
(into-array [RepositorySystemSession RequestTrace String ArtifactResolver VersionRangeResolver RemoteRepositoryManager List]))]
(.setAccessible ct true) ;; turn away from the horror
(.newInstance ct (object-array [session nil "runtime" artifact-resolver version-range-resolver repo-mgr repos]))))
;; pom (jio/file dir "pom.xml")
(defn read-model
^Model [^ModelSource source config]
(let [req (doto (DefaultModelBuildingRequest.)
(.setModelSource source)
(.setModelResolver (model-resolver config)))
builder (.newInstance (DefaultModelBuilderFactory.))
result (.build builder req)]
(.getEffectiveModel result)))
(defn- read-model-file
^Model [^File file config]
(read-model (FileModelSource. file) config))
(defn- model-exclusions->data
[exclusions]
(when (and exclusions (pos? (count exclusions)))
(into #{}
(map (fn [^Exclusion exclusion]
(symbol (.getGroupId exclusion) (.getArtifactId exclusion))))
exclusions)))
(defn- model-dep->data
[^Dependency dep]
(let [scope (.getScope dep)
optional (.isOptional dep)
exclusions (model-exclusions->data (.getExclusions dep))
classifier (.getClassifier dep)]
[(symbol (.getGroupId dep) (.getArtifactId dep))
(cond-> {:mvn/version (.getVersion dep)}
(not (str/blank? classifier)) (assoc :classifier classifier)
scope (assoc :scope scope)
optional (assoc :optional true)
(seq exclusions) (assoc :exclusions exclusions))]))
(defn model-deps
[^Model model]
(map model-dep->data (.getDependencies model)))
(defmethod ext/coord-deps :pom
[_lib {:keys [deps/root] :as coord} _mf config]
(let [pom (jio/file root "pom.xml")
model (read-model-file pom config)]
(model-deps model)))
(defmethod ext/coord-paths :pom
[_lib {:keys [deps/root] :as coord} _mf config]
(let [pom (jio/file root "pom.xml")
model (read-model-file pom config)
srcs [(.getCanonicalPath (jio/file (.. model getBuild getSourceDirectory)))
(.getCanonicalPath (jio/file root "src/main/clojure"))]]
(distinct srcs)))
(comment
(ext/coord-deps 'org.clojure/core.async {:deps/root "../core.async" :deps/manifest :pom}
:pom {:mvn/repos maven/standard-repos})
(ext/coord-paths 'org.clojure/core.async {:deps/root "../core.async" :deps/manifest :pom}
:pom {:mvn/repos maven/standard-repos})
)
| 47846 | ; Copyright (c) <NAME>. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns clojure.tools.deps.alpha.extensions.pom
(:require
[clojure.java.io :as jio]
[clojure.string :as str]
[clojure.tools.deps.alpha.extensions :as ext]
[clojure.tools.deps.alpha.util.maven :as maven])
(:import
[java.io File]
[java.util List]
;; maven-model
[org.apache.maven.model Model Dependency Exclusion]
;; maven-model-builder
[org.apache.maven.model.building DefaultModelBuildingRequest DefaultModelBuilderFactory ModelSource FileModelSource]
[org.apache.maven.model.resolution ModelResolver]
;; maven-aether-provider
[org.apache.maven.repository.internal DefaultModelResolver DefaultVersionRangeResolver]
;; maven-resolver-api
[org.eclipse.aether RepositorySystemSession RequestTrace]
;; maven-resolver-impl
[org.eclipse.aether.impl ArtifactResolver VersionRangeResolver RemoteRepositoryManager]
[org.eclipse.aether.internal.impl DefaultRemoteRepositoryManager]
;; maven-resolver-spi
[org.eclipse.aether.spi.locator ServiceLocator]))
(set! *warn-on-reflection* true)
(defn- model-resolver
^ModelResolver [{:keys [mvn/repos mvn/local-repo]}]
(let [local-repo (or local-repo maven/default-local-repo)
locator ^ServiceLocator @maven/the-locator
system (maven/make-system)
session (maven/make-session system local-repo)
artifact-resolver (.getService locator ArtifactResolver)
version-range-resolver (doto (DefaultVersionRangeResolver.) (.initService locator))
repo-mgr (doto (DefaultRemoteRepositoryManager.) (.initService locator))
repos (mapv maven/remote-repo repos)
ct (.getConstructor org.apache.maven.repository.internal.DefaultModelResolver
(into-array [RepositorySystemSession RequestTrace String ArtifactResolver VersionRangeResolver RemoteRepositoryManager List]))]
(.setAccessible ct true) ;; turn away from the horror
(.newInstance ct (object-array [session nil "runtime" artifact-resolver version-range-resolver repo-mgr repos]))))
;; pom (jio/file dir "pom.xml")
(defn read-model
^Model [^ModelSource source config]
(let [req (doto (DefaultModelBuildingRequest.)
(.setModelSource source)
(.setModelResolver (model-resolver config)))
builder (.newInstance (DefaultModelBuilderFactory.))
result (.build builder req)]
(.getEffectiveModel result)))
(defn- read-model-file
^Model [^File file config]
(read-model (FileModelSource. file) config))
(defn- model-exclusions->data
[exclusions]
(when (and exclusions (pos? (count exclusions)))
(into #{}
(map (fn [^Exclusion exclusion]
(symbol (.getGroupId exclusion) (.getArtifactId exclusion))))
exclusions)))
(defn- model-dep->data
[^Dependency dep]
(let [scope (.getScope dep)
optional (.isOptional dep)
exclusions (model-exclusions->data (.getExclusions dep))
classifier (.getClassifier dep)]
[(symbol (.getGroupId dep) (.getArtifactId dep))
(cond-> {:mvn/version (.getVersion dep)}
(not (str/blank? classifier)) (assoc :classifier classifier)
scope (assoc :scope scope)
optional (assoc :optional true)
(seq exclusions) (assoc :exclusions exclusions))]))
(defn model-deps
[^Model model]
(map model-dep->data (.getDependencies model)))
(defmethod ext/coord-deps :pom
[_lib {:keys [deps/root] :as coord} _mf config]
(let [pom (jio/file root "pom.xml")
model (read-model-file pom config)]
(model-deps model)))
(defmethod ext/coord-paths :pom
[_lib {:keys [deps/root] :as coord} _mf config]
(let [pom (jio/file root "pom.xml")
model (read-model-file pom config)
srcs [(.getCanonicalPath (jio/file (.. model getBuild getSourceDirectory)))
(.getCanonicalPath (jio/file root "src/main/clojure"))]]
(distinct srcs)))
(comment
(ext/coord-deps 'org.clojure/core.async {:deps/root "../core.async" :deps/manifest :pom}
:pom {:mvn/repos maven/standard-repos})
(ext/coord-paths 'org.clojure/core.async {:deps/root "../core.async" :deps/manifest :pom}
:pom {:mvn/repos maven/standard-repos})
)
| true | ; Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns clojure.tools.deps.alpha.extensions.pom
(:require
[clojure.java.io :as jio]
[clojure.string :as str]
[clojure.tools.deps.alpha.extensions :as ext]
[clojure.tools.deps.alpha.util.maven :as maven])
(:import
[java.io File]
[java.util List]
;; maven-model
[org.apache.maven.model Model Dependency Exclusion]
;; maven-model-builder
[org.apache.maven.model.building DefaultModelBuildingRequest DefaultModelBuilderFactory ModelSource FileModelSource]
[org.apache.maven.model.resolution ModelResolver]
;; maven-aether-provider
[org.apache.maven.repository.internal DefaultModelResolver DefaultVersionRangeResolver]
;; maven-resolver-api
[org.eclipse.aether RepositorySystemSession RequestTrace]
;; maven-resolver-impl
[org.eclipse.aether.impl ArtifactResolver VersionRangeResolver RemoteRepositoryManager]
[org.eclipse.aether.internal.impl DefaultRemoteRepositoryManager]
;; maven-resolver-spi
[org.eclipse.aether.spi.locator ServiceLocator]))
(set! *warn-on-reflection* true)
(defn- model-resolver
^ModelResolver [{:keys [mvn/repos mvn/local-repo]}]
(let [local-repo (or local-repo maven/default-local-repo)
locator ^ServiceLocator @maven/the-locator
system (maven/make-system)
session (maven/make-session system local-repo)
artifact-resolver (.getService locator ArtifactResolver)
version-range-resolver (doto (DefaultVersionRangeResolver.) (.initService locator))
repo-mgr (doto (DefaultRemoteRepositoryManager.) (.initService locator))
repos (mapv maven/remote-repo repos)
ct (.getConstructor org.apache.maven.repository.internal.DefaultModelResolver
(into-array [RepositorySystemSession RequestTrace String ArtifactResolver VersionRangeResolver RemoteRepositoryManager List]))]
(.setAccessible ct true) ;; turn away from the horror
(.newInstance ct (object-array [session nil "runtime" artifact-resolver version-range-resolver repo-mgr repos]))))
;; pom (jio/file dir "pom.xml")
(defn read-model
^Model [^ModelSource source config]
(let [req (doto (DefaultModelBuildingRequest.)
(.setModelSource source)
(.setModelResolver (model-resolver config)))
builder (.newInstance (DefaultModelBuilderFactory.))
result (.build builder req)]
(.getEffectiveModel result)))
(defn- read-model-file
^Model [^File file config]
(read-model (FileModelSource. file) config))
(defn- model-exclusions->data
[exclusions]
(when (and exclusions (pos? (count exclusions)))
(into #{}
(map (fn [^Exclusion exclusion]
(symbol (.getGroupId exclusion) (.getArtifactId exclusion))))
exclusions)))
(defn- model-dep->data
[^Dependency dep]
(let [scope (.getScope dep)
optional (.isOptional dep)
exclusions (model-exclusions->data (.getExclusions dep))
classifier (.getClassifier dep)]
[(symbol (.getGroupId dep) (.getArtifactId dep))
(cond-> {:mvn/version (.getVersion dep)}
(not (str/blank? classifier)) (assoc :classifier classifier)
scope (assoc :scope scope)
optional (assoc :optional true)
(seq exclusions) (assoc :exclusions exclusions))]))
(defn model-deps
[^Model model]
(map model-dep->data (.getDependencies model)))
(defmethod ext/coord-deps :pom
[_lib {:keys [deps/root] :as coord} _mf config]
(let [pom (jio/file root "pom.xml")
model (read-model-file pom config)]
(model-deps model)))
(defmethod ext/coord-paths :pom
[_lib {:keys [deps/root] :as coord} _mf config]
(let [pom (jio/file root "pom.xml")
model (read-model-file pom config)
srcs [(.getCanonicalPath (jio/file (.. model getBuild getSourceDirectory)))
(.getCanonicalPath (jio/file root "src/main/clojure"))]]
(distinct srcs)))
(comment
(ext/coord-deps 'org.clojure/core.async {:deps/root "../core.async" :deps/manifest :pom}
:pom {:mvn/repos maven/standard-repos})
(ext/coord-paths 'org.clojure/core.async {:deps/root "../core.async" :deps/manifest :pom}
:pom {:mvn/repos maven/standard-repos})
)
|
[
{
"context": "ns under the License.\n;;\n;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.\n\n(ns czlab.niou.webss\n\n \"A",
"end": 597,
"score": 0.999864935874939,
"start": 584,
"tag": "NAME",
"value": "Kenneth Leung"
}
] | src/main/clojure/czlab/niou/webss.clj | llnek/nettio | 0 | ;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; Copyright © 2013-2022, Kenneth Leung. All rights reserved.
(ns czlab.niou.webss
"A Http Web Session."
(:require [czlab.twisty.core :as t]
[clojure.java.io :as io]
[clojure.string :as cs]
[czlab.basal.util :as u]
[czlab.basal.io :as i]
[czlab.basal.core :as c]
[czlab.niou.core :as v])
(:import [java.security GeneralSecurityException]
[java.net HttpCookie]
[java.util Date]
[java.io File]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* true)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^String session-cookie "__xs117")
(def ^String csrf-cookie "__xc117")
(def ^String capc-cookie "__xp117")
(def ^String nv-sep "&")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/def- ssid-flag :__xf01es)
(c/def- user-flag :__u982i)
(c/def- ct-flag :__xf184n ) ;; creation time
(c/def- is-flag :__xf284n ) ;; max idle secs
(c/def- lt-flag :__xf384n ) ;; last access time
(c/def- et-flag :__xf484n ) ;; expiry time
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- reset-flags
"A negative value means that the cookie
is not stored persistently and will be deleted
when the Web browser exits.
A zero value causes the cookie to be deleted."
[mvs {:strs [max-age-secs max-idle-secs] :as cfg}]
(let [now (u/system-time)]
(c/assoc!! mvs
:impls cfg
:attrs
{ssid-flag (u/uid<>)
ct-flag now
lt-flag now
is-flag max-idle-secs
et-flag (if-not (c/spos? max-age-secs)
-1 (+ now (* max-age-secs 1000)))})))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- test-cookie
[pkey {:keys [crypt? $cright $cleft]}]
(if crypt?
(when (or (c/nichts? $cright)
(c/nichts? $cleft)
(.equals ^String $cleft
(t/gen-mac pkey $cright)))
(c/error "session cookie - broken.")
(c/trap! GeneralSecurityException "Bad Session Cookie."))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- crack-cookie!
[wss ^HttpCookie ck encrypt?]
(let [cookie (str (some-> ck .getValue))
pos (cs/index-of cookie \|)
[p1 p2] (if (nil? pos)
["" cookie]
[(subs cookie 0 pos)
(subs cookie (+ 1 pos))])]
(c/debug "session left=%s right=%s." p1 p2)
(swap! wss
#(update-in %
[:impls]
assoc
:crypt? encrypt?
:$cright p2
:$cleft p1
:domain-path (some-> ck .getPath)
:domain (some-> ck .getDomain)
:secure? (some-> ck .getSecure)
:hidden? (some-> ck .isHttpOnly)
:max-age-secs (some-> ck .getMaxAge)))
(doseq [nv (c/split p2 nv-sep)
:let [ss (c/split nv "=" 2)]
:when (c/two? ss)]
(let [s1 (u/url-decode (c/_1 ss))
s2 (u/url-decode (c/_2 ss))]
(c/debug "s-attr n=%s, v=%s." s1 s2)
(swap! wss
#(update-in %
[:attrs]
assoc
(keyword s1)
(if (c/wrapped? s1 "__xf" "n") (c/s->long s2 0) s2)))))
wss))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-session-new?
"If session is brand new?"
{:arglists '([wss])}
[wss]
(boolean (get-in @wss [:impls :$new?])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-session-null?
"If session is a null session?"
{:arglists '([wss])}
[wss]
(empty? (:impls @wss)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn set-max-idle-secs
"Set the max idle seconds."
{:arglists '([wss idleSecs])}
[wss idleSecs]
(swap! wss
#(update-in %
[:attrs]
assoc is-flag idleSecs)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn last-accessed-time
"Get the last accessed time."
{:arglists '([wss])}
[wss]
(c/num?? (lt-flag (:attrs @wss)) -1))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn max-idle-secs
"Get the max idle seconds."
{:arglists '([wss])}
[wss]
(c/num?? (is-flag (:attrs @wss)) -1))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn creation-time
"Get the creation time."
{:arglists '([wss])}
[wss]
(c/num?? (ct-flag (:attrs @wss)) -1))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn expiry-time
"Get the expiry time."
{:arglists '([wss])}
[wss]
(c/num?? (et-flag (:attrs @wss)) -1))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn session-signer
"Get the session's signing key."
{:arglists '([wss])}
[wss]
(:$pkey @wss))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn validate??
"Validate this session."
{:arglists '([wss])}
[wss]
(let [ts (last-accessed-time wss)
mi (max-idle-secs wss)
es (expiry-time wss)
now (u/system-time)]
(test-cookie (session-signer wss) @wss)
(if (or (and (c/spos? es) (< es now))
(and (c/spos? mi)
(< (+ ts (* 1000 mi)) now)))
(c/trap! GeneralSecurityException "Session has expired"))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn remove-session-attr
"Remove an attribute from session."
{:arglists '([wss k])}
[wss k]
(swap! wss
#(update-in % [:attrs] dissoc k)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn set-session-attr
"Set a session's attribute value."
{:arglists '([wss k v])}
[wss k v]
(swap! wss
#(update-in % [:attrs] assoc k v)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn session-attr
"Get a session attribute."
{:arglists '([wss k])}
[wss k]
(get-in @wss [:attrs k]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn remove-session-attrs
"Clear all session attibutes."
{:arglists '([wss])}
[wss]
(c/assoc!! wss :attrs {}))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn session-attrs
"Get the session attibutes."
{:arglists '([wss])}
[wss]
(:attrs @wss))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn invalidate!
"Invalidate this session."
{:arglists '([wss])}
[wss]
(c/assoc!! wss :impls {} :attrs {}))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn set-principal
"Set the user id."
{:arglists '([wss p])}
[wss p]
(swap! wss
#(update-in % [:impls] assoc user-flag p)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn principal
"Get the user id."
{:arglists '([wss])}
[wss]
(get-in @wss [:impls user-flag]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn set-session-new
"Set a new session with data."
{:arglists '([wss flag? arg])}
[wss flag? arg]
(when flag?
(invalidate! wss)
(reset-flags wss arg))
(swap! wss
#(update-in % [:impls] assoc :$new? flag?)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn session-error
"Get the last session error."
{:arglists '([wss])}
[wss]
(get-in @wss [:impls :$error]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn set-session-error
"Set the last session error."
{:arglists '([wss t])}
[wss t]
(swap! wss
#(update-in % [:impls] assoc :$error t)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn encode-attrs
"URL encode the session attributes."
{:arglists '([wss])}
[wss]
(c/sreduce<>
#(let [[k v] %2]
(c/sbf-join %1
nv-sep
(str (-> (name k)
(u/url-encode))
"="
(u/url-encode v)))) (session-attrs wss)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn session-id
"Get the session id."
{:arglists '([wss])}
[wss]
(get-in @wss [:impls ssid-flag]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn wsession<>
"Create a Web Session."
{:arglists '([pkey]
[pkey arg]
[pkey cookie secure?])}
([^bytes pkey cookie secure?]
(doto
(wsession<> pkey)
(set-session-new false nil)
(crack-cookie! cookie secure?)))
([^bytes pkey arg]
(doto
(wsession<> pkey)
(set-session-new true arg)))
([^bytes pkey]
(atom {:$pkey pkey
:attrs {}
:impls {:$new? true}})))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- macit??
[pkey data secure?]
(if secure? (str (t/gen-mac pkey data) "|" data) data))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn downstream
"Set session-cookie for outbound message#response."
{:arglists '([res][res session])}
([res]
(downstream res nil))
([res sessionObj]
(let [req (:request res)
mvs (or sessionObj
(:session req))]
(if (or (nil? mvs)
(is-session-null? mvs))
res
(let [_ (c/debug "session ok, about to set-cookie!")
pkey (session-signer mvs)
data (encode-attrs mvs)
{{:keys [max-age-secs
domain-path
domain
crypt? hidden? secure?]} :impls} @mvs
ck (->> (macit?? pkey data crypt?)
(HttpCookie. session-cookie))]
;;session cookie should always be -1 -> maxAge
;;and really should be httpOnly=true
(doto ck
(.setHttpOnly (boolean hidden?))
(.setSecure (boolean secure?))
(.setMaxAge (if (c/spos? max-age-secs) max-age-secs -1)))
(if (c/hgl? domain-path) (.setPath ck domain-path))
(if (c/hgl? domain) (.setDomain ck domain))
(update-in res
[:cookies] assoc (.getName ck) ck))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn upstream
"Create session from session-cookie."
{:arglists '([pkey cookies encrypt?])}
[pkey cookies encrypt?]
(wsession<> pkey (get cookies session-cookie) encrypt?))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
| 41472 | ;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; Copyright © 2013-2022, <NAME>. All rights reserved.
(ns czlab.niou.webss
"A Http Web Session."
(:require [czlab.twisty.core :as t]
[clojure.java.io :as io]
[clojure.string :as cs]
[czlab.basal.util :as u]
[czlab.basal.io :as i]
[czlab.basal.core :as c]
[czlab.niou.core :as v])
(:import [java.security GeneralSecurityException]
[java.net HttpCookie]
[java.util Date]
[java.io File]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* true)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^String session-cookie "__xs117")
(def ^String csrf-cookie "__xc117")
(def ^String capc-cookie "__xp117")
(def ^String nv-sep "&")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/def- ssid-flag :__xf01es)
(c/def- user-flag :__u982i)
(c/def- ct-flag :__xf184n ) ;; creation time
(c/def- is-flag :__xf284n ) ;; max idle secs
(c/def- lt-flag :__xf384n ) ;; last access time
(c/def- et-flag :__xf484n ) ;; expiry time
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- reset-flags
"A negative value means that the cookie
is not stored persistently and will be deleted
when the Web browser exits.
A zero value causes the cookie to be deleted."
[mvs {:strs [max-age-secs max-idle-secs] :as cfg}]
(let [now (u/system-time)]
(c/assoc!! mvs
:impls cfg
:attrs
{ssid-flag (u/uid<>)
ct-flag now
lt-flag now
is-flag max-idle-secs
et-flag (if-not (c/spos? max-age-secs)
-1 (+ now (* max-age-secs 1000)))})))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- test-cookie
[pkey {:keys [crypt? $cright $cleft]}]
(if crypt?
(when (or (c/nichts? $cright)
(c/nichts? $cleft)
(.equals ^String $cleft
(t/gen-mac pkey $cright)))
(c/error "session cookie - broken.")
(c/trap! GeneralSecurityException "Bad Session Cookie."))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- crack-cookie!
[wss ^HttpCookie ck encrypt?]
(let [cookie (str (some-> ck .getValue))
pos (cs/index-of cookie \|)
[p1 p2] (if (nil? pos)
["" cookie]
[(subs cookie 0 pos)
(subs cookie (+ 1 pos))])]
(c/debug "session left=%s right=%s." p1 p2)
(swap! wss
#(update-in %
[:impls]
assoc
:crypt? encrypt?
:$cright p2
:$cleft p1
:domain-path (some-> ck .getPath)
:domain (some-> ck .getDomain)
:secure? (some-> ck .getSecure)
:hidden? (some-> ck .isHttpOnly)
:max-age-secs (some-> ck .getMaxAge)))
(doseq [nv (c/split p2 nv-sep)
:let [ss (c/split nv "=" 2)]
:when (c/two? ss)]
(let [s1 (u/url-decode (c/_1 ss))
s2 (u/url-decode (c/_2 ss))]
(c/debug "s-attr n=%s, v=%s." s1 s2)
(swap! wss
#(update-in %
[:attrs]
assoc
(keyword s1)
(if (c/wrapped? s1 "__xf" "n") (c/s->long s2 0) s2)))))
wss))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-session-new?
"If session is brand new?"
{:arglists '([wss])}
[wss]
(boolean (get-in @wss [:impls :$new?])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-session-null?
"If session is a null session?"
{:arglists '([wss])}
[wss]
(empty? (:impls @wss)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn set-max-idle-secs
"Set the max idle seconds."
{:arglists '([wss idleSecs])}
[wss idleSecs]
(swap! wss
#(update-in %
[:attrs]
assoc is-flag idleSecs)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn last-accessed-time
"Get the last accessed time."
{:arglists '([wss])}
[wss]
(c/num?? (lt-flag (:attrs @wss)) -1))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn max-idle-secs
"Get the max idle seconds."
{:arglists '([wss])}
[wss]
(c/num?? (is-flag (:attrs @wss)) -1))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn creation-time
"Get the creation time."
{:arglists '([wss])}
[wss]
(c/num?? (ct-flag (:attrs @wss)) -1))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn expiry-time
"Get the expiry time."
{:arglists '([wss])}
[wss]
(c/num?? (et-flag (:attrs @wss)) -1))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn session-signer
"Get the session's signing key."
{:arglists '([wss])}
[wss]
(:$pkey @wss))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn validate??
"Validate this session."
{:arglists '([wss])}
[wss]
(let [ts (last-accessed-time wss)
mi (max-idle-secs wss)
es (expiry-time wss)
now (u/system-time)]
(test-cookie (session-signer wss) @wss)
(if (or (and (c/spos? es) (< es now))
(and (c/spos? mi)
(< (+ ts (* 1000 mi)) now)))
(c/trap! GeneralSecurityException "Session has expired"))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn remove-session-attr
"Remove an attribute from session."
{:arglists '([wss k])}
[wss k]
(swap! wss
#(update-in % [:attrs] dissoc k)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn set-session-attr
"Set a session's attribute value."
{:arglists '([wss k v])}
[wss k v]
(swap! wss
#(update-in % [:attrs] assoc k v)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn session-attr
"Get a session attribute."
{:arglists '([wss k])}
[wss k]
(get-in @wss [:attrs k]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn remove-session-attrs
"Clear all session attibutes."
{:arglists '([wss])}
[wss]
(c/assoc!! wss :attrs {}))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn session-attrs
"Get the session attibutes."
{:arglists '([wss])}
[wss]
(:attrs @wss))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn invalidate!
"Invalidate this session."
{:arglists '([wss])}
[wss]
(c/assoc!! wss :impls {} :attrs {}))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn set-principal
"Set the user id."
{:arglists '([wss p])}
[wss p]
(swap! wss
#(update-in % [:impls] assoc user-flag p)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn principal
"Get the user id."
{:arglists '([wss])}
[wss]
(get-in @wss [:impls user-flag]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn set-session-new
"Set a new session with data."
{:arglists '([wss flag? arg])}
[wss flag? arg]
(when flag?
(invalidate! wss)
(reset-flags wss arg))
(swap! wss
#(update-in % [:impls] assoc :$new? flag?)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn session-error
"Get the last session error."
{:arglists '([wss])}
[wss]
(get-in @wss [:impls :$error]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn set-session-error
"Set the last session error."
{:arglists '([wss t])}
[wss t]
(swap! wss
#(update-in % [:impls] assoc :$error t)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn encode-attrs
"URL encode the session attributes."
{:arglists '([wss])}
[wss]
(c/sreduce<>
#(let [[k v] %2]
(c/sbf-join %1
nv-sep
(str (-> (name k)
(u/url-encode))
"="
(u/url-encode v)))) (session-attrs wss)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn session-id
"Get the session id."
{:arglists '([wss])}
[wss]
(get-in @wss [:impls ssid-flag]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn wsession<>
"Create a Web Session."
{:arglists '([pkey]
[pkey arg]
[pkey cookie secure?])}
([^bytes pkey cookie secure?]
(doto
(wsession<> pkey)
(set-session-new false nil)
(crack-cookie! cookie secure?)))
([^bytes pkey arg]
(doto
(wsession<> pkey)
(set-session-new true arg)))
([^bytes pkey]
(atom {:$pkey pkey
:attrs {}
:impls {:$new? true}})))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- macit??
[pkey data secure?]
(if secure? (str (t/gen-mac pkey data) "|" data) data))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn downstream
"Set session-cookie for outbound message#response."
{:arglists '([res][res session])}
([res]
(downstream res nil))
([res sessionObj]
(let [req (:request res)
mvs (or sessionObj
(:session req))]
(if (or (nil? mvs)
(is-session-null? mvs))
res
(let [_ (c/debug "session ok, about to set-cookie!")
pkey (session-signer mvs)
data (encode-attrs mvs)
{{:keys [max-age-secs
domain-path
domain
crypt? hidden? secure?]} :impls} @mvs
ck (->> (macit?? pkey data crypt?)
(HttpCookie. session-cookie))]
;;session cookie should always be -1 -> maxAge
;;and really should be httpOnly=true
(doto ck
(.setHttpOnly (boolean hidden?))
(.setSecure (boolean secure?))
(.setMaxAge (if (c/spos? max-age-secs) max-age-secs -1)))
(if (c/hgl? domain-path) (.setPath ck domain-path))
(if (c/hgl? domain) (.setDomain ck domain))
(update-in res
[:cookies] assoc (.getName ck) ck))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn upstream
"Create session from session-cookie."
{:arglists '([pkey cookies encrypt?])}
[pkey cookies encrypt?]
(wsession<> pkey (get cookies session-cookie) encrypt?))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
| true | ;; Licensed under the Apache License, Version 2.0 (the "License");
;; you may not use this file except in compliance with the License.
;; You may obtain a copy of the License at
;;
;; http://www.apache.org/licenses/LICENSE-2.0
;;
;; Unless required by applicable law or agreed to in writing, software
;; distributed under the License is distributed on an "AS IS" BASIS,
;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
;; See the License for the specific language governing permissions and
;; limitations under the License.
;;
;; Copyright © 2013-2022, PI:NAME:<NAME>END_PI. All rights reserved.
(ns czlab.niou.webss
"A Http Web Session."
(:require [czlab.twisty.core :as t]
[clojure.java.io :as io]
[clojure.string :as cs]
[czlab.basal.util :as u]
[czlab.basal.io :as i]
[czlab.basal.core :as c]
[czlab.niou.core :as v])
(:import [java.security GeneralSecurityException]
[java.net HttpCookie]
[java.util Date]
[java.io File]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;(set! *warn-on-reflection* true)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def ^String session-cookie "__xs117")
(def ^String csrf-cookie "__xc117")
(def ^String capc-cookie "__xp117")
(def ^String nv-sep "&")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(c/def- ssid-flag :__xf01es)
(c/def- user-flag :__u982i)
(c/def- ct-flag :__xf184n ) ;; creation time
(c/def- is-flag :__xf284n ) ;; max idle secs
(c/def- lt-flag :__xf384n ) ;; last access time
(c/def- et-flag :__xf484n ) ;; expiry time
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- reset-flags
"A negative value means that the cookie
is not stored persistently and will be deleted
when the Web browser exits.
A zero value causes the cookie to be deleted."
[mvs {:strs [max-age-secs max-idle-secs] :as cfg}]
(let [now (u/system-time)]
(c/assoc!! mvs
:impls cfg
:attrs
{ssid-flag (u/uid<>)
ct-flag now
lt-flag now
is-flag max-idle-secs
et-flag (if-not (c/spos? max-age-secs)
-1 (+ now (* max-age-secs 1000)))})))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- test-cookie
[pkey {:keys [crypt? $cright $cleft]}]
(if crypt?
(when (or (c/nichts? $cright)
(c/nichts? $cleft)
(.equals ^String $cleft
(t/gen-mac pkey $cright)))
(c/error "session cookie - broken.")
(c/trap! GeneralSecurityException "Bad Session Cookie."))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- crack-cookie!
[wss ^HttpCookie ck encrypt?]
(let [cookie (str (some-> ck .getValue))
pos (cs/index-of cookie \|)
[p1 p2] (if (nil? pos)
["" cookie]
[(subs cookie 0 pos)
(subs cookie (+ 1 pos))])]
(c/debug "session left=%s right=%s." p1 p2)
(swap! wss
#(update-in %
[:impls]
assoc
:crypt? encrypt?
:$cright p2
:$cleft p1
:domain-path (some-> ck .getPath)
:domain (some-> ck .getDomain)
:secure? (some-> ck .getSecure)
:hidden? (some-> ck .isHttpOnly)
:max-age-secs (some-> ck .getMaxAge)))
(doseq [nv (c/split p2 nv-sep)
:let [ss (c/split nv "=" 2)]
:when (c/two? ss)]
(let [s1 (u/url-decode (c/_1 ss))
s2 (u/url-decode (c/_2 ss))]
(c/debug "s-attr n=%s, v=%s." s1 s2)
(swap! wss
#(update-in %
[:attrs]
assoc
(keyword s1)
(if (c/wrapped? s1 "__xf" "n") (c/s->long s2 0) s2)))))
wss))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-session-new?
"If session is brand new?"
{:arglists '([wss])}
[wss]
(boolean (get-in @wss [:impls :$new?])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn is-session-null?
"If session is a null session?"
{:arglists '([wss])}
[wss]
(empty? (:impls @wss)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn set-max-idle-secs
"Set the max idle seconds."
{:arglists '([wss idleSecs])}
[wss idleSecs]
(swap! wss
#(update-in %
[:attrs]
assoc is-flag idleSecs)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn last-accessed-time
"Get the last accessed time."
{:arglists '([wss])}
[wss]
(c/num?? (lt-flag (:attrs @wss)) -1))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn max-idle-secs
"Get the max idle seconds."
{:arglists '([wss])}
[wss]
(c/num?? (is-flag (:attrs @wss)) -1))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn creation-time
"Get the creation time."
{:arglists '([wss])}
[wss]
(c/num?? (ct-flag (:attrs @wss)) -1))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn expiry-time
"Get the expiry time."
{:arglists '([wss])}
[wss]
(c/num?? (et-flag (:attrs @wss)) -1))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn session-signer
"Get the session's signing key."
{:arglists '([wss])}
[wss]
(:$pkey @wss))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn validate??
"Validate this session."
{:arglists '([wss])}
[wss]
(let [ts (last-accessed-time wss)
mi (max-idle-secs wss)
es (expiry-time wss)
now (u/system-time)]
(test-cookie (session-signer wss) @wss)
(if (or (and (c/spos? es) (< es now))
(and (c/spos? mi)
(< (+ ts (* 1000 mi)) now)))
(c/trap! GeneralSecurityException "Session has expired"))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn remove-session-attr
"Remove an attribute from session."
{:arglists '([wss k])}
[wss k]
(swap! wss
#(update-in % [:attrs] dissoc k)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn set-session-attr
"Set a session's attribute value."
{:arglists '([wss k v])}
[wss k v]
(swap! wss
#(update-in % [:attrs] assoc k v)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn session-attr
"Get a session attribute."
{:arglists '([wss k])}
[wss k]
(get-in @wss [:attrs k]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn remove-session-attrs
"Clear all session attibutes."
{:arglists '([wss])}
[wss]
(c/assoc!! wss :attrs {}))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn session-attrs
"Get the session attibutes."
{:arglists '([wss])}
[wss]
(:attrs @wss))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn invalidate!
"Invalidate this session."
{:arglists '([wss])}
[wss]
(c/assoc!! wss :impls {} :attrs {}))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn set-principal
"Set the user id."
{:arglists '([wss p])}
[wss p]
(swap! wss
#(update-in % [:impls] assoc user-flag p)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn principal
"Get the user id."
{:arglists '([wss])}
[wss]
(get-in @wss [:impls user-flag]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn set-session-new
"Set a new session with data."
{:arglists '([wss flag? arg])}
[wss flag? arg]
(when flag?
(invalidate! wss)
(reset-flags wss arg))
(swap! wss
#(update-in % [:impls] assoc :$new? flag?)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn session-error
"Get the last session error."
{:arglists '([wss])}
[wss]
(get-in @wss [:impls :$error]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn set-session-error
"Set the last session error."
{:arglists '([wss t])}
[wss t]
(swap! wss
#(update-in % [:impls] assoc :$error t)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn encode-attrs
"URL encode the session attributes."
{:arglists '([wss])}
[wss]
(c/sreduce<>
#(let [[k v] %2]
(c/sbf-join %1
nv-sep
(str (-> (name k)
(u/url-encode))
"="
(u/url-encode v)))) (session-attrs wss)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn session-id
"Get the session id."
{:arglists '([wss])}
[wss]
(get-in @wss [:impls ssid-flag]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn wsession<>
"Create a Web Session."
{:arglists '([pkey]
[pkey arg]
[pkey cookie secure?])}
([^bytes pkey cookie secure?]
(doto
(wsession<> pkey)
(set-session-new false nil)
(crack-cookie! cookie secure?)))
([^bytes pkey arg]
(doto
(wsession<> pkey)
(set-session-new true arg)))
([^bytes pkey]
(atom {:$pkey pkey
:attrs {}
:impls {:$new? true}})))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn- macit??
[pkey data secure?]
(if secure? (str (t/gen-mac pkey data) "|" data) data))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn downstream
"Set session-cookie for outbound message#response."
{:arglists '([res][res session])}
([res]
(downstream res nil))
([res sessionObj]
(let [req (:request res)
mvs (or sessionObj
(:session req))]
(if (or (nil? mvs)
(is-session-null? mvs))
res
(let [_ (c/debug "session ok, about to set-cookie!")
pkey (session-signer mvs)
data (encode-attrs mvs)
{{:keys [max-age-secs
domain-path
domain
crypt? hidden? secure?]} :impls} @mvs
ck (->> (macit?? pkey data crypt?)
(HttpCookie. session-cookie))]
;;session cookie should always be -1 -> maxAge
;;and really should be httpOnly=true
(doto ck
(.setHttpOnly (boolean hidden?))
(.setSecure (boolean secure?))
(.setMaxAge (if (c/spos? max-age-secs) max-age-secs -1)))
(if (c/hgl? domain-path) (.setPath ck domain-path))
(if (c/hgl? domain) (.setDomain ck domain))
(update-in res
[:cookies] assoc (.getName ck) ck))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn upstream
"Create session from session-cookie."
{:arglists '([pkey cookies encrypt?])}
[pkey cookies encrypt?]
(wsession<> pkey (get cookies session-cookie) encrypt?))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;EOF
|
[
{
"context": " (testing \"1a. Failed\"\r\n (is (= (hello-name [\"Bob\" \"Chris\"])\r\n [\"Hello Bob\" \"Hello Chris\"",
"end": 233,
"score": 0.9996986389160156,
"start": 230,
"tag": "NAME",
"value": "Bob"
},
{
"context": "ting \"1a. Failed\"\r\n (is (= (hello-name [\"Bob\" \"Chris\"])\r\n [\"Hello Bob\" \"Hello Chris\"])\r\n ",
"end": 241,
"score": 0.9997724294662476,
"start": 236,
"tag": "NAME",
"value": "Chris"
},
{
"context": "= (hello-name [\"Bob\" \"Chris\"])\r\n [\"Hello Bob\" \"Hello Chris\"])\r\n (= (hello-name [\"Waldo\"",
"end": 268,
"score": 0.9995313286781311,
"start": 265,
"tag": "NAME",
"value": "Bob"
},
{
"context": "e [\"Bob\" \"Chris\"])\r\n [\"Hello Bob\" \"Hello Chris\"])\r\n (= (hello-name [\"Waldo\"])\r\n ",
"end": 282,
"score": 0.9996924996376038,
"start": 277,
"tag": "NAME",
"value": "Chris"
},
{
"context": "lo Bob\" \"Hello Chris\"])\r\n (= (hello-name [\"Waldo\"])\r\n [\"Hello Waldo\"]))))\r\n\r\n(deftest nu",
"end": 317,
"score": 0.9988544583320618,
"start": 312,
"tag": "NAME",
"value": "Waldo"
},
{
"context": " (= (hello-name [\"Waldo\"])\r\n [\"Hello Waldo\"]))))\r\n\r\n(deftest num-english-test\r\n (testing \"1",
"end": 346,
"score": 0.94757080078125,
"start": 341,
"tag": "NAME",
"value": "Waldo"
}
] | plp-clojure/test/plp_clojure/core_test.clj | timaeudg/CSSE403-PLP | 0 | (ns plp-clojure.core-test
(:require [clojure.test :refer :all]
[plp-clojure.core :refer :all]
[clojure.set :refer :all]))
(deftest hello-name-test
(testing "1a. Failed"
(is (= (hello-name ["Bob" "Chris"])
["Hello Bob" "Hello Chris"])
(= (hello-name ["Waldo"])
["Hello Waldo"]))))
(deftest num-english-test
(testing "1b. Failed"
(is (= (num-english [1 2 3])
["one" "two" "three"])
(= (num-english [4 5 6])
["four" "five" nil]))))
(deftest node-degree-test
(testing "2b. Failed"
(is (= (node-degree [[:a :b] [:b :c] [:a :c]])
[["a" 2] ["b" 2] ["c" 2]]))))
(deftest prime?-test
(testing "3a. Failed"
(are [n] (prime? n) 3 7 23)))
(deftest n-prime-test
(testing "3b. Failed"
(is (= (n-prime 6) [3 5 7 11 13 17])))) | 76362 | (ns plp-clojure.core-test
(:require [clojure.test :refer :all]
[plp-clojure.core :refer :all]
[clojure.set :refer :all]))
(deftest hello-name-test
(testing "1a. Failed"
(is (= (hello-name ["<NAME>" "<NAME>"])
["Hello <NAME>" "Hello <NAME>"])
(= (hello-name ["<NAME>"])
["Hello <NAME>"]))))
(deftest num-english-test
(testing "1b. Failed"
(is (= (num-english [1 2 3])
["one" "two" "three"])
(= (num-english [4 5 6])
["four" "five" nil]))))
(deftest node-degree-test
(testing "2b. Failed"
(is (= (node-degree [[:a :b] [:b :c] [:a :c]])
[["a" 2] ["b" 2] ["c" 2]]))))
(deftest prime?-test
(testing "3a. Failed"
(are [n] (prime? n) 3 7 23)))
(deftest n-prime-test
(testing "3b. Failed"
(is (= (n-prime 6) [3 5 7 11 13 17])))) | true | (ns plp-clojure.core-test
(:require [clojure.test :refer :all]
[plp-clojure.core :refer :all]
[clojure.set :refer :all]))
(deftest hello-name-test
(testing "1a. Failed"
(is (= (hello-name ["PI:NAME:<NAME>END_PI" "PI:NAME:<NAME>END_PI"])
["Hello PI:NAME:<NAME>END_PI" "Hello PI:NAME:<NAME>END_PI"])
(= (hello-name ["PI:NAME:<NAME>END_PI"])
["Hello PI:NAME:<NAME>END_PI"]))))
(deftest num-english-test
(testing "1b. Failed"
(is (= (num-english [1 2 3])
["one" "two" "three"])
(= (num-english [4 5 6])
["four" "five" nil]))))
(deftest node-degree-test
(testing "2b. Failed"
(is (= (node-degree [[:a :b] [:b :c] [:a :c]])
[["a" 2] ["b" 2] ["c" 2]]))))
(deftest prime?-test
(testing "3a. Failed"
(are [n] (prime? n) 3 7 23)))
(deftest n-prime-test
(testing "3b. Failed"
(is (= (n-prime 6) [3 5 7 11 13 17])))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.